youtube-dl

Another place where youtube-dl lives on
git clone git://git.oshgnacknak.de/youtube-dl.git
Log | Files | Refs | README | LICENSE

twitter.py (28035B)


      1 # coding: utf-8
      2 from __future__ import unicode_literals
      3 
      4 import re
      5 
      6 from .common import InfoExtractor
      7 from ..compat import (
      8     compat_HTTPError,
      9     compat_parse_qs,
     10     compat_urllib_parse_unquote,
     11     compat_urllib_parse_urlparse,
     12 )
     13 from ..utils import (
     14     dict_get,
     15     ExtractorError,
     16     float_or_none,
     17     int_or_none,
     18     try_get,
     19     strip_or_none,
     20     unified_timestamp,
     21     update_url_query,
     22     url_or_none,
     23     xpath_text,
     24 )
     25 
     26 from .periscope import (
     27     PeriscopeBaseIE,
     28     PeriscopeIE,
     29 )
     30 
     31 
     32 class TwitterBaseIE(InfoExtractor):
     33     _API_BASE = 'https://api.twitter.com/1.1/'
     34     _BASE_REGEX = r'https?://(?:(?:www|m(?:obile)?)\.)?twitter\.com/'
     35     _GUEST_TOKEN = None
     36 
     37     def _extract_variant_formats(self, variant, video_id):
     38         variant_url = variant.get('url')
     39         if not variant_url:
     40             return []
     41         elif '.m3u8' in variant_url:
     42             return self._extract_m3u8_formats(
     43                 variant_url, video_id, 'mp4', 'm3u8_native',
     44                 m3u8_id='hls', fatal=False)
     45         else:
     46             tbr = int_or_none(dict_get(variant, ('bitrate', 'bit_rate')), 1000) or None
     47             f = {
     48                 'url': variant_url,
     49                 'format_id': 'http' + ('-%d' % tbr if tbr else ''),
     50                 'tbr': tbr,
     51             }
     52             self._search_dimensions_in_video_url(f, variant_url)
     53             return [f]
     54 
     55     def _extract_formats_from_vmap_url(self, vmap_url, video_id):
     56         vmap_url = url_or_none(vmap_url)
     57         if not vmap_url:
     58             return []
     59         vmap_data = self._download_xml(vmap_url, video_id)
     60         formats = []
     61         urls = []
     62         for video_variant in vmap_data.findall('.//{http://twitter.com/schema/videoVMapV2.xsd}videoVariant'):
     63             video_variant.attrib['url'] = compat_urllib_parse_unquote(
     64                 video_variant.attrib['url'])
     65             urls.append(video_variant.attrib['url'])
     66             formats.extend(self._extract_variant_formats(
     67                 video_variant.attrib, video_id))
     68         video_url = strip_or_none(xpath_text(vmap_data, './/MediaFile'))
     69         if video_url not in urls:
     70             formats.extend(self._extract_variant_formats({'url': video_url}, video_id))
     71         return formats
     72 
     73     @staticmethod
     74     def _search_dimensions_in_video_url(a_format, video_url):
     75         m = re.search(r'/(?P<width>\d+)x(?P<height>\d+)/', video_url)
     76         if m:
     77             a_format.update({
     78                 'width': int(m.group('width')),
     79                 'height': int(m.group('height')),
     80             })
     81 
     82     def _call_api(self, path, video_id, query={}):
     83         headers = {
     84             'Authorization': 'Bearer AAAAAAAAAAAAAAAAAAAAAPYXBAAAAAAACLXUNDekMxqa8h%2F40K4moUkGsoc%3DTYfbDKbT3jJPCEVnMYqilB28NHfOPqkca3qaAxGfsyKCs0wRbw',
     85         }
     86         if not self._GUEST_TOKEN:
     87             self._GUEST_TOKEN = self._download_json(
     88                 self._API_BASE + 'guest/activate.json', video_id,
     89                 'Downloading guest token', data=b'',
     90                 headers=headers)['guest_token']
     91         headers['x-guest-token'] = self._GUEST_TOKEN
     92         try:
     93             return self._download_json(
     94                 self._API_BASE + path, video_id, headers=headers, query=query)
     95         except ExtractorError as e:
     96             if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
     97                 raise ExtractorError(self._parse_json(
     98                     e.cause.read().decode(),
     99                     video_id)['errors'][0]['message'], expected=True)
    100             raise
    101 
    102 
    103 class TwitterCardIE(InfoExtractor):
    104     IE_NAME = 'twitter:card'
    105     _VALID_URL = TwitterBaseIE._BASE_REGEX + r'i/(?:cards/tfw/v1|videos(?:/tweet)?)/(?P<id>\d+)'
    106     _TESTS = [
    107         {
    108             'url': 'https://twitter.com/i/cards/tfw/v1/560070183650213889',
    109             # MD5 checksums are different in different places
    110             'info_dict': {
    111                 'id': '560070183650213889',
    112                 'ext': 'mp4',
    113                 'title': "Twitter - You can now shoot, edit and share video on Twitter. Capture life's most moving moments from your perspective.",
    114                 'description': 'md5:18d3e24bb4f6e5007487dd546e53bd96',
    115                 'uploader': 'Twitter',
    116                 'uploader_id': 'Twitter',
    117                 'thumbnail': r're:^https?://.*\.jpg',
    118                 'duration': 30.033,
    119                 'timestamp': 1422366112,
    120                 'upload_date': '20150127',
    121             },
    122         },
    123         {
    124             'url': 'https://twitter.com/i/cards/tfw/v1/623160978427936768',
    125             'md5': '7137eca597f72b9abbe61e5ae0161399',
    126             'info_dict': {
    127                 'id': '623160978427936768',
    128                 'ext': 'mp4',
    129                 'title': "NASA - Fly over Pluto's icy Norgay Mountains and Sputnik Plain in this @NASANewHorizons #PlutoFlyby video.",
    130                 'description': "Fly over Pluto's icy Norgay Mountains and Sputnik Plain in this @NASANewHorizons #PlutoFlyby video. https://t.co/BJYgOjSeGA",
    131                 'uploader': 'NASA',
    132                 'uploader_id': 'NASA',
    133                 'timestamp': 1437408129,
    134                 'upload_date': '20150720',
    135             },
    136         },
    137         {
    138             'url': 'https://twitter.com/i/cards/tfw/v1/654001591733886977',
    139             'md5': 'b6d9683dd3f48e340ded81c0e917ad46',
    140             'info_dict': {
    141                 'id': 'dq4Oj5quskI',
    142                 'ext': 'mp4',
    143                 'title': 'Ubuntu 11.10 Overview',
    144                 'description': 'md5:a831e97fa384863d6e26ce48d1c43376',
    145                 'upload_date': '20111013',
    146                 'uploader': 'OMG! UBUNTU!',
    147                 'uploader_id': 'omgubuntu',
    148             },
    149             'add_ie': ['Youtube'],
    150         },
    151         {
    152             'url': 'https://twitter.com/i/cards/tfw/v1/665289828897005568',
    153             'md5': '6dabeaca9e68cbb71c99c322a4b42a11',
    154             'info_dict': {
    155                 'id': 'iBb2x00UVlv',
    156                 'ext': 'mp4',
    157                 'upload_date': '20151113',
    158                 'uploader_id': '1189339351084113920',
    159                 'uploader': 'ArsenalTerje',
    160                 'title': 'Vine by ArsenalTerje',
    161                 'timestamp': 1447451307,
    162             },
    163             'add_ie': ['Vine'],
    164         }, {
    165             'url': 'https://twitter.com/i/videos/tweet/705235433198714880',
    166             'md5': '884812a2adc8aaf6fe52b15ccbfa3b88',
    167             'info_dict': {
    168                 'id': '705235433198714880',
    169                 'ext': 'mp4',
    170                 'title': "Brent Yarina - Khalil Iverson's missed highlight dunk. And made highlight dunk. In one highlight.",
    171                 'description': "Khalil Iverson's missed highlight dunk. And made highlight dunk. In one highlight. https://t.co/OrxcJ28Bns",
    172                 'uploader': 'Brent Yarina',
    173                 'uploader_id': 'BTNBrentYarina',
    174                 'timestamp': 1456976204,
    175                 'upload_date': '20160303',
    176             },
    177             'skip': 'This content is no longer available.',
    178         }, {
    179             'url': 'https://twitter.com/i/videos/752274308186120192',
    180             'only_matching': True,
    181         },
    182     ]
    183 
    184     def _real_extract(self, url):
    185         status_id = self._match_id(url)
    186         return self.url_result(
    187             'https://twitter.com/statuses/' + status_id,
    188             TwitterIE.ie_key(), status_id)
    189 
    190 
    191 class TwitterIE(TwitterBaseIE):
    192     IE_NAME = 'twitter'
    193     _VALID_URL = TwitterBaseIE._BASE_REGEX + r'(?:(?:i/web|[^/]+)/status|statuses)/(?P<id>\d+)'
    194 
    195     _TESTS = [{
    196         'url': 'https://twitter.com/freethenipple/status/643211948184596480',
    197         'info_dict': {
    198             'id': '643211948184596480',
    199             'ext': 'mp4',
    200             'title': 'FREE THE NIPPLE - FTN supporters on Hollywood Blvd today!',
    201             'thumbnail': r're:^https?://.*\.jpg',
    202             'description': 'FTN supporters on Hollywood Blvd today! http://t.co/c7jHH749xJ',
    203             'uploader': 'FREE THE NIPPLE',
    204             'uploader_id': 'freethenipple',
    205             'duration': 12.922,
    206             'timestamp': 1442188653,
    207             'upload_date': '20150913',
    208             'age_limit': 18,
    209         },
    210     }, {
    211         'url': 'https://twitter.com/giphz/status/657991469417025536/photo/1',
    212         'md5': 'f36dcd5fb92bf7057f155e7d927eeb42',
    213         'info_dict': {
    214             'id': '657991469417025536',
    215             'ext': 'mp4',
    216             'title': 'Gifs - tu vai cai tu vai cai tu nao eh capaz disso tu vai cai',
    217             'description': 'Gifs on Twitter: "tu vai cai tu vai cai tu nao eh capaz disso tu vai cai https://t.co/tM46VHFlO5"',
    218             'thumbnail': r're:^https?://.*\.png',
    219             'uploader': 'Gifs',
    220             'uploader_id': 'giphz',
    221         },
    222         'expected_warnings': ['height', 'width'],
    223         'skip': 'Account suspended',
    224     }, {
    225         'url': 'https://twitter.com/starwars/status/665052190608723968',
    226         'info_dict': {
    227             'id': '665052190608723968',
    228             'ext': 'mp4',
    229             'title': 'Star Wars - A new beginning is coming December 18. Watch the official 60 second #TV spot for #StarWars: #TheForceAwakens.',
    230             'description': 'A new beginning is coming December 18. Watch the official 60 second #TV spot for #StarWars: #TheForceAwakens. https://t.co/OkSqT2fjWJ',
    231             'uploader_id': 'starwars',
    232             'uploader': 'Star Wars',
    233             'timestamp': 1447395772,
    234             'upload_date': '20151113',
    235         },
    236     }, {
    237         'url': 'https://twitter.com/BTNBrentYarina/status/705235433198714880',
    238         'info_dict': {
    239             'id': '705235433198714880',
    240             'ext': 'mp4',
    241             'title': "Brent Yarina - Khalil Iverson's missed highlight dunk. And made highlight dunk. In one highlight.",
    242             'description': "Khalil Iverson's missed highlight dunk. And made highlight dunk. In one highlight. https://t.co/OrxcJ28Bns",
    243             'uploader_id': 'BTNBrentYarina',
    244             'uploader': 'Brent Yarina',
    245             'timestamp': 1456976204,
    246             'upload_date': '20160303',
    247         },
    248         'params': {
    249             # The same video as https://twitter.com/i/videos/tweet/705235433198714880
    250             # Test case of TwitterCardIE
    251             'skip_download': True,
    252         },
    253     }, {
    254         'url': 'https://twitter.com/jaydingeer/status/700207533655363584',
    255         'info_dict': {
    256             'id': '700207533655363584',
    257             'ext': 'mp4',
    258             'title': 'simon vertugo - BEAT PROD: @suhmeduh #Damndaniel',
    259             'description': 'BEAT PROD: @suhmeduh  https://t.co/HBrQ4AfpvZ #Damndaniel https://t.co/byBooq2ejZ',
    260             'thumbnail': r're:^https?://.*\.jpg',
    261             'uploader': 'simon vertugo',
    262             'uploader_id': 'simonvertugo',
    263             'duration': 30.0,
    264             'timestamp': 1455777459,
    265             'upload_date': '20160218',
    266         },
    267     }, {
    268         'url': 'https://twitter.com/Filmdrunk/status/713801302971588609',
    269         'md5': '89a15ed345d13b86e9a5a5e051fa308a',
    270         'info_dict': {
    271             'id': 'MIOxnrUteUd',
    272             'ext': 'mp4',
    273             'title': 'Dr.Pepperの飲み方 #japanese #バカ #ドクペ #電動ガン',
    274             'uploader': 'TAKUMA',
    275             'uploader_id': '1004126642786242560',
    276             'timestamp': 1402826626,
    277             'upload_date': '20140615',
    278         },
    279         'add_ie': ['Vine'],
    280     }, {
    281         'url': 'https://twitter.com/captainamerica/status/719944021058060289',
    282         'info_dict': {
    283             'id': '719944021058060289',
    284             'ext': 'mp4',
    285             'title': 'Captain America - @King0fNerd Are you sure you made the right choice? Find out in theaters.',
    286             'description': '@King0fNerd Are you sure you made the right choice? Find out in theaters. https://t.co/GpgYi9xMJI',
    287             'uploader_id': 'CaptainAmerica',
    288             'uploader': 'Captain America',
    289             'duration': 3.17,
    290             'timestamp': 1460483005,
    291             'upload_date': '20160412',
    292         },
    293     }, {
    294         'url': 'https://twitter.com/OPP_HSD/status/779210622571536384',
    295         'info_dict': {
    296             'id': '1zqKVVlkqLaKB',
    297             'ext': 'mp4',
    298             'title': 'Sgt Kerry Schmidt - Ontario Provincial Police - Road rage, mischief, assault, rollover and fire in one occurrence',
    299             'upload_date': '20160923',
    300             'uploader_id': '1PmKqpJdOJQoY',
    301             'uploader': 'Sgt Kerry Schmidt - Ontario Provincial Police',
    302             'timestamp': 1474613214,
    303         },
    304         'add_ie': ['Periscope'],
    305     }, {
    306         # has mp4 formats via mobile API
    307         'url': 'https://twitter.com/news_al3alm/status/852138619213144067',
    308         'info_dict': {
    309             'id': '852138619213144067',
    310             'ext': 'mp4',
    311             'title': 'عالم الأخبار - كلمة تاريخية بجلسة الجناسي التاريخية.. النائب خالد مؤنس العتيبي للمعارضين : اتقوا الله .. الظلم ظلمات يوم القيامة',
    312             'description': 'كلمة تاريخية بجلسة الجناسي التاريخية.. النائب خالد مؤنس العتيبي للمعارضين : اتقوا الله .. الظلم ظلمات يوم القيامة   https://t.co/xg6OhpyKfN',
    313             'uploader': 'عالم الأخبار',
    314             'uploader_id': 'news_al3alm',
    315             'duration': 277.4,
    316             'timestamp': 1492000653,
    317             'upload_date': '20170412',
    318         },
    319         'skip': 'Account suspended',
    320     }, {
    321         'url': 'https://twitter.com/i/web/status/910031516746514432',
    322         'info_dict': {
    323             'id': '910031516746514432',
    324             'ext': 'mp4',
    325             'title': 'Préfet de Guadeloupe - [Direct] #Maria Le centre se trouve actuellement au sud de Basse-Terre. Restez confinés. Réfugiez-vous dans la pièce la + sûre.',
    326             'thumbnail': r're:^https?://.*\.jpg',
    327             'description': '[Direct] #Maria Le centre se trouve actuellement au sud de Basse-Terre. Restez confinés. Réfugiez-vous dans la pièce la + sûre. https://t.co/mwx01Rs4lo',
    328             'uploader': 'Préfet de Guadeloupe',
    329             'uploader_id': 'Prefet971',
    330             'duration': 47.48,
    331             'timestamp': 1505803395,
    332             'upload_date': '20170919',
    333         },
    334         'params': {
    335             'skip_download': True,  # requires ffmpeg
    336         },
    337     }, {
    338         # card via api.twitter.com/1.1/videos/tweet/config
    339         'url': 'https://twitter.com/LisPower1/status/1001551623938805763',
    340         'info_dict': {
    341             'id': '1001551623938805763',
    342             'ext': 'mp4',
    343             'title': 're:.*?Shep is on a roll today.*?',
    344             'thumbnail': r're:^https?://.*\.jpg',
    345             'description': 'md5:37b9f2ff31720cef23b2bd42ee8a0f09',
    346             'uploader': 'Lis Power',
    347             'uploader_id': 'LisPower1',
    348             'duration': 111.278,
    349             'timestamp': 1527623489,
    350             'upload_date': '20180529',
    351         },
    352         'params': {
    353             'skip_download': True,  # requires ffmpeg
    354         },
    355     }, {
    356         'url': 'https://twitter.com/foobar/status/1087791357756956680',
    357         'info_dict': {
    358             'id': '1087791357756956680',
    359             'ext': 'mp4',
    360             'title': 'Twitter - A new is coming.  Some of you got an opt-in to try it now. Check out the emoji button, quick keyboard shortcuts, upgraded trends, advanced search, and more. Let us know your thoughts!',
    361             'thumbnail': r're:^https?://.*\.jpg',
    362             'description': 'md5:6dfd341a3310fb97d80d2bf7145df976',
    363             'uploader': 'Twitter',
    364             'uploader_id': 'Twitter',
    365             'duration': 61.567,
    366             'timestamp': 1548184644,
    367             'upload_date': '20190122',
    368         },
    369     }, {
    370         # not available in Periscope
    371         'url': 'https://twitter.com/ViviEducation/status/1136534865145286656',
    372         'info_dict': {
    373             'id': '1vOGwqejwoWxB',
    374             'ext': 'mp4',
    375             'title': 'Vivi - Vivi founder @lior_rauchy announcing our new student feedback tool live at @EduTECH_AU #EduTECH2019',
    376             'uploader': 'Vivi',
    377             'uploader_id': '1eVjYOLGkGrQL',
    378         },
    379         'add_ie': ['TwitterBroadcast'],
    380     }, {
    381         # unified card
    382         'url': 'https://twitter.com/BrooklynNets/status/1349794411333394432?s=20',
    383         'info_dict': {
    384             'id': '1349794411333394432',
    385             'ext': 'mp4',
    386             'title': 'md5:d1c4941658e4caaa6cb579260d85dcba',
    387             'thumbnail': r're:^https?://.*\.jpg',
    388             'description': 'md5:71ead15ec44cee55071547d6447c6a3e',
    389             'uploader': 'Brooklyn Nets',
    390             'uploader_id': 'BrooklynNets',
    391             'duration': 324.484,
    392             'timestamp': 1610651040,
    393             'upload_date': '20210114',
    394         },
    395         'params': {
    396             'skip_download': True,
    397         },
    398     }, {
    399         # Twitch Clip Embed
    400         'url': 'https://twitter.com/GunB1g/status/1163218564784017422',
    401         'only_matching': True,
    402     }, {
    403         # promo_video_website card
    404         'url': 'https://twitter.com/GunB1g/status/1163218564784017422',
    405         'only_matching': True,
    406     }, {
    407         # promo_video_convo card
    408         'url': 'https://twitter.com/poco_dandy/status/1047395834013384704',
    409         'only_matching': True,
    410     }, {
    411         # appplayer card
    412         'url': 'https://twitter.com/poco_dandy/status/1150646424461176832',
    413         'only_matching': True,
    414     }, {
    415         # video_direct_message card
    416         'url': 'https://twitter.com/qarev001/status/1348948114569269251',
    417         'only_matching': True,
    418     }, {
    419         # poll2choice_video card
    420         'url': 'https://twitter.com/CAF_Online/status/1349365911120195585',
    421         'only_matching': True,
    422     }, {
    423         # poll3choice_video card
    424         'url': 'https://twitter.com/SamsungMobileSA/status/1348609186725289984',
    425         'only_matching': True,
    426     }, {
    427         # poll4choice_video card
    428         'url': 'https://twitter.com/SouthamptonFC/status/1347577658079641604',
    429         'only_matching': True,
    430     }]
    431 
    432     def _real_extract(self, url):
    433         twid = self._match_id(url)
    434         status = self._call_api(
    435             'statuses/show/%s.json' % twid, twid, {
    436                 'cards_platform': 'Web-12',
    437                 'include_cards': 1,
    438                 'include_reply_count': 1,
    439                 'include_user_entities': 0,
    440                 'tweet_mode': 'extended',
    441             })
    442 
    443         title = description = status['full_text'].replace('\n', ' ')
    444         # strip  'https -_t.co_BJYgOjSeGA' junk from filenames
    445         title = re.sub(r'\s+(https?://[^ ]+)', '', title)
    446         user = status.get('user') or {}
    447         uploader = user.get('name')
    448         if uploader:
    449             title = '%s - %s' % (uploader, title)
    450         uploader_id = user.get('screen_name')
    451 
    452         tags = []
    453         for hashtag in (try_get(status, lambda x: x['entities']['hashtags'], list) or []):
    454             hashtag_text = hashtag.get('text')
    455             if not hashtag_text:
    456                 continue
    457             tags.append(hashtag_text)
    458 
    459         info = {
    460             'id': twid,
    461             'title': title,
    462             'description': description,
    463             'uploader': uploader,
    464             'timestamp': unified_timestamp(status.get('created_at')),
    465             'uploader_id': uploader_id,
    466             'uploader_url': 'https://twitter.com/' + uploader_id if uploader_id else None,
    467             'like_count': int_or_none(status.get('favorite_count')),
    468             'repost_count': int_or_none(status.get('retweet_count')),
    469             'comment_count': int_or_none(status.get('reply_count')),
    470             'age_limit': 18 if status.get('possibly_sensitive') else 0,
    471             'tags': tags,
    472         }
    473 
    474         def extract_from_video_info(media):
    475             video_info = media.get('video_info') or {}
    476 
    477             formats = []
    478             for variant in video_info.get('variants', []):
    479                 formats.extend(self._extract_variant_formats(variant, twid))
    480             self._sort_formats(formats)
    481 
    482             thumbnails = []
    483             media_url = media.get('media_url_https') or media.get('media_url')
    484             if media_url:
    485                 def add_thumbnail(name, size):
    486                     thumbnails.append({
    487                         'id': name,
    488                         'url': update_url_query(media_url, {'name': name}),
    489                         'width': int_or_none(size.get('w') or size.get('width')),
    490                         'height': int_or_none(size.get('h') or size.get('height')),
    491                     })
    492                 for name, size in media.get('sizes', {}).items():
    493                     add_thumbnail(name, size)
    494                 add_thumbnail('orig', media.get('original_info') or {})
    495 
    496             info.update({
    497                 'formats': formats,
    498                 'thumbnails': thumbnails,
    499                 'duration': float_or_none(video_info.get('duration_millis'), 1000),
    500             })
    501 
    502         media = try_get(status, lambda x: x['extended_entities']['media'][0])
    503         if media and media.get('type') != 'photo':
    504             extract_from_video_info(media)
    505         else:
    506             card = status.get('card')
    507             if card:
    508                 binding_values = card['binding_values']
    509 
    510                 def get_binding_value(k):
    511                     o = binding_values.get(k) or {}
    512                     return try_get(o, lambda x: x[x['type'].lower() + '_value'])
    513 
    514                 card_name = card['name'].split(':')[-1]
    515                 if card_name == 'player':
    516                     info.update({
    517                         '_type': 'url',
    518                         'url': get_binding_value('player_url'),
    519                     })
    520                 elif card_name == 'periscope_broadcast':
    521                     info.update({
    522                         '_type': 'url',
    523                         'url': get_binding_value('url') or get_binding_value('player_url'),
    524                         'ie_key': PeriscopeIE.ie_key(),
    525                     })
    526                 elif card_name == 'broadcast':
    527                     info.update({
    528                         '_type': 'url',
    529                         'url': get_binding_value('broadcast_url'),
    530                         'ie_key': TwitterBroadcastIE.ie_key(),
    531                     })
    532                 elif card_name == 'summary':
    533                     info.update({
    534                         '_type': 'url',
    535                         'url': get_binding_value('card_url'),
    536                     })
    537                 elif card_name == 'unified_card':
    538                     media_entities = self._parse_json(get_binding_value('unified_card'), twid)['media_entities']
    539                     extract_from_video_info(next(iter(media_entities.values())))
    540                 # amplify, promo_video_website, promo_video_convo, appplayer,
    541                 # video_direct_message, poll2choice_video, poll3choice_video,
    542                 # poll4choice_video, ...
    543                 else:
    544                     is_amplify = card_name == 'amplify'
    545                     vmap_url = get_binding_value('amplify_url_vmap') if is_amplify else get_binding_value('player_stream_url')
    546                     content_id = get_binding_value('%s_content_id' % (card_name if is_amplify else 'player'))
    547                     formats = self._extract_formats_from_vmap_url(vmap_url, content_id or twid)
    548                     self._sort_formats(formats)
    549 
    550                     thumbnails = []
    551                     for suffix in ('_small', '', '_large', '_x_large', '_original'):
    552                         image = get_binding_value('player_image' + suffix) or {}
    553                         image_url = image.get('url')
    554                         if not image_url or '/player-placeholder' in image_url:
    555                             continue
    556                         thumbnails.append({
    557                             'id': suffix[1:] if suffix else 'medium',
    558                             'url': image_url,
    559                             'width': int_or_none(image.get('width')),
    560                             'height': int_or_none(image.get('height')),
    561                         })
    562 
    563                     info.update({
    564                         'formats': formats,
    565                         'thumbnails': thumbnails,
    566                         'duration': int_or_none(get_binding_value(
    567                             'content_duration_seconds')),
    568                     })
    569             else:
    570                 expanded_url = try_get(status, lambda x: x['entities']['urls'][0]['expanded_url'])
    571                 if not expanded_url:
    572                     raise ExtractorError("There's no video in this tweet.")
    573                 info.update({
    574                     '_type': 'url',
    575                     'url': expanded_url,
    576                 })
    577         return info
    578 
    579 
    580 class TwitterAmplifyIE(TwitterBaseIE):
    581     IE_NAME = 'twitter:amplify'
    582     _VALID_URL = r'https?://amp\.twimg\.com/v/(?P<id>[0-9a-f\-]{36})'
    583 
    584     _TEST = {
    585         'url': 'https://amp.twimg.com/v/0ba0c3c7-0af3-4c0a-bed5-7efd1ffa2951',
    586         'md5': '7df102d0b9fd7066b86f3159f8e81bf6',
    587         'info_dict': {
    588             'id': '0ba0c3c7-0af3-4c0a-bed5-7efd1ffa2951',
    589             'ext': 'mp4',
    590             'title': 'Twitter Video',
    591             'thumbnail': 're:^https?://.*',
    592         },
    593     }
    594 
    595     def _real_extract(self, url):
    596         video_id = self._match_id(url)
    597         webpage = self._download_webpage(url, video_id)
    598 
    599         vmap_url = self._html_search_meta(
    600             'twitter:amplify:vmap', webpage, 'vmap url')
    601         formats = self._extract_formats_from_vmap_url(vmap_url, video_id)
    602 
    603         thumbnails = []
    604         thumbnail = self._html_search_meta(
    605             'twitter:image:src', webpage, 'thumbnail', fatal=False)
    606 
    607         def _find_dimension(target):
    608             w = int_or_none(self._html_search_meta(
    609                 'twitter:%s:width' % target, webpage, fatal=False))
    610             h = int_or_none(self._html_search_meta(
    611                 'twitter:%s:height' % target, webpage, fatal=False))
    612             return w, h
    613 
    614         if thumbnail:
    615             thumbnail_w, thumbnail_h = _find_dimension('image')
    616             thumbnails.append({
    617                 'url': thumbnail,
    618                 'width': thumbnail_w,
    619                 'height': thumbnail_h,
    620             })
    621 
    622         video_w, video_h = _find_dimension('player')
    623         formats[0].update({
    624             'width': video_w,
    625             'height': video_h,
    626         })
    627 
    628         return {
    629             'id': video_id,
    630             'title': 'Twitter Video',
    631             'formats': formats,
    632             'thumbnails': thumbnails,
    633         }
    634 
    635 
    636 class TwitterBroadcastIE(TwitterBaseIE, PeriscopeBaseIE):
    637     IE_NAME = 'twitter:broadcast'
    638     _VALID_URL = TwitterBaseIE._BASE_REGEX + r'i/broadcasts/(?P<id>[0-9a-zA-Z]{13})'
    639 
    640     _TEST = {
    641         # untitled Periscope video
    642         'url': 'https://twitter.com/i/broadcasts/1yNGaQLWpejGj',
    643         'info_dict': {
    644             'id': '1yNGaQLWpejGj',
    645             'ext': 'mp4',
    646             'title': 'Andrea May Sahouri - Periscope Broadcast',
    647             'uploader': 'Andrea May Sahouri',
    648             'uploader_id': '1PXEdBZWpGwKe',
    649         },
    650     }
    651 
    652     def _real_extract(self, url):
    653         broadcast_id = self._match_id(url)
    654         broadcast = self._call_api(
    655             'broadcasts/show.json', broadcast_id,
    656             {'ids': broadcast_id})['broadcasts'][broadcast_id]
    657         info = self._parse_broadcast_data(broadcast, broadcast_id)
    658         media_key = broadcast['media_key']
    659         source = self._call_api(
    660             'live_video_stream/status/' + media_key, media_key)['source']
    661         m3u8_url = source.get('noRedirectPlaybackUrl') or source['location']
    662         if '/live_video_stream/geoblocked/' in m3u8_url:
    663             self.raise_geo_restricted()
    664         m3u8_id = compat_parse_qs(compat_urllib_parse_urlparse(
    665             m3u8_url).query).get('type', [None])[0]
    666         state, width, height = self._extract_common_format_info(broadcast)
    667         info['formats'] = self._extract_pscp_m3u8_formats(
    668             m3u8_url, broadcast_id, m3u8_id, state, width, height)
    669         return info