Files
MediaCollectorLibary/resources/views/admin/index.twig
Lars Behrends a44c311e89 actor sync
2025-11-06 13:08:02 +01:00

555 lines
29 KiB
Twig

{% extends 'admin/layout.twig' %}
{% block content %}
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-light bg-light mb-4 rounded">
<div class="container-fluid">
<div class="navbar-nav me-auto">
<a class="nav-link active" href="{{ path_for('admin.index') }}">
<i class="fas fa-tachometer-alt me-2"></i>Dashboard
</a>
{% if is_admin() %}
<a class="nav-link" href="{{ path_for('admin.sources') }}">
<i class="fas fa-database me-2"></i>Sources
</a>
{% endif %}
<a class="nav-link" href="{{ path_for('admin.settings') }}">
<i class="fas fa-cog me-2"></i>Settings
</a>
</div>
</div>
</nav>
<div class="mb-4">
<h1 class="display-4 fw-bold text-dark">Admin Dashboard</h1>
<p class="lead text-muted">Manage your media sources and synchronization</p>
</div>
<!-- Source Management -->
<div class="card mb-4">
<div class="card-header">
<h2 class="h5 mb-0">Source Management</h2>
<p class="text-muted mb-0">Configure and sync your media sources</p>
</div>
<div class="card-body">
<div class="row g-3">
{% for source in sources %}
<div class="col-12 col-sm-6 col-lg-3">
<div class="card border">
<div class="card-body">
<div class="d-flex justify-content-between align-items-center mb-3">
<h6 class="card-title mb-0">{{ source.display_name }}</h6>
{% if source.is_active %}
<span class="badge bg-success">Active</span>
{% else %}
<span class="badge bg-danger">Inactive</span>
{% endif %}
</div>
<div class="mb-3">
<!-- Sync Buttons -->
{% if source.name == 'jellyfin' %}
<!-- Jellyfin-specific sync options -->
<div class="d-flex gap-1 mb-2 flex-wrap">
<button onclick="startSync({{ source.id }}, 'all')"
class="btn btn-primary btn-sm flex-fill"
data-source-id="{{ source.id }}">
All Content
</button>
<button onclick="startSync({{ source.id }}, 'movies')"
class="btn btn-outline-primary btn-sm flex-fill"
data-source-id="{{ source.id }}">
Movies Only
</button>
<button onclick="startSync({{ source.id }}, 'tvshows')"
class="btn btn-outline-primary btn-sm flex-fill"
data-source-id="{{ source.id }}">
TV Shows Only
</button>
</div>
<div class="d-flex gap-1 mb-2">
<button onclick="startSync({{ source.id }}, 'full')"
class="btn btn-secondary btn-sm flex-fill"
data-source-id="{{ source.id }}">
Full Sync
</button>
<button onclick="startSync({{ source.id }}, 'incremental')"
class="btn btn-outline-secondary btn-sm flex-fill"
data-source-id="{{ source.id }}">
Incremental
</button>
<button onclick="startSync({{ source.id }}, 'cleanup')"
class="btn btn-outline-warning btn-sm flex-fill"
data-source-id="{{ source.id }}">
Cleanup
</button>
</div>
{% elseif source.name == 'stash' %}
<!-- Stash-specific sync options -->
<div class="d-flex gap-2 mb-2">
<button onclick="startSync({{ source.id }}, 'full')"
class="btn btn-primary btn-sm flex-fill"
data-source-id="{{ source.id }}">
Full Sync
</button>
<button onclick="startSync({{ source.id }}, 'incremental')"
class="btn btn-secondary btn-sm flex-fill"
data-source-id="{{ source.id }}">
Incremental
</button>
</div>
<!-- Stash Performer Sync Button -->
<div class="mb-2">
<button onclick="syncStashPerformers()"
class="btn btn-info btn-sm w-100"
id="stash-performer-sync-btn">
<i class="bi bi-person-lines-fill me-1"></i>Sync Performers
</button>
</div>
{% else %}
<!-- Standard sync options for other sources -->
<div class="d-flex gap-2 mb-2">
<button onclick="startSync({{ source.id }}, 'full')"
class="btn btn-primary btn-sm flex-fill"
data-source-id="{{ source.id }}">
Full Sync
</button>
<button onclick="startSync({{ source.id }}, 'incremental')"
class="btn btn-secondary btn-sm flex-fill"
data-source-id="{{ source.id }}">
Incremental
</button>
</div>
{% endif %}
<!-- Last Sync Status -->
{% if source.last_sync_at %}
<div class="small text-muted">
Last sync: {{ source.last_sync_at|date('M j, Y H:i') }}
</div>
{% else %}
<div class="small text-muted">
Never synced
</div>
{% endif %}
<!-- Sync Progress (hidden by default) -->
<div id="sync-progress-{{ source.id }}" class="d-none mt-2">
<div class="progress">
<div id="sync-progress-bar-{{ source.id }}"
class="progress-bar bg-primary"
role="progressbar"
style="width: 0%">
</div>
</div>
<div id="sync-status-{{ source.id }}" class="small text-muted mt-1">
Preparing sync...
</div>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
<!-- Recent Sync Activity -->
<div class="card">
<div class="card-header">
<h2 class="h5 mb-0">Recent Sync Activity</h2>
<p class="text-muted mb-0">Latest synchronization logs and status</p>
</div>
<div class="card-body p-0">
<div class="table-responsive">
<table class="table table-hover mb-0">
<thead class="table-light">
<tr>
<th>Source</th>
<th>Type</th>
<th>Status</th>
<th>Progress</th>
<th>Items</th>
<th>Started</th>
<th>Duration</th>
<th>Message</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for sync in recent_syncs %}
<tr>
<td class="fw-medium">{{ sync.source_name }}</td>
<td>{{ sync.sync_type|title }}</td>
<td>
{% if sync.status == 'completed' %}
<span class="badge bg-success">Completed</span>
{% elseif sync.status == 'failed' %}
<span class="badge bg-danger">Failed</span>
{% elseif sync.status == 'running' %}
<span class="badge bg-warning text-dark">Running</span>
{% else %}
<span class="badge bg-secondary">{{ sync.status|title }}</span>
{% endif %}
</td>
<td>
{% if sync.total_items > 0 %}
{{ sync.processed_items }} / {{ sync.total_items }}
{% if sync.total_items > 0 %}
<div class="progress mt-1" style="height: 4px;">
<div class="progress-bar bg-primary" role="progressbar"
style="width: {{ (sync.processed_items / sync.total_items * 100)|round }}%"></div>
</div>
{% endif %}
{% else %}
-
{% endif %}
</td>
<td>
<small>
{% if sync.new_items > 0 %}<span class="text-success">+{{ sync.new_items }}</span>{% endif %}
{% if sync.updated_items > 0 %} <span class="text-primary">{{ sync.updated_items }} updated</span>{% endif %}
{% if sync.deleted_items > 0 %} <span class="text-danger">{{ sync.deleted_items }} deleted</span>{% endif %}
{% if sync.new_items == 0 and sync.updated_items == 0 and sync.deleted_items == 0 %}No changes{% endif %}
</small>
</td>
<td>
{% if sync.started_at %}
<small>{{ sync.started_at|date('M j, H:i') }}</small>
{% else %}
-
{% endif %}
</td>
<td>
{% if sync.started_at and sync.completed_at %}
{% set duration = sync.completed_at|date('U') - sync.started_at|date('U') %}
{% if duration < 60 %}
<small>{{ duration }}s</small>
{% elseif duration < 3600 %}
<small>{{ (duration / 60)|round }}m</small>
{% else %}
<small>{{ (duration / 3600)|round }}h</small>
{% endif %}
{% else %}
-
{% endif %}
</td>
<td>
{% if sync.message %}
<small class="text-muted" title="{{ sync.message }}">
{{ sync.message|length > 50 ? sync.message|slice(0, 50) ~ '...' : sync.message }}
</small>
{% else %}
<small class="text-muted">-</small>
{% endif %}
</td>
<td>
{% if sync.errors %}
<button class="btn btn-sm btn-outline-danger"
onclick="showSyncDetails({{ sync.id }}, '{{ sync.source_name }}', '{{ sync.sync_type }}')"
title="View errors and details">
Details
</button>
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
<script>
let syncIntervals = {};
function startSync(sourceId, syncType) {
// Show progress indicator
const progressDiv = document.getElementById(`sync-progress-${sourceId}`);
const progressBar = document.getElementById(`sync-progress-bar-${sourceId}`);
const statusDiv = document.getElementById(`sync-status-${sourceId}`);
progressDiv.classList.remove('d-none');
progressBar.style.width = '0%';
statusDiv.textContent = 'Starting sync...';
// Disable all sync buttons for this source - use a more reliable selector
const buttons = document.querySelectorAll(`[data-source-id="${sourceId}"]`);
buttons.forEach(button => {
button.disabled = true;
button.textContent = 'Syncing...';
button.dataset.originalText = button.textContent;
});
// Start sync via API
fetch(`/admin/sync/${sourceId}?type=${syncType}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content')
}
})
.then(response => response.json())
.then(data => {
if (data.success) {
// Start monitoring sync status
monitorSyncStatus(data.sync_log_id, sourceId, progressBar, statusDiv, buttons);
} else {
statusDiv.textContent = 'Error: ' + (data.message || 'Unknown error');
progressDiv.classList.add('d-none');
// Re-enable buttons on error
buttons.forEach(button => {
button.disabled = false;
button.textContent = button.dataset.originalText || button.textContent.replace('Syncing...', '').trim();
});
}
})
.catch(error => {
statusDiv.textContent = 'Error: ' + error.message;
progressDiv.classList.add('d-none');
// Re-enable buttons on error
buttons.forEach(button => {
button.disabled = false;
button.textContent = button.dataset.originalText || button.textContent.replace('Syncing...', '').trim();
});
});
}
function monitorSyncStatus(syncLogId, sourceId, progressBar, statusDiv, buttons) {
const interval = setInterval(() => {
fetch(`/admin/sync/status/${syncLogId}`)
.then(response => response.json())
.then(data => {
// Update progress bar using percentage from backend
if (data.progress_percentage !== undefined && data.progress_percentage > 0) {
progressBar.style.width = data.progress_percentage + '%';
}
// Update status
statusDiv.textContent = getStatusMessage(data);
// Debug logging for troubleshooting
console.log('Sync status check:', {
syncLogId: syncLogId,
status: data.status,
message: data.message,
progress_percentage: data.progress_percentage,
processed_items: data.processed_items,
total_items: data.total_items,
completed_at: data.completed_at
});
// Stop monitoring if sync is complete or failed
if (['completed', 'failed'].includes(data.status)) {
clearInterval(interval);
delete syncIntervals[sourceId];
if (data.status === 'completed') {
// Show completion message briefly before hiding
statusDiv.textContent = 'Sync completed successfully!';
setTimeout(() => {
document.getElementById(`sync-progress-${sourceId}`).classList.add('d-none');
// Re-enable buttons immediately on completion
buttons.forEach(button => {
button.disabled = false;
button.textContent = button.dataset.originalText || button.textContent.replace('Syncing...', '').trim();
});
}, 1500);
} else {
// Re-enable buttons on failure
buttons.forEach(button => {
button.disabled = false;
button.textContent = button.dataset.originalText || button.textContent.replace('Syncing...', '').trim();
});
}
}
})
.catch(error => {
console.error('Error monitoring sync:', error);
clearInterval(interval);
delete syncIntervals[sourceId];
// Re-enable buttons on error
buttons.forEach(button => {
button.disabled = false;
button.textContent = button.dataset.originalText || button.textContent.replace('Syncing...', '').trim();
});
});
}, 1000);
syncIntervals[sourceId] = interval;
}
function getStatusMessage(data) {
if (data.status === 'completed') {
let message = `Completed: ${data.new_items || 0} new`;
if (data.updated_items > 0) message += `, ${data.updated_items} updated`;
if (data.deleted_items > 0) message += `, ${data.deleted_items} deleted`;
// If we have a cleaner message from the completion handler, use it
if (data.message && !data.message.includes('===')) {
return data.message;
}
return message;
} else if (data.status === 'failed') {
return 'Failed: ' + (data.message || 'Unknown error');
} else if (data.status === 'running') {
let progress = 'Processing';
if (data.total_items > 0) {
progress += `: ${data.processed_items}/${data.total_items} items`;
}
if (data.progress_percentage !== undefined && data.progress_percentage > 0) {
progress += ` (${Math.round(data.progress_percentage)}%)`;
}
if (data.sync_type === 'cleanup') {
progress = 'Cleanup: ' + progress;
}
if (data.message && !data.message.includes('===')) {
progress += ` - ${data.message}`;
}
return progress;
} else {
return data.message || 'Unknown status';
}
}
function showSyncDetails(syncId, sourceName, syncType) {
// Fetch detailed sync information
fetch(`/admin/sync/status/${syncId}`)
.then(response => response.json())
.then(data => {
const modal = document.createElement('div');
modal.className = 'modal fade show';
modal.style.display = 'block';
modal.innerHTML = `
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Sync Details: ${sourceName} - ${syncType}</h5>
<button type="button" class="btn-close" onclick="closeModal()"></button>
</div>
<div class="modal-body">
<div class="row mb-3">
<div class="col-md-6">
<strong>Status:</strong>
<span class="badge bg-${data.status === 'completed' ? 'success' : data.status === 'failed' ? 'danger' : 'warning'} ms-2">
${data.status}
</span>
</div>
<div class="col-md-6">
<strong>Started:</strong> ${data.started_at ? new Date(data.started_at).toLocaleString() : 'N/A'}
</div>
</div>
<div class="row mb-3">
<div class="col-md-6">
<strong>Completed:</strong> ${data.completed_at ? new Date(data.completed_at).toLocaleString() : 'N/A'}
</div>
<div class="col-md-6">
<strong>Duration:</strong> ${data.started_at && data.completed_at ?
formatDuration(new Date(data.completed_at) - new Date(data.started_at)) : 'N/A'}
</div>
</div>
<div class="row mb-3">
<div class="col-md-3"><strong>Total Items:</strong> ${data.total_items || 0}</div>
<div class="col-md-3"><strong>Processed:</strong> ${data.processed_items || 0}</div>
<div class="col-md-3"><strong>New:</strong> <span class="text-success">${data.new_items || 0}</span></div>
<div class="col-md-3"><strong>Updated:</strong> <span class="text-primary">${data.updated_items || 0}</span></div>
</div>
<div class="mb-3">
<strong>Message:</strong>
<div class="alert alert-info">${data.message || 'No message available'}</div>
</div>
${data.errors && data.errors.length > 0 ? `
<div class="mb-3">
<strong>Errors:</strong>
<div class="alert alert-danger">
<ul class="mb-0">
${data.errors.map(error => `<li>${error}</li>`).join('')}
</ul>
</div>
</div>
` : ''}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" onclick="closeModal()">Close</button>
</div>
</div>
</div>
`;
document.body.appendChild(modal);
})
.catch(error => {
console.error('Error fetching sync details:', error);
alert('Error loading sync details');
});
}
function closeModal() {
const modal = document.querySelector('.modal.show');
if (modal) {
modal.remove();
}
}
function formatDuration(ms) {
const seconds = Math.floor(ms / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
if (hours > 0) {
return `${hours}h ${minutes % 60}m`;
} else if (minutes > 0) {
return `${minutes}m ${seconds % 60}s`;
} else {
return `${seconds}s`;
}
}
function syncStashPerformers() {
const button = document.getElementById('stash-performer-sync-btn');
const originalText = button.innerHTML;
// Show loading state
button.disabled = true;
button.innerHTML = '<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>Syncing...';
// Make AJAX request to sync performers
fetch('/api/actors/sync-existing-stash', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content')
}
})
.then(response => response.json())
.then(data => {
if (data.success) {
alert(`Stash performer sync completed!\n\nProcessed: ${data.results.processed}\nUpdated: ${data.results.updated}\nSkipped: ${data.results.skipped}\nNot found in Stash: ${data.results.not_found_in_stash.length}\n\nCheck the logs for detailed information.`);
} else {
alert('Error syncing performers: ' + (data.error || 'Unknown error'));
}
// Re-enable button
button.disabled = false;
button.innerHTML = originalText;
})
.catch(error => {
alert('Failed to sync performers: ' + error.message);
// Re-enable button
button.disabled = false;
button.innerHTML = originalText;
});
}
// Cleanup intervals on page unload
window.addEventListener('beforeunload', () => {
Object.values(syncIntervals).forEach(interval => clearInterval(interval));
});
</script>
{% endblock %}