]>
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/(?: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 Card' ,
55 'thumbnail' : r
're:^https?://.*\.jpg$' ,
61 'url' : 'https://twitter.com/i/cards/tfw/v1/623160978427936768' ,
62 'md5' : '7ee2a553b63d1bccba97fbed97d9e1c8' ,
64 'id' : '623160978427936768' ,
66 'title' : 'Twitter Card' ,
67 'thumbnail' : r
're:^https?://.*\.jpg' ,
73 'url' : 'https://twitter.com/i/cards/tfw/v1/654001591733886977' ,
74 'md5' : 'b6d9683dd3f48e340ded81c0e917ad46' ,
78 'title' : 'Ubuntu 11.10 Overview' ,
79 'description' : 'md5:a831e97fa384863d6e26ce48d1c43376' ,
80 'upload_date' : '20111013' ,
81 'uploader' : 'OMG! Ubuntu!' ,
82 'uploader_id' : 'omgubuntu' ,
84 'add_ie' : [ 'Youtube' ],
87 'url' : 'https://twitter.com/i/cards/tfw/v1/665289828897005568' ,
88 'md5' : '6dabeaca9e68cbb71c99c322a4b42a11' ,
92 'upload_date' : '20151113' ,
93 'uploader_id' : '1189339351084113920' ,
94 'uploader' : 'ArsenalTerje' ,
95 'title' : 'Vine by ArsenalTerje' ,
96 'timestamp' : 1447451307 ,
100 'url' : 'https://twitter.com/i/videos/tweet/705235433198714880' ,
101 'md5' : '884812a2adc8aaf6fe52b15ccbfa3b88' ,
103 'id' : '705235433198714880' ,
105 'title' : 'Twitter web player' ,
106 'thumbnail' : r
're:^https?://.*' ,
109 'url' : 'https://twitter.com/i/videos/752274308186120192' ,
110 'only_matching' : True ,
114 def _parse_media_info ( self
, media_info
, video_id
):
116 for media_variant
in media_info
. get ( 'variants' , []):
117 media_url
= media_variant
[ 'url' ]
118 if media_url
. endswith ( '.m3u8' ):
119 formats
. extend ( self
._ extract
_ m
3u8_ formats
( media_url
, video_id
, ext
= 'mp4' , m3u8_id
= 'hls' ))
120 elif media_url
. endswith ( '.mpd' ):
121 formats
. extend ( self
._ extract
_ mpd
_ formats
( media_url
, video_id
, mpd_id
= 'dash' ))
123 vbr
= int_or_none ( dict_get ( media_variant
, ( 'bitRate' , 'bitrate' )), scale
= 1000 )
126 'format_id' : 'http- %d ' % vbr
if vbr
else 'http' ,
129 # Reported bitRate may be zero
130 if not a_format
[ 'vbr' ]:
133 self
._ search
_ dimensions
_ in
_ video
_u rl
( a_format
, media_url
)
135 formats
. append ( a_format
)
138 def _extract_mobile_formats ( self
, username
, video_id
):
139 webpage
= self
._ download
_ webpage
(
140 'https://mobile.twitter.com/ %s /status/ %s ' % ( username
, video_id
),
141 video_id
, 'Downloading mobile webpage' ,
143 # A recent mobile UA is necessary for `gt` cookie
144 'User-Agent' : 'Mozilla/5.0 (Android 6.0.1; Mobile; rv:54.0) Gecko/54.0 Firefox/54.0' ,
146 main_script_url
= self
._ html
_ search
_ regex
(
147 r
'<script[^>]+src="([^"]+main\.[^"]+)"' , webpage
, 'main script URL' )
148 main_script
= self
._ download
_ webpage
(
149 main_script_url
, video_id
, 'Downloading main script' )
150 bearer_token
= self
._ search
_ regex
(
151 r
'BEARER_TOKEN\s*:\s*"([^"]+)"' ,
152 main_script
, 'bearer token' )
153 guest_token
= self
._ search
_ regex
(
154 r
'document\.cookie\s*=\s*decodeURIComponent\("gt=(\d+)' ,
155 webpage
, 'guest token' )
156 api_data
= self
._ download
_ json
(
157 'https://api.twitter.com/2/timeline/conversation/ %s .json' % video_id
,
158 video_id
, 'Downloading mobile API data' ,
160 'Authorization' : 'Bearer ' + bearer_token
,
161 'x-guest-token' : guest_token
,
163 media_info
= try_get ( api_data
, lambda o
: o
[ 'globalObjects' ][ 'tweets' ][ video_id
]
164 [ 'extended_entities' ][ 'media' ][ 0 ][ 'video_info' ]) or {}
165 return self
._ parse
_ media
_ info
( media_info
, video_id
)
167 def _real_extract ( self
, url
):
168 video_id
= self
._ match
_ id
( url
)
174 webpage
= self
._ download
_ webpage
( url
, video_id
)
176 iframe_url
= self
._ html
_ search
_ regex
(
177 r
'<iframe[^>]+src="((?:https?:)?//(?:www\.youtube\.com/embed/[^"]+|(?:www\.)?vine\.co/v/\w+/card))"' ,
178 webpage
, 'video iframe' , default
= None )
180 return self
. url_result ( iframe_url
)
182 config
= self
._ parse
_ json
( self
._ html
_ search
_ regex
(
183 r
'data-(?:player-)?config="([^"]+)"' , webpage
,
184 'data player config' , default
= '{}' ),
187 if config
. get ( 'source_type' ) == 'vine' :
188 return self
. url_result ( config
[ 'player_url' ], 'Vine' )
190 periscope_url
= PeriscopeIE
._ extract
_u rl
( webpage
)
192 return self
. url_result ( periscope_url
, PeriscopeIE
. ie_key ())
194 video_url
= config
. get ( 'video_url' ) or config
. get ( 'playlist' , [{}])[ 0 ]. get ( 'source' )
197 if determine_ext ( video_url
) == 'm3u8' :
198 formats
. extend ( self
._ extract
_ m
3u8_ formats
( video_url
, video_id
, ext
= 'mp4' , m3u8_id
= 'hls' ))
204 self
._ search
_ dimensions
_ in
_ video
_u rl
( f
, video_url
)
208 vmap_url
= config
. get ( 'vmapUrl' ) or config
. get ( 'vmap_url' )
211 self
._ extract
_ formats
_ from
_ vmap
_u rl
( vmap_url
, video_id
))
215 for entity
in config
. get ( 'status' , {}). get ( 'entities' , []):
216 if 'mediaInfo' in entity
:
217 media_info
= entity
[ 'mediaInfo' ]
220 formats
. extend ( self
._ parse
_ media
_ info
( media_info
, video_id
))
221 duration
= float_or_none ( media_info
. get ( 'duration' , {}). get ( 'nanos' ), scale
= 1 e9
)
223 username
= config
. get ( 'user' , {}). get ( 'screen_name' )
225 formats
. extend ( self
._ extract
_ mobile
_ formats
( username
, video_id
))
227 self
._ remove
_ duplicate
_ formats
( formats
)
228 self
._ sort
_ formats
( formats
)
230 title
= self
._ search
_ regex
( r
'<title>([^<]+)</title>' , webpage
, 'title' )
231 thumbnail
= config
. get ( 'posterImageUrl' ) or config
. get ( 'image_src' )
232 duration
= float_or_none ( config
. get ( 'duration' ), scale
= 1000 ) or duration
237 'thumbnail' : thumbnail
,
238 'duration' : duration
,
243 class TwitterIE ( InfoExtractor
):
245 _VALID_URL
= r
'https?://(?:www\.|m\.|mobile\.)?twitter\.com/(?:i/web|(?P<user_id>[^/]+))/status/(?P<id>\d+)'
246 _TEMPLATE_URL
= 'https://twitter.com/ %s /status/ %s '
247 _TEMPLATE_STATUSES_URL
= 'https://twitter.com/statuses/ %s '
250 'url' : 'https://twitter.com/freethenipple/status/643211948184596480' ,
252 'id' : '643211948184596480' ,
254 'title' : 'FREE THE NIPPLE - FTN supporters on Hollywood Blvd today!' ,
255 'thumbnail' : r
're:^https?://.*\.jpg' ,
256 'description' : 'FREE THE NIPPLE on Twitter: "FTN supporters on Hollywood Blvd today! http://t.co/c7jHH749xJ"' ,
257 'uploader' : 'FREE THE NIPPLE' ,
258 'uploader_id' : 'freethenipple' ,
262 'skip_download' : True , # requires ffmpeg
265 'url' : 'https://twitter.com/giphz/status/657991469417025536/photo/1' ,
266 'md5' : 'f36dcd5fb92bf7057f155e7d927eeb42' ,
268 'id' : '657991469417025536' ,
270 'title' : 'Gifs - tu vai cai tu vai cai tu nao eh capaz disso tu vai cai' ,
271 'description' : 'Gifs on Twitter: "tu vai cai tu vai cai tu nao eh capaz disso tu vai cai https://t.co/tM46VHFlO5"' ,
272 'thumbnail' : r
're:^https?://.*\.png' ,
274 'uploader_id' : 'giphz' ,
276 'expected_warnings' : [ 'height' , 'width' ],
277 'skip' : 'Account suspended' ,
279 'url' : 'https://twitter.com/starwars/status/665052190608723968' ,
280 'md5' : '39b7199856dee6cd4432e72c74bc69d4' ,
282 'id' : '665052190608723968' ,
284 'title' : 'Star Wars - A new beginning is coming December 18. Watch the official 60 second #TV spot for #StarWars: #TheForceAwakens.' ,
285 'description' : 'Star Wars on Twitter: "A new beginning is coming December 18. Watch the official 60 second #TV spot for #StarWars: #TheForceAwakens."' ,
286 'uploader_id' : 'starwars' ,
287 'uploader' : 'Star Wars' ,
290 'url' : 'https://twitter.com/BTNBrentYarina/status/705235433198714880' ,
292 'id' : '705235433198714880' ,
294 'title' : 'Brent Yarina - Khalil Iverson \' s missed highlight dunk. And made highlight dunk. In one highlight.' ,
295 'description' : 'Brent Yarina on Twitter: "Khalil Iverson \' s missed highlight dunk. And made highlight dunk. In one highlight."' ,
296 'uploader_id' : 'BTNBrentYarina' ,
297 'uploader' : 'Brent Yarina' ,
300 # The same video as https://twitter.com/i/videos/tweet/705235433198714880
301 # Test case of TwitterCardIE
302 'skip_download' : True ,
305 'url' : 'https://twitter.com/jaydingeer/status/700207533655363584' ,
308 'id' : '700207533655363584' ,
310 'title' : 'あかさ - BEAT PROD: @suhmeduh #Damndaniel' ,
311 'description' : 'あかさ on Twitter: "BEAT PROD: @suhmeduh https://t.co/HBrQ4AfpvZ #Damndaniel https://t.co/byBooq2ejZ"' ,
312 'thumbnail' : r
're:^https?://.*\.jpg' ,
314 'uploader_id' : 'jaydingeer' ,
318 'skip_download' : True , # requires ffmpeg
321 'url' : 'https://twitter.com/Filmdrunk/status/713801302971588609' ,
322 'md5' : '89a15ed345d13b86e9a5a5e051fa308a' ,
326 'title' : 'Vince Mancini - Vine of the day' ,
327 'description' : 'Vince Mancini on Twitter: "Vine of the day https://t.co/xmTvRdqxWf"' ,
328 'uploader' : 'Vince Mancini' ,
329 'uploader_id' : 'Filmdrunk' ,
330 'timestamp' : 1402826626 ,
331 'upload_date' : '20140615' ,
335 'url' : 'https://twitter.com/captainamerica/status/719944021058060289' ,
337 'id' : '719944021058060289' ,
339 'title' : 'Captain America - @King0fNerd Are you sure you made the right choice? Find out in theaters.' ,
340 'description' : 'Captain America on Twitter: "@King0fNerd Are you sure you made the right choice? Find out in theaters. https://t.co/GpgYi9xMJI"' ,
341 'uploader_id' : 'captainamerica' ,
342 'uploader' : 'Captain America' ,
346 'skip_download' : True , # requires ffmpeg
349 'url' : 'https://twitter.com/OPP_HSD/status/779210622571536384' ,
351 'id' : '1zqKVVlkqLaKB' ,
353 'title' : 'Sgt Kerry Schmidt - LIVE on #Periscope: Road rage, mischief, assault, rollover and fire in one occurrence' ,
354 'description' : 'Sgt Kerry Schmidt on Twitter: "LIVE on #Periscope: Road rage, mischief, assault, rollover and fire in one occurrence https://t.co/EKrVgIXF3s"' ,
355 'upload_date' : '20160923' ,
356 'uploader_id' : 'OPP_HSD' ,
357 'uploader' : 'Sgt Kerry Schmidt' ,
358 'timestamp' : 1474613214 ,
360 'add_ie' : [ 'Periscope' ],
362 # has mp4 formats via mobile API
363 'url' : 'https://twitter.com/news_al3alm/status/852138619213144067' ,
365 'id' : '852138619213144067' ,
367 'title' : 'عالم الأخبار - كلمة تاريخية بجلسة الجناسي التاريخية.. النائب خالد مؤنس العتيبي للمعارضين : اتقوا الله .. الظلم ظلمات يوم القيامة' ,
368 'description' : 'عالم الأخبار on Twitter: "كلمة تاريخية بجلسة الجناسي التاريخية.. النائب خالد مؤنس العتيبي للمعارضين : اتقوا الله .. الظلم ظلمات يوم القيامة https://t.co/xg6OhpyKfN"' ,
369 'uploader' : 'عالم الأخبار' ,
370 'uploader_id' : 'news_al3alm' ,
374 'format' : 'best[format_id^=http-]' ,
377 'url' : 'https://twitter.com/i/web/status/910031516746514432' ,
379 'id' : '910031516746514432' ,
381 '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.' ,
382 'thumbnail' : r
're:^https?://.*\.jpg' ,
383 '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"' ,
384 'uploader' : 'Préfet de Guadeloupe' ,
385 'uploader_id' : 'Prefet971' ,
389 'skip_download' : True , # requires ffmpeg
393 def _real_extract ( self
, url
):
394 mobj
= re
. match ( self
._ VALID
_U RL
, url
)
395 user_id
= mobj
. group ( 'user_id' )
396 twid
= mobj
. group ( 'id' )
398 webpage
, urlh
= self
._ download
_ webpage
_ handle
(
399 self
._ TEMPLATE
_ STATUSES
_U RL
% twid
, twid
)
401 if 'twitter.com/account/suspended' in urlh
. geturl ():
402 raise ExtractorError ( 'Account suspended by Twitter.' , expected
= True )
405 mobj
= re
. match ( self
._ VALID
_U RL
, urlh
. geturl ())
406 user_id
= mobj
. group ( 'user_id' )
408 username
= remove_end ( self
._ og
_ search
_ title
( webpage
), ' on Twitter' )
410 title
= description
= self
._ og
_ search
_ description
( webpage
). strip ( '' ). replace ( ' \n ' , ' ' ). strip ( '“”' )
412 # strip 'https -_t.co_BJYgOjSeGA' junk from filenames
413 title
= re
. sub ( r
'\s+(https?://[^ ]+)' , '' , title
)
416 'uploader_id' : user_id
,
417 'uploader' : username
,
419 'description' : ' %s on Twitter: " %s "' % ( username
, description
),
420 'title' : username
+ ' - ' + title
,
423 mobj
= re
. search ( r
'''(?x)
424 <video[^>]+class="animated-gif"(?P<more_info>[^>]+)>\s*
425 <source[^>]+video-src="(?P<url>[^"]+)"
429 more_info
= mobj
. group ( 'more_info' )
430 height
= int_or_none ( self
._ search
_ regex
(
431 r
'data-height="(\d+)"' , more_info
, 'height' , fatal
= False ))
432 width
= int_or_none ( self
._ search
_ regex
(
433 r
'data-width="(\d+)"' , more_info
, 'width' , fatal
= False ))
434 thumbnail
= self
._ search
_ regex
(
435 r
'poster="([^"]+)"' , more_info
, 'poster' , fatal
= False )
438 'url' : mobj
. group ( 'url' ),
441 'thumbnail' : thumbnail
,
445 twitter_card_url
= None
446 if 'class="PlayableMedia' in webpage
:
447 twitter_card_url
= ' %s //twitter.com/i/videos/tweet/ %s ' % ( self
. http_scheme (), twid
)
449 twitter_card_iframe_url
= self
._ search
_ regex
(
450 r
'data-full-card-iframe-url=([\' "])(?P<url>(?:(?!\1).)+)\1',
451 webpage, 'Twitter card iframe URL', default=None, group='url')
452 if twitter_card_iframe_url:
453 twitter_card_url = compat_urlparse.urljoin(url, twitter_card_iframe_url)
457 '_type': 'url_transparent',
458 'ie_key': 'TwitterCard',
459 'url': twitter_card_url,
463 raise ExtractorError('There \' s no video in this tweet.')
466 class TwitterAmplifyIE(TwitterBaseIE):
467 IE_NAME = 'twitter:amplify'
468 _VALID_URL = r'https?://amp\.twimg\.com/v/(?P<id>[0-9a-f\-] {36} )'
471 'url': 'https://amp.twimg.com/v/0ba0c3c7-0af3-4c0a-bed5-7efd1ffa2951',
472 'md5': '7df102d0b9fd7066b86f3159f8e81bf6',
474 'id': '0ba0c3c7-0af3-4c0a-bed5-7efd1ffa2951',
476 'title': 'Twitter Video',
477 'thumbnail': 're:^https?://.*',
481 def _real_extract(self, url):
482 video_id = self._match_id(url)
483 webpage = self._download_webpage(url, video_id)
485 vmap_url = self._html_search_meta(
486 'twitter:amplify:vmap', webpage, 'vmap url')
487 formats = self._extract_formats_from_vmap_url(vmap_url, video_id)
490 thumbnail = self._html_search_meta(
491 'twitter:image:src', webpage, 'thumbnail', fatal=False)
493 def _find_dimension(target):
494 w = int_or_none(self._html_search_meta(
495 'twitter: %s :width' % target, webpage, fatal=False))
496 h = int_or_none(self._html_search_meta(
497 'twitter: %s :height' % target, webpage, fatal=False))
501 thumbnail_w, thumbnail_h = _find_dimension('image')
504 'width': thumbnail_w,
505 'height': thumbnail_h,
508 video_w, video_h = _find_dimension('player')
516 'title': 'Twitter Video',
518 'thumbnails': thumbnails,