suggestions.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import os
  2. from flask import current_app
  3. from larigira.config import get_conf
  4. from larigira.fsutils import scan_dir_audio
  5. def get_suggested_files():
  6. if not get_conf()["FILE_PATH_SUGGESTION"]:
  7. return []
  8. if current_app.cache.has("dbadmin.get_suggested_files"):
  9. return current_app.cache.get("dbadmin.get_suggested_files")
  10. current_app.logger.debug("get_suggested_files MISS in cache")
  11. files = []
  12. for path in get_conf()["FILE_PATH_SUGGESTION"]:
  13. if not os.path.isdir(path):
  14. current_app.logger.warning("Invalid suggestion path: %s" % path)
  15. continue
  16. pathfiles = scan_dir_audio(path)
  17. files.extend(pathfiles)
  18. current_app.logger.debug("Suggested files: %s" % ", ".join(files))
  19. current_app.cache.set(
  20. "dbadmin.get_suggested_files", files, timeout=600
  21. ) # ten minutes
  22. return files
  23. def get_suggested_dirs():
  24. dirset = set()
  25. for f in get_suggested_files():
  26. dirpath = os.path.dirname(f)
  27. while dirpath:
  28. if dirpath in dirset:
  29. break
  30. dirset.add(dirpath)
  31. dirpath = os.path.dirname(dirpath)
  32. return list(dirset)
  33. def get_suggested_scripts():
  34. base = get_conf()["SCRIPTS_PATH"]
  35. if not base or not os.path.isdir(base):
  36. return []
  37. fnames = [
  38. f
  39. for f in os.listdir(base)
  40. if os.access(os.path.join(base, f), os.R_OK | os.X_OK)
  41. ]
  42. return fnames
  43. def get_suggestions():
  44. files = get_suggested_files()
  45. if len(files) > 200:
  46. current_app.logger.warning("Too many suggested files, cropping")
  47. files = files[:200]
  48. return dict(files=files, dirs=get_suggested_dirs(), scripts=get_suggested_scripts())