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.

157 lines
5.0 KiB

  1. const Model = require('objection').Model
  2. const path = require('path')
  3. const fs = require('fs-extra')
  4. const _ = require('lodash')
  5. const yaml = require('js-yaml')
  6. const DepGraph = require('dependency-graph').DepGraph
  7. const commonHelper = require('../helpers/common')
  8. /* global WIKI */
  9. /**
  10. * Renderer model
  11. */
  12. module.exports = class Renderer extends Model {
  13. static get tableName() { return 'renderers' }
  14. static get idColumn() { return 'key' }
  15. static get jsonSchema () {
  16. return {
  17. type: 'object',
  18. required: ['key', 'isEnabled'],
  19. properties: {
  20. key: {type: 'string'},
  21. isEnabled: {type: 'boolean'},
  22. config: {type: 'object'}
  23. }
  24. }
  25. }
  26. static async getRenderers() {
  27. return WIKI.models.renderers.query()
  28. }
  29. static async refreshRenderersFromDisk() {
  30. let trx
  31. try {
  32. const dbRenderers = await WIKI.models.renderers.query()
  33. // -> Fetch definitions from disk
  34. const rendererDirs = await fs.readdir(path.join(WIKI.SERVERPATH, 'modules/rendering'))
  35. let diskRenderers = []
  36. for (let dir of rendererDirs) {
  37. const def = await fs.readFile(path.join(WIKI.SERVERPATH, 'modules/rendering', dir, 'definition.yml'), 'utf8')
  38. diskRenderers.push(yaml.safeLoad(def))
  39. }
  40. WIKI.data.renderers = diskRenderers.map(renderer => ({
  41. ...renderer,
  42. props: commonHelper.parseModuleProps(renderer.props)
  43. }))
  44. // -> Insert new Renderers
  45. let newRenderers = []
  46. for (let renderer of WIKI.data.renderers) {
  47. if (!_.some(dbRenderers, ['key', renderer.key])) {
  48. newRenderers.push({
  49. key: renderer.key,
  50. isEnabled: _.get(renderer, 'enabledDefault', true),
  51. config: _.transform(renderer.props, (result, value, key) => {
  52. _.set(result, key, value.default)
  53. return result
  54. }, {})
  55. })
  56. } else {
  57. const rendererConfig = _.get(_.find(dbRenderers, ['key', renderer.key]), 'config', {})
  58. await WIKI.models.renderers.query().patch({
  59. config: _.transform(renderer.props, (result, value, key) => {
  60. if (!_.has(result, key)) {
  61. _.set(result, key, value.default)
  62. }
  63. return result
  64. }, rendererConfig)
  65. }).where('key', renderer.key)
  66. }
  67. }
  68. if (newRenderers.length > 0) {
  69. trx = await WIKI.models.Objection.transaction.start(WIKI.models.knex)
  70. for (let renderer of newRenderers) {
  71. await WIKI.models.renderers.query(trx).insert(renderer)
  72. }
  73. await trx.commit()
  74. WIKI.logger.info(`Loaded ${newRenderers.length} new renderers: [ OK ]`)
  75. } else {
  76. WIKI.logger.info(`No new renderers found: [ SKIPPED ]`)
  77. }
  78. } catch (err) {
  79. WIKI.logger.error(`Failed to scan or load new renderers: [ FAILED ]`)
  80. WIKI.logger.error(err)
  81. if (trx) {
  82. trx.rollback()
  83. }
  84. }
  85. }
  86. static async getRenderingPipeline(contentType) {
  87. const renderersDb = await WIKI.models.renderers.query().where('isEnabled', true)
  88. if (renderersDb && renderersDb.length > 0) {
  89. const renderers = renderersDb.map(rdr => {
  90. const renderer = _.find(WIKI.data.renderers, ['key', rdr.key])
  91. return {
  92. ...renderer,
  93. config: rdr.config
  94. }
  95. })
  96. // Build tree
  97. const rawCores = _.filter(renderers, renderer => !_.has(renderer, 'dependsOn')).map(core => {
  98. core.children = _.filter(renderers, ['dependsOn', core.key])
  99. return core
  100. })
  101. // Build dependency graph
  102. const graph = new DepGraph({ circular: true })
  103. rawCores.map(core => { graph.addNode(core.key) })
  104. rawCores.map(core => {
  105. rawCores.map(coreTarget => {
  106. if (core.key !== coreTarget.key) {
  107. if (core.output === coreTarget.input) {
  108. graph.addDependency(core.key, coreTarget.key)
  109. }
  110. }
  111. })
  112. })
  113. // Filter unused cores
  114. let activeCoreKeys = _.filter(rawCores, ['input', contentType]).map(core => core.key)
  115. _.clone(activeCoreKeys).map(coreKey => {
  116. activeCoreKeys = _.union(activeCoreKeys, graph.dependenciesOf(coreKey))
  117. })
  118. const activeCores = _.filter(rawCores, core => _.includes(activeCoreKeys, core.key))
  119. // Rebuild dependency graph with active cores
  120. const graphActive = new DepGraph({ circular: true })
  121. activeCores.map(core => { graphActive.addNode(core.key) })
  122. activeCores.map(core => {
  123. activeCores.map(coreTarget => {
  124. if (core.key !== coreTarget.key) {
  125. if (core.output === coreTarget.input) {
  126. graphActive.addDependency(core.key, coreTarget.key)
  127. }
  128. }
  129. })
  130. })
  131. // Reorder cores in reverse dependency order
  132. let orderedCores = []
  133. _.reverse(graphActive.overallOrder()).map(coreKey => {
  134. orderedCores.push(_.find(rawCores, ['key', coreKey]))
  135. })
  136. return orderedCores
  137. } else {
  138. WIKI.logger.error(`Rendering pipeline is empty!`)
  139. return false
  140. }
  141. }
  142. }