Skip to content

Commit eecb1b5

Browse files
authored
[DISC-110] Adding Course Chats 1-year "Subscription" (#191)
* Added database implementation of user roles when assigned and removed * Added time checking function for expired user_roles and added time assigned column to user_roles table * Added on ready file with cron.js to perform daily check of old_roles * Adding new package cron for scheduling * fixing lint issues * Fixing prettier issues * Package changes * Restoring develop package lock.json and fixing db_ready * Moving guild and roles out of for loop to remove redundant fetching
1 parent 5298768 commit eecb1b5

File tree

5 files changed

+149
-30
lines changed

5 files changed

+149
-30
lines changed

commands/course.js

+9
Original file line numberDiff line numberDiff line change
@@ -127,9 +127,14 @@ module.exports = {
127127
ephemeral: true,
128128
});
129129
}
130+
// // Add it to the existing database to track.
131+
/** @type {DBuser} */
132+
const userDB = global.userDB;
133+
await userDB.add_user_role(interaction.user.id, role.name);
130134

131135
// If they don't, let's add the role to them
132136
await interaction.member.roles.add(role);
137+
133138
return await interaction.reply({
134139
content: `✅ | Added you to the chat for \`${course_with_alias}\`.`,
135140
ephemeral: true,
@@ -190,6 +195,10 @@ module.exports = {
190195
in_overwrites(permissions, role.id)
191196
) {
192197
// If they do remove the role
198+
/** @type {DBuser} */
199+
const userDB = global.userDB;
200+
userDB.remove_user_role(interaction.user.id, role.name);
201+
193202
await interaction.member.roles.remove(role);
194203
return await interaction.reply({
195204
content: `✅ | Removed you from the role and chat for \`${course}\`.`,

events/db_ready.js

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// @ts-check
2+
const { DBuser } = require("../lib/database/database");
3+
const { CronJob } = require("cron");
4+
5+
const CSESOC_SERVER_ID = "693779865916276746";
6+
// const TEST_SERVER_ID = "1220297696829509713";
7+
8+
module.exports = {
9+
name: "ready",
10+
once: true,
11+
async execute(client) {
12+
/** @type {DBuser} */
13+
const userDB = new DBuser();
14+
global.userDB = userDB;
15+
16+
// Set up an automatic database check to see if there is any out of date roles.
17+
const role_job = new CronJob("0 0 12 * * *", async function () {
18+
console.log("Performing daily check of old roles at 12:00pm");
19+
20+
const old_roles = await userDB.checkTimeAssigned();
21+
const guild = await client.guilds.fetch(CSESOC_SERVER_ID);
22+
const roles = await guild.roles.fetch();
23+
24+
for (const removed_role of old_roles) {
25+
try {
26+
const member = await guild.members.fetch(removed_role.userid);
27+
const role = roles.find((r) => r.name === removed_role.role_name);
28+
29+
if (member && role) {
30+
await member.roles.remove(role);
31+
await userDB.remove_user_role(removed_role.userid, removed_role.role_name);
32+
// console.log(`Removed role ${removed_role.role_name} from user ${removed_role.userid}`);
33+
} else {
34+
console.log(
35+
`Could not find role ${removed_role.role_name} or user ${removed_role.userid}`,
36+
);
37+
}
38+
} catch (error) {
39+
console.log(error);
40+
}
41+
}
42+
});
43+
44+
role_job.start();
45+
},
46+
};

lib/database/database.js

+49-28
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ class DBuser {
2727
load_db_login() {
2828
// Get document, or throw exception on error
2929
try {
30-
const doc = yaml.load(fs.readFileSync("../../config/database.yml"));
30+
const doc = yaml.load(fs.readFileSync("./config/database.yml"));
3131
return doc;
3232
} catch (e) {
3333
console.log(e);
@@ -90,14 +90,14 @@ class DBuser {
9090
const client = await this.pool.connect();
9191
try {
9292
if ((await this.check_table("users")) == false) {
93-
// console.log("Running create_table")
93+
console.log("Running creating user table");
9494
await client.query("BEGIN");
9595
const query = `CREATE TABLE users (
9696
userid INTEGER PRIMARY KEY,
9797
joindate DATE NOT NULL,
9898
leavedate DATE,
9999
userleft BOOLEAN
100-
);`;
100+
)`;
101101
await client.query(query);
102102
await client.query("COMMIT");
103103
}
@@ -114,21 +114,19 @@ class DBuser {
114114
async create_table_user_roles() {
115115
const client = await this.pool.connect();
116116
try {
117-
if ((await this.check_table("user_roles")) == false) {
118-
// console.log("Running create_table")
119-
await client.query("BEGIN");
120-
const query = `CREATE TABLE user_roles (
121-
rid INTEGER PRIMARY KEY,
122-
userid INTEGER NOT NULL,
123-
role varchar(64),
124-
FOREIGN KEY (userid)
125-
REFERENCES users (userid)
126-
);`;
127-
await client.query(query);
128-
await client.query("COMMIT");
129-
}
117+
// if ((await this.check_table("user_roles")) == false) {
118+
119+
await client.query("BEGIN");
120+
const query = `CREATE TABLE user_roles (
121+
rid INTEGER PRIMARY KEY,
122+
userid BIGINT NOT NULL,
123+
role varchar(64),
124+
time_assigned TIMESTAMP
125+
)`;
126+
await client.query(query);
127+
await client.query("COMMIT");
130128
} catch (ex) {
131-
console.log(`Something wrong happend ${ex}`);
129+
console.log(`Something wrong happende:${ex}`);
132130
} finally {
133131
await client.query("ROLLBACK");
134132
client.release();
@@ -170,12 +168,12 @@ class DBuser {
170168
// console.log("Running create_table")
171169
await client.query("BEGIN");
172170
const query = `CREATE TABLE user_permissions (
173-
pid INTEGER PRIMARY KEY,
174-
userid INTEGER NOT NULL,
175-
permission varchar(64),
176-
FOREIGN KEY (userid)
177-
REFERENCES users (userid)
178-
);`;
171+
pid INTEGER PRIMARY KEY,
172+
userid INTEGER NOT NULL,
173+
permission varchar(64),
174+
FOREIGN KEY (userid)
175+
REFERENCES users (userid)
176+
);`;
179177
await client.query(query);
180178
await client.query("COMMIT");
181179
}
@@ -250,18 +248,18 @@ class DBuser {
250248
const client = await this.pool.connect();
251249
try {
252250
await client.query("BEGIN");
253-
254251
let query = "SELECT max(rid) from user_roles";
255252
let result = await client.query(query);
256253

257254
const count = result.rows[0]["max"] + 1;
258-
query = "INSERT INTO user_roles (RID, USERID, ROLE) VALUES ($1,$2,$3)";
255+
query =
256+
"INSERT INTO user_roles (RID, USERID, ROLE, TIME_ASSIGNED) VALUES ($1,$2,$3,NOW())";
259257
const values = [count, userid, role];
260258
result = await client.query(query, values);
261259

262260
await client.query("COMMIT");
263261
} catch (ex) {
264-
console.log(`Something wrong happend ${ex}`);
262+
console.log(`Something wrong happend when trying to add user role to table ${ex}`);
265263
} finally {
266264
await client.query("ROLLBACK");
267265
client.release();
@@ -275,8 +273,7 @@ class DBuser {
275273
try {
276274
await client.query("BEGIN");
277275
const values = [userid, role];
278-
const query = `DELETE FROM user_roles
279-
where userid = $1 and role = $2`;
276+
const query = `DELETE FROM user_roles where userid = $1 and role = $2`;
280277
await client.query(query, values);
281278
await client.query("COMMIT");
282279
} catch (ex) {
@@ -456,6 +453,30 @@ class DBuser {
456453
// console.log("Client released successfully.")
457454
}
458455
}
456+
457+
async checkTimeAssigned() {
458+
const client = await this.pool.connect();
459+
try {
460+
// Query to select rows where time_assigned is older than 1 hour
461+
const query = `
462+
SELECT * FROM user_roles WHERE time_assigned < NOW() - interval '1 year'
463+
`;
464+
465+
const result = await client.query(query);
466+
467+
const old_roles = result.rows.map((row) => ({
468+
role_name: row.role,
469+
userid: row.userid,
470+
}));
471+
472+
return old_roles;
473+
} catch (error) {
474+
console.error(error);
475+
return [];
476+
} finally {
477+
client.release();
478+
}
479+
}
459480
}
460481

461482
module.exports = {

package-lock.json

+43-1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
"chartjs-node-canvas": "^4.1.6",
3434
"cheerio": "^1.0.0-rc.12",
3535
"closest-match": "1.3.3",
36+
"cron": "^3.1.7",
3637
"csv-parser": "3.0.0",
3738
"csv-writer": "1.6.0",
3839
"discord-api-types": "0.37.90",
@@ -41,7 +42,7 @@
4142
"dotenv": "16.4.5",
4243
"js-yaml": "4.1.0",
4344
"mathjs": "^13.0.0",
44-
"node-cron": "^3.0.2",
45+
"node-cron": "^3.0.3",
4546
"nodemailer": "6.9.13",
4647
"nodemon": "^3.0.0",
4748
"pg": "8.12.0",

0 commit comments

Comments
 (0)