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.

200 lines
5.9 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 commonHelper = require('../helpers/common')
  7. /* global WIKI */
  8. /**
  9. * Storage model
  10. */
  11. module.exports = class Storage extends Model {
  12. static get tableName() { return 'storage' }
  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. mode: {type: 'string'}
  22. }
  23. }
  24. }
  25. static get jsonAttributes() {
  26. return ['config', 'state']
  27. }
  28. static async getTargets() {
  29. return WIKI.models.storage.query()
  30. }
  31. static async refreshTargetsFromDisk() {
  32. let trx
  33. try {
  34. const dbTargets = await WIKI.models.storage.query()
  35. // -> Fetch definitions from disk
  36. const storageDirs = await fs.readdir(path.join(WIKI.SERVERPATH, 'modules/storage'))
  37. let diskTargets = []
  38. for (let dir of storageDirs) {
  39. const def = await fs.readFile(path.join(WIKI.SERVERPATH, 'modules/storage', dir, 'definition.yml'), 'utf8')
  40. diskTargets.push(yaml.safeLoad(def))
  41. }
  42. WIKI.data.storage = diskTargets.map(target => ({
  43. ...target,
  44. isAvailable: _.get(target, 'isAvailable', false),
  45. props: commonHelper.parseModuleProps(target.props)
  46. }))
  47. // -> Insert new targets
  48. let newTargets = []
  49. for (let target of WIKI.data.storage) {
  50. if (!_.some(dbTargets, ['key', target.key])) {
  51. newTargets.push({
  52. key: target.key,
  53. isEnabled: false,
  54. mode: target.defaultMode || 'push',
  55. syncInterval: target.schedule || 'P0D',
  56. config: _.transform(target.props, (result, value, key) => {
  57. _.set(result, key, value.default)
  58. return result
  59. }, {}),
  60. state: {
  61. status: 'pending',
  62. message: '',
  63. lastAttempt: null
  64. }
  65. })
  66. } else {
  67. const targetConfig = _.get(_.find(dbTargets, ['key', target.key]), 'config', {})
  68. await WIKI.models.storage.query().patch({
  69. config: _.transform(target.props, (result, value, key) => {
  70. if (!_.has(result, key)) {
  71. _.set(result, key, value.default)
  72. }
  73. return result
  74. }, targetConfig)
  75. }).where('key', target.key)
  76. }
  77. }
  78. if (newTargets.length > 0) {
  79. trx = await WIKI.models.Objection.transaction.start(WIKI.models.knex)
  80. for (let target of newTargets) {
  81. await WIKI.models.storage.query(trx).insert(target)
  82. }
  83. await trx.commit()
  84. WIKI.logger.info(`Loaded ${newTargets.length} new storage targets: [ OK ]`)
  85. } else {
  86. WIKI.logger.info(`No new storage targets found: [ SKIPPED ]`)
  87. }
  88. } catch (err) {
  89. WIKI.logger.error(`Failed to scan or load new storage providers: [ FAILED ]`)
  90. WIKI.logger.error(err)
  91. if (trx) {
  92. trx.rollback()
  93. }
  94. }
  95. }
  96. /**
  97. * Initialize active storage targets
  98. */
  99. static async initTargets() {
  100. this.targets = await WIKI.models.storage.query().where('isEnabled', true).orderBy('key')
  101. try {
  102. // -> Stop and delete existing jobs
  103. const prevjobs = _.remove(WIKI.scheduler.jobs, job => job.name === `sync-storage`)
  104. if (prevjobs.length > 0) {
  105. prevjobs.forEach(job => job.stop())
  106. }
  107. // -> Initialize targets
  108. for (let target of this.targets) {
  109. const targetDef = _.find(WIKI.data.storage, ['key', target.key])
  110. target.fn = require(`../modules/storage/${target.key}/storage`)
  111. target.fn.config = target.config
  112. target.fn.mode = target.mode
  113. try {
  114. await target.fn.init()
  115. // -> Save succeeded init state
  116. await WIKI.models.storage.query().patch({
  117. state: {
  118. status: 'operational',
  119. message: '',
  120. lastAttempt: new Date().toISOString()
  121. }
  122. }).where('key', target.key)
  123. // -> Set recurring sync job
  124. if (targetDef.schedule && target.syncInterval !== `P0D`) {
  125. WIKI.scheduler.registerJob({
  126. name: `sync-storage`,
  127. immediate: false,
  128. schedule: target.syncInterval,
  129. repeat: true
  130. }, target.key)
  131. }
  132. // -> Set internal recurring sync job
  133. if (targetDef.intervalSchedule && targetDef.intervalSchedule !== `P0D`) {
  134. WIKI.scheduler.registerJob({
  135. name: `sync-storage`,
  136. immediate: false,
  137. schedule: target.intervalSchedule,
  138. repeat: true
  139. }, target.key)
  140. }
  141. } catch (err) {
  142. // -> Save initialization error
  143. await WIKI.models.storage.query().patch({
  144. state: {
  145. status: 'error',
  146. message: err.message,
  147. lastAttempt: new Date().toISOString()
  148. }
  149. }).where('key', target.key)
  150. }
  151. }
  152. } catch (err) {
  153. WIKI.logger.warn(err)
  154. throw err
  155. }
  156. }
  157. static async pageEvent({ event, page }) {
  158. try {
  159. for (let target of this.targets) {
  160. await target.fn[event](page)
  161. }
  162. } catch (err) {
  163. WIKI.logger.warn(err)
  164. throw err
  165. }
  166. }
  167. static async executeAction(targetKey, handler) {
  168. try {
  169. const target = _.find(this.targets, ['key', targetKey])
  170. if (target) {
  171. if (_.has(target.fn, handler)) {
  172. await target.fn[handler]()
  173. } else {
  174. throw new Error('Invalid Handler for Storage Target')
  175. }
  176. } else {
  177. throw new Error('Invalid or Inactive Storage Target')
  178. }
  179. } catch (err) {
  180. WIKI.logger.warn(err)
  181. throw err
  182. }
  183. }
  184. }