playlist_manager.py 4.6 KB

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