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.

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