audiogen_mostrecent.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import os
  2. import logging
  3. import shutil
  4. import time
  5. from tempfile import mkstemp
  6. from pytimeparse.timeparse import timeparse
  7. from larigira.fsutils import scan_dir, shortname
  8. log = logging.getLogger(__name__)
  9. def get_mtime(fname):
  10. return int(os.path.getmtime(fname))
  11. def recent_choose(paths, howmany, minepoch):
  12. found_files = {}
  13. for path in paths:
  14. if not os.path.exists(path):
  15. log.warning("Can't find requested path: %s", path)
  16. continue
  17. if os.path.isfile(path):
  18. found_files[path] = get_mtime(path)
  19. elif os.path.isdir(path):
  20. found_files.update({fname: get_mtime(fname) for fname in scan_dir(path)})
  21. found_files = [
  22. (fname, mtime) for (fname, mtime) in found_files.items() if mtime >= minepoch
  23. ]
  24. return [
  25. fname
  26. for fname, mtime in sorted(found_files, key=lambda x: x[1], reverse=True)[
  27. :howmany
  28. ]
  29. ]
  30. def generate(spec):
  31. """
  32. resolves audiospec-randomdir
  33. Recognized arguments:
  34. - path [mandatory] source dir
  35. - maxage [default=ignored] max age of audio files to pick
  36. """
  37. for attr in ("path", "maxage"):
  38. if attr not in spec:
  39. raise ValueError("Malformed audiospec: missing '%s'" % attr)
  40. if spec["maxage"].strip():
  41. try:
  42. maxage = int(spec["maxage"])
  43. except ValueError:
  44. maxage = timeparse(spec["maxage"])
  45. if maxage is None:
  46. raise ValueError(
  47. "Unknown format for maxage: '{}'".format(spec["maxage"])
  48. )
  49. assert type(maxage) is int
  50. else:
  51. maxage = None
  52. now = int(time.time())
  53. minepoch = 0 if maxage is None else now - maxage
  54. picked = recent_choose([spec["path"]], 1, minepoch)
  55. for path in picked:
  56. tmp = mkstemp(
  57. suffix=os.path.splitext(path)[-1], prefix="randomdir-%s-" % shortname(path)
  58. )
  59. os.close(tmp[0])
  60. shutil.copy(path, tmp[1])
  61. log.info("copying %s -> %s", path, os.path.basename(tmp[1]))
  62. yield "file://{}".format(tmp[1])
  63. generate.description = "Select most recent file inside a directory"