Add Social Scheduler — global social media post scheduling

- New /social page with left/right layout (form + post list)
- Social topbar link
- Tables: social_posts, social_targets (project-agnostic posts, per-target project refs)
- CRUD: create, edit, duplicate, delete, retry
- Image upload (JPEG/PNG/GIF/WebP, 10MB max) stored in data/social-uploads/
- Per-platform image toggle (Discord multipart, Mastodon /api/v2/media, LinkedIn Assets API)
- bin/dispatch-social.php cron dispatcher (every minute via /etc/cron.d)
- Settings: eligible projects section to enable bot projects as social account sources
- Platforms: Discord (webhook), Mastodon, LinkedIn personal profile

Cron setup:
  * * * * * www-data /usr/bin/php /opt/hackmancms/bin/dispatch-social.php >> /var/log/hackman_social.log 2>&1

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Bashy 2026-06-03 17:01:03 +03:00
parent 45b9e15152
commit ac5c262bfb
9 changed files with 1081 additions and 0 deletions

View file

@ -3819,3 +3819,352 @@ window.addEventListener('DOMContentLoaded', () => {
loadLogs();
})();
// ── Social Scheduler ─────────────────────────────────────────────────────────
(function () {
const page = document.getElementById('socialPage');
if (!page) return;
let _targets = [];
let _filter = 'pending';
let _hasImage = false;
const esc = s => String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
// ── Targets ──────────────────────────────────────────────────────────────────
async function loadTargets() {
const r = await fetch('/api/social?action=targets');
const d = await r.json();
_targets = d.groups || [];
renderTargets(null);
}
function renderTargets(prefill) {
const el = document.getElementById('socialTargets');
if (!_targets.length) {
el.innerHTML = '<div class="text-muted small">No eligible projects configured. <a href="/settings">Go to Settings</a> to enable projects.</div>';
return;
}
const platformIcon = { discord: 'bi-discord', mastodon: 'bi-mastodon', linkedin: 'bi-linkedin' };
const platformLabel = { discord: 'Discord', mastodon: 'Mastodon', linkedin: 'LinkedIn' };
el.innerHTML = _targets.map(group => {
const platforms = ['discord', 'mastodon', 'linkedin'].filter(p => group.targets[p]?.length);
if (!platforms.length) return '';
return `<div class="mb-3">
<div class="small fw-semibold text-muted mb-1">${esc(group.project_name)}</div>
${platforms.map(platform => `
<div class="mb-2">
<div class="small text-muted mb-1"><i class="bi ${platformIcon[platform]}"></i> ${platformLabel[platform]}</div>
${group.targets[platform].map(t => {
const cbId = `st_${group.project_id}_${platform}_${t.key}`;
const imgId = `si_${group.project_id}_${platform}_${t.key}`;
const checked = prefill?.some(x => x.project_id == group.project_id && x.platform === platform && x.target_key === t.key) ? 'checked' : '';
const imgChecked = prefill?.some(x => x.project_id == group.project_id && x.platform === platform && x.target_key === t.key && x.include_image) ? 'checked' : '';
return `<div class="d-flex align-items-center gap-2 mb-1">
<input class="form-check-input social-target-cb" type="checkbox" id="${cbId}"
data-pid="${group.project_id}" data-platform="${platform}" data-key="${esc(t.key)}" ${checked}>
<label class="form-check-label small flex-grow-1" for="${cbId}">${esc(t.label)}</label>
<input class="form-check-input social-img-cb ${_hasImage ? '' : 'd-none'}" type="checkbox" id="${imgId}"
data-for="${cbId}" title="Include image" ${imgChecked}>
<label class="form-check-label small text-muted ${_hasImage ? '' : 'd-none'}" for="${imgId}">
<i class="bi bi-image"></i>
</label>
</div>`;
}).join('')}
</div>`).join('')}
</div>`;
}).join('');
}
function toggleImageCols(show) {
_hasImage = show;
page.querySelectorAll('.social-img-cb, .social-img-cb + label').forEach(el => {
el.classList.toggle('d-none', !show);
});
}
function collectTargets() {
const targets = [];
page.querySelectorAll('.social-target-cb:checked').forEach(cb => {
const imgCb = page.querySelector(`.social-img-cb[data-for="${cb.id}"]`);
targets.push({
project_id: +cb.dataset.pid,
platform: cb.dataset.platform,
target_key: cb.dataset.key,
include_image: imgCb?.checked ? 1 : 0,
});
});
return targets;
}
// ── Image upload ─────────────────────────────────────────────────────────────
document.getElementById('socialUploadBtn').addEventListener('click', () => {
document.getElementById('socialImageInput').click();
});
document.getElementById('socialImageInput').addEventListener('change', async function () {
const file = this.files[0];
if (!file) return;
const fd = new FormData();
fd.append('image', file);
const r = await fetch('/api/social_upload', { method: 'POST', body: fd });
const d = await r.json();
if (d.error) { showSocialError(d.error); return; }
document.getElementById('socialImagePath').value = d.path;
document.getElementById('socialImageThumb').src = d.url;
document.getElementById('socialImagePreview').classList.remove('d-none');
document.getElementById('socialRemoveImageBtn').classList.remove('d-none');
toggleImageCols(true);
this.value = '';
});
document.getElementById('socialRemoveImageBtn').addEventListener('click', () => {
document.getElementById('socialImagePath').value = '';
document.getElementById('socialImageThumb').src = '';
document.getElementById('socialImagePreview').classList.add('d-none');
document.getElementById('socialRemoveImageBtn').classList.add('d-none');
toggleImageCols(false);
});
// ── Form submit ───────────────────────────────────────────────────────────────
document.getElementById('socialSubmitBtn').addEventListener('click', async () => {
const editId = document.getElementById('socialEditId').value;
const content = document.getElementById('socialContent').value.trim();
const scheduledAt = document.getElementById('socialScheduledAt').value;
const imagePath = document.getElementById('socialImagePath').value;
const targets = collectTargets();
hideSocialError();
if (!content) { showSocialError('Content is required'); return; }
if (!scheduledAt) { showSocialError('Scheduled time is required'); return; }
if (!targets.length) { showSocialError('Select at least one platform target'); return; }
const body = { action: editId ? 'update' : 'create', content, scheduled_at: scheduledAt, image_path: imagePath, targets };
if (editId) body.id = +editId;
const r = await fetch('/api/social', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
const d = await r.json();
if (d.error) { showSocialError(d.error); return; }
resetForm();
loadPosts();
});
// ── Edit ─────────────────────────────────────────────────────────────────────
function startEdit(post) {
document.getElementById('socialEditId').value = post.id;
document.getElementById('socialContent').value = post.content;
document.getElementById('socialScheduledAt').value = post.scheduled_at.replace(' ', 'T').substring(0, 16);
document.getElementById('socialFormTitle').textContent = 'Edit post';
document.getElementById('socialCancelEditBtn').classList.remove('d-none');
document.getElementById('socialSubmitBtn').innerHTML = '<i class="bi bi-pencil me-1"></i>Update';
if (post.image_url) {
document.getElementById('socialImagePath').value = post.image_path || '';
document.getElementById('socialImageThumb').src = post.image_url;
document.getElementById('socialImagePreview').classList.remove('d-none');
document.getElementById('socialRemoveImageBtn').classList.remove('d-none');
toggleImageCols(true);
} else {
toggleImageCols(false);
}
renderTargets(post.targets || []);
document.getElementById('socialFormCard').scrollIntoView({ behavior: 'smooth', block: 'start' });
hideSocialError();
}
document.getElementById('socialCancelEditBtn').addEventListener('click', resetForm);
// ── Duplicate ─────────────────────────────────────────────────────────────────
async function duplicatePost(id) {
const r = await fetch('/api/social', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'duplicate', id }) });
const d = await r.json();
if (d.error) { alert(d.error); return; }
document.getElementById('socialEditId').value = '';
document.getElementById('socialContent').value = d.post.content;
document.getElementById('socialScheduledAt').value = '';
document.getElementById('socialFormTitle').textContent = 'Schedule a post';
document.getElementById('socialCancelEditBtn').classList.add('d-none');
document.getElementById('socialSubmitBtn').innerHTML = '<i class="bi bi-calendar-plus me-1"></i>Schedule';
if (d.post.image_url) {
document.getElementById('socialImagePath').value = d.post.image_path || '';
document.getElementById('socialImageThumb').src = d.post.image_url;
document.getElementById('socialImagePreview').classList.remove('d-none');
document.getElementById('socialRemoveImageBtn').classList.remove('d-none');
toggleImageCols(true);
} else {
document.getElementById('socialImagePath').value = '';
document.getElementById('socialImagePreview').classList.add('d-none');
document.getElementById('socialRemoveImageBtn').classList.add('d-none');
toggleImageCols(false);
}
renderTargets(d.targets || []);
document.getElementById('socialFormCard').scrollIntoView({ behavior: 'smooth', block: 'start' });
hideSocialError();
}
function resetForm() {
document.getElementById('socialEditId').value = '';
document.getElementById('socialContent').value = '';
document.getElementById('socialScheduledAt').value = '';
document.getElementById('socialImagePath').value = '';
document.getElementById('socialImageThumb').src = '';
document.getElementById('socialImagePreview').classList.add('d-none');
document.getElementById('socialRemoveImageBtn').classList.add('d-none');
document.getElementById('socialFormTitle').textContent = 'Schedule a post';
document.getElementById('socialCancelEditBtn').classList.add('d-none');
document.getElementById('socialSubmitBtn').innerHTML = '<i class="bi bi-calendar-plus me-1"></i>Schedule';
toggleImageCols(false);
renderTargets(null);
hideSocialError();
}
// ── Post list ─────────────────────────────────────────────────────────────────
async function loadPosts() {
const r = await fetch('/api/social?status=' + _filter);
const d = await r.json();
const el = document.getElementById('socialPostsList');
if (d.error) { el.innerHTML = `<div class="alert alert-danger small">${esc(d.error)}</div>`; return; }
if (!d.posts.length) { el.innerHTML = '<div class="text-muted small">No posts yet.</div>'; return; }
const statusBadge = s => {
const cls = { pending: 'bg-warning text-dark', sent: 'bg-success', failed: 'bg-danger', done: 'bg-success', partial: 'bg-warning text-dark', processing: 'bg-info text-dark' };
return `<span class="badge ${cls[s] || 'bg-secondary'} fw-normal">${esc(s)}</span>`;
};
const platformIcon = { discord: 'bi-discord', mastodon: 'bi-mastodon', linkedin: 'bi-linkedin' };
const relTime = ts => {
const diff = (new Date(ts.replace(' ', 'T') + 'Z') - Date.now()) / 1000;
if (Math.abs(diff) < 60) return 'just now';
if (Math.abs(diff) < 3600) return Math.round(Math.abs(diff)/60) + (diff>0?' min':' min ago');
if (Math.abs(diff) < 86400) return Math.round(Math.abs(diff)/3600) + (diff>0?' h':' h ago');
return Math.round(Math.abs(diff)/86400) + (diff>0?' d':' d ago');
};
el.innerHTML = d.posts.map(post => {
const preview = post.content.length > 160 ? post.content.substring(0, 160) + '…' : post.content;
const targBadges = (post.targets || []).map(t =>
`<span class="badge bg-secondary fw-normal d-inline-flex align-items-center gap-1">
<i class="bi ${platformIcon[t.platform] || 'bi-dot'}"></i>${esc(t.target_key)}
${statusBadge(t.status)}
${t.error ? `<span title="${esc(t.error)}"><i class="bi bi-exclamation-circle text-danger"></i></span>` : ''}
</span>`).join(' ');
const imgHtml = post.image_url
? `<div class="flex-shrink-0"><img src="${esc(post.image_url)}" style="width:72px;height:72px;object-fit:cover;border-radius:4px;border:1px solid var(--hm-border)"></div>`
: '';
const canRetry = post.targets?.some(t => t.status === 'failed');
return `<div class="card mb-2 social-post-card" data-id="${post.id}">
<div class="card-body py-2">
<div class="d-flex gap-3 align-items-start">
${imgHtml}
<div class="flex-grow-1 min-width-0">
<div class="small mb-2" style="white-space:pre-wrap">${esc(preview)}</div>
<div class="d-flex flex-wrap gap-1 mb-2">${targBadges}</div>
<div class="d-flex align-items-center gap-3 flex-wrap">
<span class="small text-muted"><i class="bi bi-clock me-1"></i>${esc(post.scheduled_at)} <span class="text-muted">(${relTime(post.scheduled_at)})</span></span>
${statusBadge(post.status)}
<div class="ms-auto d-flex gap-1">
${canRetry ? `<button class="btn btn-xs btn-outline-warning retry-post-btn" data-id="${post.id}">Retry</button>` : ''}
<button class="btn btn-xs btn-outline-secondary edit-post-btn" data-id="${post.id}">Edit</button>
<button class="btn btn-xs btn-outline-secondary dup-post-btn" data-id="${post.id}">Duplicate</button>
<button class="btn btn-xs btn-outline-danger del-post-btn" data-id="${post.id}">Delete</button>
</div>
</div>
</div>
</div>
</div>
</div>`;
}).join('');
// Store post data for edit
el._posts = d.posts;
el.querySelectorAll('.edit-post-btn').forEach(b => b.addEventListener('click', () => {
const post = el._posts.find(p => p.id == b.dataset.id);
if (post) startEdit(post);
}));
el.querySelectorAll('.dup-post-btn').forEach(b => b.addEventListener('click', () => duplicatePost(+b.dataset.id)));
el.querySelectorAll('.del-post-btn').forEach(b => b.addEventListener('click', async () => {
if (!confirm('Delete this post?')) return;
const r = await fetch('/api/social', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'delete', id: +b.dataset.id }) });
const d = await r.json();
if (d.ok) loadPosts(); else alert(d.error);
}));
el.querySelectorAll('.retry-post-btn').forEach(b => b.addEventListener('click', async () => {
const r = await fetch('/api/social', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'retry', id: +b.dataset.id }) });
const d = await r.json();
if (d.ok) loadPosts(); else alert(d.error);
}));
}
// ── Filters ───────────────────────────────────────────────────────────────────
document.getElementById('socialFilterPending').addEventListener('click', function () {
_filter = 'pending';
this.classList.add('active');
document.getElementById('socialFilterAll').classList.remove('active');
loadPosts();
});
document.getElementById('socialFilterAll').addEventListener('click', function () {
_filter = 'all';
this.classList.add('active');
document.getElementById('socialFilterPending').classList.remove('active');
loadPosts();
});
document.getElementById('socialRefreshBtn').addEventListener('click', loadPosts);
// ── Helpers ───────────────────────────────────────────────────────────────────
function showSocialError(msg) {
const el = document.getElementById('socialFormError');
el.textContent = msg;
el.classList.remove('d-none');
}
function hideSocialError() {
document.getElementById('socialFormError').classList.add('d-none');
}
// Default datetime to now + 1 hour
const dt = new Date(Date.now() + 3600000);
dt.setSeconds(0, 0);
document.getElementById('socialScheduledAt').value = dt.toISOString().slice(0, 16);
loadTargets();
loadPosts();
})();
// ── Settings: social eligible projects ──────────────────────────────────────
(function () {
const list = document.getElementById('socialProjectsList');
if (!list) return;
async function loadSocialSettings() {
const r = await fetch('/api/social?action=settings');
const d = await r.json();
const enabled = d.enabled || [];
if (!d.projects.length) {
list.innerHTML = '<div class="text-muted small">No Discord Bot projects found. Add one via project scan first.</div>';
return;
}
list.innerHTML = d.projects.map(p => `
<div class="form-check">
<input class="form-check-input social-proj-cb" type="checkbox" id="sp_${p.id}" value="${p.id}" ${enabled.includes(+p.id) ? 'checked' : ''}>
<label class="form-check-label small" for="sp_${p.id}">${p.name}</label>
</div>`).join('');
}
document.getElementById('saveSocialProjectsBtn').addEventListener('click', async () => {
const ids = [...list.querySelectorAll('.social-proj-cb:checked')].map(cb => +cb.value);
const r = await fetch('/api/social', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'save_settings', project_ids: ids }) });
const d = await r.json();
if (d.ok) {
const saved = document.getElementById('socialProjectsSaved');
saved.classList.remove('d-none');
setTimeout(() => saved.classList.add('d-none'), 2000);
}
});
loadSocialSettings();
})();