gcs.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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 configManager.getConfig('crowi', 'gcs:apiKeyJsonPath') != null
  43. && configManager.getConfig('crowi', 'gcs:bucket') != null;
  44. };
  45. lib.canRespond = function() {
  46. return !configManager.getConfig('crowi', 'gcs:referenceFileWithRelayMode');
  47. };
  48. lib.respond = async function(res, attachment) {
  49. if (!lib.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 = 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 (!lib.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.uploadAttachment = function(fileStream, attachment) {
  99. if (!lib.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. lib.saveFile = async function({ filePath, contentType, data }) {
  112. const gcs = getGcsInstance();
  113. const myBucket = gcs.bucket(getGcsBucket());
  114. return myBucket.file(filePath).save(data, { resumable: false });
  115. };
  116. /**
  117. * Find data substance
  118. *
  119. * @param {Attachment} attachment
  120. * @return {stream.Readable} readable stream
  121. */
  122. lib.findDeliveryFile = async function(attachment) {
  123. if (!lib.getIsReadable()) {
  124. throw new Error('GCS is not configured.');
  125. }
  126. const gcs = getGcsInstance();
  127. const myBucket = gcs.bucket(getGcsBucket());
  128. const filePath = getFilePathOnStorage(attachment);
  129. const file = myBucket.file(filePath);
  130. // check file exists
  131. const isExists = await isFileExists(file);
  132. if (!isExists) {
  133. throw new Error(`Any object that relate to the Attachment (${filePath}) does not exist in GCS`);
  134. }
  135. let stream;
  136. try {
  137. stream = file.createReadStream();
  138. }
  139. catch (err) {
  140. logger.error(err);
  141. throw new Error(`Coudn't get file from AWS for the Attachment (${attachment._id.toString()})`);
  142. }
  143. // return stream.Readable
  144. return stream;
  145. };
  146. /**
  147. * check the file size limit
  148. *
  149. * In detail, the followings are checked.
  150. * - per-file size limit (specified by MAX_FILE_SIZE)
  151. */
  152. lib.checkLimit = async function(uploadFileSize) {
  153. const maxFileSize = configManager.getConfig('crowi', 'app:maxFileSize');
  154. const gcsTotalLimit = configManager.getConfig('crowi', 'app:fileUploadTotalLimit');
  155. return lib.doCheckLimit(uploadFileSize, maxFileSize, gcsTotalLimit);
  156. };
  157. /**
  158. * List files in storage
  159. */
  160. lib.listFiles = async function() {
  161. if (!lib.getIsReadable()) {
  162. throw new Error('GCS is not configured.');
  163. }
  164. const gcs = getGcsInstance();
  165. const bucket = gcs.bucket(getGcsBucket());
  166. const [files] = await bucket.getFiles({
  167. prefix: configManager.getConfig('crowi', 'gcs:uploadNamespace'),
  168. });
  169. return files.map(({ name, metadata: { size } }) => {
  170. return { name, size };
  171. });
  172. };
  173. return lib;
  174. };