storage.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. const { BlobServiceClient, StorageSharedKeyCredential } = require('@azure/storage-blob')
  2. const stream = require('node:stream')
  3. const util = require('node:util')
  4. const pipeline = util.promisify(stream.pipeline)
  5. const pageHelper = require('../../../helpers/page.js')
  6. const _ = require('lodash')
  7. const getFilePath = (page, pathKey) => {
  8. const fileName = `${page[pathKey]}.${pageHelper.getFileExtension(page.contentType)}`
  9. const withLocaleCode = WIKI.config.lang.namespacing && WIKI.config.lang.code !== page.localeCode
  10. return withLocaleCode ? `${page.localeCode}/${fileName}` : fileName
  11. }
  12. module.exports = {
  13. async activated() {
  14. },
  15. async deactivated() {
  16. },
  17. async init() {
  18. WIKI.logger.info(`(STORAGE/AZURE) Initializing...`)
  19. const { accountName, accountKey, containerName } = this.config
  20. this.client = new BlobServiceClient(
  21. `https://${accountName}.blob.core.windows.net`,
  22. new StorageSharedKeyCredential(accountName, accountKey)
  23. )
  24. this.container = this.client.getContainerClient(containerName)
  25. try {
  26. await this.container.create()
  27. } catch (err) {
  28. if (err.statusCode !== 409) {
  29. WIKI.logger.warn(err)
  30. throw err
  31. }
  32. }
  33. WIKI.logger.info(`(STORAGE/AZURE) Initialization completed.`)
  34. },
  35. async created (page) {
  36. WIKI.logger.info(`(STORAGE/AZURE) Creating file ${page.path}...`)
  37. const filePath = getFilePath(page, 'path')
  38. const pageContent = page.injectMetadata()
  39. const blockBlobClient = this.container.getBlockBlobClient(filePath)
  40. await blockBlobClient.upload(pageContent, pageContent.length, { tier: this.config.storageTier })
  41. },
  42. async updated (page) {
  43. WIKI.logger.info(`(STORAGE/AZURE) Updating file ${page.path}...`)
  44. const filePath = getFilePath(page, 'path')
  45. const pageContent = page.injectMetadata()
  46. const blockBlobClient = this.container.getBlockBlobClient(filePath)
  47. await blockBlobClient.upload(pageContent, pageContent.length, { tier: this.config.storageTier })
  48. },
  49. async deleted (page) {
  50. WIKI.logger.info(`(STORAGE/AZURE) Deleting file ${page.path}...`)
  51. const filePath = getFilePath(page, 'path')
  52. const blockBlobClient = this.container.getBlockBlobClient(filePath)
  53. await blockBlobClient.delete({
  54. deleteSnapshots: 'include'
  55. })
  56. },
  57. async renamed(page) {
  58. WIKI.logger.info(`(STORAGE/${this.storageName}) 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. const sourceBlockBlobClient = this.container.getBlockBlobClient(sourceFilePath)
  70. const destBlockBlobClient = this.container.getBlockBlobClient(destinationFilePath)
  71. await destBlockBlobClient.syncCopyFromURL(sourceBlockBlobClient.url)
  72. await sourceBlockBlobClient.delete({
  73. deleteSnapshots: 'include'
  74. })
  75. },
  76. /**
  77. * ASSET UPLOAD
  78. *
  79. * @param {Object} asset Asset to upload
  80. */
  81. async assetUploaded (asset) {
  82. WIKI.logger.info(`(STORAGE/AZURE) Creating new file ${asset.path}...`)
  83. const blockBlobClient = this.container.getBlockBlobClient(asset.path)
  84. await blockBlobClient.upload(asset.data, asset.data.length, { tier: this.config.storageTier })
  85. },
  86. /**
  87. * ASSET DELETE
  88. *
  89. * @param {Object} asset Asset to delete
  90. */
  91. async assetDeleted (asset) {
  92. WIKI.logger.info(`(STORAGE/AZURE) Deleting file ${asset.path}...`)
  93. const blockBlobClient = this.container.getBlockBlobClient(asset.path)
  94. await blockBlobClient.delete({
  95. deleteSnapshots: 'include'
  96. })
  97. },
  98. /**
  99. * ASSET RENAME
  100. *
  101. * @param {Object} asset Asset to rename
  102. */
  103. async assetRenamed (asset) {
  104. WIKI.logger.info(`(STORAGE/AZURE) Renaming file from ${asset.path} to ${asset.destinationPath}...`)
  105. const sourceBlockBlobClient = this.container.getBlockBlobClient(asset.path)
  106. const destBlockBlobClient = this.container.getBlockBlobClient(asset.destinationPath)
  107. await destBlockBlobClient.syncCopyFromURL(sourceBlockBlobClient.url)
  108. await sourceBlockBlobClient.delete({
  109. deleteSnapshots: 'include'
  110. })
  111. },
  112. async getLocalLocation () {
  113. },
  114. /**
  115. * HANDLERS
  116. */
  117. async exportAll() {
  118. WIKI.logger.info(`(STORAGE/AZURE) Exporting all content to Azure Blob Storage...`)
  119. // -> Pages
  120. await pipeline(
  121. WIKI.db.knex.column('path', 'localeCode', 'title', 'description', 'contentType', 'content', 'isPublished', 'updatedAt', 'createdAt').select().from('pages').where({
  122. isPrivate: false
  123. }).stream(),
  124. new stream.Transform({
  125. objectMode: true,
  126. transform: async (page, enc, cb) => {
  127. const filePath = getFilePath(page, 'path')
  128. WIKI.logger.info(`(STORAGE/AZURE) Adding page ${filePath}...`)
  129. const pageContent = pageHelper.injectPageMetadata(page)
  130. const blockBlobClient = this.container.getBlockBlobClient(filePath)
  131. await blockBlobClient.upload(pageContent, pageContent.length, { tier: this.config.storageTier })
  132. cb()
  133. }
  134. })
  135. )
  136. // -> Assets
  137. const assetFolders = await WIKI.db.assetFolders.getAllPaths()
  138. await pipeline(
  139. WIKI.db.knex.column('filename', 'folderId', 'data').select().from('assets').join('assetData', 'assets.id', '=', 'assetData.id').stream(),
  140. new stream.Transform({
  141. objectMode: true,
  142. transform: async (asset, enc, cb) => {
  143. const filename = (asset.folderId && asset.folderId > 0) ? `${_.get(assetFolders, asset.folderId)}/${asset.filename}` : asset.filename
  144. WIKI.logger.info(`(STORAGE/AZURE) Adding asset ${filename}...`)
  145. const blockBlobClient = this.container.getBlockBlobClient(filename)
  146. await blockBlobClient.upload(asset.data, asset.data.length, { tier: this.config.storageTier })
  147. cb()
  148. }
  149. })
  150. )
  151. WIKI.logger.info('(STORAGE/AZURE) All content has been pushed to Azure Blob Storage.')
  152. }
  153. }