[twitter] Simplify and improve
[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     unescapeHTML,
11     xpath_text,
12     remove_end,
13 )
14
15
16 class TwitterCardIE(InfoExtractor):
17     IE_NAME = 'twitter:card'
18     _VALID_URL = r'https?://(?:www\.)?twitter\.com/i/cards/tfw/v1/(?P<id>\d+)'
19     _TESTS = [
20         {
21             'url': 'https://twitter.com/i/cards/tfw/v1/560070183650213889',
22             'md5': '7d2f6b4d2eb841a7ccc893d479bfceb4',
23             'info_dict': {
24                 'id': '560070183650213889',
25                 'ext': 'mp4',
26                 'title': 'TwitterCard',
27                 'thumbnail': 're:^https?://.*\.jpg$',
28                 'duration': 30.033,
29             }
30         },
31         {
32             'url': 'https://twitter.com/i/cards/tfw/v1/623160978427936768',
33             'md5': '7ee2a553b63d1bccba97fbed97d9e1c8',
34             'info_dict': {
35                 'id': '623160978427936768',
36                 'ext': 'mp4',
37                 'title': 'TwitterCard',
38                 'thumbnail': 're:^https?://.*\.jpg',
39                 'duration': 80.155,
40             },
41         }
42     ]
43
44     def _real_extract(self, url):
45         video_id = self._match_id(url)
46
47         # Different formats served for different User-Agents
48         USER_AGENTS = [
49             'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20150101 Firefox/20.0 (Chrome)',  # mp4
50             'Mozilla/5.0 (Windows NT 5.2; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0',  # webm
51         ]
52
53         config = None
54         formats = []
55         for user_agent in USER_AGENTS:
56             request = compat_urllib_request.Request(url)
57             request.add_header('User-Agent', user_agent)
58             webpage = self._download_webpage(request, video_id)
59
60             config = self._parse_json(
61                 unescapeHTML(self._search_regex(
62                     r'data-player-config="([^"]+)"', webpage, 'data player config')),
63                 video_id)
64             if 'playlist' not in config:
65                 if 'vmapUrl' in config:
66                     vmap_data = self._download_xml(config['vmapUrl'], video_id)
67                     video_url = xpath_text(vmap_data, './/MediaFile').strip()
68                     formats.append({
69                         'url': video_url,
70                     })
71                     break   # same video regardless of UA
72                 continue
73
74             video_url = config['playlist'][0]['source']
75
76             f = {
77                 'url': video_url,
78             }
79
80             m = re.search(r'/(?P<width>\d+)x(?P<height>\d+)/', video_url)
81             if m:
82                 f.update({
83                     'width': int(m.group('width')),
84                     'height': int(m.group('height')),
85                 })
86             formats.append(f)
87         self._sort_formats(formats)
88
89         thumbnail = config.get('posterImageUrl')
90         duration = float_or_none(config.get('duration'))
91
92         return {
93             'id': video_id,
94             'title': 'TwitterCard',
95             'thumbnail': thumbnail,
96             'duration': duration,
97             'formats': formats,
98         }
99
100
101 class TwitterIE(InfoExtractor):
102     IE_NAME = 'twitter'
103     _VALID_URL = r'https?://(?:www\.|m\.|mobile\.)?twitter\.com/(?P<user_id>[^/]+)/status/(?P<id>\d+)'
104     _TEMPLATE_URL = 'https://twitter.com/%s/status/%s'
105
106     _TEST = {
107         'url': 'https://twitter.com/freethenipple/status/643211948184596480',
108         'md5': '31cd83a116fc41f99ae3d909d4caf6a0',
109         'info_dict': {
110             'id': '643211948184596480',
111             'ext': 'mp4',
112             'title': 'FREE THE NIPPLE - FTN supporters on Hollywood Blvd today!',
113             'thumbnail': 're:^https?://.*\.jpg',
114             'duration': 12.922,
115             'description': 'FREE THE NIPPLE on Twitter: "FTN supporters on Hollywood Blvd today! http://t.co/c7jHH749xJ"',
116             'uploader': 'FREE THE NIPPLE',
117             'uploader_id': 'freethenipple',
118         },
119     }
120
121     def _real_extract(self, url):
122         mobj = re.match(self._VALID_URL, url)
123         user_id = mobj.group('user_id')
124         twid = mobj.group('id')
125
126         webpage = self._download_webpage(self._TEMPLATE_URL % (user_id, twid), twid)
127
128         username = remove_end(self._og_search_title(webpage), ' on Twitter')
129
130         title = self._og_search_description(webpage).strip('').replace('\n', ' ')
131
132         # strip  'https -_t.co_BJYgOjSeGA' junk from filenames
133         mobj = re.match(r'“(.*)\s+(http://[^ ]+)”', title)
134         title, short_url = mobj.groups()
135
136         card_id = self._search_regex(
137             r'["\']/i/cards/tfw/v1/(\d+)', webpage, 'twitter card url')
138         card_url = 'https://twitter.com/i/cards/tfw/v1/' + card_id
139
140         return {
141             '_type': 'url_transparent',
142             'ie_key': 'TwitterCard',
143             'uploader_id': user_id,
144             'uploader': username,
145             'url': card_url,
146             'webpage_url': url,
147             'description': '%s on Twitter: "%s %s"' % (username, title, short_url),
148             'title': username + ' - ' + title,
149         }