playlist_manager.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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. def rename_playlist(old_name, new_name):
  78. """Rename an existing playlist."""
  79. if not new_name or not new_name.strip():
  80. logger.warning("Cannot rename playlist: new name is empty")
  81. return False, "New name cannot be empty"
  82. new_name = new_name.strip()
  83. playlists_dict = load_playlists()
  84. if old_name not in playlists_dict:
  85. logger.warning(f"Cannot rename non-existent playlist: {old_name}")
  86. return False, "Playlist not found"
  87. if old_name == new_name:
  88. return True, "Name unchanged"
  89. if new_name in playlists_dict:
  90. logger.warning(f"Cannot rename playlist: '{new_name}' already exists")
  91. return False, "A playlist with that name already exists"
  92. # Copy files to new key and delete old key
  93. playlists_dict[new_name] = playlists_dict[old_name]
  94. del playlists_dict[old_name]
  95. save_playlists(playlists_dict)
  96. logger.info(f"Renamed playlist '{old_name}' to '{new_name}'")
  97. return True, f"Playlist renamed to '{new_name}'"
  98. async def run_playlist(playlist_name, pause_time=0, clear_pattern=None, run_mode="single", shuffle=False):
  99. """Run a playlist with the given options."""
  100. if pattern_manager.get_pattern_lock().locked():
  101. logger.info("Another pattern is running, stopping it first...")
  102. await pattern_manager.stop_actions()
  103. playlists = load_playlists()
  104. if playlist_name not in playlists:
  105. logger.error(f"Cannot run non-existent playlist: {playlist_name}")
  106. return False, "Playlist not found"
  107. file_paths = playlists[playlist_name]
  108. file_paths = [os.path.join(pattern_manager.THETA_RHO_DIR, file) for file in file_paths]
  109. if not file_paths:
  110. logger.warning(f"Cannot run empty playlist: {playlist_name}")
  111. return False, "Playlist is empty"
  112. try:
  113. logger.info(f"Starting playlist '{playlist_name}' with mode={run_mode}, shuffle={shuffle}")
  114. state.current_playlist = file_paths
  115. state.current_playlist_name = playlist_name
  116. asyncio.create_task(
  117. pattern_manager.run_theta_rho_files(
  118. file_paths,
  119. pause_time=pause_time,
  120. clear_pattern=clear_pattern,
  121. run_mode=run_mode,
  122. shuffle=shuffle,
  123. )
  124. )
  125. return True, f"Playlist '{playlist_name}' is now running."
  126. except Exception as e:
  127. logger.error(f"Failed to run playlist '{playlist_name}': {str(e)}")
  128. return False, str(e)