1 import decache from 'decache'
2 import * as express from 'express'
3 import { createReadStream, createWriteStream } from 'fs'
4 import { ensureDir, outputFile, readJSON } from 'fs-extra'
5 import { basename, join } from 'path'
6 import { MOAuthTokenUser, MUser } from '@server/types/models'
7 import { getCompleteLocale } from '@shared/core-utils'
8 import { ClientScript, PluginPackageJson, PluginTranslation, PluginTranslationPaths, RegisterServerHookOptions } from '@shared/models'
9 import { getHookType, internalRunHook } from '../../../shared/core-utils/plugins/hooks'
10 import { PluginType } from '../../../shared/models/plugins/plugin.type'
11 import { ServerHook, ServerHookName } from '../../../shared/models/plugins/server/server-hook.model'
12 import { isLibraryCodeValid, isPackageJSONValid } from '../../helpers/custom-validators/plugins'
13 import { logger } from '../../helpers/logger'
14 import { CONFIG } from '../../initializers/config'
15 import { PLUGIN_GLOBAL_CSS_PATH } from '../../initializers/constants'
16 import { PluginModel } from '../../models/server/plugin'
17 import { PluginLibrary, RegisterServerAuthExternalOptions, RegisterServerAuthPassOptions, RegisterServerOptions } from '../../types/plugins'
18 import { ClientHtml } from '../client-html'
19 import { RegisterHelpers } from './register-helpers'
20 import { installNpmPlugin, installNpmPluginFromDisk, removeNpmPlugin } from './yarn'
22 export interface RegisteredPlugin {
27 peertubeEngine: string
33 staticDirs: { [name: string]: string }
34 clientScripts: { [name: string]: ClientScript }
38 // Only if this is a plugin
39 registerHelpers?: RegisterHelpers
43 export interface HookInformationValue {
50 type PluginLocalesTranslations = {
51 [locale: string]: PluginTranslation
54 export class PluginManager implements ServerHook {
56 private static instance: PluginManager
58 private registeredPlugins: { [name: string]: RegisteredPlugin } = {}
60 private hooks: { [name: string]: HookInformationValue[] } = {}
61 private translations: PluginLocalesTranslations = {}
63 private constructor () {
66 // ###################### Getters ######################
68 isRegistered (npmName: string) {
69 return !!this.getRegisteredPluginOrTheme(npmName)
72 getRegisteredPluginOrTheme (npmName: string) {
73 return this.registeredPlugins[npmName]
76 getRegisteredPluginByShortName (name: string) {
77 const npmName = PluginModel.buildNpmName(name, PluginType.PLUGIN)
78 const registered = this.getRegisteredPluginOrTheme(npmName)
80 if (!registered || registered.type !== PluginType.PLUGIN) return undefined
85 getRegisteredThemeByShortName (name: string) {
86 const npmName = PluginModel.buildNpmName(name, PluginType.THEME)
87 const registered = this.getRegisteredPluginOrTheme(npmName)
89 if (!registered || registered.type !== PluginType.THEME) return undefined
94 getRegisteredPlugins () {
95 return this.getRegisteredPluginsOrThemes(PluginType.PLUGIN)
98 getRegisteredThemes () {
99 return this.getRegisteredPluginsOrThemes(PluginType.THEME)
102 getIdAndPassAuths () {
103 return this.getRegisteredPlugins()
108 idAndPassAuths: p.registerHelpers.getIdAndPassAuths()
110 .filter(v => v.idAndPassAuths.length !== 0)
113 getExternalAuths () {
114 return this.getRegisteredPlugins()
119 externalAuths: p.registerHelpers.getExternalAuths()
121 .filter(v => v.externalAuths.length !== 0)
124 getRegisteredSettings (npmName: string) {
125 const result = this.getRegisteredPluginOrTheme(npmName)
126 if (!result || result.type !== PluginType.PLUGIN) return []
128 return result.registerHelpers.getSettings()
131 getRouter (npmName: string) {
132 const result = this.getRegisteredPluginOrTheme(npmName)
133 if (!result || result.type !== PluginType.PLUGIN) return null
135 return result.registerHelpers.getRouter()
138 getTranslations (locale: string) {
139 return this.translations[locale] || {}
142 async isTokenValid (token: MOAuthTokenUser, type: 'access' | 'refresh') {
143 const auth = this.getAuth(token.User.pluginAuth, token.authName)
144 if (!auth) return true
146 if (auth.hookTokenValidity) {
148 const { valid } = await auth.hookTokenValidity({ token, type })
150 if (valid === false) {
151 logger.info('Rejecting %s token validity from auth %s of plugin %s', type, token.authName, token.User.pluginAuth)
156 logger.warn('Cannot run check token validity from auth %s of plugin %s.', token.authName, token.User.pluginAuth, { err })
164 // ###################### External events ######################
166 async onLogout (npmName: string, authName: string, user: MUser, req: express.Request) {
167 const auth = this.getAuth(npmName, authName)
169 if (auth?.onLogout) {
170 logger.info('Running onLogout function from auth %s of plugin %s', authName, npmName)
173 // Force await, in case or onLogout returns a promise
174 const result = await auth.onLogout(user, req)
176 return typeof result === 'string'
180 logger.warn('Cannot run onLogout function from auth %s of plugin %s.', authName, npmName, { err })
187 async onSettingsChanged (name: string, settings: any) {
188 const registered = this.getRegisteredPluginByShortName(name)
190 logger.error('Cannot find plugin %s to call on settings changed.', name)
193 for (const cb of registered.registerHelpers.getOnSettingsChangedCallbacks()) {
197 logger.error('Cannot run on settings changed callback for %s.', registered.npmName, { err })
202 // ###################### Hooks ######################
204 async runHook<T> (hookName: ServerHookName, result?: T, params?: any): Promise<T> {
205 if (!this.hooks[hookName]) return Promise.resolve(result)
207 const hookType = getHookType(hookName)
209 for (const hook of this.hooks[hookName]) {
210 logger.debug('Running hook %s of plugin %s.', hookName, hook.npmName)
212 result = await internalRunHook(hook.handler, hookType, result, params, err => {
213 logger.error('Cannot run hook %s of plugin %s.', hookName, hook.pluginName, { err })
220 // ###################### Registration ######################
222 async registerPluginsAndThemes () {
223 await this.resetCSSGlobalFile()
225 const plugins = await PluginModel.listEnabledPluginsAndThemes()
227 for (const plugin of plugins) {
229 await this.registerPluginOrTheme(plugin)
231 // Try to unregister the plugin
233 await this.unregister(PluginModel.buildNpmName(plugin.name, plugin.type))
235 // we don't care if we cannot unregister it
238 logger.error('Cannot register plugin %s, skipping.', plugin.name, { err })
242 this.sortHooksByPriority()
245 // Don't need the plugin type since themes cannot register server code
246 async unregister (npmName: string) {
247 logger.info('Unregister plugin %s.', npmName)
249 const plugin = this.getRegisteredPluginOrTheme(npmName)
252 throw new Error(`Unknown plugin ${npmName} to unregister`)
255 delete this.registeredPlugins[plugin.npmName]
257 this.deleteTranslations(plugin.npmName)
259 if (plugin.type === PluginType.PLUGIN) {
260 await plugin.unregister()
262 // Remove hooks of this plugin
263 for (const key of Object.keys(this.hooks)) {
264 this.hooks[key] = this.hooks[key].filter(h => h.npmName !== npmName)
267 const store = plugin.registerHelpers
268 store.reinitVideoConstants(plugin.npmName)
269 store.reinitTranscodingProfilesAndEncoders(plugin.npmName)
271 logger.info('Regenerating registered plugin CSS to global file.')
272 await this.regeneratePluginGlobalCSS()
276 // ###################### Installation ######################
278 async install (toInstall: string, version?: string, fromDisk = false) {
279 let plugin: PluginModel
282 logger.info('Installing plugin %s.', toInstall)
286 ? await installNpmPluginFromDisk(toInstall)
287 : await installNpmPlugin(toInstall, version)
289 npmName = fromDisk ? basename(toInstall) : toInstall
290 const pluginType = PluginModel.getTypeFromNpmName(npmName)
291 const pluginName = PluginModel.normalizePluginName(npmName)
293 const packageJSON = await this.getPackageJSON(pluginName, pluginType)
295 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, pluginType);
297 [ plugin ] = await PluginModel.upsert({
299 description: packageJSON.description,
300 homepage: packageJSON.homepage,
302 version: packageJSON.version,
305 peertubeEngine: packageJSON.engine.peertube
306 }, { returning: true })
308 logger.error('Cannot install plugin %s, removing it...', toInstall, { err })
311 await removeNpmPlugin(npmName)
313 logger.error('Cannot remove plugin %s after failed installation.', toInstall, { err })
319 logger.info('Successful installation of plugin %s.', toInstall)
321 await this.registerPluginOrTheme(plugin)
326 async update (toUpdate: string, fromDisk = false) {
327 const npmName = fromDisk ? basename(toUpdate) : toUpdate
329 logger.info('Updating plugin %s.', npmName)
331 // Use the latest version from DB, to not upgrade to a version that does not support our PeerTube version
334 const plugin = await PluginModel.loadByNpmName(toUpdate)
335 version = plugin.latestVersion
338 // Unregister old hooks
339 await this.unregister(npmName)
341 return this.install(toUpdate, version, fromDisk)
344 async uninstall (npmName: string) {
345 logger.info('Uninstalling plugin %s.', npmName)
348 await this.unregister(npmName)
350 logger.warn('Cannot unregister plugin %s.', npmName, { err })
353 const plugin = await PluginModel.loadByNpmName(npmName)
354 if (!plugin || plugin.uninstalled === true) {
355 logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', npmName)
359 plugin.enabled = false
360 plugin.uninstalled = true
364 await removeNpmPlugin(npmName)
366 logger.info('Plugin %s uninstalled.', npmName)
369 // ###################### Private register ######################
371 private async registerPluginOrTheme (plugin: PluginModel) {
372 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
374 logger.info('Registering plugin or theme %s.', npmName)
376 const packageJSON = await this.getPackageJSON(plugin.name, plugin.type)
377 const pluginPath = this.getPluginPath(plugin.name, plugin.type)
379 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, plugin.type)
381 let library: PluginLibrary
382 let registerHelpers: RegisterHelpers
383 if (plugin.type === PluginType.PLUGIN) {
384 const result = await this.registerPlugin(plugin, pluginPath, packageJSON)
385 library = result.library
386 registerHelpers = result.registerStore
389 const clientScripts: { [id: string]: ClientScript } = {}
390 for (const c of packageJSON.clientScripts) {
391 clientScripts[c.script] = c
394 this.registeredPlugins[npmName] = {
398 version: plugin.version,
399 description: plugin.description,
400 peertubeEngine: plugin.peertubeEngine,
402 staticDirs: packageJSON.staticDirs,
404 css: packageJSON.css,
405 registerHelpers: registerHelpers || undefined,
406 unregister: library ? library.unregister : undefined
409 await this.addTranslations(plugin, npmName, packageJSON.translations)
412 private async registerPlugin (plugin: PluginModel, pluginPath: string, packageJSON: PluginPackageJson) {
413 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
415 // Delete cache if needed
416 const modulePath = join(pluginPath, packageJSON.library)
418 const library: PluginLibrary = require(modulePath)
420 if (!isLibraryCodeValid(library)) {
421 throw new Error('Library code is not valid (miss register or unregister function)')
424 const { registerOptions, registerStore } = this.getRegisterHelpers(npmName, plugin)
426 await ensureDir(registerOptions.peertubeHelpers.plugin.getDataDirectoryPath())
428 library.register(registerOptions)
429 .catch(err => logger.error('Cannot register plugin %s.', npmName, { err }))
431 logger.info('Add plugin %s CSS to global file.', npmName)
433 await this.addCSSToGlobalFile(pluginPath, packageJSON.css)
435 return { library, registerStore }
438 // ###################### Translations ######################
440 private async addTranslations (plugin: PluginModel, npmName: string, translationPaths: PluginTranslationPaths) {
441 for (const locale of Object.keys(translationPaths)) {
442 const path = translationPaths[locale]
443 const json = await readJSON(join(this.getPluginPath(plugin.name, plugin.type), path))
445 const completeLocale = getCompleteLocale(locale)
447 if (!this.translations[completeLocale]) this.translations[completeLocale] = {}
448 this.translations[completeLocale][npmName] = json
450 logger.info('Added locale %s of plugin %s.', completeLocale, npmName)
454 private deleteTranslations (npmName: string) {
455 for (const locale of Object.keys(this.translations)) {
456 delete this.translations[locale][npmName]
458 logger.info('Deleted locale %s of plugin %s.', locale, npmName)
462 // ###################### CSS ######################
464 private resetCSSGlobalFile () {
465 ClientHtml.invalidCache()
467 return outputFile(PLUGIN_GLOBAL_CSS_PATH, '')
470 private async addCSSToGlobalFile (pluginPath: string, cssRelativePaths: string[]) {
471 for (const cssPath of cssRelativePaths) {
472 await this.concatFiles(join(pluginPath, cssPath), PLUGIN_GLOBAL_CSS_PATH)
475 ClientHtml.invalidCache()
478 private concatFiles (input: string, output: string) {
479 return new Promise<void>((res, rej) => {
480 const inputStream = createReadStream(input)
481 const outputStream = createWriteStream(output, { flags: 'a' })
483 inputStream.pipe(outputStream)
485 inputStream.on('end', () => res())
486 inputStream.on('error', err => rej(err))
490 private async regeneratePluginGlobalCSS () {
491 await this.resetCSSGlobalFile()
493 for (const plugin of this.getRegisteredPlugins()) {
494 await this.addCSSToGlobalFile(plugin.path, plugin.css)
498 // ###################### Utils ######################
500 private sortHooksByPriority () {
501 for (const hookName of Object.keys(this.hooks)) {
502 this.hooks[hookName].sort((a, b) => {
503 return b.priority - a.priority
508 private getPackageJSON (pluginName: string, pluginType: PluginType) {
509 const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json')
511 return readJSON(pluginPath) as Promise<PluginPackageJson>
514 private getPluginPath (pluginName: string, pluginType: PluginType) {
515 const npmName = PluginModel.buildNpmName(pluginName, pluginType)
517 return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', npmName)
520 private getAuth (npmName: string, authName: string) {
521 const plugin = this.getRegisteredPluginOrTheme(npmName)
522 if (!plugin || plugin.type !== PluginType.PLUGIN) return null
524 let auths: (RegisterServerAuthPassOptions | RegisterServerAuthExternalOptions)[] = plugin.registerHelpers.getIdAndPassAuths()
525 auths = auths.concat(plugin.registerHelpers.getExternalAuths())
527 return auths.find(a => a.authName === authName)
530 // ###################### Private getters ######################
532 private getRegisteredPluginsOrThemes (type: PluginType) {
533 const plugins: RegisteredPlugin[] = []
535 for (const npmName of Object.keys(this.registeredPlugins)) {
536 const plugin = this.registeredPlugins[npmName]
537 if (plugin.type !== type) continue
545 // ###################### Generate register helpers ######################
547 private getRegisterHelpers (
550 ): { registerStore: RegisterHelpers, registerOptions: RegisterServerOptions } {
551 const onHookAdded = (options: RegisterServerHookOptions) => {
552 if (!this.hooks[options.target]) this.hooks[options.target] = []
554 this.hooks[options.target].push({
556 pluginName: plugin.name,
557 handler: options.handler,
558 priority: options.priority || 0
562 const registerHelpers = new RegisterHelpers(npmName, plugin, onHookAdded.bind(this))
565 registerStore: registerHelpers,
566 registerOptions: registerHelpers.buildRegisterHelpers()
570 private sanitizeAndCheckPackageJSONOrThrow (packageJSON: PluginPackageJson, pluginType: PluginType) {
571 if (!packageJSON.staticDirs) packageJSON.staticDirs = {}
572 if (!packageJSON.css) packageJSON.css = []
573 if (!packageJSON.clientScripts) packageJSON.clientScripts = []
574 if (!packageJSON.translations) packageJSON.translations = {}
576 const { result: packageJSONValid, badFields } = isPackageJSONValid(packageJSON, pluginType)
577 if (!packageJSONValid) {
578 const formattedFields = badFields.map(f => `"${f}"`)
581 throw new Error(`PackageJSON is invalid (invalid fields: ${formattedFields}).`)
585 static get Instance () {
586 return this.instance || (this.instance = new this())