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.

168 lines
6.2 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. async getLocalLocation () {
  103. },
  104. /**
  105. * HANDLERS
  106. */
  107. async exportAll() {
  108. WIKI.logger.info(`(STORAGE/SFTP) Exporting all content to the remote server...`)
  109. // -> Pages
  110. await pipeline(
  111. WIKI.models.knex.column('path', 'localeCode', 'title', 'description', 'contentType', 'content', 'isPublished', 'updatedAt', 'createdAt').select().from('pages').where({
  112. isPrivate: false
  113. }).stream(),
  114. new stream.Transform({
  115. objectMode: true,
  116. transform: async (page, enc, cb) => {
  117. const filePath = getFilePath(page, 'path')
  118. WIKI.logger.info(`(STORAGE/SFTP) Adding page ${filePath}...`)
  119. await this.ensureDirectory(filePath)
  120. await this.sftp.writeFile(path.posix.join(this.config.basePath, filePath), pageHelper.injectPageMetadata(page))
  121. cb()
  122. }
  123. })
  124. )
  125. // -> Assets
  126. const assetFolders = await WIKI.models.assetFolders.getAllPaths()
  127. await pipeline(
  128. WIKI.models.knex.column('filename', 'folderId', 'data').select().from('assets').join('assetData', 'assets.id', '=', 'assetData.id').stream(),
  129. new stream.Transform({
  130. objectMode: true,
  131. transform: async (asset, enc, cb) => {
  132. const filename = (asset.folderId && asset.folderId > 0) ? `${_.get(assetFolders, asset.folderId)}/${asset.filename}` : asset.filename
  133. WIKI.logger.info(`(STORAGE/SFTP) Adding asset ${filename}...`)
  134. await this.ensureDirectory(filename)
  135. await this.sftp.writeFile(path.posix.join(this.config.basePath, filename), asset.data)
  136. cb()
  137. }
  138. })
  139. )
  140. WIKI.logger.info('(STORAGE/SFTP) All content has been pushed to the remote server.')
  141. },
  142. async ensureDirectory(filePath) {
  143. if (filePath.indexOf('/') >= 0) {
  144. try {
  145. const folderPaths = _.dropRight(filePath.split('/'))
  146. for (let i = 1; i <= folderPaths.length; i++) {
  147. const folderSection = _.take(folderPaths, i).join('/')
  148. const folderDir = path.posix.join(this.config.basePath, folderSection)
  149. try {
  150. await this.sftp.readdir(folderDir)
  151. } catch (err) {
  152. await this.sftp.mkdir(folderDir)
  153. }
  154. }
  155. } catch (err) {}
  156. }
  157. }
  158. }