common.js 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. const S3 = require('aws-sdk/clients/s3')
  2. const stream = require('stream')
  3. const Promise = require('bluebird')
  4. const pipeline = Promise.promisify(stream.pipeline)
  5. const _ = require('lodash')
  6. const pageHelper = require('../../../helpers/page.js')
  7. /* global WIKI */
  8. /**
  9. * Deduce the file path given the `page` object and the object's key to the page's path.
  10. */
  11. const getFilePath = (page, pathKey) => {
  12. const fileName = `${page[pathKey]}.${pageHelper.getFileExtension(page.contentType)}`
  13. const withLocaleCode = WIKI.config.lang.namespacing && WIKI.config.lang.code !== page.localeCode
  14. return withLocaleCode ? `${page.localeCode}/${fileName}` : fileName
  15. }
  16. /**
  17. * Can be used with S3 compatible storage.
  18. */
  19. module.exports = class S3CompatibleStorage {
  20. constructor(storageName) {
  21. this.storageName = storageName
  22. }
  23. async activated() {
  24. // not used
  25. }
  26. async deactivated() {
  27. // not used
  28. }
  29. async init() {
  30. WIKI.logger.info(`(STORAGE/${this.storageName}) Initializing...`)
  31. const { accessKeyId, secretAccessKey, bucket } = this.config
  32. const s3Config = {
  33. accessKeyId,
  34. secretAccessKey,
  35. params: { Bucket: bucket },
  36. apiVersions: '2006-03-01'
  37. }
  38. if (!_.isNil(this.config.region)) {
  39. s3Config.region = this.config.region
  40. }
  41. if (!_.isNil(this.config.endpoint)) {
  42. s3Config.endpoint = this.config.endpoint
  43. }
  44. if (!_.isNil(this.config.sslEnabled)) {
  45. s3Config.sslEnabled = this.config.sslEnabled
  46. }
  47. if (!_.isNil(this.config.s3ForcePathStyle)) {
  48. s3Config.s3ForcePathStyle = this.config.s3ForcePathStyle
  49. }
  50. if (!_.isNil(this.config.s3BucketEndpoint)) {
  51. s3Config.s3BucketEndpoint = this.config.s3BucketEndpoint
  52. }
  53. this.s3 = new S3(s3Config)
  54. // determine if a bucket exists and you have permission to access it
  55. await this.s3.headBucket().promise()
  56. WIKI.logger.info(`(STORAGE/${this.storageName}) Initialization completed.`)
  57. }
  58. async created(page) {
  59. WIKI.logger.info(`(STORAGE/${this.storageName}) Creating file ${page.path}...`)
  60. const filePath = getFilePath(page, 'path')
  61. await this.s3.putObject({ Key: filePath, Body: page.injectMetadata() }).promise()
  62. }
  63. async updated(page) {
  64. WIKI.logger.info(`(STORAGE/${this.storageName}) Updating file ${page.path}...`)
  65. const filePath = getFilePath(page, 'path')
  66. await this.s3.putObject({ Key: filePath, Body: page.injectMetadata() }).promise()
  67. }
  68. async deleted(page) {
  69. WIKI.logger.info(`(STORAGE/${this.storageName}) Deleting file ${page.path}...`)
  70. const filePath = getFilePath(page, 'path')
  71. await this.s3.deleteObject({ Key: filePath }).promise()
  72. }
  73. async renamed(page) {
  74. WIKI.logger.info(`(STORAGE/${this.storageName}) Renaming file ${page.path} to ${page.destinationPath}...`)
  75. let sourceFilePath = getFilePath(page, 'path')
  76. let destinationFilePath = getFilePath(page, 'destinationPath')
  77. if (WIKI.config.lang.namespacing) {
  78. if (WIKI.config.lang.code !== page.localeCode) {
  79. sourceFilePath = `${page.localeCode}/${sourceFilePath}`
  80. }
  81. if (WIKI.config.lang.code !== page.destinationLocaleCode) {
  82. destinationFilePath = `${page.destinationLocaleCode}/${destinationFilePath}`
  83. }
  84. }
  85. await this.s3.copyObject({ CopySource: sourceFilePath, Key: destinationFilePath }).promise()
  86. await this.s3.deleteObject({ Key: sourceFilePath }).promise()
  87. }
  88. /**
  89. * ASSET UPLOAD
  90. *
  91. * @param {Object} asset Asset to upload
  92. */
  93. async assetUploaded (asset) {
  94. WIKI.logger.info(`(STORAGE/${this.storageName}) Creating new file ${asset.path}...`)
  95. await this.s3.putObject({ Key: asset.path, Body: asset.data }).promise()
  96. }
  97. /**
  98. * ASSET DELETE
  99. *
  100. * @param {Object} asset Asset to delete
  101. */
  102. async assetDeleted (asset) {
  103. WIKI.logger.info(`(STORAGE/${this.storageName}) Deleting file ${asset.path}...`)
  104. await this.s3.deleteObject({ Key: asset.path }).promise()
  105. }
  106. /**
  107. * ASSET RENAME
  108. *
  109. * @param {Object} asset Asset to rename
  110. */
  111. async assetRenamed (asset) {
  112. WIKI.logger.info(`(STORAGE/${this.storageName}) Renaming file from ${asset.path} to ${asset.destinationPath}...`)
  113. await this.s3.copyObject({ CopySource: asset.path, Key: asset.destinationPath }).promise()
  114. await this.s3.deleteObject({ Key: asset.path }).promise()
  115. }
  116. async getLocalLocation () {
  117. }
  118. /**
  119. * HANDLERS
  120. */
  121. async exportAll() {
  122. WIKI.logger.info(`(STORAGE/${this.storageName}) Exporting all content to the cloud provider...`)
  123. // -> Pages
  124. await pipeline(
  125. WIKI.models.knex.column('path', 'localeCode', 'title', 'description', 'contentType', 'content', 'isPublished', 'updatedAt').select().from('pages').where({
  126. isPrivate: false
  127. }).stream(),
  128. new stream.Transform({
  129. objectMode: true,
  130. transform: async (page, enc, cb) => {
  131. const filePath = getFilePath(page, 'path')
  132. WIKI.logger.info(`(STORAGE/${this.storageName}) Adding page ${filePath}...`)
  133. await this.s3.putObject({ Key: filePath, Body: pageHelper.injectPageMetadata(page) }).promise()
  134. cb()
  135. }
  136. })
  137. )
  138. // -> Assets
  139. const assetFolders = await WIKI.models.assetFolders.getAllPaths()
  140. await pipeline(
  141. WIKI.models.knex.column('filename', 'folderId', 'data').select().from('assets').join('assetData', 'assets.id', '=', 'assetData.id').stream(),
  142. new stream.Transform({
  143. objectMode: true,
  144. transform: async (asset, enc, cb) => {
  145. const filename = (asset.folderId && asset.folderId > 0) ? `${_.get(assetFolders, asset.folderId)}/${asset.filename}` : asset.filename
  146. WIKI.logger.info(`(STORAGE/${this.storageName}) Adding asset ${filename}...`)
  147. await this.s3.putObject({ Key: filename, Body: asset.data }).promise()
  148. cb()
  149. }
  150. })
  151. )
  152. WIKI.logger.info(`(STORAGE/${this.storageName}) All content has been pushed to the cloud provider.`)
  153. }
  154. }