]>
Raphaël G. Git Repositories - youtubedl/blob - youtube_dl/extractor/twitter.py 
   2  from  __future__ 
import  unicode_literals
   6  from  . common 
import  InfoExtractor
   7  from  .. compat 
import  compat_urlparse
  19  from  . periscope 
import  PeriscopeIE
  22  class  TwitterBaseIE ( InfoExtractor
):   23      def  _extract_formats_from_vmap_url ( self
,  vmap_url
,  video_id
):   24          vmap_data 
=  self
._ download
_ xml
( vmap_url
,  video_id
)   25          video_url 
=  xpath_text ( vmap_data
,  './/MediaFile' ). strip ()   26          if  determine_ext ( video_url
) ==  'm3u8' :   27              return  self
._ extract
_ m
3u8_ formats
(   28                  video_url
,  video_id
,  ext
= 'mp4' ,  m3u8_id
= 'hls' ,   29                  entry_protocol
= 'm3u8_native' )   35      def  _search_dimensions_in_video_url ( a_format
,  video_url
):   36          m 
=  re
. search ( r
'/(?P<width>\d+)x(?P<height>\d+)/' ,  video_url
)   39                  'width' :  int ( m
. group ( 'width' )),   40                  'height' :  int ( m
. group ( 'height' )),   44  class  TwitterCardIE ( TwitterBaseIE
):   45      IE_NAME 
=  'twitter:card'   46      _VALID_URL 
=  r
'https?://(?:www\.)?twitter\.com/i/(?P<path>cards/tfw/v1|videos(?:/tweet)?)/(?P<id>\d+)'   49              'url' :  'https://twitter.com/i/cards/tfw/v1/560070183650213889' ,   50              # MD5 checksums are different in different places   52                  'id' :  '560070183650213889' ,   54                  'title' :  'Twitter web player' ,   55                  'thumbnail' :  r
're:^https?://.*\.jpg$' ,   60              'url' :  'https://twitter.com/i/cards/tfw/v1/623160978427936768' ,   61              'md5' :  '7ee2a553b63d1bccba97fbed97d9e1c8' ,   63                  'id' :  '623160978427936768' ,   65                  'title' :  'Twitter web player' ,   66                  'thumbnail' :  r
're:^https?://.*(?:\bformat=|\.)jpg' ,   70              'url' :  'https://twitter.com/i/cards/tfw/v1/654001591733886977' ,   71              'md5' :  'b6d9683dd3f48e340ded81c0e917ad46' ,   75                  'title' :  'Ubuntu 11.10 Overview' ,   76                  'description' :  'md5:a831e97fa384863d6e26ce48d1c43376' ,   77                  'upload_date' :  '20111013' ,   78                  'uploader' :  'OMG! Ubuntu!' ,   79                  'uploader_id' :  'omgubuntu' ,   81              'add_ie' : [ 'Youtube' ],   84              'url' :  'https://twitter.com/i/cards/tfw/v1/665289828897005568' ,   85              'md5' :  '6dabeaca9e68cbb71c99c322a4b42a11' ,   89                  'upload_date' :  '20151113' ,   90                  'uploader_id' :  '1189339351084113920' ,   91                  'uploader' :  'ArsenalTerje' ,   92                  'title' :  'Vine by ArsenalTerje' ,   93                  'timestamp' :  1447451307 ,   97              'url' :  'https://twitter.com/i/videos/tweet/705235433198714880' ,   98              'md5' :  '884812a2adc8aaf6fe52b15ccbfa3b88' ,  100                  'id' :  '705235433198714880' ,  102                  'title' :  'Twitter web player' ,  103                  'thumbnail' :  r
're:^https?://.*' ,  106              'url' :  'https://twitter.com/i/videos/752274308186120192' ,  107              'only_matching' :  True ,  111      def  _parse_media_info ( self
,  media_info
,  video_id
):  113          for  media_variant 
in  media_info
. get ( 'variants' , []):  114              media_url 
=  media_variant
[ 'url' ]  115              if  media_url
. endswith ( '.m3u8' ):  116                  formats
. extend ( self
._ extract
_ m
3u8_ formats
( media_url
,  video_id
,  ext
= 'mp4' ,  m3u8_id
= 'hls' ))  117              elif  media_url
. endswith ( '.mpd' ):  118                  formats
. extend ( self
._ extract
_ mpd
_ formats
( media_url
,  video_id
,  mpd_id
= 'dash' ))  120                  tbr 
=  int_or_none ( dict_get ( media_variant
, ( 'bitRate' ,  'bitrate' )),  scale
= 1000 )  123                      'format_id' :  'http- %d '  %  tbr 
if  tbr 
else  'http' ,  126                  # Reported bitRate may be zero  127                  if not  a_format
[ 'tbr' ]:  130                  self
._ search
_ dimensions
_ in
_ video
_u rl
( a_format
,  media_url
)  132                  formats
. append ( a_format
)  135      def  _extract_mobile_formats ( self
,  username
,  video_id
):  136          webpage 
=  self
._ download
_ webpage
(  137              'https://mobile.twitter.com/ %s /status/ %s '  % ( username
,  video_id
),  138              video_id
,  'Downloading mobile webpage' ,  140                  # A recent mobile UA is necessary for `gt` cookie  141                  'User-Agent' :  'Mozilla/5.0 (Android 6.0.1; Mobile; rv:54.0) Gecko/54.0 Firefox/54.0' ,  143          main_script_url 
=  self
._ html
_ search
_ regex
(  144              r
'<script[^>]+src="([^"]+main\.[^"]+)"' ,  webpage
,  'main script URL' )  145          main_script 
=  self
._ download
_ webpage
(  146              main_script_url
,  video_id
,  'Downloading main script' )  147          bearer_token 
=  self
._ search
_ regex
(  148              r
'BEARER_TOKEN\s*:\s*"([^"]+)"' ,  149              main_script
,  'bearer token' )  150          # https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id  151          api_data 
=  self
._ download
_ json
(  152              'https://api.twitter.com/1.1/statuses/show/ %s .json'  %  video_id
,  153              video_id
,  'Downloading API data' ,  155                  'Authorization' :  'Bearer '  +  bearer_token
,  157          media_info 
=  try_get ( api_data
,  lambda  o
:  o
[ 'extended_entities' ][ 'media' ][ 0 ][ 'video_info' ])  or  {}  158          return  self
._ parse
_ media
_ info
( media_info
,  video_id
)  160      def  _real_extract ( self
,  url
):  161          path
,  video_id 
=  re
. search ( self
._ VALID
_U RL
,  url
). groups ()  168          if  path
. startswith ( 'cards/' ):  169              urls
. append ( 'https://twitter.com/i/videos/'  +  video_id
)  172              webpage 
=  self
._ download
_ webpage
( u
,  video_id
)  174              iframe_url 
=  self
._ html
_ search
_ regex
(  175                  r
'<iframe[^>]+src="((?:https?:)?//(?:www\.youtube\.com/embed/[^"]+|(?:www\.)?vine\.co/v/\w+/card))"' ,  176                  webpage
,  'video iframe' ,  default
= None )  178                  return  self
. url_result ( iframe_url
)  180              config 
=  self
._ parse
_ json
( self
._ html
_ search
_ regex
(  181                  r
'data-(?:player-)?config="([^"]+)"' ,  webpage
,  182                  'data player config' ,  default
= '{}' ),  185              if  config
. get ( 'source_type' ) ==  'vine' :  186                  return  self
. url_result ( config
[ 'player_url' ],  'Vine' )  188              periscope_url 
=  PeriscopeIE
._ extract
_u rl
( webpage
)  190                  return  self
. url_result ( periscope_url
,  PeriscopeIE
. ie_key ())  192              video_url 
=  config
. get ( 'video_url' )  or  config
. get ( 'playlist' , [{}])[ 0 ]. get ( 'source' )  195                  if  determine_ext ( video_url
) ==  'm3u8' :  196                      formats
. extend ( self
._ extract
_ m
3u8_ formats
( video_url
,  video_id
,  ext
= 'mp4' ,  m3u8_id
= 'hls' ))  202                      self
._ search
_ dimensions
_ in
_ video
_u rl
( f
,  video_url
)  206              vmap_url 
=  config
. get ( 'vmapUrl' )  or  config
. get ( 'vmap_url' )  209                      self
._ extract
_ formats
_ from
_ vmap
_u rl
( vmap_url
,  video_id
))  213              for  entity 
in  config
. get ( 'status' , {}). get ( 'entities' , []):  214                  if  'mediaInfo'  in  entity
:  215                      media_info 
=  entity
[ 'mediaInfo' ]  218                  formats
. extend ( self
._ parse
_ media
_ info
( media_info
,  video_id
))  219                  duration 
=  float_or_none ( media_info
. get ( 'duration' , {}). get ( 'nanos' ),  scale
= 1 e9
)  221              username 
=  config
. get ( 'user' , {}). get ( 'screen_name' )  223                  formats
. extend ( self
._ extract
_ mobile
_ formats
( username
,  video_id
))  228          self
._ remove
_ duplicate
_ formats
( formats
)  229          self
._ sort
_ formats
( formats
)  231          title 
=  self
._ search
_ regex
( r
'<title>([^<]+)</title>' ,  webpage
,  'title' )  232          thumbnail 
=  config
. get ( 'posterImageUrl' )  or  config
. get ( 'image_src' )  233          duration 
=  float_or_none ( config
. get ( 'duration' ),  scale
= 1000 )  or  duration
 238              'thumbnail' :  thumbnail
,  239              'duration' :  duration
,  244  class  TwitterIE ( InfoExtractor
):  246      _VALID_URL 
=  r
'https?://(?:www\.|m\.|mobile\.)?twitter\.com/(?:i/web|(?P<user_id>[^/]+))/status/(?P<id>\d+)'  247      _TEMPLATE_URL 
=  'https://twitter.com/ %s /status/ %s '  248      _TEMPLATE_STATUSES_URL 
=  'https://twitter.com/statuses/ %s '  251          'url' :  'https://twitter.com/freethenipple/status/643211948184596480' ,  253              'id' :  '643211948184596480' ,  255              'title' :  'FREE THE NIPPLE - FTN supporters on Hollywood Blvd today!' ,  256              'thumbnail' :  r
're:^https?://.*\.jpg' ,  257              'description' :  'FREE THE NIPPLE on Twitter: "FTN supporters on Hollywood Blvd today! http://t.co/c7jHH749xJ"' ,  258              'uploader' :  'FREE THE NIPPLE' ,  259              'uploader_id' :  'freethenipple' ,  263          'url' :  'https://twitter.com/giphz/status/657991469417025536/photo/1' ,  264          'md5' :  'f36dcd5fb92bf7057f155e7d927eeb42' ,  266              'id' :  '657991469417025536' ,  268              'title' :  'Gifs - tu vai cai tu vai cai tu nao eh capaz disso tu vai cai' ,  269              'description' :  'Gifs on Twitter: "tu vai cai tu vai cai tu nao eh capaz disso tu vai cai https://t.co/tM46VHFlO5"' ,  270              'thumbnail' :  r
're:^https?://.*\.png' ,  272              'uploader_id' :  'giphz' ,  274          'expected_warnings' : [ 'height' ,  'width' ],  275          'skip' :  'Account suspended' ,  277          'url' :  'https://twitter.com/starwars/status/665052190608723968' ,  279              'id' :  '665052190608723968' ,  281              'title' :  'Star Wars - A new beginning is coming December 18. Watch the official 60 second #TV spot for #StarWars: #TheForceAwakens.' ,  282              'description' :  'Star Wars on Twitter: "A new beginning is coming December 18. Watch the official 60 second #TV spot for #StarWars: #TheForceAwakens."' ,  283              'uploader_id' :  'starwars' ,  284              'uploader' :  'Star Wars' ,  287          'url' :  'https://twitter.com/BTNBrentYarina/status/705235433198714880' ,  289              'id' :  '705235433198714880' ,  291              'title' :  'Brent Yarina - Khalil Iverson \' s missed highlight dunk. And made highlight dunk. In one highlight.' ,  292              'description' :  'Brent Yarina on Twitter: "Khalil Iverson \' s missed highlight dunk. And made highlight dunk. In one highlight."' ,  293              'uploader_id' :  'BTNBrentYarina' ,  294              'uploader' :  'Brent Yarina' ,  297              # The same video as https://twitter.com/i/videos/tweet/705235433198714880  298              # Test case of TwitterCardIE  299              'skip_download' :  True ,  302          'url' :  'https://twitter.com/jaydingeer/status/700207533655363584' ,  304              'id' :  '700207533655363584' ,  306              'title' :  'JG - BEAT PROD: @suhmeduh #Damndaniel' ,  307              'description' :  'JG on Twitter: "BEAT PROD: @suhmeduh  https://t.co/HBrQ4AfpvZ #Damndaniel https://t.co/byBooq2ejZ"' ,  308              'thumbnail' :  r
're:^https?://.*\.jpg' ,  310              'uploader_id' :  'jaydingeer' ,  314          'url' :  'https://twitter.com/Filmdrunk/status/713801302971588609' ,  315          'md5' :  '89a15ed345d13b86e9a5a5e051fa308a' ,  319              'title' :  'Vince Mancini - Vine of the day' ,  320              'description' :  'Vince Mancini on Twitter: "Vine of the day https://t.co/xmTvRdqxWf"' ,  321              'uploader' :  'Vince Mancini' ,  322              'uploader_id' :  'Filmdrunk' ,  323              'timestamp' :  1402826626 ,  324              'upload_date' :  '20140615' ,  328          'url' :  'https://twitter.com/captainamerica/status/719944021058060289' ,  330              'id' :  '719944021058060289' ,  332              'title' :  'Captain America - @King0fNerd Are you sure you made the right choice? Find out in theaters.' ,  333              'description' :  'Captain America on Twitter: "@King0fNerd Are you sure you made the right choice? Find out in theaters. https://t.co/GpgYi9xMJI"' ,  334              'uploader_id' :  'captainamerica' ,  335              'uploader' :  'Captain America' ,  339          'url' :  'https://twitter.com/OPP_HSD/status/779210622571536384' ,  341              'id' :  '1zqKVVlkqLaKB' ,  343              'title' :  'Sgt Kerry Schmidt - LIVE on #Periscope: Road rage, mischief, assault, rollover and fire in one occurrence' ,  344              'description' :  'Sgt Kerry Schmidt on Twitter: "LIVE on #Periscope: Road rage, mischief, assault, rollover and fire in one occurrence  https://t.co/EKrVgIXF3s"' ,  345              'upload_date' :  '20160923' ,  346              'uploader_id' :  'OPP_HSD' ,  347              'uploader' :  'Sgt Kerry Schmidt' ,  348              'timestamp' :  1474613214 ,  350          'add_ie' : [ 'Periscope' ],  352          # has mp4 formats via mobile API  353          'url' :  'https://twitter.com/news_al3alm/status/852138619213144067' ,  355              'id' :  '852138619213144067' ,  357              'title' :  'عالم الأخبار - كلمة تاريخية بجلسة الجناسي التاريخية.. النائب خالد مؤنس العتيبي للمعارضين : اتقوا الله .. الظلم ظلمات يوم القيامة' ,  358              'description' :  'عالم الأخبار on Twitter: "كلمة تاريخية بجلسة الجناسي التاريخية.. النائب خالد مؤنس العتيبي للمعارضين : اتقوا الله .. الظلم ظلمات يوم القيامة   https://t.co/xg6OhpyKfN"' ,  359              'uploader' :  'عالم الأخبار' ,  360              'uploader_id' :  'news_al3alm' ,  364          'url' :  'https://twitter.com/i/web/status/910031516746514432' ,  366              'id' :  '910031516746514432' ,  368              '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.' ,  369              'thumbnail' :  r
're:^https?://.*\.jpg' ,  370              'description' :  'Préfet de Guadeloupe on Twitter: "[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"' ,  371              'uploader' :  'Préfet de Guadeloupe' ,  372              'uploader_id' :  'Prefet971' ,  376              'skip_download' :  True ,   # requires ffmpeg  380      def  _real_extract ( self
,  url
):  381          mobj 
=  re
. match ( self
._ VALID
_U RL
,  url
)  382          user_id 
=  mobj
. group ( 'user_id' )  383          twid 
=  mobj
. group ( 'id' )  385          webpage
,  urlh 
=  self
._ download
_ webpage
_ handle
(  386              self
._ TEMPLATE
_ STATUSES
_U RL 
%  twid
,  twid
)  388          if  'twitter.com/account/suspended'  in  urlh
. geturl ():  389              raise  ExtractorError ( 'Account suspended by Twitter.' ,  expected
= True )  392              mobj 
=  re
. match ( self
._ VALID
_U RL
,  urlh
. geturl ())  393              user_id 
=  mobj
. group ( 'user_id' )  395          username 
=  remove_end ( self
._ og
_ search
_ title
( webpage
),  ' on Twitter' )  397          title 
=  description 
=  self
._ og
_ search
_ description
( webpage
). strip ( '' ). replace ( ' \n ' ,  ' ' ). strip ( '“”' )  399          # strip  'https -_t.co_BJYgOjSeGA' junk from filenames  400          title 
=  re
. sub ( r
'\s+(https?://[^ ]+)' ,  '' ,  title
)  403              'uploader_id' :  user_id
,  404              'uploader' :  username
,  406              'description' :  ' %s  on Twitter: " %s "'  % ( username
,  description
),  407              'title' :  username 
+  ' - '  +  title
,  410          mobj 
=  re
. search ( r
'''(?x)  411              <video[^>]+class="animated-gif"(?P<more_info>[^>]+)>\s*  412                  <source[^>]+video-src="(?P<url>[^"]+)"  416              more_info 
=  mobj
. group ( 'more_info' )  417              height 
=  int_or_none ( self
._ search
_ regex
(  418                  r
'data-height="(\d+)"' ,  more_info
,  'height' ,  fatal
= False ))  419              width 
=  int_or_none ( self
._ search
_ regex
(  420                  r
'data-width="(\d+)"' ,  more_info
,  'width' ,  fatal
= False ))  421              thumbnail 
=  self
._ search
_ regex
(  422                  r
'poster="([^"]+)"' ,  more_info
,  'poster' ,  fatal
= False )  425                  'url' :  mobj
. group ( 'url' ),  428                  'thumbnail' :  thumbnail
,  432          twitter_card_url 
=  None  433          if  'class="PlayableMedia'  in  webpage
:  434              twitter_card_url 
=  ' %s //twitter.com/i/videos/tweet/ %s '  % ( self
. http_scheme (),  twid
)  436              twitter_card_iframe_url 
=  self
._ search
_ regex
(  437                  r
'data-full-card-iframe-url=([\' "])(?P<url>(?:(?!\1).)+)\1',  438                  webpage, 'Twitter card iframe URL', default=None, group='url')  439              if twitter_card_iframe_url:  440                  twitter_card_url = compat_urlparse.urljoin(url, twitter_card_iframe_url)  444                  '_type': 'url_transparent',  445                  'ie_key': 'TwitterCard',  446                  'url': twitter_card_url,  450          raise ExtractorError('There \' s no video in this tweet.')  453  class TwitterAmplifyIE(TwitterBaseIE):  454      IE_NAME = 'twitter:amplify'  455      _VALID_URL = r'https?://amp\.twimg\.com/v/(?P<id>[0-9a-f\-] {36} )'  458          'url': 'https://amp.twimg.com/v/0ba0c3c7-0af3-4c0a-bed5-7efd1ffa2951',  459          'md5': '7df102d0b9fd7066b86f3159f8e81bf6',  461              'id': '0ba0c3c7-0af3-4c0a-bed5-7efd1ffa2951',  463              'title': 'Twitter Video',  464              'thumbnail': 're:^https?://.*',  468      def _real_extract(self, url):  469          video_id = self._match_id(url)  470          webpage = self._download_webpage(url, video_id)  472          vmap_url = self._html_search_meta(  473              'twitter:amplify:vmap', webpage, 'vmap url')  474          formats = self._extract_formats_from_vmap_url(vmap_url, video_id)  477          thumbnail = self._html_search_meta(  478              'twitter:image:src', webpage, 'thumbnail', fatal=False)  480          def _find_dimension(target):  481              w = int_or_none(self._html_search_meta(  482                  'twitter: %s :width' % target, webpage, fatal=False))  483              h = int_or_none(self._html_search_meta(  484                  'twitter: %s :height' % target, webpage, fatal=False))  488              thumbnail_w, thumbnail_h = _find_dimension('image')  491                  'width': thumbnail_w,  492                  'height': thumbnail_h,  495          video_w, video_h = _find_dimension('player')  503              'title': 'Twitter Video',  505              'thumbnails': thumbnails,