twitter.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import re
  4. from .common import InfoExtractor
  5. from ..compat import compat_urlparse
  6. from ..utils import (
  7. determine_ext,
  8. dict_get,
  9. ExtractorError,
  10. float_or_none,
  11. int_or_none,
  12. remove_end,
  13. try_get,
  14. xpath_text,
  15. )
  16. from .periscope import PeriscopeIE
  17. class TwitterBaseIE(InfoExtractor):
  18. def _extract_formats_from_vmap_url(self, vmap_url, video_id):
  19. vmap_data = self._download_xml(vmap_url, video_id)
  20. video_url = xpath_text(vmap_data, './/MediaFile').strip()
  21. if determine_ext(video_url) == 'm3u8':
  22. return self._extract_m3u8_formats(
  23. video_url, video_id, ext='mp4', m3u8_id='hls',
  24. entry_protocol='m3u8_native')
  25. return [{
  26. 'url': video_url,
  27. }]
  28. @staticmethod
  29. def _search_dimensions_in_video_url(a_format, video_url):
  30. m = re.search(r'/(?P<width>\d+)x(?P<height>\d+)/', video_url)
  31. if m:
  32. a_format.update({
  33. 'width': int(m.group('width')),
  34. 'height': int(m.group('height')),
  35. })
  36. class TwitterCardIE(TwitterBaseIE):
  37. IE_NAME = 'twitter:card'
  38. _VALID_URL = r'https?://(?:www\.)?twitter\.com/i/(?:cards/tfw/v1|videos(?:/tweet)?)/(?P<id>\d+)'
  39. _TESTS = [
  40. {
  41. 'url': 'https://twitter.com/i/cards/tfw/v1/560070183650213889',
  42. # MD5 checksums are different in different places
  43. 'info_dict': {
  44. 'id': '560070183650213889',
  45. 'ext': 'mp4',
  46. 'title': 'Twitter Card',
  47. 'thumbnail': r're:^https?://.*\.jpg$',
  48. 'duration': 30.033,
  49. },
  50. 'skip': 'Video gone',
  51. },
  52. {
  53. 'url': 'https://twitter.com/i/cards/tfw/v1/623160978427936768',
  54. 'md5': '7ee2a553b63d1bccba97fbed97d9e1c8',
  55. 'info_dict': {
  56. 'id': '623160978427936768',
  57. 'ext': 'mp4',
  58. 'title': 'Twitter Card',
  59. 'thumbnail': r're:^https?://.*\.jpg',
  60. 'duration': 80.155,
  61. },
  62. 'skip': 'Video gone',
  63. },
  64. {
  65. 'url': 'https://twitter.com/i/cards/tfw/v1/654001591733886977',
  66. 'md5': 'b6d9683dd3f48e340ded81c0e917ad46',
  67. 'info_dict': {
  68. 'id': 'dq4Oj5quskI',
  69. 'ext': 'mp4',
  70. 'title': 'Ubuntu 11.10 Overview',
  71. 'description': 'md5:a831e97fa384863d6e26ce48d1c43376',
  72. 'upload_date': '20111013',
  73. 'uploader': 'OMG! Ubuntu!',
  74. 'uploader_id': 'omgubuntu',
  75. },
  76. 'add_ie': ['Youtube'],
  77. },
  78. {
  79. 'url': 'https://twitter.com/i/cards/tfw/v1/665289828897005568',
  80. 'md5': '6dabeaca9e68cbb71c99c322a4b42a11',
  81. 'info_dict': {
  82. 'id': 'iBb2x00UVlv',
  83. 'ext': 'mp4',
  84. 'upload_date': '20151113',
  85. 'uploader_id': '1189339351084113920',
  86. 'uploader': 'ArsenalTerje',
  87. 'title': 'Vine by ArsenalTerje',
  88. 'timestamp': 1447451307,
  89. },
  90. 'add_ie': ['Vine'],
  91. }, {
  92. 'url': 'https://twitter.com/i/videos/tweet/705235433198714880',
  93. 'md5': '884812a2adc8aaf6fe52b15ccbfa3b88',
  94. 'info_dict': {
  95. 'id': '705235433198714880',
  96. 'ext': 'mp4',
  97. 'title': 'Twitter web player',
  98. 'thumbnail': r're:^https?://.*',
  99. },
  100. }, {
  101. 'url': 'https://twitter.com/i/videos/752274308186120192',
  102. 'only_matching': True,
  103. },
  104. ]
  105. def _parse_media_info(self, media_info, video_id):
  106. formats = []
  107. for media_variant in media_info.get('variants', []):
  108. media_url = media_variant['url']
  109. if media_url.endswith('.m3u8'):
  110. formats.extend(self._extract_m3u8_formats(media_url, video_id, ext='mp4', m3u8_id='hls'))
  111. elif media_url.endswith('.mpd'):
  112. formats.extend(self._extract_mpd_formats(media_url, video_id, mpd_id='dash'))
  113. else:
  114. vbr = int_or_none(dict_get(media_variant, ('bitRate', 'bitrate')), scale=1000)
  115. a_format = {
  116. 'url': media_url,
  117. 'format_id': 'http-%d' % vbr if vbr else 'http',
  118. 'vbr': vbr,
  119. }
  120. # Reported bitRate may be zero
  121. if not a_format['vbr']:
  122. del a_format['vbr']
  123. self._search_dimensions_in_video_url(a_format, media_url)
  124. formats.append(a_format)
  125. return formats
  126. def _extract_mobile_formats(self, username, video_id):
  127. webpage = self._download_webpage(
  128. 'https://mobile.twitter.com/%s/status/%s' % (username, video_id),
  129. video_id, 'Downloading mobile webpage',
  130. headers={
  131. # A recent mobile UA is necessary for `gt` cookie
  132. 'User-Agent': 'Mozilla/5.0 (Android 6.0.1; Mobile; rv:54.0) Gecko/54.0 Firefox/54.0',
  133. })
  134. main_script_url = self._html_search_regex(
  135. r'<script[^>]+src="([^"]+main\.[^"]+)"', webpage, 'main script URL')
  136. main_script = self._download_webpage(
  137. main_script_url, video_id, 'Downloading main script')
  138. bearer_token = self._search_regex(
  139. r'BEARER_TOKEN\s*:\s*"([^"]+)"',
  140. main_script, 'bearer token')
  141. guest_token = self._search_regex(
  142. r'document\.cookie\s*=\s*decodeURIComponent\("gt=(\d+)',
  143. webpage, 'guest token')
  144. api_data = self._download_json(
  145. 'https://api.twitter.com/2/timeline/conversation/%s.json' % video_id,
  146. video_id, 'Downloading mobile API data',
  147. headers={
  148. 'Authorization': 'Bearer ' + bearer_token,
  149. 'x-guest-token': guest_token,
  150. })
  151. media_info = try_get(api_data, lambda o: o['globalObjects']['tweets'][video_id]
  152. ['extended_entities']['media'][0]['video_info']) or {}
  153. return self._parse_media_info(media_info, video_id)
  154. def _real_extract(self, url):
  155. video_id = self._match_id(url)
  156. config = None
  157. formats = []
  158. duration = None
  159. webpage = self._download_webpage(url, video_id)
  160. iframe_url = self._html_search_regex(
  161. r'<iframe[^>]+src="((?:https?:)?//(?:www.youtube.com/embed/[^"]+|(?:www\.)?vine\.co/v/\w+/card))"',
  162. webpage, 'video iframe', default=None)
  163. if iframe_url:
  164. return self.url_result(iframe_url)
  165. config = self._parse_json(self._html_search_regex(
  166. r'data-(?:player-)?config="([^"]+)"', webpage,
  167. 'data player config', default='{}'),
  168. video_id)
  169. if config.get('source_type') == 'vine':
  170. return self.url_result(config['player_url'], 'Vine')
  171. periscope_url = PeriscopeIE._extract_url(webpage)
  172. if periscope_url:
  173. return self.url_result(periscope_url, PeriscopeIE.ie_key())
  174. video_url = config.get('video_url') or config.get('playlist', [{}])[0].get('source')
  175. if video_url:
  176. if determine_ext(video_url) == 'm3u8':
  177. formats.extend(self._extract_m3u8_formats(video_url, video_id, ext='mp4', m3u8_id='hls'))
  178. else:
  179. f = {
  180. 'url': video_url,
  181. }
  182. self._search_dimensions_in_video_url(f, video_url)
  183. formats.append(f)
  184. vmap_url = config.get('vmapUrl') or config.get('vmap_url')
  185. if vmap_url:
  186. formats.extend(
  187. self._extract_formats_from_vmap_url(vmap_url, video_id))
  188. media_info = None
  189. for entity in config.get('status', {}).get('entities', []):
  190. if 'mediaInfo' in entity:
  191. media_info = entity['mediaInfo']
  192. if media_info:
  193. formats.extend(self._parse_media_info(media_info, video_id))
  194. duration = float_or_none(media_info.get('duration', {}).get('nanos'), scale=1e9)
  195. username = config.get('user', {}).get('screen_name')
  196. if username:
  197. formats.extend(self._extract_mobile_formats(username, video_id))
  198. self._remove_duplicate_formats(formats)
  199. self._sort_formats(formats)
  200. title = self._search_regex(r'<title>([^<]+)</title>', webpage, 'title')
  201. thumbnail = config.get('posterImageUrl') or config.get('image_src')
  202. duration = float_or_none(config.get('duration'), scale=1000) or duration
  203. return {
  204. 'id': video_id,
  205. 'title': title,
  206. 'thumbnail': thumbnail,
  207. 'duration': duration,
  208. 'formats': formats,
  209. }
  210. class TwitterIE(InfoExtractor):
  211. IE_NAME = 'twitter'
  212. _VALID_URL = r'https?://(?:www\.|m\.|mobile\.)?twitter\.com/(?P<user_id>[^/]+)/status/(?P<id>\d+)'
  213. _TEMPLATE_URL = 'https://twitter.com/%s/status/%s'
  214. _TESTS = [{
  215. 'url': 'https://twitter.com/freethenipple/status/643211948184596480',
  216. 'info_dict': {
  217. 'id': '643211948184596480',
  218. 'ext': 'mp4',
  219. 'title': 'FREE THE NIPPLE - FTN supporters on Hollywood Blvd today!',
  220. 'thumbnail': r're:^https?://.*\.jpg',
  221. 'description': 'FREE THE NIPPLE on Twitter: "FTN supporters on Hollywood Blvd today! http://t.co/c7jHH749xJ"',
  222. 'uploader': 'FREE THE NIPPLE',
  223. 'uploader_id': 'freethenipple',
  224. 'duration': 12.922,
  225. },
  226. 'params': {
  227. 'skip_download': True, # requires ffmpeg
  228. },
  229. }, {
  230. 'url': 'https://twitter.com/giphz/status/657991469417025536/photo/1',
  231. 'md5': 'f36dcd5fb92bf7057f155e7d927eeb42',
  232. 'info_dict': {
  233. 'id': '657991469417025536',
  234. 'ext': 'mp4',
  235. 'title': 'Gifs - tu vai cai tu vai cai tu nao eh capaz disso tu vai cai',
  236. 'description': 'Gifs on Twitter: "tu vai cai tu vai cai tu nao eh capaz disso tu vai cai https://t.co/tM46VHFlO5"',
  237. 'thumbnail': r're:^https?://.*\.png',
  238. 'uploader': 'Gifs',
  239. 'uploader_id': 'giphz',
  240. },
  241. 'expected_warnings': ['height', 'width'],
  242. 'skip': 'Account suspended',
  243. }, {
  244. 'url': 'https://twitter.com/starwars/status/665052190608723968',
  245. 'md5': '39b7199856dee6cd4432e72c74bc69d4',
  246. 'info_dict': {
  247. 'id': '665052190608723968',
  248. 'ext': 'mp4',
  249. 'title': 'Star Wars - A new beginning is coming December 18. Watch the official 60 second #TV spot for #StarWars: #TheForceAwakens.',
  250. 'description': 'Star Wars on Twitter: "A new beginning is coming December 18. Watch the official 60 second #TV spot for #StarWars: #TheForceAwakens."',
  251. 'uploader_id': 'starwars',
  252. 'uploader': 'Star Wars',
  253. },
  254. }, {
  255. 'url': 'https://twitter.com/BTNBrentYarina/status/705235433198714880',
  256. 'info_dict': {
  257. 'id': '705235433198714880',
  258. 'ext': 'mp4',
  259. 'title': 'Brent Yarina - Khalil Iverson\'s missed highlight dunk. And made highlight dunk. In one highlight.',
  260. 'description': 'Brent Yarina on Twitter: "Khalil Iverson\'s missed highlight dunk. And made highlight dunk. In one highlight."',
  261. 'uploader_id': 'BTNBrentYarina',
  262. 'uploader': 'Brent Yarina',
  263. },
  264. 'params': {
  265. # The same video as https://twitter.com/i/videos/tweet/705235433198714880
  266. # Test case of TwitterCardIE
  267. 'skip_download': True,
  268. },
  269. }, {
  270. 'url': 'https://twitter.com/jaydingeer/status/700207533655363584',
  271. 'md5': '',
  272. 'info_dict': {
  273. 'id': '700207533655363584',
  274. 'ext': 'mp4',
  275. 'title': 'あかさ - BEAT PROD: @suhmeduh #Damndaniel',
  276. 'description': 'あかさ on Twitter: "BEAT PROD: @suhmeduh https://t.co/HBrQ4AfpvZ #Damndaniel https://t.co/byBooq2ejZ"',
  277. 'thumbnail': r're:^https?://.*\.jpg',
  278. 'uploader': 'あかさ',
  279. 'uploader_id': 'jaydingeer',
  280. 'duration': 30.0,
  281. },
  282. 'params': {
  283. 'skip_download': True, # requires ffmpeg
  284. },
  285. }, {
  286. 'url': 'https://twitter.com/Filmdrunk/status/713801302971588609',
  287. 'md5': '89a15ed345d13b86e9a5a5e051fa308a',
  288. 'info_dict': {
  289. 'id': 'MIOxnrUteUd',
  290. 'ext': 'mp4',
  291. 'title': 'FilmDrunk - Vine of the day',
  292. 'description': 'FilmDrunk on Twitter: "Vine of the day https://t.co/xmTvRdqxWf"',
  293. 'uploader': 'FilmDrunk',
  294. 'uploader_id': 'Filmdrunk',
  295. 'timestamp': 1402826626,
  296. 'upload_date': '20140615',
  297. },
  298. 'add_ie': ['Vine'],
  299. }, {
  300. 'url': 'https://twitter.com/captainamerica/status/719944021058060289',
  301. 'info_dict': {
  302. 'id': '719944021058060289',
  303. 'ext': 'mp4',
  304. 'title': 'Captain America - @King0fNerd Are you sure you made the right choice? Find out in theaters.',
  305. 'description': 'Captain America on Twitter: "@King0fNerd Are you sure you made the right choice? Find out in theaters. https://t.co/GpgYi9xMJI"',
  306. 'uploader_id': 'captainamerica',
  307. 'uploader': 'Captain America',
  308. 'duration': 3.17,
  309. },
  310. 'params': {
  311. 'skip_download': True, # requires ffmpeg
  312. },
  313. }, {
  314. 'url': 'https://twitter.com/OPP_HSD/status/779210622571536384',
  315. 'info_dict': {
  316. 'id': '1zqKVVlkqLaKB',
  317. 'ext': 'mp4',
  318. 'title': 'Sgt Kerry Schmidt - LIVE on #Periscope: Road rage, mischief, assault, rollover and fire in one occurrence',
  319. 'description': 'Sgt Kerry Schmidt on Twitter: "LIVE on #Periscope: Road rage, mischief, assault, rollover and fire in one occurrence https://t.co/EKrVgIXF3s"',
  320. 'upload_date': '20160923',
  321. 'uploader_id': 'OPP_HSD',
  322. 'uploader': 'Sgt Kerry Schmidt',
  323. 'timestamp': 1474613214,
  324. },
  325. 'add_ie': ['Periscope'],
  326. }, {
  327. # has mp4 formats via mobile API
  328. 'url': 'https://twitter.com/news_al3alm/status/852138619213144067',
  329. 'info_dict': {
  330. 'id': '852138619213144067',
  331. 'ext': 'mp4',
  332. 'title': 'عالم الأخبار - كلمة تاريخية بجلسة الجناسي التاريخية.. النائب خالد مؤنس العتيبي للمعارضين : اتقوا الله .. الظلم ظلمات يوم القيامة',
  333. 'description': 'عالم الأخبار on Twitter: "كلمة تاريخية بجلسة الجناسي التاريخية.. النائب خالد مؤنس العتيبي للمعارضين : اتقوا الله .. الظلم ظلمات يوم القيامة https://t.co/xg6OhpyKfN"',
  334. 'uploader': 'عالم الأخبار',
  335. 'uploader_id': 'news_al3alm',
  336. 'duration': 277.4,
  337. },
  338. 'params': {
  339. 'format': 'best[format_id^=http-]',
  340. },
  341. }]
  342. def _real_extract(self, url):
  343. mobj = re.match(self._VALID_URL, url)
  344. user_id = mobj.group('user_id')
  345. twid = mobj.group('id')
  346. webpage, urlh = self._download_webpage_handle(
  347. self._TEMPLATE_URL % (user_id, twid), twid)
  348. if 'twitter.com/account/suspended' in urlh.geturl():
  349. raise ExtractorError('Account suspended by Twitter.', expected=True)
  350. username = remove_end(self._og_search_title(webpage), ' on Twitter')
  351. title = description = self._og_search_description(webpage).strip('').replace('\n', ' ').strip('“”')
  352. # strip 'https -_t.co_BJYgOjSeGA' junk from filenames
  353. title = re.sub(r'\s+(https?://[^ ]+)', '', title)
  354. info = {
  355. 'uploader_id': user_id,
  356. 'uploader': username,
  357. 'webpage_url': url,
  358. 'description': '%s on Twitter: "%s"' % (username, description),
  359. 'title': username + ' - ' + title,
  360. }
  361. mobj = re.search(r'''(?x)
  362. <video[^>]+class="animated-gif"(?P<more_info>[^>]+)>\s*
  363. <source[^>]+video-src="(?P<url>[^"]+)"
  364. ''', webpage)
  365. if mobj:
  366. more_info = mobj.group('more_info')
  367. height = int_or_none(self._search_regex(
  368. r'data-height="(\d+)"', more_info, 'height', fatal=False))
  369. width = int_or_none(self._search_regex(
  370. r'data-width="(\d+)"', more_info, 'width', fatal=False))
  371. thumbnail = self._search_regex(
  372. r'poster="([^"]+)"', more_info, 'poster', fatal=False)
  373. info.update({
  374. 'id': twid,
  375. 'url': mobj.group('url'),
  376. 'height': height,
  377. 'width': width,
  378. 'thumbnail': thumbnail,
  379. })
  380. return info
  381. twitter_card_url = None
  382. if 'class="PlayableMedia' in webpage:
  383. twitter_card_url = '%s//twitter.com/i/videos/tweet/%s' % (self.http_scheme(), twid)
  384. else:
  385. twitter_card_iframe_url = self._search_regex(
  386. r'data-full-card-iframe-url=([\'"])(?P<url>(?:(?!\1).)+)\1',
  387. webpage, 'Twitter card iframe URL', default=None, group='url')
  388. if twitter_card_iframe_url:
  389. twitter_card_url = compat_urlparse.urljoin(url, twitter_card_iframe_url)
  390. if twitter_card_url:
  391. info.update({
  392. '_type': 'url_transparent',
  393. 'ie_key': 'TwitterCard',
  394. 'url': twitter_card_url,
  395. })
  396. return info
  397. raise ExtractorError('There\'s no video in this tweet.')
  398. class TwitterAmplifyIE(TwitterBaseIE):
  399. IE_NAME = 'twitter:amplify'
  400. _VALID_URL = r'https?://amp\.twimg\.com/v/(?P<id>[0-9a-f\-]{36})'
  401. _TEST = {
  402. 'url': 'https://amp.twimg.com/v/0ba0c3c7-0af3-4c0a-bed5-7efd1ffa2951',
  403. 'md5': '7df102d0b9fd7066b86f3159f8e81bf6',
  404. 'info_dict': {
  405. 'id': '0ba0c3c7-0af3-4c0a-bed5-7efd1ffa2951',
  406. 'ext': 'mp4',
  407. 'title': 'Twitter Video',
  408. 'thumbnail': 're:^https?://.*',
  409. },
  410. }
  411. def _real_extract(self, url):
  412. video_id = self._match_id(url)
  413. webpage = self._download_webpage(url, video_id)
  414. vmap_url = self._html_search_meta(
  415. 'twitter:amplify:vmap', webpage, 'vmap url')
  416. formats = self._extract_formats_from_vmap_url(vmap_url, video_id)
  417. thumbnails = []
  418. thumbnail = self._html_search_meta(
  419. 'twitter:image:src', webpage, 'thumbnail', fatal=False)
  420. def _find_dimension(target):
  421. w = int_or_none(self._html_search_meta(
  422. 'twitter:%s:width' % target, webpage, fatal=False))
  423. h = int_or_none(self._html_search_meta(
  424. 'twitter:%s:height' % target, webpage, fatal=False))
  425. return w, h
  426. if thumbnail:
  427. thumbnail_w, thumbnail_h = _find_dimension('image')
  428. thumbnails.append({
  429. 'url': thumbnail,
  430. 'width': thumbnail_w,
  431. 'height': thumbnail_h,
  432. })
  433. video_w, video_h = _find_dimension('player')
  434. formats[0].update({
  435. 'width': video_w,
  436. 'height': video_h,
  437. })
  438. return {
  439. 'id': video_id,
  440. 'title': 'Twitter Video',
  441. 'formats': formats,
  442. 'thumbnails': thumbnails,
  443. }