Merge remote-tracking branch 'origin/master'
[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
70         json_data = self._download_json(request, video_id=presumptive_id)
71
72         if 'Post' in json_data:
73             data = json_data['Post']
74         else:
75             data = json_data
76
77         video_id = compat_str(data['item_id'])
78         upload_date = datetime.datetime.strptime(data['datestamp'], '%m-%d-%y %H:%M%p').strftime('%Y%m%d')
79         subtitles = {}
80         formats = []
81         if 'additionalMedia' in data:
82             for f in data['additionalMedia']:
83                 if f.get('file_type_srt') == 1:
84                     LANGS = {
85                         'english': 'en',
86                     }
87                     lang = f['role'].rpartition('-')[-1].strip().lower()
88                     langcode = LANGS.get(lang, lang)
89                     subtitles[langcode] = f['url']
90                     continue
91                 if not int(f['media_width']):  # filter m3u8
92                     continue
93                 formats.append({
94                     'url': f['url'],
95                     'format_id': f['role'],
96                     'width': int(f['media_width']),
97                     'height': int(f['media_height']),
98                 })
99         else:
100             formats.append({
101                 'url': data['media']['url'],
102                 'width': int(data['media']['width']),
103                 'height': int(data['media']['height']),
104             })
105         self._sort_formats(formats)
106
107         # subtitles
108         video_subtitles = self.extract_subtitles(video_id, subtitles)
109         if self._downloader.params.get('listsubtitles', False):
110             self._list_available_subtitles(video_id, subtitles)
111             return
112
113         return {
114             'id': video_id,
115             'uploader': data['display_name'],
116             'upload_date': upload_date,
117             'title': data['title'],
118             'thumbnail': data['thumbnailUrl'],
119             'description': data['description'],
120             'user_agent': 'iTunes/10.6.1',
121             'formats': formats,
122             'subtitles': video_subtitles,
123         }
124
125     def _download_subtitle_url(self, sub_lang, url):
126         # For some weird reason, blip.tv serves a video instead of subtitles
127         # when we request with a common UA
128         req = compat_urllib_request.Request(url)
129         req.add_header('Youtubedl-user-agent', 'youtube-dl')
130         return self._download_webpage(req, None, note=False)
131
132
133 class BlipTVUserIE(InfoExtractor):
134     _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?blip\.tv/)|bliptvuser:)([^/]+)/*$'
135     _PAGE_SIZE = 12
136     IE_NAME = 'blip.tv:user'
137
138     def _real_extract(self, url):
139         mobj = re.match(self._VALID_URL, url)
140         username = mobj.group(1)
141
142         page_base = 'http://m.blip.tv/pr/show_get_full_episode_list?users_id=%s&lite=0&esi=1'
143
144         page = self._download_webpage(url, username, 'Downloading user page')
145         mobj = re.search(r'data-users-id="([^"]+)"', page)
146         page_base = page_base % mobj.group(1)
147
148         # Download video ids using BlipTV Ajax calls. Result size per
149         # query is limited (currently to 12 videos) so we need to query
150         # page by page until there are no video ids - it means we got
151         # all of them.
152
153         video_ids = []
154         pagenum = 1
155
156         while True:
157             url = page_base + "&page=" + str(pagenum)
158             page = self._download_webpage(
159                 url, username, 'Downloading video ids from page %d' % pagenum)
160
161             # Extract video identifiers
162             ids_in_page = []
163
164             for mobj in re.finditer(r'href="/([^"]+)"', page):
165                 if mobj.group(1) not in ids_in_page:
166                     ids_in_page.append(unescapeHTML(mobj.group(1)))
167
168             video_ids.extend(ids_in_page)
169
170             # A little optimization - if current page is not
171             # "full", ie. does not contain PAGE_SIZE video ids then
172             # we can assume that this page is the last one - there
173             # are no more ids on further pages - no need to query
174             # again.
175
176             if len(ids_in_page) < self._PAGE_SIZE:
177                 break
178
179             pagenum += 1
180
181         urls = ['http://blip.tv/%s' % video_id for video_id in video_ids]
182         url_entries = [self.url_result(vurl, 'BlipTV') for vurl in urls]
183         return [self.playlist_result(url_entries, playlist_title=username)]