1
0
Fork 0
mirror of https://github.com/Chocobozzz/PeerTube.git synced 2025-10-04 10:19:35 +02:00

server/server -> server/core

This commit is contained in:
Chocobozzz 2023-10-04 15:13:25 +02:00
parent 114327d4ce
commit 5a3d0650c9
No known key found for this signature in database
GPG key ID: 583A612D890159BE
838 changed files with 111 additions and 111 deletions

View file

@ -0,0 +1,35 @@
import Bluebird from 'bluebird'
import { ServerActionHookName, ServerFilterHookName } from '@peertube/peertube-models'
import { logger } from '../../helpers/logger.js'
import { PluginManager } from './plugin-manager.js'
type PromiseFunction <U, T> = (params: U) => Promise<T> | Bluebird<T>
type RawFunction <U, T> = (params: U) => T
// Helpers to run hooks
const Hooks = {
wrapObject: <T, U extends ServerFilterHookName>(result: T, hookName: U, context?: any) => {
return PluginManager.Instance.runHook(hookName, result, context)
},
wrapPromiseFun: async <U, T, V extends ServerFilterHookName>(fun: PromiseFunction<U, T>, params: U, hookName: V) => {
const result = await fun(params)
return PluginManager.Instance.runHook(hookName, result, params)
},
wrapFun: async <U, T, V extends ServerFilterHookName>(fun: RawFunction<U, T>, params: U, hookName: V) => {
const result = fun(params)
return PluginManager.Instance.runHook(hookName, result, params)
},
runAction: <T, U extends ServerActionHookName>(hookName: U, params?: T) => {
PluginManager.Instance.runHook(hookName, undefined, params)
.catch(err => logger.error('Fatal hook error.', { err }))
}
}
export {
Hooks
}

View file

@ -0,0 +1,262 @@
import express from 'express'
import { Server } from 'http'
import { join } from 'path'
import { buildLogger } from '@server/helpers/logger.js'
import { CONFIG } from '@server/initializers/config.js'
import { WEBSERVER } from '@server/initializers/constants.js'
import { sequelizeTypescript } from '@server/initializers/database.js'
import { AccountModel } from '@server/models/account/account.js'
import { AccountBlocklistModel } from '@server/models/account/account-blocklist.js'
import { getServerActor } from '@server/models/application/application.js'
import { ServerModel } from '@server/models/server/server.js'
import { ServerBlocklistModel } from '@server/models/server/server-blocklist.js'
import { UserModel } from '@server/models/user/user.js'
import { VideoModel } from '@server/models/video/video.js'
import { VideoBlacklistModel } from '@server/models/video/video-blacklist.js'
import { MPlugin, MVideo, UserNotificationModelForApi } from '@server/types/models/index.js'
import { PeerTubeHelpers } from '@server/types/plugins/index.js'
import { ffprobePromise } from '@peertube/peertube-ffmpeg'
import { VideoBlacklistCreate, VideoStorage } from '@peertube/peertube-models'
import { addAccountInBlocklist, addServerInBlocklist, removeAccountFromBlocklist, removeServerFromBlocklist } from '../blocklist.js'
import { PeerTubeSocket } from '../peertube-socket.js'
import { ServerConfigManager } from '../server-config-manager.js'
import { blacklistVideo, unblacklistVideo } from '../video-blacklist.js'
import { VideoPathManager } from '../video-path-manager.js'
function buildPluginHelpers (httpServer: Server, pluginModel: MPlugin, npmName: string): PeerTubeHelpers {
const logger = buildPluginLogger(npmName)
const database = buildDatabaseHelpers()
const videos = buildVideosHelpers()
const config = buildConfigHelpers()
const server = buildServerHelpers(httpServer)
const moderation = buildModerationHelpers()
const plugin = buildPluginRelatedHelpers(pluginModel, npmName)
const socket = buildSocketHelpers()
const user = buildUserHelpers()
return {
logger,
database,
videos,
config,
moderation,
plugin,
server,
socket,
user
}
}
export {
buildPluginHelpers
}
// ---------------------------------------------------------------------------
function buildPluginLogger (npmName: string) {
return buildLogger(npmName)
}
function buildDatabaseHelpers () {
return {
query: sequelizeTypescript.query.bind(sequelizeTypescript)
}
}
function buildServerHelpers (httpServer: Server) {
return {
getHTTPServer: () => httpServer,
getServerActor: () => getServerActor()
}
}
function buildVideosHelpers () {
return {
loadByUrl: (url: string) => {
return VideoModel.loadByUrl(url)
},
loadByIdOrUUID: (id: number | string) => {
return VideoModel.load(id)
},
removeVideo: (id: number) => {
return sequelizeTypescript.transaction(async t => {
const video = await VideoModel.loadFull(id, t)
await video.destroy({ transaction: t })
})
},
ffprobe: (path: string) => {
return ffprobePromise(path)
},
getFiles: async (id: number | string) => {
const video = await VideoModel.loadFull(id)
if (!video) return undefined
const webVideoFiles = (video.VideoFiles || []).map(f => ({
path: f.storage === VideoStorage.FILE_SYSTEM
? VideoPathManager.Instance.getFSVideoFileOutputPath(video, f)
: null,
url: f.getFileUrl(video),
resolution: f.resolution,
size: f.size,
fps: f.fps
}))
const hls = video.getHLSPlaylist()
const hlsVideoFiles = hls
? (video.getHLSPlaylist().VideoFiles || []).map(f => {
return {
path: f.storage === VideoStorage.FILE_SYSTEM
? VideoPathManager.Instance.getFSVideoFileOutputPath(hls, f)
: null,
url: f.getFileUrl(video),
resolution: f.resolution,
size: f.size,
fps: f.fps
}
})
: []
const thumbnails = video.Thumbnails.map(t => ({
type: t.type,
url: t.getOriginFileUrl(video),
path: t.getPath()
}))
return {
webtorrent: { // TODO: remove in v7
videoFiles: webVideoFiles
},
webVideo: {
videoFiles: webVideoFiles
},
hls: {
videoFiles: hlsVideoFiles
},
thumbnails
}
}
}
}
function buildModerationHelpers () {
return {
blockServer: async (options: { byAccountId: number, hostToBlock: string }) => {
const serverToBlock = await ServerModel.loadOrCreateByHost(options.hostToBlock)
await addServerInBlocklist(options.byAccountId, serverToBlock.id)
},
unblockServer: async (options: { byAccountId: number, hostToUnblock: string }) => {
const serverBlock = await ServerBlocklistModel.loadByAccountAndHost(options.byAccountId, options.hostToUnblock)
if (!serverBlock) return
await removeServerFromBlocklist(serverBlock)
},
blockAccount: async (options: { byAccountId: number, handleToBlock: string }) => {
const accountToBlock = await AccountModel.loadByNameWithHost(options.handleToBlock)
if (!accountToBlock) return
await addAccountInBlocklist(options.byAccountId, accountToBlock.id)
},
unblockAccount: async (options: { byAccountId: number, handleToUnblock: string }) => {
const targetAccount = await AccountModel.loadByNameWithHost(options.handleToUnblock)
if (!targetAccount) return
const accountBlock = await AccountBlocklistModel.loadByAccountAndTarget(options.byAccountId, targetAccount.id)
if (!accountBlock) return
await removeAccountFromBlocklist(accountBlock)
},
blacklistVideo: async (options: { videoIdOrUUID: number | string, createOptions: VideoBlacklistCreate }) => {
const video = await VideoModel.loadFull(options.videoIdOrUUID)
if (!video) return
await blacklistVideo(video, options.createOptions)
},
unblacklistVideo: async (options: { videoIdOrUUID: number | string }) => {
const video = await VideoModel.loadFull(options.videoIdOrUUID)
if (!video) return
const videoBlacklist = await VideoBlacklistModel.loadByVideoId(video.id)
if (!videoBlacklist) return
await unblacklistVideo(videoBlacklist, video)
}
}
}
function buildConfigHelpers () {
return {
getWebserverUrl () {
return WEBSERVER.URL
},
getServerListeningConfig () {
return { hostname: CONFIG.LISTEN.HOSTNAME, port: CONFIG.LISTEN.PORT }
},
getServerConfig () {
return ServerConfigManager.Instance.getServerConfig()
}
}
}
function buildPluginRelatedHelpers (plugin: MPlugin, npmName: string) {
return {
getBaseStaticRoute: () => `/plugins/${plugin.name}/${plugin.version}/static/`,
getBaseRouterRoute: () => `/plugins/${plugin.name}/${plugin.version}/router/`,
getBaseWebSocketRoute: () => `/plugins/${plugin.name}/${plugin.version}/ws/`,
getDataDirectoryPath: () => join(CONFIG.STORAGE.PLUGINS_DIR, 'data', npmName)
}
}
function buildSocketHelpers () {
return {
sendNotification: (userId: number, notification: UserNotificationModelForApi) => {
PeerTubeSocket.Instance.sendNotification(userId, notification)
},
sendVideoLiveNewState: (video: MVideo) => {
PeerTubeSocket.Instance.sendVideoLiveNewState(video)
}
}
}
function buildUserHelpers () {
return {
loadById: (id: number) => {
return UserModel.loadByIdFull(id)
},
getAuthUser: (res: express.Response) => {
const user = res.locals.oauth?.token?.User || res.locals.videoFileToken?.user
if (!user) return undefined
return UserModel.loadByIdFull(user.id)
}
}
}

