archive.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import { blobStream, concatStream } from './streams';
  2. function isDupe(newFile, array) {
  3. for (const file of array) {
  4. if (
  5. newFile.name === file.name &&
  6. newFile.size === file.size &&
  7. newFile.lastModified === file.lastModified
  8. ) {
  9. return true;
  10. }
  11. }
  12. return false;
  13. }
  14. export default class Archive {
  15. constructor(files = [], defaultTimeLimit = 86400) {
  16. this.files = Array.from(files);
  17. this.defaultTimeLimit = defaultTimeLimit;
  18. this.timeLimit = defaultTimeLimit;
  19. this.dlimit = 1;
  20. this.password = null;
  21. }
  22. get name() {
  23. return this.files.length > 1 ? 'Send-Archive.zip' : this.files[0].name;
  24. }
  25. get type() {
  26. return this.files.length > 1 ? 'send-archive' : this.files[0].type;
  27. }
  28. get size() {
  29. return this.files.reduce((total, file) => total + file.size, 0);
  30. }
  31. get numFiles() {
  32. return this.files.length;
  33. }
  34. get manifest() {
  35. return {
  36. files: this.files.map(file => ({
  37. name: file.name,
  38. size: file.size,
  39. type: file.type
  40. }))
  41. };
  42. }
  43. get stream() {
  44. return concatStream(this.files.map(file => blobStream(file)));
  45. }
  46. addFiles(files, maxSize, maxFiles) {
  47. if (this.files.length + files.length > maxFiles) {
  48. throw new Error('tooManyFiles');
  49. }
  50. const newFiles = files.filter(
  51. file => file.size > 0 && !isDupe(file, this.files)
  52. );
  53. const newSize = newFiles.reduce((total, file) => total + file.size, 0);
  54. if (this.size + newSize > maxSize) {
  55. throw new Error('fileTooBig');
  56. }
  57. this.files = this.files.concat(newFiles);
  58. return true;
  59. }
  60. remove(file) {
  61. const index = this.files.indexOf(file);
  62. if (index > -1) {
  63. this.files.splice(index, 1);
  64. }
  65. }
  66. clear() {
  67. this.files = [];
  68. this.dlimit = 1;
  69. this.timeLimit = this.defaultTimeLimit;
  70. this.password = null;
  71. }
  72. }