[blip.tv] Add support for subtitles (#2274)
[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 .subtitles import SubtitlesInfoExtractor
10 from ..utils import (
11     compat_http_client,
12     compat_str,
13     compat_urllib_error,
14     compat_urllib_request,
15
16     ExtractorError,
17     unescapeHTML,
18 )
19
20
21 class BlipTVIE(SubtitlesInfoExtractor):
22     """Information extractor for blip.tv"""
23
24     _VALID_URL = r'https?://(?:\w+\.)?blip\.tv/((.+/)|(play/)|(api\.swf#))(?P<presumptive_id>.+)$'
25
26     _TESTS = [{
27         'url': 'http://blip.tv/cbr/cbr-exclusive-gotham-city-imposters-bats-vs-jokerz-short-3-5796352',
28         'md5': 'c6934ad0b6acf2bd920720ec888eb812',
29         'info_dict': {
30             'id': '5779306',
31             'ext': 'mov',
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         # https://github.com/rg3/youtube-dl/pull/2274
39         'note': 'Video with subtitles',
40         'url': 'http://blip.tv/play/h6Uag5OEVgI.html',
41         'md5': '309f9d25b820b086ca163ffac8031806',
42         'info_dict': {
43             'id': '6586561',
44             'ext': 'mp4',
45             'uploader': 'Red vs. Blue',
46             'description': 'One-Zero-One',
47             'upload_date': '20130614',
48             'title': 'Red vs. Blue Season 11 Episode 1',
49         }
50     }]
51
52     def _real_extract(self, url):
53         mobj = re.match(self._VALID_URL, url)
54         presumptive_id = mobj.group('presumptive_id')
55
56         # See https://github.com/rg3/youtube-dl/issues/857
57         embed_mobj = re.match(r'https?://(?:\w+\.)?blip\.tv/(?:play/|api\.swf#)([a-zA-Z0-9]+)', url)
58         if embed_mobj:
59             info_url = 'http://blip.tv/play/%s.x?p=1' % embed_mobj.group(1)
60             info_page = self._download_webpage(info_url, embed_mobj.group(1))
61             video_id = self._search_regex(
62                 r'data-episode-id="([0-9]+)', info_page, 'video_id')
63             return self.url_result('http://blip.tv/a/a-' + video_id, 'BlipTV')
64         
65         cchar = '&' if '?' in url else '?'
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         json_data = self._download_json(request, video_id=presumptive_id)
70
71         if 'Post' in json_data:
72             data = json_data['Post']
73         else:
74             data = json_data
75
76         video_id = compat_str(data['item_id'])
77         upload_date = datetime.datetime.strptime(data['datestamp'], '%m-%d-%y %H:%M%p').strftime('%Y%m%d')
78         subtitles = {}
79         formats = []
80         if 'additionalMedia' in data:
81             for f in data['additionalMedia']:
82                 if f.get('file_type_srt') == 1:
83                     LANGS = {
84                         'english': 'en',
85                     }
86                     lang = f['role'].rpartition('-')[-1].strip().lower()
87                     langcode = LANGS.get(lang, lang)
88                     subtitles[langcode] = f['url']
89                     continue
90                 if not int(f['media_width']):  # filter m3u8
91                     continue
92                 formats.append({
93                     'url': f['url'],
94                     'format_id': f['role'],
95                     'width': int(f['media_width']),
96                     'height': int(f['media_height']),
97                 })
98         else:
99             formats.append({
100                 'url': data['media']['url'],
101                 'width': int(data['media']['width']),
102                 'height': int(data['media']['height']),
103             })
104         self._sort_formats(formats)
105
106         # subtitles
107         video_subtitles = self.extract_subtitles(video_id, subtitles)
108         if self._downloader.params.get('listsubtitles', False):
109             self._list_available_subtitles(video_id, subtitles)
110             return
111
112         return {
113             'id': video_id,
114             'uploader': data['display_name'],
115             'upload_date': upload_date,
116             'title': data['title'],
117             'thumbnail': data['thumbnailUrl'],
118             'description': data['description'],
119             'user_agent': 'iTunes/10.6.1',
120             'formats': formats,
121             'subtitles': video_subtitles,
122         }
123
124     def _download_subtitle_url(self, sub_lang, url):
125         # For some weird reason, blip.tv serves a video instead of subtitles
126         # when we request with a common UA
127         req = compat_urllib_request.Request(url)
128         req.add_header('Youtubedl-user-agent', 'youtube-dl')
129         return self._download_webpage(req, None, note=False)
130
131
132 class BlipTVUserIE(InfoExtractor):
133     _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?blip\.tv/)|bliptvuser:)([^/]+)/*$'
134     _PAGE_SIZE = 12
135     IE_NAME = 'blip.tv:user'
136
137     def _real_extract(self, url):
138         mobj = re.match(self._VALID_URL, url)
139         username = mobj.group(1)
140
141         page_base = 'http://m.blip.tv/pr/show_get_full_episode_list?users_id=%s&lite=0&esi=1'
142
143         page = self._download_webpage(url, username, 'Downloading user page')
144         mobj = re.search(r'data-users-id="([^"]+)"', page)
145         page_base = page_base % mobj.group(1)
146
147         # Download video ids using BlipTV Ajax calls. Result size per
148         # query is limited (currently to 12 videos) so we need to query
149         # page by page until there are no video ids - it means we got
150         # all of them.
151
152         video_ids = []
153         pagenum = 1
154
155         while True:
156             url = page_base + "&page=" + str(pagenum)
157             page = self._download_webpage(
158                 url, username, 'Downloading video ids from page %d' % pagenum)
159
160             # Extract video identifiers
161             ids_in_page = []
162
163             for mobj in re.finditer(r'href="/([^"]+)"', page):
164                 if mobj.group(1) not in ids_in_page:
165                     ids_in_page.append(unescapeHTML(mobj.group(1)))
166
167             video_ids.extend(ids_in_page)
168
169             # A little optimization - if current page is not
170             # "full", ie. does not contain PAGE_SIZE video ids then
171             # we can assume that this page is the last one - there
172             # are no more ids on further pages - no need to query
173             # again.
174
175             if len(ids_in_page) < self._PAGE_SIZE:
176                 break
177
178             pagenum += 1
179
180         urls = ['http://blip.tv/%s' % video_id for video_id in video_ids]
181         url_entries = [self.url_result(vurl, 'BlipTV') for vurl in urls]
182         return [self.playlist_result(url_entries, playlist_title=username)]