twitter.py 19 KB

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