storage.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. const SSH2Promise = require('ssh2-promise')
  2. const _ = require('lodash')
  3. const path = require('node:path')
  4. const stream = require('node:stream')
  5. const util = require('node:util')
  6. const pipeline = util.promisify(stream.pipeline)
  7. const pageHelper = require('../../../helpers/page.js')
  8. const getFilePath = (page, pathKey) => {
  9. const fileName = `${page[pathKey]}.${pageHelper.getFileExtension(page.contentType)}`
  10. const withLocaleCode = WIKI.config.lang.namespacing && WIKI.config.lang.code !== page.localeCode
  11. return withLocaleCode ? `${page.localeCode}/${fileName}` : fileName
  12. }
  13. module.exports = {
  14. client: null,
  15. sftp: null,
  16. async activated() {
  17. },
  18. async deactivated() {
  19. },
  20. async init() {
  21. WIKI.logger.info(`(STORAGE/SFTP) Initializing...`)
  22. this.client = new SSH2Promise({
  23. host: this.config.host,
  24. port: this.config.port || 22,
  25. username: this.config.username,
  26. password: (this.config.authMode === 'password') ? this.config.password : null,
  27. privateKey: (this.config.authMode === 'privateKey') ? this.config.privateKey : null,
  28. passphrase: (this.config.authMode === 'privateKey') ? this.config.passphrase : null
  29. })
  30. await this.client.connect()
  31. this.sftp = this.client.sftp()
  32. try {
  33. await this.sftp.readdir(this.config.basePath)
  34. } catch (err) {
  35. WIKI.logger.warn(`(STORAGE/SFTP) ${err.message}`)
  36. throw new Error(`Unable to read specified base directory: ${err.message}`)
  37. }
  38. WIKI.logger.info(`(STORAGE/SFTP) Initialization completed.`)
  39. },
  40. async created(page) {
  41. WIKI.logger.info(`(STORAGE/SFTP) Creating file ${page.path}...`)
  42. const filePath = getFilePath(page, 'path')
  43. await this.ensureDirectory(filePath)
  44. await this.sftp.writeFile(path.posix.join(this.config.basePath, filePath), page.injectMetadata())
  45. },
  46. async updated(page) {
  47. WIKI.logger.info(`(STORAGE/SFTP) Updating file ${page.path}...`)
  48. const filePath = getFilePath(page, 'path')
  49. await this.ensureDirectory(filePath)
  50. await this.sftp.writeFile(path.posix.join(this.config.basePath, filePath), page.injectMetadata())
  51. },
  52. async deleted(page) {
  53. WIKI.logger.info(`(STORAGE/SFTP) Deleting file ${page.path}...`)
  54. const filePath = getFilePath(page, 'path')
  55. await this.sftp.unlink(path.posix.join(this.config.basePath, filePath))
  56. },
  57. async renamed(page) {
  58. WIKI.logger.info(`(STORAGE/SFTP) Renaming file ${page.path} to ${page.destinationPath}...`)
  59. let sourceFilePath = getFilePath(page, 'path')
  60. let destinationFilePath = getFilePath(page, 'destinationPath')
  61. if (WIKI.config.lang.namespacing) {
  62. if (WIKI.config.lang.code !== page.localeCode) {
  63. sourceFilePath = `${page.localeCode}/${sourceFilePath}`
  64. }
  65. if (WIKI.config.lang.code !== page.destinationLocaleCode) {
  66. destinationFilePath = `${page.destinationLocaleCode}/${destinationFilePath}`
  67. }
  68. }
  69. await this.ensureDirectory(destinationFilePath)
  70. await this.sftp.rename(path.posix.join(this.config.basePath, sourceFilePath), path.posix.join(this.config.basePath, destinationFilePath))
  71. },
  72. /**
  73. * ASSET UPLOAD
  74. *
  75. * @param {Object} asset Asset to upload
  76. */
  77. async assetUploaded (asset) {
  78. WIKI.logger.info(`(STORAGE/SFTP) Creating new file ${asset.path}...`)
  79. await this.ensureDirectory(asset.path)
  80. await this.sftp.writeFile(path.posix.join(this.config.basePath, asset.path), asset.data)
  81. },
  82. /**
  83. * ASSET DELETE
  84. *
  85. * @param {Object} asset Asset to delete
  86. */
  87. async assetDeleted (asset) {
  88. WIKI.logger.info(`(STORAGE/SFTP) Deleting file ${asset.path}...`)
  89. await this.sftp.unlink(path.posix.join(this.config.basePath, asset.path))
  90. },
  91. /**
  92. * ASSET RENAME
  93. *
  94. * @param {Object} asset Asset to rename
  95. */
  96. async assetRenamed (asset) {
  97. WIKI.logger.info(`(STORAGE/SFTP) Renaming file from ${asset.path} to ${asset.destinationPath}...`)
  98. await this.ensureDirectory(asset.destinationPath)
  99. await this.sftp.rename(path.posix.join(this.config.basePath, asset.path), path.posix.join(this.config.basePath, asset.destinationPath))
  100. },
  101. async getLocalLocation () {
  102. },
  103. /**
  104. * HANDLERS
  105. */
  106. async exportAll() {
  107. WIKI.logger.info(`(STORAGE/SFTP) Exporting all content to the remote server...`)
  108. // -> Pages
  109. await pipeline(
  110. WIKI.db.knex.column('path', 'localeCode', 'title', 'description', 'contentType', 'content', 'isPublished', 'updatedAt', 'createdAt').select().from('pages').where({
  111. isPrivate: false
  112. }).stream(),
  113. new stream.Transform({
  114. objectMode: true,
  115. transform: async (page, enc, cb) => {
  116. const filePath = getFilePath(page, 'path')
  117. WIKI.logger.info(`(STORAGE/SFTP) Adding page ${filePath}...`)
  118. await this.ensureDirectory(filePath)
  119. await this.sftp.writeFile(path.posix.join(this.config.basePath, filePath), pageHelper.injectPageMetadata(page))
  120. cb()
  121. }
  122. })
  123. )
  124. // -> Assets
  125. const assetFolders = await WIKI.db.assetFolders.getAllPaths()
  126. await pipeline(
  127. WIKI.db.knex.column('filename', 'folderId', 'data').select().from('assets').join('assetData', 'assets.id', '=', 'assetData.id').stream(),
  128. new stream.Transform({
  129. objectMode: true,
  130. transform: async (asset, enc, cb) => {
  131. const filename = (asset.folderId && asset.folderId > 0) ? `${_.get(assetFolders, asset.folderId)}/${asset.filename}` : asset.filename
  132. WIKI.logger.info(`(STORAGE/SFTP) Adding asset ${filename}...`)
  133. await this.ensureDirectory(filename)
  134. await this.sftp.writeFile(path.posix.join(this.config.basePath, filename), asset.data)
  135. cb()
  136. }
  137. })
  138. )
  139. WIKI.logger.info('(STORAGE/SFTP) All content has been pushed to the remote server.')
  140. },
  141. async ensureDirectory(filePath) {
  142. if (filePath.indexOf('/') >= 0) {
  143. try {
  144. const folderPaths = _.dropRight(filePath.split('/'))
  145. for (let i = 1; i <= folderPaths.length; i++) {
  146. const folderSection = _.take(folderPaths, i).join('/')
  147. await this.sftp.mkdir(path.posix.join(this.config.basePath, folderSection))
  148. }
  149. } catch (err) {}
  150. }
  151. }
  152. }