app.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. // ==================== Utility Functions ====================
  2. function showMessage(text, type = 'success') {
  3. const messageEl = document.getElementById('message');
  4. if (!messageEl) return;
  5. messageEl.textContent = text;
  6. messageEl.className = `message ${type}`;
  7. setTimeout(() => {
  8. messageEl.className = 'message hidden';
  9. }, 5000);
  10. }
  11. async function handleApiError(response) {
  12. if (response.status === 401) {
  13. // Unauthorized - redirect to login
  14. window.location.href = '/login';
  15. return true;
  16. }
  17. return false;
  18. }
  19. // ==================== Authentication Functions ====================
  20. async function handleLogin(event) {
  21. // Let the form submit naturally - server will handle redirect
  22. // No need to prevent default or use fetch
  23. }
  24. async function handleRegister(event) {
  25. // Let the form submit naturally - server will handle redirect
  26. // No need to prevent default or use fetch
  27. }
  28. async function logout() {
  29. try {
  30. const response = await fetch('/api/auth/logout', {
  31. method: 'POST'
  32. });
  33. const data = await response.json();
  34. if (data.status === 'success') {
  35. window.location.href = '/';
  36. }
  37. } catch (error) {
  38. console.error('Logout error:', error);
  39. window.location.href = '/';
  40. }
  41. }
  42. // ==================== Dashboard Functions ====================
  43. async function syncLibrary() {
  44. showMessage('Syncing with Audiobookshelf...', 'success');
  45. try {
  46. const response = await fetch('/api/sync');
  47. if (await handleApiError(response)) return;
  48. const data = await response.json();
  49. if (data.status === 'success') {
  50. showMessage(data.message, 'success');
  51. setTimeout(() => window.location.reload(), 1500);
  52. } else {
  53. showMessage(data.message || 'Sync failed', 'error');
  54. }
  55. } catch (error) {
  56. showMessage('Error syncing with Audiobookshelf: ' + error.message, 'error');
  57. }
  58. }
  59. async function generateRecommendations() {
  60. showMessage('Generating AI recommendations...', 'success');
  61. try {
  62. const response = await fetch('/api/recommendations/generate');
  63. if (await handleApiError(response)) return;
  64. const data = await response.json();
  65. if (data.status === 'success') {
  66. showMessage(`Generated ${data.count} new recommendations!`, 'success');
  67. setTimeout(() => window.location.reload(), 1500);
  68. } else {
  69. showMessage(data.message || 'Failed to generate recommendations', 'error');
  70. }
  71. } catch (error) {
  72. showMessage('Error generating recommendations: ' + error.message, 'error');
  73. }
  74. }