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.

160 lines
6.0 KiB

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