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 // Check if it's a plugin websocket connection
83 // No need to destroy the stream when we abort the request
84 // Other handlers in PeerTube will catch this upgrade event too (socket.io, tracker etc)
86 const url = request.url
88 const matched = url.match(`/plugins/([^/]+)/([^/]+/)?ws(/.*)`)
91 const npmName = PluginModel.buildNpmName(matched[1], PluginType.PLUGIN)
92 const subRoute = matched[3]
94 const result = this.getRegisteredPluginOrTheme(npmName)
97 const routes = result.registerHelpers.getWebSocketRoutes()
99 const wss = routes.find(r => r.route.startsWith(subRoute))
103 wss.handler(request, socket, head)
105 logger.error('Exception in plugin handler ' + npmName, { err })
110 // ###################### Getters ######################
112 isRegistered (npmName: string) {
113 return !!this.getRegisteredPluginOrTheme(npmName)
116 getRegisteredPluginOrTheme (npmName: string) {
117 return this.registeredPlugins[npmName]
120 getRegisteredPluginByShortName (name: string) {
121 const npmName = PluginModel.buildNpmName(name, PluginType.PLUGIN)
122 const registered = this.getRegisteredPluginOrTheme(npmName)
124 if (!registered || registered.type !== PluginType.PLUGIN) return undefined
129 getRegisteredThemeByShortName (name: string) {
130 const npmName = PluginModel.buildNpmName(name, PluginType.THEME)
131 const registered = this.getRegisteredPluginOrTheme(npmName)
133 if (!registered || registered.type !== PluginType.THEME) return undefined
138 getRegisteredPlugins () {
139 return this.getRegisteredPluginsOrThemes(PluginType.PLUGIN)
142 getRegisteredThemes () {
143 return this.getRegisteredPluginsOrThemes(PluginType.THEME)
146 getIdAndPassAuths () {
147 return this.getRegisteredPlugins()
152 idAndPassAuths: p.registerHelpers.getIdAndPassAuths()
154 .filter(v => v.idAndPassAuths.length !== 0)
157 getExternalAuths () {
158 return this.getRegisteredPlugins()
163 externalAuths: p.registerHelpers.getExternalAuths()
165 .filter(v => v.externalAuths.length !== 0)
168 getRegisteredSettings (npmName: string) {
169 const result = this.getRegisteredPluginOrTheme(npmName)
170 if (!result || result.type !== PluginType.PLUGIN) return []
172 return result.registerHelpers.getSettings()
175 getRouter (npmName: string) {
176 const result = this.getRegisteredPluginOrTheme(npmName)
177 if (!result || result.type !== PluginType.PLUGIN) return null
179 return result.registerHelpers.getRouter()
182 getTranslations (locale: string) {
183 return this.translations[locale] || {}
186 async isTokenValid (token: MOAuthTokenUser, type: 'access' | 'refresh') {
187 const auth = this.getAuth(token.User.pluginAuth, token.authName)
188 if (!auth) return true
190 if (auth.hookTokenValidity) {
192 const { valid } = await auth.hookTokenValidity({ token, type })
194 if (valid === false) {
195 logger.info('Rejecting %s token validity from auth %s of plugin %s', type, token.authName, token.User.pluginAuth)
200 logger.warn('Cannot run check token validity from auth %s of plugin %s.', token.authName, token.User.pluginAuth, { err })
208 // ###################### External events ######################
210 async onLogout (npmName: string, authName: string, user: MUser, req: express.Request) {
211 const auth = this.getAuth(npmName, authName)
213 if (auth?.onLogout) {
214 logger.info('Running onLogout function from auth %s of plugin %s', authName, npmName)
217 // Force await, in case or onLogout returns a promise
218 const result = await auth.onLogout(user, req)
220 return typeof result === 'string'
224 logger.warn('Cannot run onLogout function from auth %s of plugin %s.', authName, npmName, { err })
231 async onSettingsChanged (name: string, settings: any) {
232 const registered = this.getRegisteredPluginByShortName(name)
234 logger.error('Cannot find plugin %s to call on settings changed.', name)
237 for (const cb of registered.registerHelpers.getOnSettingsChangedCallbacks()) {
241 logger.error('Cannot run on settings changed callback for %s.', registered.npmName, { err })
246 // ###################### Hooks ######################
248 async runHook<T> (hookName: ServerHookName, result?: T, params?: any): Promise<T> {
249 if (!this.hooks[hookName]) return Promise.resolve(result)
251 const hookType = getHookType(hookName)
253 for (const hook of this.hooks[hookName]) {
254 logger.debug('Running hook %s of plugin %s.', hookName, hook.npmName)
256 result = await internalRunHook({
257 handler: hook.handler,
261 onError: err => { logger.error('Cannot run hook %s of plugin %s.', hookName, hook.pluginName, { err }) }
268 // ###################### Registration ######################
270 async registerPluginsAndThemes () {
271 await this.resetCSSGlobalFile()
273 const plugins = await PluginModel.listEnabledPluginsAndThemes()
275 for (const plugin of plugins) {
277 await this.registerPluginOrTheme(plugin)
279 // Try to unregister the plugin
281 await this.unregister(PluginModel.buildNpmName(plugin.name, plugin.type))
283 // we don't care if we cannot unregister it
286 logger.error('Cannot register plugin %s, skipping.', plugin.name, { err })
290 this.sortHooksByPriority()
293 // Don't need the plugin type since themes cannot register server code
294 async unregister (npmName: string) {
295 logger.info('Unregister plugin %s.', npmName)
297 const plugin = this.getRegisteredPluginOrTheme(npmName)
300 throw new Error(`Unknown plugin ${npmName} to unregister`)
303 delete this.registeredPlugins[plugin.npmName]
305 this.deleteTranslations(plugin.npmName)
307 if (plugin.type === PluginType.PLUGIN) {
308 await plugin.unregister()
310 // Remove hooks of this plugin
311 for (const key of Object.keys(this.hooks)) {
312 this.hooks[key] = this.hooks[key].filter(h => h.npmName !== npmName)
315 const store = plugin.registerHelpers
316 store.reinitVideoConstants(plugin.npmName)
317 store.reinitTranscodingProfilesAndEncoders(plugin.npmName)
319 logger.info('Regenerating registered plugin CSS to global file.')
320 await this.regeneratePluginGlobalCSS()
323 ClientHtml.invalidCache()
326 // ###################### Installation ######################
328 async install (options: {
331 fromDisk?: boolean // default false
332 register?: boolean // default true
334 const { toInstall, version, fromDisk = false, register = true } = options
336 let plugin: PluginModel
339 logger.info('Installing plugin %s.', toInstall)
343 ? await installNpmPluginFromDisk(toInstall)
344 : await installNpmPlugin(toInstall, version)
346 npmName = fromDisk ? basename(toInstall) : toInstall
347 const pluginType = PluginModel.getTypeFromNpmName(npmName)
348 const pluginName = PluginModel.normalizePluginName(npmName)
350 const packageJSON = await this.getPackageJSON(pluginName, pluginType)
352 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, pluginType);
354 [ plugin ] = await PluginModel.upsert({
356 description: packageJSON.description,
357 homepage: packageJSON.homepage,
359 version: packageJSON.version,
362 peertubeEngine: packageJSON.engine.peertube
363 }, { returning: true })
365 logger.info('Successful installation of plugin %s.', toInstall)
368 await this.registerPluginOrTheme(plugin)
371 logger.error('Cannot install plugin %s, removing it...', toInstall, { err: rootErr })
374 await this.uninstall({ npmName })
376 logger.error('Cannot uninstall plugin %s after failed installation.', toInstall, { err })
379 await removeNpmPlugin(npmName)
381 logger.error('Cannot remove plugin %s after failed installation.', toInstall, { err })
391 async update (toUpdate: string, fromDisk = false) {
392 const npmName = fromDisk ? basename(toUpdate) : toUpdate
394 logger.info('Updating plugin %s.', npmName)
396 // Use the latest version from DB, to not upgrade to a version that does not support our PeerTube version
399 const plugin = await PluginModel.loadByNpmName(toUpdate)
400 version = plugin.latestVersion
403 // Unregister old hooks
404 await this.unregister(npmName)
406 return this.install({ toInstall: toUpdate, version, fromDisk })
409 async uninstall (options: {
411 unregister?: boolean // default true
413 const { npmName, unregister = true } = options
415 logger.info('Uninstalling plugin %s.', npmName)
419 await this.unregister(npmName)
421 logger.warn('Cannot unregister plugin %s.', npmName, { err })
425 const plugin = await PluginModel.loadByNpmName(npmName)
426 if (!plugin || plugin.uninstalled === true) {
427 logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', npmName)
431 plugin.enabled = false
432 plugin.uninstalled = true
436 await removeNpmPlugin(npmName)
438 logger.info('Plugin %s uninstalled.', npmName)
441 async rebuildNativePluginsIfNeeded () {
442 if (!await ApplicationModel.nodeABIChanged()) return
444 return rebuildNativePlugins()
447 // ###################### Private register ######################
449 private async registerPluginOrTheme (plugin: PluginModel) {
450 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
452 logger.info('Registering plugin or theme %s.', npmName)
454 const packageJSON = await this.getPackageJSON(plugin.name, plugin.type)
455 const pluginPath = this.getPluginPath(plugin.name, plugin.type)
457 this.sanitizeAndCheckPackageJSONOrThrow(packageJSON, plugin.type)
459 let library: PluginLibrary
460 let registerHelpers: RegisterHelpers
461 if (plugin.type === PluginType.PLUGIN) {
462 const result = await this.registerPlugin(plugin, pluginPath, packageJSON)
463 library = result.library
464 registerHelpers = result.registerStore
467 const clientScripts: { [id: string]: ClientScriptJSON } = {}
468 for (const c of packageJSON.clientScripts) {
469 clientScripts[c.script] = c
472 this.registeredPlugins[npmName] = {
476 version: plugin.version,
477 description: plugin.description,
478 peertubeEngine: plugin.peertubeEngine,
480 staticDirs: packageJSON.staticDirs,
482 css: packageJSON.css,
483 registerHelpers: registerHelpers || undefined,
484 unregister: library ? library.unregister : undefined
487 await this.addTranslations(plugin, npmName, packageJSON.translations)
489 ClientHtml.invalidCache()
492 private async registerPlugin (plugin: PluginModel, pluginPath: string, packageJSON: PluginPackageJSON) {
493 const npmName = PluginModel.buildNpmName(plugin.name, plugin.type)
495 // Delete cache if needed
496 const modulePath = join(pluginPath, packageJSON.library)
497 decachePlugin(pluginPath, modulePath)
498 const library: PluginLibrary = require(modulePath)
500 if (!isLibraryCodeValid(library)) {
501 throw new Error('Library code is not valid (miss register or unregister function)')
504 const { registerOptions, registerStore } = this.getRegisterHelpers(npmName, plugin)
506 await ensureDir(registerOptions.peertubeHelpers.plugin.getDataDirectoryPath())
508 await library.register(registerOptions)
510 logger.info('Add plugin %s CSS to global file.', npmName)
512 await this.addCSSToGlobalFile(pluginPath, packageJSON.css)
514 return { library, registerStore }
517 // ###################### Translations ######################
519 private async addTranslations (plugin: PluginModel, npmName: string, translationPaths: PluginTranslationPathsJSON) {
520 for (const locale of Object.keys(translationPaths)) {
521 const path = translationPaths[locale]
522 const json = await readJSON(join(this.getPluginPath(plugin.name, plugin.type), path))
524 const completeLocale = getCompleteLocale(locale)
526 if (!this.translations[completeLocale]) this.translations[completeLocale] = {}
527 this.translations[completeLocale][npmName] = json
529 logger.info('Added locale %s of plugin %s.', completeLocale, npmName)
533 private deleteTranslations (npmName: string) {
534 for (const locale of Object.keys(this.translations)) {
535 delete this.translations[locale][npmName]
537 logger.info('Deleted locale %s of plugin %s.', locale, npmName)
541 // ###################### CSS ######################
543 private resetCSSGlobalFile () {
544 return outputFile(PLUGIN_GLOBAL_CSS_PATH, '')
547 private async addCSSToGlobalFile (pluginPath: string, cssRelativePaths: string[]) {
548 for (const cssPath of cssRelativePaths) {
549 await this.concatFiles(join(pluginPath, cssPath), PLUGIN_GLOBAL_CSS_PATH)
553 private concatFiles (input: string, output: string) {
554 return new Promise<void>((res, rej) => {
555 const inputStream = createReadStream(input)
556 const outputStream = createWriteStream(output, { flags: 'a' })
558 inputStream.pipe(outputStream)
560 inputStream.on('end', () => res())
561 inputStream.on('error', err => rej(err))
565 private async regeneratePluginGlobalCSS () {
566 await this.resetCSSGlobalFile()
568 for (const plugin of this.getRegisteredPlugins()) {
569 await this.addCSSToGlobalFile(plugin.path, plugin.css)
573 // ###################### Utils ######################
575 private sortHooksByPriority () {
576 for (const hookName of Object.keys(this.hooks)) {
577 this.hooks[hookName].sort((a, b) => {
578 return b.priority - a.priority
583 private getPackageJSON (pluginName: string, pluginType: PluginType) {
584 const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json')
586 return readJSON(pluginPath) as Promise<PluginPackageJSON>
589 private getPluginPath (pluginName: string, pluginType: PluginType) {
590 const npmName = PluginModel.buildNpmName(pluginName, pluginType)
592 return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', npmName)
595 private getAuth (npmName: string, authName: string) {
596 const plugin = this.getRegisteredPluginOrTheme(npmName)
597 if (!plugin || plugin.type !== PluginType.PLUGIN) return null
599 let auths: (RegisterServerAuthPassOptions | RegisterServerAuthExternalOptions)[] = plugin.registerHelpers.getIdAndPassAuths()
600 auths = auths.concat(plugin.registerHelpers.getExternalAuths())
602 return auths.find(a => a.authName === authName)
605 // ###################### Private getters ######################
607 private getRegisteredPluginsOrThemes (type: PluginType) {
608 const plugins: RegisteredPlugin[] = []
610 for (const npmName of Object.keys(this.registeredPlugins)) {
611 const plugin = this.registeredPlugins[npmName]
612 if (plugin.type !== type) continue
620 // ###################### Generate register helpers ######################
622 private getRegisterHelpers (
625 ): { registerStore: RegisterHelpers, registerOptions: RegisterServerOptions } {
626 const onHookAdded = (options: RegisterServerHookOptions) => {
627 if (!this.hooks[options.target]) this.hooks[options.target] = []
629 this.hooks[options.target].push({
631 pluginName: plugin.name,
632 handler: options.handler,
633 priority: options.priority || 0
637 const registerHelpers = new RegisterHelpers(npmName, plugin, this.server, onHookAdded.bind(this))
640 registerStore: registerHelpers,
641 registerOptions: registerHelpers.buildRegisterHelpers()
645 private sanitizeAndCheckPackageJSONOrThrow (packageJSON: PluginPackageJSON, pluginType: PluginType) {
646 if (!packageJSON.staticDirs) packageJSON.staticDirs = {}
647 if (!packageJSON.css) packageJSON.css = []
648 if (!packageJSON.clientScripts) packageJSON.clientScripts = []
649 if (!packageJSON.translations) packageJSON.translations = {}
651 const { result: packageJSONValid, badFields } = isPackageJSONValid(packageJSON, pluginType)
652 if (!packageJSONValid) {
653 const formattedFields = badFields.map(f => `"${f}"`)
656 throw new Error(`PackageJSON is invalid (invalid fields: ${formattedFields}).`)
660 static get Instance () {
661 return this.instance || (this.instance = new this())