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