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.

142 lines
4.4 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. * Analytics model
  10. */
  11. module.exports = class Analytics extends Model {
  12. static get tableName() { return 'analytics' }
  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. }
  22. }
  23. }
  24. static get jsonAttributes() {
  25. return ['config']
  26. }
  27. static async getProviders(isEnabled) {
  28. const providers = await WIKI.models.analytics.query().where(_.isBoolean(isEnabled) ? { isEnabled } : {})
  29. return _.sortBy(providers, ['key'])
  30. }
  31. static async refreshProvidersFromDisk() {
  32. let trx
  33. try {
  34. const dbProviders = await WIKI.models.analytics.query()
  35. // -> Fetch definitions from disk
  36. const analyticsDirs = await fs.readdir(path.join(WIKI.SERVERPATH, 'modules/analytics'))
  37. let diskProviders = []
  38. for (let dir of analyticsDirs) {
  39. const def = await fs.readFile(path.join(WIKI.SERVERPATH, 'modules/analytics', dir, 'definition.yml'), 'utf8')
  40. diskProviders.push(yaml.safeLoad(def))
  41. }
  42. WIKI.data.analytics = diskProviders.map(provider => ({
  43. ...provider,
  44. props: commonHelper.parseModuleProps(provider.props)
  45. }))
  46. let newProviders = []
  47. for (let provider of WIKI.data.analytics) {
  48. if (!_.some(dbProviders, ['key', provider.key])) {
  49. newProviders.push({
  50. key: provider.key,
  51. isEnabled: false,
  52. config: _.transform(provider.props, (result, value, key) => {
  53. _.set(result, key, value.default)
  54. return result
  55. }, {})
  56. })
  57. } else {
  58. const providerConfig = _.get(_.find(dbProviders, ['key', provider.key]), 'config', {})
  59. await WIKI.models.analytics.query().patch({
  60. config: _.transform(provider.props, (result, value, key) => {
  61. if (!_.has(result, key)) {
  62. _.set(result, key, value.default)
  63. }
  64. return result
  65. }, providerConfig)
  66. }).where('key', provider.key)
  67. }
  68. }
  69. if (newProviders.length > 0) {
  70. trx = await WIKI.models.Objection.transaction.start(WIKI.models.knex)
  71. for (let provider of newProviders) {
  72. await WIKI.models.analytics.query(trx).insert(provider)
  73. }
  74. await trx.commit()
  75. WIKI.logger.info(`Loaded ${newProviders.length} new analytics providers: [ OK ]`)
  76. } else {
  77. WIKI.logger.info(`No new analytics providers found: [ SKIPPED ]`)
  78. }
  79. } catch (err) {
  80. WIKI.logger.error(`Failed to scan or load new analytics providers: [ FAILED ]`)
  81. WIKI.logger.error(err)
  82. if (trx) {
  83. trx.rollback()
  84. }
  85. }
  86. }
  87. static async getCode ({ cache = false } = {}) {
  88. if (cache) {
  89. const analyticsCached = await WIKI.cache.get('analytics')
  90. if (analyticsCached) {
  91. return analyticsCached
  92. }
  93. }
  94. try {
  95. const analyticsCode = {
  96. head: '',
  97. bodyStart: '',
  98. bodyEnd: ''
  99. }
  100. const providers = await WIKI.models.analytics.getProviders(true)
  101. for (let provider of providers) {
  102. const def = await fs.readFile(path.join(WIKI.SERVERPATH, 'modules/analytics', provider.key, 'code.yml'), 'utf8')
  103. let code = yaml.safeLoad(def)
  104. code.head = _.defaultTo(code.head, '')
  105. code.bodyStart = _.defaultTo(code.bodyStart, '')
  106. code.bodyEnd = _.defaultTo(code.bodyEnd, '')
  107. _.forOwn(provider.config, (value, key) => {
  108. code.head = _.replace(code.head, `{{${key}}}`, value)
  109. code.bodyStart = _.replace(code.bodyStart, `{{${key}}}`, value)
  110. code.bodyEnd = _.replace(code.bodyEnd, `{{${key}}}`, value)
  111. })
  112. analyticsCode.head += code.head
  113. analyticsCode.bodyStart += code.bodyStart
  114. analyticsCode.bodyEnd += code.bodyEnd
  115. }
  116. await WIKI.cache.set('analytics', analyticsCode, 300)
  117. return analyticsCode
  118. } catch (err) {
  119. WIKI.logger.warn('Error while getting analytics code: ', err)
  120. return {
  121. head: '',
  122. bodyStart: '',
  123. bodyEnd: ''
  124. }
  125. }
  126. }
  127. }