twitter.py 19 KB

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