gcs.js 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. import loggerFactory from '~/utils/logger';
  2. const logger = loggerFactory('growi:service:fileUploaderAws');
  3. const { Storage } = require('@google-cloud/storage');
  4. const urljoin = require('url-join');
  5. let _instance;
  6. module.exports = function(crowi) {
  7. const Uploader = require('./uploader');
  8. const { configManager } = crowi;
  9. const lib = new Uploader(crowi);
  10. function getGcsBucket() {
  11. return configManager.getConfig('crowi', 'gcs:bucket');
  12. }
  13. function getGcsInstance() {
  14. if (_instance == null) {
  15. const keyFilename = configManager.getConfig('crowi', 'gcs:apiKeyJsonPath');
  16. // see https://googleapis.dev/nodejs/storage/latest/Storage.html
  17. _instance = keyFilename != null
  18. ? new Storage({ keyFilename }) // Create a client with explicit credentials
  19. : new Storage(); // Create a client that uses Application Default Credentials
  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. /**
  33. * check file existence
  34. * @param {File} file https://googleapis.dev/nodejs/storage/latest/File.html
  35. */
  36. async function isFileExists(file) {
  37. // check file exists
  38. const res = await file.exists();
  39. return res[0];
  40. }
  41. lib.isValidUploadSettings = function() {
  42. return this.configManager.getConfig('crowi', 'gcs:apiKeyJsonPath') != null
  43. && this.configManager.getConfig('crowi', 'gcs:bucket') != null;
  44. };
  45. lib.canRespond = function() {
  46. return !this.configManager.getConfig('crowi', 'gcs:referenceFileWithRelayMode');
  47. };
  48. lib.respond = async function(res, attachment) {
  49. if (!this.getIsUploadable()) {
  50. throw new Error('GCS is not configured.');
  51. }
  52. const temporaryUrl = attachment.getValidTemporaryUrl();
  53. if (temporaryUrl != null) {
  54. return res.redirect(temporaryUrl);
  55. }
  56. const gcs = getGcsInstance();
  57. const myBucket = gcs.bucket(getGcsBucket());
  58. const filePath = getFilePathOnStorage(attachment);
  59. const file = myBucket.file(filePath);
  60. const lifetimeSecForTemporaryUrl = this.configManager.getConfig('crowi', 'gcs:lifetimeSecForTemporaryUrl');
  61. // issue signed url (default: expires 120 seconds)
  62. // https://cloud.google.com/storage/docs/access-control/signed-urls
  63. const [signedUrl] = await file.getSignedUrl({
  64. action: 'read',
  65. expires: Date.now() + lifetimeSecForTemporaryUrl * 1000,
  66. });
  67. res.redirect(signedUrl);
  68. try {
  69. return attachment.cashTemporaryUrlByProvideSec(signedUrl, lifetimeSecForTemporaryUrl);
  70. }
  71. catch (err) {
  72. logger.error(err);
  73. }
  74. };
  75. lib.deleteFile = function(attachment) {
  76. const filePath = getFilePathOnStorage(attachment);
  77. return lib.deleteFilesByFilePaths([filePath]);
  78. };
  79. lib.deleteFiles = function(attachments) {
  80. const filePaths = attachments.map((attachment) => {
  81. return getFilePathOnStorage(attachment);
  82. });
  83. return lib.deleteFilesByFilePaths(filePaths);
  84. };
  85. lib.deleteFilesByFilePaths = function(filePaths) {
  86. if (!this.getIsUploadable()) {
  87. throw new Error('GCS is not configured.');
  88. }
  89. const gcs = getGcsInstance();
  90. const myBucket = gcs.bucket(getGcsBucket());
  91. const files = filePaths.map((filePath) => {
  92. return myBucket.file(filePath);
  93. });
  94. files.forEach((file) => {
  95. file.delete({ ignoreNotFound: true });
  96. });
  97. };
  98. lib.uploadFile = function(fileStream, attachment) {
  99. if (!this.getIsUploadable()) {
  100. throw new Error('GCS is not configured.');
  101. }
  102. logger.debug(`File uploading: fileName=${attachment.fileName}`);
  103. const gcs = getGcsInstance();
  104. const myBucket = gcs.bucket(getGcsBucket());
  105. const filePath = getFilePathOnStorage(attachment);
  106. const options = {
  107. destination: filePath,
  108. };
  109. return myBucket.upload(fileStream.path, options);
  110. };
  111. /**
  112. * Find data substance
  113. *
  114. * @param {Attachment} attachment
  115. * @return {stream.Readable} readable stream
  116. */
  117. lib.findDeliveryFile = async function(attachment) {
  118. if (!this.getIsReadable()) {
  119. throw new Error('GCS is not configured.');
  120. }
  121. const gcs = getGcsInstance();
  122. const myBucket = gcs.bucket(getGcsBucket());
  123. const filePath = getFilePathOnStorage(attachment);
  124. const file = myBucket.file(filePath);
  125. // check file exists
  126. const isExists = await isFileExists(file);
  127. if (!isExists) {
  128. throw new Error(`Any object that relate to the Attachment (${filePath}) does not exist in GCS`);
  129. }
  130. let stream;
  131. try {
  132. stream = file.createReadStream();
  133. }
  134. catch (err) {
  135. logger.error(err);
  136. throw new Error(`Coudn't get file from AWS for the Attachment (${attachment._id.toString()})`);
  137. }
  138. // return stream.Readable
  139. return stream;
  140. };
  141. /**
  142. * check the file size limit
  143. *
  144. * In detail, the followings are checked.
  145. * - per-file size limit (specified by MAX_FILE_SIZE)
  146. */
  147. lib.checkLimit = async(uploadFileSize) => {
  148. const maxFileSize = crowi.configManager.getConfig('crowi', 'app:maxFileSize');
  149. const gcsTotalLimit = crowi.configManager.getConfig('crowi', 'app:fileUploadTotalLimit');
  150. return lib.doCheckLimit(uploadFileSize, maxFileSize, gcsTotalLimit);
  151. };
  152. return lib;
  153. };