]> git.bitcoin.ninja Git - youtube-dl/blob - youtube_dl/extractor/bliptv.py
Merge pull request #2005 from dstftw/ivi.ru
[youtube-dl] / youtube_dl / extractor / bliptv.py
1 import datetime
2 import json
3 import os
4 import re
5 import socket
6
7 from .common import InfoExtractor
8 from ..utils import (
9     compat_http_client,
10     compat_parse_qs,
11     compat_str,
12     compat_urllib_error,
13     compat_urllib_parse_urlparse,
14     compat_urllib_request,
15
16     ExtractorError,
17     unescapeHTML,
18 )
19
20
21 class BlipTVIE(InfoExtractor):
22     """Information extractor for blip.tv"""
23
24     _VALID_URL = r'^(?:https?://)?(?:\w+\.)?blip\.tv/((.+/)|(play/)|(api\.swf#))(.+)$'
25     _URL_EXT = r'^.*\.([a-z0-9]+)$'
26     IE_NAME = u'blip.tv'
27     _TEST = {
28         u'url': u'http://blip.tv/cbr/cbr-exclusive-gotham-city-imposters-bats-vs-jokerz-short-3-5796352',
29         u'file': u'5779306.m4v',
30         u'md5': u'80baf1ec5c3d2019037c1c707d676b9f',
31         u'info_dict': {
32             u"upload_date": u"20111205", 
33             u"description": u"md5:9bc31f227219cde65e47eeec8d2dc596", 
34             u"uploader": u"Comic Book Resources - CBR TV", 
35             u"title": u"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(u'%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(u'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
62         if '?' in url:
63             cchar = '&'
64         else:
65             cchar = '?'
66         json_url = url + cchar + 'skin=json&version=2&no_wrap=1'
67         request = compat_urllib_request.Request(json_url)
68         request.add_header('User-Agent', 'iTunes/10.6.1')
69         self.report_extraction(mobj.group(1))
70         info = None
71         urlh = self._request_webpage(request, None, False,
72             u'unable to download video info webpage')
73         if urlh.headers.get('Content-Type', '').startswith('video/'): # Direct download
74             basename = url.split('/')[-1]
75             title,ext = os.path.splitext(basename)
76             title = title.decode('UTF-8')
77             ext = ext.replace('.', '')
78             self.report_direct_download(title)
79             info = {
80                 'id': title,
81                 'url': url,
82                 'uploader': None,
83                 'upload_date': None,
84                 'title': title,
85                 'ext': ext,
86                 'urlhandle': urlh
87             }
88         if info is None: # Regular URL
89             try:
90                 json_code_bytes = urlh.read()
91                 json_code = json_code_bytes.decode('utf-8')
92             except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
93                 raise ExtractorError(u'Unable to read video info webpage: %s' % compat_str(err))
94
95             try:
96                 json_data = json.loads(json_code)
97                 if 'Post' in json_data:
98                     data = json_data['Post']
99                 else:
100                     data = json_data
101
102                 upload_date = datetime.datetime.strptime(data['datestamp'], '%m-%d-%y %H:%M%p').strftime('%Y%m%d')
103                 if 'additionalMedia' in data:
104                     formats = sorted(data['additionalMedia'], key=lambda f: int(f['media_height']))
105                     best_format = formats[-1]
106                     video_url = best_format['url']
107                 else:
108                     video_url = data['media']['url']
109                 umobj = re.match(self._URL_EXT, video_url)
110                 if umobj is None:
111                     raise ValueError('Can not determine filename extension')
112                 ext = umobj.group(1)
113
114                 info = {
115                     'id': compat_str(data['item_id']),
116                     'url': video_url,
117                     'uploader': data['display_name'],
118                     'upload_date': upload_date,
119                     'title': data['title'],
120                     'ext': ext,
121                     'format': data['media']['mimeType'],
122                     'thumbnail': data['thumbnailUrl'],
123                     'description': data['description'],
124                     'player_url': data['embedUrl'],
125                     'user_agent': 'iTunes/10.6.1',
126                 }
127             except (ValueError,KeyError) as err:
128                 raise ExtractorError(u'Unable to parse video information: %s' % repr(err))
129
130         return [info]
131
132
133 class BlipTVUserIE(InfoExtractor):
134     """Information Extractor for blip.tv users."""
135
136     _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?blip\.tv/)|bliptvuser:)([^/]+)/*$'
137     _PAGE_SIZE = 12
138     IE_NAME = u'blip.tv:user'
139
140     def _real_extract(self, url):
141         # Extract username
142         mobj = re.match(self._VALID_URL, url)
143         if mobj is None:
144             raise ExtractorError(u'Invalid URL: %s' % url)
145
146         username = mobj.group(1)
147
148         page_base = 'http://m.blip.tv/pr/show_get_full_episode_list?users_id=%s&lite=0&esi=1'
149
150         page = self._download_webpage(url, username, u'Downloading user page')
151         mobj = re.search(r'data-users-id="([^"]+)"', page)
152         page_base = page_base % mobj.group(1)
153
154
155         # Download video ids using BlipTV Ajax calls. Result size per
156         # query is limited (currently to 12 videos) so we need to query
157         # page by page until there are no video ids - it means we got
158         # all of them.
159
160         video_ids = []
161         pagenum = 1
162
163         while True:
164             url = page_base + "&page=" + str(pagenum)
165             page = self._download_webpage(url, username,
166                                           u'Downloading video ids from page %d' % pagenum)
167
168             # Extract video identifiers
169             ids_in_page = []
170
171             for mobj in re.finditer(r'href="/([^"]+)"', page):
172                 if mobj.group(1) not in ids_in_page:
173                     ids_in_page.append(unescapeHTML(mobj.group(1)))
174
175             video_ids.extend(ids_in_page)
176
177             # A little optimization - if current page is not
178             # "full", ie. does not contain PAGE_SIZE video ids then
179             # we can assume that this page is the last one - there
180             # are no more ids on further pages - no need to query
181             # again.
182
183             if len(ids_in_page) < self._PAGE_SIZE:
184                 break
185
186             pagenum += 1
187
188         urls = [u'http://blip.tv/%s' % video_id for video_id in video_ids]
189         url_entries = [self.url_result(vurl, 'BlipTV') for vurl in urls]
190         return [self.playlist_result(url_entries, playlist_title = username)]