View file

@ -0,0 +1,85 @@
import { sanitizeUrl } from '@server/helpers/core-utils.js'
import { logger } from '@server/helpers/logger.js'
import { doJSONRequest } from '@server/helpers/requests.js'
import { CONFIG } from '@server/initializers/config.js'
import { PEERTUBE_VERSION } from '@server/initializers/constants.js'
import { PluginModel } from '@server/models/server/plugin.js'
import {
PeerTubePluginIndex,
PeertubePluginIndexList,
PeertubePluginLatestVersionRequest,
PeertubePluginLatestVersionResponse,
ResultList
} from '@peertube/peertube-models'
import { PluginManager } from './plugin-manager.js'
async function listAvailablePluginsFromIndex (options: PeertubePluginIndexList) {
const { start = 0, count = 20, search, sort = 'npmName', pluginType } = options
const searchParams: PeertubePluginIndexList & Record<string, string | number> = {
start,
count,
sort,
pluginType,
search,
currentPeerTubeEngine: options.currentPeerTubeEngine || PEERTUBE_VERSION
}
const uri = CONFIG.PLUGINS.INDEX.URL + '/api/v1/plugins'
try {
const { body } = await doJSONRequest<any>(uri, { searchParams })
logger.debug('Got result from PeerTube index.', { body })
addInstanceInformation(body)
return body as ResultList<PeerTubePluginIndex>
} catch (err) {
logger.error('Cannot list available plugins from index %s.', uri, { err })
return undefined
}
}
function addInstanceInformation (result: ResultList<PeerTubePluginIndex>) {
for (const d of result.data) {
d.installed = PluginManager.Instance.isRegistered(d.npmName)
d.name = PluginModel.normalizePluginName(d.npmName)
}
return result
}
async function getLatestPluginsVersion (npmNames: string[]): Promise<PeertubePluginLatestVersionResponse> {
const bodyRequest: PeertubePluginLatestVersionRequest = {
npmNames,
currentPeerTubeEngine: PEERTUBE_VERSION
}
const uri = sanitizeUrl(CONFIG.PLUGINS.INDEX.URL) + '/api/v1/plugins/latest-version'
const options = {
json: bodyRequest,
method: 'POST' as 'POST'
}
const { body } = await doJSONRequest<PeertubePluginLatestVersionResponse>(uri, options)
return body
}
async function getLatestPluginVersion (npmName: string) {
const results = await getLatestPluginsVersion([ npmName ])
if (Array.isArray(results) === false || results.length !== 1) {
logger.warn('Cannot get latest supported plugin version of %s.', npmName)
return undefined
}
return results[0].latestVersion
}
export {
listAvailablePluginsFromIndex,
getLatestPluginVersion,
getLatestPluginsVersion
}

View file

