Merge remote-tracking branch 'rzhxeo/blip'
[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?://)?(?:\w+\.)?blip\.tv/((.+/)|(play/)|(api\.swf#))(.+)$'
26
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         embed_mobj = re.search(r'^(?:https?://)?(?:\w+\.)?blip\.tv/(?:play/|api\.swf#)([a-zA-Z0-9]+)', url)
50         if embed_mobj:
51             info_url = 'http://blip.tv/play/%s.x?p=1' % embed_mobj.group(1)
52             info_page = self._download_webpage(info_url, embed_mobj.group(1))
53             video_id = self._search_regex(r'data-episode-id="(\d+)', info_page,  'video_id')
54             return self.url_result('http://blip.tv/a/a-' + video_id, 'BlipTV')
55
56         if '?' in url:
57             cchar = '&'
58         else:
59             cchar = '?'
60         json_url = url + cchar + 'skin=json&version=2&no_wrap=1'
61         request = compat_urllib_request.Request(json_url)
62         request.add_header('User-Agent', 'iTunes/10.6.1')
63         self.report_extraction(mobj.group(1))
64         urlh = self._request_webpage(request, None, False,
65             'unable to download video info webpage')
66
67         try:
68             json_code_bytes = urlh.read()
69             json_code = json_code_bytes.decode('utf-8')
70         except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
71             raise ExtractorError('Unable to read video info webpage: %s' % compat_str(err))
72
73         try:
74             json_data = json.loads(json_code)
75             if 'Post' in json_data:
76                 data = json_data['Post']
77             else:
78                 data = json_data
79
80             upload_date = datetime.datetime.strptime(data['datestamp'], '%m-%d-%y %H:%M%p').strftime('%Y%m%d')
81             formats = []
82             if 'additionalMedia' in data:
83                 for f in sorted(data['additionalMedia'], key=lambda f: int(f['media_height'])):
84                     if not int(f['media_width']): # filter m3u8
85                         continue
86                     formats.append({
87                         'url': f['url'],
88                         'format_id': f['role'],
89                         'width': int(f['media_width']),
90                         'height': int(f['media_height']),
91                     })
92             else:
93                 formats.append({
94                     'url': data['media']['url'],
95                     'width': int(data['media']['width']),
96                     'height': int(data['media']['height']),
97                 })
98
99             self._sort_formats(formats)
100
101             return {
102                 'id': compat_str(data['item_id']),
103                 'uploader': data['display_name'],
104                 'upload_date': upload_date,
105                 'title': data['title'],
106                 'thumbnail': data['thumbnailUrl'],
107                 'description': data['description'],
108                 'user_agent': 'iTunes/10.6.1',
109                 'formats': formats,
110             }
111         except (ValueError, KeyError) as err:
112             raise ExtractorError('Unable to parse video information: %s' % repr(err))
113
114
115 class BlipTVUserIE(InfoExtractor):
116     """Information Extractor for blip.tv users."""
117
118     _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?blip\.tv/)|bliptvuser:)([^/]+)/*$'
119     _PAGE_SIZE = 12
120     IE_NAME = 'blip.tv:user'
121
122     def _real_extract(self, url):
123         # Extract username
124         mobj = re.match(self._VALID_URL, url)
125         if mobj is None:
126             raise ExtractorError('Invalid URL: %s' % url)
127
128         username = mobj.group(1)
129
130         page_base = 'http://m.blip.tv/pr/show_get_full_episode_list?users_id=%s&lite=0&esi=1'
131
132         page = self._download_webpage(url, username, 'Downloading user page')
133         mobj = re.search(r'data-users-id="([^"]+)"', page)
134         page_base = page_base % mobj.group(1)
135
136
137         # Download video ids using BlipTV Ajax calls. Result size per
138         # query is limited (currently to 12 videos) so we need to query
139         # page by page until there are no video ids - it means we got
140         # all of them.
141
142         video_ids = []
143         pagenum = 1
144
145         while True:
146             url = page_base + "&page=" + str(pagenum)
147             page = self._download_webpage(url, username,
148                                           'Downloading video ids from page %d' % pagenum)
149
150             # Extract video identifiers
151             ids_in_page = []
152
153             for mobj in re.finditer(r'href="/([^"]+)"', page):
154                 if mobj.group(1) not in ids_in_page:
155                     ids_in_page.append(unescapeHTML(mobj.group(1)))
156
157             video_ids.extend(ids_in_page)
158
159             # A little optimization - if current page is not
160             # "full", ie. does not contain PAGE_SIZE video ids then
161             # we can assume that this page is the last one - there
162             # are no more ids on further pages - no need to query
163             # again.
164
165             if len(ids_in_page) < self._PAGE_SIZE:
166                 break
167
168             pagenum += 1
169
170         urls = ['http://blip.tv/%s' % video_id for video_id in video_ids]
171         url_entries = [self.url_result(vurl, 'BlipTV') for vurl in urls]
172         return [self.playlist_result(url_entries, playlist_title = username)]