ownedFile.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import Keychain from './keychain';
  2. import { arrayToB64 } from './utils';
  3. import { del, fileInfo, setParams, setPassword } from './api';
  4. export default class OwnedFile {
  5. constructor(obj) {
  6. if (!obj.manifest) {
  7. throw new Error('invalid file object');
  8. }
  9. this.id = obj.id;
  10. this.url = obj.url;
  11. this.name = obj.name;
  12. this.size = obj.size;
  13. this.manifest = obj.manifest;
  14. this.time = obj.time;
  15. this.speed = obj.speed;
  16. this.createdAt = obj.createdAt;
  17. this.expiresAt = obj.expiresAt;
  18. this.ownerToken = obj.ownerToken;
  19. this.dlimit = obj.dlimit || 1;
  20. this.dtotal = obj.dtotal || 0;
  21. this.keychain = new Keychain(obj.secretKey, obj.nonce);
  22. this._hasPassword = !!obj.hasPassword;
  23. this.timeLimit = obj.timeLimit;
  24. }
  25. get hasPassword() {
  26. return !!this._hasPassword;
  27. }
  28. get expired() {
  29. return this.dlimit === this.dtotal || Date.now() > this.expiresAt;
  30. }
  31. async setPassword(password) {
  32. try {
  33. this.password = password;
  34. this._hasPassword = true;
  35. this.keychain.setPassword(password, this.url);
  36. const result = await setPassword(this.id, this.ownerToken, this.keychain);
  37. return result;
  38. } catch (e) {
  39. this.password = null;
  40. this._hasPassword = false;
  41. throw e;
  42. }
  43. }
  44. del() {
  45. return del(this.id, this.ownerToken);
  46. }
  47. changeLimit(dlimit, user = {}) {
  48. if (this.dlimit !== dlimit) {
  49. this.dlimit = dlimit;
  50. return setParams(this.id, this.ownerToken, user.bearerToken, { dlimit });
  51. }
  52. return Promise.resolve(true);
  53. }
  54. async updateDownloadCount() {
  55. const oldTotal = this.dtotal;
  56. const oldLimit = this.dlimit;
  57. try {
  58. const result = await fileInfo(this.id, this.ownerToken);
  59. this.dtotal = result.dtotal;
  60. this.dlimit = result.dlimit;
  61. } catch (e) {
  62. if (e.message === '404') {
  63. this.dtotal = this.dlimit;
  64. }
  65. // ignore other errors
  66. }
  67. return oldTotal !== this.dtotal || oldLimit !== this.dlimit;
  68. }
  69. toJSON() {
  70. return {
  71. id: this.id,
  72. url: this.url,
  73. name: this.name,
  74. size: this.size,
  75. manifest: this.manifest,
  76. time: this.time,
  77. speed: this.speed,
  78. createdAt: this.createdAt,
  79. expiresAt: this.expiresAt,
  80. secretKey: arrayToB64(this.keychain.rawSecret),
  81. ownerToken: this.ownerToken,
  82. dlimit: this.dlimit,
  83. dtotal: this.dtotal,
  84. hasPassword: this.hasPassword,
  85. timeLimit: this.timeLimit
  86. };
  87. }
  88. }