1
0

playlist_manager.py 6.6 KB

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