forked from daniel-j/send2ereader
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathkey-session.js
More file actions
62 lines (52 loc) · 1.43 KB
/
Copy pathkey-session.js
File metadata and controls
62 lines (52 loc) · 1.43 KB
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
const fs = require("fs");
function create(keysMap, config) {
const { expireDelay } = config;
function removeSession(key) {
const info = keysMap.get(key);
if (!info) {
console.log("Tried to remove non-existing key", key);
return;
}
clearTimeout(info.timer);
if (info.files && info.files.length > 0) {
for (const file of info.files) {
console.log("Deleting file", file.path);
fs.unlink(file.path, (err) => err && console.error(err));
}
info.files = [];
}
keysMap.delete(key);
}
function expireSession(key) {
const info = keysMap.get(key);
const timer = setTimeout(removeSession, expireDelay * 1000, key);
if (info) {
clearTimeout(info.timer);
info.timer = timer;
info.alive = new Date();
}
return timer;
}
function generateKey(keyChars, keyLength) {
const choices = Math.pow(keyChars.length, keyLength);
const rnd = Math.floor(Math.random() * choices);
return rnd
.toString(keyChars.length)
.padStart(keyLength, "0")
.split("")
.map((chr) => keyChars[parseInt(chr, keyChars.length)])
.join("");
}
return {
generateKey,
getSession: (key) => keysMap.get(key),
hasSession: (key) => keysMap.has(key),
setSession: (key, info) => keysMap.set(key, info),
removeSession,
expireSession,
get size() {
return keysMap.size;
},
};
}
module.exports = { create };