fileStoreStrategy.js 8.9 KB

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