@ -0,0 +1,674 @@
import express from 'express'
import { createReadStream, createWriteStream } from 'fs'
import { ensureDir, outputFile, readJSON } from 'fs-extra/esm'
import { Server } from 'http'
import { createRequire } from 'module'
import { basename, join } from 'path'
import { getCompleteLocale, getHookType, internalRunHook } from '@peertube/peertube-core-utils'
import {
ClientScriptJSON,
PluginPackageJSON,
PluginTranslation,
PluginTranslationPathsJSON,
PluginType,
PluginType_Type,
RegisterServerHookOptions,
ServerHook,
ServerHookName
} from '@peertube/peertube-models'
import { decachePlugin } from '@server/helpers/decache.js'
import { ApplicationModel } from '@server/models/application/application.js'
import { MOAuthTokenUser, MUser } from '@server/types/models/index.js'
import { isLibraryCodeValid, isPackageJSONValid } from '../../helpers/custom-validators/plugins.js'
import { logger } from '../../helpers/logger.js'
import { CONFIG } from '../../initializers/config.js'
import { PLUGIN_GLOBAL_CSS_PATH } from '../../initializers/constants.js'
import { PluginModel } from '../../models/server/plugin.js'
import {
PluginLibrary,
RegisterServerAuthExternalOptions,
RegisterServerAuthPassOptions,
RegisterServerOptions
} from '../../types/plugins/index.js'
import { ClientHtml } from '../client-html.js'
import { RegisterHelpers } from './register-helpers.js'
import { installNpmPlugin, installNpmPluginFromDisk, rebuildNativePlugins, removeNpmPlugin } from './yarn.js'
const require = createRequire(import.meta.url)
export interface RegisteredPlugin {
npmName: string
name: string
version: string
description: string
peertubeEngine: string
type: PluginType_Type
path: string
staticDirs: { [name: string]: string }
clientScripts: { [name: string]: ClientScriptJSON }
css: string[]
// Only if this is a plugin
registerHelpers?: RegisterHelpers
unregister?: Function
}
export interface HookInformationValue {
npmName: string
pluginName: string
handler: Function
priority: number
}
type PluginLocalesTranslations = {
[locale: string]: PluginTranslation
}
export class PluginManager implements ServerHook {
private static instance: PluginManager
private registeredPlugins: { [name: string]: RegisteredPlugin } = {}
private hooks: { [name: string]: HookInformationValue[] } = {}
private translations: PluginLocalesTranslations = {}
private server: Server
private constructor () {
}
init (server: Server) {
this.server = server
}
registerWebSocketRouter () {
this.server.on('upgrade', (request, socket, head) => {
// Check if it's a plugin websocket connection
// No need to destroy the stream when we abort the request
// Other handlers in PeerTube will catch this upgrade event too (socket.io, tracker etc)
const url = request.url
const matched = url.match(`/plugins/([^/]+)/([^/]+/)?ws(/.*)`)
if (!matched) return
const npmName = PluginModel.buildNpmName(matched[1], PluginType.PLUGIN)
const subRoute = matched[3]
const result = this.getRegisteredPluginOrTheme(npmName)
if (!result) return
const routes = result.registerHelpers.getWebSocketRoutes()
const wss = routes.find(r => r.route.startsWith(subRoute))
if (!wss) return
try {
wss.handler(request, socket, head)
} catch (err) {
logger.error('Exception in plugin handler ' + npmName, { err })
}
})
}
// ###################### Getters ######################
isRegistered (npmName: string) {
return !!this.getRegisteredPluginOrTheme(npmName)
}
getRegisteredPluginOrTheme (npmName: string) {
return this.registeredPlugins[npmName]
}
getRegisteredPluginByShortName (name: string) {
const npmName = PluginModel.buildNpmName(name, PluginType.PLUGIN)
const registered = this.getRegisteredPluginOrTheme(npmName)
if (!registered || registered.type !== PluginType.PLUGIN) return undefined
return registered
}
getRegisteredThemeByShortName (name: string) {
const npmName = PluginModel.buildNpmName(name, PluginType.THEME)
const registered = this.getRegisteredPluginOrTheme(npmName)
if (!registered || registered.type !== PluginType.THEME) return undefined
return registered
}
getRegisteredPlugins () {
return this.getRegisteredPluginsOrThemes(PluginType.PLUGIN)
}
getRegisteredThemes () {
return this.getRegisteredPluginsOrThemes(PluginType.THEME)
}
getIdAndPassAuths () {
return this.getRegisteredPlugins()
.map(p => ({
npmName: p.npmName,
name: p.name,
version: p.version,
idAndPassAuths: p.registerHelpers.getIdAndPassAuths()
}))
.filter(v => v.idAndPassAuths.length !== 0)
}
getExternalAuths () {
return this.getRegisteredPlugins()
.map(p => ({
npmName: p.npmName,
name: p.name,
version: p.version,
externalAuths: p.registerHelpers.getExternalAuths()
}))
.filter(v => v.externalAuths.length !== 0)
}
getRegisteredSettings (npmName: string) {
const result = this.getRegisteredPluginOrTheme(npmName)
if (!result || result.type !== PluginType.PLUGIN) return []
return result.registerHelpers.getSettings()
}
getRouter (npmName: string) {
const result = this.getRegisteredPluginOrTheme(npmName)
if (!result || result.type !== PluginType.PLUGIN) return null
return result.registerHelpers.getRouter()
}
getTranslations (locale: string) {
return this.translations[locale] || {}
}
async isTokenValid (token: MOAuthTokenUser, type: 'access' | 'refresh') {
const auth = this.getAuth(token.User.pluginAuth, token.authName)
if (!auth) return true
if (auth.hookTokenValidity) {
try {
const { valid } = await auth.hookTokenValidity({ token, type })
if (valid === false) {
logger.info('Rejecting %s token validity from auth %s of plugin %s', type, token.authName, token.User.pluginAuth)
}
return valid
} catch (err) {
logger.warn('Cannot run check token validity from auth %s of plugin %s.', token.authName, token.User.pluginAuth, { err })
return true
}
}
return true
}
// ###################### External events ######################
async onLogout (npmName: string, authName: string, user: MUser, req: express.Request) {
const auth = this.getAuth(npmName, authName)
if (auth?.onLogout) {
logger.info('Running onLogout function from auth %s of plugin %s', authName, npmName)
try {
// Force await, in case or onLogout returns a promise
const result = await auth.onLogout(user, req)
return typeof result === 'string'
? result
: undefined
} catch (err) {
logger.warn('Cannot run onLogout function from auth %s of plugin %s.', authName, npmName, { err })
}
}
return undefined
}
async onSettingsChanged (name: string, settings: any) {
const registered = this.getRegisteredPluginByShortName(name)
if (!registered) {
logger.error('Cannot find plugin %s to call on settings changed.', name)
}
for (const cb of registered.registerHelpers.getOnSettingsChangedCallbacks()) {
try {
await cb(settings)
} catch (err) {
logger.error('Cannot run on settings changed callback for %s.', registered.npmName, { err })
}
}
}
// ###################### Hooks ######################
async runHook<T> (hookName: ServerHookName, result?: T, params?: any): Promise<T> {
if (!this.hooks[hookName]) return Promise.resolve(result)
const hookType = getHookType(hookName)
for (const hook of this.hooks[hookName]) {
logger.debug('Running hook %s of plugin %s.', hookName, hook.npmName)
result = await internalRunHook({
handler: hook.handler,
hookType,
result,
params,
onError: err => { logger.error('Cannot run hook %s of plugin %s.', hookName, hook.pluginName, { err }) }
})
}
return result
}
// ###################### Registration ######################
async registerPluginsAndThemes () {
await this.resetCSSGlobalFile()
const plugins = await PluginModel.listEnabledPluginsAndThemes()
for (const plugin of plugins) {
try {
await this.registerPluginOrTheme(plugin)
} catch (err) {
// Try to unregister the plugin
try {
await this.unregister(PluginModel.buildNpmName(plugin.name, plugin.type))
} catch {
// we don't care if we cannot unregister it
}
logger.error('Cannot register plugin %s, skipping.', plugin.name, { err })
}
}
this.sortHooksByPriority()
}
// Don't need the plugin type since themes cannot register server code
async unregister (npmName: string) {
logger.info('Unregister plugin %s.', npmName)
const plugin = this.getRegisteredPluginOrTheme(npmName)
if (!plugin) {
throw new Error(`Unknown plugin ${npmName} to unregister`)
}
delete this.registeredPlugins[plugin.npmName]
this.deleteTranslations(plugin.npmName)
if (plugin.type === PluginType.PLUGIN) {
await plugin.unregister()
// Remove hooks of this plugin
for (const key of Object.keys(this.hooks)) {
this.hooks[key] = this.hooks[key].filter(h => h.npmName !== npmName)
}
const store = plugin.registerHelpers
store.reinitVideoConstants(plugin.npmName)
store.reinitTranscodingProfilesAndEncoders(plugin.npmName)
logger.info('Regenerating registered plugin CSS to global file.')
await this.regeneratePluginGlobalCSS()
}
ClientHtml.invalidCache()
}
// ###################### Installation ######################
async install (options: {
toInstall: string
version?: string
fromDisk?: boolean // default false
register?: boolean // default true
}) {
const { toInstall, version, fromDisk = false, register = true } = options
let plugin: PluginModel
let npmName: string
logger.info('Installing plugin %s.', toInstall)
try {
fromDisk
? await installNpmPluginFromDisk(toInstall)
: await installNpmPlugin(toInstall, version)
npmName = fromDisk ? basename(toInstall) : toInstall
const pluginType = PluginModel.getTypeFromNpmName(npmName)
const pluginName = PluginModel.normalizePluginName(npmName)
const packageJSON = await this.getPackageJSON(pluginName, pluginType)
this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, pluginType);
[ plugin ] = await PluginModel.upsert({
name: pluginName,
description: packageJSON.description,
homepage: packageJSON.homepage,
type: pluginType,
version: packageJSON.version,
enabled: true,
uninstalled: false,
peertubeEngine: packageJSON.engine.peertube
}, { returning: true })
logger.info('Successful installation of plugin %s.', toInstall)
if (register) {
await this.registerPluginOrTheme(plugin)
}
} catch (rootErr) {
logger.error('Cannot install plugin %s, removing it...', toInstall, { err: rootErr })
if (npmName) {
try {
await this.uninstall({ npmName })
} catch (err) {
logger.error('Cannot uninstall plugin %s after failed installation.', toInstall, { err })
try {
await removeNpmPlugin(npmName)
} catch (err) {
logger.error('Cannot remove plugin %s after failed installation.', toInstall, { err })
}
}
}
throw rootErr
}
return plugin
}
async update (toUpdate: string, fromDisk = false) {
const npmName = fromDisk ? basename(toUpdate) : toUpdate
logger.info('Updating plugin %s.', npmName)
// Use the latest version from DB, to not upgrade to a version that does not support our PeerTube version
let version: string
if (!fromDisk) {
const plugin = await PluginModel.loadByNpmName(toUpdate)
version = plugin.latestVersion
}
// Unregister old hooks
await this.unregister(npmName)
return this.install({ toInstall: toUpdate, version, fromDisk })
}
async uninstall (options: {
npmName: string
unregister?: boolean // default true
}) {
const { npmName, unregister = true } = options
logger.info('Uninstalling plugin %s.', npmName)
if (unregister) {
try {
await this.unregister(npmName)
} catch (err) {
logger.warn('Cannot unregister plugin %s.', npmName, { err })
}
}
const plugin = await PluginModel.loadByNpmName(npmName)
if (!plugin || plugin.uninstalled === true) {
logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', npmName)
return
}
plugin.enabled = false
plugin.uninstalled = true
await plugin.save()
await removeNpmPlugin(npmName)
logger.info('Plugin %s uninstalled.', npmName)
}
async rebuildNativePluginsIfNeeded () {
if (!await ApplicationModel.nodeABIChanged()) return
return rebuildNativePlugins()
}
// ###################### Private register ######################
private async registerPluginOrTheme (plugin: PluginModel) {
const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
logger.info('Registering plugin or theme %s.', npmName)
const packageJSON = await this.getPackageJSON(plugin.name, plugin.type)
const pluginPath = this.getPluginPath(plugin.name, plugin.type)
this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, plugin.type)
let library: PluginLibrary
let registerHelpers: RegisterHelpers
if (plugin.type === PluginType.PLUGIN) {
const result = await this.registerPlugin(plugin, pluginPath, packageJSON)
library = result.library
registerHelpers = result.registerStore
}
const clientScripts: { [id: string]: ClientScriptJSON } = {}
for (const c of packageJSON.clientScripts) {
clientScripts[c.script] = c
}
this.registeredPlugins[npmName] = {
npmName,
name: plugin.name,
type: plugin.type,
version: plugin.version,
description: plugin.description,
peertubeEngine: plugin.peertubeEngine,
path: pluginPath,
staticDirs: packageJSON.staticDirs,
clientScripts,
css: packageJSON.css,
registerHelpers: registerHelpers || undefined,
unregister: library ? library.unregister : undefined
}
await this.addTranslations(plugin, npmName, packageJSON.translations)
ClientHtml.invalidCache()
}
private async registerPlugin (plugin: PluginModel, pluginPath: string, packageJSON: PluginPackageJSON) {
const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
// Delete cache if needed
const modulePath = join(pluginPath, packageJSON.library)
decachePlugin(require, modulePath)
const library: PluginLibrary = require(modulePath)
if (!isLibraryCodeValid(library)) {
throw new Error('Library code is not valid (miss register or unregister function)')
}
const { registerOptions, registerStore } = this.getRegisterHelpers(npmName, plugin)
await ensureDir(registerOptions.peertubeHelpers.plugin.getDataDirectoryPath())
await library.register(registerOptions)
logger.info('Add plugin %s CSS to global file.', npmName)
await this.addCSSToGlobalFile(pluginPath, packageJSON.css)
return { library, registerStore }
}
// ###################### Translations ######################
private async addTranslations (plugin: PluginModel, npmName: string, translationPaths: PluginTranslationPathsJSON) {
for (const locale of Object.keys(translationPaths)) {
const path = translationPaths[locale]
const json = await readJSON(join(this.getPluginPath(plugin.name, plugin.type), path))
const completeLocale = getCompleteLocale(locale)
if (!this.translations[completeLocale]) this.translations[completeLocale] = {}
this.translations[completeLocale][npmName] = json
logger.info('Added locale %s of plugin %s.', completeLocale, npmName)
}
}
private deleteTranslations (npmName: string) {
for (const locale of Object.keys(this.translations)) {
delete this.translations[locale][npmName]
logger.info('Deleted locale %s of plugin %s.', locale, npmName)
}
}
// ###################### CSS ######################
private resetCSSGlobalFile () {
return outputFile(PLUGIN_GLOBAL_CSS_PATH, '')
}
private async addCSSToGlobalFile (pluginPath: string, cssRelativePaths: string[]) {
for (const cssPath of cssRelativePaths) {
await this.concatFiles(join(pluginPath, cssPath), PLUGIN_GLOBAL_CSS_PATH)
}
}
private concatFiles (input: string, output: string) {
return new Promise<void>((res, rej) => {
const inputStream = createReadStream(input)
const outputStream = createWriteStream(output, { flags: 'a' })
inputStream.pipe(outputStream)
inputStream.on('end', () => res())
inputStream.on('error', err => rej(err))
})
}
private async regeneratePluginGlobalCSS () {
await this.resetCSSGlobalFile()
for (const plugin of this.getRegisteredPlugins()) {
await this.addCSSToGlobalFile(plugin.path, plugin.css)
}
}
// ###################### Utils ######################
private sortHooksByPriority () {
for (const hookName of Object.keys(this.hooks)) {
this.hooks[hookName].sort((a, b) => {
return b.priority - a.priority
})
}
}
private getPackageJSON (pluginName: string, pluginType: PluginType_Type) {
const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json')
return readJSON(pluginPath) as Promise<PluginPackageJSON>
}
private getPluginPath (pluginName: string, pluginType: PluginType_Type) {
const npmName = PluginModel.buildNpmName(pluginName, pluginType)
return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', npmName)
}
private getAuth (npmName: string, authName: string) {
const plugin = this.getRegisteredPluginOrTheme(npmName)
if (!plugin || plugin.type !== PluginType.PLUGIN) return null
let auths: (RegisterServerAuthPassOptions | RegisterServerAuthExternalOptions)[] = plugin.registerHelpers.getIdAndPassAuths()
auths = auths.concat(plugin.registerHelpers.getExternalAuths())
return auths.find(a => a.authName === authName)
}
// ###################### Private getters ######################
private getRegisteredPluginsOrThemes (type: PluginType_Type) {
const plugins: RegisteredPlugin[] = []
for (const npmName of Object.keys(this.registeredPlugins)) {
const plugin = this.registeredPlugins[npmName]
if (plugin.type !== type) continue
plugins.push(plugin)
}
return plugins
}
// ###################### Generate register helpers ######################
private getRegisterHelpers (
npmName: string,
plugin: PluginModel
): { registerStore: RegisterHelpers, registerOptions: RegisterServerOptions } {
const onHookAdded = (options: RegisterServerHookOptions) => {
if (!this.hooks[options.target]) this.hooks[options.target] = []
this.hooks[options.target].push({
npmName,
pluginName: plugin.name,
handler: options.handler,
priority: options.priority || 0
})
}
const registerHelpers = new RegisterHelpers(npmName, plugin, this.server, onHookAdded.bind(this))
return {
registerStore: registerHelpers,
registerOptions: registerHelpers.buildRegisterHelpers()
}
}
private sanitizeAndCheckPackageJSONOrThrow (packageJSON: PluginPackageJSON, pluginType: PluginType_Type) {
if (!packageJSON.staticDirs) packageJSON.staticDirs = {}
if (!packageJSON.css) packageJSON.css = []
if (!packageJSON.clientScripts) packageJSON.clientScripts = []
if (!packageJSON.translations) packageJSON.translations = {}
const { result: packageJSONValid, badFields } = isPackageJSONValid(packageJSON, pluginType)
if (!packageJSONValid) {
const formattedFields = badFields.map(f => `"${f}"`)
.join(', ')
throw new Error(`PackageJSON is invalid (invalid fields: ${formattedFields}).`)
}
}
static get Instance () {
return this.instance || (this.instance = new this())
}
}

