playlist_manager.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. import json
  2. import os
  3. import threading
  4. import logging
  5. import asyncio
  6. from modules.core import pattern_manager
  7. from modules.core.state import state
  8. # Configure logging
  9. logger = logging.getLogger(__name__)
  10. # Global state
  11. PLAYLISTS_FILE = os.path.join(os.getcwd(), "playlists.json")
  12. # Ensure the file exists and contains at least an empty JSON object
  13. if not os.path.isfile(PLAYLISTS_FILE):
  14. logger.info(f"Creating new playlists file at {PLAYLISTS_FILE}")
  15. with open(PLAYLISTS_FILE, "w") as f:
  16. json.dump({}, f, indent=2)
  17. def load_playlists():
  18. """Load the entire playlists dictionary from the JSON file."""
  19. with open(PLAYLISTS_FILE, "r") as f:
  20. playlists = json.load(f)
  21. logger.debug(f"Loaded {len(playlists)} playlists")
  22. return playlists
  23. def save_playlists(playlists_dict):
  24. """Save the entire playlists dictionary back to the JSON file."""
  25. logger.debug(f"Saving {len(playlists_dict)} playlists to file")
  26. with open(PLAYLISTS_FILE, "w") as f:
  27. json.dump(playlists_dict, f, indent=2)
  28. def list_all_playlists():
  29. """Returns a list of all playlist names."""
  30. playlists_dict = load_playlists()
  31. playlist_names = list(playlists_dict.keys())
  32. logger.debug(f"Found {len(playlist_names)} playlists")
  33. return playlist_names
  34. def get_playlist(playlist_name):
  35. """Get a specific playlist by name."""
  36. playlists_dict = load_playlists()
  37. if playlist_name not in playlists_dict:
  38. logger.warning(f"Playlist not found: {playlist_name}")
  39. return None
  40. logger.debug(f"Retrieved playlist: {playlist_name}")
  41. return {
  42. "name": playlist_name,
  43. "files": playlists_dict[playlist_name]
  44. }
  45. def create_playlist(playlist_name, files):
  46. """Create or update a playlist."""
  47. playlists_dict = load_playlists()
  48. playlists_dict[playlist_name] = files
  49. save_playlists(playlists_dict)
  50. logger.info(f"Created/updated playlist '{playlist_name}' with {len(files)} files")
  51. return True
  52. def modify_playlist(playlist_name, files):
  53. """Modify an existing playlist."""
  54. logger.info(f"Modifying playlist '{playlist_name}' with {len(files)} files")
  55. return create_playlist(playlist_name, files)
  56. def delete_playlist(playlist_name):
  57. """Delete a playlist."""
  58. playlists_dict = load_playlists()
  59. if playlist_name not in playlists_dict:
  60. logger.warning(f"Cannot delete non-existent playlist: {playlist_name}")
  61. return False
  62. del playlists_dict[playlist_name]
  63. save_playlists(playlists_dict)
  64. logger.info(f"Deleted playlist: {playlist_name}")
  65. return True
  66. def add_to_playlist(playlist_name, pattern):
  67. """Add a pattern to an existing playlist."""
  68. playlists_dict = load_playlists()
  69. if playlist_name not in playlists_dict:
  70. logger.warning(f"Cannot add to non-existent playlist: {playlist_name}")
  71. return False
  72. playlists_dict[playlist_name].append(pattern)
  73. save_playlists(playlists_dict)
  74. logger.info(f"Added pattern '{pattern}' to playlist '{playlist_name}'")
  75. return True
  76. async def run_playlist(playlist_name, pause_time=0, clear_pattern=None, run_mode="single", shuffle=False):
  77. """Run a playlist with the given options."""
  78. if pattern_manager.pattern_lock.locked():
  79. logger.warning("Cannot start playlist: Another pattern is already running")
  80. return False, "Cannot start playlist: Another pattern is already running"
  81. playlists = load_playlists()
  82. if playlist_name not in playlists:
  83. logger.error(f"Cannot run non-existent playlist: {playlist_name}")
  84. return False, "Playlist not found"
  85. file_paths = playlists[playlist_name]
  86. file_paths = [os.path.join(pattern_manager.THETA_RHO_DIR, file) for file in file_paths]
  87. if not file_paths:
  88. logger.warning(f"Cannot run empty playlist: {playlist_name}")
  89. return False, "Playlist is empty"
  90. try:
  91. logger.info(f"Starting playlist '{playlist_name}' with mode={run_mode}, shuffle={shuffle}")
  92. state.current_playlist = file_paths
  93. asyncio.create_task(
  94. pattern_manager.run_theta_rho_files(
  95. file_paths,
  96. pause_time=pause_time,
  97. clear_pattern=clear_pattern,
  98. run_mode=run_mode,
  99. shuffle=shuffle,
  100. )
  101. )
  102. return True, f"Playlist '{playlist_name}' is now running."
  103. except Exception as e:
  104. logger.error(f"Failed to run playlist '{playlist_name}': {str(e)}")
  105. return False, str(e)