Ignore more downloaded files
[youtube-dl] / youtube_dl / extractor / bliptv.py
1 from __future__ import unicode_literals
2
3 import datetime
4 import json
5 import re
6 import socket
7
8 from .common import InfoExtractor
9 from ..utils import (
10     compat_http_client,
11     compat_parse_qs,
12     compat_str,
13     compat_urllib_error,
14     compat_urllib_parse_urlparse,
15     compat_urllib_request,
16
17     ExtractorError,
18     unescapeHTML,
19 )
20
21
22 class BlipTVIE(InfoExtractor):
23     """Information extractor for blip.tv"""
24
25     _VALID_URL = r'^(?:https?://)?(?:www\.)?blip\.tv/((.+/)|(play/)|(api\.swf#))(.+)$'
26     IE_NAME = 'blip.tv'
27     _TEST = {
28         'url': 'http://blip.tv/cbr/cbr-exclusive-gotham-city-imposters-bats-vs-jokerz-short-3-5796352',
29         'file': '5779306.mov',
30         'md5': 'c6934ad0b6acf2bd920720ec888eb812',
31         'info_dict': {
32             'upload_date': '20111205',
33             'description': 'md5:9bc31f227219cde65e47eeec8d2dc596',
34             'uploader': 'Comic Book Resources - CBR TV',
35             'title': 'CBR EXCLUSIVE: "Gotham City Imposters" Bats VS Jokerz Short 3',
36         }
37     }
38
39     def report_direct_download(self, title):
40         """Report information extraction."""
41         self.to_screen('%s: Direct download detected' % title)
42
43     def _real_extract(self, url):
44         mobj = re.match(self._VALID_URL, url)
45         if mobj is None:
46             raise ExtractorError('Invalid URL: %s' % url)
47
48         # See https://github.com/rg3/youtube-dl/issues/857
49         api_mobj = re.match(r'http://a\.blip\.tv/api\.swf#(?P<video_id>[\d\w]+)', url)
50         if api_mobj is not None:
51             url = 'http://blip.tv/play/g_%s' % api_mobj.group('video_id')
52         urlp = compat_urllib_parse_urlparse(url)
53         if urlp.path.startswith('/play/'):
54             response = self._request_webpage(url, None, False)
55             redirecturl = response.geturl()
56             rurlp = compat_urllib_parse_urlparse(redirecturl)
57             file_id = compat_parse_qs(rurlp.fragment)['file'][0].rpartition('/')[2]
58             url = 'http://blip.tv/a/a-' + file_id
59             return self._real_extract(url)
60
61         if '?' in url:
62             cchar = '&'
63         else:
64             cchar = '?'
65         json_url = url + cchar + 'skin=json&version=2&no_wrap=1'
66         request = compat_urllib_request.Request(json_url)
67         request.add_header('User-Agent', 'iTunes/10.6.1')
68         self.report_extraction(mobj.group(1))
69         urlh = self._request_webpage(request, None, False,
70             'unable to download video info webpage')
71
72         try:
73             json_code_bytes = urlh.read()
74             json_code = json_code_bytes.decode('utf-8')
75         except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
76             raise ExtractorError('Unable to read video info webpage: %s' % compat_str(err))
77
78         try:
79             json_data = json.loads(json_code)
80             if 'Post' in json_data:
81                 data = json_data['Post']
82             else:
83                 data = json_data
84
85             upload_date = datetime.datetime.strptime(data['datestamp'], '%m-%d-%y %H:%M%p').strftime('%Y%m%d')
86             formats = []
87             if 'additionalMedia' in data:
88                 for f in sorted(data['additionalMedia'], key=lambda f: int(f['media_height'])):
89                     if not int(f['media_width']): # filter m3u8
90                         continue
91                     formats.append({
92                         'url': f['url'],
93                         'format_id': f['role'],
94                         'width': int(f['media_width']),
95                         'height': int(f['media_height']),
96                     })
97             else:
98                 formats.append({
99                     'url': data['media']['url'],
100                     'width': int(data['media']['width']),
101                     'height': int(data['media']['height']),
102                 })
103
104             self._sort_formats(formats)
105
106             return {
107                 'id': compat_str(data['item_id']),
108                 'uploader': data['display_name'],
109                 'upload_date': upload_date,
110                 'title': data['title'],
111                 'thumbnail': data['thumbnailUrl'],
112                 'description': data['description'],
113                 'user_agent': 'iTunes/10.6.1',
114                 'formats': formats,
115             }
116         except (ValueError, KeyError) as err:
117             raise ExtractorError('Unable to parse video information: %s' % repr(err))
118
119
120 class BlipTVUserIE(InfoExtractor):
121     """Information Extractor for blip.tv users."""
122
123     _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?blip\.tv/)|bliptvuser:)([^/]+)/*$'
124     _PAGE_SIZE = 12
125     IE_NAME = 'blip.tv:user'
126
127     def _real_extract(self, url):
128         # Extract username
129         mobj = re.match(self._VALID_URL, url)
130         if mobj is None:
131             raise ExtractorError('Invalid URL: %s' % url)
132
133         username = mobj.group(1)
134
135         page_base = 'http://m.blip.tv/pr/show_get_full_episode_list?users_id=%s&lite=0&esi=1'
136
137         page = self._download_webpage(url, username, 'Downloading user page')
138         mobj = re.search(r'data-users-id="([^"]+)"', page)
139         page_base = page_base % mobj.group(1)
140
141
142         # Download video ids using BlipTV Ajax calls. Result size per
143         # query is limited (currently to 12 videos) so we need to query
144         # page by page until there are no video ids - it means we got
145         # all of them.
146
147         video_ids = []
148         pagenum = 1
149
150         while True:
151             url = page_base + "&page=" + str(pagenum)
152             page = self._download_webpage(url, username,
153                                           'Downloading video ids from page %d' % pagenum)
154
155             # Extract video identifiers
156             ids_in_page = []
157
158             for mobj in re.finditer(r'href="/([^"]+)"', page):
159                 if mobj.group(1) not in ids_in_page:
160                     ids_in_page.append(unescapeHTML(mobj.group(1)))
161
162             video_ids.extend(ids_in_page)
163
164             # A little optimization - if current page is not
165             # "full", ie. does not contain PAGE_SIZE video ids then
166             # we can assume that this page is the last one - there
167             # are no more ids on further pages - no need to query
168             # again.
169
170             if len(ids_in_page) < self._PAGE_SIZE:
171                 break
172
173             pagenum += 1
174
175         urls = ['http://blip.tv/%s' % video_id for video_id in video_ids]
176         url_entries = [self.url_result(vurl, 'BlipTV') for vurl in urls]
177         return [self.playlist_result(url_entries, playlist_title = username)]