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.

90 lines
2.7 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 idColumn() { return 'key' }
  14. static get jsonSchema () {
  15. return {
  16. type: 'object',
  17. required: ['key', 'isEnabled'],
  18. properties: {
  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. let trx
  30. try {
  31. const dbEditors = await WIKI.models.editors.query()
  32. // -> Fetch definitions from disk
  33. const editorDirs = await fs.readdir(path.join(WIKI.SERVERPATH, 'modules/editor'))
  34. let diskEditors = []
  35. for (let dir of editorDirs) {
  36. const def = await fs.readFile(path.join(WIKI.SERVERPATH, 'modules/editor', dir, 'definition.yml'), 'utf8')
  37. diskEditors.push(yaml.safeLoad(def))
  38. }
  39. WIKI.data.editors = diskEditors.map(editor => ({
  40. ...editor,
  41. props: commonHelper.parseModuleProps(editor.props)
  42. }))
  43. // -> Insert new editors
  44. let newEditors = []
  45. for (let editor of WIKI.data.editors) {
  46. if (!_.some(dbEditors, ['key', editor.key])) {
  47. newEditors.push({
  48. key: editor.key,
  49. isEnabled: false,
  50. config: _.transform(editor.props, (result, value, key) => {
  51. _.set(result, key, value.default)
  52. return result
  53. }, {})
  54. })
  55. } else {
  56. const editorConfig = _.get(_.find(dbEditors, ['key', editor.key]), 'config', {})
  57. await WIKI.models.editors.query().patch({
  58. config: _.transform(editor.props, (result, value, key) => {
  59. if (!_.has(result, key)) {
  60. _.set(result, key, value.default)
  61. }
  62. return result
  63. }, editorConfig)
  64. }).where('key', editor.key)
  65. }
  66. }
  67. if (newEditors.length > 0) {
  68. trx = await WIKI.models.Objection.transaction.start(WIKI.models.knex)
  69. for (let editor of newEditors) {
  70. await WIKI.models.editors.query(trx).insert(editor)
  71. }
  72. await trx.commit()
  73. WIKI.logger.info(`Loaded ${newEditors.length} new editors: [ OK ]`)
  74. } else {
  75. WIKI.logger.info(`No new editors found: [ SKIPPED ]`)
  76. }
  77. } catch (err) {
  78. WIKI.logger.error(`Failed to scan or load new editors: [ FAILED ]`)
  79. WIKI.logger.error(err)
  80. }
  81. }
  82. }