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