Skip to content

Commit

Permalink
make the code... readable!
Browse files Browse the repository at this point in the history
  • Loading branch information
Niceygy committed Jun 13, 2024
1 parent d60b71f commit a96a452
Show file tree
Hide file tree
Showing 4 changed files with 212 additions and 170 deletions.
2 changes: 1 addition & 1 deletion .prettierrc
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"printWidth": 200,
"printWidth": 750,
"singleQuote": true,
"semi": true,
"useTabs": true
Expand Down
35 changes: 35 additions & 0 deletions src/scheduled/chart.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import sendMessageToDiscord from "./weeklyMessage.js";

/**
* Creates a chart of the hightest 5 repos and sends it to the discord channel.
* @param {string} input The raw repo data
* @param {object} env The ENV object
*/
export async function chart(input, env) {
var arr = input.toString().split('\n');
var repos = [];
var counts = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i].includes(',')) {
var temp = arr[i].split(',');
repos.push(temp[0].toString().split('Repo: ')[1].replace('TheAlienDoctor/', ''));
counts.push(temp[1].toString().split('Count: ')[1]);
}
}
console.log(repos);
console.log(counts);
var chartJSON = {
type: 'bar', // Show a bar chart
data: {
labels: repos, // Set X-axis labels
datasets: [
{
label: 'Counts', // Create the 'Users' dataset
data: counts, // Add data to the chart
},
],
},
};
var chartUrl = 'https://quickchart.io/chart?c=' + /*Turn the JSON to string, then encode it to a URI*/ encodeURIComponent(JSON.stringify(chartJSON));
await sendMessageToDiscord(chartUrl, env);
}
105 changes: 105 additions & 0 deletions src/scheduled/weeklyMessage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import { chart } from "./scheduled/chart";

/**
* Sends the weekly totals to a discord channel.
* @param {object} env
* @returns
*/

export async function cron(env) {
console.log('Cron func is running...');
const KV1 = env.WDR;
const KV2 = env.WVR;
var repos = [];
var pages = [];
const Dlist = await KV1.list();
console.log('Key list aquired for downloads');
var Dtotal = 0;
var i = 0;
var len = Dlist.keys.length;
for (const { name, expiration } of Dlist.keys) {
i++;
console.log(`Getting value for ${name} (${i}/${len})`);
const value = await KV1.get(name);
if (!name || name == 'total' || name.toString().includes('%2F') || name.toString().includes('%3F') || name.toString().includes('%3D') || name.toString().includes('?file=')) {
if (!name) {
console.log('Invalid Repo, skipping');
} else {
if (name.toString().includes('%2F') || name.toString().includes('%3F') || name.toString().includes('%3D')) {
var newName = name.toString().replace('%2F', '/');
var newName = newName.replace('%3F', '?');
var newName = newName.replace('%3D', '=');
var newName = newName.split('?')[0];
var lcount = await KV1.get(newName);
await KV1.put(newName, lcount * 1 + value * 1);
await KV1.delete(name);
console.log('Deleted invalid repo ' + name + ' and replaced with ' + newName);
}
await KV1.delete(name);
console.log('Invalid Repo, deleting');
}
} else {
repos.push({ name, count: parseInt(value) });
Dtotal += parseInt(value);
}
}
repos.sort((a, b) => b.count - a.count);
const Plist = await KV2.list();
console.log('Key list aquired for pages');
var Ptotal = 0;
var i = 0;
var len = Plist.keys.length;
for (const { name, expiration } of Plist.keys) {
i++;
console.log(`Getting value for ${name} (${i}/${len})`);
const value = await KV2.get(name);
if (!name) {
console.log('Invalid page, skipping');
} else {
pages.push({ name, count: parseInt(value) });
Ptotal += parseInt(value);
}
}
pages.sort((a, b) => b.count - a.count);
let currentDate = /* @__PURE__ */ new Date();

var downloadMessageRaw = repos.map((repo) => `Repo: ${repo.name}, Count: ${repo.count}`).join('');
var downloadMessage = '# Downloads as of ' + currentDate.toUTCString() + '\n\n' + downloadMessageRaw + '\n\nTotal downloads: ' + Dtotal;
var pageViewMessage = '# Page visits as of ' + currentDate.toUTCString() + '\n\n' + pages.map((page) => `Page: ${page.name}, Count: ${page.count}`).join('');
let pageViewMessage_1 = pageViewMessage.substring(0, 1999);
let pageViewMessage_2 = pageViewMessage.substring(2e3);
console.log('Message generated. Sending to Discord...');
console.log('Sending data to ' + env.url);
await sendMessageToDiscord(downloadMessage, env);
await sendMessageToDiscord(pageViewMessage_1, env);
await chart(downloadMessageRaw);
if (pageViewMessage_2.length > 0) {
await sendMessageToDiscord(pageViewMessage_2, env);
}
console.log('Message sent to Discord');
return 'Complete! Message sent.';
}

/**
* Sends a text message to a Discord channel.
* @param {string} message The message to be sent.
* @param {object} env The ENV object.
* @returns
*/
async function sendMessageToDiscord(message, env) {
await fetch(env.url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
content: message,
}),
})
.then((response) => {
console.log('Status:', response.status);
})
.then((body) => console.log('Body:', body))
.catch((error) => console.error(error));
return;
}
Loading

0 comments on commit a96a452

Please sign in to comment.