plugins-check-scheduler.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { logger } from '../../helpers/logger'
  2. import { AbstractScheduler } from './abstract-scheduler'
  3. import { SCHEDULER_INTERVALS_MS } from '../../initializers/constants'
  4. import { CONFIG } from '../../initializers/config'
  5. import { PluginModel } from '../../models/server/plugin'
  6. import { chunk } from 'lodash'
  7. import { getLatestPluginsVersion } from '../plugins/plugin-index'
  8. import { compareSemVer } from '../../../shared/core-utils/miscs/miscs'
  9. export class PluginsCheckScheduler extends AbstractScheduler {
  10. private static instance: AbstractScheduler
  11. protected schedulerIntervalMs = SCHEDULER_INTERVALS_MS.checkPlugins
  12. private constructor () {
  13. super()
  14. }
  15. protected async internalExecute () {
  16. return this.checkLatestPluginsVersion()
  17. }
  18. private async checkLatestPluginsVersion () {
  19. if (CONFIG.PLUGINS.INDEX.ENABLED === false) return
  20. logger.info('Checking latest plugins version.')
  21. const plugins = await PluginModel.listInstalled()
  22. // Process 10 plugins in 1 HTTP request
  23. const chunks = chunk(plugins, 10)
  24. for (const chunk of chunks) {
  25. // Find plugins according to their npm name
  26. const pluginIndex: { [npmName: string]: PluginModel} = {}
  27. for (const plugin of chunk) {
  28. pluginIndex[PluginModel.buildNpmName(plugin.name, plugin.type)] = plugin
  29. }
  30. const npmNames = Object.keys(pluginIndex)
  31. try {
  32. const results = await getLatestPluginsVersion(npmNames)
  33. for (const result of results) {
  34. const plugin = pluginIndex[result.npmName]
  35. if (!result.latestVersion) continue
  36. if (
  37. !plugin.latestVersion ||
  38. (plugin.latestVersion !== result.latestVersion && compareSemVer(plugin.latestVersion, result.latestVersion) < 0)
  39. ) {
  40. plugin.latestVersion = result.latestVersion
  41. await plugin.save()
  42. logger.info('Plugin %s has a new latest version %s.', result.npmName, plugin.latestVersion)
  43. }
  44. }
  45. } catch (err) {
  46. logger.error('Cannot get latest plugins version.', { npmNames, err })
  47. }
  48. }
  49. }
  50. static get Instance () {
  51. return this.instance || (this.instance = new this())
  52. }
  53. }