gcs.js 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. const logger = require('@alias/logger')('growi:service:fileUploaderAws');
  2. const urljoin = require('url-join');
  3. const { Storage } = require('@google-cloud/storage');
  4. let _instance;
  5. module.exports = function(crowi) {
  6. const Uploader = require('./uploader');
  7. const { configManager } = crowi;
  8. const lib = new Uploader(configManager);
  9. function getGcsBucket() {
  10. return configManager.getConfig('crowi', 'gcs:bucket');
  11. }
  12. function getGcsInstance(isUploadable) {
  13. if (!isUploadable) {
  14. throw new Error('GCS is not configured.');
  15. }
  16. if (_instance == null) {
  17. const keyFilename = configManager.getConfig('crowi', 'gcs:apiKeyJsonPath');
  18. // see https://googleapis.dev/nodejs/storage/latest/Storage.html
  19. _instance = new Storage({ keyFilename });
  20. }
  21. return _instance;
  22. }
  23. function getFilePathOnStorage(attachment) {
  24. const namespace = configManager.getConfig('crowi', 'gcs:uploadNamespace');
  25. // const namespace = null;
  26. const dirName = (attachment.page != null)
  27. ? 'attachment'
  28. : 'user';
  29. const filePath = urljoin(namespace || '', dirName, attachment.fileName);
  30. return filePath;
  31. }
  32. lib.getIsUploadable = function() {
  33. return this.configManager.getConfig('crowi', 'gcs:apiKeyJsonPath') != null && this.configManager.getConfig('crowi', 'gcs:bucket') != null;
  34. };
  35. lib.deleteFile = async function(attachment) {
  36. const filePath = getFilePathOnStorage(attachment);
  37. return lib.deleteFileByFilePath(filePath);
  38. };
  39. lib.deleteFileByFilePath = async function(filePath) {
  40. const gcs = getGcsInstance(this.getIsUploadable());
  41. const myBucket = gcs.bucket(getGcsBucket());
  42. // TODO: ensure not to throw error even when the file does not exist
  43. return myBucket.file(filePath).delete();
  44. };
  45. lib.uploadFile = function(fileStream, attachment) {
  46. logger.debug(`File uploading: fileName=${attachment.fileName}`);
  47. const gcs = getGcsInstance(this.getIsUploadable());
  48. const myBucket = gcs.bucket(getGcsBucket());
  49. const filePath = getFilePathOnStorage(attachment);
  50. const options = {
  51. destination: filePath,
  52. };
  53. return myBucket.upload(fileStream.path, options);
  54. };
  55. /**
  56. * Find data substance
  57. *
  58. * @param {Attachment} attachment
  59. * @return {stream.Readable} readable stream
  60. */
  61. lib.findDeliveryFile = async function(attachment) {
  62. const gcs = getGcsInstance(this.getIsUploadable());
  63. const myBucket = gcs.bucket(getGcsBucket());
  64. const filePath = getFilePathOnStorage(attachment);
  65. let stream;
  66. try {
  67. stream = myBucket.file(filePath).createReadStream();
  68. }
  69. catch (err) {
  70. logger.error(err);
  71. throw new Error(`Coudn't get file from AWS for the Attachment (${attachment._id.toString()})`);
  72. }
  73. // return stream.Readable
  74. return stream;
  75. };
  76. /**
  77. * check the file size limit
  78. *
  79. * In detail, the followings are checked.
  80. * - per-file size limit (specified by MAX_FILE_SIZE)
  81. */
  82. lib.checkLimit = async(uploadFileSize) => {
  83. const maxFileSize = crowi.configManager.getConfig('crowi', 'app:maxFileSize');
  84. if (uploadFileSize > maxFileSize) {
  85. return { isUploadable: false, errorMessage: 'File size exceeds the size limit per file' };
  86. }
  87. const Attachment = crowi.model('Attachment');
  88. // Get attachment total file size
  89. const res = await Attachment.aggregate().group({
  90. _id: null,
  91. total: { $sum: '$fileSize' },
  92. });
  93. const usingFilesSize = res[0].total;
  94. const gcsTotalLimit = crowi.configManager.getConfig('crowi', 'app:fileUploadTotalLimit');
  95. if (usingFilesSize + uploadFileSize > gcsTotalLimit) {
  96. return { isUploadable: false, errorMessage: 'GCS for uploading files reaches limit' };
  97. }
  98. return { isUploadable: true };
  99. };
  100. return lib;
  101. };