← back to Dear Bubbe Nextjs

lib/instagram-service.js

99 lines

#!/usr/bin/env node

const { postAnonymousToInstagram } = require('./instagram-poster');
const fs = require('fs').promises;

const CONFIG = {
    CHECK_INTERVAL: 2 * 60 * 60 * 1000, // Check every 2 hours
    STATE_FILE: '/root/Projects/dear-bubbe-admin/logs/instagram-state.json',
    POSTS_PER_DAY: 3,
    MIN_INTERVAL_HOURS: 6
};

async function loadState() {
    try {
        const data = await fs.readFile(CONFIG.STATE_FILE, 'utf8');
        return JSON.parse(data);
    } catch {
        return {
            postedMessages: [],
            lastPostTime: null,
            totalPosts: 0,
            dailyPosts: 0,
            lastResetDate: new Date().toDateString()
        };
    }
}

async function shouldPost() {
    const state = await loadState();
    
    // Reset daily counter
    const today = new Date().toDateString();
    if (today !== state.lastResetDate) {
        return true; // New day, can post
    }
    
    // Check daily limit
    if (state.dailyPosts >= CONFIG.POSTS_PER_DAY) {
        console.log(`📊 Daily limit reached (${state.dailyPosts}/${CONFIG.POSTS_PER_DAY})`);
        return false;
    }
    
    // Check time since last post
    if (state.lastPostTime) {
        const hoursSince = (Date.now() - new Date(state.lastPostTime).getTime()) / (1000 * 60 * 60);
        if (hoursSince < CONFIG.MIN_INTERVAL_HOURS) {
            console.log(`⏱️ Wait ${(CONFIG.MIN_INTERVAL_HOURS - hoursSince).toFixed(1)} more hours`);
            return false;
        }
    }
    
    return true;
}

async function runService() {
    console.log('🚀 Instagram Service Started');
    console.log(`📸 Will post up to ${CONFIG.POSTS_PER_DAY} times per day`);
    console.log(`⏱️ Minimum ${CONFIG.MIN_INTERVAL_HOURS} hours between posts`);
    console.log(`🔄 Checking every ${CONFIG.CHECK_INTERVAL / 1000 / 60} minutes`);
    console.log('=' .repeat(40));
    
    // Main service loop
    async function checkAndPost() {
        try {
            const canPost = await shouldPost();
            if (canPost) {
                console.log(`\n[${new Date().toISOString()}] Attempting to post...`);
                await postAnonymousToInstagram();
            } else {
                console.log(`[${new Date().toISOString()}] Skipping - conditions not met`);
            }
        } catch (error) {
            console.error(`[${new Date().toISOString()}] Error:`, error.message);
        }
    }
    
    // Post immediately on startup if conditions are met
    await checkAndPost();
    
    // Then check periodically
    setInterval(checkAndPost, CONFIG.CHECK_INTERVAL);
    
    // Keep the process alive
    process.on('SIGTERM', () => {
        console.log('📛 Service shutting down...');
        process.exit(0);
    });
    
    process.on('SIGINT', () => {
        console.log('📛 Service interrupted...');
        process.exit(0);
    });
}

// Start the service
runService().catch(error => {
    console.error('Fatal error:', error);
    process.exit(1);
});