twitter.py 19 KB

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