View file

@ -0,0 +1,340 @@
import express from 'express'
import { Server } from 'http'
import {
EncoderOptionsBuilder,
PluginSettingsManager,
PluginStorageManager,
RegisterServerHookOptions,
RegisterServerSettingOptions,
serverHookObject,
SettingsChangeCallback,
VideoPlaylistPrivacyType,
VideoPrivacyType
} from '@peertube/peertube-models'
import { logger } from '@server/helpers/logger.js'
import { onExternalUserAuthenticated } from '@server/lib/auth/external-auth.js'
import { VideoConstantManagerFactory } from '@server/lib/plugins/video-constant-manager-factory.js'
import { PluginModel } from '@server/models/server/plugin.js'
import {
RegisterServerAuthExternalOptions,
RegisterServerAuthExternalResult,
RegisterServerAuthPassOptions,
RegisterServerExternalAuthenticatedResult,
RegisterServerOptions,
RegisterServerWebSocketRouteOptions
} from '@server/types/plugins/index.js'
import { VideoTranscodingProfilesManager } from '../transcoding/default-transcoding-profiles.js'
import { buildPluginHelpers } from './plugin-helpers-builder.js'
export class RegisterHelpers {
private readonly transcodingProfiles: {
[ npmName: string ]: {
type: 'vod' | 'live'
encoder: string
profile: string
}[]
} = {}
private readonly transcodingEncoders: {
[ npmName: string ]: {
type: 'vod' | 'live'
streamType: 'audio' | 'video'
encoder: string
priority: number
}[]
} = {}
private readonly settings: RegisterServerSettingOptions[] = []
private idAndPassAuths: RegisterServerAuthPassOptions[] = []
private externalAuths: RegisterServerAuthExternalOptions[] = []
private readonly onSettingsChangeCallbacks: SettingsChangeCallback[] = []
private readonly webSocketRoutes: RegisterServerWebSocketRouteOptions[] = []
private readonly router: express.Router
private readonly videoConstantManagerFactory: VideoConstantManagerFactory
constructor (
private readonly npmName: string,
private readonly plugin: PluginModel,
private readonly server: Server,
private readonly onHookAdded: (options: RegisterServerHookOptions) => void
) {
this.router = express.Router()
this.videoConstantManagerFactory = new VideoConstantManagerFactory(this.npmName)
}
buildRegisterHelpers (): RegisterServerOptions {
const registerHook = this.buildRegisterHook()
const registerSetting = this.buildRegisterSetting()
const getRouter = this.buildGetRouter()
const registerWebSocketRoute = this.buildRegisterWebSocketRoute()
const settingsManager = this.buildSettingsManager()
const storageManager = this.buildStorageManager()
const videoLanguageManager = this.videoConstantManagerFactory.createVideoConstantManager<string>('language')
const videoLicenceManager = this.videoConstantManagerFactory.createVideoConstantManager<number>('licence')
const videoCategoryManager = this.videoConstantManagerFactory.createVideoConstantManager<number>('category')
const videoPrivacyManager = this.videoConstantManagerFactory.createVideoConstantManager<VideoPrivacyType>('privacy')
const playlistPrivacyManager = this.videoConstantManagerFactory.createVideoConstantManager<VideoPlaylistPrivacyType>('playlistPrivacy')
const transcodingManager = this.buildTranscodingManager()
const registerIdAndPassAuth = this.buildRegisterIdAndPassAuth()
const registerExternalAuth = this.buildRegisterExternalAuth()
const unregisterIdAndPassAuth = this.buildUnregisterIdAndPassAuth()
const unregisterExternalAuth = this.buildUnregisterExternalAuth()
const peertubeHelpers = buildPluginHelpers(this.server, this.plugin, this.npmName)
return {
registerHook,
registerSetting,
getRouter,
registerWebSocketRoute,
settingsManager,
storageManager,
videoLanguageManager: {
...videoLanguageManager,
/** @deprecated use `addConstant` instead **/
addLanguage: videoLanguageManager.addConstant,
/** @deprecated use `deleteConstant` instead **/
deleteLanguage: videoLanguageManager.deleteConstant
},
videoCategoryManager: {
...videoCategoryManager,
/** @deprecated use `addConstant` instead **/
addCategory: videoCategoryManager.addConstant,
/** @deprecated use `deleteConstant` instead **/
deleteCategory: videoCategoryManager.deleteConstant
},
videoLicenceManager: {
...videoLicenceManager,
/** @deprecated use `addConstant` instead **/
addLicence: videoLicenceManager.addConstant,
/** @deprecated use `deleteConstant` instead **/
deleteLicence: videoLicenceManager.deleteConstant
},
videoPrivacyManager: {
...videoPrivacyManager,
/** @deprecated use `deleteConstant` instead **/
deletePrivacy: videoPrivacyManager.deleteConstant
},
playlistPrivacyManager: {
...playlistPrivacyManager,
/** @deprecated use `deleteConstant` instead **/
deletePlaylistPrivacy: playlistPrivacyManager.deleteConstant
},
transcodingManager,
registerIdAndPassAuth,
registerExternalAuth,
unregisterIdAndPassAuth,
unregisterExternalAuth,
peertubeHelpers
}
}
reinitVideoConstants (npmName: string) {
this.videoConstantManagerFactory.resetVideoConstants(npmName)
}
reinitTranscodingProfilesAndEncoders (npmName: string) {
const profiles = this.transcodingProfiles[npmName]
if (Array.isArray(profiles)) {
for (const profile of profiles) {
VideoTranscodingProfilesManager.Instance.removeProfile(profile)
}
}
const encoders = this.transcodingEncoders[npmName]
if (Array.isArray(encoders)) {
for (const o of encoders) {
VideoTranscodingProfilesManager.Instance.removeEncoderPriority(o.type, o.streamType, o.encoder, o.priority)
}
}
}
getSettings () {
return this.settings
}
getRouter () {
return this.router
}
getIdAndPassAuths () {
return this.idAndPassAuths
}
getExternalAuths () {
return this.externalAuths
}
getOnSettingsChangedCallbacks () {
return this.onSettingsChangeCallbacks
}
getWebSocketRoutes () {
return this.webSocketRoutes
}
private buildGetRouter () {
return () => this.router
}
private buildRegisterWebSocketRoute () {
return (options: RegisterServerWebSocketRouteOptions) => {
this.webSocketRoutes.push(options)
}
}
private buildRegisterSetting () {
return (options: RegisterServerSettingOptions) => {
this.settings.push(options)
}
}
private buildRegisterHook () {
return (options: RegisterServerHookOptions) => {
if (serverHookObject[options.target] !== true) {
logger.warn('Unknown hook %s of plugin %s. Skipping.', options.target, this.npmName)
return
}
return this.onHookAdded(options)
}
}
private buildRegisterIdAndPassAuth () {
return (options: RegisterServerAuthPassOptions) => {
if (!options.authName || typeof options.getWeight !== 'function' || typeof options.login !== 'function') {
logger.error('Cannot register auth plugin %s: authName, getWeight or login are not valid.', this.npmName, { options })
return
}
this.idAndPassAuths.push(options)
}
}
private buildRegisterExternalAuth () {
const self = this
return (options: RegisterServerAuthExternalOptions) => {
if (!options.authName || typeof options.authDisplayName !== 'function' || typeof options.onAuthRequest !== 'function') {
logger.error('Cannot register auth plugin %s: authName, authDisplayName or onAuthRequest are not valid.', this.npmName, { options })
return
}
this.externalAuths.push(options)
return {
userAuthenticated (result: RegisterServerExternalAuthenticatedResult): void {
onExternalUserAuthenticated({
npmName: self.npmName,
authName: options.authName,
authResult: result
}).catch(err => {
logger.error('Cannot execute onExternalUserAuthenticated.', { npmName: self.npmName, authName: options.authName, err })
})
}
} as RegisterServerAuthExternalResult
}
}
private buildUnregisterExternalAuth () {
return (authName: string) => {
this.externalAuths = this.externalAuths.filter(a => a.authName !== authName)
}
}
private buildUnregisterIdAndPassAuth () {
return (authName: string) => {
this.idAndPassAuths = this.idAndPassAuths.filter(a => a.authName !== authName)
}
}
private buildSettingsManager (): PluginSettingsManager {
return {
getSetting: (name: string) => PluginModel.getSetting(this.plugin.name, this.plugin.type, name, this.settings),
getSettings: (names: string[]) => PluginModel.getSettings(this.plugin.name, this.plugin.type, names, this.settings),
setSetting: (name: string, value: string) => PluginModel.setSetting(this.plugin.name, this.plugin.type, name, value),
onSettingsChange: (cb: SettingsChangeCallback) => this.onSettingsChangeCallbacks.push(cb)
}
}
private buildStorageManager (): PluginStorageManager {
return {
getData: (key: string) => PluginModel.getData(this.plugin.name, this.plugin.type, key),
storeData: (key: string, data: any) => PluginModel.storeData(this.plugin.name, this.plugin.type, key, data)
}
}
private buildTranscodingManager () {
const self = this
function addProfile (type: 'live' | 'vod', encoder: string, profile: string, builder: EncoderOptionsBuilder) {
if (profile === 'default') {
logger.error('A plugin cannot add a default live transcoding profile')
return false
}
VideoTranscodingProfilesManager.Instance.addProfile({
type,
encoder,
profile,
builder
})
if (!self.transcodingProfiles[self.npmName]) self.transcodingProfiles[self.npmName] = []
self.transcodingProfiles[self.npmName].push({ type, encoder, profile })
return true
}
function addEncoderPriority (type: 'live' | 'vod', streamType: 'audio' | 'video', encoder: string, priority: number) {
VideoTranscodingProfilesManager.Instance.addEncoderPriority(type, streamType, encoder, priority)
if (!self.transcodingEncoders[self.npmName]) self.transcodingEncoders[self.npmName] = []
self.transcodingEncoders[self.npmName].push({ type, streamType, encoder, priority })
}
return {
addLiveProfile (encoder: string, profile: string, builder: EncoderOptionsBuilder) {
return addProfile('live', encoder, profile, builder)
},
addVODProfile (encoder: string, profile: string, builder: EncoderOptionsBuilder) {
return addProfile('vod', encoder, profile, builder)
},
addLiveEncoderPriority (streamType: 'audio' | 'video', encoder: string, priority: number) {
return addEncoderPriority('live', streamType, encoder, priority)
},
addVODEncoderPriority (streamType: 'audio' | 'video', encoder: string, priority: number) {
return addEncoderPriority('vod', streamType, encoder, priority)
},
removeAllProfilesAndEncoderPriorities () {
return self.reinitTranscodingProfilesAndEncoders(self.npmName)
}
}
}
}

