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.

236 lines
6.8 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. // -> Delete removed targets
  89. for (const target of dbTargets) {
  90. if (!_.some(WIKI.data.storage, ['key', target.key])) {
  91. await WIKI.models.storage.query().where('key', target.key).del()
  92. WIKI.logger.info(`Removed target ${target.key} because it is no longer present in the modules folder: [ OK ]`)
  93. }
  94. }
  95. } catch (err) {
  96. WIKI.logger.error(`Failed to scan or load new storage providers: [ FAILED ]`)
  97. WIKI.logger.error(err)
  98. if (trx) {
  99. trx.rollback()
  100. }
  101. }
  102. }
  103. /**
  104. * Initialize active storage targets
  105. */
  106. static async initTargets() {
  107. this.targets = await WIKI.models.storage.query().where('isEnabled', true).orderBy('key')
  108. try {
  109. // -> Stop and delete existing jobs
  110. const prevjobs = _.remove(WIKI.scheduler.jobs, job => job.name === `sync-storage`)
  111. if (prevjobs.length > 0) {
  112. prevjobs.forEach(job => job.stop())
  113. }
  114. // -> Initialize targets
  115. for (let target of this.targets) {
  116. const targetDef = _.find(WIKI.data.storage, ['key', target.key])
  117. target.fn = require(`../modules/storage/${target.key}/storage`)
  118. target.fn.config = target.config
  119. target.fn.mode = target.mode
  120. try {
  121. await target.fn.init()
  122. // -> Save succeeded init state
  123. await WIKI.models.storage.query().patch({
  124. state: {
  125. status: 'operational',
  126. message: '',
  127. lastAttempt: new Date().toISOString()
  128. }
  129. }).where('key', target.key)
  130. // -> Set recurring sync job
  131. if (targetDef.schedule && target.syncInterval !== `P0D`) {
  132. WIKI.scheduler.registerJob({
  133. name: `sync-storage`,
  134. immediate: false,
  135. schedule: target.syncInterval,
  136. repeat: true
  137. }, target.key)
  138. }
  139. // -> Set internal recurring sync job
  140. if (targetDef.internalSchedule && targetDef.internalSchedule !== `P0D`) {
  141. WIKI.scheduler.registerJob({
  142. name: `sync-storage`,
  143. immediate: false,
  144. schedule: target.internalSchedule,
  145. repeat: true
  146. }, target.key)
  147. }
  148. } catch (err) {
  149. // -> Save initialization error
  150. await WIKI.models.storage.query().patch({
  151. state: {
  152. status: 'error',
  153. message: err.message,
  154. lastAttempt: new Date().toISOString()
  155. }
  156. }).where('key', target.key)
  157. }
  158. }
  159. } catch (err) {
  160. WIKI.logger.warn(err)
  161. throw err
  162. }
  163. }
  164. static async pageEvent({ event, page }) {
  165. try {
  166. for (let target of this.targets) {
  167. await target.fn[event](page)
  168. }
  169. } catch (err) {
  170. WIKI.logger.warn(err)
  171. throw err
  172. }
  173. }
  174. static async assetEvent({ event, asset }) {
  175. try {
  176. for (let target of this.targets) {
  177. await target.fn[`asset${_.capitalize(event)}`](asset)
  178. }
  179. } catch (err) {
  180. WIKI.logger.warn(err)
  181. throw err
  182. }
  183. }
  184. static async getLocalLocations({ asset }) {
  185. const locations = []
  186. const promises = this.targets.map(async (target) => {
  187. try {
  188. const path = await target.fn.getLocalLocation(asset)
  189. locations.push({
  190. path,
  191. key: target.key
  192. })
  193. } catch (err) {
  194. WIKI.logger.warn(err)
  195. }
  196. })
  197. await Promise.all(promises)
  198. return locations
  199. }
  200. static async executeAction(targetKey, handler) {
  201. try {
  202. const target = _.find(this.targets, ['key', targetKey])
  203. if (target) {
  204. if (_.hasIn(target.fn, handler)) {
  205. await target.fn[handler]()
  206. } else {
  207. throw new Error('Invalid Handler for Storage Target')
  208. }
  209. } else {
  210. throw new Error('Invalid or Inactive Storage Target')
  211. }
  212. } catch (err) {
  213. WIKI.logger.warn(err)
  214. throw err
  215. }
  216. }
  217. }