audiogen_http.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import os
  2. import logging
  3. import posixpath
  4. from tempfile import mkstemp
  5. import urllib.request
  6. from urllib.parse import urlparse
  7. log = logging.getLogger(__name__)
  8. def put(url, destdir=None, copy=False):
  9. if url.split(":")[0] not in ("http", "https"):
  10. log.warning("Not a valid URL: %s", url)
  11. return None
  12. ext = url.split(".")[-1]
  13. if ext.lower() not in ("mp3", "ogg", "oga", "wma", "m4a"):
  14. log.warning('Invalid format (%s) for "%s"', ext, url)
  15. return None
  16. if not copy:
  17. return url
  18. fname = posixpath.basename(urlparse(url).path)
  19. # sanitize
  20. fname = "".join(c for c in fname if c.isalnum() or c in list("._-")).rstrip()
  21. tmp = mkstemp(suffix="." + ext, prefix="http-%s-" % fname, dir=destdir)
  22. os.close(tmp[0])
  23. log.info("downloading %s -> %s", url, tmp[1])
  24. fname, headers = urllib.request.urlretrieve(url, tmp[1])
  25. return "file://%s" % os.path.realpath(tmp[1])
  26. def generate(spec):
  27. """
  28. resolves audiospec-static
  29. Recognized argument is "paths" (list of static paths)
  30. """
  31. if "urls" not in spec:
  32. raise ValueError("Malformed audiospec: missing 'paths'")
  33. for url in spec["urls"]:
  34. ret = put(url, copy=True)
  35. if ret is None:
  36. continue
  37. yield ret
  38. generate.description = "Fetch audio from an URL"