]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/core/plugins/plugin.service.ts
Add ability to set custom field to video form
[github/Chocobozzz/PeerTube.git] / client / src / app / core / plugins / plugin.service.ts
1 import { Observable, of, ReplaySubject } from 'rxjs'
2 import { catchError, first, map, shareReplay } from 'rxjs/operators'
3 import { HttpClient } from '@angular/common/http'
4 import { Inject, Injectable, LOCALE_ID, NgZone } from '@angular/core'
5 import { AuthService } from '@app/core/auth'
6 import { Notifier } from '@app/core/notification'
7 import { MarkdownService } from '@app/core/renderer'
8 import { RestExtractor } from '@app/core/rest'
9 import { ServerService } from '@app/core/server/server.service'
10 import { getDevLocale, isOnDevLocale } from '@app/helpers'
11 import { CustomModalComponent } from '@app/modal/custom-modal.component'
12 import { FormFields, Hooks, loadPlugin, PluginInfo, runHook } from '@root-helpers/plugins'
13 import { getCompleteLocale, isDefaultLocale, peertubeTranslate } from '@shared/core-utils/i18n'
14 import {
15 ClientHook,
16 ClientHookName,
17 PluginClientScope,
18 PluginTranslation,
19 PluginType,
20 PublicServerSetting,
21 ServerConfigPlugin
22 } from '@shared/models'
23 import { environment } from '../../../environments/environment'
24 import { RegisterClientHelpers } from '../../../types/register-client-option.model'
25
26 @Injectable()
27 export class PluginService implements ClientHook {
28 private static BASE_PLUGIN_API_URL = environment.apiUrl + '/api/v1/plugins'
29 private static BASE_PLUGIN_URL = environment.apiUrl + '/plugins'
30
31 pluginsBuilt = new ReplaySubject<boolean>(1)
32
33 pluginsLoaded: { [ scope in PluginClientScope ]: ReplaySubject<boolean> } = {
34 common: new ReplaySubject<boolean>(1),
35 search: new ReplaySubject<boolean>(1),
36 'video-watch': new ReplaySubject<boolean>(1),
37 signup: new ReplaySubject<boolean>(1),
38 login: new ReplaySubject<boolean>(1),
39 'video-edit': new ReplaySubject<boolean>(1),
40 embed: new ReplaySubject<boolean>(1)
41 }
42
43 translationsObservable: Observable<PluginTranslation>
44
45 customModal: CustomModalComponent
46
47 private plugins: ServerConfigPlugin[] = []
48 private scopes: { [ scopeName: string ]: PluginInfo[] } = {}
49 private loadedScripts: { [ script: string ]: boolean } = {}
50 private loadedScopes: PluginClientScope[] = []
51 private loadingScopes: { [id in PluginClientScope]?: boolean } = {}
52
53 private hooks: Hooks = {}
54 private formFields: FormFields = {
55 video: []
56 }
57
58 constructor (
59 private authService: AuthService,
60 private notifier: Notifier,
61 private markdownRenderer: MarkdownService,
62 private server: ServerService,
63 private zone: NgZone,
64 private authHttp: HttpClient,
65 private restExtractor: RestExtractor,
66 @Inject(LOCALE_ID) private localeId: string
67 ) {
68 this.loadTranslations()
69 }
70
71 initializePlugins () {
72 this.server.getConfig()
73 .subscribe(config => {
74 this.plugins = config.plugin.registered
75
76 this.buildScopeStruct()
77
78 this.pluginsBuilt.next(true)
79 })
80 }
81
82 initializeCustomModal (customModal: CustomModalComponent) {
83 this.customModal = customModal
84 }
85
86 ensurePluginsAreBuilt () {
87 return this.pluginsBuilt.asObservable()
88 .pipe(first(), shareReplay())
89 .toPromise()
90 }
91
92 ensurePluginsAreLoaded (scope: PluginClientScope) {
93 this.loadPluginsByScope(scope)
94
95 return this.pluginsLoaded[scope].asObservable()
96 .pipe(first(), shareReplay())
97 .toPromise()
98 }
99
100 addPlugin (plugin: ServerConfigPlugin, isTheme = false) {
101 const pathPrefix = this.getPluginPathPrefix(isTheme)
102
103 for (const key of Object.keys(plugin.clientScripts)) {
104 const clientScript = plugin.clientScripts[key]
105
106 for (const scope of clientScript.scopes) {
107 if (!this.scopes[scope]) this.scopes[scope] = []
108
109 this.scopes[scope].push({
110 plugin,
111 clientScript: {
112 script: `${pathPrefix}/${plugin.name}/${plugin.version}/client-scripts/${clientScript.script}`,
113 scopes: clientScript.scopes
114 },
115 pluginType: isTheme ? PluginType.THEME : PluginType.PLUGIN,
116 isTheme
117 })
118
119 this.loadedScripts[clientScript.script] = false
120 }
121 }
122 }
123
124 removePlugin (plugin: ServerConfigPlugin) {
125 for (const key of Object.keys(this.scopes)) {
126 this.scopes[key] = this.scopes[key].filter(o => o.plugin.name !== plugin.name)
127 }
128 }
129
130 async reloadLoadedScopes () {
131 for (const scope of this.loadedScopes) {
132 await this.loadPluginsByScope(scope, true)
133 }
134 }
135
136 async loadPluginsByScope (scope: PluginClientScope, isReload = false) {
137 if (this.loadingScopes[scope]) return
138 if (!isReload && this.loadedScopes.includes(scope)) return
139
140 this.loadingScopes[scope] = true
141
142 try {
143 await this.ensurePluginsAreBuilt()
144
145 if (!isReload) this.loadedScopes.push(scope)
146
147 const toLoad = this.scopes[ scope ]
148 if (!Array.isArray(toLoad)) {
149 this.loadingScopes[scope] = false
150 this.pluginsLoaded[scope].next(true)
151
152 return
153 }
154
155 const promises: Promise<any>[] = []
156 for (const pluginInfo of toLoad) {
157 const clientScript = pluginInfo.clientScript
158
159 if (this.loadedScripts[ clientScript.script ]) continue
160
161 promises.push(this.loadPlugin(pluginInfo))
162
163 this.loadedScripts[ clientScript.script ] = true
164 }
165
166 await Promise.all(promises)
167
168 this.pluginsLoaded[scope].next(true)
169 this.loadingScopes[scope] = false
170 } catch (err) {
171 console.error('Cannot load plugins by scope %s.', scope, err)
172 }
173 }
174
175 runHook <T> (hookName: ClientHookName, result?: T, params?: any): Promise<T> {
176 return this.zone.runOutsideAngular(() => {
177 return runHook(this.hooks, hookName, result, params)
178 })
179 }
180
181 nameToNpmName (name: string, type: PluginType) {
182 const prefix = type === PluginType.PLUGIN
183 ? 'peertube-plugin-'
184 : 'peertube-theme-'
185
186 return prefix + name
187 }
188
189 pluginTypeFromNpmName (npmName: string) {
190 return npmName.startsWith('peertube-plugin-')
191 ? PluginType.PLUGIN
192 : PluginType.THEME
193 }
194
195 getRegisteredVideoFormFields (type: 'import-url' | 'import-torrent' | 'upload' | 'update') {
196 return this.formFields.video.filter(f => f.videoFormOptions.type === type)
197 }
198
199 private loadPlugin (pluginInfo: PluginInfo) {
200 return this.zone.runOutsideAngular(() => {
201 return loadPlugin({
202 hooks: this.hooks,
203 formFields: this.formFields,
204 pluginInfo,
205 peertubeHelpersFactory: pluginInfo => this.buildPeerTubeHelpers(pluginInfo)
206 })
207 })
208 }
209
210 private buildScopeStruct () {
211 for (const plugin of this.plugins) {
212 this.addPlugin(plugin)
213 }
214 }
215
216 private buildPeerTubeHelpers (pluginInfo: PluginInfo): RegisterClientHelpers {
217 const { plugin } = pluginInfo
218 const npmName = this.nameToNpmName(pluginInfo.plugin.name, pluginInfo.pluginType)
219
220 return {
221 getBaseStaticRoute: () => {
222 const pathPrefix = this.getPluginPathPrefix(pluginInfo.isTheme)
223 return environment.apiUrl + `${pathPrefix}/${plugin.name}/${plugin.version}/static`
224 },
225
226 getSettings: () => {
227 const path = PluginService.BASE_PLUGIN_API_URL + '/' + npmName + '/public-settings'
228
229 return this.authHttp.get<PublicServerSetting>(path)
230 .pipe(
231 map(p => p.publicSettings),
232 catchError(res => this.restExtractor.handleError(res))
233 )
234 .toPromise()
235 },
236
237 isLoggedIn: () => {
238 return this.authService.isLoggedIn()
239 },
240
241 notifier: {
242 info: (text: string, title?: string, timeout?: number) => this.notifier.info(text, title, timeout),
243 error: (text: string, title?: string, timeout?: number) => this.notifier.error(text, title, timeout),
244 success: (text: string, title?: string, timeout?: number) => this.notifier.success(text, title, timeout)
245 },
246
247 showModal: (input: {
248 title: string,
249 content: string,
250 close?: boolean,
251 cancel?: { value: string, action?: () => void },
252 confirm?: { value: string, action?: () => void }
253 }) => {
254 this.customModal.show(input)
255 },
256
257 markdownRenderer: {
258 textMarkdownToHTML: (textMarkdown: string) => {
259 return this.markdownRenderer.textMarkdownToHTML(textMarkdown)
260 },
261
262 enhancedMarkdownToHTML: (enhancedMarkdown: string) => {
263 return this.markdownRenderer.enhancedMarkdownToHTML(enhancedMarkdown)
264 }
265 },
266
267 translate: (value: string) => {
268 return this.translationsObservable
269 .pipe(map(allTranslations => allTranslations[npmName]))
270 .pipe(map(translations => peertubeTranslate(value, translations)))
271 .toPromise()
272 }
273 }
274 }
275
276 private loadTranslations () {
277 const completeLocale = isOnDevLocale() ? getDevLocale() : getCompleteLocale(this.localeId)
278
279 // Default locale, nothing to translate
280 if (isDefaultLocale(completeLocale)) this.translationsObservable = of({}).pipe(shareReplay())
281
282 this.translationsObservable = this.authHttp
283 .get<PluginTranslation>(PluginService.BASE_PLUGIN_URL + '/translations/' + completeLocale + '.json')
284 .pipe(shareReplay())
285 }
286
287 private getPluginPathPrefix (isTheme: boolean) {
288 return isTheme ? '/themes' : '/plugins'
289 }
290 }