ElevAIt / scripts /github-db-sync.js
Mahdi Naser Moghadasi
Claude Opus 4.5
Add GitHub sync daemon to push logs to mahdinaser/brightmind repo
96fdde4
Raw History Blame Contribute Delete
5.21 kB
/**
* GitHub Sync Script for ElevAIt
*
* Syncs visitor logs to GitHub using API
* GitHub Repo: https://github.com/mahdinaser/brightmind.git
* Log path: elevait-logs/YYYY-MM-DD/log_HH-MM.txt
*/
const fs = require('fs');
const path = require('path');
const https = require('https');
const GITHUB_REPO = 'mahdinaser/brightmind';
const GITHUB_BRANCH = 'main';
const LOG_PREFIX = 'elevait-logs'; // Separate folder for ElevAIt logs
const GITHUB_TOKEN = process.env.GITHUB_TOKEN;
// Helper to make GitHub API requests
async function githubRequest(method, endpoint, data = null) {
return new Promise((resolve, reject) => {
const options = {
hostname: 'api.github.com',
path: endpoint,
method: method,
headers: {
'Authorization': `token ${GITHUB_TOKEN}`,
'User-Agent': 'ElevAIt-Log-Sync',
'Accept': 'application/vnd.github.v3+json',
'Content-Type': 'application/json'
}
};
const req = https.request(options, (res) => {
let body = '';
res.on('data', chunk => body += chunk);
res.on('end', () => {
try {
const parsed = body ? JSON.parse(body) : {};
if (res.statusCode >= 200 && res.statusCode < 300) {
resolve(parsed);
} else {
reject(new Error(`GitHub API error ${res.statusCode}: ${parsed.message || body}`));
}
} catch (e) {
resolve(body);
}
});
});
req.on('error', reject);
if (data) {
req.write(JSON.stringify(data));
}
req.end();
});
}
// Push log file to GitHub (in date folders) with retry on 409 conflict
async function pushLogToGitHub(logPath, logContent, retryCount = 0) {
console.log(`πŸ“‹ Pushing log to GitHub: ${logPath}`);
if (!GITHUB_TOKEN) {
console.warn('⚠️ GITHUB_TOKEN not set, skipping log push');
return false;
}
try {
const base64Content = Buffer.from(logContent).toString('base64');
// Check if file already exists (to get SHA for update)
let sha = null;
try {
const existing = await githubRequest('GET', `/repos/${GITHUB_REPO}/contents/${logPath}?ref=${GITHUB_BRANCH}`);
sha = existing.sha;
// If file exists, append content instead of replacing
if (existing.content) {
const existingContent = Buffer.from(existing.content, 'base64').toString('utf8');
const combinedContent = existingContent + '\n' + logContent;
const base64Combined = Buffer.from(combinedContent).toString('base64');
const timestamp = new Date().toISOString();
const data = {
message: `ElevAIt logs update - ${timestamp}`,
content: base64Combined,
branch: GITHUB_BRANCH,
sha: sha
};
await githubRequest('PUT', `/repos/${GITHUB_REPO}/contents/${logPath}`, data);
console.log(`βœ… Log appended to GitHub: ${logPath}`);
return true;
}
} catch (e) {
// File doesn't exist yet, that's fine - create new
}
const timestamp = new Date().toISOString();
const data = {
message: `ElevAIt logs - ${timestamp}`,
content: base64Content,
branch: GITHUB_BRANCH
};
if (sha) {
data.sha = sha;
}
await githubRequest('PUT', `/repos/${GITHUB_REPO}/contents/${logPath}`, data);
console.log(`βœ… Log pushed to GitHub: ${logPath}`);
return true;
} catch (error) {
// Retry on 409 conflict (SHA mismatch)
if (error.message.includes('409') && retryCount < 3) {
console.log(`⚠️ Log SHA conflict, retrying... (attempt ${retryCount + 2})`);
await new Promise(r => setTimeout(r, 1000)); // Wait 1 second
return pushLogToGitHub(logPath, logContent, retryCount + 1);
}
console.error('❌ Failed to push log to GitHub:', error.message);
return false;
}
}
// Collect all logs from local directory and push to GitHub
async function syncLogsToGitHub() {
const dataDir = process.env.DATA_DIR || '/data';
const logsDir = path.join(dataDir, 'career-growth-project');
if (!fs.existsSync(logsDir)) {
console.log('πŸ“‹ No logs directory found');
return;
}
// Get all date directories
const dateDirs = fs.readdirSync(logsDir).filter(d => d.match(/^\d{4}-\d{2}-\d{2}$/));
for (const dateDir of dateDirs) {
const datePath = path.join(logsDir, dateDir);
const logFiles = fs.readdirSync(datePath).filter(f => f.endsWith('.txt'));
for (const logFile of logFiles) {
const localPath = path.join(datePath, logFile);
const content = fs.readFileSync(localPath, 'utf-8');
if (!content.trim()) continue;
const githubPath = `${LOG_PREFIX}/${dateDir}/${logFile}`;
await pushLogToGitHub(githubPath, content);
}
}
}
// Export functions for use in other modules
module.exports = { pushLogToGitHub, syncLogsToGitHub, githubRequest };
// Run if called directly
if (require.main === module) {
const command = process.argv[2];
switch (command) {
case 'sync':
syncLogsToGitHub().catch(console.error);
break;
default:
console.log('Usage: node github-db-sync.js [sync]');
console.log(' sync - Upload all logs to GitHub');
}
}