View file

@ -0,0 +1,24 @@
import { DEFAULT_THEME_NAME, DEFAULT_USER_THEME_NAME } from '../../initializers/constants.js'
import { PluginManager } from './plugin-manager.js'
import { CONFIG } from '../../initializers/config.js'
function getThemeOrDefault (name: string, defaultTheme: string) {
if (isThemeRegistered(name)) return name
// Fallback to admin default theme
if (name !== CONFIG.THEME.DEFAULT) return getThemeOrDefault(CONFIG.THEME.DEFAULT, DEFAULT_THEME_NAME)
return defaultTheme
}
function isThemeRegistered (name: string) {
if (name === DEFAULT_THEME_NAME || name === DEFAULT_USER_THEME_NAME) return true
return !!PluginManager.Instance.getRegisteredThemes()
.find(r => r.name === name)
}
export {
getThemeOrDefault,
isThemeRegistered
}

View file

@ -0,0 +1,139 @@
import { ConstantManager } from '@peertube/peertube-models'
import { logger } from '@server/helpers/logger.js'
import {
VIDEO_CATEGORIES,
VIDEO_LANGUAGES,
VIDEO_LICENCES,
VIDEO_PLAYLIST_PRIVACIES,
VIDEO_PRIVACIES
} from '@server/initializers/constants.js'
type AlterableVideoConstant = 'language' | 'licence' | 'category' | 'privacy' | 'playlistPrivacy'
type VideoConstant = Record<number | string, string>
type UpdatedVideoConstant = {
[name in AlterableVideoConstant]: {
[ npmName: string]: {
added: VideoConstant[]
deleted: VideoConstant[]
}
}
}
const constantsHash: { [key in AlterableVideoConstant]: VideoConstant } = {
language: VIDEO_LANGUAGES,
licence: VIDEO_LICENCES,
category: VIDEO_CATEGORIES,
privacy: VIDEO_PRIVACIES,
playlistPrivacy: VIDEO_PLAYLIST_PRIVACIES
}
export class VideoConstantManagerFactory {
private readonly updatedVideoConstants: UpdatedVideoConstant = {
playlistPrivacy: { },
privacy: { },
language: { },
licence: { },
category: { }
}
constructor (
private readonly npmName: string
) {}
public resetVideoConstants (npmName: string) {
const types: AlterableVideoConstant[] = [ 'language', 'licence', 'category', 'privacy', 'playlistPrivacy' ]
for (const type of types) {
this.resetConstants({ npmName, type })
}
}
private resetConstants (parameters: { npmName: string, type: AlterableVideoConstant }) {
const { npmName, type } = parameters
const updatedConstants = this.updatedVideoConstants[type][npmName]
if (!updatedConstants) return
for (const added of updatedConstants.added) {
delete constantsHash[type][added.key]
}
for (const deleted of updatedConstants.deleted) {
constantsHash[type][deleted.key] = deleted.label
}
delete this.updatedVideoConstants[type][npmName]
}
public createVideoConstantManager<K extends number | string>(type: AlterableVideoConstant): ConstantManager<K> {
const { npmName } = this
return {
addConstant: (key: K, label: string) => this.addConstant({ npmName, type, key, label }),
deleteConstant: (key: K) => this.deleteConstant({ npmName, type, key }),
getConstantValue: (key: K) => constantsHash[type][key],
getConstants: () => constantsHash[type] as Record<K, string>,
resetConstants: () => this.resetConstants({ npmName, type })
}
}
private addConstant<T extends string | number> (parameters: {
npmName: string
type: AlterableVideoConstant
key: T
label: string
}) {
const { npmName, type, key, label } = parameters
const obj = constantsHash[type]
if (obj[key]) {
logger.warn('Cannot add %s %s by plugin %s: key already exists.', type, npmName, key)
return false
}
if (!this.updatedVideoConstants[type][npmName]) {
this.updatedVideoConstants[type][npmName] = {
added: [],
deleted: []
}
}
this.updatedVideoConstants[type][npmName].added.push({ key, label } as VideoConstant)
obj[key] = label
return true
}
private deleteConstant<T extends string | number> (parameters: {
npmName: string
type: AlterableVideoConstant
key: T
}) {
const { npmName, type, key } = parameters
const obj = constantsHash[type]
if (!obj[key]) {
logger.warn('Cannot delete %s by plugin %s: key %s does not exist.', type, npmName, key)
return false
}
if (!this.updatedVideoConstants[type][npmName]) {
this.updatedVideoConstants[type][npmName] = {
added: [],
deleted: []
}
}
const updatedConstants = this.updatedVideoConstants[type][npmName]
const alreadyAdded = updatedConstants.added.find(a => a.key === key)
if (alreadyAdded) {
updatedConstants.added.filter(a => a.key !== key)
} else if (obj[key]) {
updatedConstants.deleted.push({ key, label: obj[key] } as VideoConstant)
}
delete obj[key]
return true
}
}

