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