[downloader/dash] Do not pollute ```self```
[youtube-dl] / youtube_dl / downloader / dash.py
1 from __future__ import unicode_literals
2
3 import re
4
5 from .common import FileDownloader
6 from ..compat import compat_urllib_request
7
8
9 class DashSegmentsFD(FileDownloader):
10     """
11     Download segments in a DASH manifest
12     """
13     def real_download(self, filename, info_dict):
14         self.report_destination(filename)
15         tmpfilename = self.temp_name(filename)
16         base_url = info_dict['url']
17         segment_urls = info_dict['segment_urls']
18
19         byte_counter = 0
20
21         def append_url_to_file(outf, target_url, target_name):
22             self.to_screen('[DashSegments] %s: Downloading %s' % (info_dict['id'], target_name))
23             req = compat_urllib_request.Request(target_url)
24             data = self.ydl.urlopen(req).read()
25             outf.write(data)
26             return len(data)
27
28         def combine_url(base_url, target_url):
29             if re.match(r'^https?://', target_url):
30                 return target_url
31             return '%s/%s' % (base_url, target_url)
32
33         with open(tmpfilename, 'wb') as outf:
34             append_url_to_file(
35                 outf, combine_url(base_url, info_dict['initialization_url']),
36                 'initialization segment')
37             for i, segment_url in enumerate(segment_urls):
38                 segment_len = append_url_to_file(
39                     outf, combine_url(base_url, segment_url),
40                     'segment %d / %d' % (i + 1, len(segment_urls)))
41                 byte_counter += segment_len
42
43         self.try_rename(tmpfilename, filename)
44
45         self._hook_progress({
46             'downloaded_bytes': byte_counter,
47             'total_bytes': byte_counter,
48             'filename': filename,
49             'status': 'finished',
50         })
51
52         return True