]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/plugins/plugin-manager.ts
WIP plugins: add theme support
[github/Chocobozzz/PeerTube.git] / server / lib / plugins / plugin-manager.ts
1 import { PluginModel } from '../../models/server/plugin'
2 import { logger } from '../../helpers/logger'
3 import { RegisterHookOptions } from '../../../shared/models/plugins/register.model'
4 import { basename, join } from 'path'
5 import { CONFIG } from '../../initializers/config'
6 import { isLibraryCodeValid, isPackageJSONValid } from '../../helpers/custom-validators/plugins'
7 import { ClientScript, PluginPackageJson } from '../../../shared/models/plugins/plugin-package-json.model'
8 import { PluginLibrary } from '../../../shared/models/plugins/plugin-library.model'
9 import { createReadStream, createWriteStream } from 'fs'
10 import { PLUGIN_GLOBAL_CSS_PATH } from '../../initializers/constants'
11 import { PluginType } from '../../../shared/models/plugins/plugin.type'
12 import { installNpmPlugin, installNpmPluginFromDisk, removeNpmPlugin } from './yarn'
13 import { outputFile } from 'fs-extra'
14 import { ServerConfigPlugin } from '../../../shared/models/server'
15
16 export interface RegisteredPlugin {
17 name: string
18 version: string
19 description: string
20 peertubeEngine: string
21
22 type: PluginType
23
24 path: string
25
26 staticDirs: { [name: string]: string }
27 clientScripts: { [name: string]: ClientScript }
28
29 css: string[]
30
31 // Only if this is a plugin
32 unregister?: Function
33 }
34
35 export interface HookInformationValue {
36 pluginName: string
37 handler: Function
38 priority: number
39 }
40
41 export class PluginManager {
42
43 private static instance: PluginManager
44
45 private registeredPlugins: { [ name: string ]: RegisteredPlugin } = {}
46 private hooks: { [ name: string ]: HookInformationValue[] } = {}
47
48 private constructor () {
49 }
50
51 async registerPluginsAndThemes () {
52 await this.resetCSSGlobalFile()
53
54 const plugins = await PluginModel.listEnabledPluginsAndThemes()
55
56 for (const plugin of plugins) {
57 try {
58 await this.registerPluginOrTheme(plugin)
59 } catch (err) {
60 logger.error('Cannot register plugin %s, skipping.', plugin.name, { err })
61 }
62 }
63
64 this.sortHooksByPriority()
65 }
66
67 getRegisteredPluginOrTheme (name: string) {
68 return this.registeredPlugins[name]
69 }
70
71 getRegisteredPlugin (name: string) {
72 const registered = this.getRegisteredPluginOrTheme(name)
73
74 if (!registered || registered.type !== PluginType.PLUGIN) return undefined
75
76 return registered
77 }
78
79 getRegisteredTheme (name: string) {
80 const registered = this.getRegisteredPluginOrTheme(name)
81
82 if (!registered || registered.type !== PluginType.THEME) return undefined
83
84 return registered
85 }
86
87 getRegisteredPlugins () {
88 return this.getRegisteredPluginsOrThemes(PluginType.PLUGIN)
89 }
90
91 getRegisteredThemes () {
92 return this.getRegisteredPluginsOrThemes(PluginType.THEME)
93 }
94
95 async runHook (hookName: string, param?: any) {
96 let result = param
97
98 const wait = hookName.startsWith('static:')
99
100 for (const hook of this.hooks[hookName]) {
101 try {
102 if (wait) result = await hook.handler(param)
103 else result = hook.handler()
104 } catch (err) {
105 logger.error('Cannot run hook %s of plugin %s.', hookName, hook.pluginName, { err })
106 }
107 }
108
109 return result
110 }
111
112 async unregister (name: string) {
113 const plugin = this.getRegisteredPlugin(name)
114
115 if (!plugin) {
116 throw new Error(`Unknown plugin ${name} to unregister`)
117 }
118
119 if (plugin.type === PluginType.THEME) {
120 throw new Error(`Cannot unregister ${name}: this is a theme`)
121 }
122
123 await plugin.unregister()
124
125 // Remove hooks of this plugin
126 for (const key of Object.keys(this.hooks)) {
127 this.hooks[key] = this.hooks[key].filter(h => h.pluginName !== name)
128 }
129
130 delete this.registeredPlugins[plugin.name]
131
132 logger.info('Regenerating registered plugin CSS to global file.')
133 await this.regeneratePluginGlobalCSS()
134 }
135
136 async install (toInstall: string, version: string, fromDisk = false) {
137 let plugin: PluginModel
138 let name: string
139
140 logger.info('Installing plugin %s.', toInstall)
141
142 try {
143 fromDisk
144 ? await installNpmPluginFromDisk(toInstall)
145 : await installNpmPlugin(toInstall, version)
146
147 name = fromDisk ? basename(toInstall) : toInstall
148 const pluginType = name.startsWith('peertube-theme-') ? PluginType.THEME : PluginType.PLUGIN
149 const pluginName = this.normalizePluginName(name)
150
151 const packageJSON = this.getPackageJSON(pluginName, pluginType)
152 if (!isPackageJSONValid(packageJSON, pluginType)) {
153 throw new Error('PackageJSON is invalid.')
154 }
155
156 [ plugin ] = await PluginModel.upsert({
157 name: pluginName,
158 description: packageJSON.description,
159 type: pluginType,
160 version: packageJSON.version,
161 enabled: true,
162 uninstalled: false,
163 peertubeEngine: packageJSON.engine.peertube
164 }, { returning: true })
165 } catch (err) {
166 logger.error('Cannot install plugin %s, removing it...', toInstall, { err })
167
168 try {
169 await removeNpmPlugin(name)
170 } catch (err) {
171 logger.error('Cannot remove plugin %s after failed installation.', toInstall, { err })
172 }
173
174 throw err
175 }
176
177 logger.info('Successful installation of plugin %s.', toInstall)
178
179 await this.registerPluginOrTheme(plugin)
180 }
181
182 async uninstall (packageName: string) {
183 logger.info('Uninstalling plugin %s.', packageName)
184
185 const pluginName = this.normalizePluginName(packageName)
186
187 try {
188 await this.unregister(pluginName)
189 } catch (err) {
190 logger.warn('Cannot unregister plugin %s.', pluginName, { err })
191 }
192
193 const plugin = await PluginModel.load(pluginName)
194 if (!plugin || plugin.uninstalled === true) {
195 logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', packageName)
196 return
197 }
198
199 plugin.enabled = false
200 plugin.uninstalled = true
201
202 await plugin.save()
203
204 await removeNpmPlugin(packageName)
205
206 logger.info('Plugin %s uninstalled.', packageName)
207 }
208
209 private async registerPluginOrTheme (plugin: PluginModel) {
210 logger.info('Registering plugin or theme %s.', plugin.name)
211
212 const packageJSON = this.getPackageJSON(plugin.name, plugin.type)
213 const pluginPath = this.getPluginPath(plugin.name, plugin.type)
214
215 if (!isPackageJSONValid(packageJSON, plugin.type)) {
216 throw new Error('Package.JSON is invalid.')
217 }
218
219 let library: PluginLibrary
220 if (plugin.type === PluginType.PLUGIN) {
221 library = await this.registerPlugin(plugin, pluginPath, packageJSON)
222 }
223
224 const clientScripts: { [id: string]: ClientScript } = {}
225 for (const c of packageJSON.clientScripts) {
226 clientScripts[c.script] = c
227 }
228
229 this.registeredPlugins[ plugin.name ] = {
230 name: plugin.name,
231 type: plugin.type,
232 version: plugin.version,
233 description: plugin.description,
234 peertubeEngine: plugin.peertubeEngine,
235 path: pluginPath,
236 staticDirs: packageJSON.staticDirs,
237 clientScripts,
238 css: packageJSON.css,
239 unregister: library ? library.unregister : undefined
240 }
241 }
242
243 private async registerPlugin (plugin: PluginModel, pluginPath: string, packageJSON: PluginPackageJson) {
244 const registerHook = (options: RegisterHookOptions) => {
245 if (!this.hooks[options.target]) this.hooks[options.target] = []
246
247 this.hooks[options.target].push({
248 pluginName: plugin.name,
249 handler: options.handler,
250 priority: options.priority || 0
251 })
252 }
253
254 const library: PluginLibrary = require(join(pluginPath, packageJSON.library))
255
256 if (!isLibraryCodeValid(library)) {
257 throw new Error('Library code is not valid (miss register or unregister function)')
258 }
259
260 library.register({ registerHook })
261
262 logger.info('Add plugin %s CSS to global file.', plugin.name)
263
264 await this.addCSSToGlobalFile(pluginPath, packageJSON.css)
265
266 return library
267 }
268
269 private sortHooksByPriority () {
270 for (const hookName of Object.keys(this.hooks)) {
271 this.hooks[hookName].sort((a, b) => {
272 return b.priority - a.priority
273 })
274 }
275 }
276
277 private resetCSSGlobalFile () {
278 return outputFile(PLUGIN_GLOBAL_CSS_PATH, '')
279 }
280
281 private async addCSSToGlobalFile (pluginPath: string, cssRelativePaths: string[]) {
282 for (const cssPath of cssRelativePaths) {
283 await this.concatFiles(join(pluginPath, cssPath), PLUGIN_GLOBAL_CSS_PATH)
284 }
285 }
286
287 private concatFiles (input: string, output: string) {
288 return new Promise<void>((res, rej) => {
289 const inputStream = createReadStream(input)
290 const outputStream = createWriteStream(output, { flags: 'a' })
291
292 inputStream.pipe(outputStream)
293
294 inputStream.on('end', () => res())
295 inputStream.on('error', err => rej(err))
296 })
297 }
298
299 private getPackageJSON (pluginName: string, pluginType: PluginType) {
300 const pluginPath = join(this.getPluginPath(pluginName, pluginType), 'package.json')
301
302 return require(pluginPath) as PluginPackageJson
303 }
304
305 private getPluginPath (pluginName: string, pluginType: PluginType) {
306 const prefix = pluginType === PluginType.PLUGIN ? 'peertube-plugin-' : 'peertube-theme-'
307
308 return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', prefix + pluginName)
309 }
310
311 private normalizePluginName (name: string) {
312 return name.replace(/^peertube-((theme)|(plugin))-/, '')
313 }
314
315 private async regeneratePluginGlobalCSS () {
316 await this.resetCSSGlobalFile()
317
318 for (const key of Object.keys(this.registeredPlugins)) {
319 const plugin = this.registeredPlugins[key]
320
321 await this.addCSSToGlobalFile(plugin.path, plugin.css)
322 }
323 }
324
325 private getRegisteredPluginsOrThemes (type: PluginType) {
326 const plugins: RegisteredPlugin[] = []
327
328 for (const pluginName of Object.keys(this.registeredPlugins)) {
329 const plugin = this.registeredPlugins[ pluginName ]
330 if (plugin.type !== type) continue
331
332 plugins.push(plugin)
333 }
334
335 return plugins
336 }
337
338 static get Instance () {
339 return this.instance || (this.instance = new this())
340 }
341 }