You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
3.1 KiB

  1. from __future__ import unicode_literals
  2. import os
  3. import re
  4. from .fragment import FragmentFD
  5. from ..compat import compat_urllib_error
  6. from ..utils import (
  7. sanitize_open,
  8. encodeFilename,
  9. )
  10. class DashSegmentsFD(FragmentFD):
  11. """
  12. Download segments in a DASH manifest
  13. """
  14. FD_NAME = 'dashsegments'
  15. def real_download(self, filename, info_dict):
  16. base_url = info_dict['url']
  17. segment_urls = [info_dict['segment_urls'][0]] if self.params.get('test', False) else info_dict['segment_urls']
  18. initialization_url = info_dict.get('initialization_url')
  19. ctx = {
  20. 'filename': filename,
  21. 'total_frags': len(segment_urls) + (1 if initialization_url else 0),
  22. }
  23. self._prepare_and_start_frag_download(ctx)
  24. def combine_url(base_url, target_url):
  25. if re.match(r'^https?://', target_url):
  26. return target_url
  27. return '%s%s%s' % (base_url, '' if base_url.endswith('/') else '/', target_url)
  28. segments_filenames = []
  29. fragment_retries = self.params.get('fragment_retries', 0)
  30. def append_url_to_file(target_url, tmp_filename, segment_name):
  31. target_filename = '%s-%s' % (tmp_filename, segment_name)
  32. count = 0
  33. while count <= fragment_retries:
  34. try:
  35. success = ctx['dl'].download(target_filename, {'url': combine_url(base_url, target_url)})
  36. if not success:
  37. return False
  38. down, target_sanitized = sanitize_open(target_filename, 'rb')
  39. ctx['dest_stream'].write(down.read())
  40. down.close()
  41. segments_filenames.append(target_sanitized)
  42. break
  43. except (compat_urllib_error.HTTPError, ) as err:
  44. # YouTube may often return 404 HTTP error for a fragment causing the
  45. # whole download to fail. However if the same fragment is immediately
  46. # retried with the same request data this usually succeeds (1-2 attemps
  47. # is usually enough) thus allowing to download the whole file successfully.
  48. # So, we will retry all fragments that fail with 404 HTTP error for now.
  49. if err.code != 404:
  50. raise
  51. # Retry fragment
  52. count += 1
  53. if count <= fragment_retries:
  54. self.report_retry_fragment(segment_name, count, fragment_retries)
  55. if count > fragment_retries:
  56. self.report_error('giving up after %s fragment retries' % fragment_retries)
  57. return False
  58. if initialization_url:
  59. append_url_to_file(initialization_url, ctx['tmpfilename'], 'Init')
  60. for i, segment_url in enumerate(segment_urls):
  61. append_url_to_file(segment_url, ctx['tmpfilename'], 'Seg%d' % i)
  62. self._finish_frag_download(ctx)
  63. for segment_file in segments_filenames:
  64. os.remove(encodeFilename(segment_file))
  65. return True