Init commit
This commit is contained in:
114
server/core/models/video/event-registration.ts
Normal file
114
server/core/models/video/event-registration.ts
Normal file
@@ -0,0 +1,114 @@
|
||||
import { FindOptions, Transaction } from 'sequelize'
|
||||
import {
|
||||
AllowNull,
|
||||
BelongsTo,
|
||||
Column,
|
||||
CreatedAt,
|
||||
DataType,
|
||||
ForeignKey,
|
||||
Table,
|
||||
UpdatedAt
|
||||
} from 'sequelize-typescript'
|
||||
import { SequelizeModel } from '../shared/index.js'
|
||||
import { EventModel } from './event.js'
|
||||
|
||||
@Table({
|
||||
tableName: 'eventRegistration',
|
||||
indexes: [
|
||||
{
|
||||
fields: [ 'eventId' ]
|
||||
}
|
||||
]
|
||||
})
|
||||
export class EventRegistrationModel extends SequelizeModel<EventRegistrationModel> {
|
||||
@AllowNull(false)
|
||||
@Column(DataType.STRING(255))
|
||||
declare firstName: string
|
||||
|
||||
@AllowNull(false)
|
||||
@Column(DataType.STRING(255))
|
||||
declare lastName: string
|
||||
|
||||
@AllowNull(false)
|
||||
@Column(DataType.STRING(320))
|
||||
declare email: string
|
||||
|
||||
@AllowNull(false)
|
||||
@Column(DataType.STRING(50))
|
||||
declare phone: string
|
||||
|
||||
@AllowNull(false)
|
||||
@Column(DataType.STRING(255))
|
||||
declare companyName: string
|
||||
|
||||
@AllowNull(false)
|
||||
@Column(DataType.STRING(255))
|
||||
declare jobTitle: string
|
||||
|
||||
@AllowNull(false)
|
||||
@Column(DataType.STRING(100))
|
||||
declare country: string
|
||||
|
||||
@CreatedAt
|
||||
declare createdAt: Date
|
||||
|
||||
@UpdatedAt
|
||||
declare updatedAt: Date
|
||||
|
||||
@ForeignKey(() => EventModel)
|
||||
@Column
|
||||
declare eventId: number
|
||||
|
||||
@BelongsTo(() => EventModel, {
|
||||
foreignKey: {
|
||||
allowNull: false
|
||||
},
|
||||
onDelete: 'CASCADE'
|
||||
})
|
||||
declare Event: Awaited<EventModel>
|
||||
|
||||
static listForApi (options: {
|
||||
eventId: number
|
||||
start: number
|
||||
count: number
|
||||
}) {
|
||||
const { eventId, start, count } = options
|
||||
|
||||
const query: FindOptions = {
|
||||
where: {
|
||||
eventId
|
||||
},
|
||||
order: [ [ 'createdAt', 'DESC' ] ],
|
||||
offset: start,
|
||||
limit: count
|
||||
}
|
||||
|
||||
return EventRegistrationModel.findAndCountAll(query)
|
||||
}
|
||||
|
||||
static loadByIdAndEventId (registrationId: number, eventId: number, transaction?: Transaction) {
|
||||
return EventRegistrationModel.findOne({
|
||||
where: {
|
||||
id: registrationId,
|
||||
eventId
|
||||
},
|
||||
transaction
|
||||
})
|
||||
}
|
||||
|
||||
toFormattedJSON (this: EventRegistrationModel) {
|
||||
return {
|
||||
id: this.id,
|
||||
firstName: this.firstName,
|
||||
lastName: this.lastName,
|
||||
email: this.email,
|
||||
phone: this.phone,
|
||||
companyName: this.companyName,
|
||||
jobTitle: this.jobTitle,
|
||||
country: this.country,
|
||||
eventId: this.eventId,
|
||||
createdAt: this.createdAt.toISOString(),
|
||||
updatedAt: this.updatedAt.toISOString()
|
||||
}
|
||||
}
|
||||
}
|
||||
182
server/core/models/video/event.ts
Normal file
182
server/core/models/video/event.ts
Normal file
@@ -0,0 +1,182 @@
|
||||
import { Transaction } from 'sequelize'
|
||||
import { AllowNull, BelongsTo, Column, CreatedAt, DataType, Default, ForeignKey, Table, UpdatedAt } from 'sequelize-typescript'
|
||||
import { MEvent } from '@server/types/models/index.js'
|
||||
import { VideoChannelModel } from './video-channel.js'
|
||||
import { SequelizeModel } from '../shared/index.js'
|
||||
|
||||
export enum EventState {
|
||||
ACTIVE = 'active',
|
||||
DISABLED = 'disabled'
|
||||
}
|
||||
|
||||
@Table({
|
||||
tableName: 'event',
|
||||
indexes: [
|
||||
{
|
||||
fields: [ 'channelId' ]
|
||||
},
|
||||
{
|
||||
fields: [ 'state' ]
|
||||
},
|
||||
{
|
||||
fields: [ 'startTime' ]
|
||||
}
|
||||
]
|
||||
})
|
||||
export class EventModel extends SequelizeModel<EventModel> {
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare title: string
|
||||
|
||||
@AllowNull(true)
|
||||
@Column(DataType.TEXT)
|
||||
declare description: string | null
|
||||
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare startTime: Date
|
||||
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare endTime: Date
|
||||
|
||||
@AllowNull(true)
|
||||
@Column
|
||||
declare thumbnailFilename: string | null
|
||||
|
||||
@AllowNull(true)
|
||||
@Column(DataType.BLOB)
|
||||
declare thumbnailData: Buffer | null
|
||||
|
||||
@AllowNull(true)
|
||||
@Column
|
||||
declare thumbnailMimeType: string | null
|
||||
|
||||
@AllowNull(true)
|
||||
@Column(DataType.BIGINT)
|
||||
declare thumbnailSize: number | null
|
||||
|
||||
@AllowNull(true)
|
||||
@Column
|
||||
declare thumbnailEtag: string | null
|
||||
|
||||
@AllowNull(true)
|
||||
@Column(DataType.TEXT)
|
||||
declare liveUrl: string | null
|
||||
|
||||
@AllowNull(false)
|
||||
@Default(EventState.ACTIVE)
|
||||
@Column
|
||||
declare state: EventState
|
||||
|
||||
@CreatedAt
|
||||
declare createdAt: Date
|
||||
|
||||
@UpdatedAt
|
||||
declare updatedAt: Date
|
||||
|
||||
@ForeignKey(() => VideoChannelModel)
|
||||
@Column
|
||||
declare channelId: number
|
||||
|
||||
@BelongsTo(() => VideoChannelModel, {
|
||||
foreignKey: {
|
||||
allowNull: false
|
||||
},
|
||||
onDelete: 'cascade'
|
||||
})
|
||||
declare Channel: Awaited<VideoChannelModel>
|
||||
|
||||
static listByChannelId (channelId: number, transaction?: Transaction) {
|
||||
const query = {
|
||||
where: {
|
||||
channelId
|
||||
},
|
||||
order: [ [ 'startTime', 'DESC' ] ] as any,
|
||||
transaction
|
||||
}
|
||||
|
||||
return EventModel.findAll<MEvent>(query)
|
||||
}
|
||||
|
||||
static findByIdAndChannelId (eventId: number, channelId: number, transaction?: Transaction) {
|
||||
const query = {
|
||||
where: {
|
||||
id: eventId,
|
||||
channelId
|
||||
},
|
||||
transaction
|
||||
}
|
||||
|
||||
return EventModel.findOne<MEvent>(query)
|
||||
}
|
||||
|
||||
static loadByThumbnailFilename (thumbnailFilename: string, transaction?: Transaction) {
|
||||
return EventModel.findOne<MEvent>({
|
||||
where: {
|
||||
thumbnailFilename
|
||||
},
|
||||
transaction
|
||||
})
|
||||
}
|
||||
|
||||
static listPublicEvents (limit?: number, states?: string[]) {
|
||||
const query: any = {
|
||||
order: [ [ 'startTime', 'DESC' ] ] as any,
|
||||
limit
|
||||
}
|
||||
|
||||
// Only filter by state if explicitly provided; otherwise return all events
|
||||
if (states && states.length > 0) {
|
||||
query.where = { state: states }
|
||||
}
|
||||
|
||||
return EventModel.findAll<MEvent>(query)
|
||||
}
|
||||
|
||||
static async deleteByIdAndChannelId (eventId: number, channelId: number, transaction?: Transaction) {
|
||||
const event = await EventModel.findByIdAndChannelId(eventId, channelId, transaction)
|
||||
if (!event) return false
|
||||
|
||||
await event.destroy({ transaction })
|
||||
return true
|
||||
}
|
||||
|
||||
static async updateEventState (eventId: number, newState: EventState, transaction?: Transaction) {
|
||||
const query = {
|
||||
where: {
|
||||
id: eventId
|
||||
},
|
||||
transaction
|
||||
}
|
||||
|
||||
return EventModel.update({ state: newState }, query)
|
||||
}
|
||||
|
||||
toFormattedJSON (this: EventModel) {
|
||||
return {
|
||||
id: this.id,
|
||||
title: this.title,
|
||||
description: this.description,
|
||||
startTime: this.startTime.toISOString(),
|
||||
endTime: this.endTime.toISOString(),
|
||||
thumbnailFilename: this.thumbnailFilename,
|
||||
liveUrl: this.liveUrl,
|
||||
state: this.state,
|
||||
channelId: this.channelId,
|
||||
createdAt: this.createdAt.toISOString(),
|
||||
updatedAt: this.updatedAt.toISOString()
|
||||
}
|
||||
}
|
||||
|
||||
toLogKeys (this: EventModel) {
|
||||
return {
|
||||
id: this.id,
|
||||
title: this.title,
|
||||
state: this.state,
|
||||
startTime: this.startTime,
|
||||
endTime: this.endTime,
|
||||
channelId: this.channelId
|
||||
}
|
||||
}
|
||||
}
|
||||
2
server/core/models/video/formatter/index.ts
Normal file
2
server/core/models/video/formatter/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from './video-activity-pub-format.js'
|
||||
export * from './video-api-format.js'
|
||||
1
server/core/models/video/formatter/shared/index.ts
Normal file
1
server/core/models/video/formatter/shared/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from './video-format-utils.js'
|
||||
@@ -0,0 +1,7 @@
|
||||
import { MVideoFile } from '@server/types/models/index.js'
|
||||
|
||||
export function sortByResolutionDesc (fileA: MVideoFile, fileB: MVideoFile) {
|
||||
if (fileA.resolution < fileB.resolution) return 1
|
||||
if (fileA.resolution === fileB.resolution) return 0
|
||||
return -1
|
||||
}
|
||||
322
server/core/models/video/formatter/video-activity-pub-format.ts
Normal file
322
server/core/models/video/formatter/video-activity-pub-format.ts
Normal file
@@ -0,0 +1,322 @@
|
||||
import {
|
||||
ActivityHashTagObject,
|
||||
ActivityIconObject,
|
||||
ActivityPlaylistUrlObject,
|
||||
ActivityPubStoryboard,
|
||||
ActivitySensitiveTagObject,
|
||||
ActivityTagObject,
|
||||
ActivityTrackerUrlObject,
|
||||
ActivityUrlObject,
|
||||
nsfwFlagsToString,
|
||||
VideoCommentPolicy,
|
||||
VideoObject
|
||||
} from '@peertube/peertube-models'
|
||||
import { getAPPublicValue } from '@server/helpers/activity-pub-utils.js'
|
||||
import { isArray } from '@server/helpers/custom-validators/misc.js'
|
||||
import { generateMagnetUri } from '@server/lib/webtorrent.js'
|
||||
import { getActivityStreamDuration } from '@server/lib/activitypub/activity.js'
|
||||
import { getLocalVideoFileMetadataUrl } from '@server/lib/video-urls.js'
|
||||
import { WEBSERVER } from '../../../initializers/constants.js'
|
||||
import {
|
||||
getLocalVideoChaptersActivityPubUrl,
|
||||
getLocalVideoCommentsActivityPubUrl,
|
||||
getLocalVideoDislikesActivityPubUrl,
|
||||
getLocalVideoLikesActivityPubUrl,
|
||||
getLocalVideoPlayerSettingsActivityPubUrl,
|
||||
getLocalVideoSharesActivityPubUrl
|
||||
} from '../../../lib/activitypub/url.js'
|
||||
import { MStreamingPlaylistFiles, MUserId, MVideo, MVideoAP, MVideoFile } from '../../../types/models/index.js'
|
||||
import { sortByResolutionDesc } from './shared/index.js'
|
||||
import { getCategoryLabel, getLanguageLabel, getLicenceLabel } from './video-api-format.js'
|
||||
|
||||
export function videoModelToActivityPubObject (video: MVideoAP): VideoObject {
|
||||
const language = video.language
|
||||
? { identifier: video.language, name: getLanguageLabel(video.language) }
|
||||
: undefined
|
||||
|
||||
const category = video.category
|
||||
? { identifier: video.category + '', name: getCategoryLabel(video.category) }
|
||||
: undefined
|
||||
|
||||
const licence = video.licence
|
||||
? { identifier: video.licence + '', name: getLicenceLabel(video.licence) }
|
||||
: undefined
|
||||
|
||||
const url: ActivityUrlObject[] = [
|
||||
// HTML url should be the first element in the array so Mastodon correctly displays the embed
|
||||
{
|
||||
type: 'Link',
|
||||
mediaType: 'text/html',
|
||||
href: WEBSERVER.URL + video.getWatchStaticPath()
|
||||
} as ActivityUrlObject,
|
||||
|
||||
{
|
||||
type: 'Link',
|
||||
mediaType: 'text/html',
|
||||
href: video.url
|
||||
} as ActivityUrlObject,
|
||||
|
||||
...buildVideoFileUrls({ video, files: video.VideoFiles }),
|
||||
|
||||
...buildStreamingPlaylistUrls(video),
|
||||
|
||||
...buildTrackerUrls(video)
|
||||
]
|
||||
|
||||
return {
|
||||
type: 'Video' as 'Video',
|
||||
id: video.url,
|
||||
name: video.name,
|
||||
duration: getActivityStreamDuration(video.duration),
|
||||
uuid: video.uuid,
|
||||
category,
|
||||
licence,
|
||||
language,
|
||||
views: video.views,
|
||||
|
||||
sensitive: video.nsfw,
|
||||
summary: video.nsfwSummary,
|
||||
|
||||
waitTranscoding: video.waitTranscoding,
|
||||
|
||||
state: video.state,
|
||||
|
||||
canReply: video.commentsPolicy === VideoCommentPolicy.ENABLED
|
||||
? null
|
||||
: getAPPublicValue(), // Requires approval
|
||||
|
||||
commentsPolicy: video.commentsPolicy,
|
||||
|
||||
downloadEnabled: video.downloadEnabled,
|
||||
published: video.publishedAt.toISOString(),
|
||||
|
||||
originallyPublishedAt: video.originallyPublishedAt
|
||||
? video.originallyPublishedAt.toISOString()
|
||||
: null,
|
||||
|
||||
schedules: (video.VideoLive?.LiveSchedules || []).map(s => ({
|
||||
startDate: s.startAt
|
||||
})),
|
||||
|
||||
updated: video.updatedAt.toISOString(),
|
||||
|
||||
uploadDate: video.inputFileUpdatedAt?.toISOString(),
|
||||
|
||||
tag: buildTags(video),
|
||||
|
||||
mediaType: 'text/markdown',
|
||||
content: video.description,
|
||||
support: video.support,
|
||||
|
||||
subtitleLanguage: buildSubtitleLanguage(video),
|
||||
|
||||
icon: buildIcon(video),
|
||||
|
||||
preview: buildPreviewAPAttribute(video),
|
||||
|
||||
aspectRatio: video.aspectRatio,
|
||||
|
||||
url,
|
||||
|
||||
likes: getLocalVideoLikesActivityPubUrl(video),
|
||||
dislikes: getLocalVideoDislikesActivityPubUrl(video),
|
||||
shares: getLocalVideoSharesActivityPubUrl(video),
|
||||
comments: getLocalVideoCommentsActivityPubUrl(video),
|
||||
hasParts: getLocalVideoChaptersActivityPubUrl(video),
|
||||
playerSettings: getLocalVideoPlayerSettingsActivityPubUrl(video),
|
||||
|
||||
attributedTo: [
|
||||
video.VideoChannel.Account.Actor.url,
|
||||
video.VideoChannel.Actor.url
|
||||
],
|
||||
|
||||
...buildLiveAPAttributes(video)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Private
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function buildLiveAPAttributes (video: MVideoAP) {
|
||||
if (!video.isLive) {
|
||||
return {
|
||||
isLiveBroadcast: false,
|
||||
liveSaveReplay: null,
|
||||
permanentLive: null,
|
||||
latencyMode: null
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
isLiveBroadcast: true,
|
||||
liveSaveReplay: video.VideoLive.saveReplay,
|
||||
permanentLive: video.VideoLive.permanentLive,
|
||||
latencyMode: video.VideoLive.latencyMode
|
||||
}
|
||||
}
|
||||
|
||||
function buildPreviewAPAttribute (video: MVideoAP): ActivityPubStoryboard[] {
|
||||
if (!video.Storyboard) return undefined
|
||||
|
||||
const storyboard = video.Storyboard
|
||||
|
||||
return [
|
||||
{
|
||||
type: 'Image',
|
||||
rel: [ 'storyboard' ],
|
||||
url: [
|
||||
{
|
||||
mediaType: 'image/jpeg',
|
||||
|
||||
href: storyboard.getOriginFileUrl(video),
|
||||
|
||||
width: storyboard.totalWidth,
|
||||
height: storyboard.totalHeight,
|
||||
|
||||
tileWidth: storyboard.spriteWidth,
|
||||
tileHeight: storyboard.spriteHeight,
|
||||
tileDuration: getActivityStreamDuration(storyboard.spriteDuration)
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
function buildVideoFileUrls (options: {
|
||||
video: MVideo
|
||||
files: MVideoFile[]
|
||||
user?: MUserId
|
||||
}): ActivityUrlObject[] {
|
||||
const { video, files } = options
|
||||
|
||||
if (!isArray(files)) return []
|
||||
|
||||
const urls: ActivityUrlObject[] = []
|
||||
|
||||
const trackerUrls = video.getTrackerUrls()
|
||||
const sortedFiles = files
|
||||
.filter(f => !f.isLive())
|
||||
.sort(sortByResolutionDesc)
|
||||
|
||||
for (const file of sortedFiles) {
|
||||
const fileAP = file.toActivityPubObject(video)
|
||||
urls.push(fileAP)
|
||||
|
||||
urls.push({
|
||||
type: 'Link',
|
||||
rel: [ 'metadata', fileAP.mediaType ],
|
||||
mediaType: 'application/json' as 'application/json',
|
||||
href: getLocalVideoFileMetadataUrl(video, file),
|
||||
height: file.height || file.resolution,
|
||||
width: file.width,
|
||||
fps: file.fps
|
||||
})
|
||||
|
||||
if (file.hasTorrent()) {
|
||||
urls.push({
|
||||
type: 'Link',
|
||||
mediaType: 'application/x-bittorrent' as 'application/x-bittorrent',
|
||||
href: file.getTorrentUrl(),
|
||||
height: file.height || file.resolution,
|
||||
width: file.width,
|
||||
fps: file.fps
|
||||
})
|
||||
|
||||
urls.push({
|
||||
type: 'Link',
|
||||
mediaType: 'application/x-bittorrent;x-scheme-handler/magnet' as 'application/x-bittorrent;x-scheme-handler/magnet',
|
||||
href: generateMagnetUri(video, file, trackerUrls),
|
||||
height: file.height || file.resolution,
|
||||
width: file.width,
|
||||
fps: file.fps
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return urls
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function buildStreamingPlaylistUrls (video: MVideoAP): ActivityPlaylistUrlObject[] {
|
||||
if (!isArray(video.VideoStreamingPlaylists)) return []
|
||||
|
||||
return video.VideoStreamingPlaylists
|
||||
.map(playlist => ({
|
||||
type: 'Link',
|
||||
mediaType: 'application/x-mpegURL' as 'application/x-mpegURL',
|
||||
href: playlist.getMasterPlaylistUrl(video),
|
||||
tag: buildStreamingPlaylistTags(video, playlist)
|
||||
}))
|
||||
}
|
||||
|
||||
function buildStreamingPlaylistTags (video: MVideoAP, playlist: MStreamingPlaylistFiles) {
|
||||
return [
|
||||
...playlist.p2pMediaLoaderInfohashes.map(i => ({ type: 'Infohash' as 'Infohash', name: i })),
|
||||
|
||||
{
|
||||
type: 'Link',
|
||||
name: 'sha256',
|
||||
mediaType: 'application/json' as 'application/json',
|
||||
href: playlist.getSha256SegmentsUrl(video)
|
||||
},
|
||||
|
||||
...buildVideoFileUrls({ video, files: playlist.VideoFiles })
|
||||
] as ActivityTagObject[]
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function buildTrackerUrls (video: MVideoAP): ActivityTrackerUrlObject[] {
|
||||
return video.getTrackerUrls()
|
||||
.map(trackerUrl => {
|
||||
const rel2 = trackerUrl.startsWith('http')
|
||||
? 'http'
|
||||
: 'websocket'
|
||||
|
||||
return {
|
||||
type: 'Link',
|
||||
name: `tracker-${rel2}`,
|
||||
rel: [ 'tracker', rel2 ],
|
||||
href: trackerUrl
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function buildTags (video: MVideoAP): (ActivitySensitiveTagObject | ActivityHashTagObject)[] {
|
||||
const tags = isArray(video.Tags)
|
||||
? video.Tags
|
||||
: []
|
||||
|
||||
return [
|
||||
...tags.map(t =>
|
||||
({
|
||||
type: 'Hashtag' as 'Hashtag',
|
||||
name: t.name
|
||||
}) as ActivityHashTagObject
|
||||
),
|
||||
|
||||
...nsfwFlagsToString(video.nsfwFlags).map(f =>
|
||||
({
|
||||
type: 'SensitiveTag' as 'SensitiveTag',
|
||||
name: f
|
||||
}) as ActivitySensitiveTagObject
|
||||
)
|
||||
]
|
||||
}
|
||||
|
||||
function buildIcon (video: MVideoAP): ActivityIconObject[] {
|
||||
return [ video.getMiniature(), video.getPreview() ]
|
||||
.filter(i => !!i)
|
||||
.map(i => i.toActivityPubObject(video))
|
||||
}
|
||||
|
||||
function buildSubtitleLanguage (video: MVideoAP) {
|
||||
if (!isArray(video.VideoCaptions)) return []
|
||||
|
||||
return video.VideoCaptions
|
||||
.map(caption => caption.toActivityPubObject(video))
|
||||
}
|
||||
374
server/core/models/video/formatter/video-api-format.ts
Normal file
374
server/core/models/video/formatter/video-api-format.ts
Normal file
@@ -0,0 +1,374 @@
|
||||
import { getResolutionLabel } from '@peertube/peertube-core-utils'
|
||||
import {
|
||||
Video,
|
||||
VideoAdditionalAttributes,
|
||||
VideoDetails,
|
||||
VideoFile,
|
||||
VideoInclude,
|
||||
VideosCommonQueryAfterSanitize,
|
||||
VideoStreamingPlaylist
|
||||
} from '@peertube/peertube-models'
|
||||
import { uuidToShort } from '@peertube/peertube-node-utils'
|
||||
import { generateMagnetUri } from '@server/lib/webtorrent.js'
|
||||
import { tracer } from '@server/lib/opentelemetry/tracing.js'
|
||||
import { getHLSResolutionPlaylistFilename } from '@server/lib/paths.js'
|
||||
import { getLocalVideoFileMetadataUrl } from '@server/lib/video-urls.js'
|
||||
import { VideoViewsManager } from '@server/lib/views/video-views-manager.js'
|
||||
import { isArray } from '../../../helpers/custom-validators/misc.js'
|
||||
import {
|
||||
VIDEO_CATEGORIES,
|
||||
VIDEO_COMMENTS_POLICY,
|
||||
VIDEO_LANGUAGES,
|
||||
VIDEO_LICENCES,
|
||||
VIDEO_PRIVACIES,
|
||||
VIDEO_STATES
|
||||
} from '../../../initializers/constants.js'
|
||||
import { MServer, MStreamingPlaylistRedundanciesOpt, MVideoFormattable, MVideoFormattableDetails } from '../../../types/models/index.js'
|
||||
import { MVideoFile } from '../../../types/models/video/video-file.js'
|
||||
import { sortByResolutionDesc } from './shared/index.js'
|
||||
|
||||
export type VideoFormattingJSONOptions = {
|
||||
completeDescription?: boolean
|
||||
|
||||
additionalAttributes?: {
|
||||
state?: boolean
|
||||
waitTranscoding?: boolean
|
||||
scheduledUpdate?: boolean
|
||||
blacklistInfo?: boolean
|
||||
files?: boolean
|
||||
source?: boolean
|
||||
blockedOwner?: boolean
|
||||
automaticTags?: boolean
|
||||
liveSchedules?: boolean
|
||||
}
|
||||
}
|
||||
|
||||
export function guessAdditionalAttributesFromQuery (
|
||||
query: Pick<VideosCommonQueryAfterSanitize, 'include' | 'includeScheduledLive'>
|
||||
): VideoFormattingJSONOptions {
|
||||
return {
|
||||
additionalAttributes: {
|
||||
state: query.includeScheduledLive || !!(query.include & VideoInclude.NOT_PUBLISHED_STATE),
|
||||
waitTranscoding: !!(query.include & VideoInclude.NOT_PUBLISHED_STATE),
|
||||
scheduledUpdate: !!(query.include & VideoInclude.NOT_PUBLISHED_STATE),
|
||||
blacklistInfo: !!(query.include & VideoInclude.BLACKLISTED),
|
||||
files: !!(query.include & VideoInclude.FILES),
|
||||
source: !!(query.include & VideoInclude.SOURCE),
|
||||
blockedOwner: !!(query.include & VideoInclude.BLOCKED_OWNER),
|
||||
automaticTags: !!(query.include & VideoInclude.AUTOMATIC_TAGS),
|
||||
liveSchedules: query.includeScheduledLive
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function videoModelToFormattedJSON (video: MVideoFormattable, options: VideoFormattingJSONOptions = {}): Video {
|
||||
const span = tracer.startSpan('peertube.VideoModel.toFormattedJSON')
|
||||
|
||||
const userHistory = isArray(video.UserVideoHistories)
|
||||
? video.UserVideoHistories[0]
|
||||
: undefined
|
||||
|
||||
const videoObject: Video = {
|
||||
id: video.id,
|
||||
uuid: video.uuid,
|
||||
shortUUID: uuidToShort(video.uuid),
|
||||
|
||||
url: video.url,
|
||||
|
||||
name: video.name,
|
||||
category: {
|
||||
id: video.category,
|
||||
label: getCategoryLabel(video.category)
|
||||
},
|
||||
licence: {
|
||||
id: video.licence,
|
||||
label: getLicenceLabel(video.licence)
|
||||
},
|
||||
language: {
|
||||
id: video.language,
|
||||
label: getLanguageLabel(video.language)
|
||||
},
|
||||
privacy: {
|
||||
id: video.privacy,
|
||||
label: getPrivacyLabel(video.privacy)
|
||||
},
|
||||
|
||||
nsfw: video.nsfw,
|
||||
nsfwFlags: video.nsfwFlags,
|
||||
nsfwSummary: video.nsfwSummary,
|
||||
|
||||
truncatedDescription: video.getTruncatedDescription(),
|
||||
description: options?.completeDescription === true
|
||||
? video.description
|
||||
: video.getTruncatedDescription(),
|
||||
|
||||
isLocal: video.isLocal(),
|
||||
duration: video.duration,
|
||||
|
||||
aspectRatio: video.aspectRatio,
|
||||
|
||||
views: video.views,
|
||||
viewers: VideoViewsManager.Instance.getTotalViewersOf(video),
|
||||
|
||||
likes: video.likes,
|
||||
dislikes: video.dislikes,
|
||||
thumbnailPath: video.getMiniatureStaticPath(),
|
||||
previewPath: video.getPreviewStaticPath(),
|
||||
embedPath: video.getEmbedStaticPath(),
|
||||
createdAt: video.createdAt,
|
||||
updatedAt: video.updatedAt,
|
||||
publishedAt: video.publishedAt,
|
||||
originallyPublishedAt: video.originallyPublishedAt,
|
||||
|
||||
isLive: video.isLive,
|
||||
|
||||
account: video.VideoChannel.Account.toFormattedSummaryJSON(),
|
||||
channel: video.VideoChannel.toFormattedSummaryJSON(),
|
||||
|
||||
userHistory: userHistory
|
||||
? { currentTime: userHistory.currentTime }
|
||||
: undefined,
|
||||
|
||||
comments: video.comments,
|
||||
|
||||
// Can be added by external plugins
|
||||
pluginData: (video as any).pluginData,
|
||||
|
||||
...buildAdditionalAttributes(video, options)
|
||||
}
|
||||
|
||||
span.end()
|
||||
|
||||
return videoObject
|
||||
}
|
||||
|
||||
export function videoModelToFormattedDetailsJSON (video: MVideoFormattableDetails): VideoDetails {
|
||||
const span = tracer.startSpan('peertube.VideoModel.toFormattedDetailsJSON')
|
||||
|
||||
const videoJSON = video.toFormattedJSON({
|
||||
completeDescription: true,
|
||||
additionalAttributes: {
|
||||
liveSchedules: true,
|
||||
scheduledUpdate: true,
|
||||
blacklistInfo: true,
|
||||
files: true
|
||||
}
|
||||
}) as Video & Required<Pick<Video, 'files' | 'streamingPlaylists' | 'scheduledUpdate' | 'blacklisted' | 'blacklistedReason'>>
|
||||
|
||||
const tags = video.Tags
|
||||
? video.Tags.map(t => t.name)
|
||||
: []
|
||||
|
||||
const detailsJSON = {
|
||||
...videoJSON,
|
||||
|
||||
support: video.support,
|
||||
channel: video.VideoChannel.toFormattedJSON(),
|
||||
account: video.VideoChannel.Account.toFormattedJSON(),
|
||||
tags,
|
||||
|
||||
commentsPolicy: {
|
||||
id: video.commentsPolicy,
|
||||
label: VIDEO_COMMENTS_POLICY[video.commentsPolicy]
|
||||
},
|
||||
|
||||
downloadEnabled: video.downloadEnabled,
|
||||
waitTranscoding: video.waitTranscoding,
|
||||
inputFileUpdatedAt: video.inputFileUpdatedAt,
|
||||
state: {
|
||||
id: video.state,
|
||||
label: getStateLabel(video.state)
|
||||
},
|
||||
|
||||
trackerUrls: video.getTrackerUrls()
|
||||
}
|
||||
|
||||
span.end()
|
||||
|
||||
return detailsJSON
|
||||
}
|
||||
|
||||
export function streamingPlaylistsModelToFormattedJSON (
|
||||
video: MVideoFormattable,
|
||||
playlists: MStreamingPlaylistRedundanciesOpt[]
|
||||
): VideoStreamingPlaylist[] {
|
||||
if (isArray(playlists) === false) return []
|
||||
|
||||
return playlists
|
||||
.map(playlist => ({
|
||||
id: playlist.id,
|
||||
type: playlist.type,
|
||||
|
||||
playlistUrl: playlist.getMasterPlaylistUrl(video),
|
||||
segmentsSha256Url: playlist.getSha256SegmentsUrl(video),
|
||||
|
||||
redundancies: isArray(playlist.RedundancyVideos)
|
||||
? playlist.RedundancyVideos.map(r => ({ baseUrl: r.fileUrl }))
|
||||
: [],
|
||||
|
||||
files: videoFilesModelToFormattedJSON(video, playlist.VideoFiles, { includePlaylistUrl: true })
|
||||
}))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function videoFilesModelToFormattedJSON (
|
||||
video: MVideoFormattable,
|
||||
videoFiles: MVideoFile[],
|
||||
options?: {
|
||||
includePlaylistUrl?: true
|
||||
includeMagnet?: boolean
|
||||
}
|
||||
): (VideoFile & { playlistUrl: string })[]
|
||||
|
||||
export function videoFilesModelToFormattedJSON (
|
||||
video: MVideoFormattable,
|
||||
videoFiles: MVideoFile[],
|
||||
options: {
|
||||
includePlaylistUrl?: boolean // default false
|
||||
includeMagnet?: boolean // default true
|
||||
} = {}
|
||||
): VideoFile[] {
|
||||
const { includePlaylistUrl = false, includeMagnet = true } = options
|
||||
|
||||
if (isArray(videoFiles) === false) return []
|
||||
|
||||
const trackerUrls = includeMagnet
|
||||
? video.getTrackerUrls()
|
||||
: []
|
||||
|
||||
return videoFiles
|
||||
.filter(f => !f.isLive())
|
||||
.sort(sortByResolutionDesc)
|
||||
.map(videoFile => {
|
||||
const fileUrl = videoFile.getFileUrl(video)
|
||||
|
||||
return {
|
||||
id: videoFile.id,
|
||||
|
||||
resolution: {
|
||||
id: videoFile.resolution,
|
||||
|
||||
label: getResolutionLabel({
|
||||
resolution: videoFile.resolution,
|
||||
height: videoFile.height,
|
||||
width: videoFile.width
|
||||
})
|
||||
},
|
||||
|
||||
width: videoFile.width,
|
||||
height: videoFile.height,
|
||||
|
||||
magnetUri: includeMagnet && videoFile.hasTorrent()
|
||||
? generateMagnetUri(video, videoFile, trackerUrls)
|
||||
: undefined,
|
||||
|
||||
size: videoFile.size,
|
||||
fps: videoFile.fps,
|
||||
|
||||
torrentUrl: videoFile.getTorrentUrl(),
|
||||
torrentDownloadUrl: videoFile.getTorrentDownloadUrl(),
|
||||
|
||||
fileUrl,
|
||||
fileDownloadUrl: videoFile.getFileDownloadUrl(video),
|
||||
|
||||
metadataUrl: videoFile.metadataUrl ?? getLocalVideoFileMetadataUrl(video, videoFile),
|
||||
|
||||
hasAudio: videoFile.hasAudio(),
|
||||
hasVideo: videoFile.hasVideo(),
|
||||
|
||||
playlistUrl: includePlaylistUrl === true
|
||||
? getHLSResolutionPlaylistFilename(fileUrl)
|
||||
: undefined,
|
||||
|
||||
storage: video.remote
|
||||
? null
|
||||
: videoFile.storage
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function getCategoryLabel (id: number) {
|
||||
return VIDEO_CATEGORIES[id] || 'Unknown'
|
||||
}
|
||||
|
||||
export function getLicenceLabel (id: number) {
|
||||
return VIDEO_LICENCES[id] || 'Unknown'
|
||||
}
|
||||
|
||||
export function getLanguageLabel (id: string) {
|
||||
return VIDEO_LANGUAGES[id] || 'Unknown'
|
||||
}
|
||||
|
||||
export function getPrivacyLabel (id: number) {
|
||||
return VIDEO_PRIVACIES[id] || 'Unknown'
|
||||
}
|
||||
|
||||
export function getStateLabel (id: number) {
|
||||
return VIDEO_STATES[id] || 'Unknown'
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Private
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function buildAdditionalAttributes (video: MVideoFormattable, options: VideoFormattingJSONOptions) {
|
||||
const add = options.additionalAttributes
|
||||
|
||||
const result: Partial<VideoAdditionalAttributes> = {}
|
||||
|
||||
if (add?.state === true) {
|
||||
result.state = {
|
||||
id: video.state,
|
||||
label: getStateLabel(video.state)
|
||||
}
|
||||
}
|
||||
|
||||
if (add?.waitTranscoding === true) {
|
||||
result.waitTranscoding = video.waitTranscoding
|
||||
}
|
||||
|
||||
if (add?.scheduledUpdate === true && video.ScheduleVideoUpdate) {
|
||||
result.scheduledUpdate = {
|
||||
updateAt: video.ScheduleVideoUpdate.updateAt,
|
||||
privacy: video.ScheduleVideoUpdate.privacy || undefined
|
||||
}
|
||||
}
|
||||
|
||||
if (add?.blacklistInfo === true) {
|
||||
result.blacklisted = !!video.VideoBlacklist
|
||||
result.blacklistedReason = video.VideoBlacklist
|
||||
? video.VideoBlacklist.reason
|
||||
: null
|
||||
}
|
||||
|
||||
if (add?.blockedOwner === true) {
|
||||
result.blockedOwner = video.VideoChannel.Account.isBlocked()
|
||||
|
||||
const server = video.VideoChannel.Account.Actor.Server as MServer
|
||||
result.blockedServer = !!(server?.isBlocked())
|
||||
}
|
||||
|
||||
if (add?.files === true) {
|
||||
result.streamingPlaylists = streamingPlaylistsModelToFormattedJSON(video, video.VideoStreamingPlaylists)
|
||||
result.files = videoFilesModelToFormattedJSON(video, video.VideoFiles)
|
||||
}
|
||||
|
||||
if (add?.source === true) {
|
||||
result.videoSource = video.VideoSource?.toFormattedJSON() || null
|
||||
}
|
||||
|
||||
if (add?.automaticTags === true) {
|
||||
result.automaticTags = (video.VideoAutomaticTags || []).map(t => t.AutomaticTag.name)
|
||||
}
|
||||
|
||||
if (add?.liveSchedules === true) {
|
||||
result.liveSchedules = (video.VideoLive?.LiveSchedules || []).map(s => s.toFormattedJSON())
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
214
server/core/models/video/live-video.ts
Normal file
214
server/core/models/video/live-video.ts
Normal file
@@ -0,0 +1,214 @@
|
||||
import { FindAndCountOptions, Op, Transaction } from 'sequelize'
|
||||
import {
|
||||
AllowNull,
|
||||
BelongsTo,
|
||||
Column,
|
||||
CreatedAt,
|
||||
DataType,
|
||||
Default,
|
||||
ForeignKey,
|
||||
Table,
|
||||
UpdatedAt
|
||||
} from 'sequelize-typescript'
|
||||
import { MLiveVideo } from '@server/types/models/index.js'
|
||||
import { UserModel } from '../user/user.js'
|
||||
import { SequelizeModel } from '../shared/index.js'
|
||||
|
||||
export enum LiveVideoStatus {
|
||||
SCHEDULED = 'scheduled',
|
||||
CANCELLED = 'cancelled',
|
||||
COMPLETED = 'completed'
|
||||
}
|
||||
|
||||
@Table({
|
||||
tableName: 'liveVideo',
|
||||
indexes: [
|
||||
{
|
||||
fields: [ 'targetCamera' ]
|
||||
},
|
||||
{
|
||||
fields: [ 'startTime' ]
|
||||
},
|
||||
{
|
||||
fields: [ 'status' ]
|
||||
}
|
||||
]
|
||||
})
|
||||
export class LiveVideoModel extends SequelizeModel<LiveVideoModel> {
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare title: string
|
||||
|
||||
@AllowNull(true)
|
||||
@Column
|
||||
declare thumbnailFilename: string | null
|
||||
|
||||
@AllowNull(true)
|
||||
@Column(DataType.BLOB)
|
||||
declare thumbnailData: Buffer | null
|
||||
|
||||
@AllowNull(true)
|
||||
@Column
|
||||
declare thumbnailMimeType: string | null
|
||||
|
||||
@AllowNull(true)
|
||||
@Column(DataType.BIGINT)
|
||||
declare thumbnailSize: number | null
|
||||
|
||||
@AllowNull(true)
|
||||
@Column
|
||||
declare thumbnailEtag: string | null
|
||||
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare videoOriginalName: string
|
||||
|
||||
@AllowNull(false)
|
||||
@Column(DataType.TEXT)
|
||||
declare videoStoragePath: string
|
||||
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare videoMimeType: string
|
||||
|
||||
@AllowNull(false)
|
||||
@Column(DataType.BIGINT)
|
||||
declare videoSize: number
|
||||
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare startTime: Date
|
||||
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare endTime: Date
|
||||
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare targetCamera: string
|
||||
|
||||
@AllowNull(false)
|
||||
@Default(LiveVideoStatus.SCHEDULED)
|
||||
@Column
|
||||
declare status: LiveVideoStatus
|
||||
|
||||
@ForeignKey(() => UserModel)
|
||||
@Column
|
||||
declare createdByUserId: number
|
||||
|
||||
@BelongsTo(() => UserModel, {
|
||||
foreignKey: {
|
||||
allowNull: false
|
||||
},
|
||||
onDelete: 'restrict'
|
||||
})
|
||||
declare CreatedBy: Awaited<UserModel>
|
||||
|
||||
@CreatedAt
|
||||
declare createdAt: Date
|
||||
|
||||
@UpdatedAt
|
||||
declare updatedAt: Date
|
||||
|
||||
static listForApi (options: {
|
||||
start?: number
|
||||
count?: number
|
||||
targetCamera?: string
|
||||
status?: string
|
||||
transaction?: Transaction
|
||||
}) {
|
||||
const query: FindAndCountOptions = {
|
||||
offset: options.start,
|
||||
limit: options.count,
|
||||
order: [ [ 'startTime', 'DESC' ] ],
|
||||
transaction: options.transaction
|
||||
}
|
||||
|
||||
const where: Record<string, any> = {}
|
||||
|
||||
if (options.targetCamera) where.targetCamera = options.targetCamera
|
||||
if (options.status) where.status = options.status
|
||||
|
||||
if (Object.keys(where).length !== 0) query.where = where
|
||||
|
||||
return LiveVideoModel.findAndCountAll<MLiveVideo>(query)
|
||||
}
|
||||
|
||||
static loadById (id: number, transaction?: Transaction) {
|
||||
return LiveVideoModel.findByPk<MLiveVideo>(id, { transaction })
|
||||
}
|
||||
|
||||
static loadByThumbnailFilename (thumbnailFilename: string, transaction?: Transaction) {
|
||||
return LiveVideoModel.findOne<MLiveVideo>({
|
||||
where: {
|
||||
thumbnailFilename
|
||||
},
|
||||
transaction
|
||||
})
|
||||
}
|
||||
|
||||
static listConflicts (options: {
|
||||
targetCamera: string
|
||||
startTime: Date
|
||||
endTime: Date
|
||||
excludeId?: number
|
||||
transaction?: Transaction
|
||||
}) {
|
||||
const where: Record<string, any> = {
|
||||
targetCamera: options.targetCamera,
|
||||
status: {
|
||||
[Op.not]: LiveVideoStatus.CANCELLED
|
||||
}
|
||||
}
|
||||
|
||||
if (options.excludeId) {
|
||||
where.id = {
|
||||
[Op.ne]: options.excludeId
|
||||
}
|
||||
}
|
||||
|
||||
return LiveVideoModel.findAll<MLiveVideo>({
|
||||
where,
|
||||
transaction: options.transaction
|
||||
})
|
||||
}
|
||||
|
||||
static listForStarting (options: {
|
||||
startBefore: Date
|
||||
endAfter: Date
|
||||
transaction?: Transaction
|
||||
}) {
|
||||
return LiveVideoModel.findAll<MLiveVideo>({
|
||||
where: {
|
||||
status: LiveVideoStatus.SCHEDULED,
|
||||
startTime: {
|
||||
[Op.lte]: options.startBefore
|
||||
},
|
||||
endTime: {
|
||||
[Op.gt]: options.endAfter
|
||||
}
|
||||
},
|
||||
order: [ [ 'startTime', 'ASC' ] ],
|
||||
transaction: options.transaction
|
||||
})
|
||||
}
|
||||
|
||||
toFormattedJSON (this: LiveVideoModel) {
|
||||
return {
|
||||
id: this.id,
|
||||
title: this.title,
|
||||
thumbnailFilename: this.thumbnailFilename,
|
||||
videoOriginalName: this.videoOriginalName,
|
||||
videoStoragePath: this.videoStoragePath,
|
||||
videoMimeType: this.videoMimeType,
|
||||
videoSize: this.videoSize,
|
||||
startTime: this.startTime.toISOString(),
|
||||
endTime: this.endTime.toISOString(),
|
||||
targetCamera: this.targetCamera,
|
||||
status: this.status,
|
||||
createdByUserId: this.createdByUserId,
|
||||
createdAt: this.createdAt.toISOString(),
|
||||
updatedAt: this.updatedAt.toISOString()
|
||||
}
|
||||
}
|
||||
}
|
||||
184
server/core/models/video/player-setting.ts
Normal file
184
server/core/models/video/player-setting.ts
Normal file
@@ -0,0 +1,184 @@
|
||||
import type {
|
||||
PlayerChannelSettings,
|
||||
PlayerSettingsObject,
|
||||
PlayerThemeChannelSetting,
|
||||
PlayerThemeVideoSetting,
|
||||
PlayerVideoSettings
|
||||
} from '@peertube/peertube-models'
|
||||
import { CONFIG } from '@server/initializers/config.js'
|
||||
import { DEFAULT_CHANNEL_PLAYER_SETTING_VALUE, DEFAULT_INSTANCE_PLAYER_SETTING_VALUE } from '@server/initializers/constants.js'
|
||||
import { getLocalChannelPlayerSettingsActivityPubUrl, getLocalVideoPlayerSettingsActivityPubUrl } from '@server/lib/activitypub/url.js'
|
||||
import { MChannel, MChannelActorLight, MVideoUrl } from '@server/types/models/index.js'
|
||||
import { MPlayerSetting } from '@server/types/models/video/player-setting.js'
|
||||
import { Op, Transaction } from 'sequelize'
|
||||
import { AllowNull, BelongsTo, Column, CreatedAt, Default, ForeignKey, Table, UpdatedAt } from 'sequelize-typescript'
|
||||
import { SequelizeModel } from '../shared/index.js'
|
||||
import { VideoChannelModel } from './video-channel.js'
|
||||
import { VideoModel } from './video.js'
|
||||
|
||||
@Table({
|
||||
tableName: 'playerSetting',
|
||||
indexes: [
|
||||
{
|
||||
fields: [ 'videoId' ],
|
||||
unique: true
|
||||
},
|
||||
{
|
||||
fields: [ 'channelId' ],
|
||||
unique: true
|
||||
}
|
||||
]
|
||||
})
|
||||
export class PlayerSettingModel extends SequelizeModel<PlayerSettingModel> {
|
||||
@CreatedAt
|
||||
declare createdAt: Date
|
||||
|
||||
@UpdatedAt
|
||||
declare updatedAt: Date
|
||||
|
||||
@AllowNull(false)
|
||||
@Default(DEFAULT_INSTANCE_PLAYER_SETTING_VALUE)
|
||||
@Column
|
||||
declare theme: PlayerThemeVideoSetting | PlayerThemeChannelSetting
|
||||
|
||||
@ForeignKey(() => VideoModel)
|
||||
@Column
|
||||
declare videoId: number
|
||||
|
||||
@BelongsTo(() => VideoModel, {
|
||||
foreignKey: {
|
||||
allowNull: true
|
||||
},
|
||||
onDelete: 'cascade'
|
||||
})
|
||||
declare Video: Awaited<VideoModel>
|
||||
|
||||
@ForeignKey(() => VideoChannelModel)
|
||||
@Column
|
||||
declare channelId: number
|
||||
|
||||
@BelongsTo(() => VideoChannelModel, {
|
||||
foreignKey: {
|
||||
allowNull: true
|
||||
},
|
||||
onDelete: 'cascade'
|
||||
})
|
||||
declare VideoChannel: Awaited<VideoChannelModel>
|
||||
|
||||
static loadByVideoId (videoId: number, transaction?: Transaction) {
|
||||
return PlayerSettingModel.findOne<MPlayerSetting>({
|
||||
where: { videoId },
|
||||
transaction
|
||||
})
|
||||
}
|
||||
|
||||
static loadByChannelId (channelId: number, transaction?: Transaction) {
|
||||
return PlayerSettingModel.findOne<MPlayerSetting>({
|
||||
where: { channelId },
|
||||
transaction
|
||||
})
|
||||
}
|
||||
|
||||
static async loadByVideoIdOrChannelId (options: {
|
||||
videoId: number
|
||||
channelId: number
|
||||
transaction?: Transaction
|
||||
}) {
|
||||
const { videoId, channelId, transaction } = options
|
||||
|
||||
const results = await PlayerSettingModel.findAll<MPlayerSetting>({
|
||||
where: {
|
||||
[Op.or]: [
|
||||
{ videoId },
|
||||
{ channelId }
|
||||
]
|
||||
},
|
||||
transaction
|
||||
})
|
||||
|
||||
const videoSetting = results.find(s => s.videoId === videoId)
|
||||
const channelSetting = results.find(s => s.channelId === channelId)
|
||||
|
||||
return { videoSetting, channelSetting }
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static formatVideoPlayerSetting (options: {
|
||||
videoSetting: MPlayerSetting
|
||||
channelSetting: MPlayerSetting
|
||||
}): PlayerVideoSettings {
|
||||
const { videoSetting, channelSetting } = options
|
||||
|
||||
const channelFormattedSetting = this.formatChannelPlayerSetting({ channelSetting })
|
||||
if (!videoSetting) return channelFormattedSetting
|
||||
|
||||
let theme: PlayerThemeVideoSetting
|
||||
if (videoSetting.theme === DEFAULT_CHANNEL_PLAYER_SETTING_VALUE) {
|
||||
theme = channelFormattedSetting.theme
|
||||
} else if (videoSetting.theme === DEFAULT_INSTANCE_PLAYER_SETTING_VALUE) {
|
||||
theme = CONFIG.DEFAULTS.PLAYER.THEME
|
||||
} else {
|
||||
theme = videoSetting.theme
|
||||
}
|
||||
|
||||
return {
|
||||
theme
|
||||
}
|
||||
}
|
||||
|
||||
static formatVideoPlayerRawSetting (videoSetting: MPlayerSetting) {
|
||||
return {
|
||||
theme: videoSetting?.theme ?? DEFAULT_CHANNEL_PLAYER_SETTING_VALUE
|
||||
}
|
||||
}
|
||||
|
||||
static formatChannelPlayerSetting (options: {
|
||||
channelSetting: MPlayerSetting
|
||||
}): PlayerChannelSettings {
|
||||
const { channelSetting } = options
|
||||
|
||||
const instanceSetting = {
|
||||
theme: CONFIG.DEFAULTS.PLAYER.THEME
|
||||
}
|
||||
|
||||
if (!channelSetting) return instanceSetting
|
||||
|
||||
return {
|
||||
theme: channelSetting.theme === DEFAULT_INSTANCE_PLAYER_SETTING_VALUE
|
||||
? instanceSetting.theme
|
||||
: channelSetting.theme as PlayerThemeChannelSetting
|
||||
}
|
||||
}
|
||||
|
||||
static formatChannelPlayerRawSetting (channelSetting: MPlayerSetting) {
|
||||
return {
|
||||
theme: channelSetting?.theme ?? DEFAULT_INSTANCE_PLAYER_SETTING_VALUE
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static formatAPPlayerSetting (options: {
|
||||
settings: MPlayerSetting
|
||||
channel: MChannel & MChannelActorLight
|
||||
video: MVideoUrl
|
||||
}): PlayerSettingsObject {
|
||||
const { channel, settings, video } = options
|
||||
|
||||
const json = video
|
||||
? this.formatVideoPlayerRawSetting(settings)
|
||||
: this.formatChannelPlayerRawSetting(settings)
|
||||
|
||||
return {
|
||||
id: video
|
||||
? getLocalVideoPlayerSettingsActivityPubUrl(video)
|
||||
: getLocalChannelPlayerSettingsActivityPubUrl(channel.Actor.preferredUsername),
|
||||
|
||||
object: video?.url || channel?.Actor.url,
|
||||
type: 'PlayerSettings',
|
||||
|
||||
theme: json.theme
|
||||
}
|
||||
}
|
||||
}
|
||||
94
server/core/models/video/schedule-video-update.ts
Normal file
94
server/core/models/video/schedule-video-update.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
import { Op, Transaction } from 'sequelize'
|
||||
import { AllowNull, BelongsTo, Column, CreatedAt, DataType, Default, ForeignKey, Table, UpdatedAt } from 'sequelize-typescript'
|
||||
import { VideoPrivacy } from '@peertube/peertube-models'
|
||||
import { MScheduleVideoUpdate, MScheduleVideoUpdateFormattable } from '@server/types/models/index.js'
|
||||
import { VideoModel } from './video.js'
|
||||
import { SequelizeModel } from '../shared/index.js'
|
||||
|
||||
@Table({
|
||||
tableName: 'scheduleVideoUpdate',
|
||||
indexes: [
|
||||
{
|
||||
fields: [ 'videoId' ],
|
||||
unique: true
|
||||
},
|
||||
{
|
||||
fields: [ 'updateAt' ]
|
||||
}
|
||||
]
|
||||
})
|
||||
export class ScheduleVideoUpdateModel extends SequelizeModel<ScheduleVideoUpdateModel> {
|
||||
@AllowNull(false)
|
||||
@Default(null)
|
||||
@Column
|
||||
declare updateAt: Date
|
||||
|
||||
@AllowNull(true)
|
||||
@Default(null)
|
||||
@Column(DataType.INTEGER)
|
||||
declare privacy: typeof VideoPrivacy.PUBLIC | typeof VideoPrivacy.UNLISTED | typeof VideoPrivacy.INTERNAL
|
||||
|
||||
@CreatedAt
|
||||
declare createdAt: Date
|
||||
|
||||
@UpdatedAt
|
||||
declare updatedAt: Date
|
||||
|
||||
@ForeignKey(() => VideoModel)
|
||||
@Column
|
||||
declare videoId: number
|
||||
|
||||
@BelongsTo(() => VideoModel, {
|
||||
foreignKey: {
|
||||
allowNull: false
|
||||
},
|
||||
onDelete: 'cascade'
|
||||
})
|
||||
declare Video: Awaited<VideoModel>
|
||||
|
||||
static areVideosToUpdate () {
|
||||
const query = {
|
||||
logging: false,
|
||||
attributes: [ 'id' ],
|
||||
where: {
|
||||
updateAt: {
|
||||
[Op.lte]: new Date()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ScheduleVideoUpdateModel.findOne(query)
|
||||
.then(res => !!res)
|
||||
}
|
||||
|
||||
static listVideosToUpdate (transaction?: Transaction) {
|
||||
const query = {
|
||||
where: {
|
||||
updateAt: {
|
||||
[Op.lte]: new Date()
|
||||
}
|
||||
},
|
||||
transaction
|
||||
}
|
||||
|
||||
return ScheduleVideoUpdateModel.findAll<MScheduleVideoUpdate>(query)
|
||||
}
|
||||
|
||||
static deleteByVideoId (videoId: number, t: Transaction) {
|
||||
const query = {
|
||||
where: {
|
||||
videoId
|
||||
},
|
||||
transaction: t
|
||||
}
|
||||
|
||||
return ScheduleVideoUpdateModel.destroy(query)
|
||||
}
|
||||
|
||||
toFormattedJSON (this: MScheduleVideoUpdateFormattable) {
|
||||
return {
|
||||
updateAt: this.updateAt,
|
||||
privacy: this.privacy || undefined
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
import { ActorImageType, VideoChannelCollaboratorState } from '@peertube/peertube-models'
|
||||
import { WEBSERVER } from '@server/initializers/constants.js'
|
||||
import { AbstractListQuery, AbstractListQueryOptions } from '@server/models/shared/abstract-list-query.js'
|
||||
import { buildServerIdsFollowedBy } from '@server/models/shared/index.js'
|
||||
import { Sequelize } from 'sequelize'
|
||||
import { VideoChannelTableAttributes } from './video-channel-table-attributes.js'
|
||||
|
||||
export interface ListVideoChannelsOptions extends AbstractListQueryOptions {
|
||||
actorId?: number
|
||||
search?: string
|
||||
host?: string
|
||||
handles?: string[]
|
||||
forCount?: boolean
|
||||
|
||||
accountId?: number
|
||||
|
||||
// If accountId is provided, include channels where the account is a collaborator
|
||||
// default: false
|
||||
includeCollaborations?: boolean
|
||||
|
||||
statsDaysPrior?: number
|
||||
}
|
||||
|
||||
export class VideoChannelListQueryBuilder extends AbstractListQuery {
|
||||
private readonly tableAttributes = new VideoChannelTableAttributes()
|
||||
|
||||
private builtActorJoin = false
|
||||
private builtAccountJoin = false
|
||||
private builtChannelCollaboratorsJoin = false
|
||||
private builtAccountAvatarJoin = false
|
||||
private builtChannelAvatarJoin = false
|
||||
private builtChannelBannerJoin = false
|
||||
|
||||
constructor (
|
||||
protected readonly sequelize: Sequelize,
|
||||
protected readonly options: ListVideoChannelsOptions
|
||||
) {
|
||||
super(sequelize, { modelName: 'VideoChannelModel', tableName: 'videoChannel' }, options)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
protected buildSubQueryWhere () {
|
||||
const where: string[] = []
|
||||
|
||||
if (this.options.host) {
|
||||
this.buildActorJoin()
|
||||
|
||||
if (this.options.host === WEBSERVER.HOST) {
|
||||
where.push('"Actor"."serverId" IS NULL')
|
||||
} else {
|
||||
where.push('"Actor->Server"."host" = :host')
|
||||
|
||||
this.replacements.host = this.options.host
|
||||
}
|
||||
}
|
||||
|
||||
// Only list local channels OR channels that are on an instance followed by actorId
|
||||
if (this.options.actorId) {
|
||||
this.buildActorJoin()
|
||||
|
||||
where.push(
|
||||
`(` +
|
||||
`"Actor"."serverId" IS NULL OR ` +
|
||||
`"Actor"."serverId" IN ${buildServerIdsFollowedBy(this.options.actorId)}` +
|
||||
`)`
|
||||
)
|
||||
}
|
||||
|
||||
if (this.options.accountId) {
|
||||
this.buildAccountJoin()
|
||||
|
||||
if (this.options.includeCollaborations !== true) {
|
||||
where.push('"VideoChannelModel"."accountId" = :accountId')
|
||||
|
||||
this.replacements.accountId = this.options.accountId
|
||||
} else {
|
||||
this.buildChannelCollaboratorsJoin()
|
||||
|
||||
where.push(
|
||||
`("VideoChannelModel"."accountId" = :accountId OR "VideoChannelCollaborators"."accountId" = :accountId)`
|
||||
)
|
||||
|
||||
this.replacements.accountId = this.options.accountId
|
||||
}
|
||||
}
|
||||
|
||||
if (Array.isArray(this.options.handles) && this.options.handles.length !== 0) {
|
||||
this.buildActorJoin()
|
||||
|
||||
const or: string[] = []
|
||||
|
||||
for (const handle of this.options.handles || []) {
|
||||
const [ preferredUsername, host ] = handle.split('@')
|
||||
|
||||
const sanitizedPreferredUsername = this.sequelize.escape(preferredUsername.toLowerCase())
|
||||
const sanitizedHost = this.sequelize.escape(host)
|
||||
|
||||
if (!host || host === WEBSERVER.HOST) {
|
||||
or.push(`(LOWER("Actor"."preferredUsername") = ${sanitizedPreferredUsername} AND "Actor"."serverId" IS NULL)`)
|
||||
} else {
|
||||
or.push(`(LOWER("Actor"."preferredUsername") = ${sanitizedPreferredUsername} AND "Actor->Server"."host" = ${sanitizedHost})`)
|
||||
}
|
||||
}
|
||||
|
||||
where.push(`(${or.join(' OR ')})`)
|
||||
}
|
||||
|
||||
if (this.options.search) {
|
||||
this.buildAccountJoin()
|
||||
|
||||
const escapedSearch = this.sequelize.escape(this.options.search)
|
||||
const escapedLikeSearch = this.sequelize.escape('%' + this.options.search + '%')
|
||||
|
||||
this.subQueryAttributes.push(
|
||||
`word_similarity(lower(immutable_unaccent(${escapedSearch})), lower(immutable_unaccent("VideoChannelModel"."name"))) as similarity`
|
||||
)
|
||||
|
||||
where.push(
|
||||
`(` +
|
||||
`lower(immutable_unaccent(${escapedSearch})) <% lower(immutable_unaccent("VideoChannelModel"."name")) OR ` +
|
||||
`lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(${escapedLikeSearch})) OR ` +
|
||||
`lower(immutable_unaccent("Account"."name")) LIKE lower(immutable_unaccent(${escapedLikeSearch}))` +
|
||||
`)`
|
||||
)
|
||||
} else {
|
||||
this.subQueryAttributes.push('0 as similarity')
|
||||
}
|
||||
|
||||
if (where.length !== 0) {
|
||||
this.subQueryWhere = `WHERE ${where.join(' AND ')}`
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
private buildActorJoin () {
|
||||
if (this.builtActorJoin) return
|
||||
|
||||
this.subQueryJoin += ' INNER JOIN "actor" "Actor" ON "Actor"."videoChannelId" = "VideoChannelModel"."id" ' +
|
||||
'LEFT JOIN "server" "Actor->Server" ON "Actor"."serverId" = "Actor->Server"."id" '
|
||||
|
||||
this.builtActorJoin = true
|
||||
}
|
||||
|
||||
private buildAccountJoin () {
|
||||
if (this.builtAccountJoin) return
|
||||
|
||||
this.subQueryJoin += ' INNER JOIN "account" "Account" ON "Account"."id" = "VideoChannelModel"."accountId" ' +
|
||||
'INNER JOIN "actor" "Account->Actor" ON "Account->Actor"."accountId" = "Account"."id" ' +
|
||||
'LEFT JOIN "server" "Account->Actor->Server" ON "Account->Actor"."serverId" = "Account->Actor->Server"."id" '
|
||||
|
||||
this.builtAccountJoin = true
|
||||
}
|
||||
|
||||
private buildChannelCollaboratorsJoin () {
|
||||
if (this.builtChannelCollaboratorsJoin) return
|
||||
|
||||
this.subQueryJoin += ' LEFT JOIN "videoChannelCollaborator" "VideoChannelCollaborators" ' +
|
||||
'ON "VideoChannelCollaborators"."channelId" = "VideoChannelModel"."id" ' +
|
||||
'AND "VideoChannelCollaborators"."state" = :channelCollaboratorState ' +
|
||||
// Ensure we join with max 1 collaborator to not duplicate rows
|
||||
'AND "VideoChannelCollaborators"."accountId" = :accountId '
|
||||
|
||||
this.replacements.channelCollaboratorState = VideoChannelCollaboratorState.ACCEPTED
|
||||
this.replacements.accountId = this.options.accountId
|
||||
|
||||
this.builtChannelCollaboratorsJoin = true
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
private buildAccountAvatarsJoin () {
|
||||
if (this.builtAccountAvatarJoin) return
|
||||
|
||||
this.join += `LEFT JOIN "actorImage" "Account->Actor->Avatars" ` +
|
||||
`ON "Account->Actor->Avatars"."actorId" = "VideoChannelModel"."Account.Actor.id" ` +
|
||||
`AND "Account->Actor->Avatars"."type" = ${ActorImageType.AVATAR} `
|
||||
|
||||
this.builtAccountAvatarJoin = true
|
||||
}
|
||||
|
||||
private buildChannelAvatarsJoin () {
|
||||
if (this.builtChannelAvatarJoin) return
|
||||
|
||||
this.join += `LEFT JOIN "actorImage" "Actor->Avatars" ` +
|
||||
`ON "Actor->Avatars"."actorId" = "VideoChannelModel"."Actor.id" ` +
|
||||
`AND "Actor->Avatars"."type" = ${ActorImageType.AVATAR} `
|
||||
|
||||
this.builtChannelAvatarJoin = true
|
||||
}
|
||||
|
||||
private buildChannelBannersJoin () {
|
||||
if (this.builtChannelBannerJoin) return
|
||||
|
||||
this.join += `LEFT JOIN "actorImage" "Actor->Banners" ` +
|
||||
`ON "Actor->Banners"."actorId" = "VideoChannelModel"."Actor.id" ` +
|
||||
`AND "Actor->Banners"."type" = ${ActorImageType.BANNER} `
|
||||
|
||||
this.builtChannelBannerJoin = true
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
protected buildQueryJoin () {
|
||||
this.buildChannelAvatarsJoin()
|
||||
this.buildAccountAvatarsJoin()
|
||||
this.buildChannelBannersJoin()
|
||||
}
|
||||
|
||||
protected buildQueryAttributes () {
|
||||
this.attributes = [
|
||||
...this.attributes,
|
||||
|
||||
this.tableAttributes.getAccountAvatarAttributes(),
|
||||
this.tableAttributes.getChannelAvatarAttributes(),
|
||||
this.tableAttributes.getChannelBannerAttributes()
|
||||
]
|
||||
|
||||
if (this.options.statsDaysPrior) {
|
||||
this.attributes.push(
|
||||
`(SELECT COUNT(*) FROM "video" WHERE "channelId" = "VideoChannelModel"."id") AS "videosCount"`
|
||||
)
|
||||
|
||||
this.attributes.push(
|
||||
// dprint-ignore
|
||||
'(' +
|
||||
`SELECT string_agg(concat_ws('|', t.day, t.views), ',') ` +
|
||||
'FROM ( ' +
|
||||
'WITH days AS ( ' +
|
||||
`SELECT generate_series(date_trunc('day', now()) - '${this.options.statsDaysPrior} day'::interval, ` +
|
||||
`date_trunc('day', now()), '1 day'::interval) AS day ` +
|
||||
') ' +
|
||||
'SELECT days.day AS day, COALESCE(SUM("videoView".views), 0) AS views ' +
|
||||
'FROM days ' +
|
||||
'LEFT JOIN (' +
|
||||
'"videoView" INNER JOIN "video" ON "videoView"."videoId" = "video"."id" ' +
|
||||
'AND "video"."channelId" = "VideoChannelModel"."id"' +
|
||||
`) ON date_trunc('day', "videoView"."startDate") = date_trunc('day', days.day) ` +
|
||||
'GROUP BY day ORDER BY day ' +
|
||||
') t' +
|
||||
') AS "viewsPerDay"'
|
||||
)
|
||||
|
||||
this.attributes.push(
|
||||
'(' +
|
||||
'SELECT COALESCE(SUM("video".views), 0) AS totalViews ' +
|
||||
'FROM "video" ' +
|
||||
'WHERE "video"."channelId" = "VideoChannelModel"."id"' +
|
||||
') AS "totalViews"'
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
protected buildSubQueryJoin () {
|
||||
this.buildActorJoin()
|
||||
this.buildAccountJoin()
|
||||
}
|
||||
|
||||
protected buildSubQueryAttributes () {
|
||||
this.subQueryAttributes = [
|
||||
...this.subQueryAttributes,
|
||||
|
||||
this.tableAttributes.getVideoChannelAttributes(),
|
||||
|
||||
this.tableAttributes.getChannelActorAttributes(),
|
||||
this.tableAttributes.getChannelServerAttributes(),
|
||||
|
||||
this.tableAttributes.getAccountAttributes(),
|
||||
this.tableAttributes.getAccountActorAttributes(),
|
||||
this.tableAttributes.getAccountServerAttributes()
|
||||
]
|
||||
}
|
||||
|
||||
protected getCalculatedAttributes () {
|
||||
return [ 'similarity' ]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { Memoize } from '@server/helpers/memoize.js'
|
||||
import { AccountModel } from '@server/models/account/account.js'
|
||||
import { ActorImageModel } from '@server/models/actor/actor-image.js'
|
||||
import { ActorModel } from '@server/models/actor/actor.js'
|
||||
import { ServerModel } from '@server/models/server/server.js'
|
||||
import { VideoChannelModel } from '../../video-channel.js'
|
||||
|
||||
export class VideoChannelTableAttributes {
|
||||
@Memoize()
|
||||
getVideoChannelAttributes () {
|
||||
return VideoChannelModel.getSQLAttributes('VideoChannelModel').join(', ')
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@Memoize()
|
||||
getChannelActorAttributes () {
|
||||
return ActorModel.getSQLAPIAttributes('Actor', `Actor.`).join(', ')
|
||||
}
|
||||
|
||||
@Memoize()
|
||||
getChannelServerAttributes () {
|
||||
return ServerModel.getSQLSummaryAttributes('Actor->Server', `Actor.Server.`).join(', ')
|
||||
}
|
||||
|
||||
@Memoize()
|
||||
getChannelAvatarAttributes () {
|
||||
return ActorImageModel.getSQLAttributes('Actor->Avatars', 'Actor.Avatars.').join(', ')
|
||||
}
|
||||
|
||||
@Memoize()
|
||||
getChannelBannerAttributes () {
|
||||
return ActorImageModel.getSQLAttributes('Actor->Banners', 'Actor.Banners.').join(', ')
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@Memoize()
|
||||
getAccountAttributes () {
|
||||
return AccountModel.getSQLSummaryAttributes('Account', 'Account.').join(', ')
|
||||
}
|
||||
|
||||
@Memoize()
|
||||
getAccountActorAttributes () {
|
||||
return ActorModel.getSQLSummaryAttributes('Account->Actor', `Account.Actor.`).join(', ')
|
||||
}
|
||||
|
||||
@Memoize()
|
||||
getAccountServerAttributes () {
|
||||
return ServerModel.getSQLSummaryAttributes('Account->Actor->Server', `Account.Actor.Server.`).join(', ')
|
||||
}
|
||||
|
||||
@Memoize()
|
||||
getAccountAvatarAttributes () {
|
||||
return ActorImageModel.getSQLAttributes('Account->Actor->Avatars', 'Account.Actor.Avatars.').join(', ')
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,510 @@
|
||||
import { VideoChannelCollaboratorState, VideoPrivacy } from '@peertube/peertube-models'
|
||||
import { AbstractListQuery, AbstractListQueryOptions } from '@server/models/shared/abstract-list-query.js'
|
||||
import { getAccountJoin, getActorJoin, getAvatarsJoin, getChannelJoin } from '@server/models/shared/sql/actor-helpers.js'
|
||||
import { Sequelize } from 'sequelize'
|
||||
import { createSafeIn } from '../../../shared/index.js'
|
||||
import { VideoCommentTableAttributes } from './video-comment-table-attributes.js'
|
||||
|
||||
export interface ListVideoCommentsOptions extends AbstractListQueryOptions {
|
||||
selectType: 'api-list' | 'api-video' | 'feed' | 'comment-only'
|
||||
|
||||
autoTagOfAccountId?: number
|
||||
|
||||
videoId?: number
|
||||
threadId?: number
|
||||
accountId?: number
|
||||
|
||||
blockerAccountIds?: number[]
|
||||
|
||||
isThread?: boolean
|
||||
notDeleted?: boolean
|
||||
|
||||
isLocal?: boolean
|
||||
onLocalVideo?: boolean
|
||||
|
||||
onPublicVideo?: boolean
|
||||
videoChannelOwnerId?: number
|
||||
videoAccountOwnerId?: number
|
||||
videoAccountOwnerIncludeCollaborations?: boolean
|
||||
|
||||
heldForReview: boolean
|
||||
heldForReviewAccountIdException?: number
|
||||
|
||||
autoTagOneOf?: string[]
|
||||
|
||||
search?: string
|
||||
searchAccount?: string
|
||||
searchVideo?: string
|
||||
|
||||
includeReplyCounters?: boolean
|
||||
}
|
||||
|
||||
export class VideoCommentListQueryBuilder extends AbstractListQuery {
|
||||
private readonly tableAttributes = new VideoCommentTableAttributes()
|
||||
|
||||
private builtAccountJoin = false
|
||||
private builtAccountActorJoin = false
|
||||
private builtVideoJoin = false
|
||||
private builtVideoChannelJoin = false
|
||||
private builtVideoChannelActorJoin = false
|
||||
private builtVideoChannelCollaboratorsJoin = false
|
||||
private builtAccountAvatarJoin = false
|
||||
private builtChannelAvatarJoin = false
|
||||
private builtAutomaticTagsJoin = false
|
||||
|
||||
constructor (
|
||||
protected readonly sequelize: Sequelize,
|
||||
protected readonly options: ListVideoCommentsOptions
|
||||
) {
|
||||
super(sequelize, { modelName: 'VideoCommentModel', tableName: 'videoComment' }, options)
|
||||
|
||||
if (this.options.includeReplyCounters && !this.options.videoId) {
|
||||
throw new Error('Cannot include reply counters without videoId')
|
||||
}
|
||||
}
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
protected buildSubQueryWhere () {
|
||||
let where: string[] = []
|
||||
|
||||
if (this.options.videoId) {
|
||||
this.replacements.videoId = this.options.videoId
|
||||
|
||||
where.push('"VideoCommentModel"."videoId" = :videoId')
|
||||
}
|
||||
|
||||
if (this.options.threadId) {
|
||||
this.replacements.threadId = this.options.threadId
|
||||
|
||||
where.push('("VideoCommentModel"."id" = :threadId OR "VideoCommentModel"."originCommentId" = :threadId)')
|
||||
}
|
||||
|
||||
if (this.options.accountId) {
|
||||
this.replacements.accountId = this.options.accountId
|
||||
|
||||
where.push('"VideoCommentModel"."accountId" = :accountId')
|
||||
}
|
||||
|
||||
if (this.options.blockerAccountIds) {
|
||||
this.buildVideoChannelJoin()
|
||||
|
||||
where = where.concat(this.getBlockWhere('VideoCommentModel', 'Video->VideoChannel'))
|
||||
}
|
||||
|
||||
if (this.options.isThread === true) {
|
||||
where.push('"VideoCommentModel"."inReplyToCommentId" IS NULL')
|
||||
}
|
||||
|
||||
if (this.options.notDeleted === true) {
|
||||
where.push('"VideoCommentModel"."deletedAt" IS NULL')
|
||||
}
|
||||
|
||||
if (this.options.heldForReview === true) {
|
||||
where.push('"VideoCommentModel"."heldForReview" IS TRUE')
|
||||
} else if (this.options.heldForReview === false) {
|
||||
const base = '"VideoCommentModel"."heldForReview" IS FALSE'
|
||||
|
||||
if (this.options.heldForReviewAccountIdException) {
|
||||
this.replacements.heldForReviewAccountIdException = this.options.heldForReviewAccountIdException
|
||||
|
||||
where.push(`(${base} OR "VideoCommentModel"."accountId" = :heldForReviewAccountIdException)`)
|
||||
} else {
|
||||
where.push(base)
|
||||
}
|
||||
}
|
||||
|
||||
if (this.options.autoTagOneOf) {
|
||||
const tags = this.options.autoTagOneOf.map(t => t.toLowerCase())
|
||||
this.buildAutomaticTagsJoin()
|
||||
|
||||
where.push('lower("CommentAutomaticTags->AutomaticTag"."name") IN (' + createSafeIn(this.sequelize, tags) + ')')
|
||||
}
|
||||
|
||||
if (this.options.isLocal === true) {
|
||||
this.buildAccountJoin()
|
||||
this.buildAccountActorJoin()
|
||||
|
||||
where.push('"Account->Actor"."serverId" IS NULL')
|
||||
} else if (this.options.isLocal === false) {
|
||||
this.buildAccountJoin()
|
||||
this.buildAccountActorJoin()
|
||||
|
||||
where.push('"Account->Actor"."serverId" IS NOT NULL')
|
||||
}
|
||||
|
||||
if (this.options.onLocalVideo === true) {
|
||||
this.buildVideoJoin()
|
||||
|
||||
where.push('"Video"."remote" IS FALSE')
|
||||
} else if (this.options.onLocalVideo === false) {
|
||||
this.buildVideoJoin()
|
||||
|
||||
where.push('"Video"."remote" IS TRUE')
|
||||
}
|
||||
|
||||
if (this.options.onPublicVideo === true) {
|
||||
this.buildVideoJoin()
|
||||
|
||||
where.push(`"Video"."privacy" = ${VideoPrivacy.PUBLIC}`)
|
||||
}
|
||||
|
||||
if (this.options.videoAccountOwnerId) {
|
||||
this.buildVideoChannelJoin()
|
||||
|
||||
this.replacements.videoAccountOwnerId = this.options.videoAccountOwnerId
|
||||
|
||||
if (this.options.videoAccountOwnerIncludeCollaborations !== true) {
|
||||
where.push(`"Video->VideoChannel"."accountId" = :videoAccountOwnerId`)
|
||||
} else {
|
||||
this.buildVideoChannelCollaboratorsJoin()
|
||||
|
||||
where.push(
|
||||
`(` +
|
||||
`"Video->VideoChannel"."accountId" = :videoAccountOwnerId OR ` +
|
||||
`"Video->VideoChannel->VideoChannelCollaborators"."accountId" = :videoAccountOwnerId` +
|
||||
`)`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (this.options.videoChannelOwnerId) {
|
||||
this.buildVideoChannelJoin()
|
||||
|
||||
this.replacements.videoChannelOwnerId = this.options.videoChannelOwnerId
|
||||
|
||||
where.push(`"Video->VideoChannel"."id" = :videoChannelOwnerId`)
|
||||
}
|
||||
|
||||
if (this.options.search) {
|
||||
this.buildVideoJoin()
|
||||
this.buildAccountJoin()
|
||||
this.buildAccountActorJoin()
|
||||
|
||||
const escapedLikeSearch = this.sequelize.escape('%' + this.options.search + '%')
|
||||
|
||||
where.push(
|
||||
`(` +
|
||||
`"VideoCommentModel"."text" ILIKE ${escapedLikeSearch} OR ` +
|
||||
`"Account->Actor"."preferredUsername" ILIKE ${escapedLikeSearch} OR ` +
|
||||
`"Account"."name" ILIKE ${escapedLikeSearch} OR ` +
|
||||
`"Video"."name" ILIKE ${escapedLikeSearch} ` +
|
||||
`)`
|
||||
)
|
||||
}
|
||||
|
||||
if (this.options.searchAccount) {
|
||||
this.buildAccountJoin()
|
||||
this.buildAccountActorJoin()
|
||||
|
||||
const escapedLikeSearch = this.sequelize.escape('%' + this.options.searchAccount + '%')
|
||||
|
||||
where.push(
|
||||
`(` +
|
||||
`"Account->Actor"."preferredUsername" ILIKE ${escapedLikeSearch} OR ` +
|
||||
`"Account"."name" ILIKE ${escapedLikeSearch} ` +
|
||||
`)`
|
||||
)
|
||||
}
|
||||
|
||||
if (this.options.searchVideo) {
|
||||
this.buildVideoJoin()
|
||||
|
||||
const escapedLikeSearch = this.sequelize.escape('%' + this.options.searchVideo + '%')
|
||||
|
||||
where.push(`"Video"."name" ILIKE ${escapedLikeSearch}`)
|
||||
}
|
||||
|
||||
if (where.length !== 0) {
|
||||
this.subQueryWhere = `WHERE ${where.join(' AND ')}`
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
private buildAccountJoin () {
|
||||
if (this.builtAccountJoin) return
|
||||
|
||||
this.subQueryJoin += getAccountJoin({
|
||||
on: `"VideoCommentModel"."accountId"`,
|
||||
includeAvatars: false,
|
||||
includeActor: false,
|
||||
required: false
|
||||
})
|
||||
|
||||
this.builtAccountJoin = true
|
||||
}
|
||||
|
||||
private buildAccountActorJoin () {
|
||||
if (this.builtAccountActorJoin) return
|
||||
|
||||
this.subQueryJoin += getActorJoin({
|
||||
base: 'Account->',
|
||||
on: `"Account"."id"`,
|
||||
type: 'account',
|
||||
includeAvatars: false,
|
||||
required: false
|
||||
})
|
||||
|
||||
this.builtAccountActorJoin = true
|
||||
}
|
||||
|
||||
private buildVideoJoin () {
|
||||
if (this.builtVideoJoin) return
|
||||
|
||||
this.subQueryJoin += ' INNER JOIN "video" "Video" ON "Video"."id" = "VideoCommentModel"."videoId" '
|
||||
|
||||
this.builtVideoJoin = true
|
||||
}
|
||||
|
||||
private buildVideoChannelJoin () {
|
||||
if (this.builtVideoChannelJoin) return
|
||||
|
||||
this.buildVideoJoin()
|
||||
|
||||
this.subQueryJoin += getChannelJoin({
|
||||
base: 'Video->',
|
||||
on: '"Video"."channelId"',
|
||||
includeAccount: false,
|
||||
includeAvatars: false,
|
||||
includeActors: false,
|
||||
required: true
|
||||
})
|
||||
|
||||
this.builtVideoChannelJoin = true
|
||||
}
|
||||
|
||||
private buildVideoChannelActorJoin () {
|
||||
if (this.builtVideoChannelActorJoin) return
|
||||
|
||||
this.subQueryJoin += getActorJoin({
|
||||
base: 'Video->VideoChannel->',
|
||||
on: '"Video->VideoChannel"."id"',
|
||||
type: 'channel',
|
||||
includeAvatars: false,
|
||||
required: true
|
||||
})
|
||||
|
||||
this.builtVideoChannelActorJoin = true
|
||||
}
|
||||
|
||||
private buildVideoChannelCollaboratorsJoin () {
|
||||
if (this.builtVideoChannelCollaboratorsJoin) return
|
||||
|
||||
this.buildVideoChannelJoin()
|
||||
|
||||
this.subQueryJoin += ' LEFT JOIN "videoChannelCollaborator" "Video->VideoChannel->VideoChannelCollaborators" ' +
|
||||
'ON "Video->VideoChannel->VideoChannelCollaborators"."channelId" = "Video->VideoChannel"."id" ' +
|
||||
'AND "Video->VideoChannel->VideoChannelCollaborators"."state" = :channelCollaboratorState ' +
|
||||
// Ensure we join with max 1 collaborator to not duplicate rows
|
||||
'AND "Video->VideoChannel->VideoChannelCollaborators"."accountId" = :videoAccountOwnerId '
|
||||
|
||||
this.replacements.videoAccountOwnerId = this.options.videoAccountOwnerId
|
||||
this.replacements.channelCollaboratorState = VideoChannelCollaboratorState.ACCEPTED
|
||||
|
||||
this.builtVideoChannelCollaboratorsJoin = true
|
||||
}
|
||||
|
||||
private buildAutomaticTagsJoin () {
|
||||
if (this.builtAutomaticTagsJoin) return
|
||||
|
||||
this.subQueryJoin += ' LEFT JOIN (' +
|
||||
'"commentAutomaticTag" AS "CommentAutomaticTags" INNER JOIN "automaticTag" AS "CommentAutomaticTags->AutomaticTag" ' +
|
||||
'ON "CommentAutomaticTags->AutomaticTag"."id" = "CommentAutomaticTags"."automaticTagId" ' +
|
||||
') ON "VideoCommentModel"."id" = "CommentAutomaticTags"."commentId" AND "CommentAutomaticTags"."accountId" = :autoTagOfAccountId '
|
||||
|
||||
this.replacements.autoTagOfAccountId = this.options.autoTagOfAccountId
|
||||
this.builtAutomaticTagsJoin = true
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
private buildAccountAvatarsJoin () {
|
||||
if (this.builtAccountAvatarJoin) return
|
||||
|
||||
this.join += getAvatarsJoin({
|
||||
base: 'Account->Actor->',
|
||||
on: '"VideoCommentModel"."Account.Actor.id"'
|
||||
})
|
||||
|
||||
this.builtAccountAvatarJoin = true
|
||||
}
|
||||
|
||||
private buildChannelAvatarsJoin () {
|
||||
if (this.builtChannelAvatarJoin) return
|
||||
|
||||
this.join += getAvatarsJoin({
|
||||
base: 'Video->VideoChannel->Actor->',
|
||||
on: '"VideoCommentModel"."Video.VideoChannel.Actor.id"'
|
||||
})
|
||||
|
||||
this.builtChannelAvatarJoin = true
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
protected buildQueryJoin () {
|
||||
const selectType = this.options.selectType
|
||||
|
||||
if (selectType === 'api-list' || selectType === 'api-video' || selectType === 'feed') {
|
||||
this.buildAccountAvatarsJoin()
|
||||
}
|
||||
|
||||
if (selectType === 'api-list') {
|
||||
this.buildChannelAvatarsJoin()
|
||||
}
|
||||
}
|
||||
|
||||
protected buildQueryAttributes () {
|
||||
const selectType = this.options.selectType
|
||||
|
||||
if (selectType === 'api-list' || selectType === 'api-video' || selectType === 'feed') {
|
||||
this.attributes.push(this.tableAttributes.getAccountAvatarAttributes())
|
||||
}
|
||||
|
||||
if (selectType === 'api-list') {
|
||||
this.attributes.push(this.tableAttributes.getChannelAvatarAttributes())
|
||||
}
|
||||
}
|
||||
|
||||
protected buildSubQueryJoin () {
|
||||
const selectType = this.options.selectType
|
||||
|
||||
if (selectType === 'api-list' || selectType === 'api-video' || selectType === 'feed') {
|
||||
this.buildAccountJoin()
|
||||
this.buildAccountActorJoin()
|
||||
}
|
||||
|
||||
if (selectType === 'api-list') {
|
||||
this.buildVideoJoin()
|
||||
this.buildVideoChannelJoin()
|
||||
this.buildVideoChannelActorJoin()
|
||||
}
|
||||
|
||||
if (this.options.autoTagOfAccountId && selectType === 'api-list') {
|
||||
this.buildAutomaticTagsJoin()
|
||||
}
|
||||
}
|
||||
|
||||
protected buildSubQueryAttributes () {
|
||||
const selectType = this.options.selectType
|
||||
|
||||
this.subQueryAttributes = [
|
||||
...this.subQueryAttributes,
|
||||
|
||||
this.tableAttributes.getVideoCommentAttributes()
|
||||
]
|
||||
|
||||
if (selectType === 'api-list' || selectType === 'api-video' || selectType === 'feed') {
|
||||
this.subQueryAttributes = [
|
||||
...this.subQueryAttributes,
|
||||
|
||||
this.tableAttributes.getVideoAttributes(),
|
||||
|
||||
this.tableAttributes.getAccountAttributes(),
|
||||
this.tableAttributes.getAccountActorAttributes(),
|
||||
this.tableAttributes.getAccountServerAttributes()
|
||||
]
|
||||
}
|
||||
|
||||
if (selectType === 'api-list') {
|
||||
this.subQueryAttributes = [
|
||||
...this.subQueryAttributes,
|
||||
|
||||
this.tableAttributes.getChannelAttributes(),
|
||||
this.tableAttributes.getChannelActorAttributes(),
|
||||
this.tableAttributes.getChannelServerAttributes()
|
||||
]
|
||||
}
|
||||
|
||||
if (this.options.autoTagOfAccountId && this.options.selectType === 'api-list') {
|
||||
this.subQueryAttributes = [
|
||||
...this.subQueryAttributes,
|
||||
|
||||
this.tableAttributes.getCommentAutomaticTagAttributes(),
|
||||
this.tableAttributes.getAutomaticTagAttributes()
|
||||
]
|
||||
}
|
||||
|
||||
if (this.options.includeReplyCounters === true) {
|
||||
this.subQueryAttributes.push('"totalRepliesFromVideoAuthor"."count" AS "totalRepliesFromVideoAuthor"')
|
||||
this.subQueryAttributes.push('"totalReplies"."count" AS "totalReplies"')
|
||||
}
|
||||
}
|
||||
|
||||
protected getCalculatedAttributes () {
|
||||
return [
|
||||
'totalRepliesFromVideoAuthor',
|
||||
'totalReplies'
|
||||
]
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
protected buildSubQueryLateralJoin () {
|
||||
if (this.options.includeReplyCounters === true) {
|
||||
this.buildTotalRepliesLateralJoin()
|
||||
this.buildAuthorTotalRepliesLateralJoin()
|
||||
}
|
||||
}
|
||||
|
||||
private buildTotalRepliesLateralJoin () {
|
||||
const blockWhereString = this.getBlockWhere('replies', 'videoChannel').join(' AND ')
|
||||
|
||||
// Help the planner by providing videoId that should filter out many comments
|
||||
this.replacements.videoId = this.options.videoId
|
||||
|
||||
this.subQueryLateralJoin += `LEFT JOIN LATERAL (` +
|
||||
`SELECT COUNT("replies"."id") AS "count" FROM "videoComment" AS "replies" ` +
|
||||
`INNER JOIN "video" ON "video"."id" = "replies"."videoId" AND "replies"."videoId" = :videoId ` +
|
||||
`LEFT JOIN "videoChannel" ON "video"."channelId" = "videoChannel"."id" ` +
|
||||
`WHERE ("replies"."inReplyToCommentId" = "VideoCommentModel"."id" OR "replies"."originCommentId" = "VideoCommentModel"."id") ` +
|
||||
`AND "deletedAt" IS NULL ` +
|
||||
`AND ${blockWhereString} ` +
|
||||
`) "totalReplies" ON TRUE `
|
||||
}
|
||||
|
||||
private buildAuthorTotalRepliesLateralJoin () {
|
||||
// Help the planner by providing videoId that should filter out many comments
|
||||
this.replacements.videoId = this.options.videoId
|
||||
|
||||
this.subQueryLateralJoin += `LEFT JOIN LATERAL (` +
|
||||
`SELECT COUNT("replies"."id") AS "count" FROM "videoComment" AS "replies" ` +
|
||||
`INNER JOIN "video" ON "video"."id" = "replies"."videoId" AND "replies"."videoId" = :videoId ` +
|
||||
`INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ` +
|
||||
`WHERE ("replies"."inReplyToCommentId" = "VideoCommentModel"."id" OR "replies"."originCommentId" = "VideoCommentModel"."id") ` +
|
||||
`AND "replies"."accountId" = "videoChannel"."accountId"` +
|
||||
`) "totalRepliesFromVideoAuthor" ON TRUE `
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
private getBlockWhere (commentTableName: string, channelTableName: string) {
|
||||
const where: string[] = []
|
||||
|
||||
const blockerIdsString = createSafeIn(
|
||||
this.sequelize,
|
||||
this.options.blockerAccountIds,
|
||||
[ `"${channelTableName}"."accountId"` ]
|
||||
)
|
||||
|
||||
where.push(
|
||||
`NOT EXISTS (` +
|
||||
`SELECT 1 FROM "accountBlocklist" ` +
|
||||
`WHERE "targetAccountId" = "${commentTableName}"."accountId" ` +
|
||||
`AND "accountId" IN (${blockerIdsString})` +
|
||||
`)`
|
||||
)
|
||||
|
||||
where.push(
|
||||
`NOT EXISTS (` +
|
||||
`SELECT 1 FROM "account" ` +
|
||||
`INNER JOIN "actor" ON account."id" = actor."accountId" ` +
|
||||
`INNER JOIN "serverBlocklist" ON "actor"."serverId" = "serverBlocklist"."targetServerId" ` +
|
||||
`WHERE "account"."id" = "${commentTableName}"."accountId" ` +
|
||||
`AND "serverBlocklist"."accountId" IN (${blockerIdsString})` +
|
||||
`)`
|
||||
)
|
||||
|
||||
return where
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { Memoize } from '@server/helpers/memoize.js'
|
||||
import { AccountModel } from '@server/models/account/account.js'
|
||||
import { ActorImageModel } from '@server/models/actor/actor-image.js'
|
||||
import { ActorModel } from '@server/models/actor/actor.js'
|
||||
import { CommentAutomaticTagModel } from '@server/models/automatic-tag/comment-automatic-tag.js'
|
||||
import { ServerModel } from '@server/models/server/server.js'
|
||||
import { buildSQLAttributes } from '@server/models/shared/table.js'
|
||||
import { AutomaticTagModel } from '../../../automatic-tag/automatic-tag.js'
|
||||
import { VideoCommentModel } from '../../video-comment.js'
|
||||
import { VideoChannelModel } from '../../video-channel.js'
|
||||
|
||||
export class VideoCommentTableAttributes {
|
||||
@Memoize()
|
||||
getVideoCommentAttributes () {
|
||||
return VideoCommentModel.getSQLAttributes('VideoCommentModel').join(', ')
|
||||
}
|
||||
|
||||
@Memoize()
|
||||
getVideoAttributes () {
|
||||
return [
|
||||
`"Video"."id" AS "Video.id"`,
|
||||
`"Video"."uuid" AS "Video.uuid"`,
|
||||
`"Video"."name" AS "Video.name"`
|
||||
].join(', ')
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@Memoize()
|
||||
getAccountAttributes () {
|
||||
return AccountModel.getSQLAttributes('Account', 'Account.').join(', ')
|
||||
}
|
||||
|
||||
@Memoize()
|
||||
getAccountActorAttributes () {
|
||||
return ActorModel.getSQLAPIAttributes('Account->Actor', `Account.Actor.`).join(', ')
|
||||
}
|
||||
|
||||
@Memoize()
|
||||
getAccountServerAttributes () {
|
||||
return ServerModel.getSQLAttributes('Account->Actor->Server', `Account.Actor.Server.`).join(', ')
|
||||
}
|
||||
|
||||
@Memoize()
|
||||
getAccountAvatarAttributes () {
|
||||
return ActorImageModel.getSQLAttributes('Account->Actor->Avatars', 'Account.Actor.Avatars.').join(', ')
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@Memoize()
|
||||
getChannelAttributes () {
|
||||
return VideoChannelModel.getSQLSummaryAttributes('Video->VideoChannel', 'Video.VideoChannel.').join(', ')
|
||||
}
|
||||
|
||||
@Memoize()
|
||||
getChannelActorAttributes () {
|
||||
return ActorModel.getSQLSummaryAttributes('Video->VideoChannel->Actor', `Video.VideoChannel.Actor.`).join(', ')
|
||||
}
|
||||
|
||||
@Memoize()
|
||||
getChannelServerAttributes () {
|
||||
return ServerModel.getSQLAttributes('Video->VideoChannel->Actor->Server', `Video.VideoChannel.Actor.Server.`).join(', ')
|
||||
}
|
||||
|
||||
@Memoize()
|
||||
getChannelAvatarAttributes () {
|
||||
return ActorImageModel.getSQLAttributes('Video->VideoChannel->Actor->Avatars', 'Video.VideoChannel.Actor.Avatars.').join(', ')
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@Memoize()
|
||||
getCommentAutomaticTagAttributes () {
|
||||
return buildSQLAttributes({
|
||||
model: CommentAutomaticTagModel,
|
||||
tableName: 'CommentAutomaticTags',
|
||||
aliasPrefix: 'CommentAutomaticTags.',
|
||||
idBuilder: [ 'commentId', 'automaticTagId', 'accountId' ]
|
||||
}).join(', ')
|
||||
}
|
||||
|
||||
@Memoize()
|
||||
getAutomaticTagAttributes () {
|
||||
return buildSQLAttributes({
|
||||
model: AutomaticTagModel,
|
||||
tableName: 'CommentAutomaticTags->AutomaticTag',
|
||||
aliasPrefix: 'CommentAutomaticTags.AutomaticTag.'
|
||||
}).join(', ')
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
import { VideoChannelCollaboratorState } from '@peertube/peertube-models'
|
||||
import { AbstractListQuery, AbstractListQueryOptions } from '@server/models/shared/abstract-list-query.js'
|
||||
import { getAvatarsJoin, getChannelJoin } from '@server/models/shared/sql/actor-helpers.js'
|
||||
import { Sequelize } from 'sequelize'
|
||||
import { VideoImportTableAttributes } from './video-import-table-attributes.js'
|
||||
|
||||
export interface ListVideoImportsOptions extends AbstractListQueryOptions {
|
||||
userId: number
|
||||
|
||||
id?: number
|
||||
videoId?: number
|
||||
search?: string
|
||||
targetUrl?: string
|
||||
videoChannelSyncId?: number
|
||||
|
||||
collaborationAccountId?: number
|
||||
}
|
||||
|
||||
export class VideoImportListQueryBuilder extends AbstractListQuery {
|
||||
private readonly tableAttributes = new VideoImportTableAttributes()
|
||||
|
||||
private builtVideoJoin = false
|
||||
private builtTagJoin = false
|
||||
private builtChannelCollaboratorsJoin = false
|
||||
private builtThumbnailJoin = false
|
||||
private builtAccountAvatarJoin = false
|
||||
private builtChannelAvatarJoin = false
|
||||
|
||||
constructor (
|
||||
protected readonly sequelize: Sequelize,
|
||||
protected readonly options: ListVideoImportsOptions
|
||||
) {
|
||||
super(sequelize, { modelName: 'VideoImportModel', tableName: 'videoImport' }, options)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
protected buildSubQueryWhere () {
|
||||
const where: string[] = []
|
||||
|
||||
this.buildVideoJoin()
|
||||
|
||||
if (this.options.collaborationAccountId) {
|
||||
this.buildChannelCollaboratorsJoin()
|
||||
|
||||
where.push(
|
||||
'(' +
|
||||
'"VideoImportModel"."userId" = :userId OR ' +
|
||||
'"Video->VideoChannel->VideoChannelCollaborators"."accountId" = :collaborationAccountId OR ' +
|
||||
'"Video->VideoChannel->Account"."userId" = :userId' +
|
||||
')'
|
||||
)
|
||||
|
||||
this.replacements.collaborationAccountId = this.options.collaborationAccountId
|
||||
this.replacements.userId = this.options.userId
|
||||
} else {
|
||||
where.push(
|
||||
'(' +
|
||||
'"VideoImportModel"."userId" = :userId OR ' +
|
||||
'"Video->VideoChannel->Account"."userId" = :userId' +
|
||||
')'
|
||||
)
|
||||
|
||||
this.replacements.userId = this.options.userId
|
||||
}
|
||||
|
||||
if (this.options.id) {
|
||||
where.push('"VideoImportModel"."id" = :id')
|
||||
|
||||
this.replacements.id = this.options.id
|
||||
}
|
||||
|
||||
if (this.options.videoId) {
|
||||
where.push('"VideoImportModel"."videoId" = :videoId')
|
||||
|
||||
this.replacements.videoId = this.options.videoId
|
||||
}
|
||||
|
||||
if (this.options.targetUrl) {
|
||||
where.push('"VideoImportModel"."targetUrl" = :targetUrl')
|
||||
|
||||
this.replacements.targetUrl = this.options.targetUrl
|
||||
}
|
||||
|
||||
if (this.options.videoChannelSyncId) {
|
||||
where.push('"VideoImportModel"."videoChannelSyncId" = :videoChannelSyncId')
|
||||
|
||||
this.replacements.videoChannelSyncId = this.options.videoChannelSyncId
|
||||
}
|
||||
|
||||
if (this.options.search) {
|
||||
const escapedLikeSearch = this.sequelize.escape('%' + this.options.search + '%')
|
||||
|
||||
where.push(
|
||||
`(` +
|
||||
`lower(immutable_unaccent("Video"."name")) LIKE lower(immutable_unaccent(${escapedLikeSearch})) OR ` +
|
||||
`lower(immutable_unaccent("VideoImportModel"."targetUrl")) LIKE lower(immutable_unaccent(${escapedLikeSearch})) OR ` +
|
||||
`lower(immutable_unaccent("VideoImportModel"."torrentName")) LIKE lower(immutable_unaccent(${escapedLikeSearch})) OR ` +
|
||||
`lower(immutable_unaccent("VideoImportModel"."magnetUri")) LIKE lower(immutable_unaccent(${escapedLikeSearch}))` +
|
||||
`)`
|
||||
)
|
||||
}
|
||||
|
||||
if (where.length !== 0) {
|
||||
this.subQueryWhere = `WHERE ${where.join(' AND ')}`
|
||||
}
|
||||
}
|
||||
|
||||
private buildVideoJoin () {
|
||||
if (this.builtVideoJoin) return
|
||||
|
||||
this.subQueryJoin += ` LEFT JOIN "video" "Video" ON "Video"."id" = "VideoImportModel"."videoId" ` +
|
||||
getChannelJoin({
|
||||
base: 'Video->',
|
||||
on: '"Video"."channelId"',
|
||||
includeAccount: true,
|
||||
includeActors: true,
|
||||
includeAvatars: false,
|
||||
required: false
|
||||
})
|
||||
|
||||
this.builtVideoJoin = true
|
||||
}
|
||||
|
||||
private buildChannelCollaboratorsJoin () {
|
||||
if (this.builtChannelCollaboratorsJoin) return
|
||||
|
||||
this.buildVideoJoin()
|
||||
|
||||
this.subQueryJoin += ' LEFT JOIN "videoChannelCollaborator" "Video->VideoChannel->VideoChannelCollaborators" ' +
|
||||
'ON "Video->VideoChannel->VideoChannelCollaborators"."channelId" = "Video->VideoChannel"."id" ' +
|
||||
'AND "Video->VideoChannel->VideoChannelCollaborators"."state" = :channelCollaboratorState ' +
|
||||
// Ensure we join with max 1 collaborator to not duplicate rows
|
||||
'AND "Video->VideoChannel->VideoChannelCollaborators"."accountId" = :collaborationAccountId '
|
||||
|
||||
this.replacements.channelCollaboratorState = VideoChannelCollaboratorState.ACCEPTED
|
||||
this.replacements.collaborationAccountId = this.options.collaborationAccountId
|
||||
|
||||
this.builtChannelCollaboratorsJoin = true
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
private buildThumbnailJoin () {
|
||||
if (this.builtThumbnailJoin) return
|
||||
|
||||
this.join += ' LEFT JOIN "thumbnail" "Video->Thumbnails" ON "Video->Thumbnails"."videoId" = "Video.id" '
|
||||
|
||||
this.builtThumbnailJoin = true
|
||||
}
|
||||
|
||||
private buildTagJoin () {
|
||||
if (this.builtTagJoin) return
|
||||
|
||||
this.join += ' LEFT JOIN "videoTag" ON "videoTag"."videoId" = "Video.id" ' +
|
||||
'LEFT JOIN "tag" "Video->Tags" ON "Video->Tags"."id" = "videoTag"."tagId" '
|
||||
|
||||
this.builtTagJoin = true
|
||||
}
|
||||
|
||||
private buildAccountAvatarsJoin () {
|
||||
if (this.builtAccountAvatarJoin) return
|
||||
|
||||
this.join += getAvatarsJoin({ base: 'Video->VideoChannel->Account->Actor->', on: '"Video.VideoChannel.Account.Actor.id"' })
|
||||
|
||||
this.builtAccountAvatarJoin = true
|
||||
}
|
||||
|
||||
private buildChannelAvatarsJoin () {
|
||||
if (this.builtChannelAvatarJoin) return
|
||||
|
||||
this.join += getAvatarsJoin({ base: 'Video->VideoChannel->Actor->', on: '"Video.VideoChannel.Actor.id"' })
|
||||
|
||||
this.builtChannelAvatarJoin = true
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
protected buildQueryJoin () {
|
||||
this.buildChannelAvatarsJoin()
|
||||
this.buildAccountAvatarsJoin()
|
||||
this.buildTagJoin()
|
||||
this.buildThumbnailJoin()
|
||||
}
|
||||
|
||||
protected buildQueryAttributes () {
|
||||
this.attributes = [
|
||||
...this.attributes,
|
||||
|
||||
this.tableAttributes.getVideoTagAttributes(),
|
||||
this.tableAttributes.getAccountAvatarAttributes(),
|
||||
this.tableAttributes.getChannelAvatarAttributes(),
|
||||
this.tableAttributes.getThumbnailAttributes()
|
||||
]
|
||||
}
|
||||
|
||||
protected buildSubQueryJoin () {
|
||||
this.buildVideoJoin()
|
||||
}
|
||||
|
||||
protected buildSubQueryAttributes () {
|
||||
this.subQueryAttributes = [
|
||||
...this.subQueryAttributes,
|
||||
|
||||
this.tableAttributes.getVideoImportAttributes(),
|
||||
this.tableAttributes.getVideoAttributes(),
|
||||
|
||||
this.tableAttributes.getChannelAttributes(),
|
||||
this.tableAttributes.getChannelActorAttributes(),
|
||||
this.tableAttributes.getChannelServerAttributes(),
|
||||
|
||||
this.tableAttributes.getAccountAttributes(),
|
||||
this.tableAttributes.getAccountActorAttributes(),
|
||||
this.tableAttributes.getAccountServerAttributes()
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { Memoize } from '@server/helpers/memoize.js'
|
||||
import { AccountModel } from '@server/models/account/account.js'
|
||||
import { ActorImageModel } from '@server/models/actor/actor-image.js'
|
||||
import { ActorModel } from '@server/models/actor/actor.js'
|
||||
import { ServerModel } from '@server/models/server/server.js'
|
||||
import { TagModel } from '../../tag.js'
|
||||
import { ThumbnailModel } from '../../thumbnail.js'
|
||||
import { VideoChannelModel } from '../../video-channel.js'
|
||||
import { VideoImportModel } from '../../video-import.js'
|
||||
import { VideoModel } from '../../video.js'
|
||||
|
||||
export class VideoImportTableAttributes {
|
||||
@Memoize()
|
||||
getVideoImportAttributes () {
|
||||
return VideoImportModel.getSQLAttributes('VideoImportModel').join(', ')
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@Memoize()
|
||||
getVideoAttributes () {
|
||||
return VideoModel.getSQLAttributes('Video', 'Video.').join(', ')
|
||||
}
|
||||
|
||||
getVideoTagAttributes () {
|
||||
return TagModel.getSQLAttributes('Video->Tags', 'Video.Tags.').join(', ')
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@Memoize()
|
||||
getChannelAttributes () {
|
||||
return VideoChannelModel.getSQLAttributes('Video->VideoChannel', 'Video.VideoChannel.').join(', ')
|
||||
}
|
||||
|
||||
@Memoize()
|
||||
getChannelActorAttributes () {
|
||||
return ActorModel.getSQLSummaryAttributes('Video->VideoChannel->Actor', `Video.VideoChannel.Actor.`).join(', ')
|
||||
}
|
||||
|
||||
@Memoize()
|
||||
getChannelServerAttributes () {
|
||||
return ServerModel.getSQLSummaryAttributes('Video->VideoChannel->Actor->Server', `Video.VideoChannel.Actor.Server.`).join(', ')
|
||||
}
|
||||
|
||||
@Memoize()
|
||||
getChannelAvatarAttributes () {
|
||||
return ActorImageModel.getSQLAttributes('Video->VideoChannel->Actor->Avatars', 'Video.VideoChannel.Actor.Avatars.').join(', ')
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@Memoize()
|
||||
getAccountAttributes () {
|
||||
return AccountModel.getSQLSummaryAttributes('Video->VideoChannel->Account', 'Video.VideoChannel.Account.').join(', ')
|
||||
}
|
||||
|
||||
@Memoize()
|
||||
getAccountActorAttributes () {
|
||||
return ActorModel.getSQLSummaryAttributes('Video->VideoChannel->Account->Actor', `Video.VideoChannel.Account.Actor.`).join(', ')
|
||||
}
|
||||
|
||||
@Memoize()
|
||||
getAccountServerAttributes () {
|
||||
return ServerModel.getSQLSummaryAttributes('Video->VideoChannel->Account->Actor->Server', `Video.VideoChannel.Account.Actor.Server.`)
|
||||
.join(', ')
|
||||
}
|
||||
|
||||
@Memoize()
|
||||
getAccountAvatarAttributes () {
|
||||
return ActorImageModel.getSQLAttributes('Video->VideoChannel->Account->Actor->Avatars', 'Video.VideoChannel.Account.Actor.Avatars.')
|
||||
.join(', ')
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@Memoize()
|
||||
getThumbnailAttributes () {
|
||||
return ThumbnailModel.getSQLAttributes('Video->Thumbnails', 'Video.Thumbnails.').join(', ')
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
import { ActorImageType, VideoChannelCollaboratorState, VideoPlaylistPrivacy, VideoPlaylistType_Type } from '@peertube/peertube-models'
|
||||
import { WEBSERVER } from '@server/initializers/constants.js'
|
||||
import { AbstractListQuery, AbstractListQueryOptions } from '@server/models/shared/abstract-list-query.js'
|
||||
import { buildServerIdsFollowedBy, getPlaylistSort } from '@server/models/shared/index.js'
|
||||
import { Sequelize } from 'sequelize'
|
||||
import { VideoPlaylistTableAttributes } from './video-playlist-table-attributes.js'
|
||||
|
||||
export interface ListVideoPlaylistsOptions extends AbstractListQueryOptions {
|
||||
followerActorId?: number
|
||||
type?: VideoPlaylistType_Type
|
||||
|
||||
accountId?: number
|
||||
includeCollaborationsForAccount?: number
|
||||
|
||||
videoChannelId?: number
|
||||
listMyPlaylists?: boolean
|
||||
search?: string
|
||||
host?: string
|
||||
uuids?: string[]
|
||||
channelNameOneOf?: string[]
|
||||
withVideos?: boolean
|
||||
}
|
||||
|
||||
export class VideoPlaylistListQueryBuilder extends AbstractListQuery {
|
||||
private readonly tableAttributes = new VideoPlaylistTableAttributes()
|
||||
|
||||
private builtAccountJoin = false
|
||||
private builtVideoChannelJoin = false
|
||||
private builtChannelCollaboratorsJoin = false
|
||||
private builtAccountAvatarJoin = false
|
||||
private builtChannelAvatarJoin = false
|
||||
private builtThumbnailJoin = false
|
||||
|
||||
constructor (
|
||||
protected readonly sequelize: Sequelize,
|
||||
protected readonly options: ListVideoPlaylistsOptions
|
||||
) {
|
||||
super(sequelize, { modelName: 'VideoPlaylistModel', tableName: 'videoPlaylist' }, options)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
protected buildSubQueryWhere () {
|
||||
const where: string[] = []
|
||||
|
||||
if (this.options.host) {
|
||||
this.buildAccountJoin()
|
||||
|
||||
if (this.options.host === WEBSERVER.HOST) {
|
||||
where.push('"OwnerAccount->Actor"."serverId" IS NULL')
|
||||
} else {
|
||||
where.push('"OwnerAccount->Actor->Server"."host" = :host')
|
||||
|
||||
this.replacements.host = this.options.host
|
||||
}
|
||||
}
|
||||
|
||||
if (this.options.listMyPlaylists !== true) {
|
||||
where.push('"VideoPlaylistModel"."privacy" = :privacy')
|
||||
|
||||
this.replacements.privacy = VideoPlaylistPrivacy.PUBLIC
|
||||
}
|
||||
|
||||
if (this.options.followerActorId) {
|
||||
this.buildAccountJoin()
|
||||
|
||||
where.push(
|
||||
`(` +
|
||||
`"OwnerAccount->Actor"."serverId" IS NULL OR ` +
|
||||
`"OwnerAccount->Actor"."serverId" IN ${buildServerIdsFollowedBy(this.options.followerActorId)}` +
|
||||
`)`
|
||||
)
|
||||
}
|
||||
|
||||
if (this.options.accountId) {
|
||||
if (this.options.includeCollaborationsForAccount) {
|
||||
this.buildChannelCollaboratorsJoin()
|
||||
|
||||
where.push(
|
||||
`(` +
|
||||
` "VideoPlaylistModel"."ownerAccountId" = :accountId OR ` +
|
||||
` "VideoChannel->VideoChannelCollaborators"."accountId" = :collaborationAccountId` +
|
||||
`)`
|
||||
)
|
||||
|
||||
this.replacements.accountId = this.options.accountId
|
||||
this.replacements.collaborationAccountId = this.options.includeCollaborationsForAccount
|
||||
} else {
|
||||
where.push('"VideoPlaylistModel"."ownerAccountId" = :accountId')
|
||||
|
||||
this.replacements.accountId = this.options.accountId
|
||||
}
|
||||
}
|
||||
|
||||
if (this.options.videoChannelId) {
|
||||
if (this.options.includeCollaborationsForAccount) {
|
||||
this.buildChannelCollaboratorsJoin()
|
||||
|
||||
where.push(
|
||||
`(` +
|
||||
` "VideoPlaylistModel"."videoChannelId" = :videoChannelId OR ` +
|
||||
` "VideoChannel->VideoChannelCollaborators"."accountId" = :collaborationAccountId` +
|
||||
`)`
|
||||
)
|
||||
|
||||
this.replacements.videoChannelId = this.options.videoChannelId
|
||||
this.replacements.collaborationAccountId = this.options.includeCollaborationsForAccount
|
||||
} else {
|
||||
where.push('"VideoPlaylistModel"."videoChannelId" = :videoChannelId')
|
||||
|
||||
this.replacements.videoChannelId = this.options.videoChannelId
|
||||
}
|
||||
}
|
||||
|
||||
if (this.options.channelNameOneOf && this.options.channelNameOneOf.length !== 0) {
|
||||
this.buildChannelJoin()
|
||||
|
||||
where.push('"VideoChannel->Actor"."preferredUsername" IN (:channelNameOneOf)')
|
||||
this.replacements.channelNameOneOf = this.options.channelNameOneOf
|
||||
}
|
||||
|
||||
if (this.options.type) {
|
||||
where.push('"VideoPlaylistModel"."type" = :type')
|
||||
|
||||
this.replacements.type = this.options.type
|
||||
}
|
||||
|
||||
if (this.options.uuids) {
|
||||
where.push('"VideoPlaylistModel"."uuid" IN (:uuids)')
|
||||
|
||||
this.replacements.uuids = this.options.uuids
|
||||
}
|
||||
|
||||
if (this.options.withVideos === true) {
|
||||
where.push(`(${this.getTotalVideosQuery()}) != 0`)
|
||||
}
|
||||
|
||||
if (this.options.search) {
|
||||
const escapedSearch = this.sequelize.escape(this.options.search)
|
||||
const escapedLikeSearch = this.sequelize.escape('%' + this.options.search + '%')
|
||||
|
||||
this.subQueryAttributes.push(
|
||||
`word_similarity(lower(immutable_unaccent(${escapedSearch})), lower(immutable_unaccent("VideoPlaylistModel"."name"))) as similarity`
|
||||
)
|
||||
|
||||
where.push(
|
||||
`(` +
|
||||
`lower(immutable_unaccent(${escapedSearch})) <% lower(immutable_unaccent("VideoPlaylistModel"."name")) OR ` +
|
||||
`lower(immutable_unaccent("VideoPlaylistModel"."name")) LIKE lower(immutable_unaccent(${escapedLikeSearch}))` +
|
||||
`)`
|
||||
)
|
||||
} else {
|
||||
this.subQueryAttributes.push('0 as similarity')
|
||||
}
|
||||
|
||||
if (where.length !== 0) {
|
||||
this.subQueryWhere = `WHERE ${where.join(' AND ')}`
|
||||
}
|
||||
}
|
||||
|
||||
private buildAccountJoin () {
|
||||
if (this.builtAccountJoin) return
|
||||
|
||||
this.subQueryJoin += ' INNER JOIN "account" "OwnerAccount" ON "OwnerAccount"."id" = "VideoPlaylistModel"."ownerAccountId" ' +
|
||||
'INNER JOIN "actor" "OwnerAccount->Actor" ON "OwnerAccount->Actor"."accountId" = "OwnerAccount"."id" ' +
|
||||
'LEFT JOIN "server" "OwnerAccount->Actor->Server" ON "OwnerAccount->Actor"."serverId" = "OwnerAccount->Actor->Server"."id" '
|
||||
|
||||
this.builtAccountJoin = true
|
||||
}
|
||||
|
||||
private buildChannelJoin () {
|
||||
if (this.builtVideoChannelJoin) return
|
||||
|
||||
this.subQueryJoin += ' LEFT JOIN "videoChannel" "VideoChannel" ON "VideoPlaylistModel"."videoChannelId" = "VideoChannel"."id" ' +
|
||||
'LEFT JOIN "actor" "VideoChannel->Actor" ON "VideoChannel->Actor"."videoChannelId" = "VideoChannel"."id" ' +
|
||||
'LEFT JOIN "server" "VideoChannel->Actor->Server" ON "VideoChannel->Actor"."serverId" = "VideoChannel->Actor->Server"."id" '
|
||||
|
||||
this.builtVideoChannelJoin = true
|
||||
}
|
||||
|
||||
private buildChannelCollaboratorsJoin () {
|
||||
if (this.builtChannelCollaboratorsJoin) return
|
||||
|
||||
this.buildChannelJoin()
|
||||
|
||||
this.subQueryJoin += ' LEFT JOIN "videoChannelCollaborator" "VideoChannel->VideoChannelCollaborators" ' +
|
||||
'ON "VideoChannel->VideoChannelCollaborators"."channelId" = "VideoChannel"."id" ' +
|
||||
'AND "VideoChannel->VideoChannelCollaborators"."state" = :channelCollaboratorState ' +
|
||||
// Ensure we join with max 1 collaborator to not duplicate rows
|
||||
'AND "VideoChannel->VideoChannelCollaborators"."accountId" = :accountId '
|
||||
|
||||
this.replacements.channelCollaboratorState = VideoChannelCollaboratorState.ACCEPTED
|
||||
this.replacements.accountId = this.options.accountId
|
||||
|
||||
this.builtChannelCollaboratorsJoin = true
|
||||
}
|
||||
|
||||
private buildAccountAvatarsJoin () {
|
||||
if (this.builtAccountAvatarJoin) return
|
||||
|
||||
this.join += `LEFT JOIN "actorImage" "OwnerAccount->Actor->Avatars" ` +
|
||||
`ON "OwnerAccount->Actor->Avatars"."actorId" = "VideoPlaylistModel"."OwnerAccount.Actor.id" ` +
|
||||
`AND "OwnerAccount->Actor->Avatars"."type" = ${ActorImageType.AVATAR} `
|
||||
|
||||
this.builtAccountAvatarJoin = true
|
||||
}
|
||||
|
||||
private buildChannelAvatarsJoin () {
|
||||
if (this.builtChannelAvatarJoin) return
|
||||
|
||||
this.join += `LEFT JOIN "actorImage" "VideoChannel->Actor->Avatars" ` +
|
||||
`ON "VideoChannel->Actor->Avatars"."actorId" = "VideoPlaylistModel"."VideoChannel.Actor.id" ` +
|
||||
`AND "VideoChannel->Actor->Avatars"."type" = ${ActorImageType.AVATAR} `
|
||||
|
||||
this.builtChannelAvatarJoin = true
|
||||
}
|
||||
|
||||
private buildThumbnailJoin () {
|
||||
if (this.builtThumbnailJoin) return
|
||||
|
||||
this.join += ' LEFT JOIN "thumbnail" "Thumbnail" ON "Thumbnail"."videoPlaylistId" = "VideoPlaylistModel"."id" '
|
||||
|
||||
this.builtThumbnailJoin = true
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
protected buildQueryJoin () {
|
||||
this.buildChannelAvatarsJoin()
|
||||
this.buildAccountAvatarsJoin()
|
||||
this.buildThumbnailJoin()
|
||||
}
|
||||
|
||||
protected buildQueryAttributes () {
|
||||
this.attributes = [
|
||||
...this.attributes,
|
||||
|
||||
this.tableAttributes.getAccountAvatarAttributes(),
|
||||
this.tableAttributes.getChannelAvatarAttributes(),
|
||||
this.tableAttributes.getThumbnailAttributes()
|
||||
]
|
||||
}
|
||||
|
||||
protected buildSubQueryJoin () {
|
||||
this.buildAccountJoin()
|
||||
this.buildChannelJoin()
|
||||
}
|
||||
|
||||
protected buildSubQueryAttributes () {
|
||||
this.subQueryAttributes = [
|
||||
...this.subQueryAttributes,
|
||||
|
||||
this.tableAttributes.getVideoPlaylistAttributes(),
|
||||
|
||||
this.tableAttributes.getChannelAttributes(),
|
||||
this.tableAttributes.getChannelActorAttributes(),
|
||||
this.tableAttributes.getChannelServerAttributes(),
|
||||
|
||||
this.tableAttributes.getAccountAttributes(),
|
||||
this.tableAttributes.getAccountActorAttributes(),
|
||||
this.tableAttributes.getAccountServerAttributes(),
|
||||
|
||||
this.getTotalVideosAttribute()
|
||||
]
|
||||
}
|
||||
|
||||
private getTotalVideosQuery () {
|
||||
return `SELECT COUNT("id") FROM "videoPlaylistElement" WHERE "videoPlaylistId" = "VideoPlaylistModel"."id"`
|
||||
}
|
||||
|
||||
private getTotalVideosAttribute () {
|
||||
return `(${this.getTotalVideosQuery()}) AS "videosLength"`
|
||||
}
|
||||
|
||||
protected getSort (sort: string) {
|
||||
return getPlaylistSort(sort)
|
||||
}
|
||||
|
||||
protected getCalculatedAttributes () {
|
||||
return [ 'similarity', 'videosLength' ]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { Memoize } from '@server/helpers/memoize.js'
|
||||
import { AccountModel } from '@server/models/account/account.js'
|
||||
import { ActorImageModel } from '@server/models/actor/actor-image.js'
|
||||
import { ActorModel } from '@server/models/actor/actor.js'
|
||||
import { ServerModel } from '@server/models/server/server.js'
|
||||
import { VideoChannelModel } from '../../video-channel.js'
|
||||
import { VideoPlaylistModel } from '../../video-playlist.js'
|
||||
import { ThumbnailModel } from '../../thumbnail.js'
|
||||
|
||||
export class VideoPlaylistTableAttributes {
|
||||
@Memoize()
|
||||
getVideoPlaylistAttributes () {
|
||||
return VideoPlaylistModel.getSQLAttributes('VideoPlaylistModel').join(', ')
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@Memoize()
|
||||
getChannelAttributes () {
|
||||
return VideoChannelModel.getSQLSummaryAttributes('VideoChannel', 'VideoChannel.').join(', ')
|
||||
}
|
||||
|
||||
@Memoize()
|
||||
getChannelActorAttributes () {
|
||||
return ActorModel.getSQLSummaryAttributes('VideoChannel->Actor', `VideoChannel.Actor.`).join(', ')
|
||||
}
|
||||
|
||||
@Memoize()
|
||||
getChannelServerAttributes () {
|
||||
return ServerModel.getSQLSummaryAttributes('VideoChannel->Actor->Server', `VideoChannel.Actor.Server.`).join(', ')
|
||||
}
|
||||
|
||||
@Memoize()
|
||||
getChannelAvatarAttributes () {
|
||||
return ActorImageModel.getSQLAttributes('VideoChannel->Actor->Avatars', 'VideoChannel.Actor.Avatars.').join(', ')
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@Memoize()
|
||||
getAccountAttributes () {
|
||||
return AccountModel.getSQLSummaryAttributes('OwnerAccount', 'OwnerAccount.').join(', ')
|
||||
}
|
||||
|
||||
@Memoize()
|
||||
getAccountActorAttributes () {
|
||||
return ActorModel.getSQLSummaryAttributes('OwnerAccount->Actor', `OwnerAccount.Actor.`).join(', ')
|
||||
}
|
||||
|
||||
@Memoize()
|
||||
getAccountServerAttributes () {
|
||||
return ServerModel.getSQLSummaryAttributes('OwnerAccount->Actor->Server', `OwnerAccount.Actor.Server.`).join(', ')
|
||||
}
|
||||
|
||||
@Memoize()
|
||||
getAccountAvatarAttributes () {
|
||||
return ActorImageModel.getSQLAttributes('OwnerAccount->Actor->Avatars', 'OwnerAccount.Actor.Avatars.').join(', ')
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@Memoize()
|
||||
getThumbnailAttributes () {
|
||||
return ThumbnailModel.getSQLAttributes('Thumbnail', 'Thumbnail.').join(', ')
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import { VideoChannelCollaboratorState } from '@peertube/peertube-models'
|
||||
import { AbstractListQuery, AbstractListQueryOptions } from '@server/models/shared/abstract-list-query.js'
|
||||
import { getChannelSyncSort } from '@server/models/shared/index.js'
|
||||
import { OrderItem, Sequelize } from 'sequelize'
|
||||
import { VideoChannelSyncTableAttributes } from './video-channel-sync-table-attributes.js'
|
||||
import { getAvatarsJoin, getChannelJoin } from '@server/models/shared/sql/actor-helpers.js'
|
||||
|
||||
export interface ListVideoChannelSyncsOptions extends AbstractListQueryOptions {
|
||||
accountId: number
|
||||
|
||||
includeCollaborations?: boolean
|
||||
}
|
||||
|
||||
export class VideoChannelSyncListQueryBuilder extends AbstractListQuery {
|
||||
private readonly tableAttributes = new VideoChannelSyncTableAttributes()
|
||||
|
||||
private builtChannelJoin = false
|
||||
private builtChannelAvatarsJoin = false
|
||||
private builtChannelCollaboratorsJoin = false
|
||||
|
||||
constructor (
|
||||
protected readonly sequelize: Sequelize,
|
||||
protected readonly options: ListVideoChannelSyncsOptions
|
||||
) {
|
||||
super(sequelize, { modelName: 'VideoChannelSyncModel', tableName: 'videoChannelSync' }, options)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
protected buildSubQueryWhere () {
|
||||
const where: string[] = []
|
||||
|
||||
this.buildChannelJoin()
|
||||
|
||||
if (this.options.includeCollaborations) {
|
||||
this.buildChannelCollaboratorsJoin()
|
||||
|
||||
where.push(
|
||||
`("VideoChannel"."accountId" = :accountId OR "VideoChannel->VideoChannelCollaborators"."accountId" = :accountId)`
|
||||
)
|
||||
|
||||
this.replacements.accountId = this.options.accountId
|
||||
} else {
|
||||
where.push(`"VideoChannel"."accountId" = :accountId`)
|
||||
|
||||
this.replacements.accountId = this.options.accountId
|
||||
}
|
||||
|
||||
if (where.length !== 0) {
|
||||
this.subQueryWhere = `WHERE ${where.join(' AND ')}`
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
private buildChannelJoin () {
|
||||
if (this.builtChannelJoin) return
|
||||
|
||||
this.subQueryJoin += getChannelJoin({
|
||||
on: `"VideoChannelSyncModel"."videoChannelId"`,
|
||||
includeAccount: false,
|
||||
includeAvatars: false,
|
||||
includeActors: true,
|
||||
required: true
|
||||
})
|
||||
this.builtChannelJoin = true
|
||||
}
|
||||
|
||||
private buildChannelCollaboratorsJoin () {
|
||||
if (this.builtChannelCollaboratorsJoin) return
|
||||
|
||||
this.subQueryJoin += ' LEFT JOIN "videoChannelCollaborator" "VideoChannel->VideoChannelCollaborators" ' +
|
||||
'ON "VideoChannel->VideoChannelCollaborators"."channelId" = "VideoChannel"."id" ' +
|
||||
'AND "VideoChannel->VideoChannelCollaborators"."state" = :channelCollaboratorState ' +
|
||||
// Ensure we join with max 1 collaborator to not duplicate rows
|
||||
'AND "VideoChannel->VideoChannelCollaborators"."accountId" = :accountId '
|
||||
|
||||
this.replacements.channelCollaboratorState = VideoChannelCollaboratorState.ACCEPTED
|
||||
this.replacements.accountId = this.options.accountId
|
||||
|
||||
this.builtChannelCollaboratorsJoin = true
|
||||
}
|
||||
|
||||
private buildChannelAvatarsJoin () {
|
||||
if (this.builtChannelAvatarsJoin) return
|
||||
|
||||
this.join += getAvatarsJoin({ base: 'VideoChannel->Actor->', on: `"VideoChannelSyncModel"."VideoChannel.Actor.id"` })
|
||||
|
||||
this.builtChannelAvatarsJoin = true
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
protected buildQueryJoin () {
|
||||
this.buildChannelAvatarsJoin()
|
||||
}
|
||||
|
||||
protected buildQueryAttributes () {
|
||||
this.attributes = [
|
||||
...this.attributes,
|
||||
|
||||
this.tableAttributes.getChannelAvatarAttributes()
|
||||
]
|
||||
}
|
||||
|
||||
protected buildSubQueryJoin () {
|
||||
this.buildChannelJoin()
|
||||
}
|
||||
|
||||
protected buildSubQueryAttributes () {
|
||||
this.subQueryAttributes = [
|
||||
...this.subQueryAttributes,
|
||||
|
||||
this.tableAttributes.getVideoChannelSyncAttributes(),
|
||||
|
||||
this.tableAttributes.getChannelAttributes(),
|
||||
this.tableAttributes.getChannelActorAttributes(),
|
||||
this.tableAttributes.getChannelServerAttributes()
|
||||
]
|
||||
}
|
||||
|
||||
protected getSort (sort: string): OrderItem[] {
|
||||
return getChannelSyncSort(sort)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { Memoize } from '@server/helpers/memoize.js'
|
||||
import { ActorImageModel } from '@server/models/actor/actor-image.js'
|
||||
import { ActorModel } from '@server/models/actor/actor.js'
|
||||
import { ServerModel } from '@server/models/server/server.js'
|
||||
import { VideoChannelSyncModel } from '../../video-channel-sync.js'
|
||||
import { VideoChannelModel } from '../../video-channel.js'
|
||||
|
||||
export class VideoChannelSyncTableAttributes {
|
||||
@Memoize()
|
||||
getVideoChannelSyncAttributes () {
|
||||
return VideoChannelSyncModel.getSQLAttributes('VideoChannelSyncModel').join(', ')
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@Memoize()
|
||||
getChannelAttributes () {
|
||||
return VideoChannelModel.getSQLSummaryAttributes('VideoChannel', `VideoChannel.`).join(', ')
|
||||
}
|
||||
|
||||
@Memoize()
|
||||
getChannelActorAttributes () {
|
||||
return ActorModel.getSQLAPIAttributes('VideoChannel->Actor', `VideoChannel.Actor.`).join(', ')
|
||||
}
|
||||
|
||||
@Memoize()
|
||||
getChannelServerAttributes () {
|
||||
return ServerModel.getSQLSummaryAttributes('VideoChannel->Actor->Server', `VideoChannel.Actor.Server.`).join(', ')
|
||||
}
|
||||
|
||||
@Memoize()
|
||||
getChannelAvatarAttributes () {
|
||||
return ActorImageModel.getSQLAttributes('VideoChannel->Actor->Avatars', 'VideoChannel.Actor.Avatars.').join(', ')
|
||||
}
|
||||
}
|
||||
3
server/core/models/video/sql/video/index.ts
Normal file
3
server/core/models/video/sql/video/index.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export * from './video-model-get-query-builder.js'
|
||||
export * from './videos-id-list-query-builder.js'
|
||||
export * from './videos-model-list-query-builder.js'
|
||||
@@ -0,0 +1,380 @@
|
||||
import { ActorImageType } from '@peertube/peertube-models'
|
||||
import { MUserAccountId } from '@server/types/models/index.js'
|
||||
import { Sequelize } from 'sequelize'
|
||||
import validator from 'validator'
|
||||
import { AbstractRunQuery } from '../../../../shared/abstract-run-query.js'
|
||||
import { createSafeIn } from '../../../../shared/index.js'
|
||||
import { VideoTableAttributes } from './video-table-attributes.js'
|
||||
|
||||
/**
|
||||
* Abstract builder to create SQL query and fetch video models
|
||||
*/
|
||||
|
||||
export class AbstractVideoQueryBuilder extends AbstractRunQuery {
|
||||
protected attributes: { [key: string]: string } = {}
|
||||
|
||||
protected joins = ''
|
||||
protected where: string
|
||||
|
||||
protected tables: VideoTableAttributes
|
||||
|
||||
constructor (
|
||||
protected readonly sequelize: Sequelize,
|
||||
protected readonly mode: 'list' | 'get'
|
||||
) {
|
||||
super(sequelize)
|
||||
|
||||
this.tables = new VideoTableAttributes(this.mode)
|
||||
}
|
||||
|
||||
protected buildSelect () {
|
||||
return 'SELECT ' + Object.keys(this.attributes).map(key => {
|
||||
const value = this.attributes[key]
|
||||
if (value) return `${key} AS ${value}`
|
||||
|
||||
return key
|
||||
}).join(', ')
|
||||
}
|
||||
|
||||
protected includeChannels () {
|
||||
this.addJoin('INNER JOIN "videoChannel" AS "VideoChannel" ON "video"."channelId" = "VideoChannel"."id"')
|
||||
this.addJoin('INNER JOIN "actor" AS "VideoChannel->Actor" ON "VideoChannel"."id" = "VideoChannel->Actor"."videoChannelId"')
|
||||
|
||||
this.addJoin(
|
||||
'LEFT OUTER JOIN "server" AS "VideoChannel->Actor->Server" ON "VideoChannel->Actor"."serverId" = "VideoChannel->Actor->Server"."id"'
|
||||
)
|
||||
|
||||
this.addJoin(
|
||||
'LEFT OUTER JOIN "actorImage" AS "VideoChannel->Actor->Avatars" ' +
|
||||
'ON "VideoChannel->Actor"."id" = "VideoChannel->Actor->Avatars"."actorId" ' +
|
||||
`AND "VideoChannel->Actor->Avatars"."type" = ${ActorImageType.AVATAR}`
|
||||
)
|
||||
|
||||
this.attributes = {
|
||||
...this.attributes,
|
||||
|
||||
...this.buildAttributesObject('VideoChannel', this.tables.getChannelAttributes()),
|
||||
...this.buildActorInclude('VideoChannel->Actor'),
|
||||
...this.buildAvatarInclude('VideoChannel->Actor->Avatars'),
|
||||
...this.buildServerInclude('VideoChannel->Actor->Server')
|
||||
}
|
||||
}
|
||||
|
||||
protected includeAccounts () {
|
||||
this.addJoin('INNER JOIN "account" AS "VideoChannel->Account" ON "VideoChannel"."accountId" = "VideoChannel->Account"."id"')
|
||||
this.addJoin(
|
||||
'INNER JOIN "actor" AS "VideoChannel->Account->Actor" ON "VideoChannel->Account"."id" = "VideoChannel->Account->Actor"."accountId"'
|
||||
)
|
||||
|
||||
this.addJoin(
|
||||
'LEFT OUTER JOIN "server" AS "VideoChannel->Account->Actor->Server" ' +
|
||||
'ON "VideoChannel->Account->Actor"."serverId" = "VideoChannel->Account->Actor->Server"."id"'
|
||||
)
|
||||
|
||||
this.addJoin(
|
||||
'LEFT OUTER JOIN "actorImage" AS "VideoChannel->Account->Actor->Avatars" ' +
|
||||
'ON "VideoChannel->Account->Actor"."id" = "VideoChannel->Account->Actor->Avatars"."actorId" ' +
|
||||
`AND "VideoChannel->Account->Actor->Avatars"."type" = ${ActorImageType.AVATAR}`
|
||||
)
|
||||
|
||||
this.attributes = {
|
||||
...this.attributes,
|
||||
|
||||
...this.buildAttributesObject('VideoChannel->Account', this.tables.getAccountAttributes()),
|
||||
...this.buildActorInclude('VideoChannel->Account->Actor'),
|
||||
...this.buildAvatarInclude('VideoChannel->Account->Actor->Avatars'),
|
||||
...this.buildServerInclude('VideoChannel->Account->Actor->Server')
|
||||
}
|
||||
}
|
||||
|
||||
protected includeOwnerUser () {
|
||||
this.addJoin('INNER JOIN "videoChannel" AS "VideoChannel" ON "video"."channelId" = "VideoChannel"."id"')
|
||||
this.addJoin('INNER JOIN "account" AS "VideoChannel->Account" ON "VideoChannel"."accountId" = "VideoChannel->Account"."id"')
|
||||
|
||||
this.attributes = {
|
||||
...this.attributes,
|
||||
|
||||
...this.buildAttributesObject('VideoChannel', this.tables.getChannelAttributes()),
|
||||
...this.buildAttributesObject('VideoChannel->Account', this.tables.getUserAccountAttributes())
|
||||
}
|
||||
}
|
||||
|
||||
protected includeThumbnails () {
|
||||
this.addJoin('LEFT OUTER JOIN "thumbnail" AS "Thumbnails" ON "video"."id" = "Thumbnails"."videoId"')
|
||||
|
||||
this.attributes = {
|
||||
...this.attributes,
|
||||
|
||||
...this.buildAttributesObject('Thumbnails', this.tables.getThumbnailAttributes())
|
||||
}
|
||||
}
|
||||
|
||||
protected includeWebVideoFiles () {
|
||||
this.addJoin('LEFT JOIN "videoFile" AS "VideoFiles" ON "VideoFiles"."videoId" = "video"."id"')
|
||||
|
||||
this.attributes = {
|
||||
...this.attributes,
|
||||
|
||||
...this.buildAttributesObject('VideoFiles', this.tables.getFileAttributes())
|
||||
}
|
||||
}
|
||||
|
||||
protected includeStreamingPlaylistFiles () {
|
||||
this.addJoin(
|
||||
'LEFT JOIN "videoStreamingPlaylist" AS "VideoStreamingPlaylists" ON "VideoStreamingPlaylists"."videoId" = "video"."id"'
|
||||
)
|
||||
|
||||
this.addJoin(
|
||||
'LEFT JOIN "videoFile" AS "VideoStreamingPlaylists->VideoFiles" ' +
|
||||
'ON "VideoStreamingPlaylists->VideoFiles"."videoStreamingPlaylistId" = "VideoStreamingPlaylists"."id"'
|
||||
)
|
||||
|
||||
this.attributes = {
|
||||
...this.attributes,
|
||||
|
||||
...this.buildAttributesObject('VideoStreamingPlaylists', this.tables.getStreamingPlaylistAttributes()),
|
||||
...this.buildAttributesObject('VideoStreamingPlaylists->VideoFiles', this.tables.getFileAttributes())
|
||||
}
|
||||
}
|
||||
|
||||
protected includeUserHistory (userId: number) {
|
||||
this.addJoin(
|
||||
'LEFT OUTER JOIN "userVideoHistory" ' +
|
||||
'ON "video"."id" = "userVideoHistory"."videoId" AND "userVideoHistory"."userId" = :userVideoHistoryId'
|
||||
)
|
||||
|
||||
this.replacements.userVideoHistoryId = userId
|
||||
|
||||
this.attributes = {
|
||||
...this.attributes,
|
||||
|
||||
...this.buildAttributesObject('userVideoHistory', this.tables.getUserHistoryAttributes())
|
||||
}
|
||||
}
|
||||
|
||||
protected includePlaylist (playlistId: number) {
|
||||
this.addJoin(
|
||||
'INNER JOIN "videoPlaylistElement" as "VideoPlaylistElement" ON "videoPlaylistElement"."videoId" = "video"."id" ' +
|
||||
'AND "VideoPlaylistElement"."videoPlaylistId" = :videoPlaylistId'
|
||||
)
|
||||
|
||||
this.replacements.videoPlaylistId = playlistId
|
||||
|
||||
this.attributes = {
|
||||
...this.attributes,
|
||||
|
||||
...this.buildAttributesObject('VideoPlaylistElement', this.tables.getPlaylistAttributes())
|
||||
}
|
||||
}
|
||||
|
||||
protected includeTags () {
|
||||
this.addJoin(
|
||||
'LEFT OUTER JOIN (' +
|
||||
'"videoTag" AS "Tags->VideoTagModel" INNER JOIN "tag" AS "Tags" ON "Tags"."id" = "Tags->VideoTagModel"."tagId"' +
|
||||
') ' +
|
||||
'ON "video"."id" = "Tags->VideoTagModel"."videoId"'
|
||||
)
|
||||
|
||||
this.attributes = {
|
||||
...this.attributes,
|
||||
|
||||
...this.buildAttributesObject('Tags', this.tables.getTagAttributes()),
|
||||
...this.buildAttributesObject('Tags->VideoTagModel', this.tables.getVideoTagAttributes())
|
||||
}
|
||||
}
|
||||
|
||||
protected includeBlacklisted () {
|
||||
this.addJoin(
|
||||
'LEFT OUTER JOIN "videoBlacklist" AS "VideoBlacklist" ON "video"."id" = "VideoBlacklist"."videoId"'
|
||||
)
|
||||
|
||||
this.attributes = {
|
||||
...this.attributes,
|
||||
|
||||
...this.buildAttributesObject('VideoBlacklist', this.tables.getBlacklistedAttributes())
|
||||
}
|
||||
}
|
||||
|
||||
protected includeBlockedOwnerAndServer (serverAccountId: number, user?: MUserAccountId) {
|
||||
const blockerIds = [ serverAccountId ]
|
||||
if (user) blockerIds.push(user.Account.id)
|
||||
|
||||
const inClause = createSafeIn(this.sequelize, blockerIds)
|
||||
|
||||
this.addJoin(
|
||||
'LEFT JOIN "accountBlocklist" AS "VideoChannel->Account->AccountBlocklist" ' +
|
||||
'ON "VideoChannel->Account"."id" = "VideoChannel->Account->AccountBlocklist"."targetAccountId" ' +
|
||||
'AND "VideoChannel->Account->AccountBlocklist"."accountId" IN (' + inClause + ')'
|
||||
)
|
||||
|
||||
this.addJoin(
|
||||
'LEFT JOIN "serverBlocklist" AS "VideoChannel->Account->Actor->Server->ServerBlocklist" ' +
|
||||
'ON "VideoChannel->Account->Actor->Server->ServerBlocklist"."targetServerId" = "VideoChannel->Account->Actor"."serverId" ' +
|
||||
'AND "VideoChannel->Account->Actor->Server->ServerBlocklist"."accountId" IN (' + inClause + ') '
|
||||
)
|
||||
|
||||
this.attributes = {
|
||||
...this.attributes,
|
||||
|
||||
...this.buildAttributesObject('VideoChannel->Account->AccountBlocklist', this.tables.getBlocklistAttributes()),
|
||||
...this.buildAttributesObject('VideoChannel->Account->Actor->Server->ServerBlocklist', this.tables.getBlocklistAttributes())
|
||||
}
|
||||
}
|
||||
|
||||
protected includeScheduleUpdate () {
|
||||
this.addJoin(
|
||||
'LEFT OUTER JOIN "scheduleVideoUpdate" AS "ScheduleVideoUpdate" ON "video"."id" = "ScheduleVideoUpdate"."videoId"'
|
||||
)
|
||||
|
||||
this.attributes = {
|
||||
...this.attributes,
|
||||
|
||||
...this.buildAttributesObject('ScheduleVideoUpdate', this.tables.getScheduleUpdateAttributes())
|
||||
}
|
||||
}
|
||||
|
||||
protected includeLive () {
|
||||
this.addJoin(
|
||||
'LEFT OUTER JOIN "videoLive" AS "VideoLive" ON "video"."id" = "VideoLive"."videoId"'
|
||||
)
|
||||
|
||||
this.attributes = {
|
||||
...this.attributes,
|
||||
|
||||
...this.buildAttributesObject('VideoLive', this.tables.getLiveAttributes())
|
||||
}
|
||||
}
|
||||
|
||||
protected includeLiveSchedules () {
|
||||
this.addJoin(
|
||||
'LEFT OUTER JOIN "videoLiveSchedule" AS "VideoLive->VideoLiveSchedules" ' +
|
||||
'ON "VideoLive->VideoLiveSchedules"."liveVideoId" = "VideoLive"."id"'
|
||||
)
|
||||
|
||||
this.attributes = {
|
||||
...this.attributes,
|
||||
|
||||
...this.buildAttributesObject('VideoLive->VideoLiveSchedules', this.tables.getLiveScheduleAttributes())
|
||||
}
|
||||
}
|
||||
|
||||
protected includeVideoSource () {
|
||||
this.addJoin(
|
||||
'LEFT OUTER JOIN "videoSource" AS "VideoSource" ON "video"."id" = "VideoSource"."videoId"'
|
||||
)
|
||||
|
||||
this.attributes = {
|
||||
...this.attributes,
|
||||
|
||||
...this.buildAttributesObject('VideoSource', this.tables.getVideoSourceAttributes())
|
||||
}
|
||||
}
|
||||
|
||||
protected includeAutomaticTags (autoTagOfAccountId: number) {
|
||||
this.addJoin(
|
||||
'LEFT JOIN (' +
|
||||
'"videoAutomaticTag" AS "VideoAutomaticTags" INNER JOIN "automaticTag" AS "VideoAutomaticTags->AutomaticTag" ' +
|
||||
'ON "VideoAutomaticTags->AutomaticTag"."id" = "VideoAutomaticTags"."automaticTagId" ' +
|
||||
') ON "video"."id" = "VideoAutomaticTags"."videoId" AND "VideoAutomaticTags"."accountId" = :autoTagOfAccountId'
|
||||
)
|
||||
|
||||
this.replacements.autoTagOfAccountId = autoTagOfAccountId
|
||||
|
||||
this.attributes = {
|
||||
...this.attributes,
|
||||
|
||||
...this.buildAttributesObject('VideoAutomaticTags', this.tables.getVideoAutoTagAttributes()),
|
||||
...this.buildAttributesObject('VideoAutomaticTags->AutomaticTag', this.tables.getAutoTagAttributes())
|
||||
}
|
||||
}
|
||||
|
||||
protected includeTrackers () {
|
||||
this.addJoin(
|
||||
'LEFT OUTER JOIN (' +
|
||||
'"videoTracker" AS "Trackers->VideoTrackerModel" ' +
|
||||
'INNER JOIN "tracker" AS "Trackers" ON "Trackers"."id" = "Trackers->VideoTrackerModel"."trackerId"' +
|
||||
') ON "video"."id" = "Trackers->VideoTrackerModel"."videoId"'
|
||||
)
|
||||
|
||||
this.attributes = {
|
||||
...this.attributes,
|
||||
|
||||
...this.buildAttributesObject('Trackers', this.tables.getTrackerAttributes()),
|
||||
...this.buildAttributesObject('Trackers->VideoTrackerModel', this.tables.getVideoTrackerAttributes())
|
||||
}
|
||||
}
|
||||
|
||||
protected includeStreamingPlaylistRedundancies () {
|
||||
this.addJoin(
|
||||
'LEFT OUTER JOIN "videoRedundancy" AS "VideoStreamingPlaylists->RedundancyVideos" ' +
|
||||
'ON "VideoStreamingPlaylists"."id" = "VideoStreamingPlaylists->RedundancyVideos"."videoStreamingPlaylistId"'
|
||||
)
|
||||
|
||||
this.attributes = {
|
||||
...this.attributes,
|
||||
|
||||
...this.buildAttributesObject('VideoStreamingPlaylists->RedundancyVideos', this.tables.getRedundancyAttributes())
|
||||
}
|
||||
}
|
||||
|
||||
protected includeCaptions () {
|
||||
this.addJoin(
|
||||
'LEFT JOIN "videoCaption" AS "VideoCaptions" ON "video"."id" = "VideoCaptions"."videoId"'
|
||||
)
|
||||
|
||||
this.attributes = {
|
||||
...this.attributes,
|
||||
|
||||
...this.buildAttributesObject('VideoCaptions', this.tables.getCaptionAttributes())
|
||||
}
|
||||
}
|
||||
|
||||
protected buildActorInclude (prefixKey: string) {
|
||||
return this.buildAttributesObject(prefixKey, this.tables.getActorAttributes())
|
||||
}
|
||||
|
||||
protected buildAvatarInclude (prefixKey: string) {
|
||||
return this.buildAttributesObject(prefixKey, this.tables.getAvatarAttributes())
|
||||
}
|
||||
|
||||
protected buildServerInclude (prefixKey: string) {
|
||||
return this.buildAttributesObject(prefixKey, this.tables.getServerAttributes())
|
||||
}
|
||||
|
||||
protected buildAttributesObject (prefixKey: string, attributeKeys: string[]) {
|
||||
const result: { [id: string]: string } = {}
|
||||
|
||||
const prefixValue = prefixKey.replace(/->/g, '.')
|
||||
|
||||
for (const attribute of attributeKeys) {
|
||||
result[`"${prefixKey}"."${attribute}"`] = `"${prefixValue}.${attribute}"`
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
protected whereId (options: { ids?: number[], id?: string | number, url?: string }) {
|
||||
if (options.ids) {
|
||||
this.where = `WHERE "video"."id" IN (${createSafeIn(this.sequelize, options.ids)})`
|
||||
return
|
||||
}
|
||||
|
||||
if (options.url) {
|
||||
this.where = 'WHERE "video"."url" = :videoUrl'
|
||||
this.replacements.videoUrl = options.url
|
||||
return
|
||||
}
|
||||
|
||||
if (validator.default.isInt('' + options.id)) {
|
||||
this.where = 'WHERE "video".id = :videoId'
|
||||
} else {
|
||||
this.where = 'WHERE uuid = :videoId'
|
||||
}
|
||||
|
||||
this.replacements.videoId = options.id
|
||||
}
|
||||
|
||||
protected addJoin (join: string) {
|
||||
this.joins += join + ' '
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { Sequelize, Transaction } from 'sequelize'
|
||||
import { AbstractVideoQueryBuilder } from './abstract-video-query-builder.js'
|
||||
|
||||
export type FileQueryOptions = {
|
||||
id?: string | number
|
||||
url?: string
|
||||
|
||||
includeRedundancy: boolean
|
||||
|
||||
transaction?: Transaction
|
||||
|
||||
logging?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch files (web videos and streaming playlist) according to a video
|
||||
*/
|
||||
|
||||
export class VideoFileQueryBuilder extends AbstractVideoQueryBuilder {
|
||||
constructor (protected readonly sequelize: Sequelize) {
|
||||
super(sequelize, 'get')
|
||||
}
|
||||
|
||||
queryWebVideos (options: FileQueryOptions) {
|
||||
this.buildWebVideoFilesQuery(options)
|
||||
|
||||
return this.runQuery(options)
|
||||
}
|
||||
|
||||
queryStreamingPlaylistVideos (options: FileQueryOptions) {
|
||||
this.buildVideoStreamingPlaylistFilesQuery(options)
|
||||
|
||||
return this.runQuery(options)
|
||||
}
|
||||
|
||||
private buildWebVideoFilesQuery (options: FileQueryOptions) {
|
||||
this.attributes = {
|
||||
'"video"."id"': ''
|
||||
}
|
||||
|
||||
this.includeWebVideoFiles()
|
||||
|
||||
this.whereId(options)
|
||||
|
||||
this.query = this.buildQuery()
|
||||
}
|
||||
|
||||
private buildVideoStreamingPlaylistFilesQuery (options: FileQueryOptions) {
|
||||
this.attributes = {
|
||||
'"video"."id"': ''
|
||||
}
|
||||
|
||||
this.includeStreamingPlaylistFiles()
|
||||
|
||||
if (options.includeRedundancy) {
|
||||
this.includeStreamingPlaylistRedundancies()
|
||||
}
|
||||
|
||||
this.whereId(options)
|
||||
|
||||
this.query = this.buildQuery()
|
||||
}
|
||||
|
||||
private buildQuery () {
|
||||
return `${this.buildSelect()} FROM "video" ${this.joins} ${this.where}`
|
||||
}
|
||||
}
|
||||
500
server/core/models/video/sql/video/shared/video-model-builder.ts
Normal file
500
server/core/models/video/sql/video/shared/video-model-builder.ts
Normal file
@@ -0,0 +1,500 @@
|
||||
import { VideoInclude, VideoIncludeType } from '@peertube/peertube-models'
|
||||
import { AccountBlocklistModel } from '@server/models/account/account-blocklist.js'
|
||||
import { AccountModel } from '@server/models/account/account.js'
|
||||
import { ActorImageModel } from '@server/models/actor/actor-image.js'
|
||||
import { ActorModel } from '@server/models/actor/actor.js'
|
||||
import { AutomaticTagModel } from '@server/models/automatic-tag/automatic-tag.js'
|
||||
import { VideoAutomaticTagModel } from '@server/models/automatic-tag/video-automatic-tag.js'
|
||||
import { VideoRedundancyModel } from '@server/models/redundancy/video-redundancy.js'
|
||||
import { ServerBlocklistModel } from '@server/models/server/server-blocklist.js'
|
||||
import { ServerModel } from '@server/models/server/server.js'
|
||||
import { TrackerModel } from '@server/models/server/tracker.js'
|
||||
import { UserVideoHistoryModel } from '@server/models/user/user-video-history.js'
|
||||
import { VideoCaptionModel } from '@server/models/video/video-caption.js'
|
||||
import { VideoLiveScheduleModel } from '@server/models/video/video-live-schedule.js'
|
||||
import { VideoSourceModel } from '@server/models/video/video-source.js'
|
||||
import { ScheduleVideoUpdateModel } from '../../../schedule-video-update.js'
|
||||
import { TagModel } from '../../../tag.js'
|
||||
import { ThumbnailModel } from '../../../thumbnail.js'
|
||||
import { VideoBlacklistModel } from '../../../video-blacklist.js'
|
||||
import { VideoChannelModel } from '../../../video-channel.js'
|
||||
import { VideoFileModel } from '../../../video-file.js'
|
||||
import { VideoLiveModel } from '../../../video-live.js'
|
||||
import { VideoStreamingPlaylistModel } from '../../../video-streaming-playlist.js'
|
||||
import { VideoModel } from '../../../video.js'
|
||||
import { VideoTableAttributes } from './video-table-attributes.js'
|
||||
|
||||
type SQLRow = { [id: string]: string | number }
|
||||
|
||||
/**
|
||||
* Build video models from SQL rows
|
||||
*/
|
||||
|
||||
export class VideoModelBuilder {
|
||||
private videosMemo: { [id: number]: VideoModel }
|
||||
private videoStreamingPlaylistMemo: { [id: number]: VideoStreamingPlaylistModel }
|
||||
private videoFileMemo: { [id: number]: VideoFileModel }
|
||||
|
||||
private thumbnailsDone: Set<any>
|
||||
private actorImagesDone: Set<any>
|
||||
private historyDone: Set<any>
|
||||
private blacklistDone: Set<any>
|
||||
private accountBlocklistDone: Set<any>
|
||||
private serverBlocklistDone: Set<any>
|
||||
private liveDone: Set<any>
|
||||
private sourceDone: Set<any>
|
||||
private liveScheduleDone: Set<any>
|
||||
private redundancyDone: Set<any>
|
||||
private scheduleVideoUpdateDone: Set<any>
|
||||
|
||||
private trackersDone: Set<string>
|
||||
private tagsDone: Set<string>
|
||||
private autoTagsDone: Set<string>
|
||||
private captionsDone: Set<any>
|
||||
|
||||
private videos: VideoModel[]
|
||||
|
||||
private readonly buildOpts = { raw: true, isNewRecord: false }
|
||||
|
||||
constructor (
|
||||
private readonly mode: 'get' | 'list',
|
||||
private readonly tables: VideoTableAttributes
|
||||
) {
|
||||
}
|
||||
|
||||
buildVideosFromRows (options: {
|
||||
rows: SQLRow[]
|
||||
addCaptions: boolean
|
||||
include?: VideoIncludeType
|
||||
rowsWebVideoFiles?: SQLRow[]
|
||||
rowsStreamingPlaylist?: SQLRow[]
|
||||
}) {
|
||||
const { rows, rowsWebVideoFiles, rowsStreamingPlaylist, include, addCaptions } = options
|
||||
|
||||
this.reinit()
|
||||
|
||||
for (const row of rows) {
|
||||
this.buildVideoAndAccount(row, { addCaptions })
|
||||
|
||||
const videoModel = this.videosMemo[row.id as number]
|
||||
|
||||
this.setUserHistory(row, videoModel)
|
||||
this.addThumbnail(row, videoModel)
|
||||
this.setLive(row, videoModel)
|
||||
this.addLiveSchedule(row, videoModel)
|
||||
|
||||
const channelActor = videoModel.VideoChannel?.Actor
|
||||
if (channelActor) {
|
||||
this.addActorAvatar(row, 'VideoChannel.Actor', channelActor)
|
||||
}
|
||||
|
||||
const accountActor = videoModel.VideoChannel?.Account?.Actor
|
||||
if (accountActor) {
|
||||
this.addActorAvatar(row, 'VideoChannel.Account.Actor', accountActor)
|
||||
}
|
||||
|
||||
if (!rowsWebVideoFiles) {
|
||||
this.addWebVideoFile(row, videoModel)
|
||||
}
|
||||
|
||||
if (!rowsStreamingPlaylist) {
|
||||
this.addStreamingPlaylist(row, videoModel)
|
||||
this.addStreamingPlaylistFile(row)
|
||||
}
|
||||
|
||||
if (this.mode === 'get') {
|
||||
this.addTag(row, videoModel)
|
||||
this.addTracker(row, videoModel)
|
||||
this.addCaption(row, videoModel)
|
||||
this.setBlacklisted(row, videoModel)
|
||||
this.setScheduleVideoUpdate(row, videoModel)
|
||||
} else {
|
||||
if (include & VideoInclude.BLACKLISTED) {
|
||||
this.setBlacklisted(row, videoModel)
|
||||
}
|
||||
|
||||
if (include & VideoInclude.BLOCKED_OWNER) {
|
||||
this.setBlockedOwner(row, videoModel)
|
||||
this.setBlockedServer(row, videoModel)
|
||||
}
|
||||
|
||||
if (include & VideoInclude.NOT_PUBLISHED_STATE) {
|
||||
this.setScheduleVideoUpdate(row, videoModel)
|
||||
}
|
||||
|
||||
if (include & VideoInclude.SOURCE) {
|
||||
this.setSource(row, videoModel)
|
||||
}
|
||||
|
||||
if (include & VideoInclude.AUTOMATIC_TAGS) {
|
||||
this.addAutoTag(row, videoModel)
|
||||
}
|
||||
|
||||
if (include & VideoInclude.TAGS) {
|
||||
this.addTag(row, videoModel)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.grabSeparateWebVideoFiles(rowsWebVideoFiles)
|
||||
this.grabSeparateStreamingPlaylistFiles(rowsStreamingPlaylist)
|
||||
|
||||
return this.videos
|
||||
}
|
||||
|
||||
private reinit () {
|
||||
this.videosMemo = {}
|
||||
this.videoStreamingPlaylistMemo = {}
|
||||
this.videoFileMemo = {}
|
||||
|
||||
this.thumbnailsDone = new Set()
|
||||
this.actorImagesDone = new Set()
|
||||
this.historyDone = new Set()
|
||||
this.blacklistDone = new Set()
|
||||
this.liveDone = new Set()
|
||||
this.sourceDone = new Set()
|
||||
this.redundancyDone = new Set()
|
||||
this.scheduleVideoUpdateDone = new Set()
|
||||
this.liveScheduleDone = new Set()
|
||||
|
||||
this.accountBlocklistDone = new Set()
|
||||
this.serverBlocklistDone = new Set()
|
||||
|
||||
this.trackersDone = new Set()
|
||||
this.tagsDone = new Set()
|
||||
this.autoTagsDone = new Set()
|
||||
this.captionsDone = new Set()
|
||||
|
||||
this.videos = []
|
||||
}
|
||||
|
||||
private grabSeparateWebVideoFiles (rowsWebVideoFiles?: SQLRow[]) {
|
||||
if (!rowsWebVideoFiles) return
|
||||
|
||||
for (const row of rowsWebVideoFiles) {
|
||||
const id = row['VideoFiles.id']
|
||||
if (!id) continue
|
||||
|
||||
const videoModel = this.videosMemo[row.id]
|
||||
this.addWebVideoFile(row, videoModel)
|
||||
}
|
||||
}
|
||||
|
||||
private grabSeparateStreamingPlaylistFiles (rowsStreamingPlaylist?: SQLRow[]) {
|
||||
if (!rowsStreamingPlaylist) return
|
||||
|
||||
for (const row of rowsStreamingPlaylist) {
|
||||
const id = row['VideoStreamingPlaylists.id']
|
||||
if (!id) continue
|
||||
|
||||
const videoModel = this.videosMemo[row.id]
|
||||
|
||||
this.addStreamingPlaylist(row, videoModel)
|
||||
this.addStreamingPlaylistFile(row)
|
||||
this.addRedundancy(row, 'VideoStreamingPlaylists', this.videoStreamingPlaylistMemo[id])
|
||||
}
|
||||
}
|
||||
|
||||
private buildVideoAndAccount (row: SQLRow, options: {
|
||||
addCaptions: boolean
|
||||
}) {
|
||||
if (this.videosMemo[row.id]) return
|
||||
|
||||
const videoModel = new VideoModel(this.grab(row, this.tables.getVideoAttributes(), ''), this.buildOpts)
|
||||
|
||||
videoModel.UserVideoHistories = []
|
||||
videoModel.Thumbnails = []
|
||||
videoModel.VideoFiles = []
|
||||
videoModel.VideoStreamingPlaylists = []
|
||||
videoModel.Tags = []
|
||||
videoModel.VideoAutomaticTags = []
|
||||
videoModel.Trackers = []
|
||||
|
||||
if (options.addCaptions === true) {
|
||||
videoModel.VideoCaptions = []
|
||||
}
|
||||
|
||||
this.buildAccount(row, videoModel)
|
||||
|
||||
this.videosMemo[row.id] = videoModel
|
||||
|
||||
// Keep rows order
|
||||
this.videos.push(videoModel)
|
||||
}
|
||||
|
||||
private buildAccount (row: SQLRow, videoModel: VideoModel) {
|
||||
const id = row['VideoChannel.Account.id']
|
||||
if (!id) return
|
||||
|
||||
const channelModel = new VideoChannelModel(this.grab(row, this.tables.getChannelAttributes(), 'VideoChannel'), this.buildOpts)
|
||||
channelModel.Actor = this.buildActor(row, 'VideoChannel')
|
||||
|
||||
const accountModel = new AccountModel(this.grab(row, this.tables.getAccountAttributes(), 'VideoChannel.Account'), this.buildOpts)
|
||||
accountModel.Actor = this.buildActor(row, 'VideoChannel.Account')
|
||||
|
||||
accountModel.BlockedBy = []
|
||||
|
||||
channelModel.Account = accountModel
|
||||
|
||||
videoModel.VideoChannel = channelModel
|
||||
}
|
||||
|
||||
private buildActor (row: SQLRow, prefix: string) {
|
||||
const actorPrefix = `${prefix}.Actor`
|
||||
const serverPrefix = `${actorPrefix}.Server`
|
||||
|
||||
const serverModel = row[`${serverPrefix}.id`] !== null
|
||||
? new ServerModel(this.grab(row, this.tables.getServerAttributes(), serverPrefix), this.buildOpts)
|
||||
: null
|
||||
|
||||
if (serverModel) serverModel.BlockedBy = []
|
||||
|
||||
const actorModel = new ActorModel(this.grab(row, this.tables.getActorAttributes(), actorPrefix), this.buildOpts)
|
||||
actorModel.Server = serverModel
|
||||
actorModel.Avatars = []
|
||||
|
||||
return actorModel
|
||||
}
|
||||
|
||||
private setUserHistory (row: SQLRow, videoModel: VideoModel) {
|
||||
const id = row['userVideoHistory.id']
|
||||
if (!id || this.historyDone.has(id)) return
|
||||
|
||||
const attributes = this.grab(row, this.tables.getUserHistoryAttributes(), 'userVideoHistory')
|
||||
const historyModel = new UserVideoHistoryModel(attributes, this.buildOpts)
|
||||
videoModel.UserVideoHistories.push(historyModel)
|
||||
|
||||
this.historyDone.add(id)
|
||||
}
|
||||
|
||||
private addActorAvatar (row: SQLRow, actorPrefix: string, actor: ActorModel) {
|
||||
const avatarPrefix = `${actorPrefix}.Avatars`
|
||||
const id = row[`${avatarPrefix}.id`]
|
||||
const key = `${row.id}${id}`
|
||||
|
||||
if (!id || this.actorImagesDone.has(key)) return
|
||||
|
||||
const attributes = this.grab(row, this.tables.getAvatarAttributes(), avatarPrefix)
|
||||
const avatarModel = new ActorImageModel(attributes, this.buildOpts)
|
||||
actor.Avatars.push(avatarModel)
|
||||
|
||||
this.actorImagesDone.add(key)
|
||||
}
|
||||
|
||||
private addThumbnail (row: SQLRow, videoModel: VideoModel) {
|
||||
const id = row['Thumbnails.id']
|
||||
if (!id || this.thumbnailsDone.has(id)) return
|
||||
|
||||
const attributes = this.grab(row, this.tables.getThumbnailAttributes(), 'Thumbnails')
|
||||
const thumbnailModel = new ThumbnailModel(attributes, this.buildOpts)
|
||||
videoModel.Thumbnails.push(thumbnailModel)
|
||||
|
||||
this.thumbnailsDone.add(id)
|
||||
}
|
||||
|
||||
private addWebVideoFile (row: SQLRow, videoModel: VideoModel) {
|
||||
const id = row['VideoFiles.id']
|
||||
if (!id || this.videoFileMemo[id]) return
|
||||
|
||||
const attributes = this.grab(row, this.tables.getFileAttributes(), 'VideoFiles')
|
||||
const videoFileModel = new VideoFileModel(attributes, this.buildOpts)
|
||||
videoModel.VideoFiles.push(videoFileModel)
|
||||
|
||||
this.videoFileMemo[id] = videoFileModel
|
||||
}
|
||||
|
||||
private addStreamingPlaylist (row: SQLRow, videoModel: VideoModel) {
|
||||
const id = row['VideoStreamingPlaylists.id']
|
||||
if (!id || this.videoStreamingPlaylistMemo[id]) return
|
||||
|
||||
const attributes = this.grab(row, this.tables.getStreamingPlaylistAttributes(), 'VideoStreamingPlaylists')
|
||||
const streamingPlaylist = new VideoStreamingPlaylistModel(attributes, this.buildOpts)
|
||||
streamingPlaylist.VideoFiles = []
|
||||
|
||||
videoModel.VideoStreamingPlaylists.push(streamingPlaylist)
|
||||
|
||||
this.videoStreamingPlaylistMemo[id] = streamingPlaylist
|
||||
}
|
||||
|
||||
private addStreamingPlaylistFile (row: SQLRow) {
|
||||
const id = row['VideoStreamingPlaylists.VideoFiles.id']
|
||||
if (!id || this.videoFileMemo[id]) return
|
||||
|
||||
const streamingPlaylist = this.videoStreamingPlaylistMemo[row['VideoStreamingPlaylists.id']]
|
||||
|
||||
const attributes = this.grab(row, this.tables.getFileAttributes(), 'VideoStreamingPlaylists.VideoFiles')
|
||||
const videoFileModel = new VideoFileModel(attributes, this.buildOpts)
|
||||
streamingPlaylist.VideoFiles.push(videoFileModel)
|
||||
|
||||
this.videoFileMemo[id] = videoFileModel
|
||||
}
|
||||
|
||||
private addRedundancy (row: SQLRow, prefix: string, to: VideoStreamingPlaylistModel) {
|
||||
if (!to.RedundancyVideos) to.RedundancyVideos = []
|
||||
|
||||
const redundancyPrefix = `${prefix}.RedundancyVideos`
|
||||
const id = row[`${redundancyPrefix}.id`]
|
||||
|
||||
if (!id || this.redundancyDone.has(id)) return
|
||||
|
||||
const attributes = this.grab(row, this.tables.getRedundancyAttributes(), redundancyPrefix)
|
||||
const redundancyModel = new VideoRedundancyModel(attributes, this.buildOpts)
|
||||
to.RedundancyVideos.push(redundancyModel)
|
||||
|
||||
this.redundancyDone.add(id)
|
||||
}
|
||||
|
||||
private addTag (row: SQLRow, videoModel: VideoModel) {
|
||||
if (!row['Tags.name']) return
|
||||
|
||||
const key = `${row['Tags.VideoTagModel.videoId']}-${row['Tags.VideoTagModel.tagId']}`
|
||||
if (this.tagsDone.has(key)) return
|
||||
|
||||
const attributes = this.grab(row, this.tables.getTagAttributes(), 'Tags')
|
||||
const tagModel = new TagModel(attributes, this.buildOpts)
|
||||
videoModel.Tags.push(tagModel)
|
||||
|
||||
this.tagsDone.add(key)
|
||||
}
|
||||
|
||||
private addAutoTag (row: SQLRow, videoModel: VideoModel) {
|
||||
if (!row['VideoAutomaticTags.AutomaticTag.id']) return
|
||||
|
||||
const key = `${row['VideoAutomaticTags.videoId']}-${row['VideoAutomaticTags.accountId']}-${row['VideoAutomaticTags.automaticTagId']}`
|
||||
if (this.autoTagsDone.has(key)) return
|
||||
|
||||
const videoAutomaticTagAttributes = this.grab(row, this.tables.getVideoAutoTagAttributes(), 'VideoAutomaticTags')
|
||||
const automaticTagModel = new VideoAutomaticTagModel(videoAutomaticTagAttributes, this.buildOpts)
|
||||
|
||||
const automaticTagAttributes = this.grab(row, this.tables.getAutoTagAttributes(), 'VideoAutomaticTags.AutomaticTag')
|
||||
automaticTagModel.AutomaticTag = new AutomaticTagModel(automaticTagAttributes, this.buildOpts)
|
||||
|
||||
videoModel.VideoAutomaticTags.push(automaticTagModel)
|
||||
|
||||
this.autoTagsDone.add(key)
|
||||
}
|
||||
|
||||
private addTracker (row: SQLRow, videoModel: VideoModel) {
|
||||
if (!row['Trackers.id']) return
|
||||
|
||||
const key = `${row['Trackers.VideoTrackerModel.videoId']}-${row['Trackers.VideoTrackerModel.trackerId']}`
|
||||
if (this.trackersDone.has(key)) return
|
||||
|
||||
const attributes = this.grab(row, this.tables.getTrackerAttributes(), 'Trackers')
|
||||
const trackerModel = new TrackerModel(attributes, this.buildOpts)
|
||||
videoModel.Trackers.push(trackerModel)
|
||||
|
||||
this.trackersDone.add(key)
|
||||
}
|
||||
|
||||
private addCaption (row: SQLRow, videoModel: VideoModel) {
|
||||
const id = row['VideoCaptions.id']
|
||||
|
||||
if (!id || this.captionsDone.has(id)) return
|
||||
|
||||
const attributes = this.grab(row, this.tables.getCaptionAttributes(), 'VideoCaptions')
|
||||
const captionModel = new VideoCaptionModel(attributes, this.buildOpts)
|
||||
|
||||
videoModel.VideoCaptions.push(captionModel)
|
||||
|
||||
this.captionsDone.add(id)
|
||||
}
|
||||
|
||||
private setBlacklisted (row: SQLRow, videoModel: VideoModel) {
|
||||
const id = row['VideoBlacklist.id']
|
||||
if (!id || this.blacklistDone.has(id)) return
|
||||
|
||||
const attributes = this.grab(row, this.tables.getBlacklistedAttributes(), 'VideoBlacklist')
|
||||
videoModel.VideoBlacklist = new VideoBlacklistModel(attributes, this.buildOpts)
|
||||
|
||||
this.blacklistDone.add(id)
|
||||
}
|
||||
|
||||
private setBlockedOwner (row: SQLRow, videoModel: VideoModel) {
|
||||
const id = row['VideoChannel.Account.AccountBlocklist.id']
|
||||
if (!id) return
|
||||
|
||||
const key = `${videoModel.id}-${id}`
|
||||
if (this.accountBlocklistDone.has(key)) return
|
||||
|
||||
const attributes = this.grab(row, this.tables.getBlocklistAttributes(), 'VideoChannel.Account.AccountBlocklist')
|
||||
videoModel.VideoChannel.Account.BlockedBy.push(new AccountBlocklistModel(attributes, this.buildOpts))
|
||||
|
||||
this.accountBlocklistDone.add(key)
|
||||
}
|
||||
|
||||
private setBlockedServer (row: SQLRow, videoModel: VideoModel) {
|
||||
const id = row['VideoChannel.Account.Actor.Server.ServerBlocklist.id']
|
||||
if (!id || this.serverBlocklistDone.has(id)) return
|
||||
|
||||
const key = `${videoModel.id}-${id}`
|
||||
if (this.serverBlocklistDone.has(key)) return
|
||||
|
||||
const attributes = this.grab(row, this.tables.getBlocklistAttributes(), 'VideoChannel.Account.Actor.Server.ServerBlocklist')
|
||||
videoModel.VideoChannel.Account.Actor.Server.BlockedBy.push(new ServerBlocklistModel(attributes, this.buildOpts))
|
||||
|
||||
this.serverBlocklistDone.add(key)
|
||||
}
|
||||
|
||||
private setScheduleVideoUpdate (row: SQLRow, videoModel: VideoModel) {
|
||||
const id = row['ScheduleVideoUpdate.id']
|
||||
if (!id || this.scheduleVideoUpdateDone.has(id)) return
|
||||
|
||||
const attributes = this.grab(row, this.tables.getScheduleUpdateAttributes(), 'ScheduleVideoUpdate')
|
||||
videoModel.ScheduleVideoUpdate = new ScheduleVideoUpdateModel(attributes, this.buildOpts)
|
||||
|
||||
this.scheduleVideoUpdateDone.add(id)
|
||||
}
|
||||
|
||||
private setLive (row: SQLRow, videoModel: VideoModel) {
|
||||
const id = row['VideoLive.id']
|
||||
if (!id || this.liveDone.has(id)) return
|
||||
|
||||
const attributes = this.grab(row, this.tables.getLiveAttributes(), 'VideoLive')
|
||||
videoModel.VideoLive = new VideoLiveModel(attributes, this.buildOpts)
|
||||
|
||||
this.liveDone.add(id)
|
||||
}
|
||||
|
||||
private addLiveSchedule (row: SQLRow, videoModel: VideoModel) {
|
||||
const id = row['VideoLive.VideoLiveSchedules.id']
|
||||
if (!id) return
|
||||
if (this.liveScheduleDone.has(id)) return
|
||||
|
||||
const videoLiveScheduleAttributes = this.grab(row, this.tables.getLiveScheduleAttributes(), 'VideoLive.VideoLiveSchedules')
|
||||
|
||||
const liveScheduleModel = new VideoLiveScheduleModel(videoLiveScheduleAttributes, this.buildOpts)
|
||||
|
||||
if (!videoModel.VideoLive.LiveSchedules) {
|
||||
videoModel.VideoLive.LiveSchedules = []
|
||||
}
|
||||
|
||||
videoModel.VideoLive.LiveSchedules.push(liveScheduleModel)
|
||||
|
||||
this.liveScheduleDone.add(id)
|
||||
}
|
||||
|
||||
private setSource (row: SQLRow, videoModel: VideoModel) {
|
||||
const id = row['VideoSource.id']
|
||||
if (!id || this.sourceDone.has(id)) return
|
||||
|
||||
const attributes = this.grab(row, this.tables.getVideoSourceAttributes(), 'VideoSource')
|
||||
videoModel.VideoSource = new VideoSourceModel(attributes, this.buildOpts)
|
||||
|
||||
this.sourceDone.add(id)
|
||||
}
|
||||
|
||||
private grab (row: SQLRow, attributes: string[], prefix: string) {
|
||||
const result: { [id: string]: string | number } = {}
|
||||
|
||||
for (const a of attributes) {
|
||||
const key = prefix
|
||||
? prefix + '.' + a
|
||||
: a
|
||||
|
||||
result[a] = row[key]
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
/**
|
||||
* Class to build video attributes/join names we want to fetch from the database
|
||||
*/
|
||||
export class VideoTableAttributes {
|
||||
constructor (private readonly mode: 'get' | 'list') {
|
||||
}
|
||||
|
||||
getChannelAttributesForUser () {
|
||||
return [ 'id', 'accountId' ]
|
||||
}
|
||||
|
||||
getChannelAttributes () {
|
||||
let attributeKeys = [
|
||||
'id',
|
||||
'name',
|
||||
'description',
|
||||
'accountId'
|
||||
]
|
||||
|
||||
if (this.mode === 'get') {
|
||||
attributeKeys = attributeKeys.concat([
|
||||
'support',
|
||||
'createdAt',
|
||||
'updatedAt'
|
||||
])
|
||||
}
|
||||
|
||||
return attributeKeys
|
||||
}
|
||||
|
||||
getUserAccountAttributes () {
|
||||
return [ 'id', 'userId' ]
|
||||
}
|
||||
|
||||
getAccountAttributes () {
|
||||
let attributeKeys = [ 'id', 'name' ]
|
||||
|
||||
if (this.mode === 'get') {
|
||||
attributeKeys = attributeKeys.concat([
|
||||
'description',
|
||||
'userId',
|
||||
'createdAt',
|
||||
'updatedAt'
|
||||
])
|
||||
}
|
||||
|
||||
return attributeKeys
|
||||
}
|
||||
|
||||
getThumbnailAttributes () {
|
||||
let attributeKeys = [ 'id', 'type', 'filename' ]
|
||||
|
||||
if (this.mode === 'get') {
|
||||
attributeKeys = attributeKeys.concat([
|
||||
'height',
|
||||
'width',
|
||||
'fileUrl',
|
||||
'onDisk',
|
||||
'automaticallyGenerated',
|
||||
'videoId',
|
||||
'videoPlaylistId',
|
||||
'createdAt',
|
||||
'updatedAt'
|
||||
])
|
||||
}
|
||||
|
||||
return attributeKeys
|
||||
}
|
||||
|
||||
getFileAttributes () {
|
||||
return [
|
||||
'id',
|
||||
'createdAt',
|
||||
'updatedAt',
|
||||
'resolution',
|
||||
'size',
|
||||
'extname',
|
||||
'filename',
|
||||
'fileUrl',
|
||||
'torrentFilename',
|
||||
'torrentUrl',
|
||||
'infoHash',
|
||||
'fps',
|
||||
'metadataUrl',
|
||||
'videoStreamingPlaylistId',
|
||||
'videoId',
|
||||
'width',
|
||||
'height',
|
||||
'formatFlags',
|
||||
'streams',
|
||||
'storage'
|
||||
]
|
||||
}
|
||||
|
||||
getStreamingPlaylistAttributes () {
|
||||
return [
|
||||
'id',
|
||||
'playlistUrl',
|
||||
'playlistFilename',
|
||||
'type',
|
||||
'p2pMediaLoaderInfohashes',
|
||||
'p2pMediaLoaderPeerVersion',
|
||||
'segmentsSha256Filename',
|
||||
'segmentsSha256Url',
|
||||
'videoId',
|
||||
'createdAt',
|
||||
'updatedAt',
|
||||
'storage'
|
||||
]
|
||||
}
|
||||
|
||||
getUserHistoryAttributes () {
|
||||
return [ 'id', 'currentTime' ]
|
||||
}
|
||||
|
||||
getPlaylistAttributes () {
|
||||
return [
|
||||
'createdAt',
|
||||
'updatedAt',
|
||||
'url',
|
||||
'position',
|
||||
'startTimestamp',
|
||||
'stopTimestamp',
|
||||
'videoPlaylistId'
|
||||
]
|
||||
}
|
||||
|
||||
getTagAttributes () {
|
||||
return [ 'id', 'name' ]
|
||||
}
|
||||
|
||||
getVideoTagAttributes () {
|
||||
return [ 'videoId', 'tagId', 'createdAt', 'updatedAt' ]
|
||||
}
|
||||
|
||||
getBlacklistedAttributes () {
|
||||
return [ 'id', 'reason', 'unfederated' ]
|
||||
}
|
||||
|
||||
getBlocklistAttributes () {
|
||||
return [ 'id' ]
|
||||
}
|
||||
|
||||
getScheduleUpdateAttributes () {
|
||||
return [
|
||||
'id',
|
||||
'updateAt',
|
||||
'privacy',
|
||||
'videoId',
|
||||
'createdAt',
|
||||
'updatedAt'
|
||||
]
|
||||
}
|
||||
|
||||
getLiveAttributes () {
|
||||
return [
|
||||
'id',
|
||||
'streamKey',
|
||||
'saveReplay',
|
||||
'permanentLive',
|
||||
'latencyMode',
|
||||
'videoId',
|
||||
'replaySettingId',
|
||||
'createdAt',
|
||||
'updatedAt'
|
||||
]
|
||||
}
|
||||
|
||||
getLiveScheduleAttributes () {
|
||||
return [
|
||||
'id',
|
||||
'startAt',
|
||||
'createdAt',
|
||||
'updatedAt'
|
||||
]
|
||||
}
|
||||
|
||||
getVideoSourceAttributes () {
|
||||
return [
|
||||
'id',
|
||||
'inputFilename',
|
||||
'keptOriginalFilename',
|
||||
'resolution',
|
||||
'size',
|
||||
'width',
|
||||
'height',
|
||||
'fps',
|
||||
'metadata',
|
||||
'createdAt'
|
||||
]
|
||||
}
|
||||
|
||||
getTrackerAttributes () {
|
||||
return [ 'id', 'url' ]
|
||||
}
|
||||
|
||||
getVideoTrackerAttributes () {
|
||||
return [
|
||||
'videoId',
|
||||
'trackerId',
|
||||
'createdAt',
|
||||
'updatedAt'
|
||||
]
|
||||
}
|
||||
|
||||
getVideoAutoTagAttributes () {
|
||||
return [ 'videoId', 'accountId', 'automaticTagId' ]
|
||||
}
|
||||
|
||||
getAutoTagAttributes () {
|
||||
return [ 'id', 'name' ]
|
||||
}
|
||||
|
||||
getRedundancyAttributes () {
|
||||
return [ 'id', 'fileUrl' ]
|
||||
}
|
||||
|
||||
getCaptionAttributes () {
|
||||
return [ 'id', 'language', 'fileUrl', 'storage', 'filename', 'automaticallyGenerated', 'm3u8Filename', 'm3u8Url' ]
|
||||
}
|
||||
|
||||
getActorAttributes () {
|
||||
let attributeKeys = [
|
||||
'id',
|
||||
'preferredUsername',
|
||||
'url',
|
||||
'serverId',
|
||||
'accountId',
|
||||
'videoChannelId'
|
||||
]
|
||||
|
||||
if (this.mode === 'get') {
|
||||
attributeKeys = attributeKeys.concat([
|
||||
'type',
|
||||
'followersCount',
|
||||
'followingCount',
|
||||
'inboxUrl',
|
||||
'outboxUrl',
|
||||
'sharedInboxUrl',
|
||||
'followersUrl',
|
||||
'followingUrl',
|
||||
'remoteCreatedAt',
|
||||
'createdAt',
|
||||
'updatedAt'
|
||||
])
|
||||
}
|
||||
|
||||
return attributeKeys
|
||||
}
|
||||
|
||||
getAvatarAttributes () {
|
||||
let attributeKeys = [
|
||||
'id',
|
||||
'width',
|
||||
'filename',
|
||||
'type',
|
||||
'fileUrl',
|
||||
'onDisk',
|
||||
'createdAt',
|
||||
'updatedAt'
|
||||
]
|
||||
|
||||
if (this.mode === 'get') {
|
||||
attributeKeys = attributeKeys.concat([
|
||||
'height',
|
||||
'width',
|
||||
'type'
|
||||
])
|
||||
}
|
||||
|
||||
return attributeKeys
|
||||
}
|
||||
|
||||
getServerAttributes () {
|
||||
return [ 'id', 'host' ]
|
||||
}
|
||||
|
||||
getVideoAttributes () {
|
||||
return [
|
||||
'id',
|
||||
'uuid',
|
||||
'name',
|
||||
'category',
|
||||
'licence',
|
||||
'language',
|
||||
'privacy',
|
||||
'nsfw',
|
||||
'nsfwSummary',
|
||||
'nsfwFlags',
|
||||
'description',
|
||||
'support',
|
||||
'duration',
|
||||
'views',
|
||||
'likes',
|
||||
'dislikes',
|
||||
'remote',
|
||||
'isLive',
|
||||
'aspectRatio',
|
||||
'url',
|
||||
'commentsPolicy',
|
||||
'downloadEnabled',
|
||||
'waitTranscoding',
|
||||
'state',
|
||||
'publishedAt',
|
||||
'originallyPublishedAt',
|
||||
'inputFileUpdatedAt',
|
||||
'channelId',
|
||||
'createdAt',
|
||||
'updatedAt',
|
||||
'moveJobsRunning',
|
||||
'comments'
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
import { pick } from '@peertube/peertube-core-utils'
|
||||
import { Sequelize, Transaction } from 'sequelize'
|
||||
import { AbstractVideoQueryBuilder } from './shared/abstract-video-query-builder.js'
|
||||
import { VideoFileQueryBuilder } from './shared/video-file-query-builder.js'
|
||||
import { VideoModelBuilder } from './shared/video-model-builder.js'
|
||||
import { VideoTableAttributes } from './shared/video-table-attributes.js'
|
||||
|
||||
/**
|
||||
* Build a GET SQL query, fetch rows and create the video model
|
||||
*/
|
||||
|
||||
export type GetType =
|
||||
| 'api'
|
||||
| 'full'
|
||||
| 'account-blacklist-files'
|
||||
| 'account'
|
||||
| 'all-files'
|
||||
| 'thumbnails'
|
||||
| 'thumbnails-blacklist'
|
||||
| 'id'
|
||||
| 'blacklist-rights'
|
||||
| 'seo'
|
||||
|
||||
const videoFilesInclude = new Set<GetType>([ 'api', 'full', 'account-blacklist-files', 'all-files' ])
|
||||
const captionsInclude = new Set<GetType>([ 'seo' ])
|
||||
|
||||
const trackersInclude = new Set<GetType>([ 'api' ])
|
||||
const liveInclude = new Set<GetType>([ 'api', 'full' ])
|
||||
const scheduleUpdateInclude = new Set<GetType>([ 'api', 'full' ])
|
||||
const tagsInclude = new Set<GetType>([ 'api', 'full', 'seo' ])
|
||||
const userHistoryInclude = new Set<GetType>([ 'api', 'full' ])
|
||||
const accountInclude = new Set<GetType>([ 'api', 'full', 'account', 'account-blacklist-files', 'seo' ])
|
||||
const ownerUserInclude = new Set<GetType>([ 'blacklist-rights' ])
|
||||
|
||||
const blacklistedInclude = new Set<GetType>([
|
||||
'api',
|
||||
'full',
|
||||
'account-blacklist-files',
|
||||
'thumbnails-blacklist',
|
||||
'blacklist-rights',
|
||||
'seo'
|
||||
])
|
||||
|
||||
const thumbnailsInclude = new Set<GetType>([
|
||||
'api',
|
||||
'full',
|
||||
'account-blacklist-files',
|
||||
'all-files',
|
||||
'thumbnails',
|
||||
'thumbnails-blacklist',
|
||||
'seo'
|
||||
])
|
||||
|
||||
export type BuildVideoGetQueryOptions = {
|
||||
id?: number | string
|
||||
url?: string
|
||||
|
||||
type: GetType
|
||||
|
||||
userId?: number
|
||||
transaction?: Transaction
|
||||
|
||||
logging?: boolean
|
||||
}
|
||||
|
||||
export class VideoModelGetQueryBuilder {
|
||||
videoQueryBuilder: VideosModelGetQuerySubBuilder
|
||||
webVideoFilesQueryBuilder: VideoFileQueryBuilder
|
||||
streamingPlaylistFilesQueryBuilder: VideoFileQueryBuilder
|
||||
|
||||
private readonly videoModelBuilder: VideoModelBuilder
|
||||
|
||||
constructor (protected readonly sequelize: Sequelize) {
|
||||
this.videoQueryBuilder = new VideosModelGetQuerySubBuilder(sequelize)
|
||||
this.webVideoFilesQueryBuilder = new VideoFileQueryBuilder(sequelize)
|
||||
this.streamingPlaylistFilesQueryBuilder = new VideoFileQueryBuilder(sequelize)
|
||||
|
||||
this.videoModelBuilder = new VideoModelBuilder('get', new VideoTableAttributes('get'))
|
||||
}
|
||||
|
||||
async queryVideo (options: BuildVideoGetQueryOptions) {
|
||||
const fileQueryOptions = {
|
||||
...pick(options, [ 'id', 'url', 'transaction', 'logging' ]),
|
||||
|
||||
includeRedundancy: this.shouldIncludeRedundancies(options)
|
||||
}
|
||||
|
||||
const [ videoRows, webVideoFilesRows, streamingPlaylistFilesRows ] = await Promise.all([
|
||||
this.videoQueryBuilder.queryVideos(options),
|
||||
|
||||
videoFilesInclude.has(options.type)
|
||||
? this.webVideoFilesQueryBuilder.queryWebVideos(fileQueryOptions)
|
||||
: Promise.resolve(undefined),
|
||||
|
||||
videoFilesInclude.has(options.type)
|
||||
? this.streamingPlaylistFilesQueryBuilder.queryStreamingPlaylistVideos(fileQueryOptions)
|
||||
: Promise.resolve(undefined)
|
||||
])
|
||||
|
||||
const videos = this.videoModelBuilder.buildVideosFromRows({
|
||||
rows: videoRows,
|
||||
addCaptions: captionsInclude.has(options.type),
|
||||
rowsWebVideoFiles: webVideoFilesRows,
|
||||
rowsStreamingPlaylist: streamingPlaylistFilesRows
|
||||
})
|
||||
|
||||
if (videos.length > 1) {
|
||||
throw new Error('Video results is more than 1')
|
||||
}
|
||||
|
||||
if (videos.length === 0) return null
|
||||
|
||||
return videos[0]
|
||||
}
|
||||
|
||||
private shouldIncludeRedundancies (options: BuildVideoGetQueryOptions) {
|
||||
return options.type === 'api'
|
||||
}
|
||||
}
|
||||
|
||||
export class VideosModelGetQuerySubBuilder extends AbstractVideoQueryBuilder {
|
||||
protected webVideoFilesQuery: string
|
||||
protected streamingPlaylistFilesQuery: string
|
||||
|
||||
constructor (protected readonly sequelize: Sequelize) {
|
||||
super(sequelize, 'get')
|
||||
}
|
||||
|
||||
queryVideos (options: BuildVideoGetQueryOptions) {
|
||||
this.buildMainGetQuery(options)
|
||||
|
||||
return this.runQuery(options)
|
||||
}
|
||||
|
||||
private buildMainGetQuery (options: BuildVideoGetQueryOptions) {
|
||||
this.attributes = {
|
||||
'"video".*': ''
|
||||
}
|
||||
|
||||
if (thumbnailsInclude.has(options.type)) {
|
||||
this.includeThumbnails()
|
||||
}
|
||||
|
||||
if (blacklistedInclude.has(options.type)) {
|
||||
this.includeBlacklisted()
|
||||
}
|
||||
|
||||
if (accountInclude.has(options.type)) {
|
||||
this.includeChannels()
|
||||
this.includeAccounts()
|
||||
}
|
||||
|
||||
if (tagsInclude.has(options.type)) {
|
||||
this.includeTags()
|
||||
}
|
||||
|
||||
if (scheduleUpdateInclude.has(options.type)) {
|
||||
this.includeScheduleUpdate()
|
||||
}
|
||||
|
||||
if (liveInclude.has(options.type)) {
|
||||
this.includeLive()
|
||||
this.includeLiveSchedules()
|
||||
}
|
||||
|
||||
if (options.userId && userHistoryInclude.has(options.type)) {
|
||||
this.includeUserHistory(options.userId)
|
||||
}
|
||||
|
||||
if (ownerUserInclude.has(options.type)) {
|
||||
this.includeOwnerUser()
|
||||
}
|
||||
|
||||
if (trackersInclude.has(options.type)) {
|
||||
this.includeTrackers()
|
||||
}
|
||||
|
||||
if (captionsInclude.has(options.type)) {
|
||||
this.includeCaptions()
|
||||
}
|
||||
|
||||
this.whereId(options)
|
||||
|
||||
this.query = this.buildQuery(options)
|
||||
}
|
||||
|
||||
private buildQuery (options: BuildVideoGetQueryOptions) {
|
||||
const order = tagsInclude.has(options.type)
|
||||
? 'ORDER BY "Tags"."name" ASC'
|
||||
: ''
|
||||
|
||||
const from = `SELECT * FROM "video" ${this.where} LIMIT 1`
|
||||
|
||||
return `${this.buildSelect()} FROM (${from}) AS "video" ${this.joins} ${order}`
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,907 @@
|
||||
import { forceNumber } from '@peertube/peertube-core-utils'
|
||||
import {
|
||||
VideoChannelCollaboratorState,
|
||||
VideoInclude,
|
||||
VideoIncludeType,
|
||||
VideoPrivacy,
|
||||
VideoPrivacyType,
|
||||
VideoState
|
||||
} from '@peertube/peertube-models'
|
||||
import { exists } from '@server/helpers/custom-validators/misc.js'
|
||||
import { WEBSERVER } from '@server/initializers/constants.js'
|
||||
import { buildSortDirectionAndField } from '@server/models/shared/index.js'
|
||||
import { MUserAccountId, MUserId } from '@server/types/models/index.js'
|
||||
import { Sequelize, Transaction } from 'sequelize'
|
||||
import validator from 'validator'
|
||||
import { AbstractRunQuery } from '../../../shared/abstract-run-query.js'
|
||||
import { createSafeIn, parseRowCountResult } from '../../../shared/index.js'
|
||||
|
||||
/**
|
||||
* Build videos list SQL query to fetch rows
|
||||
*/
|
||||
|
||||
export type DisplayOnlyForFollowerOptions = {
|
||||
actorId: number
|
||||
orLocalVideos: boolean
|
||||
}
|
||||
|
||||
export type BuildVideosListQueryOptions = {
|
||||
attributes?: string[]
|
||||
|
||||
serverAccountIdForBlock: number
|
||||
|
||||
displayOnlyForFollower: DisplayOnlyForFollowerOptions
|
||||
|
||||
count: number
|
||||
start: number
|
||||
sort: string
|
||||
|
||||
nsfw?: boolean
|
||||
nsfwFlagsIncluded?: number
|
||||
nsfwFlagsExcluded?: number
|
||||
|
||||
host?: string
|
||||
isLive?: boolean
|
||||
isLocal?: boolean
|
||||
include?: VideoIncludeType
|
||||
includeScheduledLive?: boolean
|
||||
|
||||
categoryOneOf?: number[]
|
||||
licenceOneOf?: number[]
|
||||
languageOneOf?: string[]
|
||||
|
||||
tagsOneOf?: string[]
|
||||
tagsAllOf?: string[]
|
||||
|
||||
privacyOneOf?: VideoPrivacyType[]
|
||||
|
||||
autoTagOneOf?: string[]
|
||||
|
||||
uuids?: string[]
|
||||
|
||||
hasFiles?: boolean
|
||||
hasHLSFiles?: boolean
|
||||
|
||||
hasWebVideoFiles?: boolean
|
||||
|
||||
accountId?: number
|
||||
includeCollaborations?: boolean
|
||||
|
||||
videoChannelId?: number
|
||||
channelNameOneOf?: string[]
|
||||
|
||||
videoPlaylistId?: number
|
||||
|
||||
trendingDays: number
|
||||
|
||||
// Used to include user history information, exclude blocked videos, include internal videos, adapt hot algorithm...
|
||||
user?: MUserAccountId
|
||||
|
||||
// Only list videos watched by this user
|
||||
historyOfUser?: MUserId
|
||||
|
||||
startDate?: string // ISO 8601
|
||||
endDate?: string // ISO 8601
|
||||
originallyPublishedStartDate?: string
|
||||
originallyPublishedEndDate?: string
|
||||
|
||||
durationMin?: number // seconds
|
||||
durationMax?: number // seconds
|
||||
|
||||
search?: string
|
||||
|
||||
isCount?: boolean
|
||||
|
||||
group?: string
|
||||
having?: string
|
||||
|
||||
transaction?: Transaction
|
||||
logging?: boolean
|
||||
|
||||
excludeAlreadyWatched?: boolean
|
||||
}
|
||||
|
||||
export class VideosIdListQueryBuilder extends AbstractRunQuery {
|
||||
protected replacements: any = {}
|
||||
|
||||
private attributes: string[]
|
||||
private joins: string[] = []
|
||||
|
||||
private readonly and: string[] = []
|
||||
|
||||
private readonly cte: string[] = []
|
||||
|
||||
private group = ''
|
||||
private having = ''
|
||||
|
||||
private sort = ''
|
||||
private limit = ''
|
||||
private offset = ''
|
||||
|
||||
private builtChannelJoin = false
|
||||
|
||||
constructor (protected readonly sequelize: Sequelize) {
|
||||
super(sequelize)
|
||||
}
|
||||
|
||||
queryVideoIds (options: BuildVideosListQueryOptions) {
|
||||
this.buildIdsListQuery(options)
|
||||
|
||||
return this.runQuery()
|
||||
}
|
||||
|
||||
countVideoIds (countOptions: BuildVideosListQueryOptions): Promise<number> {
|
||||
this.buildIdsListQuery(countOptions)
|
||||
|
||||
return this.runQuery().then(rows => parseRowCountResult(rows))
|
||||
}
|
||||
|
||||
getQuery (options: BuildVideosListQueryOptions) {
|
||||
this.buildIdsListQuery(options)
|
||||
|
||||
return {
|
||||
query: this.query,
|
||||
sort: this.sort,
|
||||
replacements: this.replacements,
|
||||
queryConfig: this.queryConfig
|
||||
}
|
||||
}
|
||||
|
||||
private buildIdsListQuery (options: BuildVideosListQueryOptions) {
|
||||
this.attributes = options.attributes || [ '"video"."id"' ]
|
||||
|
||||
if (options.group) this.group = options.group
|
||||
if (options.having) this.having = options.having
|
||||
|
||||
this.joins = this.joins.concat([
|
||||
'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId"',
|
||||
'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId"',
|
||||
'INNER JOIN "actor" "accountActor" ON "account"."id" = "accountActor"."accountId"'
|
||||
])
|
||||
|
||||
if (!(options.include & VideoInclude.BLACKLISTED)) {
|
||||
this.whereNotBlacklisted()
|
||||
}
|
||||
|
||||
if (options.serverAccountIdForBlock && !(options.include & VideoInclude.BLOCKED_OWNER)) {
|
||||
this.whereNotBlocked(options.serverAccountIdForBlock, options.user)
|
||||
}
|
||||
|
||||
// Only list published videos
|
||||
if (!(options.include & VideoInclude.NOT_PUBLISHED_STATE)) {
|
||||
if (options.includeScheduledLive) this.joinLiveSchedules()
|
||||
|
||||
this.whereStateAvailable({ includeScheduledLive: options.includeScheduledLive ?? false })
|
||||
}
|
||||
|
||||
if (options.videoPlaylistId) {
|
||||
this.joinPlaylist(options.videoPlaylistId)
|
||||
}
|
||||
|
||||
if (exists(options.isLocal)) {
|
||||
this.whereLocal(options.isLocal)
|
||||
}
|
||||
|
||||
if (options.host) {
|
||||
this.whereHost(options.host)
|
||||
}
|
||||
|
||||
if (options.accountId) {
|
||||
this.whereAccountId({ accountId: options.accountId, includeCollaborations: options.includeCollaborations })
|
||||
}
|
||||
|
||||
if (options.videoChannelId) {
|
||||
this.whereChannelId(options.videoChannelId)
|
||||
}
|
||||
|
||||
if (options.channelNameOneOf && options.channelNameOneOf.length !== 0) {
|
||||
this.whereChannelOneOf(options.channelNameOneOf)
|
||||
}
|
||||
|
||||
if (options.displayOnlyForFollower) {
|
||||
this.whereFollowerActorId({ ...options.displayOnlyForFollower, isCount: options.isCount === true })
|
||||
}
|
||||
|
||||
if (options.hasFiles === true) {
|
||||
this.whereFileExists()
|
||||
}
|
||||
|
||||
if (exists(options.hasWebVideoFiles)) {
|
||||
this.whereWebVideoFileExists(options.hasWebVideoFiles)
|
||||
}
|
||||
|
||||
if (exists(options.hasHLSFiles)) {
|
||||
this.whereHLSFileExists(options.hasHLSFiles)
|
||||
}
|
||||
|
||||
if (options.tagsOneOf) {
|
||||
this.whereTagsOneOf(options.tagsOneOf)
|
||||
}
|
||||
|
||||
if (options.tagsAllOf) {
|
||||
this.whereTagsAllOf(options.tagsAllOf)
|
||||
}
|
||||
|
||||
if (options.autoTagOneOf) {
|
||||
this.whereAutoTagOneOf(options.autoTagOneOf)
|
||||
}
|
||||
|
||||
if (options.privacyOneOf) {
|
||||
this.wherePrivacyOneOf(options.privacyOneOf)
|
||||
} else {
|
||||
// Only list videos with the appropriate privacy
|
||||
this.wherePrivacyAvailable(options.user)
|
||||
}
|
||||
|
||||
if (options.uuids) {
|
||||
this.whereUUIDs(options.uuids)
|
||||
}
|
||||
|
||||
if (options.nsfw === true) {
|
||||
this.whereNSFW(options.nsfwFlagsExcluded)
|
||||
} else if (options.nsfw === false) {
|
||||
this.whereSFW(options.nsfwFlagsIncluded)
|
||||
} else if (options.nsfwFlagsExcluded) {
|
||||
this.whereNSFWFlagsExcluded(options.nsfwFlagsExcluded)
|
||||
}
|
||||
|
||||
if (options.isLive === true) {
|
||||
this.whereLive()
|
||||
} else if (options.isLive === false) {
|
||||
this.whereVOD()
|
||||
}
|
||||
|
||||
if (options.categoryOneOf) {
|
||||
this.whereCategoryOneOf(options.categoryOneOf)
|
||||
}
|
||||
|
||||
if (options.licenceOneOf) {
|
||||
this.whereLicenceOneOf(options.licenceOneOf)
|
||||
}
|
||||
|
||||
if (options.languageOneOf) {
|
||||
this.whereLanguageOneOf(options.languageOneOf)
|
||||
}
|
||||
|
||||
// We don't exclude results in this so if we do a count we don't need to add this complex clause
|
||||
if (options.isCount !== true) {
|
||||
if (options.sort.endsWith('trending')) {
|
||||
this.groupForTrending(options.trendingDays)
|
||||
} else if (options.sort.endsWith('hot') || options.sort.endsWith('best')) {
|
||||
this.addAttributeForHotOrBest(options.sort, options.user)
|
||||
}
|
||||
}
|
||||
|
||||
if (options.historyOfUser) {
|
||||
this.joinHistory(options.historyOfUser.id)
|
||||
}
|
||||
|
||||
if (options.startDate) {
|
||||
this.whereStartDate(options.startDate)
|
||||
}
|
||||
|
||||
if (options.endDate) {
|
||||
this.whereEndDate(options.endDate)
|
||||
}
|
||||
|
||||
if (options.originallyPublishedStartDate) {
|
||||
this.whereOriginallyPublishedStartDate(options.originallyPublishedStartDate)
|
||||
}
|
||||
|
||||
if (options.originallyPublishedEndDate) {
|
||||
this.whereOriginallyPublishedEndDate(options.originallyPublishedEndDate)
|
||||
}
|
||||
|
||||
if (options.durationMin) {
|
||||
this.whereDurationMin(options.durationMin)
|
||||
}
|
||||
|
||||
if (options.durationMax) {
|
||||
this.whereDurationMax(options.durationMax)
|
||||
}
|
||||
|
||||
if (options.excludeAlreadyWatched) {
|
||||
if (exists(options.user.id)) {
|
||||
this.whereExcludeAlreadyWatched(options.user.id)
|
||||
} else {
|
||||
throw new Error('Cannot use excludeAlreadyWatched parameter when auth token is not provided')
|
||||
}
|
||||
}
|
||||
|
||||
this.whereSearch(options.search)
|
||||
|
||||
if (options.isCount === true) {
|
||||
this.setCountAttribute()
|
||||
} else {
|
||||
if (exists(options.sort)) {
|
||||
this.setSort(options.sort)
|
||||
}
|
||||
|
||||
if (exists(options.count)) {
|
||||
this.setLimit(options.count)
|
||||
}
|
||||
|
||||
if (exists(options.start)) {
|
||||
this.setOffset(options.start)
|
||||
}
|
||||
}
|
||||
|
||||
const cteString = this.cte.length !== 0
|
||||
? `WITH ${this.cte.join(', ')} `
|
||||
: ''
|
||||
|
||||
this.query = cteString +
|
||||
'SELECT ' + this.attributes.join(', ') + ' ' +
|
||||
'FROM "video" ' + this.joins.join(' ') + ' ' +
|
||||
'WHERE ' + this.and.join(' AND ') + ' ' +
|
||||
this.group + ' ' +
|
||||
this.having + ' ' +
|
||||
this.sort + ' ' +
|
||||
this.limit + ' ' +
|
||||
this.offset
|
||||
}
|
||||
|
||||
private setCountAttribute () {
|
||||
this.attributes = [ 'COUNT(*) as "total"' ]
|
||||
}
|
||||
|
||||
private joinHistory (userId: number) {
|
||||
this.joins.push('INNER JOIN "userVideoHistory" ON "video"."id" = "userVideoHistory"."videoId"')
|
||||
|
||||
this.and.push('"userVideoHistory"."userId" = :historyOfUser')
|
||||
|
||||
this.replacements.historyOfUser = userId
|
||||
}
|
||||
|
||||
private joinPlaylist (playlistId: number) {
|
||||
this.joins.push(
|
||||
'INNER JOIN "videoPlaylistElement" "video"."id" = "videoPlaylistElement"."videoId" ' +
|
||||
'AND "videoPlaylistElement"."videoPlaylistId" = :videoPlaylistId'
|
||||
)
|
||||
|
||||
this.replacements.videoPlaylistId = playlistId
|
||||
}
|
||||
|
||||
private joinLiveSchedules () {
|
||||
this.joins.push(
|
||||
'LEFT JOIN "videoLive" ON "video"."id" = "videoLive"."videoId"',
|
||||
'LEFT JOIN "videoLiveSchedule" ON "videoLiveSchedule"."liveVideoId" = "videoLive"."id"'
|
||||
)
|
||||
}
|
||||
|
||||
private joinChannel () {
|
||||
if (this.builtChannelJoin) return
|
||||
this.builtChannelJoin = true
|
||||
|
||||
this.joins.push('INNER JOIN "actor" "channelActor" ON "videoChannel"."id" = "channelActor"."videoChannelId"')
|
||||
}
|
||||
|
||||
private whereStateAvailable (options: {
|
||||
includeScheduledLive: boolean
|
||||
}) {
|
||||
const or: string[] = []
|
||||
|
||||
or.push(`"video"."state" = ${VideoState.PUBLISHED}`)
|
||||
or.push(`("video"."state" = ${VideoState.TO_TRANSCODE} AND "video"."waitTranscoding" IS false)`)
|
||||
|
||||
if (options.includeScheduledLive) {
|
||||
or.push(`("video"."state" = ${VideoState.WAITING_FOR_LIVE} AND "videoLiveSchedule"."startAt" > NOW())`)
|
||||
}
|
||||
|
||||
this.and.push(`(${or.join(' OR ')})`)
|
||||
}
|
||||
|
||||
private wherePrivacyAvailable (user?: MUserAccountId) {
|
||||
if (user) {
|
||||
this.and.push(
|
||||
`("video"."privacy" = ${VideoPrivacy.PUBLIC} OR "video"."privacy" = ${VideoPrivacy.INTERNAL})`
|
||||
)
|
||||
} else { // Or only public videos
|
||||
this.and.push(
|
||||
`"video"."privacy" = ${VideoPrivacy.PUBLIC}`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private whereLocal (isLocal: boolean) {
|
||||
const isRemote = isLocal ? 'FALSE' : 'TRUE'
|
||||
|
||||
this.and.push('"video"."remote" IS ' + isRemote)
|
||||
}
|
||||
|
||||
private whereHost (host: string) {
|
||||
// Local instance
|
||||
if (host === WEBSERVER.HOST) {
|
||||
this.and.push('"accountActor"."serverId" IS NULL')
|
||||
return
|
||||
}
|
||||
|
||||
this.joins.push('INNER JOIN "server" ON "server"."id" = "accountActor"."serverId"')
|
||||
|
||||
this.and.push('"server"."host" = :host')
|
||||
this.replacements.host = host
|
||||
}
|
||||
|
||||
private whereAccountId (options: {
|
||||
accountId: number
|
||||
includeCollaborations: boolean
|
||||
}) {
|
||||
if (options.includeCollaborations !== true) {
|
||||
this.and.push('"account"."id" = :accountId')
|
||||
this.replacements.accountId = options.accountId
|
||||
return
|
||||
}
|
||||
|
||||
this.joins.push(
|
||||
'LEFT JOIN "videoChannelCollaborator" ON "videoChannelCollaborator"."channelId" = "videoChannel".id ' +
|
||||
'AND "videoChannelCollaborator"."state" = :channelCollaboratorState ' +
|
||||
// Ensure we join with max 1 collaborator to not duplicate rows
|
||||
'AND "videoChannelCollaborator"."accountId" = :accountId'
|
||||
)
|
||||
|
||||
this.and.push('("account"."id" = :accountId OR "videoChannelCollaborator"."accountId" = :accountId)')
|
||||
|
||||
this.replacements.accountId = options.accountId
|
||||
this.replacements.channelCollaboratorState = VideoChannelCollaboratorState.ACCEPTED
|
||||
}
|
||||
|
||||
private whereChannelId (channelId: number) {
|
||||
this.and.push('"videoChannel"."id" = :videoChannelId')
|
||||
this.replacements.videoChannelId = channelId
|
||||
}
|
||||
|
||||
private whereChannelOneOf (channelOneOf: string[]) {
|
||||
this.joinChannel()
|
||||
|
||||
this.and.push('"channelActor"."preferredUsername" IN (:channelOneOf)')
|
||||
this.replacements.channelOneOf = channelOneOf
|
||||
}
|
||||
|
||||
private whereFollowerActorId (options: { actorId: number, orLocalVideos: boolean, isCount: boolean }) {
|
||||
// EXISTS doesn't work very well with COUNT queries, so we use a CTE instead
|
||||
if (options.isCount) {
|
||||
// Don't use CTE on purpose, that seems to be slower in this case
|
||||
const targetActorIdQuery =
|
||||
`SELECT "targetActorId" FROM "actorFollow" WHERE "actorFollow"."actorId" = :followerActorId AND "actorFollow"."state" = 'accepted'`
|
||||
|
||||
let cteQuery = '"videoCandidates" AS (' +
|
||||
`SELECT "videoShare"."videoId" FROM "videoShare" WHERE "videoShare"."actorId" IN (${targetActorIdQuery}) ` +
|
||||
`UNION ` +
|
||||
`SELECT "video"."id" FROM "video" INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ` +
|
||||
` INNER JOIN "actor" "channelActor" ON "videoChannel"."id" = "channelActor"."videoChannelId" ` +
|
||||
` WHERE "channelActor"."id" IN (${targetActorIdQuery}) ` +
|
||||
`UNION ` +
|
||||
`SELECT "video"."id" FROM "video" INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ` +
|
||||
` INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ` +
|
||||
` INNER JOIN "actor" "accountActor" ON "account"."id" = "accountActor"."accountId" ` +
|
||||
` WHERE "accountActor"."id" IN (${targetActorIdQuery}) `
|
||||
|
||||
if (options.orLocalVideos) {
|
||||
cteQuery += 'UNION SELECT "video"."id" FROM "video" WHERE "remote" IS FALSE'
|
||||
}
|
||||
|
||||
cteQuery += ')'
|
||||
|
||||
this.cte.push(cteQuery)
|
||||
|
||||
this.joins.push('INNER JOIN "videoCandidates" ON "video"."id" = "videoCandidates"."videoId"')
|
||||
} else {
|
||||
this.joinChannel()
|
||||
|
||||
let query = ''
|
||||
|
||||
query = '(' +
|
||||
' EXISTS (' + // Videos shared by actors (instances, channels) we follow
|
||||
' SELECT 1 FROM "videoShare" ' +
|
||||
' INNER JOIN "actorFollow" "actorFollowShare" ON "actorFollowShare"."targetActorId" = "videoShare"."actorId" ' +
|
||||
' AND "actorFollowShare"."actorId" = :followerActorId AND "actorFollowShare"."state" = \'accepted\' ' +
|
||||
' WHERE "videoShare"."videoId" = "video"."id"' +
|
||||
' UNION ALL ' +
|
||||
' SELECT 1 from "actorFollow" ' + // Videos published by accounts we follow
|
||||
' WHERE "actorFollow"."targetActorId" = "accountActor"."id" ' +
|
||||
' AND "actorFollow"."actorId" = :followerActorId ' +
|
||||
' AND "actorFollow"."state" = \'accepted\'' +
|
||||
' UNION ALL ' +
|
||||
' SELECT 1 from "actorFollow" ' + // Videos published by channels we follow
|
||||
' WHERE "actorFollow"."targetActorId" = "channelActor"."id" ' +
|
||||
' AND "actorFollow"."actorId" = :followerActorId ' +
|
||||
' AND "actorFollow"."state" = \'accepted\'' +
|
||||
' LIMIT 1' +
|
||||
' )'
|
||||
|
||||
if (options.orLocalVideos) {
|
||||
query += ' OR "video"."remote" IS FALSE'
|
||||
}
|
||||
|
||||
query += ')'
|
||||
this.and.push(query)
|
||||
}
|
||||
|
||||
this.replacements.followerActorId = options.actorId
|
||||
}
|
||||
|
||||
private whereFileExists () {
|
||||
this.and.push(`(${this.buildWebVideoFileExistsQuery(true)} OR ${this.buildHLSFileExistsQuery(true)})`)
|
||||
}
|
||||
|
||||
private whereWebVideoFileExists (exists: boolean) {
|
||||
this.and.push(this.buildWebVideoFileExistsQuery(exists))
|
||||
}
|
||||
|
||||
private whereHLSFileExists (exists: boolean) {
|
||||
this.and.push(this.buildHLSFileExistsQuery(exists))
|
||||
}
|
||||
|
||||
private buildWebVideoFileExistsQuery (exists: boolean) {
|
||||
const prefix = exists ? '' : 'NOT '
|
||||
|
||||
return prefix + 'EXISTS (SELECT 1 FROM "videoFile" WHERE "videoFile"."videoId" = "video"."id")'
|
||||
}
|
||||
|
||||
private buildHLSFileExistsQuery (exists: boolean) {
|
||||
const prefix = exists ? '' : 'NOT '
|
||||
|
||||
return prefix + 'EXISTS (' +
|
||||
' SELECT 1 FROM "videoStreamingPlaylist" ' +
|
||||
' INNER JOIN "videoFile" ON "videoFile"."videoStreamingPlaylistId" = "videoStreamingPlaylist"."id" ' +
|
||||
' WHERE "videoStreamingPlaylist"."videoId" = "video"."id"' +
|
||||
')'
|
||||
}
|
||||
|
||||
private whereTagsOneOf (tagsOneOf: string[]) {
|
||||
const tagsOneOfLower = tagsOneOf.map(t => t.toLowerCase())
|
||||
|
||||
this.cte.push(
|
||||
'"tagsOneOf" AS (' +
|
||||
' SELECT "videoTag"."videoId" AS "videoId" FROM "videoTag" ' +
|
||||
' INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
|
||||
' WHERE lower("tag"."name") IN (' + createSafeIn(this.sequelize, tagsOneOfLower) + ') ' +
|
||||
')'
|
||||
)
|
||||
|
||||
this.joins.push('INNER JOIN "tagsOneOf" ON "video"."id" = "tagsOneOf"."videoId"')
|
||||
}
|
||||
|
||||
private whereAutoTagOneOf (autoTagOneOf: string[]) {
|
||||
const tags = autoTagOneOf.map(t => t.toLowerCase())
|
||||
|
||||
this.cte.push(
|
||||
'"autoTagsOneOf" AS (' +
|
||||
' SELECT "videoAutomaticTag"."videoId" AS "videoId" FROM "videoAutomaticTag" ' +
|
||||
' INNER JOIN "automaticTag" ON "automaticTag"."id" = "videoAutomaticTag"."automaticTagId" ' +
|
||||
' WHERE lower("automaticTag"."name") IN (' + createSafeIn(this.sequelize, tags) + ') ' +
|
||||
')'
|
||||
)
|
||||
|
||||
this.joins.push('INNER JOIN "autoTagsOneOf" ON "video"."id" = "autoTagsOneOf"."videoId"')
|
||||
}
|
||||
|
||||
private whereTagsAllOf (tagsAllOf: string[]) {
|
||||
const tagsAllOfLower = tagsAllOf.map(t => t.toLowerCase())
|
||||
|
||||
this.cte.push(
|
||||
'"tagsAllOf" AS (' +
|
||||
' SELECT "videoTag"."videoId" AS "videoId" FROM "videoTag" ' +
|
||||
' INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
|
||||
' WHERE lower("tag"."name") IN (' + createSafeIn(this.sequelize, tagsAllOfLower) + ') ' +
|
||||
' GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + tagsAllOfLower.length +
|
||||
')'
|
||||
)
|
||||
|
||||
this.joins.push('INNER JOIN "tagsAllOf" ON "video"."id" = "tagsAllOf"."videoId"')
|
||||
}
|
||||
|
||||
private wherePrivacyOneOf (privacyOneOf: VideoPrivacyType[]) {
|
||||
this.and.push('"video"."privacy" IN (:privacyOneOf)')
|
||||
this.replacements.privacyOneOf = privacyOneOf
|
||||
}
|
||||
|
||||
private whereUUIDs (uuids: string[]) {
|
||||
this.and.push('"video"."uuid" IN (' + createSafeIn(this.sequelize, uuids) + ')')
|
||||
}
|
||||
|
||||
private whereCategoryOneOf (categoryOneOf: number[]) {
|
||||
this.and.push('"video"."category" IN (:categoryOneOf)')
|
||||
this.replacements.categoryOneOf = categoryOneOf
|
||||
}
|
||||
|
||||
private whereLicenceOneOf (licenceOneOf: number[]) {
|
||||
this.and.push('"video"."licence" IN (:licenceOneOf)')
|
||||
this.replacements.licenceOneOf = licenceOneOf
|
||||
}
|
||||
|
||||
private whereLanguageOneOf (languageOneOf: string[]) {
|
||||
const languages = languageOneOf.filter(l => l && l !== '_unknown')
|
||||
const languagesQueryParts: string[] = []
|
||||
|
||||
if (languages.length !== 0) {
|
||||
languagesQueryParts.push('"video"."language" IN (:languageOneOf)')
|
||||
this.replacements.languageOneOf = languages
|
||||
|
||||
languagesQueryParts.push(
|
||||
'EXISTS (' +
|
||||
' SELECT 1 FROM "videoCaption" WHERE "videoCaption"."language" ' +
|
||||
' IN (' + createSafeIn(this.sequelize, languages) + ') AND ' +
|
||||
' "videoCaption"."videoId" = "video"."id"' +
|
||||
')'
|
||||
)
|
||||
}
|
||||
|
||||
if (languageOneOf.includes('_unknown')) {
|
||||
languagesQueryParts.push('"video"."language" IS NULL')
|
||||
}
|
||||
|
||||
if (languagesQueryParts.length !== 0) {
|
||||
this.and.push('(' + languagesQueryParts.join(' OR ') + ')')
|
||||
}
|
||||
}
|
||||
|
||||
private whereNSFW (nsfwFlagsExcluded?: number) {
|
||||
let filter = '"video"."nsfw" IS TRUE'
|
||||
|
||||
if (nsfwFlagsExcluded) {
|
||||
filter += ' AND "video"."nsfwFlags" & :nsfwFlagsExcluded = 0'
|
||||
this.replacements.nsfwFlagsExcluded = nsfwFlagsExcluded
|
||||
}
|
||||
|
||||
this.and.push(filter)
|
||||
}
|
||||
|
||||
private whereSFW (nsfwFlagsIncluded?: number) {
|
||||
let filter = '"video"."nsfw" IS FALSE'
|
||||
|
||||
if (nsfwFlagsIncluded) {
|
||||
filter = `(${filter} OR "video"."nsfwFlags" & :nsfwFlagsIncluded != 0)`
|
||||
this.replacements.nsfwFlagsIncluded = nsfwFlagsIncluded
|
||||
}
|
||||
|
||||
this.and.push(filter)
|
||||
}
|
||||
|
||||
private whereNSFWFlagsExcluded (nsfwFlagsExcluded: number) {
|
||||
this.and.push('"video"."nsfwFlags" & :nsfwFlagsExcluded = 0')
|
||||
this.replacements.nsfwFlagsExcluded = nsfwFlagsExcluded
|
||||
}
|
||||
|
||||
private whereLive () {
|
||||
this.and.push('"video"."isLive" IS TRUE')
|
||||
}
|
||||
|
||||
private whereVOD () {
|
||||
this.and.push('"video"."isLive" IS FALSE')
|
||||
}
|
||||
|
||||
private whereNotBlocked (serverAccountId: number, user?: MUserAccountId) {
|
||||
const blockerIds = [ serverAccountId ]
|
||||
if (user) blockerIds.push(user.Account.id)
|
||||
|
||||
const inClause = createSafeIn(this.sequelize, blockerIds)
|
||||
|
||||
this.and.push(
|
||||
'NOT EXISTS (' +
|
||||
' SELECT 1 FROM "accountBlocklist" ' +
|
||||
' WHERE "accountBlocklist"."accountId" IN (' + inClause + ') ' +
|
||||
' AND "accountBlocklist"."targetAccountId" = "account"."id" ' +
|
||||
')' +
|
||||
'AND NOT EXISTS (' +
|
||||
' SELECT 1 FROM "serverBlocklist" WHERE "serverBlocklist"."accountId" IN (' + inClause + ') ' +
|
||||
' AND "serverBlocklist"."targetServerId" = "accountActor"."serverId"' +
|
||||
')'
|
||||
)
|
||||
}
|
||||
|
||||
private whereSearch (search?: string) {
|
||||
if (!search) {
|
||||
this.attributes.push('0 as similarity')
|
||||
return
|
||||
}
|
||||
|
||||
const escapedSearch = this.sequelize.escape(search)
|
||||
const escapedLikeSearch = this.sequelize.escape('%' + search + '%')
|
||||
|
||||
this.queryConfig = 'SET pg_trgm.word_similarity_threshold = 0.40;'
|
||||
|
||||
this.cte.push(
|
||||
'"trigramSearch" AS (' +
|
||||
' SELECT "video"."id", ' +
|
||||
` word_similarity(lower(immutable_unaccent(${escapedSearch})), lower(immutable_unaccent("video"."name"))) as similarity ` +
|
||||
' FROM "video" ' +
|
||||
' WHERE lower(immutable_unaccent(' + escapedSearch + ')) <% lower(immutable_unaccent("video"."name")) OR ' +
|
||||
' lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
|
||||
')'
|
||||
)
|
||||
|
||||
this.joins.push('LEFT JOIN "trigramSearch" ON "video"."id" = "trigramSearch"."id"')
|
||||
|
||||
let base = '(' +
|
||||
' "trigramSearch"."id" IS NOT NULL OR ' +
|
||||
' EXISTS (' +
|
||||
' SELECT 1 FROM "videoTag" ' +
|
||||
' INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
|
||||
` WHERE lower("tag"."name") = lower(${escapedSearch}) ` +
|
||||
' AND "video"."id" = "videoTag"."videoId"' +
|
||||
' )'
|
||||
|
||||
if (validator.default.isUUID(search)) {
|
||||
base += ` OR "video"."uuid" = ${escapedSearch}`
|
||||
}
|
||||
|
||||
base += ')'
|
||||
|
||||
this.and.push(base)
|
||||
|
||||
let attribute = `COALESCE("trigramSearch"."similarity", 0)`
|
||||
if (this.group) attribute = `AVG(${attribute})`
|
||||
|
||||
this.attributes.push(`${attribute} as similarity`)
|
||||
}
|
||||
|
||||
private whereNotBlacklisted () {
|
||||
this.and.push('"video"."id" NOT IN (SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")')
|
||||
}
|
||||
|
||||
private whereStartDate (startDate: string) {
|
||||
this.and.push('"video"."publishedAt" >= :startDate')
|
||||
this.replacements.startDate = startDate
|
||||
}
|
||||
|
||||
private whereEndDate (endDate: string) {
|
||||
this.and.push('"video"."publishedAt" <= :endDate')
|
||||
this.replacements.endDate = endDate
|
||||
}
|
||||
|
||||
private whereOriginallyPublishedStartDate (startDate: string) {
|
||||
this.and.push('"video"."originallyPublishedAt" >= :originallyPublishedStartDate')
|
||||
this.replacements.originallyPublishedStartDate = startDate
|
||||
}
|
||||
|
||||
private whereOriginallyPublishedEndDate (endDate: string) {
|
||||
this.and.push('"video"."originallyPublishedAt" <= :originallyPublishedEndDate')
|
||||
this.replacements.originallyPublishedEndDate = endDate
|
||||
}
|
||||
|
||||
private whereDurationMin (durationMin: number) {
|
||||
this.and.push('"video"."duration" >= :durationMin')
|
||||
this.replacements.durationMin = durationMin
|
||||
}
|
||||
|
||||
private whereDurationMax (durationMax: number) {
|
||||
this.and.push('"video"."duration" <= :durationMax')
|
||||
this.replacements.durationMax = durationMax
|
||||
}
|
||||
|
||||
private whereExcludeAlreadyWatched (userId: number) {
|
||||
this.and.push(
|
||||
'NOT EXISTS (' +
|
||||
' SELECT 1' +
|
||||
' FROM "userVideoHistory"' +
|
||||
' WHERE "video"."id" = "userVideoHistory"."videoId"' +
|
||||
' AND "userVideoHistory"."userId" = :excludeAlreadyWatchedUserId' +
|
||||
')'
|
||||
)
|
||||
this.replacements.excludeAlreadyWatchedUserId = userId
|
||||
}
|
||||
|
||||
private groupForTrending (trendingDays: number) {
|
||||
const viewsGteDate = new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
|
||||
|
||||
this.joins.push('LEFT JOIN "videoView" ON "video"."id" = "videoView"."videoId" AND "videoView"."startDate" >= :viewsGteDate')
|
||||
this.replacements.viewsGteDate = viewsGteDate
|
||||
|
||||
this.attributes.push('COALESCE(SUM("videoView"."views"), 0) AS "score"')
|
||||
|
||||
this.group = 'GROUP BY "video"."id"'
|
||||
}
|
||||
|
||||
private addAttributeForHotOrBest (sort: string, user?: MUserAccountId) {
|
||||
/**
|
||||
* "Hotness" is a measure based on absolute view/comment/like/dislike numbers,
|
||||
* with fixed weights only applied to their log values.
|
||||
*
|
||||
* This algorithm gives little chance for an old video to have a good score,
|
||||
* for which recent spikes in interactions could be a sign of "hotness" and
|
||||
* justify a better score. However there are multiple ways to achieve that
|
||||
* goal, which is left for later. Yes, this is a TODO :)
|
||||
*
|
||||
* notes:
|
||||
* - weights and base score are in number of half-days.
|
||||
* - all comments are counted, regardless of being written by the video author or not
|
||||
* see https://github.com/reddit-archive/reddit/blob/master/r2/r2/lib/db/_sorts.pyx#L47-L58
|
||||
* - we have less interactions than on reddit, so multiply weights by an arbitrary factor
|
||||
*/
|
||||
const weights = {
|
||||
like: 3 * 50,
|
||||
dislike: -3 * 50,
|
||||
view: Math.floor((1 / 3) * 50),
|
||||
comment: 2 * 50, // a comment takes more time than a like to do, but can be done multiple times
|
||||
history: -2 * 50
|
||||
}
|
||||
|
||||
let attribute = `LOG(GREATEST(1, "video"."likes" - 1)) * ${weights.like} ` + // likes (+)
|
||||
`+ LOG(GREATEST(1, "video"."dislikes" - 1)) * ${weights.dislike} ` + // dislikes (-)
|
||||
`+ LOG("video"."views" + 1) * ${weights.view} ` + // views (+)
|
||||
`+ LOG(GREATEST(1, "video"."comments")) * ${weights.comment} ` + // comments (+)
|
||||
'+ (SELECT (EXTRACT(epoch FROM "video"."publishedAt") - 1446156582) / 47000) ' // base score (in number of half-days)
|
||||
|
||||
if (sort.endsWith('best') && user) {
|
||||
this.joins.push(
|
||||
'LEFT JOIN "userVideoHistory" ON "video"."id" = "userVideoHistory"."videoId" AND "userVideoHistory"."userId" = :bestUser'
|
||||
)
|
||||
this.replacements.bestUser = user.id
|
||||
|
||||
attribute += `+ POWER(CASE WHEN "userVideoHistory"."id" IS NULL THEN 0 ELSE 1 END, 2.0) * ${weights.history} `
|
||||
}
|
||||
|
||||
attribute += 'AS "score"'
|
||||
this.attributes.push(attribute)
|
||||
}
|
||||
|
||||
private setSort (sort: string) {
|
||||
if (sort === '-originallyPublishedAt' || sort === 'originallyPublishedAt') {
|
||||
this.attributes.push('COALESCE("video"."originallyPublishedAt", "video"."publishedAt") AS "publishedAtForOrder"')
|
||||
}
|
||||
|
||||
if (sort === '-localVideoFilesSize' || sort === 'localVideoFilesSize') {
|
||||
this.attributes.push(
|
||||
'(' +
|
||||
'CASE ' +
|
||||
'WHEN "video"."remote" IS TRUE THEN 0 ' + // Consider remote videos with size of 0
|
||||
'ELSE (' +
|
||||
'(SELECT COALESCE(SUM(size), 0) FROM "videoFile" WHERE "videoFile"."videoId" = "video"."id")' +
|
||||
' + ' +
|
||||
'(' +
|
||||
'SELECT COALESCE(SUM(size), 0) FROM "videoFile" ' +
|
||||
'INNER JOIN "videoStreamingPlaylist" ON "videoStreamingPlaylist"."id" = "videoFile"."videoStreamingPlaylistId" ' +
|
||||
'AND "videoStreamingPlaylist"."videoId" = "video"."id"' +
|
||||
')' +
|
||||
' + ' +
|
||||
'(' +
|
||||
'SELECT COALESCE(SUM(size), 0) FROM "videoSource" ' +
|
||||
'WHERE "videoSource"."videoId" = "video"."id" AND "videoSource"."storage" IS NOT NULL' +
|
||||
')' +
|
||||
') END' +
|
||||
') AS "localVideoFilesSize"'
|
||||
)
|
||||
}
|
||||
|
||||
this.sort = this.buildOrder(sort)
|
||||
}
|
||||
|
||||
private buildOrder (value: string) {
|
||||
const { direction, field } = buildSortDirectionAndField(value)
|
||||
if (field.match(/^[a-zA-Z."]+$/) === null) throw new Error('Invalid sort column ' + field)
|
||||
|
||||
if (field.toLowerCase() === 'random') return 'ORDER BY RANDOM()'
|
||||
if (field.toLowerCase() === 'total') return `ORDER BY "total" ${direction}`
|
||||
|
||||
if ([ 'trending', 'hot', 'best' ].includes(field.toLowerCase())) { // Sort by aggregation
|
||||
return `ORDER BY "score" ${direction}, "video"."views" ${direction}`
|
||||
}
|
||||
|
||||
let firstSort: string
|
||||
|
||||
if (field.toLowerCase() === 'match') { // Search
|
||||
firstSort = '"similarity"'
|
||||
} else if (field === 'originallyPublishedAt') {
|
||||
firstSort = '"publishedAtForOrder"'
|
||||
} else if (field === 'localVideoFilesSize') {
|
||||
firstSort = '"localVideoFilesSize"'
|
||||
} else if (field.includes('.')) {
|
||||
firstSort = field
|
||||
} else {
|
||||
firstSort = `"video"."${field}"`
|
||||
}
|
||||
|
||||
return `ORDER BY ${firstSort} ${direction}, "video"."id" ASC`
|
||||
}
|
||||
|
||||
private setLimit (countArg: number) {
|
||||
const count = forceNumber(countArg)
|
||||
this.limit = `LIMIT ${count}`
|
||||
}
|
||||
|
||||
private setOffset (startArg: number) {
|
||||
const start = forceNumber(startArg)
|
||||
this.offset = `OFFSET ${start}`
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import { pick } from '@peertube/peertube-core-utils'
|
||||
import { VideoInclude } from '@peertube/peertube-models'
|
||||
import { getServerActor } from '@server/models/application/application.js'
|
||||
import { MActorAccount } from '@server/types/models/index.js'
|
||||
import { Sequelize } from 'sequelize'
|
||||
import { AbstractVideoQueryBuilder } from './shared/abstract-video-query-builder.js'
|
||||
import { VideoFileQueryBuilder } from './shared/video-file-query-builder.js'
|
||||
import { VideoModelBuilder } from './shared/video-model-builder.js'
|
||||
import { BuildVideosListQueryOptions, VideosIdListQueryBuilder } from './videos-id-list-query-builder.js'
|
||||
|
||||
/**
|
||||
* Build videos list SQL query and create video models
|
||||
*/
|
||||
|
||||
export class VideosModelListQueryBuilder extends AbstractVideoQueryBuilder {
|
||||
private innerQuery: string
|
||||
private innerSort: string
|
||||
|
||||
webVideoFilesQueryBuilder: VideoFileQueryBuilder
|
||||
streamingPlaylistFilesQueryBuilder: VideoFileQueryBuilder
|
||||
|
||||
private readonly videoModelBuilder: VideoModelBuilder
|
||||
|
||||
constructor (protected readonly sequelize: Sequelize) {
|
||||
super(sequelize, 'list')
|
||||
|
||||
this.videoModelBuilder = new VideoModelBuilder(this.mode, this.tables)
|
||||
this.webVideoFilesQueryBuilder = new VideoFileQueryBuilder(sequelize)
|
||||
this.streamingPlaylistFilesQueryBuilder = new VideoFileQueryBuilder(sequelize)
|
||||
}
|
||||
|
||||
async queryVideos (options: BuildVideosListQueryOptions) {
|
||||
const serverActor = await getServerActor()
|
||||
|
||||
this.buildInnerQuery(options)
|
||||
this.buildMainQuery(options, serverActor)
|
||||
|
||||
const rows = await this.runQuery()
|
||||
|
||||
if (options.include & VideoInclude.FILES) {
|
||||
const videoIds = Array.from(new Set(rows.map(r => r.id)))
|
||||
|
||||
if (videoIds.length !== 0) {
|
||||
const fileQueryOptions = {
|
||||
...pick(options, [ 'transaction', 'logging' ]),
|
||||
|
||||
ids: videoIds,
|
||||
includeRedundancy: false
|
||||
}
|
||||
|
||||
const [ rowsWebVideoFiles, rowsStreamingPlaylist ] = await Promise.all([
|
||||
this.webVideoFilesQueryBuilder.queryWebVideos(fileQueryOptions),
|
||||
this.streamingPlaylistFilesQueryBuilder.queryStreamingPlaylistVideos(fileQueryOptions)
|
||||
])
|
||||
|
||||
return this.videoModelBuilder.buildVideosFromRows({
|
||||
rows,
|
||||
include: options.include,
|
||||
addCaptions: false,
|
||||
rowsStreamingPlaylist,
|
||||
rowsWebVideoFiles
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return this.videoModelBuilder.buildVideosFromRows({ rows, include: options.include, addCaptions: false })
|
||||
}
|
||||
|
||||
private buildInnerQuery (options: BuildVideosListQueryOptions) {
|
||||
const idsQueryBuilder = new VideosIdListQueryBuilder(this.sequelize)
|
||||
const { query, sort, replacements, queryConfig } = idsQueryBuilder.getQuery(options)
|
||||
|
||||
this.replacements = replacements
|
||||
this.innerQuery = query
|
||||
this.innerSort = sort
|
||||
this.queryConfig = queryConfig
|
||||
}
|
||||
|
||||
private buildMainQuery (options: BuildVideosListQueryOptions, serverActor: MActorAccount) {
|
||||
this.attributes = {
|
||||
'"video".*': ''
|
||||
}
|
||||
|
||||
this.addJoin('INNER JOIN "video" ON "tmp"."id" = "video"."id"')
|
||||
|
||||
this.includeChannels()
|
||||
this.includeAccounts()
|
||||
this.includeThumbnails()
|
||||
|
||||
if (options.user) {
|
||||
this.includeUserHistory(options.user.id)
|
||||
}
|
||||
|
||||
if (options.videoPlaylistId) {
|
||||
this.includePlaylist(options.videoPlaylistId)
|
||||
}
|
||||
|
||||
if (options.isLive || options.includeScheduledLive) {
|
||||
this.includeLive()
|
||||
}
|
||||
|
||||
if (options.includeScheduledLive) {
|
||||
this.includeLiveSchedules()
|
||||
}
|
||||
|
||||
if (options.include & VideoInclude.BLACKLISTED) {
|
||||
this.includeBlacklisted()
|
||||
}
|
||||
|
||||
if (options.include & VideoInclude.BLOCKED_OWNER) {
|
||||
this.includeBlockedOwnerAndServer(options.serverAccountIdForBlock, options.user)
|
||||
}
|
||||
|
||||
if (options.include & VideoInclude.SOURCE) {
|
||||
this.includeVideoSource()
|
||||
}
|
||||
|
||||
if (options.include & VideoInclude.AUTOMATIC_TAGS) {
|
||||
this.includeAutomaticTags(serverActor.Account.id)
|
||||
}
|
||||
|
||||
if (options.include & VideoInclude.TAGS) {
|
||||
this.includeTags()
|
||||
}
|
||||
|
||||
if (options.include & VideoInclude.NOT_PUBLISHED_STATE) {
|
||||
this.includeScheduleUpdate()
|
||||
}
|
||||
|
||||
const select = this.buildSelect()
|
||||
|
||||
this.query = `${select} FROM (${this.innerQuery}) AS "tmp" ${this.joins} ${this.innerSort}`
|
||||
}
|
||||
}
|
||||
173
server/core/models/video/storyboard.ts
Normal file
173
server/core/models/video/storyboard.ts
Normal file
@@ -0,0 +1,173 @@
|
||||
import { remove } from 'fs-extra/esm'
|
||||
import { join } from 'path'
|
||||
import { AfterDestroy, AllowNull, BelongsTo, Column, CreatedAt, DataType, ForeignKey, Table, UpdatedAt } from 'sequelize-typescript'
|
||||
import { CONFIG } from '@server/initializers/config.js'
|
||||
import { MStoryboard, MStoryboardVideo, MVideo } from '@server/types/models/index.js'
|
||||
import { Storyboard } from '@peertube/peertube-models'
|
||||
import { logger } from '../../helpers/logger.js'
|
||||
import { CONSTRAINTS_FIELDS, LAZY_STATIC_PATHS, WEBSERVER } from '../../initializers/constants.js'
|
||||
import { VideoModel } from './video.js'
|
||||
import { Transaction } from 'sequelize'
|
||||
import { SequelizeModel } from '../shared/index.js'
|
||||
|
||||
@Table({
|
||||
tableName: 'storyboard',
|
||||
indexes: [
|
||||
{
|
||||
fields: [ 'videoId' ],
|
||||
unique: true
|
||||
},
|
||||
{
|
||||
fields: [ 'filename' ],
|
||||
unique: true
|
||||
}
|
||||
]
|
||||
})
|
||||
export class StoryboardModel extends SequelizeModel<StoryboardModel> {
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare filename: string
|
||||
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare totalHeight: number
|
||||
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare totalWidth: number
|
||||
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare spriteHeight: number
|
||||
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare spriteWidth: number
|
||||
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare spriteDuration: number
|
||||
|
||||
@AllowNull(true)
|
||||
@Column(DataType.STRING(CONSTRAINTS_FIELDS.COMMONS.URL.max))
|
||||
declare fileUrl: string
|
||||
|
||||
@ForeignKey(() => VideoModel)
|
||||
@Column
|
||||
declare videoId: number
|
||||
|
||||
@BelongsTo(() => VideoModel, {
|
||||
foreignKey: {
|
||||
allowNull: false
|
||||
},
|
||||
onDelete: 'CASCADE'
|
||||
})
|
||||
declare Video: Awaited<VideoModel>
|
||||
|
||||
@CreatedAt
|
||||
declare createdAt: Date
|
||||
|
||||
@UpdatedAt
|
||||
declare updatedAt: Date
|
||||
|
||||
@AfterDestroy
|
||||
static removeInstanceFile (instance: StoryboardModel) {
|
||||
logger.info('Removing storyboard file %s.', instance.filename)
|
||||
|
||||
// Don't block the transaction
|
||||
instance.removeFile()
|
||||
.catch(err => logger.error('Cannot remove storyboard file %s.', instance.filename, { err }))
|
||||
}
|
||||
|
||||
static loadByVideo (videoId: number, transaction?: Transaction): Promise<MStoryboard> {
|
||||
const query = {
|
||||
where: {
|
||||
videoId
|
||||
},
|
||||
transaction
|
||||
}
|
||||
|
||||
return StoryboardModel.findOne(query)
|
||||
}
|
||||
|
||||
static loadByFilename (filename: string): Promise<MStoryboard> {
|
||||
const query = {
|
||||
where: {
|
||||
filename
|
||||
}
|
||||
}
|
||||
|
||||
return StoryboardModel.findOne(query)
|
||||
}
|
||||
|
||||
static loadWithVideoByFilename (filename: string): Promise<MStoryboardVideo> {
|
||||
const query = {
|
||||
where: {
|
||||
filename
|
||||
},
|
||||
include: [
|
||||
{
|
||||
model: VideoModel.unscoped(),
|
||||
required: true
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
return StoryboardModel.findOne(query)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static async listStoryboardsOf (video: MVideo): Promise<MStoryboardVideo[]> {
|
||||
const query = {
|
||||
where: {
|
||||
videoId: video.id
|
||||
}
|
||||
}
|
||||
|
||||
const storyboards = await StoryboardModel.findAll<MStoryboard>(query)
|
||||
|
||||
return storyboards.map(s => Object.assign(s, { Video: video }))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
getOriginFileUrl (video: MVideo) {
|
||||
if (video.isLocal()) {
|
||||
return WEBSERVER.URL + this.getLocalStaticPath()
|
||||
}
|
||||
|
||||
return this.fileUrl
|
||||
}
|
||||
|
||||
getFileUrl () {
|
||||
return WEBSERVER.URL + this.getLocalStaticPath()
|
||||
}
|
||||
|
||||
getLocalStaticPath () {
|
||||
return LAZY_STATIC_PATHS.STORYBOARDS + this.filename
|
||||
}
|
||||
|
||||
getPath () {
|
||||
return join(CONFIG.STORAGE.STORYBOARDS_DIR, this.filename)
|
||||
}
|
||||
|
||||
removeFile () {
|
||||
return remove(this.getPath())
|
||||
}
|
||||
|
||||
toFormattedJSON (this: MStoryboardVideo): Storyboard {
|
||||
return {
|
||||
fileUrl: this.getFileUrl(),
|
||||
storyboardPath: this.getLocalStaticPath(),
|
||||
|
||||
totalHeight: this.totalHeight,
|
||||
totalWidth: this.totalWidth,
|
||||
|
||||
spriteWidth: this.spriteWidth,
|
||||
spriteHeight: this.spriteHeight,
|
||||
|
||||
spriteDuration: this.spriteDuration
|
||||
}
|
||||
}
|
||||
}
|
||||
95
server/core/models/video/tag.ts
Normal file
95
server/core/models/video/tag.ts
Normal file
@@ -0,0 +1,95 @@
|
||||
import { VideoPrivacy, VideoState } from '@peertube/peertube-models'
|
||||
import { MTag } from '@server/types/models/video/tag.js'
|
||||
import { col, fn, QueryTypes, Transaction } from 'sequelize'
|
||||
import { AllowNull, BelongsToMany, Column, Is, Table } from 'sequelize-typescript'
|
||||
import { isVideoTagValid } from '../../helpers/custom-validators/videos.js'
|
||||
import { buildSQLAttributes, SequelizeModel, throwIfNotValid } from '../shared/index.js'
|
||||
import { VideoTagModel } from './video-tag.js'
|
||||
import { VideoModel } from './video.js'
|
||||
|
||||
@Table({
|
||||
tableName: 'tag',
|
||||
timestamps: false,
|
||||
indexes: [
|
||||
{
|
||||
fields: [ 'name' ],
|
||||
unique: true
|
||||
},
|
||||
{
|
||||
name: 'tag_lower_name',
|
||||
fields: [ fn('lower', col('name')) ]
|
||||
}
|
||||
]
|
||||
})
|
||||
export class TagModel extends SequelizeModel<TagModel> {
|
||||
@AllowNull(false)
|
||||
@Is('VideoTag', value => throwIfNotValid(value, isVideoTagValid, 'tag'))
|
||||
@Column
|
||||
declare name: string
|
||||
|
||||
@BelongsToMany(() => VideoModel, {
|
||||
foreignKey: 'tagId',
|
||||
through: () => VideoTagModel,
|
||||
onDelete: 'CASCADE'
|
||||
})
|
||||
declare Videos: Awaited<VideoModel>[]
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static getSQLAttributes (tableName: string, aliasPrefix = '') {
|
||||
return buildSQLAttributes({
|
||||
model: this,
|
||||
tableName,
|
||||
aliasPrefix
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// threshold corresponds to how many video the field should have to be returned
|
||||
static getRandomSamples (threshold: number, count: number): Promise<string[]> {
|
||||
const query = 'SELECT tag.name FROM tag ' +
|
||||
'INNER JOIN "videoTag" ON "videoTag"."tagId" = tag.id ' +
|
||||
'INNER JOIN video ON video.id = "videoTag"."videoId" ' +
|
||||
'WHERE video.privacy = $videoPrivacy AND video.state = $videoState ' +
|
||||
'GROUP BY tag.name HAVING COUNT(tag.name) >= $threshold ' +
|
||||
'ORDER BY random() ' +
|
||||
'LIMIT $count'
|
||||
|
||||
const options = {
|
||||
bind: { threshold, count, videoPrivacy: VideoPrivacy.PUBLIC, videoState: VideoState.PUBLISHED },
|
||||
type: QueryTypes.SELECT as QueryTypes.SELECT
|
||||
}
|
||||
|
||||
return TagModel.sequelize.query<{ name: string }>(query, options)
|
||||
.then(data => data.map(d => d.name))
|
||||
}
|
||||
|
||||
static findOrCreateMultiple (options: {
|
||||
tags: string[]
|
||||
transaction?: Transaction
|
||||
}): Promise<MTag[]> {
|
||||
const { tags, transaction } = options
|
||||
|
||||
if (tags === null) return Promise.resolve([])
|
||||
|
||||
const uniqueTags = new Set(tags)
|
||||
|
||||
const tasks = Array.from(uniqueTags).map(tag => {
|
||||
const query = {
|
||||
where: {
|
||||
name: tag
|
||||
},
|
||||
defaults: {
|
||||
name: tag
|
||||
},
|
||||
transaction
|
||||
}
|
||||
|
||||
return this.findOrCreate(query)
|
||||
.then(([ tagInstance ]) => tagInstance)
|
||||
})
|
||||
|
||||
return Promise.all(tasks)
|
||||
}
|
||||
}
|
||||
254
server/core/models/video/thumbnail.ts
Normal file
254
server/core/models/video/thumbnail.ts
Normal file
@@ -0,0 +1,254 @@
|
||||
import { ActivityIconObject, ThumbnailType, type ThumbnailType_Type } from '@peertube/peertube-models'
|
||||
import { afterCommitIfTransaction } from '@server/helpers/database-utils.js'
|
||||
import { MThumbnail, MThumbnailVideo, MVideo, MVideoPlaylist } from '@server/types/models/index.js'
|
||||
import { remove } from 'fs-extra/esm'
|
||||
import { extname, join } from 'path'
|
||||
import {
|
||||
AfterDestroy,
|
||||
AllowNull,
|
||||
BeforeCreate,
|
||||
BeforeUpdate,
|
||||
BelongsTo,
|
||||
Column,
|
||||
CreatedAt,
|
||||
DataType,
|
||||
Default,
|
||||
ForeignKey,
|
||||
Table,
|
||||
UpdatedAt
|
||||
} from 'sequelize-typescript'
|
||||
import { logger } from '../../helpers/logger.js'
|
||||
import { CONFIG } from '../../initializers/config.js'
|
||||
import { CONSTRAINTS_FIELDS, LAZY_STATIC_PATHS, MIMETYPES, WEBSERVER } from '../../initializers/constants.js'
|
||||
import { SequelizeModel } from '../shared/sequelize-type.js'
|
||||
import { buildSQLAttributes } from '../shared/table.js'
|
||||
import { VideoPlaylistModel } from './video-playlist.js'
|
||||
import { VideoModel } from './video.js'
|
||||
|
||||
@Table({
|
||||
tableName: 'thumbnail',
|
||||
indexes: [
|
||||
{
|
||||
fields: [ 'videoId' ]
|
||||
},
|
||||
{
|
||||
fields: [ 'videoPlaylistId' ],
|
||||
unique: true
|
||||
},
|
||||
{
|
||||
fields: [ 'filename', 'type' ],
|
||||
unique: true
|
||||
}
|
||||
]
|
||||
})
|
||||
export class ThumbnailModel extends SequelizeModel<ThumbnailModel> {
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare filename: string
|
||||
|
||||
@AllowNull(true)
|
||||
@Default(null)
|
||||
@Column
|
||||
declare height: number
|
||||
|
||||
@AllowNull(true)
|
||||
@Default(null)
|
||||
@Column
|
||||
declare width: number
|
||||
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare type: ThumbnailType_Type
|
||||
|
||||
@AllowNull(true)
|
||||
@Column(DataType.STRING(CONSTRAINTS_FIELDS.COMMONS.URL.max))
|
||||
declare fileUrl: string
|
||||
|
||||
@AllowNull(true)
|
||||
@Column
|
||||
declare automaticallyGenerated: boolean
|
||||
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare onDisk: boolean
|
||||
|
||||
@ForeignKey(() => VideoModel)
|
||||
@Column
|
||||
declare videoId: number
|
||||
|
||||
@BelongsTo(() => VideoModel, {
|
||||
foreignKey: {
|
||||
allowNull: true
|
||||
},
|
||||
onDelete: 'CASCADE'
|
||||
})
|
||||
declare Video: Awaited<VideoModel>
|
||||
|
||||
@ForeignKey(() => VideoPlaylistModel)
|
||||
@Column
|
||||
declare videoPlaylistId: number
|
||||
|
||||
@BelongsTo(() => VideoPlaylistModel, {
|
||||
foreignKey: {
|
||||
allowNull: true
|
||||
},
|
||||
onDelete: 'CASCADE'
|
||||
})
|
||||
declare VideoPlaylist: Awaited<VideoPlaylistModel>
|
||||
|
||||
@CreatedAt
|
||||
declare createdAt: Date
|
||||
|
||||
@UpdatedAt
|
||||
declare updatedAt: Date
|
||||
|
||||
// If this thumbnail replaced existing one, track the old name
|
||||
previousThumbnailFilename: string
|
||||
|
||||
private static readonly types: { [id in ThumbnailType_Type]: { label: string, directory: string, staticPath: string } } = {
|
||||
[ThumbnailType.MINIATURE]: {
|
||||
label: 'miniature',
|
||||
directory: CONFIG.STORAGE.THUMBNAILS_DIR,
|
||||
staticPath: LAZY_STATIC_PATHS.THUMBNAILS
|
||||
},
|
||||
[ThumbnailType.PREVIEW]: {
|
||||
label: 'preview',
|
||||
directory: CONFIG.STORAGE.PREVIEWS_DIR,
|
||||
staticPath: LAZY_STATIC_PATHS.PREVIEWS
|
||||
}
|
||||
}
|
||||
|
||||
@BeforeCreate
|
||||
@BeforeUpdate
|
||||
static removeOldFile (instance: ThumbnailModel, options) {
|
||||
return afterCommitIfTransaction(options.transaction, () => instance.removePreviousFilenameIfNeeded())
|
||||
}
|
||||
|
||||
@AfterDestroy
|
||||
static removeFiles (instance: ThumbnailModel) {
|
||||
logger.info('Removing %s file %s.', ThumbnailModel.types[instance.type].label, instance.filename)
|
||||
|
||||
// Don't block the transaction
|
||||
instance.removeThumbnail()
|
||||
.catch(err => logger.error('Cannot remove thumbnail file %s.', instance.filename, { err }))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static getSQLAttributes (tableName: string, aliasPrefix = '') {
|
||||
return buildSQLAttributes({
|
||||
model: this,
|
||||
tableName,
|
||||
aliasPrefix
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static loadByFilename (filename: string, thumbnailType: ThumbnailType_Type): Promise<MThumbnail> {
|
||||
const query = {
|
||||
where: {
|
||||
filename,
|
||||
type: thumbnailType
|
||||
}
|
||||
}
|
||||
|
||||
return ThumbnailModel.findOne(query)
|
||||
}
|
||||
|
||||
static loadWithVideoByFilename (filename: string, thumbnailType: ThumbnailType_Type): Promise<MThumbnailVideo> {
|
||||
const query = {
|
||||
where: {
|
||||
filename,
|
||||
type: thumbnailType
|
||||
},
|
||||
include: [
|
||||
{
|
||||
model: VideoModel.unscoped(),
|
||||
required: true
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
return ThumbnailModel.findOne(query)
|
||||
}
|
||||
|
||||
static listRemoteOnDisk () {
|
||||
return this.findAll<MThumbnail>({
|
||||
where: {
|
||||
onDisk: true
|
||||
},
|
||||
include: [
|
||||
{
|
||||
attributes: [ 'id' ],
|
||||
model: VideoModel.unscoped(),
|
||||
required: true,
|
||||
where: {
|
||||
remote: true
|
||||
}
|
||||
}
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static buildPath (type: ThumbnailType_Type, filename: string) {
|
||||
const directory = ThumbnailModel.types[type].directory
|
||||
|
||||
return join(directory, filename)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
getOriginFileUrl (videoOrPlaylist: MVideo | MVideoPlaylist) {
|
||||
const staticPath = ThumbnailModel.types[this.type].staticPath + this.filename
|
||||
|
||||
// FIXME: typings
|
||||
if ((videoOrPlaylist as MVideo).isLocal()) return WEBSERVER.URL + staticPath
|
||||
|
||||
return this.fileUrl
|
||||
}
|
||||
|
||||
getLocalStaticPath () {
|
||||
return ThumbnailModel.types[this.type].staticPath + this.filename
|
||||
}
|
||||
|
||||
getPath () {
|
||||
return ThumbnailModel.buildPath(this.type, this.filename)
|
||||
}
|
||||
|
||||
getPreviousPath () {
|
||||
return ThumbnailModel.buildPath(this.type, this.previousThumbnailFilename)
|
||||
}
|
||||
|
||||
removeThumbnail () {
|
||||
return remove(this.getPath())
|
||||
}
|
||||
|
||||
removePreviousFilenameIfNeeded () {
|
||||
if (!this.previousThumbnailFilename) return
|
||||
|
||||
const previousPath = this.getPreviousPath()
|
||||
remove(previousPath)
|
||||
.catch(err => logger.error('Cannot remove previous thumbnail file %s.', previousPath, { err }))
|
||||
|
||||
this.previousThumbnailFilename = undefined
|
||||
}
|
||||
|
||||
isLocal () {
|
||||
return !this.fileUrl
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
toActivityPubObject (this: MThumbnail, video: MVideo): ActivityIconObject {
|
||||
return {
|
||||
type: 'Image',
|
||||
url: this.getOriginFileUrl(video),
|
||||
mediaType: MIMETYPES.IMAGE.EXT_MIMETYPE[extname(this.filename)],
|
||||
width: this.width,
|
||||
height: this.height
|
||||
}
|
||||
}
|
||||
}
|
||||
132
server/core/models/video/video-blacklist.ts
Normal file
132
server/core/models/video/video-blacklist.ts
Normal file
@@ -0,0 +1,132 @@
|
||||
import { VideoBlacklist, type VideoBlacklistType_Type } from '@peertube/peertube-models'
|
||||
import { MVideoBlacklist, MVideoBlacklistFormattable } from '@server/types/models/index.js'
|
||||
import { FindOptions } from 'sequelize'
|
||||
import { AllowNull, BelongsTo, Column, CreatedAt, DataType, Default, ForeignKey, Is, Table, UpdatedAt } from 'sequelize-typescript'
|
||||
import { isVideoBlacklistReasonValid, isVideoBlacklistTypeValid } from '../../helpers/custom-validators/video-blacklist.js'
|
||||
import { CONSTRAINTS_FIELDS } from '../../initializers/constants.js'
|
||||
import { SequelizeModel, getBlacklistSort, searchAttribute, throwIfNotValid } from '../shared/index.js'
|
||||
import { ThumbnailModel } from './thumbnail.js'
|
||||
import { SummaryOptions, VideoChannelModel, ScopeNames as VideoChannelScopeNames } from './video-channel.js'
|
||||
import { VideoModel } from './video.js'
|
||||
|
||||
@Table({
|
||||
tableName: 'videoBlacklist',
|
||||
indexes: [
|
||||
{
|
||||
fields: [ 'videoId' ],
|
||||
unique: true
|
||||
}
|
||||
]
|
||||
})
|
||||
export class VideoBlacklistModel extends SequelizeModel<VideoBlacklistModel> {
|
||||
@AllowNull(true)
|
||||
@Is('VideoBlacklistReason', value => throwIfNotValid(value, isVideoBlacklistReasonValid, 'reason', true))
|
||||
@Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_BLACKLIST.REASON.max))
|
||||
declare reason: string
|
||||
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare unfederated: boolean
|
||||
|
||||
@AllowNull(false)
|
||||
@Default(null)
|
||||
@Is('VideoBlacklistType', value => throwIfNotValid(value, isVideoBlacklistTypeValid, 'type'))
|
||||
@Column
|
||||
declare type: VideoBlacklistType_Type
|
||||
|
||||
@CreatedAt
|
||||
declare createdAt: Date
|
||||
|
||||
@UpdatedAt
|
||||
declare updatedAt: Date
|
||||
|
||||
@ForeignKey(() => VideoModel)
|
||||
@Column
|
||||
declare videoId: number
|
||||
|
||||
@BelongsTo(() => VideoModel, {
|
||||
foreignKey: {
|
||||
allowNull: false
|
||||
},
|
||||
onDelete: 'cascade'
|
||||
})
|
||||
declare Video: Awaited<VideoModel>
|
||||
|
||||
static listForApi (parameters: {
|
||||
start: number
|
||||
count: number
|
||||
sort: string
|
||||
search?: string
|
||||
type?: VideoBlacklistType_Type
|
||||
}) {
|
||||
const { start, count, sort, search, type } = parameters
|
||||
|
||||
function buildBaseQuery (): FindOptions {
|
||||
return {
|
||||
offset: start,
|
||||
limit: count,
|
||||
order: getBlacklistSort(sort)
|
||||
}
|
||||
}
|
||||
|
||||
const countQuery = buildBaseQuery()
|
||||
|
||||
const findQuery = buildBaseQuery()
|
||||
findQuery.include = [
|
||||
{
|
||||
model: VideoModel,
|
||||
required: true,
|
||||
where: searchAttribute(search, 'name'),
|
||||
include: [
|
||||
{
|
||||
model: VideoChannelModel.scope({ method: [ VideoChannelScopeNames.SUMMARY, { withAccount: true } as SummaryOptions ] }),
|
||||
required: true
|
||||
},
|
||||
{
|
||||
model: ThumbnailModel,
|
||||
attributes: [ 'type', 'filename' ],
|
||||
required: false
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
if (type) {
|
||||
countQuery.where = { type }
|
||||
findQuery.where = { type }
|
||||
}
|
||||
|
||||
return Promise.all([
|
||||
VideoBlacklistModel.count(countQuery),
|
||||
VideoBlacklistModel.findAll(findQuery)
|
||||
]).then(([ count, rows ]) => {
|
||||
return {
|
||||
data: rows,
|
||||
total: count
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
static loadByVideoId (id: number): Promise<MVideoBlacklist> {
|
||||
const query = {
|
||||
where: {
|
||||
videoId: id
|
||||
}
|
||||
}
|
||||
|
||||
return VideoBlacklistModel.findOne(query)
|
||||
}
|
||||
|
||||
toFormattedJSON (this: MVideoBlacklistFormattable): VideoBlacklist {
|
||||
return {
|
||||
id: this.id,
|
||||
createdAt: this.createdAt,
|
||||
updatedAt: this.updatedAt,
|
||||
reason: this.reason,
|
||||
unfederated: this.unfederated,
|
||||
type: this.type,
|
||||
|
||||
video: this.Video.toFormattedJSON()
|
||||
}
|
||||
}
|
||||
}
|
||||
419
server/core/models/video/video-caption.ts
Normal file
419
server/core/models/video/video-caption.ts
Normal file
@@ -0,0 +1,419 @@
|
||||
import { removeVTTExt } from '@peertube/peertube-core-utils'
|
||||
import { FileStorage, type FileStorageType, VideoCaption, VideoCaptionObject } from '@peertube/peertube-models'
|
||||
import { buildUUID } from '@peertube/peertube-node-utils'
|
||||
import { getObjectStoragePublicFileUrl } from '@server/lib/object-storage/urls.js'
|
||||
import { removeCaptionObjectStorage, removeHLSFileObjectStorageByFilename } from '@server/lib/object-storage/videos.js'
|
||||
import { VideoPathManager } from '@server/lib/video-path-manager.js'
|
||||
import {
|
||||
MVideo,
|
||||
MVideoCaption,
|
||||
MVideoCaptionFilename,
|
||||
MVideoCaptionFormattable,
|
||||
MVideoCaptionLanguageUrl,
|
||||
MVideoCaptionUrl,
|
||||
MVideoCaptionVideo,
|
||||
MVideoOwned,
|
||||
MVideoPrivacy
|
||||
} from '@server/types/models/index.js'
|
||||
import { remove } from 'fs-extra/esm'
|
||||
import { join } from 'path'
|
||||
import { Op, OrderItem, Transaction } from 'sequelize'
|
||||
import {
|
||||
AllowNull,
|
||||
BeforeDestroy,
|
||||
BelongsTo,
|
||||
Column,
|
||||
CreatedAt,
|
||||
DataType,
|
||||
Default,
|
||||
ForeignKey,
|
||||
Is,
|
||||
Scopes,
|
||||
Table,
|
||||
UpdatedAt
|
||||
} from 'sequelize-typescript'
|
||||
import { isVideoCaptionLanguageValid } from '../../helpers/custom-validators/video-captions.js'
|
||||
import { logger } from '../../helpers/logger.js'
|
||||
import { CONFIG } from '../../initializers/config.js'
|
||||
import { CONSTRAINTS_FIELDS, LAZY_STATIC_PATHS, VIDEO_LANGUAGES, WEBSERVER } from '../../initializers/constants.js'
|
||||
import { SequelizeModel, buildWhereIdOrUUID, doesExist, throwIfNotValid } from '../shared/index.js'
|
||||
import { VideoStreamingPlaylistModel } from './video-streaming-playlist.js'
|
||||
import { VideoModel } from './video.js'
|
||||
|
||||
export enum ScopeNames {
|
||||
CAPTION_WITH_VIDEO = 'CAPTION_WITH_VIDEO'
|
||||
}
|
||||
|
||||
const videoAttributes = [ 'id', 'name', 'remote', 'uuid', 'url', 'state', 'privacy' ]
|
||||
|
||||
@Scopes(() => ({
|
||||
[ScopeNames.CAPTION_WITH_VIDEO]: {
|
||||
include: [
|
||||
{
|
||||
attributes: videoAttributes,
|
||||
model: VideoModel.unscoped(),
|
||||
required: true
|
||||
}
|
||||
]
|
||||
}
|
||||
}))
|
||||
@Table({
|
||||
tableName: 'videoCaption',
|
||||
indexes: [
|
||||
{
|
||||
fields: [ 'filename' ],
|
||||
unique: true
|
||||
},
|
||||
{
|
||||
fields: [ 'videoId' ]
|
||||
},
|
||||
{
|
||||
fields: [ 'videoId', 'language' ],
|
||||
unique: true
|
||||
}
|
||||
]
|
||||
})
|
||||
export class VideoCaptionModel extends SequelizeModel<VideoCaptionModel> {
|
||||
@CreatedAt
|
||||
declare createdAt: Date
|
||||
|
||||
@UpdatedAt
|
||||
declare updatedAt: Date
|
||||
|
||||
@AllowNull(false)
|
||||
@Is('VideoCaptionLanguage', value => throwIfNotValid(value, isVideoCaptionLanguageValid, 'language'))
|
||||
@Column
|
||||
declare language: string
|
||||
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare filename: string
|
||||
|
||||
@AllowNull(true)
|
||||
@Column
|
||||
declare m3u8Filename: string
|
||||
|
||||
@AllowNull(false)
|
||||
@Default(FileStorage.FILE_SYSTEM)
|
||||
@Column
|
||||
declare storage: FileStorageType
|
||||
|
||||
@AllowNull(true)
|
||||
@Column(DataType.STRING(CONSTRAINTS_FIELDS.COMMONS.URL.max))
|
||||
declare fileUrl: string
|
||||
|
||||
@AllowNull(true)
|
||||
@Column
|
||||
declare m3u8Url: string
|
||||
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare automaticallyGenerated: boolean
|
||||
|
||||
@ForeignKey(() => VideoModel)
|
||||
@Column
|
||||
declare videoId: number
|
||||
|
||||
@BelongsTo(() => VideoModel, {
|
||||
foreignKey: {
|
||||
allowNull: false
|
||||
},
|
||||
onDelete: 'CASCADE'
|
||||
})
|
||||
declare Video: Awaited<VideoModel>
|
||||
|
||||
@BeforeDestroy
|
||||
static async removeFiles (instance: VideoCaptionModel, options) {
|
||||
if (!instance.Video) {
|
||||
instance.Video = await instance.$get('Video', { transaction: options.transaction })
|
||||
}
|
||||
|
||||
if (instance.isLocal()) {
|
||||
logger.info('Removing caption %s.', instance.filename)
|
||||
|
||||
instance.removeAllCaptionFiles()
|
||||
.catch(err => logger.error('Cannot remove caption file ' + instance.filename, { err }))
|
||||
}
|
||||
|
||||
return undefined
|
||||
}
|
||||
|
||||
static async insertOrReplaceLanguage (caption: MVideoCaption, transaction: Transaction) {
|
||||
const existing = await VideoCaptionModel.loadByVideoIdAndLanguage(caption.videoId, caption.language, transaction)
|
||||
|
||||
// Delete existing file
|
||||
if (existing) await existing.destroy({ transaction })
|
||||
|
||||
return caption.save({ transaction })
|
||||
}
|
||||
|
||||
static async doesOwnedFileExist (filename: string, storage: FileStorageType) {
|
||||
const query = 'SELECT 1 FROM "videoCaption" ' +
|
||||
`WHERE "filename" = $filename AND "storage" = $storage LIMIT 1`
|
||||
|
||||
return doesExist({ sequelize: this.sequelize, query, bind: { filename, storage } })
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static loadWithVideo (captionId: number, transaction?: Transaction): Promise<MVideoCaptionVideo> {
|
||||
const query = {
|
||||
where: { id: captionId },
|
||||
include: [
|
||||
{
|
||||
model: VideoModel.unscoped(),
|
||||
attributes: videoAttributes
|
||||
}
|
||||
],
|
||||
transaction
|
||||
}
|
||||
|
||||
return VideoCaptionModel.findOne(query)
|
||||
}
|
||||
|
||||
static loadByVideoIdAndLanguage (videoId: string | number, language: string, transaction?: Transaction): Promise<MVideoCaptionVideo> {
|
||||
const videoInclude = {
|
||||
model: VideoModel.unscoped(),
|
||||
attributes: videoAttributes,
|
||||
where: buildWhereIdOrUUID(videoId)
|
||||
}
|
||||
|
||||
const query = {
|
||||
where: { language },
|
||||
include: [ videoInclude ],
|
||||
transaction
|
||||
}
|
||||
|
||||
return VideoCaptionModel.findOne(query)
|
||||
}
|
||||
|
||||
static loadWithVideoByFilename (filename: string): Promise<MVideoCaptionVideo> {
|
||||
const query = {
|
||||
where: {
|
||||
filename
|
||||
},
|
||||
include: [
|
||||
{
|
||||
model: VideoModel.unscoped(),
|
||||
attributes: videoAttributes
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
return VideoCaptionModel.findOne(query)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static async hasVideoCaption (videoId: number) {
|
||||
const query = {
|
||||
where: {
|
||||
videoId
|
||||
}
|
||||
}
|
||||
|
||||
const result = await VideoCaptionModel.unscoped().findOne(query)
|
||||
|
||||
return !!result
|
||||
}
|
||||
|
||||
static listVideoCaptions (videoId: number, transaction?: Transaction): Promise<MVideoCaptionVideo[]> {
|
||||
const query = {
|
||||
order: [ [ 'language', 'ASC' ] ] as OrderItem[],
|
||||
where: {
|
||||
videoId
|
||||
},
|
||||
transaction
|
||||
}
|
||||
|
||||
return VideoCaptionModel.scope(ScopeNames.CAPTION_WITH_VIDEO).findAll(query)
|
||||
}
|
||||
|
||||
static async listCaptionsOfMultipleVideos (videoIds: number[], transaction?: Transaction) {
|
||||
const query = {
|
||||
order: [ [ 'language', 'ASC' ] ] as OrderItem[],
|
||||
where: {
|
||||
videoId: {
|
||||
[Op.in]: videoIds
|
||||
}
|
||||
},
|
||||
transaction
|
||||
}
|
||||
|
||||
const captions = await VideoCaptionModel.scope(ScopeNames.CAPTION_WITH_VIDEO).findAll<MVideoCaptionVideo>(query)
|
||||
const result: { [id: number]: MVideoCaptionVideo[] } = {}
|
||||
|
||||
for (const id of videoIds) {
|
||||
result[id] = []
|
||||
}
|
||||
|
||||
for (const caption of captions) {
|
||||
result[caption.videoId].push(caption)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static getLanguageLabel (language: string) {
|
||||
return VIDEO_LANGUAGES[language] || 'Unknown'
|
||||
}
|
||||
|
||||
static generateCaptionName (language: string) {
|
||||
return `${buildUUID()}-${language}.vtt`
|
||||
}
|
||||
|
||||
static generateM3U8Filename (vttFilename: string) {
|
||||
return removeVTTExt(vttFilename) + '.m3u8'
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
toFormattedJSON (this: MVideoCaptionFormattable): VideoCaption {
|
||||
return {
|
||||
language: {
|
||||
id: this.language,
|
||||
label: VideoCaptionModel.getLanguageLabel(this.language)
|
||||
},
|
||||
automaticallyGenerated: this.automaticallyGenerated,
|
||||
|
||||
// TODO: remove, deprecated in 8.0
|
||||
captionPath: this.Video.isLocal() && this.fileUrl
|
||||
? null // On object storage
|
||||
: this.getFileStaticPath(),
|
||||
|
||||
fileUrl: this.getFileUrl(this.Video),
|
||||
m3u8Url: this.getM3U8Url(this.Video),
|
||||
|
||||
updatedAt: this.updatedAt.toISOString()
|
||||
}
|
||||
}
|
||||
|
||||
toActivityPubObject (this: MVideoCaptionLanguageUrl, video: MVideo): VideoCaptionObject {
|
||||
return {
|
||||
identifier: this.language,
|
||||
name: VideoCaptionModel.getLanguageLabel(this.language),
|
||||
automaticallyGenerated: this.automaticallyGenerated,
|
||||
|
||||
url: [
|
||||
{
|
||||
type: 'Link',
|
||||
mediaType: 'text/vtt',
|
||||
href: this.getOriginFileUrl(video)
|
||||
},
|
||||
{
|
||||
type: 'Link',
|
||||
mediaType: 'application/x-mpegURL',
|
||||
href: this.getOriginFileUrl(video)
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
isLocal () {
|
||||
return this.Video.remote === false
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
getFileStaticPath (this: MVideoCaptionFilename) {
|
||||
return join(LAZY_STATIC_PATHS.VIDEO_CAPTIONS, this.filename)
|
||||
}
|
||||
|
||||
getM3U8StaticPath (this: MVideoCaptionFilename, video: MVideoPrivacy) {
|
||||
if (!this.m3u8Filename) return null
|
||||
|
||||
return VideoStreamingPlaylistModel.getPlaylistFileStaticPath(video, this.m3u8Filename)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
getFSFilePath () {
|
||||
return join(CONFIG.STORAGE.CAPTIONS_DIR, this.filename)
|
||||
}
|
||||
|
||||
getFSM3U8Path (video: MVideoPrivacy) {
|
||||
if (!this.m3u8Filename) return null
|
||||
|
||||
return VideoPathManager.Instance.getFSHLSOutputPath(video, this.m3u8Filename)
|
||||
}
|
||||
|
||||
async removeAllCaptionFiles (this: MVideoCaptionVideo) {
|
||||
await this.removeCaptionFile()
|
||||
await this.removeCaptionPlaylist()
|
||||
}
|
||||
|
||||
async removeCaptionFile (this: MVideoCaptionVideo) {
|
||||
if (this.storage === FileStorage.OBJECT_STORAGE) {
|
||||
if (this.fileUrl) {
|
||||
await removeCaptionObjectStorage(this)
|
||||
}
|
||||
} else {
|
||||
await remove(this.getFSFilePath())
|
||||
}
|
||||
|
||||
this.filename = null
|
||||
this.fileUrl = null
|
||||
}
|
||||
|
||||
async removeCaptionPlaylist (this: MVideoCaptionVideo) {
|
||||
if (!this.m3u8Filename) return
|
||||
|
||||
const hls = await VideoStreamingPlaylistModel.loadHLSByVideoWithVideo(this.videoId)
|
||||
if (!hls) return
|
||||
|
||||
if (this.storage === FileStorage.OBJECT_STORAGE) {
|
||||
if (this.m3u8Url) {
|
||||
await removeHLSFileObjectStorageByFilename(hls, this.m3u8Filename)
|
||||
}
|
||||
} else {
|
||||
await remove(this.getFSM3U8Path(this.Video))
|
||||
}
|
||||
|
||||
this.m3u8Filename = null
|
||||
this.m3u8Url = null
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
getFileUrl (this: MVideoCaptionUrl, video: MVideoOwned) {
|
||||
if (video.isLocal() && this.storage === FileStorage.OBJECT_STORAGE) {
|
||||
return getObjectStoragePublicFileUrl(this.fileUrl, CONFIG.OBJECT_STORAGE.CAPTIONS)
|
||||
}
|
||||
|
||||
return WEBSERVER.URL + this.getFileStaticPath()
|
||||
}
|
||||
|
||||
getOriginFileUrl (this: MVideoCaptionUrl, video: MVideoOwned) {
|
||||
if (video.isLocal()) return this.getFileUrl(video)
|
||||
|
||||
return this.fileUrl
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
getM3U8Url (this: MVideoCaptionUrl, video: MVideoOwned & MVideoPrivacy) {
|
||||
if (!this.m3u8Filename) return null
|
||||
|
||||
if (video.isLocal()) {
|
||||
if (this.storage === FileStorage.OBJECT_STORAGE) {
|
||||
return getObjectStoragePublicFileUrl(this.m3u8Url, CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS)
|
||||
}
|
||||
|
||||
return WEBSERVER.URL + this.getM3U8StaticPath(video)
|
||||
}
|
||||
|
||||
return this.m3u8Url
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
isEqual (this: MVideoCaption, other: MVideoCaption) {
|
||||
if (this.fileUrl) return this.fileUrl === other.fileUrl
|
||||
|
||||
return this.filename === other.filename
|
||||
}
|
||||
}
|
||||
136
server/core/models/video/video-change-ownership.ts
Normal file
136
server/core/models/video/video-change-ownership.ts
Normal file
@@ -0,0 +1,136 @@
|
||||
import { VideoChangeOwnership, type VideoChangeOwnershipStatusType } from '@peertube/peertube-models'
|
||||
import { MVideoChangeOwnershipFormattable, MVideoChangeOwnershipFull } from '@server/types/models/video/video-change-ownership.js'
|
||||
import { AllowNull, BelongsTo, Column, CreatedAt, ForeignKey, Scopes, Table, UpdatedAt } from 'sequelize-typescript'
|
||||
import { AccountModel } from '../account/account.js'
|
||||
import { SequelizeModel, getSort } from '../shared/index.js'
|
||||
import { VideoModel, ScopeNames as VideoScopeNames } from './video.js'
|
||||
|
||||
enum ScopeNames {
|
||||
WITH_ACCOUNTS = 'WITH_ACCOUNTS',
|
||||
WITH_VIDEO = 'WITH_VIDEO'
|
||||
}
|
||||
|
||||
@Table({
|
||||
tableName: 'videoChangeOwnership',
|
||||
indexes: [
|
||||
{
|
||||
fields: [ 'videoId' ]
|
||||
},
|
||||
{
|
||||
fields: [ 'initiatorAccountId' ]
|
||||
},
|
||||
{
|
||||
fields: [ 'nextOwnerAccountId' ]
|
||||
}
|
||||
]
|
||||
})
|
||||
@Scopes(() => ({
|
||||
[ScopeNames.WITH_ACCOUNTS]: {
|
||||
include: [
|
||||
{
|
||||
model: AccountModel,
|
||||
as: 'Initiator',
|
||||
required: true
|
||||
},
|
||||
{
|
||||
model: AccountModel,
|
||||
as: 'NextOwner',
|
||||
required: true
|
||||
}
|
||||
]
|
||||
},
|
||||
[ScopeNames.WITH_VIDEO]: {
|
||||
include: [
|
||||
{
|
||||
model: VideoModel.scope([
|
||||
VideoScopeNames.WITH_THUMBNAILS,
|
||||
VideoScopeNames.WITH_WEB_VIDEO_FILES,
|
||||
VideoScopeNames.WITH_STREAMING_PLAYLISTS,
|
||||
VideoScopeNames.WITH_ACCOUNT_DETAILS
|
||||
]),
|
||||
required: true
|
||||
}
|
||||
]
|
||||
}
|
||||
}))
|
||||
export class VideoChangeOwnershipModel extends SequelizeModel<VideoChangeOwnershipModel> {
|
||||
@CreatedAt
|
||||
declare createdAt: Date
|
||||
|
||||
@UpdatedAt
|
||||
declare updatedAt: Date
|
||||
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare status: VideoChangeOwnershipStatusType
|
||||
|
||||
@ForeignKey(() => AccountModel)
|
||||
@Column
|
||||
declare initiatorAccountId: number
|
||||
|
||||
@BelongsTo(() => AccountModel, {
|
||||
foreignKey: {
|
||||
name: 'initiatorAccountId',
|
||||
allowNull: false
|
||||
},
|
||||
onDelete: 'cascade'
|
||||
})
|
||||
declare Initiator: Awaited<AccountModel>
|
||||
|
||||
@ForeignKey(() => AccountModel)
|
||||
@Column
|
||||
declare nextOwnerAccountId: number
|
||||
|
||||
@BelongsTo(() => AccountModel, {
|
||||
foreignKey: {
|
||||
name: 'nextOwnerAccountId',
|
||||
allowNull: false
|
||||
},
|
||||
onDelete: 'cascade'
|
||||
})
|
||||
declare NextOwner: Awaited<AccountModel>
|
||||
|
||||
@ForeignKey(() => VideoModel)
|
||||
@Column
|
||||
declare videoId: number
|
||||
|
||||
@BelongsTo(() => VideoModel, {
|
||||
foreignKey: {
|
||||
allowNull: false
|
||||
},
|
||||
onDelete: 'cascade'
|
||||
})
|
||||
declare Video: Awaited<VideoModel>
|
||||
|
||||
static listForApi (nextOwnerId: number, start: number, count: number, sort: string) {
|
||||
const query = {
|
||||
offset: start,
|
||||
limit: count,
|
||||
order: getSort(sort),
|
||||
where: {
|
||||
nextOwnerAccountId: nextOwnerId
|
||||
}
|
||||
}
|
||||
|
||||
return Promise.all([
|
||||
VideoChangeOwnershipModel.count(query),
|
||||
VideoChangeOwnershipModel.scope([ ScopeNames.WITH_ACCOUNTS, ScopeNames.WITH_VIDEO ]).findAll<MVideoChangeOwnershipFull>(query)
|
||||
]).then(([ count, rows ]) => ({ total: count, data: rows }))
|
||||
}
|
||||
|
||||
static load (id: number): Promise<MVideoChangeOwnershipFull> {
|
||||
return VideoChangeOwnershipModel.scope([ ScopeNames.WITH_ACCOUNTS, ScopeNames.WITH_VIDEO ])
|
||||
.findByPk(id)
|
||||
}
|
||||
|
||||
toFormattedJSON (this: MVideoChangeOwnershipFormattable): VideoChangeOwnership {
|
||||
return {
|
||||
id: this.id,
|
||||
status: this.status,
|
||||
initiatorAccount: this.Initiator.toFormattedJSON(),
|
||||
nextOwnerAccount: this.NextOwner.toFormattedJSON(),
|
||||
video: this.Video.toFormattedJSON(),
|
||||
createdAt: this.createdAt
|
||||
}
|
||||
}
|
||||
}
|
||||
508
server/core/models/video/video-channel-activity.ts
Normal file
508
server/core/models/video/video-channel-activity.ts
Normal file
@@ -0,0 +1,508 @@
|
||||
import {
|
||||
ResultList,
|
||||
VideoChannelActivityAction,
|
||||
VideoChannelActivityTarget,
|
||||
type VideoChannelActivity,
|
||||
type VideoChannelActivityActionType,
|
||||
type VideoChannelActivityDetails,
|
||||
type VideoChannelActivityTargetType
|
||||
} from '@peertube/peertube-models'
|
||||
import { uuidToShort } from '@peertube/peertube-node-utils'
|
||||
import { VIDEO_CHANNEL_ACTIVITY_ACTIONS, VIDEO_CHANNEL_ACTIVITY_TARGETS } from '@server/initializers/constants.js'
|
||||
import { MChannelId, MChannelSync, MUserAccountId, MVideo, MVideoImport, MVideoPlaylist } from '@server/types/models/index.js'
|
||||
import { MChannelActivityFormattable } from '@server/types/models/video/video-channel-activity.js'
|
||||
import { Op, Transaction } from 'sequelize'
|
||||
import { AllowNull, BelongsTo, Column, CreatedAt, DataType, ForeignKey, Table, UpdatedAt } from 'sequelize-typescript'
|
||||
import { AccountModel } from '../account/account.js'
|
||||
import { ActorModel } from '../actor/actor.js'
|
||||
import { getSort, SequelizeModel } from '../shared/index.js'
|
||||
import { VideoChannelSyncModel } from './video-channel-sync.js'
|
||||
import { VideoChannelModel } from './video-channel.js'
|
||||
import { VideoImportModel } from './video-import.js'
|
||||
import { VideoPlaylistModel } from './video-playlist.js'
|
||||
import { VideoModel } from './video.js'
|
||||
|
||||
interface VideoChannelActivityData {
|
||||
video?: {
|
||||
id: number
|
||||
name: string
|
||||
uuid: string
|
||||
url: string
|
||||
isLive: boolean
|
||||
}
|
||||
|
||||
videoImport?: {
|
||||
id: number
|
||||
name: string
|
||||
uuid: string
|
||||
url: string
|
||||
targetUrl: string
|
||||
}
|
||||
|
||||
playlist?: {
|
||||
id: number
|
||||
name: string
|
||||
uuid: string
|
||||
url: string
|
||||
}
|
||||
|
||||
channel?: {
|
||||
id: number
|
||||
name: string
|
||||
displayName: string
|
||||
url: string
|
||||
}
|
||||
|
||||
channelSync?: {
|
||||
id: number
|
||||
externalChannelUrl: string
|
||||
}
|
||||
}
|
||||
|
||||
@Table({
|
||||
tableName: 'videoChannelActivity',
|
||||
indexes: [
|
||||
{
|
||||
fields: [ 'videoChannelId' ]
|
||||
},
|
||||
{
|
||||
fields: [ 'accountId' ]
|
||||
},
|
||||
{
|
||||
fields: [ 'videoId' ],
|
||||
where: {
|
||||
videoId: {
|
||||
[Op.ne]: null
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
fields: [ 'videoPlaylistId' ],
|
||||
where: {
|
||||
videoPlaylistId: {
|
||||
[Op.ne]: null
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
fields: [ 'videoChannelSyncId' ],
|
||||
where: {
|
||||
videoChannelSyncId: {
|
||||
[Op.ne]: null
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
fields: [ 'videoImportId' ],
|
||||
where: {
|
||||
videoImportId: {
|
||||
[Op.ne]: null
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
})
|
||||
export class VideoChannelActivityModel extends SequelizeModel<VideoChannelActivityModel> {
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare action: VideoChannelActivityActionType
|
||||
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare targetType: VideoChannelActivityTargetType
|
||||
|
||||
// Store association data in case they are deleted
|
||||
@AllowNull(false)
|
||||
@Column(DataType.JSONB)
|
||||
declare data: VideoChannelActivityData
|
||||
|
||||
// More information about the action
|
||||
@AllowNull(true)
|
||||
@Column(DataType.JSONB)
|
||||
declare details: VideoChannelActivityDetails
|
||||
|
||||
@CreatedAt
|
||||
declare createdAt: Date
|
||||
|
||||
@UpdatedAt
|
||||
declare updatedAt: Date
|
||||
|
||||
@ForeignKey(() => VideoChannelModel)
|
||||
@Column
|
||||
declare videoChannelId: number
|
||||
|
||||
@BelongsTo(() => VideoChannelModel, {
|
||||
foreignKey: {
|
||||
allowNull: false
|
||||
},
|
||||
onDelete: 'cascade'
|
||||
})
|
||||
declare VideoChannel: Awaited<VideoChannelModel>
|
||||
|
||||
@ForeignKey(() => AccountModel)
|
||||
@Column
|
||||
declare accountId: number
|
||||
|
||||
@BelongsTo(() => AccountModel, {
|
||||
foreignKey: {
|
||||
allowNull: true
|
||||
},
|
||||
onDelete: 'set null'
|
||||
})
|
||||
declare Account: Awaited<AccountModel>
|
||||
|
||||
@ForeignKey(() => VideoModel)
|
||||
@Column
|
||||
declare videoId: number
|
||||
|
||||
@BelongsTo(() => VideoModel, {
|
||||
foreignKey: {
|
||||
allowNull: true
|
||||
},
|
||||
onDelete: 'set null'
|
||||
})
|
||||
declare Video: Awaited<VideoModel>
|
||||
|
||||
@ForeignKey(() => VideoPlaylistModel)
|
||||
@Column
|
||||
declare videoPlaylistId: number
|
||||
|
||||
@BelongsTo(() => VideoPlaylistModel, {
|
||||
foreignKey: {
|
||||
allowNull: true
|
||||
},
|
||||
onDelete: 'set null'
|
||||
})
|
||||
declare VideoPlaylist: Awaited<VideoPlaylistModel>
|
||||
|
||||
@ForeignKey(() => VideoChannelSyncModel)
|
||||
@Column
|
||||
declare videoChannelSyncId: number
|
||||
|
||||
@BelongsTo(() => VideoChannelSyncModel, {
|
||||
foreignKey: {
|
||||
allowNull: true
|
||||
},
|
||||
onDelete: 'set null'
|
||||
})
|
||||
declare VideoChannelSync: Awaited<VideoChannelSyncModel>
|
||||
|
||||
@ForeignKey(() => VideoImportModel)
|
||||
@Column
|
||||
declare videoImportId: number
|
||||
|
||||
@BelongsTo(() => VideoImportModel, {
|
||||
foreignKey: {
|
||||
allowNull: true
|
||||
},
|
||||
onDelete: 'set null'
|
||||
})
|
||||
declare VideoImport: Awaited<VideoImportModel>
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static async listForAPI (options: {
|
||||
channelId: number
|
||||
start: number
|
||||
count: number
|
||||
sort: string
|
||||
}): Promise<ResultList<MChannelActivityFormattable>> {
|
||||
const where = { videoChannelId: options.channelId }
|
||||
|
||||
const countQuery = VideoChannelActivityModel.count({ where })
|
||||
const dataQuery = VideoChannelActivityModel.findAll({
|
||||
where,
|
||||
offset: options.start,
|
||||
limit: options.count,
|
||||
order: getSort(options.sort),
|
||||
include: [
|
||||
{
|
||||
model: VideoChannelModel.unscoped(),
|
||||
required: true,
|
||||
include: [
|
||||
{
|
||||
attributes: [ 'preferredUsername', 'url' ],
|
||||
model: ActorModel.unscoped()
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
model: AccountModel,
|
||||
required: false
|
||||
},
|
||||
{
|
||||
model: VideoModel.unscoped(),
|
||||
required: false
|
||||
},
|
||||
{
|
||||
model: VideoPlaylistModel.unscoped(),
|
||||
required: false
|
||||
},
|
||||
{
|
||||
model: VideoChannelSyncModel.unscoped(),
|
||||
required: false
|
||||
},
|
||||
{
|
||||
model: VideoImportModel.unscoped(),
|
||||
required: false,
|
||||
include: [
|
||||
{
|
||||
model: VideoModel.unscoped(),
|
||||
required: false
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
})
|
||||
|
||||
const [ total, data ] = await Promise.all([ countQuery, dataQuery ])
|
||||
|
||||
return { total, data }
|
||||
}
|
||||
|
||||
static async addVideoActivity (options: {
|
||||
action: VideoChannelActivityActionType
|
||||
user: MUserAccountId
|
||||
channel: MChannelId
|
||||
video: MVideo
|
||||
transaction: Transaction
|
||||
}) {
|
||||
const { action, user, channel, video, transaction } = options
|
||||
|
||||
return this.create({
|
||||
action,
|
||||
targetType: VideoChannelActivityTarget.VIDEO,
|
||||
data: {
|
||||
video: {
|
||||
id: video.id,
|
||||
name: video.name,
|
||||
uuid: video.uuid,
|
||||
url: video.url,
|
||||
isLive: video.isLive
|
||||
}
|
||||
},
|
||||
details: null,
|
||||
accountId: user.Account.id,
|
||||
videoChannelId: channel.id,
|
||||
videoId: action !== VideoChannelActivityAction.DELETE
|
||||
? video.id
|
||||
: null
|
||||
}, { transaction })
|
||||
}
|
||||
|
||||
static async addVideoImportActivity (options: {
|
||||
action: VideoChannelActivityActionType
|
||||
user: MUserAccountId
|
||||
channel: MChannelId
|
||||
videoImport: MVideoImport
|
||||
video: MVideo
|
||||
transaction: Transaction
|
||||
}) {
|
||||
const { action, user, channel, video, videoImport, transaction } = options
|
||||
|
||||
return this.create({
|
||||
action,
|
||||
targetType: VideoChannelActivityTarget.VIDEO_IMPORT,
|
||||
data: {
|
||||
videoImport: {
|
||||
id: video.id,
|
||||
name: video.name,
|
||||
uuid: video.uuid,
|
||||
url: video.url,
|
||||
targetUrl: videoImport.targetUrl
|
||||
}
|
||||
},
|
||||
details: null,
|
||||
accountId: user.Account.id,
|
||||
videoChannelId: channel.id,
|
||||
videoImportId: action !== VideoChannelActivityAction.DELETE
|
||||
? videoImport.id
|
||||
: null
|
||||
}, { transaction })
|
||||
}
|
||||
|
||||
static async addChannelActivity (options: {
|
||||
action: VideoChannelActivityActionType
|
||||
user: MUserAccountId
|
||||
channel: MChannelActivityFormattable['VideoChannel']
|
||||
transaction: Transaction
|
||||
}) {
|
||||
const { action, user, channel, transaction } = options
|
||||
|
||||
return this.create({
|
||||
action,
|
||||
targetType: VideoChannelActivityTarget.CHANNEL,
|
||||
data: {
|
||||
channel: {
|
||||
id: channel.id,
|
||||
name: channel.Actor.preferredUsername,
|
||||
displayName: channel.name,
|
||||
url: channel.Actor.url
|
||||
}
|
||||
},
|
||||
details: null,
|
||||
accountId: user.Account.id,
|
||||
videoChannelId: channel.id
|
||||
}, { transaction })
|
||||
}
|
||||
|
||||
static async addPlaylistActivity (options: {
|
||||
action: VideoChannelActivityActionType
|
||||
user: MUserAccountId
|
||||
channel: MChannelId
|
||||
playlist: MVideoPlaylist
|
||||
transaction: Transaction
|
||||
}) {
|
||||
const { action, user, channel, playlist, transaction } = options
|
||||
|
||||
return this.create({
|
||||
action,
|
||||
targetType: VideoChannelActivityTarget.PLAYLIST,
|
||||
data: {
|
||||
playlist: {
|
||||
id: playlist.id,
|
||||
name: playlist.name,
|
||||
uuid: playlist.uuid,
|
||||
url: playlist.url
|
||||
}
|
||||
},
|
||||
details: null,
|
||||
accountId: user.Account.id,
|
||||
videoChannelId: channel.id,
|
||||
videoPlaylistId: action !== VideoChannelActivityAction.DELETE
|
||||
? playlist.id
|
||||
: null
|
||||
}, { transaction })
|
||||
}
|
||||
|
||||
static async addChannelSyncActivity (options: {
|
||||
action: VideoChannelActivityActionType
|
||||
user: MUserAccountId
|
||||
channel: MChannelId
|
||||
sync: MChannelSync
|
||||
transaction: Transaction
|
||||
}) {
|
||||
const { action, user, channel, sync, transaction } = options
|
||||
|
||||
return this.create({
|
||||
action,
|
||||
targetType: VideoChannelActivityTarget.CHANNEL_SYNC,
|
||||
data: {
|
||||
channelSync: {
|
||||
id: sync.id,
|
||||
externalChannelUrl: sync.externalChannelUrl
|
||||
}
|
||||
},
|
||||
details: null,
|
||||
accountId: user.Account.id,
|
||||
videoChannelId: channel.id,
|
||||
videoChannelSyncId: action !== VideoChannelActivityAction.DELETE
|
||||
? sync.id
|
||||
: null
|
||||
}, { transaction })
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
toFormattedJSON (this: MChannelActivityFormattable): VideoChannelActivity {
|
||||
return {
|
||||
id: this.id,
|
||||
|
||||
account: this.Account
|
||||
? this.Account.toFormattedSummaryJSON()
|
||||
: null,
|
||||
|
||||
action: {
|
||||
id: this.action,
|
||||
label: VIDEO_CHANNEL_ACTIVITY_ACTIONS[this.action]
|
||||
},
|
||||
|
||||
targetType: {
|
||||
id: this.targetType,
|
||||
label: VIDEO_CHANNEL_ACTIVITY_TARGETS[this.targetType]
|
||||
},
|
||||
|
||||
video: this.formatVideo(),
|
||||
playlist: this.formatPlaylist(),
|
||||
channel: this.formatChannel(),
|
||||
channelSync: this.formatSync(),
|
||||
videoImport: this.formatVideoImport(),
|
||||
|
||||
details: this.details,
|
||||
createdAt: this.createdAt
|
||||
}
|
||||
}
|
||||
|
||||
formatChannel (this: MChannelActivityFormattable): VideoChannelActivity['channel'] {
|
||||
return {
|
||||
id: this.VideoChannel.id,
|
||||
name: this.VideoChannel.Actor.preferredUsername,
|
||||
displayName: this.VideoChannel.name,
|
||||
url: this.VideoChannel.Actor.url
|
||||
}
|
||||
}
|
||||
|
||||
formatVideo (this: MChannelActivityFormattable): VideoChannelActivity['video'] {
|
||||
if (this.targetType !== VideoChannelActivityTarget.VIDEO) return null
|
||||
|
||||
const target = this.Video || this.data.video
|
||||
|
||||
return {
|
||||
id: target.id,
|
||||
name: target.name,
|
||||
uuid: target.uuid,
|
||||
shortUUID: uuidToShort(target.uuid),
|
||||
isLive: target.isLive,
|
||||
url: target.url
|
||||
}
|
||||
}
|
||||
|
||||
formatVideoImport (this: MChannelActivityFormattable): VideoChannelActivity['videoImport'] {
|
||||
if (this.targetType !== VideoChannelActivityTarget.VIDEO_IMPORT) return null
|
||||
|
||||
if (this.VideoImport && this.VideoImport.Video) {
|
||||
return {
|
||||
id: this.VideoImport.id,
|
||||
name: this.VideoImport.Video.name,
|
||||
uuid: this.VideoImport.Video.uuid,
|
||||
shortUUID: uuidToShort(this.VideoImport.Video.uuid),
|
||||
url: this.VideoImport.Video.url,
|
||||
targetUrl: this.VideoImport.targetUrl
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
id: this.data.videoImport.id,
|
||||
name: this.data.videoImport.name,
|
||||
uuid: this.data.videoImport.uuid,
|
||||
shortUUID: uuidToShort(this.data.videoImport.uuid),
|
||||
url: this.data.videoImport.url,
|
||||
targetUrl: this.data.videoImport.targetUrl
|
||||
}
|
||||
}
|
||||
|
||||
formatPlaylist (this: MChannelActivityFormattable): VideoChannelActivity['playlist'] {
|
||||
if (this.targetType !== VideoChannelActivityTarget.PLAYLIST) return null
|
||||
|
||||
const target = this.VideoPlaylist || this.data.playlist
|
||||
|
||||
return {
|
||||
id: target.id,
|
||||
name: target.name,
|
||||
uuid: target.uuid,
|
||||
shortUUID: uuidToShort(target.uuid),
|
||||
url: target.url
|
||||
}
|
||||
}
|
||||
|
||||
formatSync (): VideoChannelActivity['channelSync'] {
|
||||
if (this.targetType !== VideoChannelActivityTarget.CHANNEL_SYNC) return null
|
||||
|
||||
const target = this.VideoChannelSync || this.data.channelSync
|
||||
|
||||
return {
|
||||
id: target.id,
|
||||
externalChannelUrl: target.externalChannelUrl
|
||||
}
|
||||
}
|
||||
}
|
||||
213
server/core/models/video/video-channel-collaborator.ts
Normal file
213
server/core/models/video/video-channel-collaborator.ts
Normal file
@@ -0,0 +1,213 @@
|
||||
import {
|
||||
VideoChannelCollaboratorState,
|
||||
type VideoChannelCollaborator,
|
||||
type VideoChannelCollaboratorStateType
|
||||
} from '@peertube/peertube-models'
|
||||
import { CHANNEL_COLLABORATOR_STATE } from '@server/initializers/constants.js'
|
||||
import { MChannelCollaboratorAccount, MChannelId, MUserId } from '@server/types/models/index.js'
|
||||
import { AllowNull, BelongsTo, Column, CreatedAt, ForeignKey, Scopes, Table, UpdatedAt } from 'sequelize-typescript'
|
||||
import { AccountModel } from '../account/account.js'
|
||||
import { ActorModel } from '../actor/actor.js'
|
||||
import { SequelizeModel, buildSQLAttributes, doesExist, getSort } from '../shared/index.js'
|
||||
import { VideoChannelModel } from './video-channel.js'
|
||||
import { Op } from 'sequelize'
|
||||
|
||||
enum ScopeNames {
|
||||
WITH_ACCOUNT = 'WITH_ACCOUNT'
|
||||
}
|
||||
|
||||
@Table({
|
||||
tableName: 'videoChannelCollaborator',
|
||||
indexes: [
|
||||
{
|
||||
fields: [ 'channelId', 'accountId' ],
|
||||
unique: true
|
||||
}
|
||||
]
|
||||
})
|
||||
@Scopes(() => ({
|
||||
[ScopeNames.WITH_ACCOUNT]: {
|
||||
include: [
|
||||
{
|
||||
model: AccountModel,
|
||||
required: true
|
||||
}
|
||||
]
|
||||
}
|
||||
}))
|
||||
export class VideoChannelCollaboratorModel extends SequelizeModel<VideoChannelCollaboratorModel> {
|
||||
@CreatedAt
|
||||
declare createdAt: Date
|
||||
|
||||
@UpdatedAt
|
||||
declare updatedAt: Date
|
||||
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare state: VideoChannelCollaboratorStateType
|
||||
|
||||
@ForeignKey(() => AccountModel)
|
||||
@Column
|
||||
declare accountId: number
|
||||
|
||||
@BelongsTo(() => AccountModel, {
|
||||
foreignKey: {
|
||||
name: 'accountId',
|
||||
allowNull: false
|
||||
},
|
||||
onDelete: 'cascade'
|
||||
})
|
||||
declare Account: Awaited<AccountModel>
|
||||
|
||||
@ForeignKey(() => AccountModel)
|
||||
@Column
|
||||
declare channelId: number
|
||||
|
||||
@BelongsTo(() => VideoChannelModel, {
|
||||
foreignKey: {
|
||||
name: 'channelId',
|
||||
allowNull: false
|
||||
},
|
||||
onDelete: 'cascade'
|
||||
})
|
||||
declare Channel: Awaited<VideoChannelModel>
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static getSQLAttributes (tableName: string, aliasPrefix = '') {
|
||||
return buildSQLAttributes({
|
||||
model: this,
|
||||
tableName,
|
||||
aliasPrefix
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static listForApi (options: {
|
||||
channelId: number
|
||||
start: number
|
||||
count: number
|
||||
sort: string
|
||||
}) {
|
||||
const { channelId, start, count, sort } = options
|
||||
|
||||
const query = {
|
||||
offset: start,
|
||||
limit: count,
|
||||
order: getSort(sort),
|
||||
where: {
|
||||
channelId,
|
||||
state: {
|
||||
[Op.ne]: VideoChannelCollaboratorState.REJECTED
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Promise.all([
|
||||
VideoChannelCollaboratorModel.count(query),
|
||||
VideoChannelCollaboratorModel.scope([ ScopeNames.WITH_ACCOUNT ]).findAll<MChannelCollaboratorAccount>(query)
|
||||
]).then(([ count, rows ]) => ({ total: count, data: rows }))
|
||||
}
|
||||
|
||||
static countByChannel (channelId: number): Promise<number> {
|
||||
const query = {
|
||||
where: {
|
||||
channelId
|
||||
}
|
||||
}
|
||||
|
||||
return VideoChannelCollaboratorModel.count(query)
|
||||
}
|
||||
|
||||
static loadByChannelHandle (id: number, channelHandle: string): Promise<MChannelCollaboratorAccount> {
|
||||
return VideoChannelCollaboratorModel
|
||||
.scope([ ScopeNames.WITH_ACCOUNT ])
|
||||
.findOne({
|
||||
where: { id },
|
||||
include: [
|
||||
{
|
||||
model: VideoChannelModel.unscoped(),
|
||||
attributes: [ 'id' ],
|
||||
required: true,
|
||||
include: [
|
||||
{
|
||||
model: ActorModel.unscoped(),
|
||||
required: true,
|
||||
where: {
|
||||
preferredUsername: channelHandle
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
static loadByCollaboratorAccountName (options: {
|
||||
channelId: number
|
||||
accountName: string
|
||||
}): Promise<MChannelCollaboratorAccount | null> {
|
||||
const { channelId, accountName } = options
|
||||
|
||||
return VideoChannelCollaboratorModel.findOne({
|
||||
where: {
|
||||
channelId
|
||||
},
|
||||
include: [
|
||||
{
|
||||
model: AccountModel.unscoped(),
|
||||
required: true,
|
||||
include: [
|
||||
{
|
||||
model: ActorModel.unscoped(),
|
||||
required: true,
|
||||
where: {
|
||||
preferredUsername: accountName
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
static async isCollaborator (options: {
|
||||
user: MUserId
|
||||
channel: MChannelId
|
||||
}): Promise<boolean> {
|
||||
const { user, channel } = options
|
||||
|
||||
const query = `SELECT 1 FROM "videoChannelCollaborator" ` +
|
||||
`INNER JOIN "account" ON "account"."id" = "videoChannelCollaborator"."accountId" AND account."userId" = $userId ` +
|
||||
`WHERE "videoChannelCollaborator"."channelId" = $channelId AND "state" = $state ` +
|
||||
`LIMIT 1`
|
||||
|
||||
return doesExist({
|
||||
sequelize: this.sequelize,
|
||||
query,
|
||||
bind: { userId: user.id, channelId: channel.id, state: VideoChannelCollaboratorState.ACCEPTED }
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static getStateLabel (state: VideoChannelCollaboratorStateType) {
|
||||
return CHANNEL_COLLABORATOR_STATE[state]
|
||||
}
|
||||
|
||||
toFormattedJSON (this: MChannelCollaboratorAccount): VideoChannelCollaborator {
|
||||
return {
|
||||
id: this.id,
|
||||
|
||||
state: {
|
||||
id: this.state,
|
||||
label: VideoChannelCollaboratorModel.getStateLabel(this.state)
|
||||
},
|
||||
|
||||
account: this.Account.toFormattedJSON(),
|
||||
updatedAt: this.updatedAt.toISOString(),
|
||||
createdAt: this.createdAt.toISOString()
|
||||
}
|
||||
}
|
||||
}
|
||||
158
server/core/models/video/video-channel-sync.ts
Normal file
158
server/core/models/video/video-channel-sync.ts
Normal file
@@ -0,0 +1,158 @@
|
||||
import { VideoChannelSync, VideoChannelSyncState, type VideoChannelSyncStateType } from '@peertube/peertube-models'
|
||||
import { isUrlValid } from '@server/helpers/custom-validators/activitypub/misc.js'
|
||||
import { isVideoChannelSyncStateValid } from '@server/helpers/custom-validators/video-channel-syncs.js'
|
||||
import { CONSTRAINTS_FIELDS, VIDEO_CHANNEL_SYNC_STATE } from '@server/initializers/constants.js'
|
||||
import { MChannelSync, MChannelSyncChannel, MChannelSyncFormattable } from '@server/types/models/index.js'
|
||||
import { Op } from 'sequelize'
|
||||
import {
|
||||
AllowNull,
|
||||
BelongsTo,
|
||||
Column,
|
||||
CreatedAt,
|
||||
DataType,
|
||||
Default,
|
||||
DefaultScope,
|
||||
ForeignKey,
|
||||
Is,
|
||||
Table,
|
||||
UpdatedAt
|
||||
} from 'sequelize-typescript'
|
||||
import { AccountModel } from '../account/account.js'
|
||||
import { SequelizeModel, buildSQLAttributes, throwIfNotValid } from '../shared/index.js'
|
||||
import { UserModel } from '../user/user.js'
|
||||
import { VideoChannelSyncListQueryBuilder } from './sql/video-channel-sync/video-channel-sync-list-query-builder.js'
|
||||
import { VideoChannelModel } from './video-channel.js'
|
||||
|
||||
@DefaultScope(() => ({
|
||||
include: [
|
||||
{
|
||||
model: VideoChannelModel, // Default scope includes avatar and server
|
||||
required: true
|
||||
}
|
||||
]
|
||||
}))
|
||||
@Table({
|
||||
tableName: 'videoChannelSync',
|
||||
indexes: [
|
||||
{
|
||||
fields: [ 'videoChannelId' ]
|
||||
}
|
||||
]
|
||||
})
|
||||
export class VideoChannelSyncModel extends SequelizeModel<VideoChannelSyncModel> {
|
||||
@AllowNull(false)
|
||||
@Default(null)
|
||||
@Is('VideoChannelExternalChannelUrl', value => throwIfNotValid(value, isUrlValid, 'externalChannelUrl', true))
|
||||
@Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNEL_SYNCS.EXTERNAL_CHANNEL_URL.max))
|
||||
declare externalChannelUrl: string
|
||||
|
||||
@AllowNull(false)
|
||||
@Default(VideoChannelSyncState.WAITING_FIRST_RUN)
|
||||
@Is('VideoChannelSyncState', value => throwIfNotValid(value, isVideoChannelSyncStateValid, 'state'))
|
||||
@Column
|
||||
declare state: VideoChannelSyncStateType
|
||||
|
||||
@AllowNull(true)
|
||||
@Column(DataType.DATE)
|
||||
declare lastSyncAt: Date
|
||||
|
||||
@CreatedAt
|
||||
declare createdAt: Date
|
||||
|
||||
@UpdatedAt
|
||||
declare updatedAt: Date
|
||||
|
||||
@ForeignKey(() => VideoChannelModel)
|
||||
@Column
|
||||
declare videoChannelId: number
|
||||
|
||||
@BelongsTo(() => VideoChannelModel, {
|
||||
foreignKey: {
|
||||
allowNull: false
|
||||
},
|
||||
onDelete: 'cascade'
|
||||
})
|
||||
declare VideoChannel: Awaited<VideoChannelModel>
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static getSQLAttributes (tableName: string, aliasPrefix = '') {
|
||||
return buildSQLAttributes({
|
||||
model: this,
|
||||
tableName,
|
||||
aliasPrefix
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static listByAccountForAPI (options: {
|
||||
accountId: number
|
||||
start: number
|
||||
count: number
|
||||
sort: string
|
||||
includeCollaborations: boolean
|
||||
}) {
|
||||
return Promise.all([
|
||||
new VideoChannelSyncListQueryBuilder(VideoChannelSyncModel.sequelize, options).list<MChannelSyncFormattable>(),
|
||||
new VideoChannelSyncListQueryBuilder(VideoChannelSyncModel.sequelize, options).count()
|
||||
]).then(([ rows, count ]) => {
|
||||
return { total: count, data: rows }
|
||||
})
|
||||
}
|
||||
|
||||
static countByAccount (accountId: number) {
|
||||
return new VideoChannelSyncListQueryBuilder(VideoChannelSyncModel.sequelize, { accountId }).count()
|
||||
}
|
||||
|
||||
static async listSyncs (): Promise<MChannelSync[]> {
|
||||
const query = {
|
||||
include: [
|
||||
{
|
||||
model: VideoChannelModel.unscoped(),
|
||||
required: true,
|
||||
include: [
|
||||
{
|
||||
model: AccountModel.unscoped(),
|
||||
required: true,
|
||||
include: [ {
|
||||
attributes: [],
|
||||
model: UserModel.unscoped(),
|
||||
required: true,
|
||||
where: {
|
||||
videoQuota: {
|
||||
[Op.ne]: 0
|
||||
},
|
||||
videoQuotaDaily: {
|
||||
[Op.ne]: 0
|
||||
}
|
||||
}
|
||||
} ]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
return VideoChannelSyncModel.unscoped().findAll(query)
|
||||
}
|
||||
|
||||
static loadWithChannel (id: number): Promise<MChannelSyncChannel> {
|
||||
return VideoChannelSyncModel.findByPk(id)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
toFormattedJSON (this: MChannelSyncFormattable): VideoChannelSync {
|
||||
return {
|
||||
id: this.id,
|
||||
state: {
|
||||
id: this.state,
|
||||
label: VIDEO_CHANNEL_SYNC_STATE[this.state]
|
||||
},
|
||||
externalChannelUrl: this.externalChannelUrl,
|
||||
createdAt: this.createdAt.toISOString(),
|
||||
channel: this.VideoChannel.toFormattedSummaryJSON(),
|
||||
lastSyncAt: this.lastSyncAt?.toISOString()
|
||||
}
|
||||
}
|
||||
}
|
||||
607
server/core/models/video/video-channel.ts
Normal file
607
server/core/models/video/video-channel.ts
Normal file
@@ -0,0 +1,607 @@
|
||||
import { ActivityPubActor, ActivityUrlObject, VideoChannel, VideoChannelSummary, VideoPrivacy } from '@peertube/peertube-models'
|
||||
import { AttributesOnly } from '@peertube/peertube-typescript-utils'
|
||||
import { CONFIG } from '@server/initializers/config.js'
|
||||
import { getLocalActorPlayerSettingsActivityPubUrl } from '@server/lib/activitypub/url.js'
|
||||
import { InternalEventEmitter } from '@server/lib/internal-event-emitter.js'
|
||||
import { MAccountIdHost } from '@server/types/models/index.js'
|
||||
import { FindOptions, Includeable, literal, Op, QueryTypes, Transaction } from 'sequelize'
|
||||
import {
|
||||
AfterCreate,
|
||||
AfterDestroy,
|
||||
AfterUpdate,
|
||||
AllowNull,
|
||||
BeforeDestroy,
|
||||
BelongsTo,
|
||||
Column,
|
||||
CreatedAt,
|
||||
DataType,
|
||||
Default,
|
||||
DefaultScope,
|
||||
ForeignKey,
|
||||
HasMany,
|
||||
HasOne,
|
||||
Is,
|
||||
Scopes,
|
||||
Table,
|
||||
UpdatedAt
|
||||
} from 'sequelize-typescript'
|
||||
import {
|
||||
isVideoChannelDescriptionValid,
|
||||
isVideoChannelDisplayNameValid,
|
||||
isVideoChannelSupportValid
|
||||
} from '../../helpers/custom-validators/video-channels.js'
|
||||
import { CONSTRAINTS_FIELDS, WEBSERVER } from '../../initializers/constants.js'
|
||||
import { sendDeleteActor } from '../../lib/activitypub/send/index.js'
|
||||
import {
|
||||
MChannelAP,
|
||||
MChannelBannerAccountDefault,
|
||||
MChannelDefault,
|
||||
MChannelFormattable,
|
||||
MChannelHost,
|
||||
MChannelIdHost,
|
||||
MChannelSummaryFormattable,
|
||||
type MChannel
|
||||
} from '../../types/models/video/index.js'
|
||||
import { AccountModel, ScopeNames as AccountModelScopeNames, SummaryOptions as AccountSummaryOptions } from '../account/account.js'
|
||||
import { ActorImageModel } from '../actor/actor-image.js'
|
||||
import { ActorModel, actorSummaryAttributes } from '../actor/actor.js'
|
||||
import { ServerModel, serverSummaryAttributes } from '../server/server.js'
|
||||
import { buildSQLAttributes, buildTrigramSearchIndex, getSort, SequelizeModel, setAsUpdated, throwIfNotValid } from '../shared/index.js'
|
||||
import { ListVideoChannelsOptions, VideoChannelListQueryBuilder } from './sql/channel/video-channel-list-query-builder.js'
|
||||
import { VideoChannelCollaboratorModel } from './video-channel-collaborator.js'
|
||||
import { VideoPlaylistModel } from './video-playlist.js'
|
||||
import { VideoModel } from './video.js'
|
||||
|
||||
const channelSummaryAttributes = [ 'id', 'name', 'description' ] as const satisfies (keyof AttributesOnly<AccountModel>)[]
|
||||
|
||||
export enum ScopeNames {
|
||||
SUMMARY = 'SUMMARY',
|
||||
WITH_ACCOUNT = 'WITH_ACCOUNT',
|
||||
WITH_ACTOR = 'WITH_ACTOR',
|
||||
WITH_ACTOR_BANNER = 'WITH_ACTOR_BANNER',
|
||||
WITH_VIDEOS = 'WITH_VIDEOS'
|
||||
}
|
||||
|
||||
export type SummaryOptions = {
|
||||
actorRequired?: boolean // Default: true
|
||||
withAccount?: boolean // Default: false
|
||||
withAccountBlockerIds?: number[]
|
||||
}
|
||||
|
||||
@DefaultScope(() => ({
|
||||
include: [
|
||||
{
|
||||
model: ActorModel,
|
||||
required: true
|
||||
}
|
||||
]
|
||||
}))
|
||||
@Scopes(() => ({
|
||||
[ScopeNames.SUMMARY]: (options: SummaryOptions = {}) => {
|
||||
const include: Includeable[] = [
|
||||
{
|
||||
attributes: actorSummaryAttributes,
|
||||
model: ActorModel.unscoped(),
|
||||
required: options.actorRequired ?? true,
|
||||
include: [
|
||||
{
|
||||
attributes: serverSummaryAttributes,
|
||||
model: ServerModel.unscoped(),
|
||||
required: false
|
||||
},
|
||||
{
|
||||
model: ActorImageModel,
|
||||
as: 'Avatars',
|
||||
required: false
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
const base: FindOptions = {
|
||||
attributes: channelSummaryAttributes
|
||||
}
|
||||
|
||||
if (options.withAccount === true) {
|
||||
include.push({
|
||||
model: AccountModel.scope({
|
||||
method: [ AccountModelScopeNames.SUMMARY, { withAccountBlockerIds: options.withAccountBlockerIds } as AccountSummaryOptions ]
|
||||
}),
|
||||
required: true
|
||||
})
|
||||
}
|
||||
|
||||
base.include = include
|
||||
|
||||
return base
|
||||
},
|
||||
[ScopeNames.WITH_ACCOUNT]: {
|
||||
include: [
|
||||
{
|
||||
model: AccountModel,
|
||||
required: true
|
||||
}
|
||||
]
|
||||
},
|
||||
[ScopeNames.WITH_ACTOR]: {
|
||||
include: [
|
||||
ActorModel
|
||||
]
|
||||
},
|
||||
[ScopeNames.WITH_ACTOR_BANNER]: {
|
||||
include: [
|
||||
{
|
||||
model: ActorModel,
|
||||
include: [
|
||||
{
|
||||
model: ActorImageModel,
|
||||
required: false,
|
||||
as: 'Banners'
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
[ScopeNames.WITH_VIDEOS]: {
|
||||
include: [
|
||||
VideoModel
|
||||
]
|
||||
}
|
||||
}))
|
||||
@Table({
|
||||
tableName: 'videoChannel',
|
||||
indexes: [
|
||||
buildTrigramSearchIndex('video_channel_name_trigram', 'name'),
|
||||
|
||||
{
|
||||
fields: [ 'accountId' ]
|
||||
}
|
||||
]
|
||||
})
|
||||
export class VideoChannelModel extends SequelizeModel<VideoChannelModel> {
|
||||
@AllowNull(false)
|
||||
@Is('VideoChannelName', value => throwIfNotValid(value, isVideoChannelDisplayNameValid, 'name'))
|
||||
@Column
|
||||
declare name: string
|
||||
|
||||
@AllowNull(true)
|
||||
@Default(null)
|
||||
@Is('VideoChannelDescription', value => throwIfNotValid(value, isVideoChannelDescriptionValid, 'description', true))
|
||||
@Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.DESCRIPTION.max))
|
||||
declare description: string
|
||||
|
||||
@AllowNull(true)
|
||||
@Default(null)
|
||||
@Is('VideoChannelSupport', value => throwIfNotValid(value, isVideoChannelSupportValid, 'support', true))
|
||||
@Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.SUPPORT.max))
|
||||
declare support: string
|
||||
|
||||
@CreatedAt
|
||||
declare createdAt: Date
|
||||
|
||||
@UpdatedAt
|
||||
declare updatedAt: Date
|
||||
|
||||
@ForeignKey(() => AccountModel)
|
||||
@Column
|
||||
declare accountId: number
|
||||
|
||||
@BelongsTo(() => AccountModel, {
|
||||
foreignKey: {
|
||||
allowNull: false
|
||||
}
|
||||
})
|
||||
declare Account: Awaited<AccountModel>
|
||||
|
||||
@HasMany(() => VideoModel, {
|
||||
foreignKey: {
|
||||
name: 'channelId',
|
||||
allowNull: false
|
||||
},
|
||||
onDelete: 'CASCADE',
|
||||
hooks: true
|
||||
})
|
||||
declare Videos: Awaited<VideoModel>[]
|
||||
|
||||
@HasMany(() => VideoPlaylistModel, {
|
||||
foreignKey: {
|
||||
allowNull: true
|
||||
},
|
||||
onDelete: 'CASCADE',
|
||||
hooks: true
|
||||
})
|
||||
declare VideoPlaylists: Awaited<VideoPlaylistModel>[]
|
||||
|
||||
@HasMany(() => VideoChannelCollaboratorModel, {
|
||||
foreignKey: 'accountId',
|
||||
onDelete: 'CASCADE'
|
||||
})
|
||||
declare VideoChannelCollaborators: Awaited<VideoChannelCollaboratorModel>[]
|
||||
|
||||
@HasOne(() => ActorModel, {
|
||||
foreignKey: {
|
||||
allowNull: true
|
||||
},
|
||||
onDelete: 'cascade',
|
||||
hooks: true
|
||||
})
|
||||
declare Actor: Awaited<ActorModel>
|
||||
|
||||
@AfterCreate
|
||||
static notifyCreate (channel: MChannel) {
|
||||
InternalEventEmitter.Instance.emit('channel-created', { channel })
|
||||
}
|
||||
|
||||
@AfterUpdate
|
||||
static notifyUpdate (channel: MChannel) {
|
||||
InternalEventEmitter.Instance.emit('channel-updated', { channel })
|
||||
}
|
||||
|
||||
@AfterDestroy
|
||||
static notifyDestroy (channel: MChannel) {
|
||||
InternalEventEmitter.Instance.emit('channel-deleted', { channel })
|
||||
}
|
||||
|
||||
@BeforeDestroy
|
||||
static async sendDeleteIfOwned (instance: VideoChannelModel, options) {
|
||||
if (!instance.Actor) {
|
||||
instance.Actor = await instance.$get('Actor', { transaction: options.transaction })
|
||||
}
|
||||
|
||||
if (instance.Actor.isLocal()) {
|
||||
return sendDeleteActor(instance.Actor, options.transaction)
|
||||
}
|
||||
|
||||
return undefined
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static getSQLAttributes (tableName: string, aliasPrefix = '') {
|
||||
return buildSQLAttributes({
|
||||
model: this,
|
||||
tableName,
|
||||
aliasPrefix
|
||||
})
|
||||
}
|
||||
|
||||
static getSQLSummaryAttributes (tableName: string, aliasPrefix = '') {
|
||||
return buildSQLAttributes({
|
||||
model: this,
|
||||
tableName,
|
||||
aliasPrefix,
|
||||
includeAttributes: channelSummaryAttributes
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static countByAccount (accountId: number) {
|
||||
const query = {
|
||||
where: {
|
||||
accountId
|
||||
}
|
||||
}
|
||||
|
||||
return VideoChannelModel.unscoped().count(query)
|
||||
}
|
||||
|
||||
static async getStats () {
|
||||
function getLocalVideoChannelStats (days?: number) {
|
||||
const options = {
|
||||
type: QueryTypes.SELECT as QueryTypes.SELECT,
|
||||
raw: true
|
||||
}
|
||||
|
||||
const videoJoin = days
|
||||
? `INNER JOIN "video" AS "Videos" ON "VideoChannelModel"."id" = "Videos"."channelId" ` +
|
||||
`AND ("Videos"."publishedAt" > Now() - interval '${days}d')`
|
||||
: ''
|
||||
|
||||
const query = `
|
||||
SELECT COUNT(DISTINCT("VideoChannelModel"."id")) AS "count"
|
||||
FROM "videoChannel" AS "VideoChannelModel"
|
||||
${videoJoin}
|
||||
INNER JOIN "account" AS "Account" ON "VideoChannelModel"."accountId" = "Account"."id"
|
||||
INNER JOIN "actor" AS "Account->Actor" ON "Account"."id" = "Account->Actor"."accountId"
|
||||
AND "Account->Actor"."serverId" IS NULL`
|
||||
|
||||
return VideoChannelModel.sequelize.query<{ count: string }>(query, options)
|
||||
.then(r => parseInt(r[0].count, 10))
|
||||
}
|
||||
|
||||
const totalLocalVideoChannels = await getLocalVideoChannelStats()
|
||||
const totalLocalDailyActiveVideoChannels = await getLocalVideoChannelStats(1)
|
||||
const totalLocalWeeklyActiveVideoChannels = await getLocalVideoChannelStats(7)
|
||||
const totalLocalMonthlyActiveVideoChannels = await getLocalVideoChannelStats(30)
|
||||
const totalLocalHalfYearActiveVideoChannels = await getLocalVideoChannelStats(180)
|
||||
|
||||
return {
|
||||
totalLocalVideoChannels,
|
||||
totalLocalDailyActiveVideoChannels,
|
||||
totalLocalWeeklyActiveVideoChannels,
|
||||
totalLocalMonthlyActiveVideoChannels,
|
||||
totalLocalHalfYearActiveVideoChannels
|
||||
}
|
||||
}
|
||||
|
||||
static listLocalsForSitemap (sort: string): Promise<MChannelHost[]> {
|
||||
const query = {
|
||||
attributes: [],
|
||||
offset: 0,
|
||||
order: getSort(sort),
|
||||
include: [
|
||||
{
|
||||
attributes: [ 'preferredUsername', 'serverId' ],
|
||||
model: ActorModel.unscoped(),
|
||||
where: {
|
||||
serverId: null
|
||||
}
|
||||
}
|
||||
],
|
||||
where: {
|
||||
[Op.and]: [
|
||||
literal(`EXISTS (SELECT 1 FROM "video" WHERE "privacy" = ${VideoPrivacy.PUBLIC} AND "channelId" = "VideoChannelModel"."id")`)
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
return VideoChannelModel
|
||||
.unscoped()
|
||||
.findAll(query)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static listForApi (options: ListVideoChannelsOptions) {
|
||||
return Promise.all([
|
||||
new VideoChannelListQueryBuilder(VideoChannelModel.sequelize, options).list<VideoChannelModel>() as Promise<MChannelFormattable[]>,
|
||||
new VideoChannelListQueryBuilder(VideoChannelModel.sequelize, options).count()
|
||||
]).then(([ rows, count ]) => {
|
||||
return { total: count, data: rows }
|
||||
})
|
||||
}
|
||||
|
||||
static listByAccountForAPI (
|
||||
options: Pick<ListVideoChannelsOptions, 'accountId' | 'includeCollaborations' | 'search' | 'start' | 'count' | 'sort'> & {
|
||||
withStats?: boolean
|
||||
}
|
||||
) {
|
||||
const listOptions = options.withStats
|
||||
? { ...options, statsDaysPrior: 30 }
|
||||
: options
|
||||
|
||||
return this.listForApi(listOptions)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static listAllOwnedByAccount (accountId: number): Promise<MChannelDefault[]> {
|
||||
const query = {
|
||||
limit: CONFIG.VIDEO_CHANNELS.MAX_PER_USER,
|
||||
include: [
|
||||
{
|
||||
attributes: [],
|
||||
model: AccountModel.unscoped(),
|
||||
where: {
|
||||
id: accountId
|
||||
},
|
||||
required: true
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
return VideoChannelModel.findAll(query)
|
||||
}
|
||||
|
||||
static loadAndPopulateAccount (id: number, transaction?: Transaction): Promise<MChannelBannerAccountDefault> {
|
||||
return VideoChannelModel.unscoped()
|
||||
.scope([ ScopeNames.WITH_ACTOR_BANNER, ScopeNames.WITH_ACCOUNT ])
|
||||
.findByPk(id, { transaction })
|
||||
}
|
||||
|
||||
static loadByUrlAndPopulateAccount (url: string): Promise<MChannelBannerAccountDefault> {
|
||||
const query = {
|
||||
include: [
|
||||
{
|
||||
model: ActorModel,
|
||||
required: true,
|
||||
where: {
|
||||
url
|
||||
},
|
||||
include: [
|
||||
{
|
||||
model: ActorImageModel,
|
||||
required: false,
|
||||
as: 'Banners'
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
return VideoChannelModel
|
||||
.scope([ ScopeNames.WITH_ACCOUNT ])
|
||||
.findOne(query)
|
||||
}
|
||||
|
||||
static loadByHandleAndPopulateAccount (handle: string) {
|
||||
const [ name, host ] = handle.split('@')
|
||||
|
||||
if (!host || host === WEBSERVER.HOST) return VideoChannelModel.loadLocalByNameAndPopulateAccount(name)
|
||||
|
||||
return VideoChannelModel.loadByNameAndHostAndPopulateAccount(name, host)
|
||||
}
|
||||
|
||||
static loadLocalByNameAndPopulateAccount (name: string): Promise<MChannelBannerAccountDefault> {
|
||||
const query = {
|
||||
include: [
|
||||
{
|
||||
model: ActorModel,
|
||||
required: true,
|
||||
where: {
|
||||
[Op.and]: [
|
||||
ActorModel.wherePreferredUsername(name, 'Actor.preferredUsername'),
|
||||
{ serverId: null }
|
||||
]
|
||||
},
|
||||
include: [
|
||||
{
|
||||
model: ActorImageModel,
|
||||
required: false,
|
||||
as: 'Banners'
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
return VideoChannelModel.unscoped()
|
||||
.scope([ ScopeNames.WITH_ACCOUNT ])
|
||||
.findOne(query)
|
||||
}
|
||||
|
||||
static loadByNameAndHostAndPopulateAccount (name: string, host: string): Promise<MChannelBannerAccountDefault> {
|
||||
const query = {
|
||||
include: [
|
||||
{
|
||||
model: ActorModel,
|
||||
required: true,
|
||||
where: ActorModel.wherePreferredUsername(name, 'Actor.preferredUsername'),
|
||||
include: [
|
||||
{
|
||||
model: ServerModel,
|
||||
required: true,
|
||||
where: { host }
|
||||
},
|
||||
{
|
||||
model: ActorImageModel,
|
||||
required: false,
|
||||
as: 'Banners'
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
return VideoChannelModel.unscoped()
|
||||
.scope([ ScopeNames.WITH_ACCOUNT ])
|
||||
.findOne(query)
|
||||
}
|
||||
|
||||
toFormattedSummaryJSON (this: MChannelSummaryFormattable): VideoChannelSummary {
|
||||
const actor = this.Actor.toFormattedSummaryJSON()
|
||||
|
||||
return {
|
||||
id: this.id,
|
||||
name: actor.name,
|
||||
displayName: this.getDisplayName(),
|
||||
url: actor.url,
|
||||
host: actor.host,
|
||||
avatars: actor.avatars
|
||||
}
|
||||
}
|
||||
|
||||
toFormattedJSON (this: MChannelFormattable): VideoChannel {
|
||||
const viewsPerDayString = this.get('viewsPerDay') as string
|
||||
const videosCount = this.get('videosCount') as number
|
||||
|
||||
let viewsPerDay: { date: Date, views: number }[]
|
||||
|
||||
if (viewsPerDayString) {
|
||||
viewsPerDay = viewsPerDayString.split(',')
|
||||
.map(v => {
|
||||
const [ dateString, amount ] = v.split('|')
|
||||
|
||||
return {
|
||||
date: new Date(dateString),
|
||||
views: +amount
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const totalViews = this.get('totalViews') as number
|
||||
|
||||
const actor = this.Actor.toFormattedJSON()
|
||||
const videoChannel = {
|
||||
id: this.id,
|
||||
displayName: this.getDisplayName(),
|
||||
description: this.description,
|
||||
support: this.support,
|
||||
isLocal: this.Actor.isLocal(),
|
||||
updatedAt: this.updatedAt,
|
||||
|
||||
ownerAccount: undefined,
|
||||
|
||||
videosCount,
|
||||
viewsPerDay,
|
||||
totalViews,
|
||||
|
||||
avatars: actor.avatars
|
||||
}
|
||||
|
||||
if (this.Account) videoChannel.ownerAccount = this.Account.toFormattedJSON()
|
||||
|
||||
return Object.assign(actor, videoChannel)
|
||||
}
|
||||
|
||||
async toActivityPubObject (this: MChannelAP): Promise<ActivityPubActor> {
|
||||
const obj = await this.Actor.toActivityPubObject(this.name)
|
||||
|
||||
return {
|
||||
...obj,
|
||||
|
||||
url: [
|
||||
{
|
||||
type: 'Link',
|
||||
mediaType: 'text/html',
|
||||
href: this.getClientUrl(true)
|
||||
},
|
||||
{
|
||||
type: 'Link',
|
||||
mediaType: 'text/html',
|
||||
href: this.getClientUrl(false)
|
||||
},
|
||||
{
|
||||
type: 'Link',
|
||||
mediaType: 'text/html',
|
||||
href: this.Actor.url
|
||||
}
|
||||
] as ActivityUrlObject[],
|
||||
|
||||
playerSettings: getLocalActorPlayerSettingsActivityPubUrl(this.Actor),
|
||||
|
||||
summary: this.description,
|
||||
support: this.support,
|
||||
postingRestrictedToMods: true,
|
||||
attributedTo: [
|
||||
this.Account.Actor.url
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
// Avoid error when running this method on MAccount... | MChannel...
|
||||
getClientUrl (this: MAccountIdHost | MChannelIdHost, videosSuffix = true) {
|
||||
const suffix = videosSuffix
|
||||
? '/videos'
|
||||
: ''
|
||||
|
||||
return WEBSERVER.URL + '/c/' + this.Actor.getIdentifier() + suffix
|
||||
}
|
||||
|
||||
getClientManageUrl (this: MAccountIdHost | MChannelIdHost) {
|
||||
return WEBSERVER.URL + '/my-library/video-channels/manage/' + this.Actor.getIdentifier()
|
||||
}
|
||||
|
||||
getDisplayName () {
|
||||
return this.name
|
||||
}
|
||||
|
||||
isOutdated () {
|
||||
return this.Actor.isOutdated()
|
||||
}
|
||||
|
||||
setAsUpdated (transaction?: Transaction) {
|
||||
return setAsUpdated({ sequelize: this.sequelize, table: 'videoChannel', id: this.id, transaction })
|
||||
}
|
||||
}
|
||||
94
server/core/models/video/video-chapter.ts
Normal file
94
server/core/models/video/video-chapter.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
import { AllowNull, BelongsTo, Column, CreatedAt, ForeignKey, Table, UpdatedAt } from 'sequelize-typescript'
|
||||
import { MVideo, MVideoChapter } from '@server/types/models/index.js'
|
||||
import { VideoChapter, VideoChapterObject } from '@peertube/peertube-models'
|
||||
import { VideoModel } from './video.js'
|
||||
import { Transaction } from 'sequelize'
|
||||
import { getSort } from '../shared/sort.js'
|
||||
import { SequelizeModel } from '../shared/sequelize-type.js'
|
||||
|
||||
@Table({
|
||||
tableName: 'videoChapter',
|
||||
indexes: [
|
||||
{
|
||||
fields: [ 'videoId', 'timecode' ],
|
||||
unique: true
|
||||
}
|
||||
]
|
||||
})
|
||||
export class VideoChapterModel extends SequelizeModel<VideoChapterModel> {
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare timecode: number
|
||||
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare title: string
|
||||
|
||||
@ForeignKey(() => VideoModel)
|
||||
@Column
|
||||
declare videoId: number
|
||||
|
||||
@BelongsTo(() => VideoModel, {
|
||||
foreignKey: {
|
||||
allowNull: false
|
||||
},
|
||||
onDelete: 'CASCADE'
|
||||
})
|
||||
declare Video: Awaited<VideoModel>
|
||||
|
||||
@CreatedAt
|
||||
declare createdAt: Date
|
||||
|
||||
@UpdatedAt
|
||||
declare updatedAt: Date
|
||||
|
||||
static deleteChapters (videoId: number, transaction: Transaction) {
|
||||
const query = {
|
||||
where: {
|
||||
videoId
|
||||
},
|
||||
transaction
|
||||
}
|
||||
|
||||
return VideoChapterModel.destroy(query)
|
||||
}
|
||||
|
||||
static listChaptersOfVideo (videoId: number, transaction?: Transaction) {
|
||||
const query = {
|
||||
where: {
|
||||
videoId
|
||||
},
|
||||
order: getSort('timecode'),
|
||||
transaction
|
||||
}
|
||||
|
||||
return VideoChapterModel.findAll<MVideoChapter>(query)
|
||||
}
|
||||
|
||||
static hasVideoChapters (videoId: number, transaction: Transaction) {
|
||||
return VideoChapterModel.findOne({
|
||||
where: { videoId },
|
||||
transaction
|
||||
}).then(c => !!c)
|
||||
}
|
||||
|
||||
toActivityPubJSON (this: MVideoChapter, options: {
|
||||
video: MVideo
|
||||
nextChapter: MVideoChapter
|
||||
}): VideoChapterObject {
|
||||
return {
|
||||
name: this.title,
|
||||
startOffset: this.timecode,
|
||||
endOffset: options.nextChapter
|
||||
? options.nextChapter.timecode
|
||||
: options.video.duration
|
||||
}
|
||||
}
|
||||
|
||||
toFormattedJSON (this: MVideoChapter): VideoChapter {
|
||||
return {
|
||||
timecode: this.timecode,
|
||||
title: this.title
|
||||
}
|
||||
}
|
||||
}
|
||||
863
server/core/models/video/video-comment.ts
Normal file
863
server/core/models/video/video-comment.ts
Normal file
@@ -0,0 +1,863 @@
|
||||
import { pick } from '@peertube/peertube-core-utils'
|
||||
import {
|
||||
ActivityTagObject,
|
||||
ActivityTombstoneObject,
|
||||
UserRight,
|
||||
VideoComment,
|
||||
VideoCommentForAdminOrUser,
|
||||
VideoCommentObject
|
||||
} from '@peertube/peertube-models'
|
||||
import { afterCommitIfTransaction, retryTransactionWrapper } from '@server/helpers/database-utils.js'
|
||||
import { logger } from '@server/helpers/logger.js'
|
||||
import { extractMentions } from '@server/helpers/mentions.js'
|
||||
import { sequelizeTypescript } from '@server/initializers/database.js'
|
||||
import { getLocalApproveReplyActivityPubUrl } from '@server/lib/activitypub/url.js'
|
||||
import { getServerActor } from '@server/models/application/application.js'
|
||||
import { MAccount, MAccountId, MUserAccountId } from '@server/types/models/index.js'
|
||||
import { Op, Order, QueryTypes, Sequelize, Transaction } from 'sequelize'
|
||||
import {
|
||||
AfterCreate,
|
||||
AfterDestroy,
|
||||
AfterUpdate,
|
||||
AllowNull,
|
||||
BelongsTo,
|
||||
Column,
|
||||
CreatedAt,
|
||||
DataType,
|
||||
ForeignKey,
|
||||
HasMany,
|
||||
Is,
|
||||
Scopes,
|
||||
Table,
|
||||
UpdatedAt
|
||||
} from 'sequelize-typescript'
|
||||
import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc.js'
|
||||
import { CONSTRAINTS_FIELDS, USER_EXPORT_MAX_ITEMS } from '../../initializers/constants.js'
|
||||
import {
|
||||
MComment,
|
||||
MCommentAdminOrUserFormattable,
|
||||
MCommentAP,
|
||||
MCommentExport,
|
||||
MCommentFormattable,
|
||||
MCommentId,
|
||||
MCommentOwner,
|
||||
MCommentOwnerReplyVideoImmutable,
|
||||
MCommentOwnerVideoFeed,
|
||||
MCommentOwnerVideoReply,
|
||||
MVideo,
|
||||
MVideoImmutable
|
||||
} from '../../types/models/video/index.js'
|
||||
import { VideoCommentAbuseModel } from '../abuse/video-comment-abuse.js'
|
||||
import { AccountModel } from '../account/account.js'
|
||||
import { ActorModel } from '../actor/actor.js'
|
||||
import { CommentAutomaticTagModel } from '../automatic-tag/comment-automatic-tag.js'
|
||||
import { buildLocalAccountIdsIn, buildSQLAttributes, SequelizeModel, throwIfNotValid } from '../shared/index.js'
|
||||
import { ListVideoCommentsOptions, VideoCommentListQueryBuilder } from './sql/comment/video-comment-list-query-builder.js'
|
||||
import { VideoChannelModel } from './video-channel.js'
|
||||
import { VideoModel } from './video.js'
|
||||
|
||||
export enum ScopeNames {
|
||||
WITH_ACCOUNT = 'WITH_ACCOUNT',
|
||||
WITH_IN_REPLY_TO = 'WITH_IN_REPLY_TO',
|
||||
WITH_VIDEO = 'WITH_VIDEO'
|
||||
}
|
||||
|
||||
@Scopes(() => ({
|
||||
[ScopeNames.WITH_ACCOUNT]: {
|
||||
include: [
|
||||
{
|
||||
model: AccountModel
|
||||
}
|
||||
]
|
||||
},
|
||||
[ScopeNames.WITH_IN_REPLY_TO]: {
|
||||
include: [
|
||||
{
|
||||
model: VideoCommentModel,
|
||||
as: 'InReplyToVideoComment'
|
||||
}
|
||||
]
|
||||
},
|
||||
[ScopeNames.WITH_VIDEO]: {
|
||||
include: [
|
||||
{
|
||||
model: VideoModel,
|
||||
required: true,
|
||||
include: [
|
||||
{
|
||||
model: VideoChannelModel.unscoped(),
|
||||
attributes: [ 'id', 'accountId' ],
|
||||
required: true,
|
||||
include: [
|
||||
{
|
||||
attributes: [ 'id', 'url' ],
|
||||
model: ActorModel.unscoped(),
|
||||
required: true
|
||||
},
|
||||
{
|
||||
attributes: [ 'id' ],
|
||||
model: AccountModel.unscoped(),
|
||||
required: true,
|
||||
include: [
|
||||
{
|
||||
attributes: [ 'id', 'url' ],
|
||||
model: ActorModel.unscoped(),
|
||||
required: true
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}))
|
||||
@Table({
|
||||
tableName: 'videoComment',
|
||||
indexes: [
|
||||
{
|
||||
fields: [ 'videoId' ]
|
||||
},
|
||||
{
|
||||
fields: [ 'videoId', 'originCommentId' ]
|
||||
},
|
||||
{
|
||||
fields: [ 'url' ],
|
||||
unique: true
|
||||
},
|
||||
{
|
||||
fields: [ 'accountId' ]
|
||||
},
|
||||
{
|
||||
fields: [
|
||||
{ name: 'createdAt', order: 'DESC' }
|
||||
]
|
||||
}
|
||||
]
|
||||
})
|
||||
export class VideoCommentModel extends SequelizeModel<VideoCommentModel> {
|
||||
@CreatedAt
|
||||
declare createdAt: Date
|
||||
|
||||
@UpdatedAt
|
||||
declare updatedAt: Date
|
||||
|
||||
@AllowNull(true)
|
||||
@Column(DataType.DATE)
|
||||
declare deletedAt: Date
|
||||
|
||||
@AllowNull(false)
|
||||
@Is('VideoCommentUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
|
||||
@Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
|
||||
declare url: string
|
||||
|
||||
@AllowNull(false)
|
||||
@Column(DataType.TEXT)
|
||||
declare text: string
|
||||
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare heldForReview: boolean
|
||||
|
||||
@AllowNull(true)
|
||||
@Column
|
||||
declare replyApproval: string
|
||||
|
||||
@ForeignKey(() => VideoCommentModel)
|
||||
@Column
|
||||
declare originCommentId: number
|
||||
|
||||
@BelongsTo(() => VideoCommentModel, {
|
||||
foreignKey: {
|
||||
name: 'originCommentId',
|
||||
allowNull: true
|
||||
},
|
||||
as: 'OriginVideoComment',
|
||||
onDelete: 'CASCADE'
|
||||
})
|
||||
declare OriginVideoComment: Awaited<VideoCommentModel>
|
||||
|
||||
@ForeignKey(() => VideoCommentModel)
|
||||
@Column
|
||||
declare inReplyToCommentId: number
|
||||
|
||||
@BelongsTo(() => VideoCommentModel, {
|
||||
foreignKey: {
|
||||
name: 'inReplyToCommentId',
|
||||
allowNull: true
|
||||
},
|
||||
as: 'InReplyToVideoComment',
|
||||
onDelete: 'CASCADE'
|
||||
})
|
||||
declare InReplyToVideoComment: Awaited<VideoCommentModel> | null
|
||||
|
||||
@ForeignKey(() => VideoModel)
|
||||
@Column
|
||||
declare videoId: number
|
||||
|
||||
@BelongsTo(() => VideoModel, {
|
||||
foreignKey: {
|
||||
allowNull: false
|
||||
},
|
||||
onDelete: 'CASCADE'
|
||||
})
|
||||
declare Video: Awaited<VideoModel>
|
||||
|
||||
@ForeignKey(() => AccountModel)
|
||||
@Column
|
||||
declare accountId: number
|
||||
|
||||
@BelongsTo(() => AccountModel, {
|
||||
foreignKey: {
|
||||
allowNull: true
|
||||
},
|
||||
onDelete: 'CASCADE'
|
||||
})
|
||||
declare Account: Awaited<AccountModel>
|
||||
|
||||
@HasMany(() => VideoCommentAbuseModel, {
|
||||
foreignKey: {
|
||||
name: 'videoCommentId',
|
||||
allowNull: true
|
||||
},
|
||||
onDelete: 'set null'
|
||||
})
|
||||
declare CommentAbuses: Awaited<VideoCommentAbuseModel>[]
|
||||
|
||||
@HasMany(() => CommentAutomaticTagModel, {
|
||||
foreignKey: 'commentId',
|
||||
onDelete: 'CASCADE'
|
||||
})
|
||||
declare CommentAutomaticTags: Awaited<CommentAutomaticTagModel>[]
|
||||
|
||||
@AfterCreate
|
||||
@AfterDestroy
|
||||
static incrementCommentCount (instance: VideoCommentModel, options: any) {
|
||||
if (instance.heldForReview) return // Don't count held comments
|
||||
|
||||
return afterCommitIfTransaction(options.transaction, () => this.rebuildCommentsCount(instance.videoId))
|
||||
}
|
||||
|
||||
@AfterUpdate
|
||||
static updateCommentCountOnHeldStatusChange (instance: VideoCommentModel, options: any) {
|
||||
return afterCommitIfTransaction(options.transaction, () => this.rebuildCommentsCount(instance.videoId))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static async rebuildCommentsCount (videoId: number) {
|
||||
try {
|
||||
await retryTransactionWrapper(() => {
|
||||
return sequelizeTypescript.transaction(async transaction => {
|
||||
const video = await VideoModel.load(videoId, transaction)
|
||||
if (!video) return
|
||||
|
||||
video.comments = await new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, {
|
||||
selectType: 'comment-only',
|
||||
videoId: video.id,
|
||||
heldForReview: false,
|
||||
notDeleted: true,
|
||||
transaction
|
||||
}).count()
|
||||
|
||||
await video.save({ transaction })
|
||||
})
|
||||
})
|
||||
} catch (err) {
|
||||
logger.error('Cannot rebuild comments count for video ' + videoId, { err })
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static getSQLAttributes (tableName: string, aliasPrefix = '') {
|
||||
return buildSQLAttributes({
|
||||
model: this,
|
||||
tableName,
|
||||
aliasPrefix
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static loadById (id: number, transaction?: Transaction): Promise<MComment> {
|
||||
const query = {
|
||||
where: {
|
||||
id
|
||||
},
|
||||
transaction
|
||||
}
|
||||
|
||||
return VideoCommentModel.findOne(query)
|
||||
}
|
||||
|
||||
static loadByIdAndPopulateVideoAndAccountAndReply (id: number, transaction?: Transaction): Promise<MCommentOwnerVideoReply> {
|
||||
const query = {
|
||||
where: {
|
||||
id
|
||||
},
|
||||
transaction
|
||||
}
|
||||
|
||||
return VideoCommentModel
|
||||
.scope([ ScopeNames.WITH_VIDEO, ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_IN_REPLY_TO ])
|
||||
.findOne(query)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static loadByUrlAndPopulateAccountAndVideoAndReply (url: string, transaction?: Transaction): Promise<MCommentOwnerVideoReply> {
|
||||
const query = {
|
||||
where: {
|
||||
url
|
||||
},
|
||||
transaction
|
||||
}
|
||||
|
||||
return VideoCommentModel.scope([ ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_VIDEO, ScopeNames.WITH_IN_REPLY_TO ]).findOne(query)
|
||||
}
|
||||
|
||||
static loadByUrlAndPopulateReplyAndVideoImmutableAndAccount (
|
||||
url: string,
|
||||
transaction?: Transaction
|
||||
): Promise<MCommentOwnerReplyVideoImmutable> {
|
||||
const query = {
|
||||
where: {
|
||||
url
|
||||
},
|
||||
include: [
|
||||
{
|
||||
attributes: [ 'id', 'uuid', 'url', 'remote' ],
|
||||
model: VideoModel.unscoped()
|
||||
}
|
||||
],
|
||||
transaction
|
||||
}
|
||||
|
||||
return VideoCommentModel.scope([ ScopeNames.WITH_IN_REPLY_TO, ScopeNames.WITH_ACCOUNT ]).findOne(query)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static listForApi (parameters: {
|
||||
start: number
|
||||
count: number
|
||||
sort: string
|
||||
|
||||
autoTagOfAccountId: number
|
||||
|
||||
videoAccountOwnerId?: number
|
||||
videoAccountOwnerIncludeCollaborations?: boolean
|
||||
|
||||
videoChannelOwnerId?: number
|
||||
|
||||
onLocalVideo?: boolean
|
||||
isLocal?: boolean
|
||||
|
||||
search?: string
|
||||
searchAccount?: string
|
||||
searchVideo?: string
|
||||
|
||||
heldForReview: boolean
|
||||
|
||||
videoId?: number
|
||||
videoChannelId?: number
|
||||
autoTagOneOf?: string[]
|
||||
}) {
|
||||
const queryOptions: ListVideoCommentsOptions = {
|
||||
...pick(parameters, [
|
||||
'start',
|
||||
'count',
|
||||
'sort',
|
||||
'isLocal',
|
||||
'search',
|
||||
'searchVideo',
|
||||
'searchAccount',
|
||||
'onLocalVideo',
|
||||
'videoId',
|
||||
'videoChannelId',
|
||||
'autoTagOneOf',
|
||||
'autoTagOfAccountId',
|
||||
'videoAccountOwnerId',
|
||||
'videoAccountOwnerIncludeCollaborations',
|
||||
'videoChannelOwnerId',
|
||||
'heldForReview'
|
||||
]),
|
||||
|
||||
selectType: 'api-list',
|
||||
notDeleted: true
|
||||
}
|
||||
|
||||
return Promise.all([
|
||||
new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).list<MCommentAdminOrUserFormattable>(),
|
||||
new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).count()
|
||||
]).then(([ rows, count ]) => {
|
||||
return { total: count, data: rows }
|
||||
})
|
||||
}
|
||||
|
||||
static async listThreadsForApi (parameters: {
|
||||
video: MVideo
|
||||
start: number
|
||||
count: number
|
||||
sort: string
|
||||
user?: MUserAccountId
|
||||
}) {
|
||||
const { video, user } = parameters
|
||||
|
||||
const { blockerAccountIds, canSeeHeldForReview } = await VideoCommentModel.buildBlockerAccountIdsAndCanSeeHeldForReview({ user, video })
|
||||
|
||||
const commonOptions: ListVideoCommentsOptions = {
|
||||
selectType: 'api-video',
|
||||
videoId: video.id,
|
||||
blockerAccountIds,
|
||||
|
||||
heldForReview: canSeeHeldForReview
|
||||
? undefined // Display all comments for video owner or moderator
|
||||
: false,
|
||||
heldForReviewAccountIdException: user?.Account?.id
|
||||
}
|
||||
|
||||
const listOptions: ListVideoCommentsOptions = {
|
||||
...commonOptions,
|
||||
...pick(parameters, [ 'sort', 'start', 'count' ]),
|
||||
|
||||
isThread: true,
|
||||
includeReplyCounters: true
|
||||
}
|
||||
|
||||
const countOptions: ListVideoCommentsOptions = {
|
||||
...commonOptions,
|
||||
|
||||
isThread: true
|
||||
}
|
||||
|
||||
const notDeletedCountOptions: ListVideoCommentsOptions = {
|
||||
...commonOptions,
|
||||
|
||||
notDeleted: true
|
||||
}
|
||||
|
||||
return Promise.all([
|
||||
new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, listOptions).list<MCommentAdminOrUserFormattable>(),
|
||||
new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, countOptions).count(),
|
||||
new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, notDeletedCountOptions).count()
|
||||
]).then(([ rows, count, totalNotDeletedComments ]) => {
|
||||
return { total: count, data: rows, totalNotDeletedComments }
|
||||
})
|
||||
}
|
||||
|
||||
static async listThreadCommentsForApi (parameters: {
|
||||
video: MVideo
|
||||
threadId: number
|
||||
user?: MUserAccountId
|
||||
}) {
|
||||
const { user, video, threadId } = parameters
|
||||
|
||||
const { blockerAccountIds, canSeeHeldForReview } = await VideoCommentModel.buildBlockerAccountIdsAndCanSeeHeldForReview({ user, video })
|
||||
|
||||
const queryOptions: ListVideoCommentsOptions = {
|
||||
threadId,
|
||||
|
||||
videoId: video.id,
|
||||
selectType: 'api-video',
|
||||
sort: 'createdAt',
|
||||
|
||||
blockerAccountIds,
|
||||
includeReplyCounters: true,
|
||||
|
||||
heldForReview: canSeeHeldForReview
|
||||
? undefined // Display all comments for video owner or moderator
|
||||
: false,
|
||||
heldForReviewAccountIdException: user?.Account?.id
|
||||
}
|
||||
|
||||
return Promise.all([
|
||||
new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).list<MCommentAdminOrUserFormattable>(),
|
||||
new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).count()
|
||||
]).then(([ rows, count ]) => {
|
||||
return { total: count, data: rows }
|
||||
})
|
||||
}
|
||||
|
||||
static listThreadParentComments (options: {
|
||||
comment: MCommentId
|
||||
transaction?: Transaction
|
||||
order?: 'ASC' | 'DESC'
|
||||
}): Promise<MCommentOwner[]> {
|
||||
const { comment, transaction, order = 'ASC' } = options
|
||||
|
||||
const query = {
|
||||
order: [ [ 'createdAt', order ] ] as Order,
|
||||
where: {
|
||||
id: {
|
||||
[Op.in]: Sequelize.literal(
|
||||
'(' +
|
||||
'WITH RECURSIVE children (id, "inReplyToCommentId") AS ( ' +
|
||||
`SELECT id, "inReplyToCommentId" FROM "videoComment" WHERE id = ${comment.id} ` +
|
||||
'UNION ' +
|
||||
'SELECT "parent"."id", "parent"."inReplyToCommentId" FROM "videoComment" "parent" ' +
|
||||
'INNER JOIN "children" ON "children"."inReplyToCommentId" = "parent"."id"' +
|
||||
') ' +
|
||||
'SELECT id FROM children' +
|
||||
')'
|
||||
),
|
||||
[Op.ne]: comment.id
|
||||
}
|
||||
},
|
||||
transaction
|
||||
}
|
||||
|
||||
return VideoCommentModel
|
||||
.scope([ ScopeNames.WITH_ACCOUNT ])
|
||||
.findAll(query)
|
||||
}
|
||||
|
||||
static async listAndCountByVideoForAP (parameters: {
|
||||
video: MVideoImmutable
|
||||
start: number
|
||||
count: number
|
||||
}) {
|
||||
const { video } = parameters
|
||||
|
||||
const blockerAccountIds = await VideoCommentModel.buildBlockerAccountIds({ user: null })
|
||||
|
||||
const queryOptions: ListVideoCommentsOptions = {
|
||||
...pick(parameters, [ 'start', 'count' ]),
|
||||
|
||||
selectType: 'comment-only',
|
||||
videoId: video.id,
|
||||
sort: 'createdAt',
|
||||
|
||||
heldForReview: false,
|
||||
|
||||
blockerAccountIds
|
||||
}
|
||||
|
||||
return Promise.all([
|
||||
new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).list<MComment>(),
|
||||
new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).count()
|
||||
]).then(([ rows, count ]) => {
|
||||
return { total: count, data: rows }
|
||||
})
|
||||
}
|
||||
|
||||
static async listForFeed (parameters: {
|
||||
start: number
|
||||
count: number
|
||||
videoId?: number
|
||||
videoAccountOwnerId?: number
|
||||
videoChannelOwnerId?: number
|
||||
}) {
|
||||
const blockerAccountIds = await VideoCommentModel.buildBlockerAccountIds({ user: null })
|
||||
|
||||
const queryOptions: ListVideoCommentsOptions = {
|
||||
...pick(parameters, [ 'start', 'count', 'videoAccountOwnerId', 'videoId', 'videoChannelOwnerId' ]),
|
||||
|
||||
selectType: 'feed',
|
||||
|
||||
sort: '-createdAt',
|
||||
onPublicVideo: true,
|
||||
|
||||
notDeleted: true,
|
||||
heldForReview: false,
|
||||
|
||||
blockerAccountIds
|
||||
}
|
||||
|
||||
return new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).list<MCommentOwnerVideoFeed>()
|
||||
}
|
||||
|
||||
static listForBulkDelete (
|
||||
ofAccount: MAccount,
|
||||
filter: {
|
||||
onVideosOfAccount?: MAccountId
|
||||
includeCollaborations?: boolean
|
||||
} = {}
|
||||
) {
|
||||
const queryOptions: ListVideoCommentsOptions = {
|
||||
selectType: 'comment-only',
|
||||
|
||||
accountId: ofAccount.id,
|
||||
videoAccountOwnerId: filter.onVideosOfAccount?.id,
|
||||
videoAccountOwnerIncludeCollaborations: filter.includeCollaborations,
|
||||
|
||||
heldForReview: undefined,
|
||||
|
||||
notDeleted: true,
|
||||
count: 5000
|
||||
}
|
||||
|
||||
return new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).list<MComment>()
|
||||
}
|
||||
|
||||
static listForExport (ofAccountId: number): Promise<MCommentExport[]> {
|
||||
return VideoCommentModel.findAll({
|
||||
attributes: [ 'id', 'url', 'text', 'createdAt' ],
|
||||
where: {
|
||||
accountId: ofAccountId,
|
||||
deletedAt: null
|
||||
},
|
||||
include: [
|
||||
{
|
||||
attributes: [ 'id', 'uuid', 'url' ],
|
||||
required: true,
|
||||
model: VideoModel.unscoped()
|
||||
},
|
||||
{
|
||||
attributes: [ 'url' ],
|
||||
required: false,
|
||||
model: VideoCommentModel,
|
||||
as: 'InReplyToVideoComment'
|
||||
}
|
||||
],
|
||||
limit: USER_EXPORT_MAX_ITEMS
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static async getStats () {
|
||||
const where = {
|
||||
deletedAt: null,
|
||||
heldForReview: false
|
||||
}
|
||||
|
||||
const totalLocalVideoComments = await VideoCommentModel.count({
|
||||
where,
|
||||
include: [
|
||||
{
|
||||
model: AccountModel.unscoped(),
|
||||
required: true,
|
||||
include: [
|
||||
{
|
||||
model: ActorModel.unscoped(),
|
||||
required: true,
|
||||
where: {
|
||||
serverId: null
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
})
|
||||
const totalVideoComments = await VideoCommentModel.count({ where })
|
||||
|
||||
return {
|
||||
totalLocalVideoComments,
|
||||
totalVideoComments
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static listRemoteCommentUrlsOfLocalVideos () {
|
||||
const query = `SELECT "videoComment".url FROM "videoComment" ` +
|
||||
`INNER JOIN account ON account.id = "videoComment"."accountId" ` +
|
||||
`INNER JOIN actor ON actor."accountId" = "account"."id" AND actor."serverId" IS NOT NULL ` +
|
||||
`INNER JOIN video ON video.id = "videoComment"."videoId" AND video.remote IS FALSE`
|
||||
|
||||
return VideoCommentModel.sequelize.query<{ url: string }>(query, {
|
||||
type: QueryTypes.SELECT,
|
||||
raw: true
|
||||
}).then(rows => rows.map(r => r.url))
|
||||
}
|
||||
|
||||
static cleanOldCommentsOf (videoId: number, beforeUpdatedAt: Date) {
|
||||
const query = {
|
||||
where: {
|
||||
updatedAt: {
|
||||
[Op.lt]: beforeUpdatedAt
|
||||
},
|
||||
videoId,
|
||||
accountId: {
|
||||
[Op.notIn]: buildLocalAccountIdsIn()
|
||||
},
|
||||
// Do not delete Tombstones
|
||||
deletedAt: null
|
||||
}
|
||||
}
|
||||
|
||||
return VideoCommentModel.destroy(query)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
getCommentStaticPath () {
|
||||
return this.Video.getWatchStaticPath() + ';threadId=' + this.getThreadId()
|
||||
}
|
||||
|
||||
getCommentUserReviewPath () {
|
||||
return '/my-account/videos/comments?search=heldForReview:true'
|
||||
}
|
||||
|
||||
getThreadId (): number {
|
||||
return this.originCommentId || this.id
|
||||
}
|
||||
|
||||
isLocal () {
|
||||
if (!this.Account) return false
|
||||
|
||||
return this.Account.isLocal()
|
||||
}
|
||||
|
||||
markAsDeleted () {
|
||||
this.text = ''
|
||||
this.deletedAt = new Date()
|
||||
this.accountId = null
|
||||
}
|
||||
|
||||
isDeleted () {
|
||||
return this.deletedAt !== null
|
||||
}
|
||||
|
||||
extractMentions () {
|
||||
return extractMentions(this.text, this.isLocal())
|
||||
}
|
||||
|
||||
toFormattedJSON (this: MCommentFormattable) {
|
||||
return {
|
||||
id: this.id,
|
||||
url: this.url,
|
||||
text: this.text,
|
||||
|
||||
threadId: this.getThreadId(),
|
||||
inReplyToCommentId: this.inReplyToCommentId || null,
|
||||
videoId: this.videoId,
|
||||
|
||||
createdAt: this.createdAt,
|
||||
updatedAt: this.updatedAt,
|
||||
deletedAt: this.deletedAt,
|
||||
|
||||
heldForReview: this.heldForReview,
|
||||
|
||||
isDeleted: this.isDeleted(),
|
||||
|
||||
totalRepliesFromVideoAuthor: this.get('totalRepliesFromVideoAuthor') || 0,
|
||||
totalReplies: this.get('totalReplies') || 0,
|
||||
|
||||
account: this.Account
|
||||
? this.Account.toFormattedJSON()
|
||||
: null
|
||||
} as VideoComment
|
||||
}
|
||||
|
||||
toFormattedForAdminOrUserJSON (this: MCommentAdminOrUserFormattable) {
|
||||
return {
|
||||
id: this.id,
|
||||
url: this.url,
|
||||
text: this.text,
|
||||
|
||||
threadId: this.getThreadId(),
|
||||
inReplyToCommentId: this.inReplyToCommentId || null,
|
||||
videoId: this.videoId,
|
||||
|
||||
createdAt: this.createdAt,
|
||||
updatedAt: this.updatedAt,
|
||||
|
||||
heldForReview: this.heldForReview,
|
||||
automaticTags: (this.CommentAutomaticTags || []).map(m => m.AutomaticTag.name),
|
||||
|
||||
video: {
|
||||
id: this.Video.id,
|
||||
uuid: this.Video.uuid,
|
||||
name: this.Video.name,
|
||||
|
||||
channel: this.Video.VideoChannel.toFormattedSummaryJSON()
|
||||
},
|
||||
|
||||
account: this.Account
|
||||
? this.Account.toFormattedJSON()
|
||||
: null
|
||||
} as VideoCommentForAdminOrUser
|
||||
}
|
||||
|
||||
toActivityPubObject (this: MCommentAP, threadParentComments: MCommentOwner[]): VideoCommentObject | ActivityTombstoneObject {
|
||||
const inReplyTo = this.inReplyToCommentId === null
|
||||
? this.Video.url // New thread, so we reply to the video
|
||||
: this.InReplyToVideoComment.url
|
||||
|
||||
if (this.isDeleted()) {
|
||||
return {
|
||||
id: this.url,
|
||||
type: 'Tombstone',
|
||||
formerType: 'Note',
|
||||
inReplyTo,
|
||||
published: this.createdAt.toISOString(),
|
||||
updated: this.updatedAt.toISOString(),
|
||||
deleted: this.deletedAt.toISOString()
|
||||
}
|
||||
}
|
||||
|
||||
const tag: ActivityTagObject[] = []
|
||||
for (const parentComment of threadParentComments) {
|
||||
if (!parentComment.Account) continue
|
||||
|
||||
const actor = parentComment.Account.Actor
|
||||
|
||||
tag.push({
|
||||
type: 'Mention',
|
||||
href: actor.url,
|
||||
name: `@${actor.preferredUsername}@${actor.getHost()}`
|
||||
})
|
||||
}
|
||||
|
||||
let replyApproval = this.replyApproval
|
||||
if (this.Video.isLocal() && !this.heldForReview) {
|
||||
replyApproval = getLocalApproveReplyActivityPubUrl(this.Video, this)
|
||||
}
|
||||
|
||||
return {
|
||||
type: 'Note' as 'Note',
|
||||
id: this.url,
|
||||
|
||||
content: this.text,
|
||||
mediaType: 'text/markdown',
|
||||
|
||||
inReplyTo,
|
||||
updated: this.updatedAt.toISOString(),
|
||||
published: this.createdAt.toISOString(),
|
||||
url: this.url,
|
||||
attributedTo: this.Account.Actor.url,
|
||||
replyApproval,
|
||||
tag
|
||||
}
|
||||
}
|
||||
|
||||
private static async buildBlockerAccountIds (options: {
|
||||
user: MUserAccountId
|
||||
}): Promise<number[]> {
|
||||
const { user } = options
|
||||
|
||||
const serverActor = await getServerActor()
|
||||
const blockerAccountIds = [ serverActor.Account.id ]
|
||||
|
||||
if (user) blockerAccountIds.push(user.Account.id)
|
||||
|
||||
return blockerAccountIds
|
||||
}
|
||||
|
||||
private static buildBlockerAccountIdsAndCanSeeHeldForReview (options: {
|
||||
video: MVideo
|
||||
user: MUserAccountId
|
||||
}) {
|
||||
const { video, user } = options
|
||||
const blockerAccountIdsPromise = this.buildBlockerAccountIds(options)
|
||||
|
||||
let canSeeHeldForReviewPromise: Promise<boolean>
|
||||
if (user) {
|
||||
if (user.hasRight(UserRight.SEE_ALL_COMMENTS)) {
|
||||
canSeeHeldForReviewPromise = Promise.resolve(true)
|
||||
} else {
|
||||
canSeeHeldForReviewPromise = VideoChannelModel.loadAndPopulateAccount(video.channelId)
|
||||
.then(c => c.accountId === user.Account.id)
|
||||
}
|
||||
} else {
|
||||
canSeeHeldForReviewPromise = Promise.resolve(false)
|
||||
}
|
||||
|
||||
return Promise.all([ blockerAccountIdsPromise, canSeeHeldForReviewPromise ])
|
||||
.then(([ blockerAccountIds, canSeeHeldForReview ]) => ({ blockerAccountIds, canSeeHeldForReview }))
|
||||
}
|
||||
}
|
||||
676
server/core/models/video/video-file.ts
Normal file
676
server/core/models/video/video-file.ts
Normal file
@@ -0,0 +1,676 @@
|
||||
import {
|
||||
ActivityVideoUrlObject,
|
||||
FileStorage,
|
||||
type FileStorageType,
|
||||
VideoFileFormatFlag,
|
||||
type VideoFileFormatFlagType,
|
||||
VideoFileStream,
|
||||
type VideoFileStreamType,
|
||||
VideoResolution
|
||||
} from '@peertube/peertube-models'
|
||||
import { logger } from '@server/helpers/logger.js'
|
||||
import { extractVideo } from '@server/helpers/video.js'
|
||||
import { CONFIG } from '@server/initializers/config.js'
|
||||
import { buildRemoteUrl } from '@server/lib/activitypub/url.js'
|
||||
import { getHLSPrivateFileUrl, getObjectStoragePublicFileUrl, getWebVideoPrivateFileUrl } from '@server/lib/object-storage/index.js'
|
||||
import { getFSTorrentFilePath } from '@server/lib/paths.js'
|
||||
import { getVideoFileMimeType } from '@server/lib/video-file.js'
|
||||
import { isVideoInPrivateDirectory } from '@server/lib/video-privacy.js'
|
||||
import { MStreamingPlaylistVideo, MVideo, MVideoWithHost, isStreamingPlaylist } from '@server/types/models/index.js'
|
||||
import { remove } from 'fs-extra/esm'
|
||||
import memoizee from 'memoizee'
|
||||
import { join } from 'path'
|
||||
import { FindOptions, Op, Transaction, WhereOptions } from 'sequelize'
|
||||
import {
|
||||
AllowNull,
|
||||
BelongsTo,
|
||||
Column,
|
||||
CreatedAt,
|
||||
DataType,
|
||||
Default,
|
||||
DefaultScope,
|
||||
ForeignKey,
|
||||
Is,
|
||||
Scopes,
|
||||
Table,
|
||||
UpdatedAt
|
||||
} from 'sequelize-typescript'
|
||||
import validator from 'validator'
|
||||
import {
|
||||
isVideoFPSResolutionValid,
|
||||
isVideoFileExtnameValid,
|
||||
isVideoFileInfoHashValid,
|
||||
isVideoFileResolutionValid,
|
||||
isVideoFileSizeValid
|
||||
} from '../../helpers/custom-validators/videos.js'
|
||||
import { DOWNLOAD_PATHS, LAZY_STATIC_PATHS, MEMOIZE_LENGTH, MEMOIZE_TTL, STATIC_PATHS, WEBSERVER } from '../../initializers/constants.js'
|
||||
import { MVideoFile, MVideoFileStreamingPlaylistVideo, MVideoFileVideo } from '../../types/models/video/video-file.js'
|
||||
import { SequelizeModel, doesExist, parseAggregateResult, throwIfNotValid } from '../shared/index.js'
|
||||
import { VideoStreamingPlaylistModel } from './video-streaming-playlist.js'
|
||||
import { VideoModel } from './video.js'
|
||||
|
||||
export enum ScopeNames {
|
||||
WITH_VIDEO = 'WITH_VIDEO',
|
||||
WITH_METADATA = 'WITH_METADATA',
|
||||
WITH_VIDEO_OR_PLAYLIST = 'WITH_VIDEO_OR_PLAYLIST'
|
||||
}
|
||||
|
||||
@DefaultScope(() => ({
|
||||
attributes: {
|
||||
exclude: [ 'metadata' ]
|
||||
}
|
||||
}))
|
||||
@Scopes(() => ({
|
||||
[ScopeNames.WITH_VIDEO]: {
|
||||
include: [
|
||||
{
|
||||
model: VideoModel.unscoped(),
|
||||
required: true
|
||||
}
|
||||
]
|
||||
},
|
||||
[ScopeNames.WITH_VIDEO_OR_PLAYLIST]: (options: { whereVideo?: WhereOptions } = {}) => {
|
||||
return {
|
||||
include: [
|
||||
{
|
||||
model: VideoModel.unscoped(),
|
||||
required: false,
|
||||
where: options.whereVideo
|
||||
},
|
||||
{
|
||||
model: VideoStreamingPlaylistModel.unscoped(),
|
||||
required: false,
|
||||
include: [
|
||||
{
|
||||
model: VideoModel.unscoped(),
|
||||
required: true,
|
||||
where: options.whereVideo
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
[ScopeNames.WITH_METADATA]: {
|
||||
attributes: {
|
||||
include: [ 'metadata' ]
|
||||
}
|
||||
}
|
||||
}))
|
||||
@Table({
|
||||
tableName: 'videoFile',
|
||||
indexes: [
|
||||
{
|
||||
fields: [ 'infoHash' ]
|
||||
},
|
||||
|
||||
{
|
||||
fields: [ 'torrentFilename' ],
|
||||
unique: true
|
||||
},
|
||||
|
||||
{
|
||||
fields: [ 'filename' ],
|
||||
unique: true
|
||||
},
|
||||
|
||||
{
|
||||
fields: [ 'videoId', 'resolution', 'fps' ],
|
||||
unique: true,
|
||||
where: {
|
||||
videoId: {
|
||||
[Op.ne]: null
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
fields: [ 'videoStreamingPlaylistId', 'resolution', 'fps' ],
|
||||
unique: true,
|
||||
where: {
|
||||
videoStreamingPlaylistId: {
|
||||
[Op.ne]: null
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
})
|
||||
export class VideoFileModel extends SequelizeModel<VideoFileModel> {
|
||||
@CreatedAt
|
||||
declare createdAt: Date
|
||||
|
||||
@UpdatedAt
|
||||
declare updatedAt: Date
|
||||
|
||||
@AllowNull(false)
|
||||
@Is('VideoFileResolution', value => throwIfNotValid(value, isVideoFileResolutionValid, 'resolution'))
|
||||
@Column
|
||||
declare resolution: number
|
||||
|
||||
@AllowNull(true)
|
||||
@Column
|
||||
declare width: number
|
||||
|
||||
@AllowNull(true)
|
||||
@Column
|
||||
declare height: number
|
||||
|
||||
@AllowNull(false)
|
||||
@Is('VideoFileSize', value => throwIfNotValid(value, isVideoFileSizeValid, 'size'))
|
||||
@Column(DataType.BIGINT)
|
||||
declare size: number
|
||||
|
||||
@AllowNull(false)
|
||||
@Is('VideoFileExtname', value => throwIfNotValid(value, isVideoFileExtnameValid, 'extname'))
|
||||
@Column
|
||||
declare extname: string
|
||||
|
||||
@AllowNull(true)
|
||||
@Is('VideoFileInfohash', value => throwIfNotValid(value, isVideoFileInfoHashValid, 'info hash', true))
|
||||
@Column
|
||||
declare infoHash: string
|
||||
|
||||
@AllowNull(false)
|
||||
@Default(-1)
|
||||
@Is('VideoFileFPS', value => throwIfNotValid(value, isVideoFPSResolutionValid, 'fps'))
|
||||
@Column
|
||||
declare fps: number
|
||||
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare formatFlags: VideoFileFormatFlagType
|
||||
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare streams: VideoFileStreamType
|
||||
|
||||
@AllowNull(true)
|
||||
@Column(DataType.JSONB)
|
||||
declare metadata: any
|
||||
|
||||
@AllowNull(true)
|
||||
@Column
|
||||
declare metadataUrl: string
|
||||
|
||||
// Could be null for remote files
|
||||
@AllowNull(true)
|
||||
@Column
|
||||
declare fileUrl: string
|
||||
|
||||
// Could be null for live files
|
||||
@AllowNull(true)
|
||||
@Column
|
||||
declare filename: string
|
||||
|
||||
// Could be null for remote files
|
||||
@AllowNull(true)
|
||||
@Column
|
||||
declare torrentUrl: string
|
||||
|
||||
// Could be null for live files
|
||||
@AllowNull(true)
|
||||
@Column
|
||||
declare torrentFilename: string
|
||||
|
||||
@ForeignKey(() => VideoModel)
|
||||
@Column
|
||||
declare videoId: number
|
||||
|
||||
@AllowNull(false)
|
||||
@Default(FileStorage.FILE_SYSTEM)
|
||||
@Column
|
||||
declare storage: FileStorageType
|
||||
|
||||
@BelongsTo(() => VideoModel, {
|
||||
foreignKey: {
|
||||
allowNull: true
|
||||
},
|
||||
onDelete: 'CASCADE'
|
||||
})
|
||||
declare Video: Awaited<VideoModel>
|
||||
|
||||
@ForeignKey(() => VideoStreamingPlaylistModel)
|
||||
@Column
|
||||
declare videoStreamingPlaylistId: number
|
||||
|
||||
@BelongsTo(() => VideoStreamingPlaylistModel, {
|
||||
foreignKey: {
|
||||
allowNull: true
|
||||
},
|
||||
onDelete: 'CASCADE'
|
||||
})
|
||||
declare VideoStreamingPlaylist: Awaited<VideoStreamingPlaylistModel>
|
||||
|
||||
static doesInfohashExistCached = memoizee(VideoFileModel.doesInfohashExist.bind(VideoFileModel), {
|
||||
promise: true,
|
||||
max: MEMOIZE_LENGTH.INFO_HASH_EXISTS,
|
||||
maxAge: MEMOIZE_TTL.INFO_HASH_EXISTS
|
||||
})
|
||||
|
||||
static doesInfohashExist (infoHash: string) {
|
||||
const query = 'SELECT 1 FROM "videoFile" WHERE "infoHash" = $infoHash LIMIT 1'
|
||||
|
||||
return doesExist({ sequelize: this.sequelize, query, bind: { infoHash } })
|
||||
}
|
||||
|
||||
static async doesVideoExistForVideoFile (id: number, videoIdOrUUID: number | string) {
|
||||
const videoFile = await VideoFileModel.loadWithVideoOrPlaylist(id, videoIdOrUUID)
|
||||
|
||||
return !!videoFile
|
||||
}
|
||||
|
||||
static async doesOwnedTorrentFileExist (filename: string) {
|
||||
const query = 'SELECT 1 FROM "videoFile" ' +
|
||||
'LEFT JOIN "video" "webvideo" ON "webvideo"."id" = "videoFile"."videoId" AND "webvideo"."remote" IS FALSE ' +
|
||||
'LEFT JOIN "videoStreamingPlaylist" ON "videoStreamingPlaylist"."id" = "videoFile"."videoStreamingPlaylistId" ' +
|
||||
'LEFT JOIN "video" "hlsVideo" ON "hlsVideo"."id" = "videoStreamingPlaylist"."videoId" AND "hlsVideo"."remote" IS FALSE ' +
|
||||
'WHERE "torrentFilename" = $filename AND ("hlsVideo"."id" IS NOT NULL OR "webvideo"."id" IS NOT NULL) LIMIT 1'
|
||||
|
||||
return doesExist({ sequelize: this.sequelize, query, bind: { filename } })
|
||||
}
|
||||
|
||||
static async doesOwnedWebVideoFileExist (filename: string, storage: FileStorageType) {
|
||||
const query = 'SELECT 1 FROM "videoFile" INNER JOIN "video" ON "video"."id" = "videoFile"."videoId" AND "video"."remote" IS FALSE ' +
|
||||
`WHERE "filename" = $filename AND "storage" = $storage LIMIT 1`
|
||||
|
||||
return doesExist({ sequelize: this.sequelize, query, bind: { filename, storage } })
|
||||
}
|
||||
|
||||
static loadByFilename (filename: string) {
|
||||
const query = {
|
||||
where: {
|
||||
filename
|
||||
}
|
||||
}
|
||||
|
||||
return VideoFileModel.findOne(query)
|
||||
}
|
||||
|
||||
static loadWithVideoByFilename (filename: string): Promise<MVideoFileVideo | MVideoFileStreamingPlaylistVideo> {
|
||||
const query = {
|
||||
where: {
|
||||
filename
|
||||
}
|
||||
}
|
||||
|
||||
return VideoFileModel.scope(ScopeNames.WITH_VIDEO_OR_PLAYLIST).findOne(query)
|
||||
}
|
||||
|
||||
static loadWithVideoOrPlaylistByTorrentFilename (filename: string) {
|
||||
const query = {
|
||||
where: {
|
||||
torrentFilename: filename
|
||||
}
|
||||
}
|
||||
|
||||
return VideoFileModel.scope(ScopeNames.WITH_VIDEO_OR_PLAYLIST).findOne(query)
|
||||
}
|
||||
|
||||
static load (id: number): Promise<MVideoFile> {
|
||||
return VideoFileModel.findByPk(id)
|
||||
}
|
||||
|
||||
static loadWithMetadata (id: number) {
|
||||
return VideoFileModel.scope(ScopeNames.WITH_METADATA).findByPk<MVideoFile>(id)
|
||||
}
|
||||
|
||||
static loadWithVideo (id: number, transaction?: Transaction) {
|
||||
return VideoFileModel.scope(ScopeNames.WITH_VIDEO).findByPk<MVideoFileVideo>(id, { transaction })
|
||||
}
|
||||
|
||||
static loadWithVideoOrPlaylist (id: number, videoIdOrUUID: number | string) {
|
||||
const whereVideo = validator.default.isUUID(videoIdOrUUID + '')
|
||||
? { uuid: videoIdOrUUID }
|
||||
: { id: videoIdOrUUID }
|
||||
|
||||
const options = {
|
||||
where: {
|
||||
id
|
||||
}
|
||||
}
|
||||
|
||||
return VideoFileModel.scope({ method: [ ScopeNames.WITH_VIDEO_OR_PLAYLIST, { whereVideo } ] })
|
||||
.findOne(options)
|
||||
.then(file => {
|
||||
if (!file) return null
|
||||
|
||||
// We used `required: false` so check we have at least a video or a streaming playlist
|
||||
if (!file.Video && !file.VideoStreamingPlaylist) return null
|
||||
|
||||
return file
|
||||
})
|
||||
}
|
||||
|
||||
static listByStreamingPlaylist (streamingPlaylistId: number, transaction: Transaction) {
|
||||
const query = {
|
||||
include: [
|
||||
{
|
||||
model: VideoStreamingPlaylistModel.unscoped(),
|
||||
required: true,
|
||||
where: {
|
||||
id: streamingPlaylistId
|
||||
}
|
||||
}
|
||||
],
|
||||
transaction
|
||||
}
|
||||
|
||||
return VideoFileModel.findAll<MVideoFile>(query)
|
||||
}
|
||||
|
||||
static getStats () {
|
||||
const webVideoFilesQuery: FindOptions = {
|
||||
include: [
|
||||
{
|
||||
attributes: [],
|
||||
required: true,
|
||||
model: VideoModel.unscoped(),
|
||||
where: {
|
||||
remote: false
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
const hlsFilesQuery: FindOptions = {
|
||||
include: [
|
||||
{
|
||||
attributes: [],
|
||||
required: true,
|
||||
model: VideoStreamingPlaylistModel.unscoped(),
|
||||
include: [
|
||||
{
|
||||
attributes: [],
|
||||
model: VideoModel.unscoped(),
|
||||
required: true,
|
||||
where: {
|
||||
remote: false
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
return Promise.all([
|
||||
VideoFileModel.aggregate('size', 'SUM', webVideoFilesQuery),
|
||||
VideoFileModel.aggregate('size', 'SUM', hlsFilesQuery)
|
||||
]).then(([ webVideoResult, hlsResult ]) => ({
|
||||
totalLocalVideoFilesSize: parseAggregateResult(webVideoResult) + parseAggregateResult(hlsResult)
|
||||
}))
|
||||
}
|
||||
|
||||
// Redefine upsert because sequelize does not use an appropriate where clause in the update query with 2 unique indexes
|
||||
static async customUpsert (
|
||||
videoFile: MVideoFile,
|
||||
mode: 'streaming-playlist' | 'video',
|
||||
transaction: Transaction
|
||||
) {
|
||||
const baseFind = {
|
||||
fps: videoFile.fps,
|
||||
resolution: videoFile.resolution,
|
||||
transaction
|
||||
}
|
||||
|
||||
const element = mode === 'streaming-playlist'
|
||||
? await VideoFileModel.loadHLSFile({ ...baseFind, playlistId: videoFile.videoStreamingPlaylistId })
|
||||
: await VideoFileModel.loadWebVideoFile({ ...baseFind, videoId: videoFile.videoId })
|
||||
|
||||
if (!element) return videoFile.save({ transaction })
|
||||
|
||||
for (const k of Object.keys(videoFile.toJSON())) {
|
||||
element.set(k, videoFile[k])
|
||||
}
|
||||
|
||||
return element.save({ transaction })
|
||||
}
|
||||
|
||||
static async loadWebVideoFile (options: {
|
||||
videoId: number
|
||||
fps: number
|
||||
resolution: number
|
||||
transaction?: Transaction
|
||||
}) {
|
||||
const where = {
|
||||
fps: options.fps,
|
||||
resolution: options.resolution,
|
||||
videoId: options.videoId
|
||||
}
|
||||
|
||||
return VideoFileModel.findOne({ where, transaction: options.transaction })
|
||||
}
|
||||
|
||||
static async loadHLSFile (options: {
|
||||
playlistId: number
|
||||
fps: number
|
||||
resolution: number
|
||||
transaction?: Transaction
|
||||
}) {
|
||||
const where = {
|
||||
fps: options.fps,
|
||||
resolution: options.resolution,
|
||||
videoStreamingPlaylistId: options.playlistId
|
||||
}
|
||||
|
||||
return VideoFileModel.findOne({ where, transaction: options.transaction })
|
||||
}
|
||||
|
||||
static removeHLSFilesOfStreamingPlaylistId (videoStreamingPlaylistId: number) {
|
||||
const options = {
|
||||
where: { videoStreamingPlaylistId }
|
||||
}
|
||||
|
||||
return VideoFileModel.destroy(options)
|
||||
}
|
||||
|
||||
hasTorrent () {
|
||||
return this.infoHash && this.torrentFilename
|
||||
}
|
||||
|
||||
getVideoOrStreamingPlaylist (this: MVideoFileVideo | MVideoFileStreamingPlaylistVideo): MVideo | MStreamingPlaylistVideo {
|
||||
if (this.videoId || (this as MVideoFileVideo).Video) return (this as MVideoFileVideo).Video
|
||||
|
||||
return (this as MVideoFileStreamingPlaylistVideo).VideoStreamingPlaylist
|
||||
}
|
||||
|
||||
getVideo (this: MVideoFileVideo | MVideoFileStreamingPlaylistVideo): MVideo {
|
||||
return extractVideo(this.getVideoOrStreamingPlaylist())
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
isAudio () {
|
||||
return this.resolution === VideoResolution.H_NOVIDEO
|
||||
}
|
||||
|
||||
isLive () {
|
||||
return this.size === -1
|
||||
}
|
||||
|
||||
isHLS () {
|
||||
return !!this.videoStreamingPlaylistId
|
||||
}
|
||||
|
||||
hasAudio () {
|
||||
return (this.streams & VideoFileStream.AUDIO) === VideoFileStream.AUDIO
|
||||
}
|
||||
|
||||
hasVideo () {
|
||||
return (this.streams & VideoFileStream.VIDEO) === VideoFileStream.VIDEO
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
getObjectStorageUrl (video: MVideo) {
|
||||
if (video.hasPrivateStaticPath() && CONFIG.OBJECT_STORAGE.PROXY.PROXIFY_PRIVATE_FILES === true) {
|
||||
return this.getPrivateObjectStorageUrl(video)
|
||||
}
|
||||
|
||||
return this.getPublicObjectStorageUrl()
|
||||
}
|
||||
|
||||
private getPrivateObjectStorageUrl (video: MVideo) {
|
||||
if (this.isHLS()) {
|
||||
return getHLSPrivateFileUrl(video, this.filename)
|
||||
}
|
||||
|
||||
return getWebVideoPrivateFileUrl(this.filename)
|
||||
}
|
||||
|
||||
private getPublicObjectStorageUrl () {
|
||||
if (this.isHLS()) {
|
||||
return getObjectStoragePublicFileUrl(this.fileUrl, CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS)
|
||||
}
|
||||
|
||||
return getObjectStoragePublicFileUrl(this.fileUrl, CONFIG.OBJECT_STORAGE.WEB_VIDEOS)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
getFileUrl (video: MVideo) {
|
||||
if (video.isLocal()) {
|
||||
if (this.storage === FileStorage.OBJECT_STORAGE) {
|
||||
return this.getObjectStorageUrl(video)
|
||||
}
|
||||
|
||||
return WEBSERVER.URL + this.getFileStaticPath(video)
|
||||
}
|
||||
|
||||
return this.fileUrl
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
getFileStaticPath (video: MVideo) {
|
||||
if (this.isHLS()) return this.getHLSFileStaticPath(video)
|
||||
|
||||
return this.getWebVideoFileStaticPath(video)
|
||||
}
|
||||
|
||||
private getWebVideoFileStaticPath (video: MVideo) {
|
||||
if (isVideoInPrivateDirectory(video.privacy)) {
|
||||
return join(STATIC_PATHS.PRIVATE_WEB_VIDEOS, this.filename)
|
||||
}
|
||||
|
||||
return join(STATIC_PATHS.WEB_VIDEOS, this.filename)
|
||||
}
|
||||
|
||||
private getHLSFileStaticPath (video: MVideo) {
|
||||
if (isVideoInPrivateDirectory(video.privacy)) {
|
||||
return join(STATIC_PATHS.STREAMING_PLAYLISTS.PRIVATE_HLS, video.uuid, this.filename)
|
||||
}
|
||||
|
||||
return join(STATIC_PATHS.STREAMING_PLAYLISTS.HLS, video.uuid, this.filename)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
getFileDownloadUrl (video: MVideoWithHost) {
|
||||
const path = this.isHLS()
|
||||
? join(DOWNLOAD_PATHS.HLS_VIDEOS, `${video.uuid}-${this.resolution}-fragmented${this.extname}`)
|
||||
: join(DOWNLOAD_PATHS.WEB_VIDEOS, `${video.uuid}-${this.resolution}${this.extname}`)
|
||||
|
||||
if (video.isLocal()) return WEBSERVER.URL + path
|
||||
|
||||
// FIXME: don't guess remote URL
|
||||
return buildRemoteUrl(video, path)
|
||||
}
|
||||
|
||||
getRemoteTorrentUrl (video: MVideo) {
|
||||
if (video.isLocal()) throw new Error(`Video ${video.url} is not a remote video`)
|
||||
|
||||
return this.torrentUrl
|
||||
}
|
||||
|
||||
// We proxify torrent requests so use a local URL
|
||||
getTorrentUrl () {
|
||||
if (!this.torrentFilename) return null
|
||||
|
||||
return WEBSERVER.URL + this.getTorrentStaticPath()
|
||||
}
|
||||
|
||||
getTorrentStaticPath () {
|
||||
if (!this.torrentFilename) return null
|
||||
|
||||
return join(LAZY_STATIC_PATHS.TORRENTS, this.torrentFilename)
|
||||
}
|
||||
|
||||
getTorrentDownloadUrl () {
|
||||
if (!this.torrentFilename) return null
|
||||
|
||||
return WEBSERVER.URL + join(DOWNLOAD_PATHS.TORRENTS, this.torrentFilename)
|
||||
}
|
||||
|
||||
removeTorrent () {
|
||||
if (!this.torrentFilename) return null
|
||||
|
||||
const torrentPath = getFSTorrentFilePath(this)
|
||||
return remove(torrentPath)
|
||||
.catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
|
||||
}
|
||||
|
||||
hasSameUniqueKeysThan (other: MVideoFile) {
|
||||
return this.fps === other.fps &&
|
||||
this.resolution === other.resolution &&
|
||||
(
|
||||
(this.videoId !== null && this.videoId === other.videoId) ||
|
||||
(this.videoStreamingPlaylistId !== null && this.videoStreamingPlaylistId === other.videoStreamingPlaylistId)
|
||||
)
|
||||
}
|
||||
|
||||
withVideoOrPlaylist (videoOrPlaylist: MVideo | MStreamingPlaylistVideo) {
|
||||
if (isStreamingPlaylist(videoOrPlaylist)) return Object.assign(this, { VideoStreamingPlaylist: videoOrPlaylist })
|
||||
|
||||
return Object.assign(this, { Video: videoOrPlaylist })
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
toActivityPubObject (this: MVideoFile, video: MVideo): ActivityVideoUrlObject {
|
||||
const mimeType = getVideoFileMimeType(this.extname, false)
|
||||
|
||||
const attachment: ActivityVideoUrlObject['attachment'] = []
|
||||
|
||||
if (this.hasAudio()) {
|
||||
attachment.push({
|
||||
type: 'PropertyValue',
|
||||
name: 'ffprobe_codec_type',
|
||||
value: 'audio'
|
||||
})
|
||||
}
|
||||
|
||||
if (this.hasVideo()) {
|
||||
attachment.push({
|
||||
type: 'PropertyValue',
|
||||
name: 'ffprobe_codec_type',
|
||||
value: 'video'
|
||||
})
|
||||
}
|
||||
|
||||
if (this.formatFlags & VideoFileFormatFlag.FRAGMENTED) {
|
||||
attachment.push({
|
||||
type: 'PropertyValue',
|
||||
name: 'peertube_format_flag',
|
||||
value: 'fragmented'
|
||||
})
|
||||
}
|
||||
|
||||
if (this.formatFlags & VideoFileFormatFlag.WEB_VIDEO) {
|
||||
attachment.push({
|
||||
type: 'PropertyValue',
|
||||
name: 'peertube_format_flag',
|
||||
value: 'web-video'
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
type: 'Link',
|
||||
mediaType: mimeType as ActivityVideoUrlObject['mediaType'],
|
||||
href: this.getFileUrl(video),
|
||||
height: this.height || this.resolution,
|
||||
width: this.width,
|
||||
size: this.size,
|
||||
fps: this.fps,
|
||||
attachment
|
||||
}
|
||||
}
|
||||
}
|
||||
280
server/core/models/video/video-import.ts
Normal file
280
server/core/models/video/video-import.ts
Normal file
@@ -0,0 +1,280 @@
|
||||
import { VideoImport, type VideoImportPayload, VideoImportState, type VideoImportStateType } from '@peertube/peertube-models'
|
||||
import { CONFIG } from '@server/initializers/config.js'
|
||||
import { MVideoImport, MVideoImportDefault, MVideoImportFormattable } from '@server/types/models/video/video-import.js'
|
||||
import { Op } from 'sequelize'
|
||||
import {
|
||||
AllowNull,
|
||||
BelongsTo,
|
||||
Column,
|
||||
CreatedAt,
|
||||
DataType,
|
||||
Default,
|
||||
DefaultScope,
|
||||
ForeignKey,
|
||||
Is,
|
||||
Table,
|
||||
UpdatedAt
|
||||
} from 'sequelize-typescript'
|
||||
import { isVideoImportStateValid, isVideoImportTargetUrlValid } from '../../helpers/custom-validators/video-imports.js'
|
||||
import { isVideoMagnetUriValid } from '../../helpers/custom-validators/videos.js'
|
||||
import { CONSTRAINTS_FIELDS, VIDEO_IMPORT_STATES } from '../../initializers/constants.js'
|
||||
import { buildSQLAttributes, getSort, SequelizeModel, throwIfNotValid } from '../shared/index.js'
|
||||
import { UserModel } from '../user/user.js'
|
||||
import { ListVideoImportsOptions, VideoImportListQueryBuilder } from './sql/import/video-import-list-query-builder.js'
|
||||
import { VideoChannelSyncModel } from './video-channel-sync.js'
|
||||
import { VideoModel, ScopeNames as VideoModelScopeNames } from './video.js'
|
||||
|
||||
const defaultVideoScope = () => {
|
||||
return VideoModel.scope([
|
||||
VideoModelScopeNames.WITH_ACCOUNT_DETAILS,
|
||||
VideoModelScopeNames.WITH_TAGS,
|
||||
VideoModelScopeNames.WITH_THUMBNAILS
|
||||
])
|
||||
}
|
||||
|
||||
@DefaultScope(() => ({
|
||||
include: [
|
||||
{
|
||||
model: UserModel.unscoped(),
|
||||
required: true
|
||||
},
|
||||
{
|
||||
model: defaultVideoScope(),
|
||||
required: false
|
||||
},
|
||||
{
|
||||
model: VideoChannelSyncModel.unscoped(),
|
||||
required: false
|
||||
}
|
||||
]
|
||||
}))
|
||||
@Table({
|
||||
tableName: 'videoImport',
|
||||
indexes: [
|
||||
{
|
||||
fields: [ 'videoId' ],
|
||||
unique: true
|
||||
},
|
||||
{
|
||||
fields: [ 'userId' ]
|
||||
}
|
||||
]
|
||||
})
|
||||
export class VideoImportModel extends SequelizeModel<VideoImportModel> {
|
||||
@CreatedAt
|
||||
declare createdAt: Date
|
||||
|
||||
@UpdatedAt
|
||||
declare updatedAt: Date
|
||||
|
||||
@AllowNull(true)
|
||||
@Default(null)
|
||||
@Is('VideoImportTargetUrl', value => throwIfNotValid(value, isVideoImportTargetUrlValid, 'targetUrl', true))
|
||||
@Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_IMPORTS.URL.max))
|
||||
declare targetUrl: string
|
||||
|
||||
@AllowNull(true)
|
||||
@Default(null)
|
||||
@Is('VideoImportMagnetUri', value => throwIfNotValid(value, isVideoMagnetUriValid, 'magnetUri', true))
|
||||
@Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_IMPORTS.URL.max)) // Use the same constraints than URLs
|
||||
declare magnetUri: string
|
||||
|
||||
@AllowNull(true)
|
||||
@Default(null)
|
||||
@Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_IMPORTS.TORRENT_NAME.max))
|
||||
declare torrentName: string
|
||||
|
||||
@AllowNull(false)
|
||||
@Default(null)
|
||||
@Is('VideoImportState', value => throwIfNotValid(value, isVideoImportStateValid, 'state'))
|
||||
@Column
|
||||
declare state: VideoImportStateType
|
||||
|
||||
@AllowNull(true)
|
||||
@Default(null)
|
||||
@Column(DataType.TEXT)
|
||||
declare error: string
|
||||
|
||||
@AllowNull(false)
|
||||
@Default(0)
|
||||
@Column
|
||||
declare attempts: number
|
||||
|
||||
@AllowNull(true)
|
||||
@Column(DataType.JSONB)
|
||||
declare payload: VideoImportPayload
|
||||
|
||||
@ForeignKey(() => UserModel)
|
||||
@Column
|
||||
declare userId: number
|
||||
|
||||
@BelongsTo(() => UserModel, {
|
||||
foreignKey: {
|
||||
allowNull: false
|
||||
},
|
||||
onDelete: 'cascade'
|
||||
})
|
||||
declare User: Awaited<UserModel>
|
||||
|
||||
@ForeignKey(() => VideoModel)
|
||||
@Column
|
||||
declare videoId: number
|
||||
|
||||
@BelongsTo(() => VideoModel, {
|
||||
foreignKey: {
|
||||
allowNull: true
|
||||
},
|
||||
onDelete: 'set null'
|
||||
})
|
||||
declare Video: Awaited<VideoModel>
|
||||
|
||||
@ForeignKey(() => VideoChannelSyncModel)
|
||||
@Column
|
||||
declare videoChannelSyncId: number
|
||||
|
||||
@BelongsTo(() => VideoChannelSyncModel, {
|
||||
foreignKey: {
|
||||
allowNull: true
|
||||
},
|
||||
onDelete: 'set null'
|
||||
})
|
||||
declare VideoChannelSync: Awaited<VideoChannelSyncModel>
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static getSQLAttributes (tableName: string, aliasPrefix = '') {
|
||||
return buildSQLAttributes({
|
||||
model: this,
|
||||
tableName,
|
||||
aliasPrefix
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static loadAndPopulateVideo (id: number): Promise<MVideoImportDefault> {
|
||||
return VideoImportModel.findByPk(id)
|
||||
}
|
||||
|
||||
static listUserVideoImportsForApi (options: ListVideoImportsOptions) {
|
||||
return Promise.all([
|
||||
new VideoImportListQueryBuilder(VideoImportModel.sequelize, options).list<MVideoImportFormattable>(),
|
||||
new VideoImportListQueryBuilder(VideoImportModel.sequelize, options).count()
|
||||
]).then(([ rows, count ]) => {
|
||||
return { total: count, data: rows }
|
||||
})
|
||||
}
|
||||
|
||||
static async urlAlreadyImported (options: {
|
||||
targetUrl: string
|
||||
channelId: number
|
||||
channelSyncId?: number
|
||||
}): Promise<boolean> {
|
||||
const { channelSyncId, channelId, targetUrl } = options
|
||||
|
||||
const baseWhere = { targetUrl }
|
||||
|
||||
const bySyncId = channelSyncId
|
||||
? VideoImportModel.unscoped().findOne({
|
||||
where: {
|
||||
...baseWhere,
|
||||
|
||||
videoChannelSyncId: channelSyncId
|
||||
}
|
||||
})
|
||||
: Promise.resolve(undefined)
|
||||
|
||||
const byChannelId = VideoImportModel.unscoped().findOne({
|
||||
where: baseWhere,
|
||||
include: [
|
||||
{
|
||||
model: VideoModel.unscoped(),
|
||||
required: true,
|
||||
where: {
|
||||
channelId
|
||||
}
|
||||
}
|
||||
]
|
||||
})
|
||||
|
||||
return (await Promise.all([ bySyncId, byChannelId ])).some(e => !!e)
|
||||
}
|
||||
|
||||
static listFailedBySyncId (options: {
|
||||
channelSyncId?: number
|
||||
}): Promise<MVideoImport[]> {
|
||||
return VideoImportModel.unscoped().findAll({
|
||||
include: [
|
||||
{
|
||||
model: VideoModel.unscoped(),
|
||||
required: true
|
||||
}
|
||||
],
|
||||
where: {
|
||||
videoChannelSyncId: options.channelSyncId,
|
||||
state: {
|
||||
[Op.in]: [ VideoImportState.FAILED ]
|
||||
},
|
||||
attempts: {
|
||||
[Op.lt]: CONFIG.IMPORT.VIDEOS.MAX_ATTEMPTS
|
||||
}
|
||||
},
|
||||
limit: 100
|
||||
})
|
||||
}
|
||||
|
||||
static loadLastImportBySyncId (options: {
|
||||
channelSyncId: number
|
||||
}) {
|
||||
return VideoImportModel.findOne<MVideoImportDefault>({
|
||||
where: {
|
||||
videoChannelSyncId: options.channelSyncId
|
||||
},
|
||||
order: getSort('-createdAt')
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
getTargetIdentifier () {
|
||||
return this.targetUrl || this.magnetUri || this.torrentName
|
||||
}
|
||||
|
||||
toFormattedJSON (this: MVideoImportFormattable): VideoImport {
|
||||
const videoFormatOptions = {
|
||||
completeDescription: true,
|
||||
additionalAttributes: { state: true, waitTranscoding: true, scheduledUpdate: true }
|
||||
}
|
||||
const video = this.Video
|
||||
? Object.assign(this.Video.toFormattedJSON(videoFormatOptions), { tags: this.Video.Tags.map(t => t.name) })
|
||||
: undefined
|
||||
|
||||
const videoChannelSync = this.VideoChannelSync
|
||||
? { id: this.VideoChannelSync.id, externalChannelUrl: this.VideoChannelSync.externalChannelUrl }
|
||||
: undefined
|
||||
|
||||
return {
|
||||
id: this.id,
|
||||
|
||||
targetUrl: this.targetUrl,
|
||||
magnetUri: this.magnetUri,
|
||||
torrentName: this.torrentName,
|
||||
|
||||
attempts: this.attempts,
|
||||
|
||||
state: {
|
||||
id: this.state,
|
||||
label: VideoImportModel.getStateLabel(this.state)
|
||||
},
|
||||
error: this.error,
|
||||
updatedAt: this.updatedAt.toISOString(),
|
||||
createdAt: this.createdAt.toISOString(),
|
||||
video,
|
||||
videoChannelSync
|
||||
}
|
||||
}
|
||||
|
||||
private static getStateLabel (id: number) {
|
||||
return VIDEO_IMPORT_STATES[id] || 'Unknown'
|
||||
}
|
||||
}
|
||||
135
server/core/models/video/video-job-info.ts
Normal file
135
server/core/models/video/video-job-info.ts
Normal file
@@ -0,0 +1,135 @@
|
||||
import { forceNumber } from '@peertube/peertube-core-utils'
|
||||
import { Op, QueryTypes, Transaction } from 'sequelize'
|
||||
import { AllowNull, BelongsTo, Column, CreatedAt, Default, ForeignKey, IsInt, Table, Unique, UpdatedAt } from 'sequelize-typescript'
|
||||
import { SequelizeModel } from '../shared/sequelize-type.js'
|
||||
import { VideoModel } from './video.js'
|
||||
|
||||
export type VideoJobInfoColumnType = 'pendingMove' | 'pendingTranscode' | 'pendingTranscription'
|
||||
|
||||
@Table({
|
||||
tableName: 'videoJobInfo',
|
||||
indexes: [
|
||||
{
|
||||
fields: [ 'videoId' ],
|
||||
where: {
|
||||
videoId: {
|
||||
[Op.ne]: null
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
})
|
||||
export class VideoJobInfoModel extends SequelizeModel<VideoJobInfoModel> {
|
||||
@CreatedAt
|
||||
declare createdAt: Date
|
||||
|
||||
@UpdatedAt
|
||||
declare updatedAt: Date
|
||||
|
||||
@AllowNull(false)
|
||||
@Default(0)
|
||||
@IsInt
|
||||
@Column
|
||||
declare pendingMove: number
|
||||
|
||||
@AllowNull(false)
|
||||
@Default(0)
|
||||
@IsInt
|
||||
@Column
|
||||
declare pendingTranscode: number
|
||||
|
||||
@AllowNull(false)
|
||||
@Default(0)
|
||||
@IsInt
|
||||
@Column
|
||||
declare pendingTranscription: number
|
||||
|
||||
@ForeignKey(() => VideoModel)
|
||||
@Unique
|
||||
@Column
|
||||
declare videoId: number
|
||||
|
||||
@BelongsTo(() => VideoModel, {
|
||||
foreignKey: {
|
||||
allowNull: false
|
||||
},
|
||||
onDelete: 'cascade'
|
||||
})
|
||||
declare Video: Awaited<VideoModel>
|
||||
|
||||
static load (videoId: number, transaction?: Transaction) {
|
||||
const where = {
|
||||
videoId
|
||||
}
|
||||
|
||||
return VideoJobInfoModel.findOne({ where, transaction })
|
||||
}
|
||||
|
||||
static async increaseOrCreate (videoUUID: string, column: VideoJobInfoColumnType, amountArg = 1): Promise<number> {
|
||||
const options = { type: QueryTypes.SELECT as QueryTypes.SELECT, bind: { videoUUID } }
|
||||
const amount = forceNumber(amountArg)
|
||||
|
||||
const [ result ] = await VideoJobInfoModel.sequelize.query(
|
||||
`
|
||||
INSERT INTO "videoJobInfo" ("videoId", "${column}", "createdAt", "updatedAt")
|
||||
SELECT
|
||||
"video"."id" AS "videoId", ${amount}, NOW(), NOW()
|
||||
FROM
|
||||
"video"
|
||||
WHERE
|
||||
"video"."uuid" = $videoUUID
|
||||
ON CONFLICT ("videoId") DO UPDATE
|
||||
SET
|
||||
"${column}" = "videoJobInfo"."${column}" + ${amount},
|
||||
"updatedAt" = NOW()
|
||||
RETURNING
|
||||
"${column}"
|
||||
`,
|
||||
options
|
||||
)
|
||||
|
||||
return result[column]
|
||||
}
|
||||
|
||||
static async decrease (videoUUID: string, column: VideoJobInfoColumnType): Promise<number> {
|
||||
const options = { type: QueryTypes.SELECT as QueryTypes.SELECT, bind: { videoUUID } }
|
||||
|
||||
const result = await VideoJobInfoModel.sequelize.query(
|
||||
`
|
||||
UPDATE
|
||||
"videoJobInfo"
|
||||
SET
|
||||
"${column}" = GREATEST("videoJobInfo"."${column}" - 1, 0),
|
||||
"updatedAt" = NOW()
|
||||
FROM "video"
|
||||
WHERE
|
||||
"video"."id" = "videoJobInfo"."videoId" AND "video"."uuid" = $videoUUID
|
||||
RETURNING
|
||||
"${column}";
|
||||
`,
|
||||
options
|
||||
)
|
||||
|
||||
if (result.length === 0) return undefined
|
||||
|
||||
return result[0][column]
|
||||
}
|
||||
|
||||
static async abortAllTasks (videoUUID: string, column: VideoJobInfoColumnType): Promise<void> {
|
||||
const options = { type: QueryTypes.UPDATE as QueryTypes.UPDATE, bind: { videoUUID } }
|
||||
|
||||
await VideoJobInfoModel.sequelize.query(
|
||||
`
|
||||
UPDATE
|
||||
"videoJobInfo"
|
||||
SET
|
||||
"${column}" = 0,
|
||||
"updatedAt" = NOW()
|
||||
FROM "video"
|
||||
WHERE
|
||||
"video"."id" = "videoJobInfo"."videoId" AND "video"."uuid" = $videoUUID
|
||||
`,
|
||||
options
|
||||
)
|
||||
}
|
||||
}
|
||||
43
server/core/models/video/video-live-replay-setting.ts
Normal file
43
server/core/models/video/video-live-replay-setting.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import { type VideoPrivacyType } from '@peertube/peertube-models'
|
||||
import { isVideoPrivacyValid } from '@server/helpers/custom-validators/videos.js'
|
||||
import { MLiveReplaySetting } from '@server/types/models/video/video-live-replay-setting.js'
|
||||
import { Transaction } from 'sequelize'
|
||||
import { AllowNull, Column, CreatedAt, Is, Table, UpdatedAt } from 'sequelize-typescript'
|
||||
import { throwIfNotValid } from '../shared/sequelize-helpers.js'
|
||||
import { SequelizeModel } from '../shared/index.js'
|
||||
|
||||
@Table({
|
||||
tableName: 'videoLiveReplaySetting'
|
||||
})
|
||||
export class VideoLiveReplaySettingModel extends SequelizeModel<VideoLiveReplaySettingModel> {
|
||||
@CreatedAt
|
||||
declare createdAt: Date
|
||||
|
||||
@UpdatedAt
|
||||
declare updatedAt: Date
|
||||
|
||||
@AllowNull(false)
|
||||
@Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
|
||||
@Column
|
||||
declare privacy: VideoPrivacyType
|
||||
|
||||
static load (id: number, transaction?: Transaction): Promise<MLiveReplaySetting> {
|
||||
return VideoLiveReplaySettingModel.findOne({
|
||||
where: { id },
|
||||
transaction
|
||||
})
|
||||
}
|
||||
|
||||
static removeSettings (id: number, transaction?: Transaction) {
|
||||
return VideoLiveReplaySettingModel.destroy({
|
||||
where: { id },
|
||||
transaction
|
||||
})
|
||||
}
|
||||
|
||||
toFormattedJSON () {
|
||||
return {
|
||||
privacy: this.privacy
|
||||
}
|
||||
}
|
||||
}
|
||||
66
server/core/models/video/video-live-schedule.ts
Normal file
66
server/core/models/video/video-live-schedule.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import { LiveVideoSchedule } from '@peertube/peertube-models'
|
||||
import { Transaction } from 'sequelize'
|
||||
import { AllowNull, BelongsTo, Column, CreatedAt, ForeignKey, Table, UpdatedAt } from 'sequelize-typescript'
|
||||
import { SequelizeModel } from '../shared/index.js'
|
||||
import { VideoLiveModel } from './video-live.js'
|
||||
|
||||
@Table({
|
||||
tableName: 'videoLiveSchedule',
|
||||
indexes: [
|
||||
{
|
||||
fields: [ 'liveVideoId' ]
|
||||
},
|
||||
{
|
||||
fields: [ 'startAt' ]
|
||||
}
|
||||
]
|
||||
})
|
||||
export class VideoLiveScheduleModel extends SequelizeModel<VideoLiveScheduleModel> {
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare startAt: Date
|
||||
|
||||
@CreatedAt
|
||||
declare createdAt: Date
|
||||
|
||||
@UpdatedAt
|
||||
declare updatedAt: Date
|
||||
|
||||
@ForeignKey(() => VideoLiveModel)
|
||||
@Column
|
||||
declare liveVideoId: number
|
||||
|
||||
@BelongsTo(() => VideoLiveModel, {
|
||||
foreignKey: {
|
||||
allowNull: true,
|
||||
name: 'liveVideoId'
|
||||
},
|
||||
as: 'LiveVideo',
|
||||
onDelete: 'cascade'
|
||||
})
|
||||
declare LiveVideo: Awaited<VideoLiveModel>
|
||||
|
||||
static deleteAllOfLiveId (id: number, t?: Transaction) {
|
||||
return VideoLiveScheduleModel.destroy({
|
||||
where: {
|
||||
liveVideoId: id
|
||||
},
|
||||
transaction: t
|
||||
})
|
||||
}
|
||||
|
||||
static addToLiveId (id: number, schedules: (Date | string)[], t?: Transaction): Promise<VideoLiveScheduleModel[]> {
|
||||
return Promise.all(schedules.map(startAt => {
|
||||
return VideoLiveScheduleModel.create({
|
||||
liveVideoId: id,
|
||||
startAt: new Date(startAt)
|
||||
}, { transaction: t })
|
||||
}))
|
||||
}
|
||||
|
||||
toFormattedJSON (): LiveVideoSchedule {
|
||||
return {
|
||||
startAt: this.startAt
|
||||
}
|
||||
}
|
||||
}
|
||||
221
server/core/models/video/video-live-session.ts
Normal file
221
server/core/models/video/video-live-session.ts
Normal file
@@ -0,0 +1,221 @@
|
||||
import { LiveVideoSession, type LiveVideoErrorType } from '@peertube/peertube-models'
|
||||
import { uuidToShort } from '@peertube/peertube-node-utils'
|
||||
import { AttributesOnly } from '@peertube/peertube-typescript-utils'
|
||||
import { MVideoLiveSession, MVideoLiveSessionReplay } from '@server/types/models/index.js'
|
||||
import { FindOptions } from 'sequelize'
|
||||
import {
|
||||
AllowNull,
|
||||
BeforeDestroy,
|
||||
BelongsTo,
|
||||
Column,
|
||||
CreatedAt,
|
||||
DataType,
|
||||
ForeignKey,
|
||||
Scopes,
|
||||
Table,
|
||||
UpdatedAt
|
||||
} from 'sequelize-typescript'
|
||||
import { getSort, SequelizeModel } from '../shared/index.js'
|
||||
import { VideoLiveReplaySettingModel } from './video-live-replay-setting.js'
|
||||
import { VideoModel } from './video.js'
|
||||
|
||||
export enum ScopeNames {
|
||||
WITH_REPLAY = 'WITH_REPLAY'
|
||||
}
|
||||
|
||||
@Scopes(() => ({
|
||||
[ScopeNames.WITH_REPLAY]: {
|
||||
include: [
|
||||
{
|
||||
model: VideoModel.unscoped(),
|
||||
as: 'ReplayVideo',
|
||||
required: false
|
||||
},
|
||||
{
|
||||
model: VideoLiveReplaySettingModel,
|
||||
required: false
|
||||
}
|
||||
]
|
||||
}
|
||||
}))
|
||||
@Table({
|
||||
tableName: 'videoLiveSession',
|
||||
indexes: [
|
||||
{
|
||||
fields: [ 'replayVideoId' ],
|
||||
unique: true
|
||||
},
|
||||
{
|
||||
fields: [ 'liveVideoId' ]
|
||||
},
|
||||
{
|
||||
fields: [ 'replaySettingId' ],
|
||||
unique: true
|
||||
}
|
||||
]
|
||||
})
|
||||
export class VideoLiveSessionModel extends SequelizeModel<VideoLiveSessionModel> {
|
||||
@CreatedAt
|
||||
declare createdAt: Date
|
||||
|
||||
@UpdatedAt
|
||||
declare updatedAt: Date
|
||||
|
||||
@AllowNull(false)
|
||||
@Column(DataType.DATE)
|
||||
declare startDate: Date
|
||||
|
||||
@AllowNull(true)
|
||||
@Column(DataType.DATE)
|
||||
declare endDate: Date
|
||||
|
||||
@AllowNull(true)
|
||||
@Column
|
||||
declare error: LiveVideoErrorType
|
||||
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare saveReplay: boolean
|
||||
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare endingProcessed: boolean
|
||||
|
||||
@ForeignKey(() => VideoModel)
|
||||
@Column
|
||||
declare replayVideoId: number
|
||||
|
||||
@BelongsTo(() => VideoModel, {
|
||||
foreignKey: {
|
||||
allowNull: true,
|
||||
name: 'replayVideoId'
|
||||
},
|
||||
as: 'ReplayVideo',
|
||||
onDelete: 'set null'
|
||||
})
|
||||
declare ReplayVideo: Awaited<VideoModel>
|
||||
|
||||
@ForeignKey(() => VideoModel)
|
||||
@Column
|
||||
declare liveVideoId: number
|
||||
|
||||
@BelongsTo(() => VideoModel, {
|
||||
foreignKey: {
|
||||
allowNull: true,
|
||||
name: 'liveVideoId'
|
||||
},
|
||||
as: 'LiveVideo',
|
||||
onDelete: 'set null'
|
||||
})
|
||||
declare LiveVideo: Awaited<VideoModel>
|
||||
|
||||
@ForeignKey(() => VideoLiveReplaySettingModel)
|
||||
@Column
|
||||
declare replaySettingId: number
|
||||
|
||||
@BelongsTo(() => VideoLiveReplaySettingModel, {
|
||||
foreignKey: {
|
||||
allowNull: true
|
||||
},
|
||||
onDelete: 'set null'
|
||||
})
|
||||
declare ReplaySetting: Awaited<VideoLiveReplaySettingModel>
|
||||
|
||||
@BeforeDestroy
|
||||
static deleteReplaySetting (instance: VideoLiveSessionModel) {
|
||||
return VideoLiveReplaySettingModel.destroy({
|
||||
where: {
|
||||
id: instance.replaySettingId
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
static load (id: number): Promise<MVideoLiveSession> {
|
||||
return VideoLiveSessionModel.findOne({
|
||||
where: { id }
|
||||
})
|
||||
}
|
||||
|
||||
static findSessionOfReplay (replayVideoId: number) {
|
||||
const query = {
|
||||
where: {
|
||||
replayVideoId
|
||||
}
|
||||
}
|
||||
|
||||
return VideoLiveSessionModel.scope(ScopeNames.WITH_REPLAY).findOne(query)
|
||||
}
|
||||
|
||||
static findCurrentSessionOf (videoUUID: string) {
|
||||
return VideoLiveSessionModel.findOne({
|
||||
where: {
|
||||
endDate: null
|
||||
},
|
||||
include: [
|
||||
{
|
||||
model: VideoModel.unscoped(),
|
||||
as: 'LiveVideo',
|
||||
required: true,
|
||||
where: {
|
||||
uuid: videoUUID
|
||||
}
|
||||
}
|
||||
],
|
||||
order: [ [ 'startDate', 'DESC' ] ]
|
||||
})
|
||||
}
|
||||
|
||||
static findLatestSessionOf (videoId: number) {
|
||||
return VideoLiveSessionModel.findOne({
|
||||
where: {
|
||||
liveVideoId: videoId
|
||||
},
|
||||
order: [ [ 'startDate', 'DESC' ] ]
|
||||
})
|
||||
}
|
||||
|
||||
static listSessionsOfLiveForAPI (options: {
|
||||
videoId: number
|
||||
count: number
|
||||
sort: string
|
||||
}) {
|
||||
const { videoId, count, sort } = options
|
||||
|
||||
const query: FindOptions<AttributesOnly<VideoLiveSessionModel>> = {
|
||||
where: {
|
||||
liveVideoId: videoId
|
||||
},
|
||||
limit: count,
|
||||
order: getSort(sort)
|
||||
}
|
||||
|
||||
return VideoLiveSessionModel.scope(ScopeNames.WITH_REPLAY).findAll(query)
|
||||
}
|
||||
|
||||
toFormattedJSON (this: MVideoLiveSessionReplay): LiveVideoSession {
|
||||
const replayVideo = this.ReplayVideo
|
||||
? {
|
||||
id: this.ReplayVideo.id,
|
||||
uuid: this.ReplayVideo.uuid,
|
||||
shortUUID: uuidToShort(this.ReplayVideo.uuid)
|
||||
}
|
||||
: undefined
|
||||
|
||||
const replaySettings = this.replaySettingId
|
||||
? this.ReplaySetting.toFormattedJSON()
|
||||
: undefined
|
||||
|
||||
return {
|
||||
id: this.id,
|
||||
startDate: this.startDate.toISOString(),
|
||||
endDate: this.endDate
|
||||
? this.endDate.toISOString()
|
||||
: null,
|
||||
endingProcessed: this.endingProcessed,
|
||||
saveReplay: this.saveReplay,
|
||||
replaySettings,
|
||||
replayVideo,
|
||||
error: this.error
|
||||
}
|
||||
}
|
||||
}
|
||||
199
server/core/models/video/video-live.ts
Normal file
199
server/core/models/video/video-live.ts
Normal file
@@ -0,0 +1,199 @@
|
||||
import { LiveVideo, VideoState, type LiveVideoLatencyModeType } from '@peertube/peertube-models'
|
||||
import { CONFIG } from '@server/initializers/config.js'
|
||||
import { WEBSERVER } from '@server/initializers/constants.js'
|
||||
import {
|
||||
MVideoLiveVideoWithSetting,
|
||||
MVideoLiveVideoWithSettingSchedules,
|
||||
MVideoLiveWithSettingSchedules
|
||||
} from '@server/types/models/index.js'
|
||||
import { Transaction } from 'sequelize'
|
||||
import {
|
||||
AllowNull,
|
||||
BeforeDestroy,
|
||||
BelongsTo,
|
||||
Column,
|
||||
CreatedAt,
|
||||
DataType,
|
||||
ForeignKey,
|
||||
HasMany,
|
||||
Table,
|
||||
UpdatedAt
|
||||
} from 'sequelize-typescript'
|
||||
import { SequelizeModel } from '../shared/index.js'
|
||||
import { VideoBlacklistModel } from './video-blacklist.js'
|
||||
import { VideoLiveReplaySettingModel } from './video-live-replay-setting.js'
|
||||
import { VideoLiveScheduleModel } from './video-live-schedule.js'
|
||||
import { VideoModel } from './video.js'
|
||||
|
||||
@Table({
|
||||
tableName: 'videoLive',
|
||||
indexes: [
|
||||
{
|
||||
fields: [ 'videoId' ],
|
||||
unique: true
|
||||
},
|
||||
{
|
||||
fields: [ 'replaySettingId' ],
|
||||
unique: true
|
||||
}
|
||||
]
|
||||
})
|
||||
export class VideoLiveModel extends SequelizeModel<VideoLiveModel> {
|
||||
@AllowNull(true)
|
||||
@Column(DataType.STRING)
|
||||
declare streamKey: string
|
||||
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare saveReplay: boolean
|
||||
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare permanentLive: boolean
|
||||
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare latencyMode: LiveVideoLatencyModeType
|
||||
|
||||
@CreatedAt
|
||||
declare createdAt: Date
|
||||
|
||||
@UpdatedAt
|
||||
declare updatedAt: Date
|
||||
|
||||
@ForeignKey(() => VideoModel)
|
||||
@Column
|
||||
declare videoId: number
|
||||
|
||||
@BelongsTo(() => VideoModel, {
|
||||
foreignKey: {
|
||||
allowNull: false
|
||||
},
|
||||
onDelete: 'cascade'
|
||||
})
|
||||
declare Video: Awaited<VideoModel>
|
||||
|
||||
@ForeignKey(() => VideoLiveReplaySettingModel)
|
||||
@Column
|
||||
declare replaySettingId: number
|
||||
|
||||
@BelongsTo(() => VideoLiveReplaySettingModel, {
|
||||
foreignKey: {
|
||||
allowNull: true
|
||||
},
|
||||
onDelete: 'set null'
|
||||
})
|
||||
declare ReplaySetting: Awaited<VideoLiveReplaySettingModel>
|
||||
|
||||
@HasMany(() => VideoLiveScheduleModel, {
|
||||
foreignKey: {
|
||||
allowNull: true
|
||||
},
|
||||
onDelete: 'cascade',
|
||||
hooks: true
|
||||
})
|
||||
declare LiveSchedules: Awaited<VideoLiveScheduleModel>[]
|
||||
|
||||
@BeforeDestroy
|
||||
static deleteReplaySetting (instance: VideoLiveModel, options: { transaction: Transaction }) {
|
||||
return VideoLiveReplaySettingModel.destroy({
|
||||
where: {
|
||||
id: instance.replaySettingId
|
||||
},
|
||||
transaction: options.transaction
|
||||
})
|
||||
}
|
||||
|
||||
static loadByStreamKey (streamKey: string) {
|
||||
const query = {
|
||||
where: {
|
||||
streamKey
|
||||
},
|
||||
include: [
|
||||
{
|
||||
model: VideoModel.unscoped(),
|
||||
required: true,
|
||||
where: {
|
||||
state: VideoState.WAITING_FOR_LIVE
|
||||
},
|
||||
include: [
|
||||
{
|
||||
model: VideoBlacklistModel.unscoped(),
|
||||
required: false
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
model: VideoLiveReplaySettingModel.unscoped(),
|
||||
required: false
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
return VideoLiveModel.findOne<MVideoLiveVideoWithSetting>(query)
|
||||
}
|
||||
|
||||
static loadByVideoId (videoId: number) {
|
||||
const query = {
|
||||
where: {
|
||||
videoId
|
||||
}
|
||||
}
|
||||
|
||||
return VideoLiveModel.findOne<MVideoLiveWithSettingSchedules>(query)
|
||||
}
|
||||
|
||||
static loadByVideoIdFull (videoId: number) {
|
||||
const query = {
|
||||
where: {
|
||||
videoId
|
||||
},
|
||||
include: [
|
||||
{
|
||||
model: VideoLiveReplaySettingModel.unscoped(),
|
||||
required: false
|
||||
},
|
||||
{
|
||||
model: VideoLiveScheduleModel.unscoped(),
|
||||
required: false
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
return VideoLiveModel.findOne<MVideoLiveVideoWithSettingSchedules>(query)
|
||||
}
|
||||
|
||||
toFormattedJSON (this: MVideoLiveWithSettingSchedules, canSeePrivateInformation: boolean): LiveVideo {
|
||||
let privateInformation: Pick<LiveVideo, 'rtmpUrl' | 'rtmpsUrl' | 'streamKey'> | {} = {}
|
||||
|
||||
// If we don't have a stream key, it means this is a remote live so we don't specify the rtmp URL
|
||||
// We also display these private information only to the live owne/moderators
|
||||
if (this.streamKey && canSeePrivateInformation === true) {
|
||||
privateInformation = {
|
||||
streamKey: this.streamKey,
|
||||
|
||||
rtmpUrl: CONFIG.LIVE.RTMP.ENABLED
|
||||
? WEBSERVER.RTMP_BASE_LIVE_URL
|
||||
: null,
|
||||
|
||||
rtmpsUrl: CONFIG.LIVE.RTMPS.ENABLED
|
||||
? WEBSERVER.RTMPS_BASE_LIVE_URL
|
||||
: null
|
||||
}
|
||||
}
|
||||
|
||||
const replaySettings = this.replaySettingId
|
||||
? this.ReplaySetting.toFormattedJSON()
|
||||
: undefined
|
||||
|
||||
return {
|
||||
...privateInformation,
|
||||
|
||||
permanentLive: this.permanentLive,
|
||||
saveReplay: this.saveReplay,
|
||||
replaySettings,
|
||||
latencyMode: this.latencyMode,
|
||||
schedules: (this.LiveSchedules || []).map(schedule => schedule.toFormattedJSON())
|
||||
}
|
||||
}
|
||||
}
|
||||
139
server/core/models/video/video-password.ts
Normal file
139
server/core/models/video/video-password.ts
Normal file
@@ -0,0 +1,139 @@
|
||||
import { AllowNull, BelongsTo, Column, CreatedAt, DefaultScope, ForeignKey, Is, Table, UpdatedAt } from 'sequelize-typescript'
|
||||
import { VideoModel } from './video.js'
|
||||
import { ResultList, VideoPassword } from '@peertube/peertube-models'
|
||||
import { SequelizeModel, getSort, throwIfNotValid } from '../shared/index.js'
|
||||
import { Transaction } from 'sequelize'
|
||||
import { MVideoPassword } from '@server/types/models/index.js'
|
||||
import { isPasswordValid } from '@server/helpers/custom-validators/videos.js'
|
||||
import { pick } from '@peertube/peertube-core-utils'
|
||||
|
||||
@DefaultScope(() => ({
|
||||
include: [
|
||||
{
|
||||
model: VideoModel.unscoped(),
|
||||
required: true
|
||||
}
|
||||
]
|
||||
}))
|
||||
@Table({
|
||||
tableName: 'videoPassword',
|
||||
indexes: [
|
||||
{
|
||||
fields: [ 'videoId', 'password' ],
|
||||
unique: true
|
||||
}
|
||||
]
|
||||
})
|
||||
export class VideoPasswordModel extends SequelizeModel<VideoPasswordModel> {
|
||||
@AllowNull(false)
|
||||
@Is('VideoPassword', value => throwIfNotValid(value, isPasswordValid, 'videoPassword'))
|
||||
@Column
|
||||
declare password: string
|
||||
|
||||
@CreatedAt
|
||||
declare createdAt: Date
|
||||
|
||||
@UpdatedAt
|
||||
declare updatedAt: Date
|
||||
|
||||
@ForeignKey(() => VideoModel)
|
||||
@Column
|
||||
declare videoId: number
|
||||
|
||||
@BelongsTo(() => VideoModel, {
|
||||
foreignKey: {
|
||||
allowNull: false
|
||||
},
|
||||
onDelete: 'cascade'
|
||||
})
|
||||
declare Video: Awaited<VideoModel>
|
||||
|
||||
static async countByVideoId (videoId: number, t?: Transaction) {
|
||||
const query = {
|
||||
where: {
|
||||
videoId
|
||||
},
|
||||
transaction: t
|
||||
}
|
||||
|
||||
return VideoPasswordModel.count(query)
|
||||
}
|
||||
|
||||
static async loadByIdAndVideo (options: { id: number, videoId: number, t?: Transaction }): Promise<MVideoPassword> {
|
||||
const { id, videoId, t } = options
|
||||
const query = {
|
||||
where: {
|
||||
id,
|
||||
videoId
|
||||
},
|
||||
transaction: t
|
||||
}
|
||||
|
||||
return VideoPasswordModel.findOne(query)
|
||||
}
|
||||
|
||||
static async listPasswords (options: {
|
||||
start: number
|
||||
count: number
|
||||
sort: string
|
||||
videoId: number
|
||||
}): Promise<ResultList<MVideoPassword>> {
|
||||
const { start, count, sort, videoId } = options
|
||||
|
||||
const { count: total, rows: data } = await VideoPasswordModel.findAndCountAll({
|
||||
where: { videoId },
|
||||
order: getSort(sort),
|
||||
offset: start,
|
||||
limit: count
|
||||
})
|
||||
|
||||
return { total, data }
|
||||
}
|
||||
|
||||
static async addPasswords (passwords: string[], videoId: number, transaction?: Transaction): Promise<void> {
|
||||
for (const password of passwords) {
|
||||
await VideoPasswordModel.addPassword(password, videoId, transaction)
|
||||
}
|
||||
}
|
||||
|
||||
static async addPassword (password: string, videoId: number, transaction?: Transaction): Promise<VideoPasswordModel> {
|
||||
return await VideoPasswordModel.create({
|
||||
password,
|
||||
videoId
|
||||
}, { transaction })
|
||||
}
|
||||
|
||||
static async deleteAllPasswords (videoId: number, transaction?: Transaction) {
|
||||
await VideoPasswordModel.destroy({
|
||||
where: { videoId },
|
||||
transaction
|
||||
})
|
||||
}
|
||||
|
||||
static async deletePassword (passwordId: number, transaction?: Transaction) {
|
||||
await VideoPasswordModel.destroy({
|
||||
where: { id: passwordId },
|
||||
transaction
|
||||
})
|
||||
}
|
||||
|
||||
static async isACorrectPassword (options: {
|
||||
videoId: number
|
||||
password: string
|
||||
}) {
|
||||
const query = {
|
||||
where: pick(options, [ 'videoId', 'password' ])
|
||||
}
|
||||
return VideoPasswordModel.findOne(query)
|
||||
}
|
||||
|
||||
toFormattedJSON (): VideoPassword {
|
||||
return {
|
||||
id: this.id,
|
||||
password: this.password,
|
||||
videoId: this.videoId,
|
||||
createdAt: this.createdAt,
|
||||
updatedAt: this.updatedAt
|
||||
}
|
||||
}
|
||||
}
|
||||
391
server/core/models/video/video-playlist-element.ts
Normal file
391
server/core/models/video/video-playlist-element.ts
Normal file
@@ -0,0 +1,391 @@
|
||||
import {
|
||||
PlaylistElementObject,
|
||||
VideoPlaylistElement,
|
||||
VideoPlaylistElementType,
|
||||
VideoPrivacy,
|
||||
VideoPrivacyType
|
||||
} from '@peertube/peertube-models'
|
||||
import { MUserAccountId } from '@server/types/models/index.js'
|
||||
import {
|
||||
MVideoPlaylistElement,
|
||||
MVideoPlaylistElementAP,
|
||||
MVideoPlaylistElementFormattable,
|
||||
MVideoPlaylistElementVideoThumbnail,
|
||||
MVideoPlaylistElementVideoUrl,
|
||||
MVideoPlaylistElementVideoUrlPlaylistPrivacy
|
||||
} from '@server/types/models/video/video-playlist-element.js'
|
||||
import { ScopeOptions, Transaction } from 'sequelize'
|
||||
import {
|
||||
AllowNull,
|
||||
BelongsTo,
|
||||
Column,
|
||||
CreatedAt,
|
||||
DataType,
|
||||
Default,
|
||||
ForeignKey,
|
||||
Is,
|
||||
IsInt,
|
||||
Min,
|
||||
Table,
|
||||
UpdatedAt
|
||||
} from 'sequelize-typescript'
|
||||
import validator from 'validator'
|
||||
import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc.js'
|
||||
import { CONSTRAINTS_FIELDS, USER_EXPORT_MAX_ITEMS } from '../../initializers/constants.js'
|
||||
import { AccountModel } from '../account/account.js'
|
||||
import { SequelizeModel, getSort, throwIfNotValid } from '../shared/index.js'
|
||||
import { getNextPositionOf, increasePositionOf, reassignPositionOf } from '../shared/position.js'
|
||||
import { VideoPlaylistModel } from './video-playlist.js'
|
||||
import { ForAPIOptions, VideoModel, ScopeNames as VideoScopeNames } from './video.js'
|
||||
|
||||
@Table({
|
||||
tableName: 'videoPlaylistElement',
|
||||
indexes: [
|
||||
{
|
||||
fields: [ 'videoPlaylistId' ]
|
||||
},
|
||||
{
|
||||
fields: [ 'videoId' ]
|
||||
},
|
||||
{
|
||||
fields: [ 'url' ],
|
||||
unique: true
|
||||
}
|
||||
]
|
||||
})
|
||||
export class VideoPlaylistElementModel extends SequelizeModel<VideoPlaylistElementModel> {
|
||||
@CreatedAt
|
||||
declare createdAt: Date
|
||||
|
||||
@UpdatedAt
|
||||
declare updatedAt: Date
|
||||
|
||||
@AllowNull(true)
|
||||
@Is('VideoPlaylistUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url', true))
|
||||
@Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.URL.max))
|
||||
declare url: string
|
||||
|
||||
@AllowNull(false)
|
||||
@Default(1)
|
||||
@IsInt
|
||||
@Min(1)
|
||||
@Column
|
||||
declare position: number
|
||||
|
||||
@AllowNull(true)
|
||||
@IsInt
|
||||
@Min(0)
|
||||
@Column
|
||||
declare startTimestamp: number
|
||||
|
||||
@AllowNull(true)
|
||||
@IsInt
|
||||
@Min(0)
|
||||
@Column
|
||||
declare stopTimestamp: number
|
||||
|
||||
@ForeignKey(() => VideoPlaylistModel)
|
||||
@Column
|
||||
declare videoPlaylistId: number
|
||||
|
||||
@BelongsTo(() => VideoPlaylistModel, {
|
||||
foreignKey: {
|
||||
allowNull: false
|
||||
},
|
||||
onDelete: 'CASCADE'
|
||||
})
|
||||
declare VideoPlaylist: Awaited<VideoPlaylistModel>
|
||||
|
||||
@ForeignKey(() => VideoModel)
|
||||
@Column
|
||||
declare videoId: number
|
||||
|
||||
@BelongsTo(() => VideoModel, {
|
||||
foreignKey: {
|
||||
allowNull: true
|
||||
},
|
||||
onDelete: 'set null'
|
||||
})
|
||||
declare Video: Awaited<VideoModel>
|
||||
|
||||
static deleteAllOf (videoPlaylistId: number, transaction?: Transaction) {
|
||||
const query = {
|
||||
where: {
|
||||
videoPlaylistId
|
||||
},
|
||||
transaction
|
||||
}
|
||||
|
||||
return VideoPlaylistElementModel.destroy(query)
|
||||
}
|
||||
|
||||
static listForApi (options: {
|
||||
start: number
|
||||
count: number
|
||||
videoPlaylistId: number
|
||||
serverAccount: AccountModel
|
||||
user?: MUserAccountId
|
||||
}) {
|
||||
const accountIds = [ options.serverAccount.id ]
|
||||
const videoScope: (ScopeOptions | string)[] = [
|
||||
VideoScopeNames.WITH_BLACKLISTED
|
||||
]
|
||||
|
||||
if (options.user) {
|
||||
accountIds.push(options.user.Account.id)
|
||||
videoScope.push({ method: [ VideoScopeNames.WITH_USER_HISTORY, options.user.id ] })
|
||||
}
|
||||
|
||||
const forApiOptions: ForAPIOptions = { withAccountBlockerIds: accountIds }
|
||||
videoScope.push({
|
||||
method: [
|
||||
VideoScopeNames.FOR_API,
|
||||
forApiOptions
|
||||
]
|
||||
})
|
||||
|
||||
const findQuery = {
|
||||
offset: options.start,
|
||||
limit: options.count,
|
||||
order: getSort('position'),
|
||||
where: {
|
||||
videoPlaylistId: options.videoPlaylistId
|
||||
},
|
||||
include: [
|
||||
{
|
||||
model: VideoModel.scope(videoScope),
|
||||
required: false
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
const countQuery = {
|
||||
where: {
|
||||
videoPlaylistId: options.videoPlaylistId
|
||||
}
|
||||
}
|
||||
|
||||
return Promise.all([
|
||||
VideoPlaylistElementModel.count(countQuery),
|
||||
VideoPlaylistElementModel.findAll(findQuery)
|
||||
]).then(([ total, data ]) => ({ total, data }))
|
||||
}
|
||||
|
||||
static loadByPlaylistAndVideo (videoPlaylistId: number, videoId: number): Promise<MVideoPlaylistElement> {
|
||||
const query = {
|
||||
where: {
|
||||
videoPlaylistId,
|
||||
videoId
|
||||
}
|
||||
}
|
||||
|
||||
return VideoPlaylistElementModel.findOne(query)
|
||||
}
|
||||
|
||||
static loadById (playlistElementId: number | string): Promise<MVideoPlaylistElement> {
|
||||
return VideoPlaylistElementModel.findByPk(playlistElementId)
|
||||
}
|
||||
|
||||
static loadByPlaylistAndElementIdForAP (
|
||||
playlistId: number | string,
|
||||
playlistElementId: number
|
||||
): Promise<MVideoPlaylistElementVideoUrlPlaylistPrivacy> {
|
||||
const playlistWhere = validator.default.isUUID('' + playlistId)
|
||||
? { uuid: playlistId }
|
||||
: { id: playlistId }
|
||||
|
||||
const query = {
|
||||
include: [
|
||||
{
|
||||
attributes: [ 'privacy' ],
|
||||
model: VideoPlaylistModel.unscoped(),
|
||||
where: playlistWhere
|
||||
},
|
||||
{
|
||||
attributes: [ 'url' ],
|
||||
model: VideoModel.unscoped()
|
||||
}
|
||||
],
|
||||
where: {
|
||||
id: playlistElementId
|
||||
}
|
||||
}
|
||||
|
||||
return VideoPlaylistElementModel.findOne(query)
|
||||
}
|
||||
|
||||
static loadFirstElementWithVideoThumbnail (videoPlaylistId: number): Promise<MVideoPlaylistElementVideoThumbnail> {
|
||||
const query = {
|
||||
order: getSort('position'),
|
||||
where: {
|
||||
videoPlaylistId
|
||||
},
|
||||
include: [
|
||||
{
|
||||
model: VideoModel.scope(VideoScopeNames.WITH_THUMBNAILS),
|
||||
required: true
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
return VideoPlaylistElementModel
|
||||
.findOne(query)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static listUrlsOfForAP (videoPlaylistId: number, start: number, count: number, t?: Transaction) {
|
||||
const getQuery = (forCount: boolean) => {
|
||||
return {
|
||||
attributes: forCount
|
||||
? []
|
||||
: [ 'url' ],
|
||||
offset: start,
|
||||
limit: count,
|
||||
order: getSort('position'),
|
||||
where: {
|
||||
videoPlaylistId
|
||||
},
|
||||
transaction: t
|
||||
}
|
||||
}
|
||||
|
||||
return Promise.all([
|
||||
VideoPlaylistElementModel.count(getQuery(true)),
|
||||
VideoPlaylistElementModel.findAll(getQuery(false))
|
||||
]).then(([ total, rows ]) => ({
|
||||
total,
|
||||
data: rows.map(e => e.url)
|
||||
}))
|
||||
}
|
||||
|
||||
static listElementsForExport (videoPlaylistId: number): Promise<MVideoPlaylistElementVideoUrl[]> {
|
||||
return VideoPlaylistElementModel.findAll({
|
||||
where: {
|
||||
videoPlaylistId
|
||||
},
|
||||
include: [
|
||||
{
|
||||
attributes: [ 'url' ],
|
||||
model: VideoModel.unscoped(),
|
||||
required: true
|
||||
}
|
||||
],
|
||||
order: getSort('position'),
|
||||
limit: USER_EXPORT_MAX_ITEMS
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static getNextPositionOf (videoPlaylistId: number, transaction?: Transaction) {
|
||||
return getNextPositionOf({
|
||||
model: VideoPlaylistElementModel,
|
||||
columnName: 'position',
|
||||
where: { videoPlaylistId },
|
||||
transaction
|
||||
})
|
||||
}
|
||||
|
||||
static reassignPositionOf (options: {
|
||||
videoPlaylistId: number
|
||||
firstPosition: number
|
||||
endPosition: number
|
||||
newPosition: number
|
||||
transaction?: Transaction
|
||||
}) {
|
||||
const { videoPlaylistId, firstPosition, endPosition, newPosition, transaction } = options
|
||||
|
||||
return reassignPositionOf({
|
||||
model: VideoPlaylistElementModel,
|
||||
columnName: 'position',
|
||||
where: { videoPlaylistId },
|
||||
transaction,
|
||||
|
||||
firstPosition,
|
||||
endPosition,
|
||||
newPosition
|
||||
})
|
||||
}
|
||||
|
||||
static increasePositionOf (options: {
|
||||
videoPlaylistId: number
|
||||
fromPosition: number
|
||||
by: number
|
||||
transaction?: Transaction
|
||||
}) {
|
||||
const { videoPlaylistId, fromPosition, by, transaction } = options
|
||||
|
||||
return increasePositionOf({
|
||||
model: VideoPlaylistElementModel,
|
||||
columnName: 'position',
|
||||
where: { videoPlaylistId },
|
||||
transaction,
|
||||
|
||||
fromPosition,
|
||||
by
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
toFormattedJSON (
|
||||
this: MVideoPlaylistElementFormattable,
|
||||
options: { accountId?: number } = {}
|
||||
): VideoPlaylistElement {
|
||||
return {
|
||||
id: this.id,
|
||||
position: this.position,
|
||||
startTimestamp: this.startTimestamp,
|
||||
stopTimestamp: this.stopTimestamp,
|
||||
|
||||
type: this.getType(options.accountId),
|
||||
|
||||
video: this.getVideoElement(options.accountId)
|
||||
}
|
||||
}
|
||||
|
||||
getType (this: MVideoPlaylistElementFormattable, accountId?: number) {
|
||||
const video = this.Video
|
||||
|
||||
if (!video) return VideoPlaylistElementType.DELETED
|
||||
|
||||
// Owned video, don't filter it
|
||||
if (accountId && video.VideoChannel.Account.id === accountId) return VideoPlaylistElementType.REGULAR
|
||||
|
||||
// Internal video?
|
||||
if (video.privacy === VideoPrivacy.INTERNAL && accountId) return VideoPlaylistElementType.REGULAR
|
||||
|
||||
// Private, internal and password protected videos cannot be read without appropriate access (ownership, internal)
|
||||
const protectedPrivacy = new Set<VideoPrivacyType>([ VideoPrivacy.PRIVATE, VideoPrivacy.INTERNAL, VideoPrivacy.PASSWORD_PROTECTED ])
|
||||
if (protectedPrivacy.has(video.privacy)) {
|
||||
return VideoPlaylistElementType.PRIVATE
|
||||
}
|
||||
|
||||
if (video.isBlacklisted() || video.isBlocked()) return VideoPlaylistElementType.UNAVAILABLE
|
||||
|
||||
return VideoPlaylistElementType.REGULAR
|
||||
}
|
||||
|
||||
getVideoElement (this: MVideoPlaylistElementFormattable, accountId?: number) {
|
||||
if (!this.Video) return null
|
||||
if (this.getType(accountId) !== VideoPlaylistElementType.REGULAR) return null
|
||||
|
||||
return this.Video.toFormattedJSON()
|
||||
}
|
||||
|
||||
toActivityPubObject (this: MVideoPlaylistElementAP): PlaylistElementObject {
|
||||
const base: PlaylistElementObject = {
|
||||
id: this.url,
|
||||
type: 'PlaylistElement',
|
||||
|
||||
url: this.Video?.url || null,
|
||||
position: this.position
|
||||
}
|
||||
|
||||
if (this.startTimestamp) base.startTimestamp = this.startTimestamp
|
||||
if (this.stopTimestamp) base.stopTimestamp = this.stopTimestamp
|
||||
|
||||
return base
|
||||
}
|
||||
}
|
||||
695
server/core/models/video/video-playlist.ts
Normal file
695
server/core/models/video/video-playlist.ts
Normal file
@@ -0,0 +1,695 @@
|
||||
import { buildPlaylistEmbedPath, buildPlaylistWatchPath } from '@peertube/peertube-core-utils'
|
||||
import {
|
||||
ActivityIconObject,
|
||||
PlaylistObject,
|
||||
VideoPlaylist,
|
||||
VideoPlaylistPrivacy,
|
||||
VideoPlaylistType,
|
||||
type VideoPlaylistPrivacyType,
|
||||
type VideoPlaylistType_Type
|
||||
} from '@peertube/peertube-models'
|
||||
import { buildUUID, uuidToShort } from '@peertube/peertube-node-utils'
|
||||
import { activityPubCollectionPagination } from '@server/lib/activitypub/collection.js'
|
||||
import { MAccountId, MChannelId, MVideoPlaylistElement } from '@server/types/models/index.js'
|
||||
import { join } from 'path'
|
||||
import { FindOptions, Op, Transaction, literal } from 'sequelize'
|
||||
import {
|
||||
AllowNull,
|
||||
BelongsTo,
|
||||
Column,
|
||||
CreatedAt,
|
||||
DataType,
|
||||
Default,
|
||||
ForeignKey,
|
||||
HasMany,
|
||||
HasOne,
|
||||
Is,
|
||||
IsUUID,
|
||||
Scopes,
|
||||
Table,
|
||||
UpdatedAt
|
||||
} from 'sequelize-typescript'
|
||||
import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc.js'
|
||||
import {
|
||||
isVideoPlaylistDescriptionValid,
|
||||
isVideoPlaylistNameValid,
|
||||
isVideoPlaylistPrivacyValid
|
||||
} from '../../helpers/custom-validators/video-playlists.js'
|
||||
import {
|
||||
ACTIVITY_PUB,
|
||||
CONSTRAINTS_FIELDS,
|
||||
LAZY_STATIC_PATHS,
|
||||
THUMBNAILS_SIZE,
|
||||
USER_EXPORT_MAX_ITEMS,
|
||||
VIDEO_PLAYLIST_PRIVACIES,
|
||||
VIDEO_PLAYLIST_TYPES,
|
||||
WEBSERVER
|
||||
} from '../../initializers/constants.js'
|
||||
import { MThumbnail } from '../../types/models/video/thumbnail.js'
|
||||
import {
|
||||
MVideoPlaylist,
|
||||
MVideoPlaylistAP,
|
||||
MVideoPlaylistAccountThumbnail,
|
||||
MVideoPlaylistFormattable,
|
||||
MVideoPlaylistFull,
|
||||
MVideoPlaylistFullSummary,
|
||||
MVideoPlaylistSummaryWithElements
|
||||
} from '../../types/models/video/video-playlist.js'
|
||||
import { AccountModel, ScopeNames as AccountScopeNames } from '../account/account.js'
|
||||
import { ActorModel } from '../actor/actor.js'
|
||||
import {
|
||||
SequelizeModel,
|
||||
buildSQLAttributes,
|
||||
buildTrigramSearchIndex,
|
||||
buildWhereIdOrUUID,
|
||||
isOutdated,
|
||||
setAsUpdated,
|
||||
throwIfNotValid
|
||||
} from '../shared/index.js'
|
||||
import { getNextPositionOf, increasePositionOf, reassignPositionOf } from '../shared/position.js'
|
||||
import { ListVideoPlaylistsOptions, VideoPlaylistListQueryBuilder } from './sql/playlist/video-playlist-list-query-builder.js'
|
||||
import { ThumbnailModel } from './thumbnail.js'
|
||||
import { VideoChannelModel, ScopeNames as VideoChannelScopeNames } from './video-channel.js'
|
||||
import { VideoPlaylistElementModel } from './video-playlist-element.js'
|
||||
|
||||
enum ScopeNames {
|
||||
WITH_VIDEOS_LENGTH = 'WITH_VIDEOS_LENGTH',
|
||||
WITH_ACCOUNT_AND_CHANNEL_SUMMARY = 'WITH_ACCOUNT_AND_CHANNEL_SUMMARY',
|
||||
WITH_ACCOUNT = 'WITH_ACCOUNT',
|
||||
WITH_THUMBNAIL = 'WITH_THUMBNAIL',
|
||||
WITH_ACCOUNT_AND_CHANNEL = 'WITH_ACCOUNT_AND_CHANNEL'
|
||||
}
|
||||
|
||||
function getVideoLengthSelect () {
|
||||
return 'SELECT COUNT("id") FROM "videoPlaylistElement" WHERE "videoPlaylistId" = "VideoPlaylistModel"."id"'
|
||||
}
|
||||
|
||||
@Scopes(() => ({
|
||||
[ScopeNames.WITH_THUMBNAIL]: {
|
||||
include: [
|
||||
{
|
||||
model: ThumbnailModel,
|
||||
required: false
|
||||
}
|
||||
]
|
||||
},
|
||||
[ScopeNames.WITH_VIDEOS_LENGTH]: {
|
||||
attributes: {
|
||||
include: [
|
||||
[
|
||||
literal(`(${getVideoLengthSelect()})`),
|
||||
'videosLength'
|
||||
]
|
||||
]
|
||||
}
|
||||
} as FindOptions,
|
||||
[ScopeNames.WITH_ACCOUNT]: {
|
||||
include: [
|
||||
{
|
||||
model: AccountModel,
|
||||
required: true
|
||||
}
|
||||
]
|
||||
},
|
||||
[ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY]: {
|
||||
include: [
|
||||
{
|
||||
model: AccountModel.scope(AccountScopeNames.SUMMARY),
|
||||
required: true
|
||||
},
|
||||
{
|
||||
model: VideoChannelModel.scope(VideoChannelScopeNames.SUMMARY),
|
||||
required: false
|
||||
}
|
||||
]
|
||||
},
|
||||
[ScopeNames.WITH_ACCOUNT_AND_CHANNEL]: {
|
||||
include: [
|
||||
{
|
||||
model: AccountModel,
|
||||
required: true
|
||||
},
|
||||
{
|
||||
model: VideoChannelModel,
|
||||
required: false
|
||||
}
|
||||
]
|
||||
}
|
||||
}))
|
||||
@Table({
|
||||
tableName: 'videoPlaylist',
|
||||
indexes: [
|
||||
buildTrigramSearchIndex('video_playlist_name_trigram', 'name'),
|
||||
|
||||
{
|
||||
fields: [ 'ownerAccountId' ]
|
||||
},
|
||||
{
|
||||
fields: [ 'videoChannelId' ]
|
||||
},
|
||||
{
|
||||
fields: [ 'url' ],
|
||||
unique: true
|
||||
}
|
||||
]
|
||||
})
|
||||
export class VideoPlaylistModel extends SequelizeModel<VideoPlaylistModel> {
|
||||
@CreatedAt
|
||||
declare createdAt: Date
|
||||
|
||||
@UpdatedAt
|
||||
declare updatedAt: Date
|
||||
|
||||
@AllowNull(false)
|
||||
@Is('VideoPlaylistName', value => throwIfNotValid(value, isVideoPlaylistNameValid, 'name'))
|
||||
@Column
|
||||
declare name: string
|
||||
|
||||
@AllowNull(true)
|
||||
@Is('VideoPlaylistDescription', value => throwIfNotValid(value, isVideoPlaylistDescriptionValid, 'description', true))
|
||||
@Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.DESCRIPTION.max))
|
||||
declare description: string
|
||||
|
||||
@AllowNull(false)
|
||||
@Is('VideoPlaylistPrivacy', value => throwIfNotValid(value, isVideoPlaylistPrivacyValid, 'privacy'))
|
||||
@Column
|
||||
declare privacy: VideoPlaylistPrivacyType
|
||||
|
||||
@AllowNull(false)
|
||||
@Is('VideoPlaylistUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
|
||||
@Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.URL.max))
|
||||
declare url: string
|
||||
|
||||
@AllowNull(false)
|
||||
@Default(DataType.UUIDV4)
|
||||
@IsUUID(4)
|
||||
@Column(DataType.UUID)
|
||||
declare uuid: string
|
||||
|
||||
@AllowNull(false)
|
||||
@Default(VideoPlaylistType.REGULAR)
|
||||
@Column
|
||||
declare type: VideoPlaylistType_Type
|
||||
|
||||
@AllowNull(true)
|
||||
@Column
|
||||
declare videoChannelPosition: number
|
||||
|
||||
@ForeignKey(() => AccountModel)
|
||||
@Column
|
||||
declare ownerAccountId: number
|
||||
|
||||
@BelongsTo(() => AccountModel, {
|
||||
foreignKey: {
|
||||
allowNull: false
|
||||
},
|
||||
onDelete: 'CASCADE'
|
||||
})
|
||||
declare OwnerAccount: Awaited<AccountModel>
|
||||
|
||||
@ForeignKey(() => VideoChannelModel)
|
||||
@Column
|
||||
declare videoChannelId: number
|
||||
|
||||
@BelongsTo(() => VideoChannelModel, {
|
||||
foreignKey: {
|
||||
allowNull: true
|
||||
},
|
||||
onDelete: 'CASCADE'
|
||||
})
|
||||
declare VideoChannel: Awaited<VideoChannelModel>
|
||||
|
||||
@HasMany(() => VideoPlaylistElementModel, {
|
||||
foreignKey: {
|
||||
name: 'videoPlaylistId',
|
||||
allowNull: false
|
||||
},
|
||||
onDelete: 'CASCADE'
|
||||
})
|
||||
declare VideoPlaylistElements: Awaited<VideoPlaylistElementModel>[]
|
||||
|
||||
@HasOne(() => ThumbnailModel, {
|
||||
foreignKey: {
|
||||
name: 'videoPlaylistId',
|
||||
allowNull: true
|
||||
},
|
||||
onDelete: 'CASCADE',
|
||||
hooks: true
|
||||
})
|
||||
declare Thumbnail: Awaited<ThumbnailModel>
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static getSQLAttributes (tableName: string, aliasPrefix = '') {
|
||||
return buildSQLAttributes({
|
||||
model: this,
|
||||
tableName,
|
||||
aliasPrefix
|
||||
})
|
||||
}
|
||||
|
||||
static getSQLSummaryAttributes (tableName: string, aliasPrefix = '') {
|
||||
return buildSQLAttributes({
|
||||
model: this,
|
||||
tableName,
|
||||
aliasPrefix,
|
||||
includeAttributes: [ 'id', 'name', 'type' ]
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static listForApi (options: ListVideoPlaylistsOptions) {
|
||||
return Promise.all([
|
||||
new VideoPlaylistListQueryBuilder(VideoPlaylistModel.sequelize, options).list<MVideoPlaylistFormattable>(),
|
||||
new VideoPlaylistListQueryBuilder(VideoPlaylistModel.sequelize, options).count()
|
||||
]).then(([ rows, count ]) => {
|
||||
return { total: count, data: rows }
|
||||
})
|
||||
}
|
||||
|
||||
static searchForApi (
|
||||
options: Pick<ListVideoPlaylistsOptions, 'followerActorId' | 'search' | 'host' | 'uuids' | 'start' | 'count' | 'sort'>
|
||||
) {
|
||||
return VideoPlaylistModel.listForApi({
|
||||
...options,
|
||||
|
||||
type: VideoPlaylistType.REGULAR,
|
||||
listMyPlaylists: false,
|
||||
withVideos: true
|
||||
})
|
||||
}
|
||||
|
||||
static listPublicUrlsOfForAP (options: { account?: MAccountId, channel?: MChannelId }, start: number, count: number) {
|
||||
const where = {
|
||||
privacy: VideoPlaylistPrivacy.PUBLIC
|
||||
}
|
||||
|
||||
if (options.account) {
|
||||
Object.assign(where, { ownerAccountId: options.account.id })
|
||||
}
|
||||
|
||||
if (options.channel) {
|
||||
Object.assign(where, { videoChannelId: options.channel.id })
|
||||
}
|
||||
|
||||
const getQuery = (forCount: boolean) => {
|
||||
return {
|
||||
attributes: forCount === true
|
||||
? []
|
||||
: [ 'url' ],
|
||||
offset: start,
|
||||
limit: count,
|
||||
where
|
||||
}
|
||||
}
|
||||
|
||||
return Promise.all([
|
||||
VideoPlaylistModel.count(getQuery(true)),
|
||||
VideoPlaylistModel.findAll(getQuery(false))
|
||||
]).then(([ total, rows ]) => ({
|
||||
total,
|
||||
data: rows.map(p => p.url)
|
||||
}))
|
||||
}
|
||||
|
||||
static listPlaylistSummariesOf (accountId: number, videoIds: number[]): Promise<MVideoPlaylistSummaryWithElements[]> {
|
||||
const query = {
|
||||
attributes: [ 'id', 'name', 'uuid' ],
|
||||
where: {
|
||||
ownerAccountId: accountId
|
||||
},
|
||||
include: [
|
||||
{
|
||||
attributes: [ 'id', 'videoId', 'startTimestamp', 'stopTimestamp' ],
|
||||
model: VideoPlaylistElementModel.unscoped(),
|
||||
where: {
|
||||
videoId: {
|
||||
[Op.in]: videoIds
|
||||
}
|
||||
},
|
||||
required: true
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
return VideoPlaylistModel.findAll(query)
|
||||
}
|
||||
|
||||
static listPlaylistForExport (accountId: number): Promise<MVideoPlaylistFull[]> {
|
||||
return VideoPlaylistModel
|
||||
.scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
|
||||
.findAll({
|
||||
where: {
|
||||
ownerAccountId: accountId
|
||||
},
|
||||
limit: USER_EXPORT_MAX_ITEMS
|
||||
})
|
||||
}
|
||||
|
||||
static listPlaylistOfChannel (channelId: number, transaction: Transaction): Promise<MVideoPlaylistFull[]> {
|
||||
return VideoPlaylistModel
|
||||
.scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
|
||||
.findAll({
|
||||
where: {
|
||||
videoChannelId: channelId
|
||||
},
|
||||
limit: 150,
|
||||
transaction
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static doesPlaylistExist (url: string) {
|
||||
const query = {
|
||||
attributes: [ 'id' ],
|
||||
where: {
|
||||
url
|
||||
}
|
||||
}
|
||||
|
||||
return VideoPlaylistModel
|
||||
.findOne(query)
|
||||
.then(e => !!e)
|
||||
}
|
||||
|
||||
static loadWithAccountAndChannelSummary (id: number | string, transaction: Transaction): Promise<MVideoPlaylistFullSummary> {
|
||||
const where = buildWhereIdOrUUID(id)
|
||||
|
||||
const query = {
|
||||
where,
|
||||
transaction
|
||||
}
|
||||
|
||||
return VideoPlaylistModel
|
||||
.scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
|
||||
.findOne(query)
|
||||
}
|
||||
|
||||
static loadWithAccountAndChannel (id: number | string, transaction: Transaction): Promise<MVideoPlaylistFull> {
|
||||
const where = buildWhereIdOrUUID(id)
|
||||
|
||||
const query = {
|
||||
where,
|
||||
transaction
|
||||
}
|
||||
|
||||
return VideoPlaylistModel
|
||||
.scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
|
||||
.findOne(query)
|
||||
}
|
||||
|
||||
static loadByUrlAndPopulateAccount (url: string): Promise<MVideoPlaylistAccountThumbnail> {
|
||||
const query = {
|
||||
where: {
|
||||
url
|
||||
}
|
||||
}
|
||||
|
||||
return VideoPlaylistModel.scope([ ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_THUMBNAIL ]).findOne(query)
|
||||
}
|
||||
|
||||
static loadByUrlWithAccountAndChannelSummary (url: string): Promise<MVideoPlaylistFullSummary> {
|
||||
const query = {
|
||||
where: {
|
||||
url
|
||||
}
|
||||
}
|
||||
|
||||
return VideoPlaylistModel
|
||||
.scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
|
||||
.findOne(query)
|
||||
}
|
||||
|
||||
static loadWatchLaterOf (account: MAccountId): Promise<MVideoPlaylistFull> {
|
||||
const query = {
|
||||
where: {
|
||||
type: VideoPlaylistType.WATCH_LATER,
|
||||
ownerAccountId: account.id
|
||||
}
|
||||
}
|
||||
|
||||
return VideoPlaylistModel
|
||||
.scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
|
||||
.findOne(query)
|
||||
}
|
||||
|
||||
static loadRegularByAccountAndName (account: MAccountId, name: string): Promise<MVideoPlaylist> {
|
||||
const query = {
|
||||
where: {
|
||||
type: VideoPlaylistType.REGULAR,
|
||||
name,
|
||||
ownerAccountId: account.id
|
||||
}
|
||||
}
|
||||
|
||||
return VideoPlaylistModel
|
||||
.findOne(query)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static getNextPositionOf (options: {
|
||||
videoChannelId: number
|
||||
transaction?: Transaction
|
||||
}) {
|
||||
const { videoChannelId, transaction } = options
|
||||
|
||||
return getNextPositionOf({
|
||||
model: VideoPlaylistModel,
|
||||
columnName: 'videoChannelPosition',
|
||||
where: { videoChannelId },
|
||||
transaction
|
||||
})
|
||||
}
|
||||
|
||||
static reassignPositionOf (options: {
|
||||
videoChannelId: number
|
||||
firstPosition: number
|
||||
endPosition: number
|
||||
newPosition: number
|
||||
transaction?: Transaction
|
||||
}) {
|
||||
const { videoChannelId, firstPosition, endPosition, newPosition, transaction } = options
|
||||
|
||||
return reassignPositionOf({
|
||||
model: VideoPlaylistModel,
|
||||
columnName: 'videoChannelPosition',
|
||||
where: { videoChannelId },
|
||||
transaction,
|
||||
|
||||
firstPosition,
|
||||
endPosition,
|
||||
newPosition
|
||||
})
|
||||
}
|
||||
|
||||
static increasePositionOf (options: {
|
||||
videoChannelId: number
|
||||
fromPosition: number
|
||||
by: number
|
||||
transaction?: Transaction
|
||||
}) {
|
||||
const { videoChannelId, fromPosition, by, transaction } = options
|
||||
|
||||
return increasePositionOf({
|
||||
model: VideoPlaylistModel,
|
||||
columnName: 'videoChannelPosition',
|
||||
where: { videoChannelId },
|
||||
transaction,
|
||||
|
||||
fromPosition,
|
||||
by
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static getPrivacyLabel (privacy: VideoPlaylistPrivacyType) {
|
||||
return VIDEO_PLAYLIST_PRIVACIES[privacy] || 'Unknown'
|
||||
}
|
||||
|
||||
static getTypeLabel (type: VideoPlaylistType_Type) {
|
||||
return VIDEO_PLAYLIST_TYPES[type] || 'Unknown'
|
||||
}
|
||||
|
||||
static resetPlaylistsOfChannel (videoChannelId: number, transaction: Transaction) {
|
||||
const query = {
|
||||
where: {
|
||||
videoChannelId
|
||||
},
|
||||
transaction
|
||||
}
|
||||
|
||||
return VideoPlaylistModel.update({
|
||||
privacy: VideoPlaylistPrivacy.PRIVATE,
|
||||
videoChannelId: null,
|
||||
videoChannelPosition: null
|
||||
}, query)
|
||||
}
|
||||
|
||||
async setAndSaveThumbnail (thumbnail: MThumbnail, t: Transaction) {
|
||||
thumbnail.videoPlaylistId = this.id
|
||||
|
||||
this.Thumbnail = await thumbnail.save({ transaction: t })
|
||||
}
|
||||
|
||||
hasThumbnail () {
|
||||
return !!this.Thumbnail
|
||||
}
|
||||
|
||||
hasGeneratedThumbnail () {
|
||||
return this.hasThumbnail() && this.Thumbnail.automaticallyGenerated === true
|
||||
}
|
||||
|
||||
shouldGenerateThumbnailWithNewElement (newElement: MVideoPlaylistElement) {
|
||||
if (this.hasThumbnail() === false) return true
|
||||
if (newElement.position === 1 && this.hasGeneratedThumbnail()) return true
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
generateThumbnailName () {
|
||||
const extension = '.jpg'
|
||||
|
||||
return 'playlist-' + buildUUID() + extension
|
||||
}
|
||||
|
||||
getThumbnailUrl () {
|
||||
if (!this.hasThumbnail()) return null
|
||||
|
||||
return WEBSERVER.URL + LAZY_STATIC_PATHS.THUMBNAILS + this.Thumbnail.filename
|
||||
}
|
||||
|
||||
getThumbnailStaticPath () {
|
||||
if (!this.hasThumbnail()) return null
|
||||
|
||||
return join(LAZY_STATIC_PATHS.THUMBNAILS, this.Thumbnail.filename)
|
||||
}
|
||||
|
||||
getWatchStaticPath () {
|
||||
return buildPlaylistWatchPath({ shortUUID: uuidToShort(this.uuid) })
|
||||
}
|
||||
|
||||
getEmbedStaticPath () {
|
||||
return buildPlaylistEmbedPath({ shortUUID: uuidToShort(this.uuid) })
|
||||
}
|
||||
|
||||
static async getStats () {
|
||||
const totalLocalPlaylists = await VideoPlaylistModel.count({
|
||||
include: [
|
||||
{
|
||||
model: AccountModel.unscoped(),
|
||||
required: true,
|
||||
include: [
|
||||
{
|
||||
model: ActorModel.unscoped(),
|
||||
required: true,
|
||||
where: {
|
||||
serverId: null
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
where: {
|
||||
privacy: VideoPlaylistPrivacy.PUBLIC
|
||||
}
|
||||
})
|
||||
|
||||
return {
|
||||
totalLocalPlaylists
|
||||
}
|
||||
}
|
||||
|
||||
setAsRefreshed () {
|
||||
return setAsUpdated({ sequelize: this.sequelize, table: 'videoPlaylist', id: this.id })
|
||||
}
|
||||
|
||||
setVideosLength (videosLength: number) {
|
||||
this.set('videosLength' as any, videosLength, { raw: true })
|
||||
}
|
||||
|
||||
isLocal () {
|
||||
return this.OwnerAccount.isLocal()
|
||||
}
|
||||
|
||||
isOutdated () {
|
||||
if (this.isLocal()) return false
|
||||
|
||||
return isOutdated(this, ACTIVITY_PUB.VIDEO_PLAYLIST_REFRESH_INTERVAL)
|
||||
}
|
||||
|
||||
toFormattedJSON (this: MVideoPlaylistFormattable): VideoPlaylist {
|
||||
return {
|
||||
id: this.id,
|
||||
uuid: this.uuid,
|
||||
shortUUID: uuidToShort(this.uuid),
|
||||
|
||||
isLocal: this.isLocal(),
|
||||
|
||||
url: this.url,
|
||||
|
||||
displayName: this.name,
|
||||
description: this.description,
|
||||
privacy: {
|
||||
id: this.privacy,
|
||||
label: VideoPlaylistModel.getPrivacyLabel(this.privacy)
|
||||
},
|
||||
|
||||
thumbnailPath: this.getThumbnailStaticPath(),
|
||||
embedPath: this.getEmbedStaticPath(),
|
||||
|
||||
type: {
|
||||
id: this.type,
|
||||
label: VideoPlaylistModel.getTypeLabel(this.type)
|
||||
},
|
||||
|
||||
videosLength: this.get('videosLength') as number,
|
||||
|
||||
createdAt: this.createdAt,
|
||||
updatedAt: this.updatedAt,
|
||||
|
||||
ownerAccount: this.OwnerAccount.toFormattedSummaryJSON(),
|
||||
|
||||
videoChannelPosition: this.videoChannelPosition,
|
||||
videoChannel: this.VideoChannel
|
||||
? this.VideoChannel.toFormattedSummaryJSON()
|
||||
: null
|
||||
}
|
||||
}
|
||||
|
||||
toActivityPubObject (this: MVideoPlaylistAP, page: number, t: Transaction): Promise<PlaylistObject> {
|
||||
const handler = (start: number, count: number) => {
|
||||
return VideoPlaylistElementModel.listUrlsOfForAP(this.id, start, count, t)
|
||||
}
|
||||
|
||||
let icon: ActivityIconObject
|
||||
if (this.hasThumbnail()) {
|
||||
icon = {
|
||||
type: 'Image' as 'Image',
|
||||
url: this.getThumbnailUrl(),
|
||||
mediaType: 'image/jpeg' as 'image/jpeg',
|
||||
width: THUMBNAILS_SIZE.width,
|
||||
height: THUMBNAILS_SIZE.height
|
||||
}
|
||||
}
|
||||
|
||||
return activityPubCollectionPagination(this.url, handler, page)
|
||||
.then(o => {
|
||||
return Object.assign(o, {
|
||||
type: 'Playlist' as 'Playlist',
|
||||
name: this.name,
|
||||
content: this.description,
|
||||
mediaType: 'text/markdown' as 'text/markdown',
|
||||
uuid: this.uuid,
|
||||
videoChannelPosition: this.videoChannelPosition,
|
||||
published: this.createdAt.toISOString(),
|
||||
updated: this.updatedAt.toISOString(),
|
||||
attributedTo: this.VideoChannel ? [ this.VideoChannel.Actor.url ] : [],
|
||||
icon
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
221
server/core/models/video/video-share.ts
Normal file
221
server/core/models/video/video-share.ts
Normal file
@@ -0,0 +1,221 @@
|
||||
import { forceNumber } from '@peertube/peertube-core-utils'
|
||||
import { literal, Op, QueryTypes, Transaction } from 'sequelize'
|
||||
import { AllowNull, BelongsTo, Column, CreatedAt, DataType, ForeignKey, Is, Scopes, Table, UpdatedAt } from 'sequelize-typescript'
|
||||
import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc.js'
|
||||
import { CONSTRAINTS_FIELDS } from '../../initializers/constants.js'
|
||||
import { MActorDefault, MActorFollowersUrl, MActorId } from '../../types/models/index.js'
|
||||
import { MVideoShareActor, MVideoShareFull } from '../../types/models/video/index.js'
|
||||
import { ActorModel } from '../actor/actor.js'
|
||||
import { buildLocalActorIdsIn, SequelizeModel, throwIfNotValid } from '../shared/index.js'
|
||||
import { VideoModel } from './video.js'
|
||||
|
||||
enum ScopeNames {
|
||||
FULL = 'FULL',
|
||||
WITH_ACTOR = 'WITH_ACTOR'
|
||||
}
|
||||
|
||||
@Scopes(() => ({
|
||||
[ScopeNames.FULL]: {
|
||||
include: [
|
||||
{
|
||||
model: ActorModel,
|
||||
required: true
|
||||
},
|
||||
{
|
||||
model: VideoModel,
|
||||
required: true
|
||||
}
|
||||
]
|
||||
},
|
||||
[ScopeNames.WITH_ACTOR]: {
|
||||
include: [
|
||||
{
|
||||
model: ActorModel,
|
||||
required: true
|
||||
}
|
||||
]
|
||||
}
|
||||
}))
|
||||
@Table({
|
||||
tableName: 'videoShare',
|
||||
indexes: [
|
||||
{
|
||||
fields: [ 'actorId' ]
|
||||
},
|
||||
{
|
||||
fields: [ 'videoId' ]
|
||||
},
|
||||
{
|
||||
fields: [ 'url' ],
|
||||
unique: true
|
||||
}
|
||||
]
|
||||
})
|
||||
export class VideoShareModel extends SequelizeModel<VideoShareModel> {
|
||||
@AllowNull(false)
|
||||
@Is('VideoShareUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
|
||||
@Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_SHARE.URL.max))
|
||||
declare url: string
|
||||
|
||||
@CreatedAt
|
||||
declare createdAt: Date
|
||||
|
||||
@UpdatedAt
|
||||
declare updatedAt: Date
|
||||
|
||||
@ForeignKey(() => ActorModel)
|
||||
@Column
|
||||
declare actorId: number
|
||||
|
||||
@BelongsTo(() => ActorModel, {
|
||||
foreignKey: {
|
||||
allowNull: false
|
||||
},
|
||||
onDelete: 'cascade'
|
||||
})
|
||||
declare Actor: Awaited<ActorModel>
|
||||
|
||||
@ForeignKey(() => VideoModel)
|
||||
@Column
|
||||
declare videoId: number
|
||||
|
||||
@BelongsTo(() => VideoModel, {
|
||||
foreignKey: {
|
||||
allowNull: false
|
||||
},
|
||||
onDelete: 'cascade'
|
||||
})
|
||||
declare Video: Awaited<VideoModel>
|
||||
|
||||
static load (actorId: number | string, videoId: number | string, t?: Transaction): Promise<MVideoShareActor> {
|
||||
return VideoShareModel.scope(ScopeNames.WITH_ACTOR).findOne({
|
||||
where: {
|
||||
actorId,
|
||||
videoId
|
||||
},
|
||||
transaction: t
|
||||
})
|
||||
}
|
||||
|
||||
static loadByUrl (url: string, t: Transaction): Promise<MVideoShareFull> {
|
||||
return VideoShareModel.scope(ScopeNames.FULL).findOne({
|
||||
where: {
|
||||
url
|
||||
},
|
||||
transaction: t
|
||||
})
|
||||
}
|
||||
|
||||
static listActorIdsAndFollowerUrlsByShare (videoId: number, t: Transaction) {
|
||||
const query = `SELECT "actor"."id" AS "id", "actor"."followersUrl" AS "followersUrl" ` +
|
||||
`FROM "videoShare" ` +
|
||||
`INNER JOIN "actor" ON "actor"."id" = "videoShare"."actorId" ` +
|
||||
`WHERE "videoShare"."videoId" = :videoId`
|
||||
|
||||
const options = {
|
||||
type: QueryTypes.SELECT as QueryTypes.SELECT,
|
||||
replacements: { videoId },
|
||||
transaction: t
|
||||
}
|
||||
|
||||
return VideoShareModel.sequelize.query<MActorId & MActorFollowersUrl>(query, options)
|
||||
}
|
||||
|
||||
static listActorsWhoSharedVideosOf (options: {
|
||||
actorOwnerId: number
|
||||
transaction: Transaction
|
||||
}): Promise<MActorDefault[]> {
|
||||
const safeOwnerId = forceNumber(options.actorOwnerId)
|
||||
|
||||
// /!\ On actor model
|
||||
const query = {
|
||||
where: {
|
||||
[Op.and]: [
|
||||
literal(
|
||||
`EXISTS (` +
|
||||
` SELECT 1 FROM "videoShare" ` +
|
||||
` INNER JOIN "video" ON "videoShare"."videoId" = "video"."id" ` +
|
||||
` INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ` +
|
||||
` INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ` +
|
||||
` INNER JOIN "actor" ON "actor"."accountId" = "account"."id" ` +
|
||||
` WHERE "videoShare"."actorId" = "ActorModel"."id" AND "actor"."id" = ${safeOwnerId} ` +
|
||||
` LIMIT 1` +
|
||||
`)`
|
||||
)
|
||||
]
|
||||
},
|
||||
transaction: options.transaction
|
||||
}
|
||||
|
||||
return ActorModel.findAll(query)
|
||||
}
|
||||
|
||||
static listActorsByVideoChannel (options: {
|
||||
channelId: number
|
||||
transaction: Transaction
|
||||
}): Promise<MActorDefault[]> {
|
||||
const safeChannelId = forceNumber(options.channelId)
|
||||
|
||||
// /!\ On actor model
|
||||
const query = {
|
||||
where: {
|
||||
[Op.and]: [
|
||||
literal(
|
||||
`EXISTS (` +
|
||||
` SELECT 1 FROM "videoShare" ` +
|
||||
` INNER JOIN "video" ON "videoShare"."videoId" = "video"."id" ` +
|
||||
` WHERE "videoShare"."actorId" = "ActorModel"."id" AND "video"."channelId" = ${safeChannelId} ` +
|
||||
` LIMIT 1` +
|
||||
`)`
|
||||
)
|
||||
]
|
||||
},
|
||||
transaction: options.transaction
|
||||
}
|
||||
|
||||
return ActorModel.findAll(query)
|
||||
}
|
||||
|
||||
static listAndCountByVideoId (videoId: number, start: number, count: number, t?: Transaction) {
|
||||
const query = {
|
||||
offset: start,
|
||||
limit: count,
|
||||
where: {
|
||||
videoId
|
||||
},
|
||||
transaction: t
|
||||
}
|
||||
|
||||
return Promise.all([
|
||||
VideoShareModel.count(query),
|
||||
VideoShareModel.findAll(query)
|
||||
]).then(([ total, data ]) => ({ total, data }))
|
||||
}
|
||||
|
||||
static listRemoteShareUrlsOfLocalVideos () {
|
||||
const query = `SELECT "videoShare".url FROM "videoShare" ` +
|
||||
`INNER JOIN actor ON actor.id = "videoShare"."actorId" AND actor."serverId" IS NOT NULL ` +
|
||||
`INNER JOIN video ON video.id = "videoShare"."videoId" AND video.remote IS FALSE`
|
||||
|
||||
return VideoShareModel.sequelize.query<{ url: string }>(query, {
|
||||
type: QueryTypes.SELECT,
|
||||
raw: true
|
||||
}).then(rows => rows.map(r => r.url))
|
||||
}
|
||||
|
||||
static cleanOldSharesOf (videoId: number, beforeUpdatedAt: Date) {
|
||||
const query = {
|
||||
where: {
|
||||
updatedAt: {
|
||||
[Op.lt]: beforeUpdatedAt
|
||||
},
|
||||
videoId,
|
||||
actorId: {
|
||||
[Op.notIn]: buildLocalActorIdsIn()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return VideoShareModel.destroy(query)
|
||||
}
|
||||
}
|
||||
168
server/core/models/video/video-source.ts
Normal file
168
server/core/models/video/video-source.ts
Normal file
@@ -0,0 +1,168 @@
|
||||
import { getResolutionLabel } from '@peertube/peertube-core-utils'
|
||||
import { ActivityVideoUrlObject, type FileStorageType, type VideoSource } from '@peertube/peertube-models'
|
||||
import { DOWNLOAD_PATHS, WEBSERVER } from '@server/initializers/constants.js'
|
||||
import { getVideoFileMimeType } from '@server/lib/video-file.js'
|
||||
import { MVideoSource } from '@server/types/models/video/video-source.js'
|
||||
import { extname, join } from 'path'
|
||||
import { Transaction } from 'sequelize'
|
||||
import { AllowNull, BelongsTo, Column, CreatedAt, DataType, ForeignKey, Table, UpdatedAt } from 'sequelize-typescript'
|
||||
import { SequelizeModel, doesExist, getSort } from '../shared/index.js'
|
||||
import { VideoModel } from './video.js'
|
||||
|
||||
@Table({
|
||||
tableName: 'videoSource',
|
||||
indexes: [
|
||||
{
|
||||
fields: [ 'videoId' ]
|
||||
},
|
||||
{
|
||||
fields: [ { name: 'createdAt', order: 'DESC' } ]
|
||||
},
|
||||
{
|
||||
fields: [ 'keptOriginalFilename' ],
|
||||
unique: true
|
||||
}
|
||||
]
|
||||
})
|
||||
export class VideoSourceModel extends SequelizeModel<VideoSourceModel> {
|
||||
@CreatedAt
|
||||
declare createdAt: Date
|
||||
|
||||
@UpdatedAt
|
||||
declare updatedAt: Date
|
||||
|
||||
// The name of the uploaded file
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare inputFilename: string
|
||||
|
||||
// The name of the file stored on disk
|
||||
// null means we don't have the file
|
||||
@AllowNull(true)
|
||||
@Column
|
||||
declare keptOriginalFilename: string
|
||||
|
||||
@AllowNull(true)
|
||||
@Column
|
||||
declare resolution: number
|
||||
|
||||
@AllowNull(true)
|
||||
@Column
|
||||
declare width: number
|
||||
|
||||
@AllowNull(true)
|
||||
@Column
|
||||
declare height: number
|
||||
|
||||
@AllowNull(true)
|
||||
@Column
|
||||
declare fps: number
|
||||
|
||||
@AllowNull(true)
|
||||
@Column(DataType.BIGINT)
|
||||
declare size: number
|
||||
|
||||
@AllowNull(true)
|
||||
@Column(DataType.JSONB)
|
||||
declare metadata: any
|
||||
|
||||
@AllowNull(true)
|
||||
@Column
|
||||
declare storage: FileStorageType
|
||||
|
||||
@AllowNull(true)
|
||||
@Column
|
||||
declare fileUrl: string
|
||||
|
||||
@ForeignKey(() => VideoModel)
|
||||
@Column
|
||||
declare videoId: number
|
||||
|
||||
@BelongsTo(() => VideoModel, {
|
||||
foreignKey: {
|
||||
allowNull: false
|
||||
},
|
||||
onDelete: 'cascade'
|
||||
})
|
||||
declare Video: Awaited<VideoModel>
|
||||
|
||||
static loadLatest (videoId: number, transaction?: Transaction) {
|
||||
return VideoSourceModel.findOne<MVideoSource>({
|
||||
where: { videoId },
|
||||
order: getSort('-createdAt'),
|
||||
transaction
|
||||
})
|
||||
}
|
||||
|
||||
static loadByKeptOriginalFilename (keptOriginalFilename: string) {
|
||||
return VideoSourceModel.findOne<MVideoSource>({
|
||||
where: { keptOriginalFilename }
|
||||
})
|
||||
}
|
||||
|
||||
static listAll (videoId: number, transaction?: Transaction) {
|
||||
return VideoSourceModel.findAll<MVideoSource>({
|
||||
where: { videoId },
|
||||
transaction
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static async doesOwnedFileExist (filename: string, storage: FileStorageType) {
|
||||
const query = 'SELECT 1 FROM "videoSource" ' +
|
||||
'INNER JOIN "video" ON "video"."id" = "videoSource"."videoId" AND "video"."remote" IS FALSE ' +
|
||||
`WHERE "keptOriginalFilename" = $filename AND "storage" = $storage LIMIT 1`
|
||||
|
||||
return doesExist({ sequelize: this.sequelize, query, bind: { filename, storage } })
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
getFileDownloadUrl () {
|
||||
if (!this.keptOriginalFilename) return null
|
||||
|
||||
return WEBSERVER.URL + join(DOWNLOAD_PATHS.ORIGINAL_VIDEO_FILE, this.keptOriginalFilename)
|
||||
}
|
||||
|
||||
toActivityPubObject (this: MVideoSource): ActivityVideoUrlObject {
|
||||
const mimeType = getVideoFileMimeType(extname(this.inputFilename), false)
|
||||
|
||||
return {
|
||||
type: 'Link',
|
||||
mediaType: mimeType as ActivityVideoUrlObject['mediaType'],
|
||||
href: null,
|
||||
height: this.height || this.resolution,
|
||||
width: this.width,
|
||||
size: this.size,
|
||||
fps: this.fps,
|
||||
attachment: []
|
||||
}
|
||||
}
|
||||
|
||||
toFormattedJSON (this: MVideoSource): VideoSource {
|
||||
return {
|
||||
inputFilename: this.inputFilename,
|
||||
|
||||
fileUrl: this.fileUrl,
|
||||
fileDownloadUrl: this.getFileDownloadUrl(),
|
||||
|
||||
resolution: {
|
||||
id: this.resolution,
|
||||
label: this.resolution !== null
|
||||
? getResolutionLabel({ resolution: this.resolution, height: this.height, width: this.width })
|
||||
: null
|
||||
},
|
||||
size: this.size,
|
||||
|
||||
width: this.width,
|
||||
height: this.height,
|
||||
|
||||
fps: this.fps,
|
||||
|
||||
metadata: this.metadata,
|
||||
|
||||
createdAt: this.createdAt.toISOString()
|
||||
}
|
||||
}
|
||||
}
|
||||
396
server/core/models/video/video-streaming-playlist.ts
Normal file
396
server/core/models/video/video-streaming-playlist.ts
Normal file
@@ -0,0 +1,396 @@
|
||||
import {
|
||||
FileStorage,
|
||||
VideoResolution,
|
||||
VideoStreamingPlaylistType,
|
||||
type FileStorageType,
|
||||
type VideoStreamingPlaylistType_Type
|
||||
} from '@peertube/peertube-models'
|
||||
import { generateP2PMediaLoaderHash } from '@peertube/peertube-node-utils'
|
||||
import { logger } from '@server/helpers/logger.js'
|
||||
import { CONFIG } from '@server/initializers/config.js'
|
||||
import { getHLSPrivateFileUrl, getObjectStoragePublicFileUrl } from '@server/lib/object-storage/index.js'
|
||||
import { generateHLSMasterPlaylistFilename, generateHlsSha256SegmentsFilename } from '@server/lib/paths.js'
|
||||
import { isVideoInPrivateDirectory } from '@server/lib/video-privacy.js'
|
||||
import { VideoFileModel } from '@server/models/video/video-file.js'
|
||||
import {
|
||||
MStreamingPlaylist,
|
||||
MStreamingPlaylistFiles,
|
||||
MStreamingPlaylistFilesVideo,
|
||||
MStreamingPlaylistVideo,
|
||||
MVideo,
|
||||
MVideoPrivacy
|
||||
} from '@server/types/models/index.js'
|
||||
import memoizee from 'memoizee'
|
||||
import { join } from 'path'
|
||||
import { Op, Transaction } from 'sequelize'
|
||||
import { AllowNull, BelongsTo, Column, CreatedAt, DataType, Default, ForeignKey, HasMany, Is, Table, UpdatedAt } from 'sequelize-typescript'
|
||||
import { isArrayOf } from '../../helpers/custom-validators/misc.js'
|
||||
import { isVideoFileInfoHashValid } from '../../helpers/custom-validators/videos.js'
|
||||
import {
|
||||
CONSTRAINTS_FIELDS,
|
||||
MEMOIZE_LENGTH,
|
||||
MEMOIZE_TTL,
|
||||
P2P_MEDIA_LOADER_PEER_VERSION,
|
||||
STATIC_PATHS,
|
||||
WEBSERVER
|
||||
} from '../../initializers/constants.js'
|
||||
import { VideoRedundancyModel } from '../redundancy/video-redundancy.js'
|
||||
import { SequelizeModel, doesExist, throwIfNotValid } from '../shared/index.js'
|
||||
import { VideoModel } from './video.js'
|
||||
|
||||
@Table({
|
||||
tableName: 'videoStreamingPlaylist',
|
||||
indexes: [
|
||||
{
|
||||
fields: [ 'videoId' ]
|
||||
},
|
||||
{
|
||||
fields: [ 'videoId', 'type' ],
|
||||
unique: true
|
||||
},
|
||||
{
|
||||
fields: [ 'p2pMediaLoaderInfohashes' ],
|
||||
using: 'gin'
|
||||
}
|
||||
]
|
||||
})
|
||||
export class VideoStreamingPlaylistModel extends SequelizeModel<VideoStreamingPlaylistModel> {
|
||||
@CreatedAt
|
||||
declare createdAt: Date
|
||||
|
||||
@UpdatedAt
|
||||
declare updatedAt: Date
|
||||
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare type: VideoStreamingPlaylistType_Type
|
||||
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare playlistFilename: string
|
||||
|
||||
@AllowNull(true)
|
||||
@Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
|
||||
declare playlistUrl: string
|
||||
|
||||
@AllowNull(false)
|
||||
@Is('VideoStreamingPlaylistInfoHashes', value => throwIfNotValid(value, v => isArrayOf(v, isVideoFileInfoHashValid), 'info hashes'))
|
||||
@Column(DataType.ARRAY(DataType.STRING))
|
||||
declare p2pMediaLoaderInfohashes: string[]
|
||||
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
declare p2pMediaLoaderPeerVersion: number
|
||||
|
||||
@AllowNull(true)
|
||||
@Column
|
||||
declare segmentsSha256Filename: string
|
||||
|
||||
@AllowNull(true)
|
||||
@Column
|
||||
declare segmentsSha256Url: string
|
||||
|
||||
@ForeignKey(() => VideoModel)
|
||||
@Column
|
||||
declare videoId: number
|
||||
|
||||
@AllowNull(false)
|
||||
@Default(FileStorage.FILE_SYSTEM)
|
||||
@Column
|
||||
declare storage: FileStorageType
|
||||
|
||||
@BelongsTo(() => VideoModel, {
|
||||
foreignKey: {
|
||||
allowNull: false
|
||||
},
|
||||
onDelete: 'CASCADE'
|
||||
})
|
||||
declare Video: Awaited<VideoModel>
|
||||
|
||||
@HasMany(() => VideoFileModel, {
|
||||
foreignKey: {
|
||||
allowNull: true
|
||||
},
|
||||
onDelete: 'CASCADE'
|
||||
})
|
||||
declare VideoFiles: Awaited<VideoFileModel>[]
|
||||
|
||||
@HasMany(() => VideoRedundancyModel, {
|
||||
foreignKey: {
|
||||
allowNull: false
|
||||
},
|
||||
onDelete: 'CASCADE',
|
||||
hooks: true
|
||||
})
|
||||
declare RedundancyVideos: Awaited<VideoRedundancyModel>[]
|
||||
|
||||
static doesInfohashExistCached = memoizee(VideoStreamingPlaylistModel.doesInfohashExist.bind(VideoStreamingPlaylistModel), {
|
||||
promise: true,
|
||||
max: MEMOIZE_LENGTH.INFO_HASH_EXISTS,
|
||||
maxAge: MEMOIZE_TTL.INFO_HASH_EXISTS
|
||||
})
|
||||
|
||||
static doesInfohashExist (infoHash: string) {
|
||||
// Don't add a LIMIT 1 here to prevent seq scan by PostgreSQL (not sure why id doesn't use the index when we add a LIMIT)
|
||||
const query = 'SELECT 1 FROM "videoStreamingPlaylist" WHERE "p2pMediaLoaderInfohashes" @> $infoHash'
|
||||
|
||||
return doesExist({ sequelize: this.sequelize, query, bind: { infoHash: `{${infoHash}}` } }) // Transform infoHash in a PG array
|
||||
}
|
||||
|
||||
static buildP2PMediaLoaderInfoHashes (playlistUrl: string, files: { height: number }[]) {
|
||||
const hashes: string[] = []
|
||||
|
||||
const version = Math.abs(P2P_MEDIA_LOADER_PEER_VERSION)
|
||||
|
||||
// https://github.com/Novage/p2p-media-loader/blob/master/p2p-media-loader-core/lib/p2p-media-manager.ts#L115
|
||||
for (let i = 0; i < files.length; i++) {
|
||||
hashes.push(generateP2PMediaLoaderHash(`v${version}-${playlistUrl}-main-${i}`))
|
||||
}
|
||||
|
||||
// Audio only stream
|
||||
if (files.some(f => f.height === 0)) {
|
||||
hashes.push(generateP2PMediaLoaderHash(`v${version}-${playlistUrl}-secondary-0`))
|
||||
}
|
||||
|
||||
logger.debug('Assigned P2P Media Loader info hashes', { playlistUrl, hashes })
|
||||
|
||||
return hashes
|
||||
}
|
||||
|
||||
static async listIdsByIncorrectPeerVersion () {
|
||||
const rows = await VideoStreamingPlaylistModel.unscoped().findAll({
|
||||
raw: true,
|
||||
attributes: [ 'id' ],
|
||||
where: {
|
||||
p2pMediaLoaderPeerVersion: {
|
||||
[Op.ne]: P2P_MEDIA_LOADER_PEER_VERSION
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return rows.map(r => r.id)
|
||||
}
|
||||
|
||||
static async listIdsLocals () {
|
||||
const rows = await VideoStreamingPlaylistModel.unscoped().findAll({
|
||||
raw: true,
|
||||
attributes: [ 'id' ],
|
||||
include: [
|
||||
{
|
||||
model: VideoModel.unscoped(),
|
||||
required: true,
|
||||
where: {
|
||||
remote: false
|
||||
}
|
||||
}
|
||||
]
|
||||
})
|
||||
|
||||
return rows.map(r => r.id)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static loadWithVideoAndFiles (id: number) {
|
||||
const options = {
|
||||
include: [
|
||||
{
|
||||
model: VideoModel.unscoped(),
|
||||
required: true
|
||||
},
|
||||
{
|
||||
model: VideoFileModel.unscoped()
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
return VideoStreamingPlaylistModel.findByPk<MStreamingPlaylistFilesVideo>(id, options)
|
||||
}
|
||||
|
||||
static loadWithVideo (id: number, transaction?: Transaction) {
|
||||
const options = {
|
||||
include: [
|
||||
{
|
||||
model: VideoModel.unscoped(),
|
||||
required: true
|
||||
}
|
||||
],
|
||||
transaction
|
||||
}
|
||||
|
||||
return VideoStreamingPlaylistModel.findByPk(id, options)
|
||||
}
|
||||
|
||||
static loadHLSByVideo (videoId: number, transaction?: Transaction): Promise<MStreamingPlaylist> {
|
||||
const options = {
|
||||
where: {
|
||||
type: VideoStreamingPlaylistType.HLS,
|
||||
videoId
|
||||
},
|
||||
transaction
|
||||
}
|
||||
|
||||
return VideoStreamingPlaylistModel.findOne(options)
|
||||
}
|
||||
|
||||
static loadHLSByVideoWithVideo (videoId: number, transaction?: Transaction): Promise<MStreamingPlaylistVideo> {
|
||||
const options = {
|
||||
where: {
|
||||
type: VideoStreamingPlaylistType.HLS,
|
||||
videoId
|
||||
},
|
||||
include: [
|
||||
{
|
||||
model: VideoModel.unscoped(),
|
||||
required: true
|
||||
}
|
||||
],
|
||||
transaction
|
||||
}
|
||||
|
||||
return VideoStreamingPlaylistModel.findOne(options)
|
||||
}
|
||||
|
||||
static async loadOrGenerate (video: MVideo, transaction?: Transaction) {
|
||||
let playlist = await VideoStreamingPlaylistModel.loadHLSByVideo(video.id, transaction)
|
||||
let generated = false
|
||||
|
||||
if (!playlist) {
|
||||
generated = true
|
||||
|
||||
playlist = new VideoStreamingPlaylistModel({
|
||||
p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
|
||||
type: VideoStreamingPlaylistType.HLS,
|
||||
storage: FileStorage.FILE_SYSTEM,
|
||||
p2pMediaLoaderInfohashes: [],
|
||||
playlistFilename: generateHLSMasterPlaylistFilename(video.isLive),
|
||||
segmentsSha256Filename: generateHlsSha256SegmentsFilename(video.isLive),
|
||||
videoId: video.id
|
||||
})
|
||||
|
||||
await playlist.save({ transaction })
|
||||
}
|
||||
|
||||
return { generated, playlist: Object.assign(playlist, { Video: video }) }
|
||||
}
|
||||
|
||||
static doesOwnedVideoUUIDExist (videoUUID: string, storage: FileStorageType) {
|
||||
const query = `SELECT 1 FROM "videoStreamingPlaylist" ` +
|
||||
`INNER JOIN "video" ON "video"."id" = "videoStreamingPlaylist"."videoId" ` +
|
||||
`AND "video"."remote" IS FALSE AND "video"."uuid" = $videoUUID ` +
|
||||
`AND "storage" = $storage LIMIT 1`
|
||||
|
||||
return doesExist({ sequelize: this.sequelize, query, bind: { videoUUID, storage } })
|
||||
}
|
||||
|
||||
assignP2PMediaLoaderInfoHashes (video: MVideo, files: { height: number }[]) {
|
||||
const masterPlaylistUrl = this.getMasterPlaylistUrl(video)
|
||||
|
||||
this.p2pMediaLoaderInfohashes = VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(masterPlaylistUrl, files)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
getMasterPlaylistUrl (video: MVideo) {
|
||||
if (video.isLocal()) {
|
||||
if (this.storage === FileStorage.OBJECT_STORAGE) {
|
||||
return this.getMasterPlaylistObjectStorageUrl(video)
|
||||
}
|
||||
|
||||
return WEBSERVER.URL + this.getMasterPlaylistStaticPath(video)
|
||||
}
|
||||
|
||||
return this.playlistUrl
|
||||
}
|
||||
|
||||
private getMasterPlaylistObjectStorageUrl (video: MVideo) {
|
||||
if (video.hasPrivateStaticPath() && CONFIG.OBJECT_STORAGE.PROXY.PROXIFY_PRIVATE_FILES === true) {
|
||||
return getHLSPrivateFileUrl(video, this.playlistFilename)
|
||||
}
|
||||
|
||||
return getObjectStoragePublicFileUrl(this.playlistUrl, CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
getSha256SegmentsUrl (video: MVideo) {
|
||||
if (video.isLocal()) {
|
||||
if (!this.segmentsSha256Filename) return null
|
||||
|
||||
if (this.storage === FileStorage.OBJECT_STORAGE) {
|
||||
return this.getSha256SegmentsObjectStorageUrl(video)
|
||||
}
|
||||
|
||||
return WEBSERVER.URL + this.getSha256SegmentsStaticPath(video)
|
||||
}
|
||||
|
||||
return this.segmentsSha256Url
|
||||
}
|
||||
|
||||
private getSha256SegmentsObjectStorageUrl (video: MVideo) {
|
||||
if (video.hasPrivateStaticPath() && CONFIG.OBJECT_STORAGE.PROXY.PROXIFY_PRIVATE_FILES === true) {
|
||||
return getHLSPrivateFileUrl(video, this.segmentsSha256Filename)
|
||||
}
|
||||
|
||||
return getObjectStoragePublicFileUrl(this.segmentsSha256Url, CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
hasAudioAndVideoSplitted (this: MStreamingPlaylistFiles) {
|
||||
// We need at least 2 files to have audio and video splitted
|
||||
if (this.VideoFiles.length === 1) return false
|
||||
|
||||
let hasAudio = false
|
||||
let hasVideo = false
|
||||
|
||||
for (const file of this.VideoFiles) {
|
||||
// File contains both streams: audio and video is not splitted
|
||||
if (file.hasAudio() && file.hasVideo()) return false
|
||||
|
||||
if (file.resolution === VideoResolution.H_NOVIDEO) hasAudio = true
|
||||
else if (file.hasVideo()) hasVideo = true
|
||||
|
||||
if (hasVideo && hasAudio) return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
getStringType () {
|
||||
if (this.type === VideoStreamingPlaylistType.HLS) return 'hls'
|
||||
|
||||
return 'unknown'
|
||||
}
|
||||
|
||||
getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
|
||||
return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
|
||||
}
|
||||
|
||||
hasSameUniqueKeysThan (other: MStreamingPlaylist) {
|
||||
return this.type === other.type &&
|
||||
this.videoId === other.videoId
|
||||
}
|
||||
|
||||
withVideo (video: MVideo) {
|
||||
return Object.assign(this, { Video: video })
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static getPlaylistFileStaticPath (video: MVideoPrivacy, filename: string) {
|
||||
if (isVideoInPrivateDirectory(video.privacy)) {
|
||||
return join(STATIC_PATHS.STREAMING_PLAYLISTS.PRIVATE_HLS, video.uuid, filename)
|
||||
}
|
||||
|
||||
return join(STATIC_PATHS.STREAMING_PLAYLISTS.HLS, video.uuid, filename)
|
||||
}
|
||||
|
||||
private getMasterPlaylistStaticPath (video: MVideoPrivacy) {
|
||||
return VideoStreamingPlaylistModel.getPlaylistFileStaticPath(video, this.playlistFilename)
|
||||
}
|
||||
|
||||
private getSha256SegmentsStaticPath (video: MVideoPrivacy) {
|
||||
return VideoStreamingPlaylistModel.getPlaylistFileStaticPath(video, this.segmentsSha256Filename)
|
||||
}
|
||||
}
|
||||
31
server/core/models/video/video-tag.ts
Normal file
31
server/core/models/video/video-tag.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { Column, CreatedAt, ForeignKey, Table, UpdatedAt } from 'sequelize-typescript'
|
||||
import { SequelizeModel } from '../shared/index.js'
|
||||
import { TagModel } from './tag.js'
|
||||
import { VideoModel } from './video.js'
|
||||
|
||||
@Table({
|
||||
tableName: 'videoTag',
|
||||
indexes: [
|
||||
{
|
||||
fields: [ 'videoId' ]
|
||||
},
|
||||
{
|
||||
fields: [ 'tagId' ]
|
||||
}
|
||||
]
|
||||
})
|
||||
export class VideoTagModel extends SequelizeModel<VideoTagModel> {
|
||||
@CreatedAt
|
||||
declare createdAt: Date
|
||||
|
||||
@UpdatedAt
|
||||
declare updatedAt: Date
|
||||
|
||||
@ForeignKey(() => VideoModel)
|
||||
@Column
|
||||
declare videoId: number
|
||||
|
||||
@ForeignKey(() => TagModel)
|
||||
@Column
|
||||
declare tagId: number
|
||||
}
|
||||
2287
server/core/models/video/video.ts
Normal file
2287
server/core/models/video/video.ts
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user