1 import express from 'express'
2 import { createReadStream, createWriteStream } from 'fs'
3 import { ensureDir, outputFile, readJSON } from 'fs-extra'
4 import { Server } from 'http'
5 import { basename, join } from 'path'
6 import { decachePlugin } from '@server/helpers/decache'
7 import { ApplicationModel } from '@server/models/application/application'
8 import { MOAuthTokenUser, MUser } from '@server/types/models'
9 import { getCompleteLocale } from '@shared/core-utils'
14 PluginTranslationPathsJSON,
15 RegisterServerHookOptions
16 } from '@shared/models'
17 import { getHookType, internalRunHook } from '../../../shared/core-utils/plugins/hooks'
18 import { PluginType } from '../../../shared/models/plugins/plugin.type'
19 import { ServerHook, ServerHookName } from '../../../shared/models/plugins/server/server-hook.model'
20 import { isLibraryCodeValid, isPackageJSONValid } from '../../helpers/custom-validators/plugins'
21 import { logger } from '../../helpers/logger'
22 import { CONFIG } from '../../initializers/config'
23 import { PLUGIN_GLOBAL_CSS_PATH } from '../../initializers/constants'
24 import { PluginModel } from '../../models/server/plugin'
25 import { PluginLibrary, RegisterServerAuthExternalOptions, RegisterServerAuthPassOptions, RegisterServerOptions } from '../../types/plugins'
26 import { ClientHtml } from '../client-html'
27 import { RegisterHelpers } from './register-helpers'
28 import { installNpmPlugin, installNpmPluginFromDisk, rebuildNativePlugins, removeNpmPlugin } from './yarn'
30 export interface RegisteredPlugin {
35 peertubeEngine: string
41 staticDirs: { [name: string]: string }
42 clientScripts: { [name: string]: ClientScriptJSON }
46 // Only if this is a plugin
47 registerHelpers?: RegisterHelpers
51 export interface HookInformationValue {
58 type PluginLocalesTranslations = {
59 [locale: string]: PluginTranslation
62 export class PluginManager implements ServerHook {
64 private static instance: PluginManager
66 private registeredPlugins: { [name: string]: RegisteredPlugin } = {}
68 private hooks: { [name: string]: HookInformationValue[] } = {}
69 private translations: PluginLocalesTranslations = {}
71 private server: Server
73 private constructor () {
76 init (server: Server) {
80 registerWebSocketRouter () {
81 this.server.on('upgrade', (request, socket, head) => {
82 const url = request.url
84 const matched = url.match(`/plugins/([^/]+)/([^/]+/)?ws(/.*)`)
87 const npmName = PluginModel.buildNpmName(matched[1], PluginType.PLUGIN)
88 const subRoute = matched[3]
90 const result = this.getRegisteredPluginOrTheme(npmName)
93 const routes = result.registerHelpers.getWebSocketRoutes()
95 const wss = routes.find(r => r.route.startsWith(subRoute))
98 wss.handler(request, socket, head)
102 // ###################### Getters ######################
104 isRegistered (npmName: string) {
105 return !!this.getRegisteredPluginOrTheme(npmName)
108 getRegisteredPluginOrTheme (npmName: string) {
109 return this.registeredPlugins[npmName]
112 getRegisteredPluginByShortName (name: string) {
113 const npmName = PluginModel.buildNpmName(name, PluginType.PLUGIN)
114 const registered = this.getRegisteredPluginOrTheme(npmName)
116 if (!registered || registered.type !== PluginType.PLUGIN) return undefined
121 getRegisteredThemeByShortName (name: string) {
122 const npmName = PluginModel.buildNpmName(name, PluginType.THEME)
123 const registered = this.getRegisteredPluginOrTheme(npmName)
125 if (!registered || registered.type !== PluginType.THEME) return undefined
130 getRegisteredPlugins () {
131 return this.getRegisteredPluginsOrThemes(PluginType.PLUGIN)
134 getRegisteredThemes () {
135 return this.getRegisteredPluginsOrThemes(PluginType.THEME)
138 getIdAndPassAuths () {
139 return this.getRegisteredPlugins()
144 idAndPassAuths: p.registerHelpers.getIdAndPassAuths()
146 .filter(v => v.idAndPassAuths.length !== 0)
149 getExternalAuths () {
150 return this.getRegisteredPlugins()
155 externalAuths: p.registerHelpers.getExternalAuths()
157 .filter(v => v.externalAuths.length !== 0)
160 getRegisteredSettings (npmName: string) {
161 const result = this.getRegisteredPluginOrTheme(npmName)
162 if (!result || result.type !== PluginType.PLUGIN) return []
164 return result.registerHelpers.getSettings()
167 getRouter (npmName: string) {
168 const result = this.getRegisteredPluginOrTheme(npmName)
169 if (!result || result.type !== PluginType.PLUGIN) return null
171 return result.registerHelpers.getRouter()
174 getTranslations (locale: string) {
175 return this.translations[locale] || {}
178 async isTokenValid (token: MOAuthTokenUser, type: 'access' | 'refresh') {
179 const auth = this.getAuth(token.User.pluginAuth, token.authName)
180 if (!auth) return true
182 if (auth.hookTokenValidity) {
184 const { valid } = await auth.hookTokenValidity({ token, type })
186 if (valid === false) {
187 logger.info('Rejecting %s token validity from auth %s of plugin %s', type, token.authName, token.User.pluginAuth)
192 logger.warn('Cannot run check token validity from auth %s of plugin %s.', token.authName, token.User.pluginAuth, { err })
200 // ###################### External events ######################
202 async onLogout (npmName: string, authName: string, user: MUser, req: express.Request) {
203 const auth = this.getAuth(npmName, authName)
205 if (auth?.onLogout) {
206 logger.info('Running onLogout function from auth %s of plugin %s', authName, npmName)
209 // Force await, in case or onLogout returns a promise
210 const result = await auth.onLogout(user, req)
212 return typeof result === 'string'
216 logger.warn('Cannot run onLogout function from auth %s of plugin %s.', authName, npmName, { err })
223 async onSettingsChanged (name: string, settings: any) {
224 const registered = this.getRegisteredPluginByShortName(name)
226 logger.error('Cannot find plugin %s to call on settings changed.', name)
229 for (const cb of registered.registerHelpers.getOnSettingsChangedCallbacks()) {
233 logger.error('Cannot run on settings changed callback for %s.', registered.npmName, { err })
238 // ###################### Hooks ######################
240 async runHook<T> (hookName: ServerHookName, result?: T, params?: any): Promise<T> {
241 if (!this.hooks[hookName]) return Promise.resolve(result)
243 const hookType = getHookType(hookName)
245 for (const hook of this.hooks[hookName]) {
246 logger.debug('Running hook %s of plugin %s.', hookName, hook.npmName)
248 result = await internalRunHook({
249 handler: hook.handler,
253 onError: err => { logger.error('Cannot run hook %s of plugin %s.', hookName, hook.pluginName, { err }) }
260 // ###################### Registration ######################
262 async registerPluginsAndThemes () {
263 await this.resetCSSGlobalFile()
265 const plugins = await PluginModel.listEnabledPluginsAndThemes()
267 for (const plugin of plugins) {
269 await this.registerPluginOrTheme(plugin)
271 // Try to unregister the plugin
273 await this.unregister(PluginModel.buildNpmName(plugin.name, plugin.type))
275 // we don't care if we cannot unregister it
278 logger.error('Cannot register plugin %s, skipping.', plugin.name, { err })
282 this.sortHooksByPriority()
285 // Don't need the plugin type since themes cannot register server code
286 async unregister (npmName: string) {
287 logger.info('Unregister plugin %s.', npmName)
289 const plugin = this.getRegisteredPluginOrTheme(npmName)
292 throw new Error(`Unknown plugin ${npmName} to unregister`)
295 delete this.registeredPlugins[plugin.npmName]
297 this.deleteTranslations(plugin.npmName)
299 if (plugin.type === PluginType.PLUGIN) {
300 await plugin.unregister()
302 // Remove hooks of this plugin
303 for (const key of Object.keys(this.hooks)) {
304 this.hooks[key] = this.hooks[key].filter(h => h.npmName !== npmName)
307 const store = plugin.registerHelpers
308 store.reinitVideoConstants(plugin.npmName)
309 store.reinitTranscodingProfilesAndEncoders(plugin.npmName)
311 logger.info('Regenerating registered plugin CSS to global file.')
312 await this.regeneratePluginGlobalCSS()
315 ClientHtml.invalidCache()
318 // ###################### Installation ######################
320 async install (toInstall: string, version?: string, fromDisk = false) {
321 let plugin: PluginModel
324 logger.info('Installing plugin %s.', toInstall)
328 ? await installNpmPluginFromDisk(toInstall)
329 : await installNpmPlugin(toInstall, version)
331 npmName = fromDisk ? basename(toInstall) : toInstall
332 const pluginType = PluginModel.getTypeFromNpmName(npmName)
333 const pluginName = PluginModel.normalizePluginName(npmName)
335 const packageJSON = await this.getPackageJSON(pluginName, pluginType)
337 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, pluginType);
339 [ plugin ] = await PluginModel.upsert({
341 description: packageJSON.description,
342 homepage: packageJSON.homepage,
344 version: packageJSON.version,
347 peertubeEngine: packageJSON.engine.peertube
348 }, { returning: true })
350 logger.info('Successful installation of plugin %s.', toInstall)
352 await this.registerPluginOrTheme(plugin)
354 logger.error('Cannot install plugin %s, removing it...', toInstall, { err: rootErr })
357 await this.uninstall(npmName)
359 logger.error('Cannot uninstall plugin %s after failed installation.', toInstall, { err })
362 await removeNpmPlugin(npmName)
364 logger.error('Cannot remove plugin %s after failed installation.', toInstall, { err })
374 async update (toUpdate: string, fromDisk = false) {
375 const npmName = fromDisk ? basename(toUpdate) : toUpdate
377 logger.info('Updating plugin %s.', npmName)
379 // Use the latest version from DB, to not upgrade to a version that does not support our PeerTube version
382 const plugin = await PluginModel.loadByNpmName(toUpdate)
383 version = plugin.latestVersion
386 // Unregister old hooks
387 await this.unregister(npmName)
389 return this.install(toUpdate, version, fromDisk)
392 async uninstall (npmName: string) {
393 logger.info('Uninstalling plugin %s.', npmName)
396 await this.unregister(npmName)
398 logger.warn('Cannot unregister plugin %s.', npmName, { err })
401 const plugin = await PluginModel.loadByNpmName(npmName)
402 if (!plugin || plugin.uninstalled === true) {
403 logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', npmName)
407 plugin.enabled = false
408 plugin.uninstalled = true
412 await removeNpmPlugin(npmName)
414 logger.info('Plugin %s uninstalled.', npmName)
417 async rebuildNativePluginsIfNeeded () {
418 if (!await ApplicationModel.nodeABIChanged()) return
420 return rebuildNativePlugins()
423 // ###################### Private register ######################
425 private async registerPluginOrTheme (plugin: PluginModel) {
426 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
428 logger.info('Registering plugin or theme %s.', npmName)
430 const packageJSON = await this.getPackageJSON(plugin.name, plugin.type)
431 const pluginPath = this.getPluginPath(plugin.name, plugin.type)
433 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, plugin.type)
435 let library: PluginLibrary
436 let registerHelpers: RegisterHelpers
437 if (plugin.type === PluginType.PLUGIN) {
438 const result = await this.registerPlugin(plugin, pluginPath, packageJSON)
439 library = result.library
440 registerHelpers = result.registerStore
443 const clientScripts: { [id: string]: ClientScriptJSON } = {}
444 for (const c of packageJSON.clientScripts) {
445 clientScripts[c.script] = c
448 this.registeredPlugins[npmName] = {
452 version: plugin.version,
453 description: plugin.description,
454 peertubeEngine: plugin.peertubeEngine,
456 staticDirs: packageJSON.staticDirs,
458 css: packageJSON.css,
459 registerHelpers: registerHelpers || undefined,
460 unregister: library ? library.unregister : undefined
463 await this.addTranslations(plugin, npmName, packageJSON.translations)
465 ClientHtml.invalidCache()
468 private async registerPlugin (plugin: PluginModel, pluginPath: string, packageJSON: PluginPackageJSON) {
469 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
471 // Delete cache if needed
472 const modulePath = join(pluginPath, packageJSON.library)
473 decachePlugin(pluginPath, modulePath)
474 const library: PluginLibrary = require(modulePath)
476 if (!isLibraryCodeValid(library)) {
477 throw new Error('Library code is not valid (miss register or unregister function)')
480 const { registerOptions, registerStore } = this.getRegisterHelpers(npmName, plugin)
482 await ensureDir(registerOptions.peertubeHelpers.plugin.getDataDirectoryPath())
484 await library.register(registerOptions)
486 logger.info('Add plugin %s CSS to global file.', npmName)
488 await this.addCSSToGlobalFile(pluginPath, packageJSON.css)
490 return { library, registerStore }
493 // ###################### Translations ######################
495 private async addTranslations (plugin: PluginModel, npmName: string, translationPaths: PluginTranslationPathsJSON) {
496 for (const locale of Object.keys(translationPaths)) {
497 const path = translationPaths[locale]
498 const json = await readJSON(join(this.getPluginPath(plugin.name, plugin.type), path))
500 const completeLocale = getCompleteLocale(locale)
502 if (!this.translations[completeLocale]) this.translations[completeLocale] = {}
503 this.translations[completeLocale][npmName] = json
505 logger.info('Added locale %s of plugin %s.', completeLocale, npmName)
509 private deleteTranslations (npmName: string) {
510 for (const locale of Object.keys(this.translations)) {
511 delete this.translations[locale][npmName]
513 logger.info('Deleted locale %s of plugin %s.', locale, npmName)
517 // ###################### CSS ######################
519 private resetCSSGlobalFile () {
520 return outputFile(PLUGIN_GLOBAL_CSS_PATH, '')
523 private async addCSSToGlobalFile (pluginPath: string, cssRelativePaths: string[]) {
524 for (const cssPath of cssRelativePaths) {
525 await this.concatFiles(join(pluginPath, cssPath), PLUGIN_GLOBAL_CSS_PATH)
529 private concatFiles (input: string, output: string) {
530 return new Promise<void>((res, rej) => {
531 const inputStream = createReadStream(input)
532 const outputStream = createWriteStream(output, { flags: 'a' })
534 inputStream.pipe(outputStream)
536 inputStream.on('end', () => res())
537 inputStream.on('error', err => rej(err))
541 private async regeneratePluginGlobalCSS () {
542 await this.resetCSSGlobalFile()
544 for (const plugin of this.getRegisteredPlugins()) {
545 await this.addCSSToGlobalFile(plugin.path, plugin.css)
549 // ###################### Utils ######################
551 private sortHooksByPriority () {
552 for (const hookName of Object.keys(this.hooks)) {
553 this.hooks[hookName].sort((a, b) => {
554 return b.priority - a.priority
559 private getPackageJSON (pluginName: string, pluginType: PluginType) {
560 const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json')
562 return readJSON(pluginPath) as Promise<PluginPackageJSON>
565 private getPluginPath (pluginName: string, pluginType: PluginType) {
566 const npmName = PluginModel.buildNpmName(pluginName, pluginType)
568 return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', npmName)
571 private getAuth (npmName: string, authName: string) {
572 const plugin = this.getRegisteredPluginOrTheme(npmName)
573 if (!plugin || plugin.type !== PluginType.PLUGIN) return null
575 let auths: (RegisterServerAuthPassOptions | RegisterServerAuthExternalOptions)[] = plugin.registerHelpers.getIdAndPassAuths()
576 auths = auths.concat(plugin.registerHelpers.getExternalAuths())
578 return auths.find(a => a.authName === authName)
581 // ###################### Private getters ######################
583 private getRegisteredPluginsOrThemes (type: PluginType) {
584 const plugins: RegisteredPlugin[] = []
586 for (const npmName of Object.keys(this.registeredPlugins)) {
587 const plugin = this.registeredPlugins[npmName]
588 if (plugin.type !== type) continue
596 // ###################### Generate register helpers ######################
598 private getRegisterHelpers (
601 ): { registerStore: RegisterHelpers, registerOptions: RegisterServerOptions } {
602 const onHookAdded = (options: RegisterServerHookOptions) => {
603 if (!this.hooks[options.target]) this.hooks[options.target] = []
605 this.hooks[options.target].push({
607 pluginName: plugin.name,
608 handler: options.handler,
609 priority: options.priority || 0
613 const registerHelpers = new RegisterHelpers(npmName, plugin, this.server, onHookAdded.bind(this))
616 registerStore: registerHelpers,
617 registerOptions: registerHelpers.buildRegisterHelpers()
621 private sanitizeAndCheckPackageJSONOrThrow (packageJSON: PluginPackageJSON, pluginType: PluginType) {
622 if (!packageJSON.staticDirs) packageJSON.staticDirs = {}
623 if (!packageJSON.css) packageJSON.css = []
624 if (!packageJSON.clientScripts) packageJSON.clientScripts = []
625 if (!packageJSON.translations) packageJSON.translations = {}
627 const { result: packageJSONValid, badFields } = isPackageJSONValid(packageJSON, pluginType)
628 if (!packageJSONValid) {
629 const formattedFields = badFields.map(f => `"${f}"`)
632 throw new Error(`PackageJSON is invalid (invalid fields: ${formattedFields}).`)
636 static get Instance () {
637 return this.instance || (this.instance = new this())