]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/commitdiff
WIP plugins: add plugin settings/uninstall in client
authorChocobozzz <me@florianbigard.com>
Thu, 11 Jul 2019 12:40:19 +0000 (14:40 +0200)
committerChocobozzz <chocobozzz@cpy.re>
Wed, 24 Jul 2019 08:58:16 +0000 (10:58 +0200)
17 files changed:
client/src/app/+admin/plugins/plugin-list-installed/plugin-list-installed.component.html
client/src/app/+admin/plugins/plugin-list-installed/plugin-list-installed.component.scss
client/src/app/+admin/plugins/plugin-list-installed/plugin-list-installed.component.ts
client/src/app/+admin/plugins/plugin-search/plugin-search.component.ts
client/src/app/+admin/plugins/plugin-show-installed/plugin-show-installed.component.html
client/src/app/+admin/plugins/plugin-show-installed/plugin-show-installed.component.scss
client/src/app/+admin/plugins/plugin-show-installed/plugin-show-installed.component.ts
client/src/app/+admin/plugins/plugins.routes.ts
client/src/app/+admin/plugins/shared/plugin-api.service.ts
client/src/app/+admin/plugins/shared/toggle-plugin-type.scss [new file with mode: 0644]
client/src/sass/include/_bootstrap.scss
server/controllers/api/plugins.ts
server/helpers/custom-validators/plugins.ts
server/lib/plugins/plugin-manager.ts
server/middlewares/validators/plugins.ts
server/models/server/plugin.ts
shared/models/plugins/peertube-plugin.model.ts

index 6bb8bcd75a6c9bc2d4c714aafd5d9376bc8d95a6..d4501490f18746b737720529812777bfaa298f52 100644 (file)
@@ -7,7 +7,31 @@
 </div>
 
 <div class="plugins" myInfiniteScroller (nearOfBottom)="onNearOfBottom()" [autoInit]="true">
-  <div class="section plugin" *ngFor="let plugin of plugins">
-    {{ plugin.name }}
+  <div class="card plugin" *ngFor="let plugin of plugins">
+    <div class="card-body">
+      <div class="first-row">
+        <a class="plugin-name" [routerLink]="getShowRouterLink(plugin)" title="Show plugin settings">{{ plugin.name }}</a>
+
+        <span class="plugin-version">{{ plugin.version }}</span>
+      </div>
+
+      <div class="second-row">
+        <div class="description">{{ plugin.description }}</div>
+
+        <div class="buttons">
+          <a class="action-button action-button-edit grey-button" target="_blank" rel="noopener noreferrer"
+             [href]="plugin.homepage" i18n-title title="Go to the plugin homepage"
+          >
+            <my-global-icon iconName="go"></my-global-icon>
+            <span i18n class="button-label">Homepage</span>
+          </a>
+
+
+          <my-edit-button [routerLink]="getShowRouterLink(plugin)" label="Settings" i18n-label></my-edit-button>
+
+          <my-delete-button (click)="uninstall(plugin)" label="Uninstall" i18n-label></my-delete-button>
+        </div>
+      </div>
+    </div>
   </div>
 </div>
index 9e98fcd340521519ea5bf3fee27856afa62abf9c..f250404ed70f325293f8d4e95701ab87e4d18449 100644 (file)
@@ -1,8 +1,37 @@
 @import '_variables';
 @import '_mixins';
 
