fileStoreStrategy.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. import fs from 'fs';
  2. import { createObjectId } from './grid/createObjectId';
  3. import { httpStreamOutput } from './httpStream.js'
  4. export const STORAGE_NAME_FILESYSTEM = "fs";
  5. export const STORAGE_NAME_GRIDFS = "gridfs";
  6. /** Factory for FileStoreStrategy */
  7. export default class FileStoreStrategyFactory {
  8. /** constructor
  9. * @param classFileStoreStrategyFilesystem use this strategy for filesystem storage
  10. * @param classFileStoreStrategyGridFs use this strategy for GridFS storage
  11. * @param gridFsBucket use this GridFS Bucket as GridFS Storage
  12. */
  13. constructor(classFileStoreStrategyFilesystem, classFileStoreStrategyGridFs, gridFsBucket) {
  14. this.classFileStoreStrategyFilesystem = classFileStoreStrategyFilesystem;
  15. this.classFileStoreStrategyGridFs = classFileStoreStrategyGridFs;
  16. this.gridFsBucket = gridFsBucket;
  17. }
  18. /** returns the right FileStoreStrategy
  19. * @param fileObj the current file object
  20. * @param versionName the current version
  21. * @param use this storage, or if not set, get the storage from fileObj
  22. */
  23. getFileStrategy(fileObj, versionName, storage) {
  24. if (!storage) {
  25. storage = fileObj.versions[versionName].storage;
  26. if (!storage) {
  27. if (fileObj.meta.source == "import") {
  28. // uploaded by import, so it's in GridFS (MongoDB)
  29. storage = STORAGE_NAME_GRIDFS;
  30. } else {
  31. // newly uploaded, so it's at the filesystem
  32. storage = STORAGE_NAME_FILESYSTEM;
  33. }
  34. }
  35. }
  36. let ret;
  37. if ([STORAGE_NAME_FILESYSTEM, STORAGE_NAME_GRIDFS].includes(storage)) {
  38. if (storage == STORAGE_NAME_FILESYSTEM) {
  39. ret = new this.classFileStoreStrategyFilesystem(fileObj, versionName);
  40. } else if (storage == STORAGE_NAME_GRIDFS) {
  41. ret = new this.classFileStoreStrategyGridFs(this.gridFsBucket, fileObj, versionName);
  42. }
  43. }
  44. return ret;
  45. }
  46. }
  47. /** Strategy to store files */
  48. class FileStoreStrategy {
  49. /** constructor
  50. * @param fileObj the current file object
  51. * @param versionName the current version
  52. */
  53. constructor(fileObj, versionName) {
  54. this.fileObj = fileObj;
  55. this.versionName = versionName;
  56. }
  57. /** after successfull upload */
  58. onAfterUpload() {
  59. }
  60. /** download the file
  61. * @param http the current http request
  62. * @param cacheControl cacheControl of FilesCollection
  63. */
  64. interceptDownload(http, cacheControl) {
  65. }
  66. /** after file remove */
  67. onAfterRemove() {
  68. }
  69. /** returns a read stream
  70. * @return the read stream
  71. */
  72. getReadStream() {
  73. }
  74. /** returns a write stream
  75. * @return the write stream
  76. */
  77. getWriteStream() {
  78. }
  79. /** writing finished
  80. * @param finishedData the data of the write stream finish event
  81. */
  82. writeStreamFinished(finishedData) {
  83. }
  84. /** remove the file */
  85. unlink() {
  86. }
  87. /** return the storage name
  88. * @return the storage name
  89. */
  90. getStorageName() {
  91. }
  92. }
  93. /** Strategy to store attachments at GridFS (MongoDB) */
  94. export class FileStoreStrategyGridFs extends FileStoreStrategy {
  95. /** constructor
  96. * @param gridFsBucket use this GridFS Bucket
  97. * @param fileObj the current file object
  98. * @param versionName the current version
  99. */
  100. constructor(gridFsBucket, fileObj, versionName) {
  101. super(fileObj, versionName);
  102. this.gridFsBucket = gridFsBucket;
  103. }
  104. /** download the file
  105. * @param http the current http request
  106. * @param cacheControl cacheControl of FilesCollection
  107. */
  108. interceptDownload(http, cacheControl) {
  109. const readStream = this.getReadStream();
  110. const downloadFlag = http?.params?.query?.download;
  111. let ret = false;
  112. if (readStream) {
  113. ret = true;
  114. httpStreamOutput(readStream, this.fileObj.name, http, downloadFlag, cacheControl);
  115. }
  116. return ret;
  117. }
  118. /** after file remove */
  119. onAfterRemove() {
  120. this.unlink();
  121. super.onAfterRemove();
  122. }
  123. /** returns a read stream
  124. * @return the read stream
  125. */
  126. getReadStream() {
  127. const gfsId = this.getGridFsObjectId();
  128. let ret;
  129. if (gfsId) {
  130. ret = this.gridFsBucket.openDownloadStream(gfsId);
  131. }
  132. return ret;
  133. }
  134. /** returns a write stream
  135. * @return the write stream
  136. */
  137. getWriteStream() {
  138. const fileObj = this.fileObj;
  139. const versionName = this.versionName;
  140. const metadata = { ...fileObj.meta, versionName, fileId: fileObj._id };
  141. const ret = this.gridFsBucket.openUploadStream(this.fileObj.name, {
  142. contentType: fileObj.type || 'binary/octet-stream',
  143. metadata,
  144. });
  145. return ret;
  146. }
  147. /** writing finished
  148. * @param finishedData the data of the write stream finish event
  149. */
  150. writeStreamFinished(finishedData) {
  151. const gridFsFileIdName = this.getGridFsFileIdName();
  152. Attachments.update({ _id: this.fileObj._id }, { $set: { [gridFsFileIdName]: finishedData._id.toHexString(), } });
  153. }
  154. /** remove the file */
  155. unlink() {
  156. const gfsId = this.getGridFsObjectId();
  157. if (gfsId) {
  158. this.gridFsBucket.delete(gfsId, err => {
  159. if (err) {
  160. console.error("error on gfs bucket.delete: ", err);
  161. }
  162. });
  163. }
  164. const gridFsFileIdName = this.getGridFsFileIdName();
  165. Attachments.update({ _id: this.fileObj._id }, { $unset: { [gridFsFileIdName]: 1 } });
  166. }
  167. /** return the storage name
  168. * @return the storage name
  169. */
  170. getStorageName() {
  171. return STORAGE_NAME_GRIDFS;
  172. }
  173. /** returns the GridFS Object-Id
  174. * @return the GridFS Object-Id
  175. */
  176. getGridFsObjectId() {
  177. let ret;
  178. const gridFsFileId = this.getGridFsFileId();
  179. if (gridFsFileId) {
  180. ret = createObjectId({ gridFsFileId });
  181. }
  182. return ret;
  183. }
  184. /** returns the GridFS Object-Id
  185. * @return the GridFS Object-Id
  186. */
  187. getGridFsFileId() {
  188. const ret = (this.fileObj.versions[this.versionName].meta || {})
  189. .gridFsFileId;
  190. return ret;
  191. }
  192. /** returns the property name of gridFsFileId
  193. * @return the property name of gridFsFileId
  194. */
  195. getGridFsFileIdName() {
  196. const ret = `versions.${this.versionName}.meta.gridFsFileId`;
  197. return ret;
  198. }
  199. }
  200. /** Strategy to store attachments at filesystem */
  201. export class FileStoreStrategyFilesystem extends FileStoreStrategy {
  202. /** constructor
  203. * @param fileObj the current file object
  204. * @param versionName the current version
  205. */
  206. constructor(fileObj, versionName) {
  207. super(fileObj, versionName);
  208. }
  209. /** returns a read stream
  210. * @return the read stream
  211. */
  212. getReadStream() {
  213. const ret = fs.createReadStream(this.fileObj.versions[this.versionName].path)
  214. return ret;
  215. }
  216. /** returns a write stream
  217. * @return the write stream
  218. */
  219. getWriteStream() {
  220. const filePath = this.fileObj.versions[this.versionName].path;
  221. const ret = fs.createWriteStream(filePath);
  222. return ret;
  223. }
  224. /** writing finished
  225. * @param finishedData the data of the write stream finish event
  226. */
  227. writeStreamFinished(finishedData) {
  228. }
  229. /** remove the file */
  230. unlink() {
  231. const filePath = this.fileObj.versions[this.versionName].path;
  232. fs.unlink(filePath, () => {});
  233. }
  234. /** return the storage name
  235. * @return the storage name
  236. */
  237. getStorageName() {
  238. return STORAGE_NAME_FILESYSTEM;
  239. }
  240. }
  241. /** move the fileObj to another storage
  242. * @param fileObj move this fileObj to another storage
  243. * @param storageDestination the storage destination (fs or gridfs)
  244. * @param fileStoreStrategyFactory get FileStoreStrategy from this factory
  245. */
  246. export const moveToStorage = function(fileObj, storageDestination, fileStoreStrategyFactory) {
  247. Object.keys(fileObj.versions).forEach(versionName => {
  248. const strategyRead = fileStoreStrategyFactory.getFileStrategy(fileObj, versionName);
  249. const strategyWrite = fileStoreStrategyFactory.getFileStrategy(fileObj, versionName, storageDestination);
  250. if (strategyRead.constructor.name != strategyWrite.constructor.name) {
  251. const readStream = strategyRead.getReadStream();
  252. const writeStream = strategyWrite.getWriteStream();
  253. writeStream.on('error', error => {
  254. console.error('[writeStream error]: ', error, fileObjId);
  255. });
  256. readStream.on('error', error => {
  257. console.error('[readStream error]: ', error, fileObjId);
  258. });
  259. writeStream.on('finish', Meteor.bindEnvironment((finishedData) => {
  260. strategyWrite.writeStreamFinished(finishedData);
  261. }));
  262. // https://forums.meteor.com/t/meteor-code-must-always-run-within-a-fiber-try-wrapping-callbacks-that-you-pass-to-non-meteor-libraries-with-meteor-bindenvironmen/40099/8
  263. readStream.on('end', Meteor.bindEnvironment(() => {
  264. Attachments.update({ _id: fileObj._id }, { $set: { [`versions.${versionName}.storage`]: strategyWrite.getStorageName() } });
  265. strategyRead.unlink();
  266. }));
  267. readStream.pipe(writeStream);
  268. }
  269. });
  270. };