]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/bliptv.py
Imported Upstream version 2013.07.02
[youtubedl] / 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'b2d849efcf7ee18917e4b4d9ff37cafe',
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 request = compat_urllib_request.Request(url)
55 response = compat_urllib_request.urlopen(request)
56 redirecturl = response.geturl()
57 rurlp = compat_urllib_parse_urlparse(redirecturl)
58 file_id = compat_parse_qs(rurlp.fragment)['file'][0].rpartition('/')[2]
59 url = 'http://blip.tv/a/a-' + file_id
60 return self._real_extract(url)
61
62
63 if '?' in url:
64 cchar = '&'
65 else:
66 cchar = '?'
67 json_url = url + cchar + 'skin=json&version=2&no_wrap=1'
68 request = compat_urllib_request.Request(json_url)
69 request.add_header('User-Agent', 'iTunes/10.6.1')
70 self.report_extraction(mobj.group(1))
71 info = None
72 try:
73 urlh = compat_urllib_request.urlopen(request)
74 if urlh.headers.get('Content-Type', '').startswith('video/'): # Direct download
75 basename = url.split('/')[-1]
76 title,ext = os.path.splitext(basename)
77 title = title.decode('UTF-8')
78 ext = ext.replace('.', '')
79 self.report_direct_download(title)
80 info = {
81 'id': title,
82 'url': url,
83 'uploader': None,
84 'upload_date': None,
85 'title': title,
86 'ext': ext,
87 'urlhandle': urlh
88 }
89 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
90 raise ExtractorError(u'ERROR: unable to download video info webpage: %s' % compat_str(err))
91 if info is None: # Regular URL
92 try:
93 json_code_bytes = urlh.read()
94 json_code = json_code_bytes.decode('utf-8')
95 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
96 raise ExtractorError(u'Unable to read video info webpage: %s' % compat_str(err))
97
98 try:
99 json_data = json.loads(json_code)
100 if 'Post' in json_data:
101 data = json_data['Post']
102 else:
103 data = json_data
104
105 upload_date = datetime.datetime.strptime(data['datestamp'], '%m-%d-%y %H:%M%p').strftime('%Y%m%d')
106 video_url = data['media']['url']
107 umobj = re.match(self._URL_EXT, video_url)
108 if umobj is None:
109 raise ValueError('Can not determine filename extension')
110 ext = umobj.group(1)
111
112 info = {
113 'id': data['item_id'],
114 'url': video_url,
115 'uploader': data['display_name'],
116 'upload_date': upload_date,
117 'title': data['title'],
118 'ext': ext,
119 'format': data['media']['mimeType'],
120 'thumbnail': data['thumbnailUrl'],
121 'description': data['description'],
122 'player_url': data['embedUrl'],
123 'user_agent': 'iTunes/10.6.1',
124 }
125 except (ValueError,KeyError) as err:
126 raise ExtractorError(u'Unable to parse video information: %s' % repr(err))
127
128 return [info]
129
130
131 class BlipTVUserIE(InfoExtractor):
132 """Information Extractor for blip.tv users."""
133
134 _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?blip\.tv/)|bliptvuser:)([^/]+)/*$'
135 _PAGE_SIZE = 12
136 IE_NAME = u'blip.tv:user'
137
138 def _real_extract(self, url):
139 # Extract username
140 mobj = re.match(self._VALID_URL, url)
141 if mobj is None:
142 raise ExtractorError(u'Invalid URL: %s' % url)
143
144 username = mobj.group(1)
145
146 page_base = 'http://m.blip.tv/pr/show_get_full_episode_list?users_id=%s&lite=0&esi=1'
147
148 page = self._download_webpage(url, username, u'Downloading user page')
149 mobj = re.search(r'data-users-id="([^"]+)"', page)
150 page_base = page_base % mobj.group(1)
151
152
153 # Download video ids using BlipTV Ajax calls. Result size per
154 # query is limited (currently to 12 videos) so we need to query
155 # page by page until there are no video ids - it means we got
156 # all of them.
157
158 video_ids = []
159 pagenum = 1
160
161 while True:
162 url = page_base + "&page=" + str(pagenum)
163 page = self._download_webpage(url, username,
164 u'Downloading video ids from page %d' % pagenum)
165
166 # Extract video identifiers
167 ids_in_page = []
168
169 for mobj in re.finditer(r'href="/([^"]+)"', page):
170 if mobj.group(1) not in ids_in_page:
171 ids_in_page.append(unescapeHTML(mobj.group(1)))
172
173 video_ids.extend(ids_in_page)
174
175 # A little optimization - if current page is not
176 # "full", ie. does not contain PAGE_SIZE video ids then
177 # we can assume that this page is the last one - there
178 # are no more ids on further pages - no need to query
179 # again.
180
181 if len(ids_in_page) < self._PAGE_SIZE:
182 break
183
184 pagenum += 1
185
186 urls = [u'http://blip.tv/%s' % video_id for video_id in video_ids]
187 url_entries = [self.url_result(url, 'BlipTV') for url in urls]
188 return [self.playlist_result(url_entries, playlist_title = username)]