MegaStorage.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. const fs = require('fs-extra');
  2. const path = require('path');
  3. const ZipStreamer = require('../ZipStreamer');
  4. const utils = require('../utils');
  5. class MegaStorage {
  6. constructor() {
  7. this.readingFiles = false;
  8. this.stats = null;
  9. }
  10. async init(config) {
  11. this.config = config;
  12. this.megaStorageDir = config.megaStorageDir;
  13. this.compressLevel = (config.compressLevel ? config.compressLevel : 4);
  14. await fs.ensureDir(this.megaStorageDir);
  15. }
  16. async nameHash(filename) {
  17. const hash = utils.toBase36(await utils.getFileHash(filename, 'sha1'));
  18. const hashPath = `${hash.substr(0, 2)}/${hash.substr(2, 2)}/${hash}`;
  19. const fullHashPath = `${this.megaStorageDir}/${hashPath}`;
  20. return {
  21. filename,
  22. hash,
  23. hashPath,
  24. fullHashPath,
  25. zipPath: `${fullHashPath}.zip`,
  26. descPath: `${fullHashPath}.desc`,
  27. };
  28. }
  29. async checkFileExists(nameHash) {
  30. return await fs.pathExists(nameHash.zipPath);
  31. }
  32. async addFile(nameHash, desc = null, force = false) {
  33. if (await this.checkFileExists(nameHash) && !force)
  34. return false;
  35. await fs.ensureDir(path.dirname(nameHash.zipPath));
  36. const zip = new ZipStreamer();
  37. let entry = {};
  38. let resultFile = await zip.pack(nameHash.zipPath, [nameHash.filename], {zlib: {level: this.compressLevel}}, (ent) => {
  39. entry = ent;
  40. });
  41. if (desc) {
  42. desc = Object.assign({}, desc, {fileSize: entry.size, zipFileSize: resultFile.size});
  43. this.updateDesc(nameHash, desc);
  44. }
  45. return desc;
  46. }
  47. async updateDesc(nameHash, desc) {
  48. await fs.writeFile(nameHash.descPath, JSON.stringify(desc, null, 2));
  49. }
  50. async readFiles(callback) {
  51. }
  52. async stopReadFiles() {
  53. }
  54. async getStats(gather = false) {
  55. }
  56. }
  57. module.exports = MegaStorage;