Skip to content

Commit

Permalink
Update to 2.0.0 (DB)
Browse files Browse the repository at this point in the history
  • Loading branch information
gagaball88 committed Jan 26, 2025
1 parent 8f83038 commit e839ec3
Show file tree
Hide file tree
Showing 5 changed files with 81 additions and 19 deletions.
11 changes: 6 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "tdp-picture-bot",
"version": "1.0.0",
"version": "2.0.0",
"description": "",
"main": "index.js",
"scripts": {
Expand All @@ -10,9 +10,10 @@
"author": "gagaball88",
"license": "",
"dependencies": {
"dotenv": "^16.0.3",
"esc-exit": "^3.0.0",
"twitter-api-v2": "^1.14.3",
"play-sound": "^1.1.5"
"dotenv": "16.4.7",
"esc-exit": "3.0.1",
"twitter-api-v2": "1.19.0",
"pg": "8.13.1",
"play-sound": "1.1.6"
}
}
2 changes: 1 addition & 1 deletion src/config/config.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"debuggingEnv": false,
"slot": 2
"slot": "s1e1"

}
14 changes: 13 additions & 1 deletion src/config/credentials.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,16 @@ export let twitterConfig = {
accessSecret : process.env.TWITTER_ACCESS_TOKEN_SECRET,

//bearerToken : process.env.TWITTER_BEARER_TOKEN
};
};

export let pgConfig = {
host: process.env.PG_HOST_IP,

port: process.env.PG_HOST_PORT,

user: process.env.PG_USERNAME,

password: process.env.PG_PASSWORD,

database: process.env.PG_DATABASE,
}
2 changes: 1 addition & 1 deletion src/utils/initPost.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export default async function initPost(pictureSlot) {

let picture = refreshPic(pictureSlot);

let message = ""
let message = "#TDPPictures #RenewArc3 #GiveUsTheSaga #ContinueTheSaga"
//console.log(picture);

let debuggingEnv = config.debuggingEnv
Expand Down
71 changes: 60 additions & 11 deletions src/utils/refreshPic.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,67 @@
import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url';
import { dirname } from 'path';
import pg from 'pg';
import logger from './logger.js';
const { Client } = pg;
import { pgConfig } from "../config/credentials.js";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const outputDir = './pictures';

export default function refreshPic(slot) {
return `./pictures/slot${slot}/${getPicture(slot)}`
}
async function extractImage(categories) {
const client = new Client(pgConfig);

try {
await client.connect();

//Convert categories to a string if it's an array
const categoryArray = Array.isArray(categories) ? categories : categories.split(',');
const uniqueCategories = Array.from(new Set(categoryArray.map(c => c.trim()))); //Remove duplicates and trim whitespace

//Get the total number of rows for the specified categories
const countQuery = `SELECT COUNT(*) FROM pictures WHERE category IN (${uniqueCategories.map((_, i) => `$${i + 1}`).join(',')})`;
const countResult = await client.query(countQuery, uniqueCategories);
const totalCount = parseInt(countResult.rows[0].count, 10);

if (totalCount === 0) {
throw new Error(`No pictures found in the specified categories: ${uniqueCategories.join(', ')}`);
}

//Generate a random index based on the total count
const randomIndex = Math.floor(Math.random() * totalCount);
//logger("Total count: " + totalCount + ", Index: " + randomIndex);

//Fetch the random picture based on the random index
const pictureQuery = `
SELECT id, picture_data FROM pictures
WHERE category IN (${uniqueCategories.map((_, i) => `$${i + 1}`).join(',')})
ORDER BY id OFFSET $${uniqueCategories.length + 1} LIMIT 1`;

const pictureResult = await client.query(pictureQuery, [...uniqueCategories, randomIndex]);

if (pictureResult.rows.length === 0) {
throw new Error(`Picture not found for the specified categories at index ${randomIndex}.`);
}

const picture = pictureResult.rows[0];

//Ensure the output directory exists
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}

//Save the picture as a file
const filePath = path.join(outputDir, `temp_img.jpg`);
fs.writeFileSync(filePath, picture.picture_data);

logger(`Image with ID ${picture.id} saved to ${filePath}`);
} catch (error) {
logger.error('Failed to extract the image:', error);
} finally {
await client.end();
}
}

function getPicture(slot) {
let paths = fs.readdirSync(path.resolve(__dirname, `../pictures/slot${slot}/`));
let randomNumber = Math.floor(Math.random() * paths.length);
return paths[randomNumber];
export default function refreshPic(categories) {
extractImage(categories);
return path.join(outputDir, `temp_img.jpg`);
}

0 comments on commit e839ec3

Please sign in to comment.