Credit @ferama
[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 ..compat import compat_urllib_request
8 from ..utils import (
9     float_or_none,
10     xpath_text,
11     remove_end,
12     int_or_none,
13     ExtractorError,
14 )
15
16
17 class TwitterCardIE(InfoExtractor):
18     IE_NAME = 'twitter:card'
19     _VALID_URL = r'https?://(?:www\.)?twitter\.com/i/cards/tfw/v1/(?P<id>\d+)'
20     _TESTS = [
21         {
22             'url': 'https://twitter.com/i/cards/tfw/v1/560070183650213889',
23             'md5': '7d2f6b4d2eb841a7ccc893d479bfceb4',
24             'info_dict': {
25                 'id': '560070183650213889',
26                 'ext': 'mp4',
27                 'title': 'TwitterCard',
28                 'thumbnail': 're:^https?://.*\.jpg$',
29                 'duration': 30.033,
30             }
31         },
32         {
33             'url': 'https://twitter.com/i/cards/tfw/v1/623160978427936768',
34             'md5': '7ee2a553b63d1bccba97fbed97d9e1c8',
35             'info_dict': {
36                 'id': '623160978427936768',
37                 'ext': 'mp4',
38                 'title': 'TwitterCard',
39                 'thumbnail': 're:^https?://.*\.jpg',
40                 'duration': 80.155,
41             },
42         },
43         {
44             'url': 'https://twitter.com/i/cards/tfw/v1/654001591733886977',
45             'md5': 'b6f35e8b08a0bec6c8af77a2f4b3a814',
46             'info_dict': {
47                 'id': 'dq4Oj5quskI',
48                 'ext': 'mp4',
49                 'title': 'Ubuntu 11.10 Overview',
50                 '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/',
51                 'upload_date': '20111013',
52                 'uploader': 'OMG! Ubuntu!',
53                 'uploader_id': 'omgubuntu',
54             },
55         }
56     ]
57
58     def _real_extract(self, url):
59         video_id = self._match_id(url)
60
61         # Different formats served for different User-Agents
62         USER_AGENTS = [
63             'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20150101 Firefox/20.0 (Chrome)',  # mp4
64             'Mozilla/5.0 (Windows NT 5.2; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0',  # webm
65         ]
66
67         config = None
68         formats = []
69         for user_agent in USER_AGENTS:
70             request = compat_urllib_request.Request(url)
71             request.add_header('User-Agent', user_agent)
72             webpage = self._download_webpage(request, video_id)
73
74             youtube_url = self._html_search_regex(
75                 r'<iframe[^>]+src="((?:https?:)?//www.youtube.com/embed/[^"]+)"',
76                 webpage, 'youtube iframe', default=None)
77             if youtube_url:
78                 return self.url_result(youtube_url, 'Youtube')
79
80             config = self._parse_json(self._html_search_regex(
81                 r'data-player-config="([^"]+)"', webpage, 'data player config'),
82                 video_id)
83             if 'playlist' not in config:
84                 if 'vmapUrl' in config:
85                     vmap_data = self._download_xml(config['vmapUrl'], video_id)
86                     video_url = xpath_text(vmap_data, './/MediaFile').strip()
87                     formats.append({
88                         'url': video_url,
89                     })
90                     break   # same video regardless of UA
91                 continue
92
93             video_url = config['playlist'][0]['source']
94
95             f = {
96                 'url': video_url,
97             }
98
99             m = re.search(r'/(?P<width>\d+)x(?P<height>\d+)/', video_url)
100             if m:
101                 f.update({
102                     'width': int(m.group('width')),
103                     'height': int(m.group('height')),
104                 })
105             formats.append(f)
106         self._sort_formats(formats)
107
108         thumbnail = config.get('posterImageUrl')
109         duration = float_or_none(config.get('duration'))
110
111         return {
112             'id': video_id,
113             'title': 'TwitterCard',
114             'thumbnail': thumbnail,
115             'duration': duration,
116             'formats': formats,
117         }
118
119
120 class TwitterIE(InfoExtractor):
121     IE_NAME = 'twitter'
122     _VALID_URL = r'https?://(?:www\.|m\.|mobile\.)?twitter\.com/(?P<user_id>[^/]+)/status/(?P<id>\d+)'
123     _TEMPLATE_URL = 'https://twitter.com/%s/status/%s'
124
125     _TESTS = [{
126         'url': 'https://twitter.com/freethenipple/status/643211948184596480',
127         'md5': '31cd83a116fc41f99ae3d909d4caf6a0',
128         'info_dict': {
129             'id': '643211948184596480',
130             'ext': 'mp4',
131             'title': 'FREE THE NIPPLE - FTN supporters on Hollywood Blvd today!',
132             'thumbnail': 're:^https?://.*\.jpg',
133             'duration': 12.922,
134             'description': 'FREE THE NIPPLE on Twitter: "FTN supporters on Hollywood Blvd today! http://t.co/c7jHH749xJ"',
135             'uploader': 'FREE THE NIPPLE',
136             'uploader_id': 'freethenipple',
137         },
138     }, {
139         'url': 'https://twitter.com/giphz/status/657991469417025536/photo/1',
140         'md5': 'f36dcd5fb92bf7057f155e7d927eeb42',
141         'info_dict': {
142             'id': '657991469417025536',
143             'ext': 'mp4',
144             'title': 'Gifs - tu vai cai tu vai cai tu nao eh capaz disso tu vai cai',
145             'description': 'Gifs on Twitter: "tu vai cai tu vai cai tu nao eh capaz disso tu vai cai https://t.co/tM46VHFlO5"',
146             'thumbnail': 're:^https?://.*\.png',
147             'uploader': 'Gifs',
148             'uploader_id': 'giphz',
149         },
150     }]
151
152     def _real_extract(self, url):
153         mobj = re.match(self._VALID_URL, url)
154         user_id = mobj.group('user_id')
155         twid = mobj.group('id')
156
157         webpage = self._download_webpage(self._TEMPLATE_URL % (user_id, twid), twid)
158
159         username = remove_end(self._og_search_title(webpage), ' on Twitter')
160
161         title = self._og_search_description(webpage).strip('').replace('\n', ' ')
162
163         # strip  'https -_t.co_BJYgOjSeGA' junk from filenames
164         mobj = re.match(r'“(.*)\s+(https?://[^ ]+)”', title)
165         title, short_url = mobj.groups()
166
167         info = {
168             'uploader_id': user_id,
169             'uploader': username,
170             'webpage_url': url,
171             'description': '%s on Twitter: "%s %s"' % (username, title, short_url),
172             'title': username + ' - ' + title,
173         }
174
175         card_id = self._search_regex(
176             r'["\']/i/cards/tfw/v1/(\d+)', webpage, 'twitter card url', default=None)
177         if card_id:
178             card_url = 'https://twitter.com/i/cards/tfw/v1/' + card_id
179             info.update({
180                 '_type': 'url_transparent',
181                 'ie_key': 'TwitterCard',
182                 'url': card_url,
183             })
184             return info
185
186         mobj = re.search(r'''(?x)
187             <video[^>]+class="animated-gif"[^>]+
188                 (?:data-height="(?P<height>\d+)")?[^>]+
189                 (?:data-width="(?P<width>\d+)")?[^>]+
190                 (?:poster="(?P<poster>[^"]+)")?[^>]*>\s*
191                 <source[^>]+video-src="(?P<url>[^"]+)"
192         ''', webpage)
193
194         if mobj:
195             info.update({
196                 'id': twid,
197                 'url': mobj.group('url'),
198                 'height': int_or_none(mobj.group('height')),
199                 'width': int_or_none(mobj.group('width')),
200                 'thumbnail': mobj.group('poster'),
201             })
202             return info
203
204         raise ExtractorError('There\'s not video in this tweet.')