You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
2.5 KiB

  1. const Model = require('objection').Model
  2. const fs = require('fs-extra')
  3. const path = require('path')
  4. const _ = require('lodash')
  5. const yaml = require('js-yaml')
  6. const commonHelper = require('../helpers/common')
  7. /* global WIKI */
  8. /**
  9. * Editor model
  10. */
  11. module.exports = class Editor extends Model {
  12. static get tableName() { return 'editors' }
  13. static get jsonSchema () {
  14. return {
  15. type: 'object',
  16. required: ['key', 'isEnabled'],
  17. properties: {
  18. id: {type: 'integer'},
  19. key: {type: 'string'},
  20. isEnabled: {type: 'boolean'},
  21. config: {type: 'object'}
  22. }
  23. }
  24. }
  25. static async getEditors() {
  26. return WIKI.models.editors.query()
  27. }
  28. static async refreshEditorsFromDisk() {
  29. try {
  30. const dbEditors = await WIKI.models.editors.query()
  31. // -> Fetch definitions from disk
  32. const editorDirs = await fs.readdir(path.join(WIKI.SERVERPATH, 'modules/editor'))
  33. let diskEditors = []
  34. for (let dir of editorDirs) {
  35. const def = await fs.readFile(path.join(WIKI.SERVERPATH, 'modules/editor', dir, 'definition.yml'), 'utf8')
  36. diskEditors.push(yaml.safeLoad(def))
  37. }
  38. WIKI.data.editors = diskEditors.map(editor => ({
  39. ...editor,
  40. props: commonHelper.parseModuleProps(editor.props)
  41. }))
  42. // -> Insert new editors
  43. let newEditors = []
  44. for (let editor of WIKI.data.editors) {
  45. if (!_.some(dbEditors, ['key', editor.key])) {
  46. newEditors.push({
  47. key: editor.key,
  48. isEnabled: false,
  49. config: _.transform(editor.props, (result, value, key) => {
  50. _.set(result, key, value.default)
  51. return result
  52. }, {})
  53. })
  54. } else {
  55. const editorConfig = _.get(_.find(dbEditors, ['key', editor.key]), 'config', {})
  56. await WIKI.models.editors.query().patch({
  57. config: _.transform(editor.props, (result, value, key) => {
  58. if (!_.has(result, key)) {
  59. _.set(result, key, value.default)
  60. }
  61. return result
  62. }, editorConfig)
  63. }).where('key', editor.key)
  64. }
  65. }
  66. if (newEditors.length > 0) {
  67. await WIKI.models.editors.query().insert(newEditors)
  68. WIKI.logger.info(`Loaded ${newEditors.length} new editors: [ OK ]`)
  69. } else {
  70. WIKI.logger.info(`No new editors found: [ SKIPPED ]`)
  71. }
  72. } catch (err) {
  73. WIKI.logger.error(`Failed to scan or load new editors: [ FAILED ]`)
  74. WIKI.logger.error(err)
  75. }
  76. }
  77. }