aboutsummaryrefslogtreecommitdiff
path: root/message-scheduler.js
blob: 12f868b6b9dfce7b9bf1114e74169857549f7a6f (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
85
86
87
88
89
90
91
92
import "dotenv/config";
import cron from "node-cron";
import { v4 as uuidv4 } from "uuid";
import fs from "node:fs";

export class Message {
    constructor(message, channel_id, crontab, repeat = true, id = null) {
        this.id = id ? id : uuidv4();
        this.repeat = repeat;

        this.channel_id = channel_id;
        this.message = message;
        this.crontab = crontab;
    }
}

export class MessageSchedule {
    constructor(state) {
        this.state = state;
        this.crons = {};

        // read db file if there is one and start up all jobs
        fs.readFile(state.job_db, "utf8", (err, data) => {
            this.jobs = err ? {} : JSON.parse(data);

            Object.keys(this.jobs).forEach((job) => {
                // fix incompatibility with older storage version
                const repeat = this.jobs[job].repeat
                    ? this.jobs[job].repeat
                    : true;
                this.jobs[job].id = job;
                this.jobs[job].repeat = repeat;

                this.schedule(this.jobs[job]);
            });
        });
    }

    save() {
        const json = JSON.stringify(this.jobs);
        fs.writeFile(this.state.job_db, json, "utf8", (err) => {
            if (err) console.log(err);
        });
    }

    schedule(message) {
        const valid = cron.validate(message.crontab);

        if (valid) {
            this.jobs[message.id] = message;

            this.crons[message.id] = cron.schedule(
                message.crontab,
                () => {
                    this.state.client.channels.cache
                        .get(message.channel_id)
                        .send(message.message);
                    if (!message.repeat) {
                        this.unschedule(message.id);
                    }
                },
                {
                    scheduled: true,
                    timezone: process.env.TIMEZONE,
                },
            );

            this.save();
        }

        return valid;
    }

    unschedule(id) {
        var valid = true;
        if (id in this.jobs) {
            delete this.jobs[id];
        } else {
            valid = false;
        }
        if (id in this.crons) {
            this.crons[id].stop();
            delete this.crons[id];
        } else {
            valid = false;
        }

        this.save();

        return valid;
    }
}