archive.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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, defaultDownloadLimit = 1) {
  16. this.files = Array.from(files);
  17. this.defaultTimeLimit = defaultTimeLimit;
  18. this.defaultDownloadLimit = defaultDownloadLimit;
  19. this.timeLimit = defaultTimeLimit;
  20. this.dlimit = defaultDownloadLimit;
  21. this.password = null;
  22. }
  23. get name() {
  24. return this.files.length > 1 ? 'Send-Archive.zip' : this.files[0].name;
  25. }
  26. get type() {
  27. return this.files.length > 1 ? 'send-archive' : this.files[0].type;
  28. }
  29. get size() {
  30. return this.files.reduce((total, file) => total + file.size, 0);
  31. }
  32. get numFiles() {
  33. return this.files.length;
  34. }
  35. get manifest() {
  36. return {
  37. files: this.files.map(file => ({
  38. name: file.name,
  39. size: file.size,
  40. type: file.type
  41. }))
  42. };
  43. }
  44. get stream() {
  45. return concatStream(this.files.map(file => blobStream(file)));
  46. }
  47. addFiles(files, maxSize, maxFiles) {
  48. if (this.files.length + files.length > maxFiles) {
  49. throw new Error('tooManyFiles');
  50. }
  51. const newFiles = files.filter(
  52. file => file.size > 0 && !isDupe(file, this.files)
  53. );
  54. const newSize = newFiles.reduce((total, file) => total + file.size, 0);
  55. if (this.size + newSize > maxSize) {
  56. throw new Error('fileTooBig');
  57. }
  58. this.files = this.files.concat(newFiles);
  59. return true;
  60. }
  61. remove(file) {
  62. const index = this.files.indexOf(file);
  63. if (index > -1) {
  64. this.files.splice(index, 1);
  65. }
  66. }
  67. clear() {
  68. this.files = [];
  69. this.dlimit = this.defaultDownloadLimit;
  70. this.timeLimit = this.defaultTimeLimit;
  71. this.password = null;
  72. }
  73. }