forked from postalsys/imapflow
/
quota.ts
105 lines (90 loc) · 3.28 KB
/
quota.ts
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
97
98
99
100
101
102
103
104
105
import { encodePath, getStatusCode, normalizePath, getErrorText } from '../tools.js';
// Requests quota information for a mailbox
export const QUOTA = async (connection, path) => {
if (![connection.states.AUTHENTICATED, connection.states.SELECTED].includes(connection.state) || !path) {
// nothing to do here
return;
}
if (!connection.capabilities.has('QUOTA')) {
return false;
}
path = normalizePath(connection, path);
let map = { path };
let processQuotaResponse = untagged => {
let attributes = untagged.attributes && untagged.attributes[1];
if (!attributes || !attributes.length) {
return false;
}
let key = false;
attributes.forEach((attribute, i) => {
if (i % 3 === 0) {
key = attribute && typeof attribute.value === 'string' ? attribute.value.toLowerCase() : false;
return;
}
if (!key) {
return;
}
let value = attribute && typeof attribute.value === 'string' && !isNaN(attribute.value) ? Number(attribute.value) : false;
if (value === false) {
return;
}
if (i % 3 === 1) {
// usage
if (!map[key]) {
map[key] = {};
}
map[key].usage = value * (key === 'storage' ? 1024 : 1);
}
if (i % 3 === 2) {
// limit
if (!map[key]) {
map[key] = {};
}
map[key].limit = value * (key === 'storage' ? 1024 : 1);
if (map[key].limit) {
map[key].status = Math.round(((map[key].usage || 0) / map[key].limit) * 100) + '%';
}
}
});
};
let quotaFound = false;
let response;
try {
response = await connection.exec('GETQUOTAROOT', [{ type: 'ATOM', value: encodePath(connection, path) }], {
untagged: {
QUOTAROOT: async untagged => {
let quotaRoot =
untagged.attributes && untagged.attributes[1] && typeof untagged.attributes[1].value === 'string'
? untagged.attributes[1].value
: false;
if (quotaRoot) {
map.quotaRoot = quotaRoot;
}
},
QUOTA: async untagged => {
quotaFound = true;
processQuotaResponse(untagged);
}
}
});
response.next();
if (map.quotaRoot && !quotaFound) {
response = await connection.exec('GETQUOTA', [{ type: 'ATOM', value: map.quotaRoot }], {
untagged: {
QUOTA: async untagged => {
processQuotaResponse(untagged);
}
}
});
}
return map;
} catch (err) {
let errorCode = getStatusCode(err.response);
if (errorCode) {
err.serverResponseCode = errorCode;
}
err.response = await getErrorText(err.response);
connection.log.warn({ err, cid: connection.id });
return false;
}
};