[twitter] Support twitter.com/i/videos/tweet/ URLS
[youtube-dl] / youtube_dl / extractor / twitter.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5
6 from .common import InfoExtractor
7 from ..utils import (
8     float_or_none,
9     xpath_text,
10     remove_end,
11     int_or_none,
12     ExtractorError,
13     sanitized_Request,
14 )
15
16
17 class TwitterBaseIE(InfoExtractor):
18     def _get_vmap_video_url(self, vmap_url, video_id):
19         vmap_data = self._download_xml(vmap_url, video_id)
20         return xpath_text(vmap_data, './/MediaFile').strip()
21
22
23 class TwitterCardIE(TwitterBaseIE):
24     IE_NAME = 'twitter:card'
25     _VALID_URL = r'https?://(?:www\.)?twitter\.com/i/(?:cards/tfw/v1|videos/tweet)/(?P<id>\d+)'
26     _TESTS = [
27         {
28             'url': 'https://twitter.com/i/cards/tfw/v1/560070183650213889',
29             # MD5 checksums are different in different places
30             'info_dict': {
31                 'id': '560070183650213889',
32                 'ext': 'mp4',
33                 'title': 'Twitter Card',
34                 'thumbnail': 're:^https?://.*\.jpg$',
35                 'duration': 30.033,
36             }
37         },
38         {
39             'url': 'https://twitter.com/i/cards/tfw/v1/623160978427936768',
40             'md5': '7ee2a553b63d1bccba97fbed97d9e1c8',
41             'info_dict': {
42                 'id': '623160978427936768',
43                 'ext': 'mp4',
44                 'title': 'Twitter Card',
45                 'thumbnail': 're:^https?://.*\.jpg',
46                 'duration': 80.155,
47             },
48         },
49         {
50             'url': 'https://twitter.com/i/cards/tfw/v1/654001591733886977',
51             'md5': 'd4724ffe6d2437886d004fa5de1043b3',
52             'info_dict': {
53                 'id': 'dq4Oj5quskI',
54                 'ext': 'mp4',
55                 'title': 'Ubuntu 11.10 Overview',
56                 'description': 'Take a quick peek at what\'s new and improved in Ubuntu 11.10.\n\nOnce installed take a look at 10 Things to Do After Installing: http://www.omgubuntu.co.uk/2011/10/10-things-to-do-after-installing-ubuntu-11-10/',
57                 'upload_date': '20111013',
58                 'uploader': 'OMG! Ubuntu!',
59                 'uploader_id': 'omgubuntu',
60             },
61             'add_ie': ['Youtube'],
62         },
63         {
64             'url': 'https://twitter.com/i/cards/tfw/v1/665289828897005568',
65             'md5': 'ab2745d0b0ce53319a534fccaa986439',
66             'info_dict': {
67                 'id': 'iBb2x00UVlv',
68                 'ext': 'mp4',
69                 'upload_date': '20151113',
70                 'uploader_id': '1189339351084113920',
71                 'uploader': 'ArsenalTerje',
72                 'title': 'Vine by ArsenalTerje',
73             },
74             'add_ie': ['Vine'],
75         }, {
76             'url': 'https://twitter.com/i/videos/tweet/705235433198714880',
77             'md5': '3846d0a07109b5ab622425449b59049d',
78             'info_dict': {
79                 'id': '705235433198714880',
80                 'ext': 'mp4',
81                 'title': 'Twitter web player',
82                 'thumbnail': 're:^https?://.*\.jpg',
83             },
84         },
85     ]
86
87     def _real_extract(self, url):
88         video_id = self._match_id(url)
89
90         # Different formats served for different User-Agents
91         USER_AGENTS = [
92             'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20150101 Firefox/20.0 (Chrome)',  # mp4
93             'Mozilla/5.0 (Windows NT 5.2; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0',  # webm
94         ]
95
96         config = None
97         formats = []
98         for user_agent in USER_AGENTS:
99             request = sanitized_Request(url)
100             request.add_header('User-Agent', user_agent)
101             webpage = self._download_webpage(request, video_id)
102
103             iframe_url = self._html_search_regex(
104                 r'<iframe[^>]+src="((?:https?:)?//(?:www.youtube.com/embed/[^"]+|(?:www\.)?vine\.co/v/\w+/card))"',
105                 webpage, 'video iframe', default=None)
106             if iframe_url:
107                 return self.url_result(iframe_url)
108
109             config = self._parse_json(self._html_search_regex(
110                 r'data-(?:player-)?config="([^"]+)"', webpage, 'data player config'),
111                 video_id)
112             if 'playlist' not in config:
113                 vmap_url = config.get('vmapUrl') or config.get('vmap_url')
114                 if vmap_url:
115                     formats.append({
116                         'url': self._get_vmap_video_url(vmap_url, video_id),
117                     })
118                     break   # same video regardless of UA
119                 continue
120
121             video_url = config['playlist'][0]['source']
122
123             f = {
124                 'url': video_url,
125             }
126
127             m = re.search(r'/(?P<width>\d+)x(?P<height>\d+)/', video_url)
128             if m:
129                 f.update({
130                     'width': int(m.group('width')),
131                     'height': int(m.group('height')),
132                 })
133             formats.append(f)
134         self._sort_formats(formats)
135
136         title = self._search_regex(r'<title>([^<]+)</title>', webpage, 'title')
137         thumbnail = config.get('posterImageUrl') or config.get('image_src')
138         duration = float_or_none(config.get('duration'))
139
140         return {
141             'id': video_id,
142             'title': title,
143             'thumbnail': thumbnail,
144             'duration': duration,
145             'formats': formats,
146         }
147
148
149 class TwitterIE(InfoExtractor):
150     IE_NAME = 'twitter'
151     _VALID_URL = r'https?://(?:www\.|m\.|mobile\.)?twitter\.com/(?P<user_id>[^/]+)/status/(?P<id>\d+)'
152     _TEMPLATE_URL = 'https://twitter.com/%s/status/%s'
153
154     _TESTS = [{
155         'url': 'https://twitter.com/freethenipple/status/643211948184596480',
156         # MD5 checksums are different in different places
157         'info_dict': {
158             'id': '643211948184596480',
159             'ext': 'mp4',
160             'title': 'FREE THE NIPPLE - FTN supporters on Hollywood Blvd today!',
161             'thumbnail': 're:^https?://.*\.jpg',
162             'duration': 12.922,
163             'description': 'FREE THE NIPPLE on Twitter: "FTN supporters on Hollywood Blvd today! http://t.co/c7jHH749xJ"',
164             'uploader': 'FREE THE NIPPLE',
165             'uploader_id': 'freethenipple',
166         },
167     }, {
168         'url': 'https://twitter.com/giphz/status/657991469417025536/photo/1',
169         'md5': 'f36dcd5fb92bf7057f155e7d927eeb42',
170         'info_dict': {
171             'id': '657991469417025536',
172             'ext': 'mp4',
173             'title': 'Gifs - tu vai cai tu vai cai tu nao eh capaz disso tu vai cai',
174             'description': 'Gifs on Twitter: "tu vai cai tu vai cai tu nao eh capaz disso tu vai cai https://t.co/tM46VHFlO5"',
175             'thumbnail': 're:^https?://.*\.png',
176             'uploader': 'Gifs',
177             'uploader_id': 'giphz',
178         },
179         'expected_warnings': ['height', 'width'],
180     }, {
181         'url': 'https://twitter.com/starwars/status/665052190608723968',
182         'md5': '39b7199856dee6cd4432e72c74bc69d4',
183         'info_dict': {
184             'id': '665052190608723968',
185             'ext': 'mp4',
186             'title': 'Star Wars - A new beginning is coming December 18. Watch the official 60 second #TV spot for #StarWars: #TheForceAwakens.',
187             'description': 'Star Wars on Twitter: "A new beginning is coming December 18. Watch the official 60 second #TV spot for #StarWars: #TheForceAwakens."',
188             'uploader_id': 'starwars',
189             'uploader': 'Star Wars',
190         },
191     }, {
192         'url': 'https://twitter.com/BTNBrentYarina/status/705235433198714880',
193         'info_dict': {
194             'id': '705235433198714880',
195             'ext': 'mp4',
196             'title': 'Brent Yarina - Khalil Iverson\'s missed highlight dunk. And made highlight dunk. In one highlight.',
197             'description': 'Brent Yarina on Twitter: "Khalil Iverson\'s missed highlight dunk. And made highlight dunk. In one highlight."',
198             'uploader_id': 'BTNBrentYarina',
199             'uploader': 'Brent Yarina',
200         },
201         'params': {
202             # The same video as https://twitter.com/i/videos/tweet/705235433198714880
203             # Test case of TwitterCardIE
204             'skip_download': True,
205         },
206     }]
207
208     def _real_extract(self, url):
209         mobj = re.match(self._VALID_URL, url)
210         user_id = mobj.group('user_id')
211         twid = mobj.group('id')
212
213         webpage = self._download_webpage(self._TEMPLATE_URL % (user_id, twid), twid)
214
215         username = remove_end(self._og_search_title(webpage), ' on Twitter')
216
217         title = description = self._og_search_description(webpage).strip('').replace('\n', ' ').strip('“”')
218
219         # strip  'https -_t.co_BJYgOjSeGA' junk from filenames
220         title = re.sub(r'\s+(https?://[^ ]+)', '', title)
221
222         info = {
223             'uploader_id': user_id,
224             'uploader': username,
225             'webpage_url': url,
226             'description': '%s on Twitter: "%s"' % (username, description),
227             'title': username + ' - ' + title,
228         }
229
230         card_id = self._search_regex(
231             r'["\']/i/cards/tfw/v1/(\d+)', webpage, 'twitter card url', default=None)
232         if card_id:
233             card_url = 'https://twitter.com/i/cards/tfw/v1/' + card_id
234             info.update({
235                 '_type': 'url_transparent',
236                 'ie_key': 'TwitterCard',
237                 'url': card_url,
238             })
239             return info
240
241         mobj = re.search(r'''(?x)
242             <video[^>]+class="animated-gif"(?P<more_info>[^>]+)>\s*
243                 <source[^>]+video-src="(?P<url>[^"]+)"
244         ''', webpage)
245
246         if mobj:
247             more_info = mobj.group('more_info')
248             height = int_or_none(self._search_regex(
249                 r'data-height="(\d+)"', more_info, 'height', fatal=False))
250             width = int_or_none(self._search_regex(
251                 r'data-width="(\d+)"', more_info, 'width', fatal=False))
252             thumbnail = self._search_regex(
253                 r'poster="([^"]+)"', more_info, 'poster', fatal=False)
254             info.update({
255                 'id': twid,
256                 'url': mobj.group('url'),
257                 'height': height,
258                 'width': width,
259                 'thumbnail': thumbnail,
260             })
261             return info
262
263         if 'class="PlayableMedia' in webpage:
264             info.update({
265                 '_type': 'url_transparent',
266                 'ie_key': 'TwitterCard',
267                 'url': '%s//twitter.com/i/videos/tweet/%s' % (self.http_scheme(), twid),
268             })
269
270             return info
271
272         raise ExtractorError('There\'s no video in this tweet.')
273
274
275 class TwitterAmplifyIE(TwitterBaseIE):
276     IE_NAME = 'twitter:amplify'
277     _VALID_URL = 'https?://amp\.twimg\.com/v/(?P<id>[0-9a-f\-]{36})'
278
279     _TEST = {
280         'url': 'https://amp.twimg.com/v/0ba0c3c7-0af3-4c0a-bed5-7efd1ffa2951',
281         'md5': '7df102d0b9fd7066b86f3159f8e81bf6',
282         'info_dict': {
283             'id': '0ba0c3c7-0af3-4c0a-bed5-7efd1ffa2951',
284             'ext': 'mp4',
285             'title': 'Twitter Video',
286             'thumbnail': 're:^https?://.*',
287         },
288     }
289
290     def _real_extract(self, url):
291         video_id = self._match_id(url)
292         webpage = self._download_webpage(url, video_id)
293
294         vmap_url = self._html_search_meta(
295             'twitter:amplify:vmap', webpage, 'vmap url')
296         video_url = self._get_vmap_video_url(vmap_url, video_id)
297
298         thumbnails = []
299         thumbnail = self._html_search_meta(
300             'twitter:image:src', webpage, 'thumbnail', fatal=False)
301
302         def _find_dimension(target):
303             w = int_or_none(self._html_search_meta(
304                 'twitter:%s:width' % target, webpage, fatal=False))
305             h = int_or_none(self._html_search_meta(
306                 'twitter:%s:height' % target, webpage, fatal=False))
307             return w, h
308
309         if thumbnail:
310             thumbnail_w, thumbnail_h = _find_dimension('image')
311             thumbnails.append({
312                 'url': thumbnail,
313                 'width': thumbnail_w,
314                 'height': thumbnail_h,
315             })
316
317         video_w, video_h = _find_dimension('player')
318         formats = [{
319             'url': video_url,
320             'width': video_w,
321             'height': video_h,
322         }]
323
324         return {
325             'id': video_id,
326             'title': 'Twitter Video',
327             'formats': formats,
328             'thumbnails': thumbnails,
329         }