instagram / server.js
Yogesh
Add Space configuration
5b89d2a
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const path = require('path');
const { createGamePost } = require('./automation');
const cron = require('node-cron');
const app = express();
const PORT = process.env.PORT || 7860; // HF Spaces default port
app.use(cors());
app.use(express.json());
app.use(express.static(path.join(__dirname)));
// API to get trending games
app.get('/api/trending-games', async (req, res) => {
try {
const { getTrendingGamesFromAI } = require('./automation');
const slugs = await getTrendingGamesFromAI();
// Fetch brief info for each from RAWG
const RAWG_API_KEY = process.env.RAWG_API_KEY;
const games = await Promise.all(slugs.slice(0, 8).map(async slug => {
try {
const resp = await axios.get(`https://api.rawg.io/api/games/${slug}?key=${RAWG_API_KEY}`);
return {
name: resp.data.name,
image: resp.data.background_image,
slug: slug
};
} catch (e) { return null; }
}));
res.json(games.filter(g => g !== null));
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Automation: Run every hour
cron.schedule('0 * * * *', async () => {
console.log('⏰ Hourly Automation Triggered...');
const { processNextGame } = require('./automation');
try {
const game = await processNextGame();
console.log(`✅ Successfully processed: ${game}`);
} catch (e) {
console.error(`❌ Hourly Task Failed: ${e.message}`);
}
});
// Manage Instagram Accounts (Simple in-memory for demo, but can be persistent)
let accounts = [];
app.post('/api/accounts', (req, res) => {
const { username, password } = req.body;
if (username) {
accounts.push({ username, status: 'connected' });
res.json({ success: true, accounts });
} else {
res.status(400).json({ error: 'Username required' });
}
});
app.get('/api/accounts', (req, res) => {
res.json(accounts);
});
// Verify Instagram Token and Fetch Username
app.post('/api/instagram/verify', async (req, res) => {
const { accessToken, accountId } = req.body;
try {
const response = await axios.get(`https://graph.facebook.com/v19.0/${accountId}?fields=username,name&access_token=${accessToken}`);
const { username, name } = response.data;
// Save to active accounts
const newAccount = { username, name, accountId, status: 'Active' };
accounts.push(newAccount);
res.json({ success: true, account: newAccount });
} catch (error) {
console.error('Verification Error:', error.response ? error.response.data : error.message);
res.status(400).json({ success: false, error: 'Invalid Token or Account ID' });
}
});
// OAuth Callback Endpoint
app.get('/api/auth/callback', (req, res) => {
const code = req.query.code;
if (code) {
res.send('<h1>Authentication Successful!</h1><p>You can close this window and return to the dashboard.</p>');
} else {
res.status(400).send('Authentication Failed');
}
});
// API to manually trigger post generation
app.post('/api/generate-posts', async (req, res) => {
try {
const { processNextGame } = require('./automation');
const game = await processNextGame();
res.json({ success: true, message: `Auto-post triggered for ${game}` });
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
});
// Serve the frontend
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
// Automation: Run daily at 9:00 AM
// Note: node-cron needs to be installed
// cron.schedule('0 9 * * *', async () => {
// console.log('Running daily automation...');
// const games = ['red-dead-redemption-2', 'god-of-war-4', 'elden-ring'];
// for (const game of games) {
// await createGamePost(game);
// }
// });
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});