plugin.service.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. const debug = require('debug')('crowi:plugins:PluginService');
  2. const path = require('path');
  3. const fs = require('hexo-fs');
  4. const PluginLoaderV2 = require('./plugin-loader-v2.model');
  5. class PluginService {
  6. constructor(crowi, app) {
  7. this.crowi = crowi;
  8. this.app = app;
  9. this.pluginLoaderV2 = new PluginLoaderV2();
  10. }
  11. /**
  12. * list plugin module names that starts with 'crowi-plugin-'
  13. * borrowing from: https://github.com/hexojs/hexo/blob/d1db459c92a4765620343b95789361cbbc6414c5/lib/hexo/load_plugins.js#L17
  14. *
  15. * @returns
  16. *
  17. * @memberOf PluginService
  18. */
  19. listPluginNames() {
  20. var packagePath = path.join(this.crowi.rootDir, 'package.json');
  21. var pluginDir = this.crowi.pluginDir;
  22. // Make sure package.json exists
  23. return fs.exists(packagePath).then(function(exist) {
  24. if (!exist) return [];
  25. // Read package.json and find dependencies
  26. return fs.readFile(packagePath).then(function(content) {
  27. var json = JSON.parse(content);
  28. var deps = json.dependencies || {};
  29. return Object.keys(deps);
  30. });
  31. }).filter(function(name) {
  32. // Ignore plugins whose name is not started with "crowi-"
  33. if (!/^crowi-plugin-/.test(name)) return false;
  34. // Make sure the plugin exists
  35. var pluginPath = path.join(pluginDir, name);
  36. return fs.exists(pluginPath);
  37. });
  38. }
  39. loadPlugins() {
  40. let self = this;
  41. this.listPluginNames()
  42. .map(function(name) {
  43. self.loadPlugin(name);
  44. });
  45. }
  46. loadPlugin(name) {
  47. const meta = require(name);
  48. // v1 is deprecated
  49. if (1 === meta.pluginSchemaVersion) {
  50. debug('pluginSchemaVersion 1 is deprecated');
  51. return;
  52. }
  53. // v2
  54. if (2 === meta.pluginSchemaVersion) {
  55. this.pluginLoaderV2.loadForServer(name, this.crowi, this.app);
  56. return;
  57. }
  58. }
  59. }
  60. module.exports = PluginService;