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