summaryrefslogtreecommitdiff
path: root/school/node_modules/pronote-api/src/session.js
blob: 6804d179ecb25e7a041aff136928c5c9210d25db (plain)
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
const { initCipher } = require('./cipher');
const getAccountType = require('./accounts');

const timetable = require('./fetch/timetable');
const marks = require('./fetch/marks');
const evaluations = require('./fetch/evaluations');
const absences = require('./fetch/absences');
const infos = require('./fetch/infos');
const contents = require('./fetch/contents');
const homeworks = require('./fetch/homeworks');
const menu = require('./fetch/menu');
const files = require('./fetch/files');

const keepAlive = require('./fetch/pronote/keepAlive');
const logout = require('./fetch/pronote/logout');

const DEFAULT_KEEP_ALIVE_RATE = 120; // In seconds. 120 is the Pronote default 'Presence' request rate.
const GENERAL_REQUESTS = {
    keepAlive, logout
};
const REQUESTS = {
    timetable, marks, evaluations, absences, contents,
    infos, homeworks, menu, files
};

class PronoteSession
{
    constructor({ serverURL, sessionID, type, disableAES, disableCompress, keyModulus, keyExponent })
    {
        this.id = ~~sessionID;
        this.server = serverURL;
        this.type = typeof type === 'string' ? getAccountType(type) : type;

        this.disableAES = disableAES;
        this.disableCompress = disableCompress;

        initCipher(this, keyModulus, keyExponent);

        this.request = -1;
        this.isKeptAlive = false;

        for (const [req, method] of Object.entries(GENERAL_REQUESTS)) {
            this[req] = () => method(this);
        }
        for (const [req, method] of Object.entries(REQUESTS)) {
            this[req] = (...args) => callRequest(method, this, args);
        }
    }

    setKeepAlive(enabled, onError, rate = DEFAULT_KEEP_ALIVE_RATE)
    {
        if (enabled === this.isKeptAlive) {
            return;
        }

        if (enabled) {
            this.interval = setInterval(() => {
                this.keepAlive().catch(err => {
                    this.setKeepAlive(false);
                    if (onError) {
                        onError(err);
                    }
                });
            }, rate * 1000);
        } else {
            clearInterval(this.interval);
        }

        this.isKeptAlive = enabled;
    }
}

function callRequest(method, session, args)
{
    switch (session.type.name)
    {
    case 'student':
        return method(session, session.user, ...args);
    default:
        return method(session, ...args);
    }
}

module.exports = PronoteSession;