View file

@ -0,0 +1,73 @@
import { outputJSON, pathExists } from 'fs-extra/esm'
import { join } from 'path'
import { execShell } from '../../helpers/core-utils.js'
import { isNpmPluginNameValid, isPluginStableOrUnstableVersionValid } from '../../helpers/custom-validators/plugins.js'
import { logger } from '../../helpers/logger.js'
import { CONFIG } from '../../initializers/config.js'
import { getLatestPluginVersion } from './plugin-index.js'
async function installNpmPlugin (npmName: string, versionArg?: string) {
// Security check
checkNpmPluginNameOrThrow(npmName)
if (versionArg) checkPluginVersionOrThrow(versionArg)
const version = versionArg || await getLatestPluginVersion(npmName)
let toInstall = npmName
if (version) toInstall += `@${version}`
const { stdout } = await execYarn('add ' + toInstall)
logger.debug('Added a yarn package.', { yarnStdout: stdout })
}
async function installNpmPluginFromDisk (path: string) {
await execYarn('add file:' + path)
}
async function removeNpmPlugin (name: string) {
checkNpmPluginNameOrThrow(name)
await execYarn('remove ' + name)
}
async function rebuildNativePlugins () {
await execYarn('install --pure-lockfile')
}
// ############################################################################
export {
installNpmPlugin,
installNpmPluginFromDisk,
rebuildNativePlugins,
removeNpmPlugin
}
// ############################################################################
async function execYarn (command: string) {
try {
const pluginDirectory = CONFIG.STORAGE.PLUGINS_DIR
const pluginPackageJSON = join(pluginDirectory, 'package.json')
// Create empty package.json file if needed
if (!await pathExists(pluginPackageJSON)) {
await outputJSON(pluginPackageJSON, {})
}
return execShell(`yarn ${command}`, { cwd: pluginDirectory })
} catch (result) {
logger.error('Cannot exec yarn.', { command, err: result.err, stderr: result.stderr })
throw result.err
}
}
function checkNpmPluginNameOrThrow (name: string) {
if (!isNpmPluginNameValid(name)) throw new Error('Invalid NPM plugin name to install')
}
function checkPluginVersionOrThrow (name: string) {
if (!isPluginStableOrUnstableVersionValid(name)) throw new Error('Invalid NPM plugin version to install')
}