fileStoreStrategy.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. import fs from 'fs';
  2. import path from 'path';
  3. import { createObjectId } from './grid/createObjectId';
  4. import { httpStreamOutput } from './httpStream.js'
  5. import { ObjectID } from 'bson';
  6. export const STORAGE_NAME_FILESYSTEM = "fs";
  7. export const STORAGE_NAME_GRIDFS = "gridfs";
  8. /** Factory for FileStoreStrategy */
  9. export default class FileStoreStrategyFactory {
  10. /** constructor
  11. * @param classFileStoreStrategyFilesystem use this strategy for filesystem storage
  12. * @param storagePath file storage path
  13. * @param classFileStoreStrategyGridFs use this strategy for GridFS storage
  14. * @param gridFsBucket use this GridFS Bucket as GridFS Storage
  15. */
  16. constructor(classFileStoreStrategyFilesystem, storagePath, classFileStoreStrategyGridFs, gridFsBucket) {
  17. this.classFileStoreStrategyFilesystem = classFileStoreStrategyFilesystem;
  18. this.storagePath = storagePath;
  19. this.classFileStoreStrategyGridFs = classFileStoreStrategyGridFs;
  20. this.gridFsBucket = gridFsBucket;
  21. }
  22. /** returns the right FileStoreStrategy
  23. * @param fileObj the current file object
  24. * @param versionName the current version
  25. * @param use this storage, or if not set, get the storage from fileObj
  26. */
  27. getFileStrategy(fileObj, versionName, storage) {
  28. if (!storage) {
  29. storage = fileObj.versions[versionName].storage;
  30. if (!storage) {
  31. if (fileObj.meta.source == "import" || fileObj.versions[versionName].meta.gridFsFileId) {
  32. // uploaded by import, so it's in GridFS (MongoDB)
  33. storage = STORAGE_NAME_GRIDFS;
  34. } else {
  35. // newly uploaded, so it's at the filesystem
  36. storage = STORAGE_NAME_FILESYSTEM;
  37. }
  38. }
  39. }
  40. let ret;
  41. if ([STORAGE_NAME_FILESYSTEM, STORAGE_NAME_GRIDFS].includes(storage)) {
  42. if (storage == STORAGE_NAME_FILESYSTEM) {
  43. ret = new this.classFileStoreStrategyFilesystem(fileObj, versionName);
  44. } else if (storage == STORAGE_NAME_GRIDFS) {
  45. ret = new this.classFileStoreStrategyGridFs(this.gridFsBucket, fileObj, versionName);
  46. }
  47. }
  48. return ret;
  49. }
  50. }
  51. /** Strategy to store files */
  52. class FileStoreStrategy {
  53. /** constructor
  54. * @param fileObj the current file object
  55. * @param versionName the current version
  56. */
  57. constructor(fileObj, versionName) {
  58. this.fileObj = fileObj;
  59. this.versionName = versionName;
  60. }
  61. /** after successfull upload */
  62. onAfterUpload() {
  63. }
  64. /** download the file
  65. * @param http the current http request
  66. * @param cacheControl cacheControl of FilesCollection
  67. */
  68. interceptDownload(http, cacheControl) {
  69. }
  70. /** after file remove */
  71. onAfterRemove() {
  72. }
  73. /** returns a read stream
  74. * @return the read stream
  75. */
  76. getReadStream() {
  77. }
  78. /** returns a write stream
  79. * @param filePath if set, use this path
  80. * @return the write stream
  81. */
  82. getWriteStream(filePath) {
  83. }
  84. /** writing finished
  85. * @param finishedData the data of the write stream finish event
  86. */
  87. writeStreamFinished(finishedData) {
  88. }
  89. /** returns the new file path
  90. * @param storagePath use this storage path
  91. * @return the new file path
  92. */
  93. getNewPath(storagePath, name) {
  94. if (!_.isString(name)) {
  95. name = this.fileObj.name;
  96. }
  97. const ret = path.join(storagePath, this.fileObj._id + "-" + this.versionName + "-" + name);
  98. return ret;
  99. }
  100. /** remove the file */
  101. unlink() {
  102. }
  103. /** rename the file (physical)
  104. * @li at database the filename is updated after this method
  105. * @param newFilePath the new file path
  106. */
  107. rename(newFilePath) {
  108. }
  109. /** return the storage name
  110. * @return the storage name
  111. */
  112. getStorageName() {
  113. }
  114. }
  115. /** Strategy to store attachments at GridFS (MongoDB) */
  116. export class FileStoreStrategyGridFs extends FileStoreStrategy {
  117. /** constructor
  118. * @param gridFsBucket use this GridFS Bucket
  119. * @param fileObj the current file object
  120. * @param versionName the current version
  121. */
  122. constructor(gridFsBucket, fileObj, versionName) {
  123. super(fileObj, versionName);
  124. this.gridFsBucket = gridFsBucket;
  125. }
  126. /** download the file
  127. * @param http the current http request
  128. * @param cacheControl cacheControl of FilesCollection
  129. */
  130. interceptDownload(http, cacheControl) {
  131. const readStream = this.getReadStream();
  132. const downloadFlag = http?.params?.query?.download;
  133. let ret = false;
  134. if (readStream) {
  135. ret = true;
  136. httpStreamOutput(readStream, this.fileObj.name, http, downloadFlag, cacheControl);
  137. }
  138. return ret;
  139. }
  140. /** after file remove */
  141. onAfterRemove() {
  142. this.unlink();
  143. super.onAfterRemove();
  144. }
  145. /** returns a read stream
  146. * @return the read stream
  147. */
  148. getReadStream() {
  149. const gfsId = this.getGridFsObjectId();
  150. let ret;
  151. if (gfsId) {
  152. ret = this.gridFsBucket.openDownloadStream(gfsId);
  153. }
  154. return ret;
  155. }
  156. /** returns a write stream
  157. * @param filePath if set, use this path
  158. * @return the write stream
  159. */
  160. getWriteStream(filePath) {
  161. const fileObj = this.fileObj;
  162. const versionName = this.versionName;
  163. const metadata = { ...fileObj.meta, versionName, fileId: fileObj._id };
  164. const ret = this.gridFsBucket.openUploadStream(this.fileObj.name, {
  165. contentType: fileObj.type || 'binary/octet-stream',
  166. metadata,
  167. });
  168. return ret;
  169. }
  170. /** writing finished
  171. * @param finishedData the data of the write stream finish event
  172. */
  173. writeStreamFinished(finishedData) {
  174. const gridFsFileIdName = this.getGridFsFileIdName();
  175. Attachments.update({ _id: this.fileObj._id }, { $set: { [gridFsFileIdName]: finishedData._id.toHexString(), } });
  176. }
  177. /** remove the file */
  178. unlink() {
  179. const gfsId = this.getGridFsObjectId();
  180. if (gfsId) {
  181. this.gridFsBucket.delete(gfsId, err => {
  182. if (err) {
  183. console.error("error on gfs bucket.delete: ", err);
  184. }
  185. });
  186. }
  187. const gridFsFileIdName = this.getGridFsFileIdName();
  188. Attachments.update({ _id: this.fileObj._id }, { $unset: { [gridFsFileIdName]: 1 } });
  189. }
  190. /** return the storage name
  191. * @return the storage name
  192. */
  193. getStorageName() {
  194. return STORAGE_NAME_GRIDFS;
  195. }
  196. /** returns the GridFS Object-Id
  197. * @return the GridFS Object-Id
  198. */
  199. getGridFsObjectId() {
  200. let ret;
  201. const gridFsFileId = this.getGridFsFileId();
  202. if (gridFsFileId) {
  203. ret = createObjectId({ gridFsFileId });
  204. }
  205. return ret;
  206. }
  207. /** returns the GridFS Object-Id
  208. * @return the GridFS Object-Id
  209. */
  210. getGridFsFileId() {
  211. const ret = (this.fileObj.versions[this.versionName].meta || {})
  212. .gridFsFileId;
  213. return ret;
  214. }
  215. /** returns the property name of gridFsFileId
  216. * @return the property name of gridFsFileId
  217. */
  218. getGridFsFileIdName() {
  219. const ret = `versions.${this.versionName}.meta.gridFsFileId`;
  220. return ret;
  221. }
  222. }
  223. /** Strategy to store attachments at filesystem */
  224. export class FileStoreStrategyFilesystem extends FileStoreStrategy {
  225. /** constructor
  226. * @param fileObj the current file object
  227. * @param versionName the current version
  228. */
  229. constructor(fileObj, versionName) {
  230. super(fileObj, versionName);
  231. }
  232. /** returns a read stream
  233. * @return the read stream
  234. */
  235. getReadStream() {
  236. const ret = fs.createReadStream(this.fileObj.versions[this.versionName].path)
  237. return ret;
  238. }
  239. /** returns a write stream
  240. * @param filePath if set, use this path
  241. * @return the write stream
  242. */
  243. getWriteStream(filePath) {
  244. if (!_.isString(filePath)) {
  245. filePath = this.fileObj.versions[this.versionName].path;
  246. }
  247. const ret = fs.createWriteStream(filePath);
  248. return ret;
  249. }
  250. /** writing finished
  251. * @param finishedData the data of the write stream finish event
  252. */
  253. writeStreamFinished(finishedData) {
  254. }
  255. /** remove the file */
  256. unlink() {
  257. const filePath = this.fileObj.versions[this.versionName].path;
  258. fs.unlink(filePath, () => {});
  259. }
  260. /** rename the file (physical)
  261. * @li at database the filename is updated after this method
  262. * @param newFilePath the new file path
  263. */
  264. rename(newFilePath) {
  265. fs.renameSync(this.fileObj.versions[this.versionName].path, newFilePath);
  266. }
  267. /** return the storage name
  268. * @return the storage name
  269. */
  270. getStorageName() {
  271. return STORAGE_NAME_FILESYSTEM;
  272. }
  273. }
  274. /** move the fileObj to another storage
  275. * @param fileObj move this fileObj to another storage
  276. * @param storageDestination the storage destination (fs or gridfs)
  277. * @param fileStoreStrategyFactory get FileStoreStrategy from this factory
  278. */
  279. export const moveToStorage = function(fileObj, storageDestination, fileStoreStrategyFactory) {
  280. Object.keys(fileObj.versions).forEach(versionName => {
  281. const strategyRead = fileStoreStrategyFactory.getFileStrategy(fileObj, versionName);
  282. const strategyWrite = fileStoreStrategyFactory.getFileStrategy(fileObj, versionName, storageDestination);
  283. if (strategyRead.constructor.name != strategyWrite.constructor.name) {
  284. const readStream = strategyRead.getReadStream();
  285. const filePath = strategyWrite.getNewPath(fileStoreStrategyFactory.storagePath);
  286. const writeStream = strategyWrite.getWriteStream(filePath);
  287. writeStream.on('error', error => {
  288. console.error('[writeStream error]: ', error, fileObj._id);
  289. });
  290. readStream.on('error', error => {
  291. console.error('[readStream error]: ', error, fileObj._id);
  292. });
  293. writeStream.on('finish', Meteor.bindEnvironment((finishedData) => {
  294. strategyWrite.writeStreamFinished(finishedData);
  295. }));
  296. // 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
  297. readStream.on('end', Meteor.bindEnvironment(() => {
  298. Attachments.update({ _id: fileObj._id }, { $set: {
  299. [`versions.${versionName}.storage`]: strategyWrite.getStorageName(),
  300. [`versions.${versionName}.path`]: filePath,
  301. } });
  302. strategyRead.unlink();
  303. }));
  304. readStream.pipe(writeStream);
  305. }
  306. });
  307. };
  308. export const copyFile = function(fileObj, newCardId, fileStoreStrategyFactory) {
  309. Object.keys(fileObj.versions).forEach(versionName => {
  310. const strategyRead = fileStoreStrategyFactory.getFileStrategy(fileObj, versionName);
  311. const readStream = strategyRead.getReadStream();
  312. const strategyWrite = fileStoreStrategyFactory.getFileStrategy(fileObj, versionName, STORAGE_NAME_FILESYSTEM);
  313. const tempPath = path.join(fileStoreStrategyFactory.storagePath, Random.id() + "-" + versionName + "-" + fileObj.name);
  314. const writeStream = strategyWrite.getWriteStream(tempPath);
  315. writeStream.on('error', error => {
  316. console.error('[writeStream error]: ', error, fileObj._id);
  317. });
  318. readStream.on('error', error => {
  319. console.error('[readStream error]: ', error, fileObj._id);
  320. });
  321. // 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
  322. readStream.on('end', Meteor.bindEnvironment(() => {
  323. const fileId = new ObjectID().toString();
  324. Attachments.addFile(
  325. tempPath,
  326. {
  327. fileName: fileObj.name,
  328. type: fileObj.type,
  329. meta: {
  330. boardId: fileObj.meta.boardId,
  331. cardId: newCardId,
  332. listId: fileObj.meta.listId,
  333. swimlaneId: fileObj.meta.swimlaneId,
  334. source: 'copy',
  335. copyFrom: fileObj._id,
  336. copyStorage: strategyRead.getStorageName(),
  337. },
  338. userId: fileObj.userId,
  339. size: fileObj.fileSize,
  340. fileId,
  341. },
  342. (err, fileRef) => {
  343. if (err) {
  344. console.log(err);
  345. } else {
  346. // Set the userId again
  347. Attachments.update({ _id: fileRef._id }, { $set: { userId: fileObj.userId } });
  348. }
  349. },
  350. true,
  351. );
  352. }));
  353. readStream.pipe(writeStream);
  354. });
  355. };
  356. export const rename = function(fileObj, newName, fileStoreStrategyFactory) {
  357. Object.keys(fileObj.versions).forEach(versionName => {
  358. const strategy = fileStoreStrategyFactory.getFileStrategy(fileObj, versionName);
  359. const newFilePath = strategy.getNewPath(fileStoreStrategyFactory.storagePath, newName);
  360. strategy.rename(newFilePath);
  361. Attachments.update({ _id: fileObj._id }, { $set: {
  362. "name": newName,
  363. [`versions.${versionName}.path`]: newFilePath,
  364. } });
  365. });
  366. };