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.

172 lines
5.5 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. // -> Delete removed Renderers
  84. for (const renderer of dbRenderers) {
  85. if (!_.some(WIKI.data.renderers, ['key', renderer.key])) {
  86. await WIKI.models.renderers.query().where('key', renderer.key).del()
  87. WIKI.logger.info(`Removed renderer ${renderer.key} because it is no longer present in the modules folder: [ OK ]`)
  88. }
  89. }
  90. } catch (err) {
  91. WIKI.logger.error(`Failed to scan or load new renderers: [ FAILED ]`)
  92. WIKI.logger.error(err)
  93. if (trx) {
  94. trx.rollback()
  95. }
  96. }
  97. }
  98. static async getRenderingPipeline(contentType) {
  99. const renderersDb = await WIKI.models.renderers.query().where('isEnabled', true)
  100. if (renderersDb && renderersDb.length > 0) {
  101. const renderers = renderersDb.map(rdr => {
  102. const renderer = _.find(WIKI.data.renderers, ['key', rdr.key])
  103. return {
  104. ...renderer,
  105. config: rdr.config
  106. }
  107. })
  108. // Build tree
  109. const rawCores = _.filter(renderers, renderer => !_.has(renderer, 'dependsOn')).map(core => {
  110. core.children = _.filter(renderers, ['dependsOn', core.key])
  111. return core
  112. })
  113. // Build dependency graph
  114. const graph = new DepGraph({ circular: true })
  115. rawCores.map(core => { graph.addNode(core.key) })
  116. rawCores.map(core => {
  117. rawCores.map(coreTarget => {
  118. if (core.key !== coreTarget.key) {
  119. if (core.output === coreTarget.input) {
  120. graph.addDependency(core.key, coreTarget.key)
  121. }
  122. }
  123. })
  124. })
  125. // Filter unused cores
  126. let activeCoreKeys = _.filter(rawCores, ['input', contentType]).map(core => core.key)
  127. _.clone(activeCoreKeys).map(coreKey => {
  128. activeCoreKeys = _.union(activeCoreKeys, graph.dependenciesOf(coreKey))
  129. })
  130. const activeCores = _.filter(rawCores, core => _.includes(activeCoreKeys, core.key))
  131. // Rebuild dependency graph with active cores
  132. const graphActive = new DepGraph({ circular: true })
  133. activeCores.map(core => { graphActive.addNode(core.key) })
  134. activeCores.map(core => {
  135. activeCores.map(coreTarget => {
  136. if (core.key !== coreTarget.key) {
  137. if (core.output === coreTarget.input) {
  138. graphActive.addDependency(core.key, coreTarget.key)
  139. }
  140. }
  141. })
  142. })
  143. // Reorder cores in reverse dependency order
  144. let orderedCores = []
  145. _.reverse(graphActive.overallOrder()).map(coreKey => {
  146. orderedCores.push(_.find(rawCores, ['key', coreKey]))
  147. })
  148. return orderedCores
  149. } else {
  150. WIKI.logger.error(`Rendering pipeline is empty!`)
  151. return false
  152. }
  153. }
  154. }