playlist_manager.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. import json
  2. import os
  3. import threading
  4. import logging
  5. import asyncio
  6. from typing import Optional
  7. from modules.core import pattern_manager
  8. from modules.core.state import state
  9. from fastapi import HTTPException
  10. # Configure logging
  11. logger = logging.getLogger(__name__)
  12. # Track the current playlist task so we can cancel it properly
  13. _current_playlist_task: Optional[asyncio.Task] = None
  14. # Global state
  15. PLAYLISTS_FILE = os.path.join(os.getcwd(), "playlists.json")
  16. # Ensure the file exists and contains at least an empty JSON object
  17. if not os.path.isfile(PLAYLISTS_FILE):
  18. logger.info(f"Creating new playlists file at {PLAYLISTS_FILE}")
  19. with open(PLAYLISTS_FILE, "w") as f:
  20. json.dump({}, f, indent=2)
  21. def load_playlists():
  22. """Load the entire playlists dictionary from the JSON file."""
  23. with open(PLAYLISTS_FILE, "r") as f:
  24. playlists = json.load(f)
  25. logger.debug(f"Loaded {len(playlists)} playlists")
  26. return playlists
  27. def save_playlists(playlists_dict):
  28. """Save the entire playlists dictionary back to the JSON file."""
  29. logger.debug(f"Saving {len(playlists_dict)} playlists to file")
  30. with open(PLAYLISTS_FILE, "w") as f:
  31. json.dump(playlists_dict, f, indent=2)
  32. def list_all_playlists():
  33. """Returns a list of all playlist names."""
  34. playlists_dict = load_playlists()
  35. playlist_names = list(playlists_dict.keys())
  36. logger.debug(f"Found {len(playlist_names)} playlists")
  37. return playlist_names
  38. def get_playlist(playlist_name):
  39. """Get a specific playlist by name."""
  40. playlists_dict = load_playlists()
  41. if playlist_name not in playlists_dict:
  42. logger.warning(f"Playlist not found: {playlist_name}")
  43. return None
  44. logger.debug(f"Retrieved playlist: {playlist_name}")
  45. return {
  46. "name": playlist_name,
  47. "files": playlists_dict[playlist_name]
  48. }
  49. def create_playlist(playlist_name, files):
  50. """Create or update a playlist."""
  51. playlists_dict = load_playlists()
  52. playlists_dict[playlist_name] = files
  53. save_playlists(playlists_dict)
  54. logger.info(f"Created/updated playlist '{playlist_name}' with {len(files)} files")
  55. return True
  56. def modify_playlist(playlist_name, files):
  57. """Modify an existing playlist."""
  58. logger.info(f"Modifying playlist '{playlist_name}' with {len(files)} files")
  59. return create_playlist(playlist_name, files)
  60. def delete_playlist(playlist_name):
  61. """Delete a playlist."""
  62. playlists_dict = load_playlists()
  63. if playlist_name not in playlists_dict:
  64. logger.warning(f"Cannot delete non-existent playlist: {playlist_name}")
  65. return False
  66. del playlists_dict[playlist_name]
  67. save_playlists(playlists_dict)
  68. logger.info(f"Deleted playlist: {playlist_name}")
  69. return True
  70. def add_to_playlist(playlist_name, pattern):
  71. """Add a pattern to an existing playlist."""
  72. playlists_dict = load_playlists()
  73. if playlist_name not in playlists_dict:
  74. logger.warning(f"Cannot add to non-existent playlist: {playlist_name}")
  75. return False
  76. playlists_dict[playlist_name].append(pattern)
  77. save_playlists(playlists_dict)
  78. logger.info(f"Added pattern '{pattern}' to playlist '{playlist_name}'")
  79. return True
  80. def rename_playlist(old_name, new_name):
  81. """Rename an existing playlist."""
  82. if not new_name or not new_name.strip():
  83. logger.warning("Cannot rename playlist: new name is empty")
  84. return False, "New name cannot be empty"
  85. new_name = new_name.strip()
  86. playlists_dict = load_playlists()
  87. if old_name not in playlists_dict:
  88. logger.warning(f"Cannot rename non-existent playlist: {old_name}")
  89. return False, "Playlist not found"
  90. if old_name == new_name:
  91. return True, "Name unchanged"
  92. if new_name in playlists_dict:
  93. logger.warning(f"Cannot rename playlist: '{new_name}' already exists")
  94. return False, "A playlist with that name already exists"
  95. # Copy files to new key and delete old key
  96. playlists_dict[new_name] = playlists_dict[old_name]
  97. del playlists_dict[old_name]
  98. save_playlists(playlists_dict)
  99. logger.info(f"Renamed playlist '{old_name}' to '{new_name}'")
  100. return True, f"Playlist renamed to '{new_name}'"
  101. async def cancel_current_playlist():
  102. """Cancel the current playlist task if one is running."""
  103. global _current_playlist_task
  104. if _current_playlist_task and not _current_playlist_task.done():
  105. logger.info("Cancelling existing playlist task...")
  106. _current_playlist_task.cancel()
  107. try:
  108. await _current_playlist_task
  109. except asyncio.CancelledError:
  110. logger.info("Playlist task cancelled successfully")
  111. except Exception as e:
  112. logger.warning(f"Error while cancelling playlist task: {e}")
  113. _current_playlist_task = None
  114. async def run_playlist(playlist_name, pause_time=0, clear_pattern=None, run_mode="single", shuffle=False):
  115. """Run a playlist with the given options."""
  116. global _current_playlist_task
  117. # Cancel any existing playlist task first
  118. await cancel_current_playlist()
  119. # Also stop any running pattern
  120. if pattern_manager.get_pattern_lock().locked():
  121. logger.info("Another pattern is running, stopping it first...")
  122. await pattern_manager.stop_actions()
  123. playlists = load_playlists()
  124. if playlist_name not in playlists:
  125. logger.error(f"Cannot run non-existent playlist: {playlist_name}")
  126. return False, "Playlist not found"
  127. file_paths = playlists[playlist_name]
  128. file_paths = [os.path.join(pattern_manager.THETA_RHO_DIR, file) for file in file_paths]
  129. if not file_paths:
  130. logger.warning(f"Cannot run empty playlist: {playlist_name}")
  131. return False, "Playlist is empty"
  132. try:
  133. logger.info(f"Starting playlist '{playlist_name}' with mode={run_mode}, shuffle={shuffle}")
  134. state.current_playlist = file_paths
  135. state.current_playlist_name = playlist_name
  136. _current_playlist_task = asyncio.create_task(
  137. pattern_manager.run_theta_rho_files(
  138. file_paths,
  139. pause_time=pause_time,
  140. clear_pattern=clear_pattern,
  141. run_mode=run_mode,
  142. shuffle=shuffle,
  143. )
  144. )
  145. return True, f"Playlist '{playlist_name}' is now running."
  146. except Exception as e:
  147. logger.error(f"Failed to run playlist '{playlist_name}': {str(e)}")
  148. return False, str(e)