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.

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