-.toggle-plugin-type {
+.first-row {
+  margin-bottom: 10px;
+
+  .plugin-name {
+    font-size: 16px;
+    margin-right: 10px;
+    font-weight: $font-semibold;
+  }
+
+  .plugin-version {
+    opacity: 0.6;
+  }
+}
+
+.second-row {
   display: flex;
-  justify-content: center;
-  margin-bottom: 30px;
+  align-items: center;
+  justify-content: space-between;
+
+  .description {
+    opacity: 0.8
+  }
+
+  .buttons {
+    > *:not(:last-child) {
+      margin-right: 10px;
+    }
+  }
+}
+
+.action-button {
+  @include peertube-button-link;
+  @include button-with-icon(21px, 0, -2px);
 }
index 9745bc36b8aa5ea6be964f8c9059dfe2d9ecc78d..26a9a616ea53944b1575709032c8bf338789bd90 100644 (file)
@@ -3,13 +3,17 @@ import { PluginType } from '@shared/models/plugins/plugin.type'
 import { I18n } from '@ngx-translate/i18n-polyfill'
 import { PluginApiService } from '@app/+admin/plugins/shared/plugin-api.service'
 import { ComponentPagination, hasMoreItems } from '@app/shared/rest/component-pagination.model'
-import { Notifier } from '@app/core'
+import { ConfirmService, Notifier } from '@app/core'
 import { PeerTubePlugin } from '@shared/models/plugins/peertube-plugin.model'
+import { ActivatedRoute, Router } from '@angular/router'
 
 @Component({
   selector: 'my-plugin-list-installed',
   templateUrl: './plugin-list-installed.component.html',
-  styleUrls: [ './plugin-list-installed.component.scss' ]
+  styleUrls: [
+    '../shared/toggle-plugin-type.scss',
+    './plugin-list-installed.component.scss'
+  ]
 })
 export class PluginListInstalledComponent implements OnInit {
   pluginTypeOptions: { label: string, value: PluginType }[] = []
@@ -26,12 +30,18 @@ export class PluginListInstalledComponent implements OnInit {
   constructor (
     private i18n: I18n,
     private pluginService: PluginApiService,
-    private notifier: Notifier
+    private notifier: Notifier,
+    private confirmService: ConfirmService,
+    private router: Router,
+    private route: ActivatedRoute
   ) {
     this.pluginTypeOptions = this.pluginService.getPluginTypeOptions()
   }
 
   ngOnInit () {
+    const query = this.route.snapshot.queryParams
+    if (query['pluginType']) this.pluginType = parseInt(query['pluginType'], 10)
+
     this.reloadPlugins()
   }
 
@@ -39,6 +49,8 @@ export class PluginListInstalledComponent implements OnInit {
     this.pagination.currentPage = 1
     this.plugins = []
 
+    this.router.navigate([], { queryParams: { pluginType: this.pluginType }})
+
     this.loadMorePlugins()
   }
 
@@ -69,4 +81,28 @@ export class PluginListInstalledComponent implements OnInit {
 
     return this.i18n('You don\'t have themes installed yet.')
   }
+
+  async uninstall (plugin: PeerTubePlugin) {
+    const res = await this.confirmService.confirm(
+      this.i18n('Do you really want to uninstall {{pluginName}}?', { pluginName: plugin.name }),
+      this.i18n('Uninstall')
+    )
+    if (res === false) return
+
+    this.pluginService.uninstall(plugin.name, plugin.type)
+      .subscribe(
+        () => {
+          this.notifier.success(this.i18n('{{pluginName}} uninstalled.', { pluginName: plugin.name }))
+
+          this.plugins = this.plugins.filter(p => p.name !== plugin.name)
+          this.pagination.totalItems--
+        },
+
+        err => this.notifier.error(err.message)
+      )
+  }
+
+  getShowRouterLink (plugin: PeerTubePlugin) {
+    return [ '/admin', 'plugins', 'show', this.pluginService.nameToNpmName(plugin.name, plugin.type) ]
+  }
 }
index db1f91f3d03eabf2c1333daffb668c3f7b7f3d1d..787be2c8c7e0346bebc84f070e3674aad162b8a4 100644 (file)
@@ -13,7 +13,10 @@ import { PluginApiService } from '@app/+admin/plugins/shared/plugin-api.service'
 @Component({
   selector: 'my-plugin-search',
   templateUrl: './plugin-search.component.html',
-  styleUrls: [ './plugin-search.component.scss' ]
+  styleUrls: [
+    '../shared/toggle-plugin-type.scss',
+    './plugin-search.component.scss'
+  ]
 })
 export class PluginSearchComponent implements OnInit {
   pluginTypeOptions: { label: string, value: PluginType }[] = []
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..aae08b94d9c12f1b69791733cdcdf510ceb28091 100644 (file)
@@ -0,0 +1,26 @@
+<ng-container *ngIf="plugin">
+
+  <h2>
+    <ng-container>{{ pluginTypeLabel }}</ng-container>
+    {{ plugin.name }}
+  </h2>
+
+  <form *ngIf="hasRegisteredSettings()" role="form" (ngSubmit)="formValidated()" [formGroup]="form">
+    <div class="form-group" *ngFor="let setting of registeredSettings">
+      <label [attr.for]="setting.name">{{ setting.label }}</label>
+
+      <input *ngIf="setting.type === 'input'" type="text" [id]="setting.name" [formControlName]="setting.name" />
+
+      <div *ngIf="formErrors[setting.name]" class="form-error">
+        {{ formErrors[setting.name] }}
+      </div>
+    </div>
+
+    <input type="submit" i18n value="Update plugin settings" [disabled]="!form.valid">
+  </form>
+
+  <div *ngIf="!hasRegisteredSettings()" i18n class="no-settings">
+    This {{ pluginTypeLabel }} does not have settings.
+  </div>
+
+</ng-container>
index 5e6774739fb643993a1068a8f5cc0ab97b73bdfe..42fc1b634b90a83e8cf8a9fd2ec8d3cc12efec8a 100644 (file)
@@ -1,2 +1,22 @@
 @import '_variables';
 @import '_mixins';
+
+h2 {
+  margin-bottom: 20px;
+}
+
+input:not([type=submit]) {
+  @include peertube-input-text(340px);
+  display: block;
+}
+
+.peertube-select-container {
+  @include peertube-select-container(340px);
+}
+
+input[type=submit], button {
+  @include peertube-button;
+  @include orange-button;
+
+  margin-top: 10px;
+}
index f6559953222764c4b75241cf2b3907d40e54bb90..8750bfd38301564d5df03d0aa1850493d0916f61 100644 (file)
-import { Component, OnInit } from '@angular/core'
+import { Component, OnDestroy, OnInit } from '@angular/core'
+import { PeerTubePlugin } from '@shared/models/plugins/peertube-plugin.model'
+import { I18n } from '@ngx-translate/i18n-polyfill'
+import { PluginApiService } from '@app/+admin/plugins/shared/plugin-api.service'
+import { Notifier } from '@app/core'
+import { ActivatedRoute } from '@angular/router'
+import { Subscription } from 'rxjs'
+import { map, switchMap } from 'rxjs/operators'
+import { RegisterSettingOptions } from '@shared/models/plugins/register-setting.model'
+import { BuildFormArgument, BuildFormDefaultValues, FormReactive, FormValidatorService } from '@app/shared'
 
 @Component({
   selector: 'my-plugin-show-installed',
   templateUrl: './plugin-show-installed.component.html',
   styleUrls: [ './plugin-show-installed.component.scss' ]
 })
-export class PluginShowInstalledComponent implements OnInit {
+export class PluginShowInstalledComponent extends FormReactive implements OnInit, OnDestroy{
+  plugin: PeerTubePlugin
+  registeredSettings: RegisterSettingOptions[] = []
+  pluginTypeLabel: string
+
+  private sub: Subscription
+
+  constructor (
+    protected formValidatorService: FormValidatorService,
+    private i18n: I18n,
+    private pluginService: PluginApiService,
+    private notifier: Notifier,
+    private route: ActivatedRoute
+  ) {
+    super()
+  }
 
   ngOnInit () {
+    this.sub = this.route.params.subscribe(
+      routeParams => {
+        const npmName = routeParams['npmName']
+
+        this.loadPlugin(npmName)
+      }
+    )
+  }
+
+  ngOnDestroy () {
+    if (this.sub) this.sub.unsubscribe()
+  }
+
+  formValidated () {
+    const settings = this.form.value
+
+    this.pluginService.updatePluginSettings(this.plugin.name, this.plugin.type, settings)
+        .subscribe(
+          () => {
+            this.notifier.success(this.i18n('Settings updated.'))
+          },
+
+          err => this.notifier.error(err.message)
+        )
+  }
+
+  hasRegisteredSettings () {
+    return Array.isArray(this.registeredSettings) && this.registeredSettings.length !== 0
+  }
+
+  private loadPlugin (npmName: string) {
+    this.pluginService.getPlugin(npmName)
+        .pipe(switchMap(plugin => {
+          return this.pluginService.getPluginRegisteredSettings(plugin.name, plugin.type)
+            .pipe(map(data => ({ plugin, registeredSettings: data.settings })))
+        }))
+        .subscribe(
+          ({ plugin, registeredSettings }) => {
+            this.plugin = plugin
+            this.registeredSettings = registeredSettings
+
+            this.pluginTypeLabel = this.pluginService.getPluginTypeLabel(this.plugin.type)
+
+            this.buildSettingsForm()
+          },
+
+          err => this.notifier.error(err.message)
+        )
+  }
+
+  private buildSettingsForm () {
+    const defaultValues: BuildFormDefaultValues = {}
+    const buildOptions: BuildFormArgument = {}
+    const settingsValues: any = {}
+
+    for (const setting of this.registeredSettings) {
+      buildOptions[ setting.name ] = null
+      settingsValues[ setting.name ] = this.getSetting(setting.name)
+    }
+
+    this.buildForm(buildOptions)
+
+    this.form.patchValue(settingsValues)
+  }
+
+  private getSetting (name: string) {
+    const settings = this.plugin.settings
+
+    if (settings && settings[name]) return settings[name]
+
+    const registered = this.registeredSettings.find(r => r.name === name)
 
+    return registered.default
   }
 
 }
index 58b5534fb94f299fdf058785c4801276fb02594a..02e8fd3248fbe04c5cab5877fe527709f302bf23 100644 (file)
@@ -40,7 +40,7 @@ export const PluginsRoutes: Routes = [
         }
       },
       {
-        path: 'show/:name',
+        path: 'show/:npmName',
         component: PluginShowInstalledComponent,
         data: {
           meta: {
index bfc2b918fc079781b97c79a70c75c3af32e0b3ed..1d33cd1791c06332c6dd1fd6012a0d59b82a471d 100644 (file)
@@ -8,6 +8,9 @@ import { PluginType } from '@shared/models/plugins/plugin.type'
 import { ComponentPagination } from '@app/shared/rest/component-pagination.model'
 import { ResultList } from '@shared/models'
 import { PeerTubePlugin } from '@shared/models/plugins/peertube-plugin.model'
+import { ManagePlugin } from '@shared/models/plugins/manage-plugin.model'
+import { InstallPlugin } from '@shared/models/plugins/install-plugin.model'
+import { RegisterSettingOptions } from '@shared/models/plugins/register-setting.model'
 
 @Injectable()
 export class PluginApiService {
@@ -23,16 +26,24 @@ export class PluginApiService {
   getPluginTypeOptions () {
     return [
       {
-        label: this.i18n('Plugin'),
+        label: this.i18n('Plugins'),
         value: PluginType.PLUGIN
       },
       {
-        label: this.i18n('Theme'),
+        label: this.i18n('Themes'),
         value: PluginType.THEME
       }
     ]
   }
 
+  getPluginTypeLabel (type: PluginType) {
+    if (type === PluginType.PLUGIN) {
+      return this.i18n('plugin')
+    }
+
+    return this.i18n('theme')
+  }
+
   getPlugins (
     type: PluginType,
     componentPagination: ComponentPagination,
@@ -47,4 +58,57 @@ export class PluginApiService {
     return this.authHttp.get<ResultList<PeerTubePlugin>>(PluginApiService.BASE_APPLICATION_URL, { params })
                .pipe(catchError(res => this.restExtractor.handleError(res)))
   }
+
+  getPlugin (npmName: string) {
+    const path = PluginApiService.BASE_APPLICATION_URL + '/' + npmName
+
+    return this.authHttp.get<PeerTubePlugin>(path)
+               .pipe(catchError(res => this.restExtractor.handleError(res)))
+  }
+
+  getPluginRegisteredSettings (pluginName: string, pluginType: PluginType) {
+    const path = PluginApiService.BASE_APPLICATION_URL + '/' + this.nameToNpmName(pluginName, pluginType) + '/registered-settings'
+
+    return this.authHttp.get<{ settings: RegisterSettingOptions[] }>(path)
+               .pipe(catchError(res => this.restExtractor.handleError(res)))
+  }
+
+  updatePluginSettings (pluginName: string, pluginType: PluginType, settings: any) {
+    const path = PluginApiService.BASE_APPLICATION_URL + '/' + this.nameToNpmName(pluginName, pluginType) + '/settings'
+
+    return this.authHttp.put(path, { settings })
+               .pipe(catchError(res => this.restExtractor.handleError(res)))
+  }
+
+  uninstall (pluginName: string, pluginType: PluginType) {
+    const body: ManagePlugin = {
+      npmName: this.nameToNpmName(pluginName, pluginType)
+    }
+
+    return this.authHttp.post(PluginApiService.BASE_APPLICATION_URL + '/uninstall', body)
+               .pipe(catchError(res => this.restExtractor.handleError(res)))
+  }
+
+  install (npmName: string) {
+    const body: InstallPlugin = {
+      npmName
+    }
+
+    return this.authHttp.post(PluginApiService.BASE_APPLICATION_URL + '/install', body)
+               .pipe(catchError(res => this.restExtractor.handleError(res)))
+  }
+
+  nameToNpmName (name: string, type: PluginType) {
+    const prefix = type === PluginType.PLUGIN
+      ? 'peertube-plugin-'
+      : 'peertube-theme-'
+
+    return prefix + name
+  }
+
+  pluginTypeFromNpmName (npmName: string) {
+    return npmName.startsWith('peertube-plugin-')
+      ? PluginType.PLUGIN
+      : PluginType.THEME
+  }
 }
diff --git a/client/src/app/+admin/plugins/shared/toggle-plugin-type.scss b/client/src/app/+admin/plugins/shared/toggle-plugin-type.scss
new file mode 100644 (file)
index 0000000..ea2eda2
--- /dev/null
@@ -0,0 +1,21 @@
+@import '_variables';
+@import '_mixins';
+
+.toggle-plugin-type {
+  display: flex;
+  justify-content: center;
+  margin-bottom: 30px;
+
+  p-selectButton {
+    /deep/ {
+      .ui-button-text {
+        font-size: 15px;
+      }
+
+      .ui-button.ui-state-active {
+        background-color: var(--mainColor);
+        border-color: var(--mainColor);
+      }
+    }
+  }
+}
index 0a9c9a90390afa016d2e2498b0587e746e247d4e..b1a23be6bcad130aeb39a2aaf48235727bfe2453 100644 (file)
@@ -20,7 +20,7 @@
 //@import '~bootstrap/scss/custom-forms';
 @import '~bootstrap/scss/nav';
 //@import '~bootstrap/scss/navbar';
-//@import '~bootstrap/scss/card';
+@import '~bootstrap/scss/card';
 //@import '~bootstrap/scss/breadcrumb';
 //@import '~bootstrap/scss/pagination';
 @import '~bootstrap/scss/badge';
index 89cc67f5444d7f549c47c41fe2eb9594519891f9..f17e8cab9cc0fdf815431bcb11240456de7cd675 100644 (file)
@@ -12,7 +12,7 @@ import { pluginsSortValidator } from '../../middlewares/validators'
 import { PluginModel } from '../../models/server/plugin'
 import { UserRight } from '../../../shared/models/users'
 import {
-  enabledPluginValidator,
+  existingPluginValidator,
   installPluginValidator,
   listPluginsValidator,
   uninstallPluginValidator,
@@ -35,18 +35,25 @@ pluginRouter.get('/',
   asyncMiddleware(listPlugins)
 )
 
-pluginRouter.get('/:pluginName/settings',
+pluginRouter.get('/:npmName',
   authenticate,
   ensureUserHasRight(UserRight.MANAGE_PLUGINS),
-  asyncMiddleware(enabledPluginValidator),
-  asyncMiddleware(listPluginSettings)
+  asyncMiddleware(existingPluginValidator),
+  getPlugin
 )
 
-pluginRouter.put('/:pluginName/settings',
+pluginRouter.get('/:npmName/registered-settings',
+  authenticate,
+  ensureUserHasRight(UserRight.MANAGE_PLUGINS),
+  asyncMiddleware(existingPluginValidator),
+  asyncMiddleware(getPluginRegisteredSettings)
+)
+
+pluginRouter.put('/:npmName/settings',
   authenticate,
   ensureUserHasRight(UserRight.MANAGE_PLUGINS),
   updatePluginSettingsValidator,
-  asyncMiddleware(enabledPluginValidator),
+  asyncMiddleware(existingPluginValidator),
   asyncMiddleware(updatePluginSettings)
 )
 
@@ -85,6 +92,12 @@ async function listPlugins (req: express.Request, res: express.Response) {
   return res.json(getFormattedObjects(resultList.data, resultList.total))
 }
 
+function getPlugin (req: express.Request, res: express.Response) {
+  const plugin = res.locals.plugin
+
+  return res.json(plugin.toFormattedJSON())
+}
+
 async function installPlugin (req: express.Request, res: express.Response) {
   const body: InstallPlugin = req.body
 
@@ -101,7 +114,7 @@ async function uninstallPlugin (req: express.Request, res: express.Response) {
   return res.sendStatus(204)
 }
 
-async function listPluginSettings (req: express.Request, res: express.Response) {
+async function getPluginRegisteredSettings (req: express.Request, res: express.Response) {
   const plugin = res.locals.plugin
 
   const settings = await PluginManager.Instance.getSettings(plugin.name)
index 4ab5f9ce8392f825c95f4de5ebed8d7c399d03a2..064af9ead88ab1d77f90d7b9eb95cbd3a1829c32 100644 (file)
@@ -41,6 +41,10 @@ function isPluginEngineValid (engine: any) {
   return exists(engine) && exists(engine.peertube)
 }
 
+function isPluginHomepage (value: string) {
+  return isUrlValid(value)
+}
+
 function isStaticDirectoriesValid (staticDirs: any) {
   if (!exists(staticDirs) || typeof staticDirs !== 'object') return false
 
@@ -70,7 +74,7 @@ function isPackageJSONValid (packageJSON: PluginPackageJson, pluginType: PluginT
   return isNpmPluginNameValid(packageJSON.name) &&
     isPluginDescriptionValid(packageJSON.description) &&
     isPluginEngineValid(packageJSON.engine) &&
-    isUrlValid(packageJSON.homepage) &&
+    isPluginHomepage(packageJSON.homepage) &&
     exists(packageJSON.author) &&
     isUrlValid(packageJSON.bugs) &&
     (pluginType === PluginType.THEME || isSafePath(packageJSON.library)) &&
@@ -88,6 +92,7 @@ export {
   isPluginTypeValid,
   isPackageJSONValid,
   isThemeValid,
+  isPluginHomepage,
   isPluginVersionValid,
   isPluginNameValid,
   isPluginDescriptionValid,
index 3d8375acdf01c6136d87105c341cf647c40e4304..8cdeff446f0bb4c57f79bb4a72f2bb7ec2be14e3 100644 (file)
@@ -89,6 +89,8 @@ export class PluginManager {
   async runHook (hookName: string, param?: any) {
     let result = param
 
+    if (!this.hooks[hookName]) return result
+
     const wait = hookName.startsWith('static:')
 
     for (const hook of this.hooks[hookName]) {
@@ -162,8 +164,8 @@ export class PluginManager {
         : await installNpmPlugin(toInstall, version)
 
       name = fromDisk ? basename(toInstall) : toInstall
-      const pluginType = name.startsWith('peertube-theme-') ? PluginType.THEME : PluginType.PLUGIN
-      const pluginName = this.normalizePluginName(name)
+      const pluginType = PluginModel.getTypeFromNpmName(name)
+      const pluginName = PluginModel.normalizePluginName(name)
 
       const packageJSON = this.getPackageJSON(pluginName, pluginType)
       if (!isPackageJSONValid(packageJSON, pluginType)) {
@@ -173,6 +175,7 @@ export class PluginManager {
       [ plugin ] = await PluginModel.upsert({
         name: pluginName,
         description: packageJSON.description,
+        homepage: packageJSON.homepage,
         type: pluginType,
         version: packageJSON.version,
         enabled: true,
@@ -196,10 +199,10 @@ export class PluginManager {
     await this.registerPluginOrTheme(plugin)
   }
 
-  async uninstall (packageName: string) {
-    logger.info('Uninstalling plugin %s.', packageName)
+  async uninstall (npmName: string) {
+    logger.info('Uninstalling plugin %s.', npmName)
 
-    const pluginName = this.normalizePluginName(packageName)
+    const pluginName = PluginModel.normalizePluginName(npmName)
 
     try {
       await this.unregister(pluginName)
@@ -207,9 +210,9 @@ export class PluginManager {
       logger.warn('Cannot unregister plugin %s.', pluginName, { err })
     }
 
-    const plugin = await PluginModel.load(pluginName)
+    const plugin = await PluginModel.loadByNpmName(npmName)
     if (!plugin || plugin.uninstalled === true) {
-      logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', packageName)
+      logger.error('Cannot uninstall plugin %s: it does not exist or is already uninstalled.', npmName)
       return
     }
 
@@ -218,9 +221,9 @@ export class PluginManager {
 
     await plugin.save()
 
-    await removeNpmPlugin(packageName)
+    await removeNpmPlugin(npmName)
 
-    logger.info('Plugin %s uninstalled.', packageName)
+    logger.info('Plugin %s uninstalled.', npmName)
   }
 
   // ###################### Private register ######################
@@ -353,10 +356,6 @@ export class PluginManager {
     return join(CONFIG.STORAGE.PLUGINS_DIR, 'node_modules', prefix + pluginName)
   }
 
-  private normalizePluginName (name: string) {
-    return name.replace(/^peertube-((theme)|(plugin))-/, '')
-  }
-
   // ###################### Private getters ######################
 
   private getRegisteredPluginsOrThemes (type: PluginType) {
index 265ac7c17b0f84f1868328ad29b8e1897a8591f9..a06add6b8e6f1f31d221407ae197eebaf0ccba95 100644 (file)
@@ -63,7 +63,7 @@ const uninstallPluginValidator = [
   body('npmName').custom(isNpmPluginNameValid).withMessage('Should have a valid npm name'),
 
   (req: express.Request, res: express.Response, next: express.NextFunction) => {
-    logger.debug('Checking managePluginValidator parameters', { parameters: req.body })
+    logger.debug('Checking uninstallPluginValidator parameters', { parameters: req.body })
 
     if (areValidationErrors(req, res)) return
 
@@ -71,15 +71,15 @@ const uninstallPluginValidator = [
   }
 ]
 
-const enabledPluginValidator = [
-  body('name').custom(isPluginNameValid).withMessage('Should have a valid plugin name'),
+const existingPluginValidator = [
+  param('npmName').custom(isPluginNameValid).withMessage('Should have a valid plugin name'),
 
   async (req: express.Request, res: express.Response, next: express.NextFunction) => {
-    logger.debug('Checking enabledPluginValidator parameters', { parameters: req.body })
+    logger.debug('Checking enabledPluginValidator parameters', { parameters: req.params })
 
     if (areValidationErrors(req, res)) return
 
-    const plugin = await PluginModel.load(req.body.name)
+    const plugin = await PluginModel.loadByNpmName(req.params.npmName)
     if (!plugin) {
       return res.status(404)
          .json({ error: 'Plugin not found' })
@@ -110,7 +110,7 @@ export {
   servePluginStaticDirectoryValidator,
   updatePluginSettingsValidator,
   uninstallPluginValidator,
-  enabledPluginValidator,
+  existingPluginValidator,
   installPluginValidator,
   listPluginsValidator
 }
index 059a442de5dfe9a96d9206f0b8698d65708aa9d0..60abaec6592bc0de89c79bcc2d124179e7cd98b7 100644 (file)
@@ -1,7 +1,7 @@
 import { AllowNull, Column, CreatedAt, DataType, DefaultScope, Is, Model, Table, UpdatedAt } from 'sequelize-typescript'
 import { getSort, throwIfNotValid } from '../utils'
 import {
-  isPluginDescriptionValid,
+  isPluginDescriptionValid, isPluginHomepage,
   isPluginNameValid,
   isPluginTypeValid,
   isPluginVersionValid
@@ -20,7 +20,7 @@ import { FindAndCountOptions } from 'sequelize'
   tableName: 'plugin',
   indexes: [
     {
-      fields: [ 'name' ],
+      fields: [ 'name', 'type' ],
       unique: true
     }
   ]
@@ -59,6 +59,11 @@ export class PluginModel extends Model<PluginModel> {
   @Column
   description: string
 
+  @AllowNull(false)
+  @Is('PluginHomepage', value => throwIfNotValid(value, isPluginHomepage, 'homepage'))
+  @Column
+  homepage: string
+
   @AllowNull(true)
   @Column(DataType.JSONB)
   settings: any
@@ -84,10 +89,14 @@ export class PluginModel extends Model<PluginModel> {
     return PluginModel.findAll(query)
   }
 
-  static load (pluginName: string) {
+  static loadByNpmName (npmName: string) {
+    const name = this.normalizePluginName(npmName)
+    const type = this.getTypeFromNpmName(npmName)
+
     const query = {
       where: {
-        name: pluginName
+        name,
+        type
       }
     }
 
@@ -150,6 +159,16 @@ export class PluginModel extends Model<PluginModel> {
       })
   }
 
+  static normalizePluginName (name: string) {
+    return name.replace(/^peertube-((theme)|(plugin))-/, '')
+  }
+
+  static getTypeFromNpmName (npmName: string) {
+    return npmName.startsWith('peertube-plugin-')
+      ? PluginType.PLUGIN
+      : PluginType.THEME
+  }
+
   toFormattedJSON (): PeerTubePlugin {
     return {
       name: this.name,
@@ -159,6 +178,7 @@ export class PluginModel extends Model<PluginModel> {
       uninstalled: this.uninstalled,
       peertubeEngine: this.peertubeEngine,
       description: this.description,
+      homepage: this.homepage,
       settings: this.settings,
       createdAt: this.createdAt,
       updatedAt: this.updatedAt
index 2a1dfb3a7b465cbc5c3c3015711484becdf74c0a..de3c7741bc07625511fde74b9997429976f13d60 100644 (file)
@@ -6,7 +6,8 @@ export interface PeerTubePlugin {
   uninstalled: boolean
   peertubeEngine: string
   description: string
-  settings: any
+  homepage: string
+  settings: { [ name: string ]: string }
   createdAt: Date
   updatedAt: Date
 }