twitter.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import re
  4. from .common import InfoExtractor
  5. from ..utils import (
  6. float_or_none,
  7. xpath_text,
  8. remove_end,
  9. int_or_none,
  10. ExtractorError,
  11. )
  12. class TwitterBaseIE(InfoExtractor):
  13. def _get_vmap_video_url(self, vmap_url, video_id):
  14. vmap_data = self._download_xml(vmap_url, video_id)
  15. return xpath_text(vmap_data, './/MediaFile').strip()
  16. class TwitterCardIE(TwitterBaseIE):
  17. IE_NAME = 'twitter:card'
  18. _VALID_URL = r'https?://(?:www\.)?twitter\.com/i/(?:cards/tfw/v1|videos/tweet)/(?P<id>\d+)'
  19. _TESTS = [
  20. {
  21. 'url': 'https://twitter.com/i/cards/tfw/v1/560070183650213889',
  22. # MD5 checksums are different in different places
  23. 'info_dict': {
  24. 'id': '560070183650213889',
  25. 'ext': 'mp4',
  26. 'title': 'Twitter Card',
  27. 'thumbnail': 're:^https?://.*\.jpg$',
  28. 'duration': 30.033,
  29. }
  30. },
  31. {
  32. 'url': 'https://twitter.com/i/cards/tfw/v1/623160978427936768',
  33. 'md5': '7ee2a553b63d1bccba97fbed97d9e1c8',
  34. 'info_dict': {
  35. 'id': '623160978427936768',
  36. 'ext': 'mp4',
  37. 'title': 'Twitter Card',
  38. 'thumbnail': 're:^https?://.*\.jpg',
  39. 'duration': 80.155,
  40. },
  41. },
  42. {
  43. 'url': 'https://twitter.com/i/cards/tfw/v1/654001591733886977',
  44. 'md5': 'd4724ffe6d2437886d004fa5de1043b3',
  45. 'info_dict': {
  46. 'id': 'dq4Oj5quskI',
  47. 'ext': 'mp4',
  48. 'title': 'Ubuntu 11.10 Overview',
  49. 'description': 'Take a quick peek at what\'s new and improved in Ubuntu 11.10.\n\nOnce installed take a look at 10 Things to Do After Installing: http://www.omgubuntu.co.uk/2011/10/10-things-to-do-after-installing-ubuntu-11-10/',
  50. 'upload_date': '20111013',
  51. 'uploader': 'OMG! Ubuntu!',
  52. 'uploader_id': 'omgubuntu',
  53. },
  54. 'add_ie': ['Youtube'],
  55. },
  56. {
  57. 'url': 'https://twitter.com/i/cards/tfw/v1/665289828897005568',
  58. 'md5': 'ab2745d0b0ce53319a534fccaa986439',
  59. 'info_dict': {
  60. 'id': 'iBb2x00UVlv',
  61. 'ext': 'mp4',
  62. 'upload_date': '20151113',
  63. 'uploader_id': '1189339351084113920',
  64. 'uploader': 'ArsenalTerje',
  65. 'title': 'Vine by ArsenalTerje',
  66. },
  67. 'add_ie': ['Vine'],
  68. }, {
  69. 'url': 'https://twitter.com/i/videos/tweet/705235433198714880',
  70. 'md5': '3846d0a07109b5ab622425449b59049d',
  71. 'info_dict': {
  72. 'id': '705235433198714880',
  73. 'ext': 'mp4',
  74. 'title': 'Twitter web player',
  75. 'thumbnail': 're:^https?://.*\.jpg',
  76. },
  77. },
  78. ]
  79. def _real_extract(self, url):
  80. video_id = self._match_id(url)
  81. config = None
  82. formats = []
  83. duration = None
  84. webpage = self._download_webpage(url, video_id)
  85. iframe_url = self._html_search_regex(
  86. r'<iframe[^>]+src="((?:https?:)?//(?:www.youtube.com/embed/[^"]+|(?:www\.)?vine\.co/v/\w+/card))"',
  87. webpage, 'video iframe', default=None)
  88. if iframe_url:
  89. return self.url_result(iframe_url)
  90. config = self._parse_json(self._html_search_regex(
  91. r'data-(?:player-)?config="([^"]+)"', webpage, 'data player config'),
  92. video_id)
  93. playlist = config.get('playlist')
  94. if playlist:
  95. video_url = playlist[0]['source']
  96. f = {
  97. 'url': video_url,
  98. }
  99. m = re.search(r'/(?P<width>\d+)x(?P<height>\d+)/', video_url)
  100. if m:
  101. f.update({
  102. 'width': int(m.group('width')),
  103. 'height': int(m.group('height')),
  104. })
  105. formats.append(f)
  106. vmap_url = config.get('vmapUrl') or config.get('vmap_url')
  107. if vmap_url:
  108. formats.append({
  109. 'url': self._get_vmap_video_url(vmap_url, video_id),
  110. })
  111. media_info = config.get('status', {}).get('entities', [{}])[0].get('mediaInfo', {})
  112. if media_info:
  113. for media_variant in media_info['variants']:
  114. media_url = media_variant['url']
  115. if media_url.endswith('.m3u8'):
  116. formats.extend(self._extract_m3u8_formats(media_url, video_id, ext='mp4', m3u8_id='hls'))
  117. elif media_url.endswith('.mpd'):
  118. formats.extend(self._extract_mpd_formats(media_url, video_id, mpd_id='dash'))
  119. else:
  120. vbr = int_or_none(media_variant.get('bitRate'), scale=1000)
  121. a_format = {
  122. 'url': media_url,
  123. 'format_id': 'http-%d' % vbr if vbr else 'http',
  124. 'vbr': vbr,
  125. }
  126. # Reported bitRate may be zero
  127. if not a_format['vbr']:
  128. del a_format['vbr']
  129. formats.append(a_format)
  130. duration = float_or_none(media_info.get('duration', {}).get('nanos'), scale=1e9)
  131. self._sort_formats(formats)
  132. title = self._search_regex(r'<title>([^<]+)</title>', webpage, 'title')
  133. thumbnail = config.get('posterImageUrl') or config.get('image_src')
  134. duration = float_or_none(config.get('duration')) or duration
  135. return {
  136. 'id': video_id,
  137. 'title': title,
  138. 'thumbnail': thumbnail,
  139. 'duration': duration,
  140. 'formats': formats,
  141. }
  142. class TwitterIE(InfoExtractor):
  143. IE_NAME = 'twitter'
  144. _VALID_URL = r'https?://(?:www\.|m\.|mobile\.)?twitter\.com/(?P<user_id>[^/]+)/status/(?P<id>\d+)'
  145. _TEMPLATE_URL = 'https://twitter.com/%s/status/%s'
  146. _TESTS = [{
  147. 'url': 'https://twitter.com/freethenipple/status/643211948184596480',
  148. 'info_dict': {
  149. 'id': '643211948184596480',
  150. 'ext': 'mp4',
  151. 'title': 'FREE THE NIPPLE - FTN supporters on Hollywood Blvd today!',
  152. 'thumbnail': 're:^https?://.*\.jpg',
  153. 'duration': 12.922,
  154. 'description': 'FREE THE NIPPLE on Twitter: "FTN supporters on Hollywood Blvd today! http://t.co/c7jHH749xJ"',
  155. 'uploader': 'FREE THE NIPPLE',
  156. 'uploader_id': 'freethenipple',
  157. },
  158. 'params': {
  159. 'skip_download': True, # requires ffmpeg
  160. },
  161. }, {
  162. 'url': 'https://twitter.com/giphz/status/657991469417025536/photo/1',
  163. 'md5': 'f36dcd5fb92bf7057f155e7d927eeb42',
  164. 'info_dict': {
  165. 'id': '657991469417025536',
  166. 'ext': 'mp4',
  167. 'title': 'Gifs - tu vai cai tu vai cai tu nao eh capaz disso tu vai cai',
  168. 'description': 'Gifs on Twitter: "tu vai cai tu vai cai tu nao eh capaz disso tu vai cai https://t.co/tM46VHFlO5"',
  169. 'thumbnail': 're:^https?://.*\.png',
  170. 'uploader': 'Gifs',
  171. 'uploader_id': 'giphz',
  172. },
  173. 'expected_warnings': ['height', 'width'],
  174. }, {
  175. 'url': 'https://twitter.com/starwars/status/665052190608723968',
  176. 'md5': '39b7199856dee6cd4432e72c74bc69d4',
  177. 'info_dict': {
  178. 'id': '665052190608723968',
  179. 'ext': 'mp4',
  180. 'title': 'Star Wars - A new beginning is coming December 18. Watch the official 60 second #TV spot for #StarWars: #TheForceAwakens.',
  181. 'description': 'Star Wars on Twitter: "A new beginning is coming December 18. Watch the official 60 second #TV spot for #StarWars: #TheForceAwakens."',
  182. 'uploader_id': 'starwars',
  183. 'uploader': 'Star Wars',
  184. },
  185. }, {
  186. 'url': 'https://twitter.com/BTNBrentYarina/status/705235433198714880',
  187. 'info_dict': {
  188. 'id': '705235433198714880',
  189. 'ext': 'mp4',
  190. 'title': 'Brent Yarina - Khalil Iverson\'s missed highlight dunk. And made highlight dunk. In one highlight.',
  191. 'description': 'Brent Yarina on Twitter: "Khalil Iverson\'s missed highlight dunk. And made highlight dunk. In one highlight."',
  192. 'uploader_id': 'BTNBrentYarina',
  193. 'uploader': 'Brent Yarina',
  194. },
  195. 'params': {
  196. # The same video as https://twitter.com/i/videos/tweet/705235433198714880
  197. # Test case of TwitterCardIE
  198. 'skip_download': True,
  199. },
  200. }]
  201. def _real_extract(self, url):
  202. mobj = re.match(self._VALID_URL, url)
  203. user_id = mobj.group('user_id')
  204. twid = mobj.group('id')
  205. webpage = self._download_webpage(self._TEMPLATE_URL % (user_id, twid), twid)
  206. username = remove_end(self._og_search_title(webpage), ' on Twitter')
  207. title = description = self._og_search_description(webpage).strip('').replace('\n', ' ').strip('“”')
  208. # strip 'https -_t.co_BJYgOjSeGA' junk from filenames
  209. title = re.sub(r'\s+(https?://[^ ]+)', '', title)
  210. info = {
  211. 'uploader_id': user_id,
  212. 'uploader': username,
  213. 'webpage_url': url,
  214. 'description': '%s on Twitter: "%s"' % (username, description),
  215. 'title': username + ' - ' + title,
  216. }
  217. card_id = self._search_regex(
  218. r'["\']/i/cards/tfw/v1/(\d+)', webpage, 'twitter card url', default=None)
  219. if card_id:
  220. card_url = 'https://twitter.com/i/cards/tfw/v1/' + card_id
  221. info.update({
  222. '_type': 'url_transparent',
  223. 'ie_key': 'TwitterCard',
  224. 'url': card_url,
  225. })
  226. return info
  227. mobj = re.search(r'''(?x)
  228. <video[^>]+class="animated-gif"(?P<more_info>[^>]+)>\s*
  229. <source[^>]+video-src="(?P<url>[^"]+)"
  230. ''', webpage)
  231. if mobj:
  232. more_info = mobj.group('more_info')
  233. height = int_or_none(self._search_regex(
  234. r'data-height="(\d+)"', more_info, 'height', fatal=False))
  235. width = int_or_none(self._search_regex(
  236. r'data-width="(\d+)"', more_info, 'width', fatal=False))
  237. thumbnail = self._search_regex(
  238. r'poster="([^"]+)"', more_info, 'poster', fatal=False)
  239. info.update({
  240. 'id': twid,
  241. 'url': mobj.group('url'),
  242. 'height': height,
  243. 'width': width,
  244. 'thumbnail': thumbnail,
  245. })
  246. return info
  247. if 'class="PlayableMedia' in webpage:
  248. info.update({
  249. '_type': 'url_transparent',
  250. 'ie_key': 'TwitterCard',
  251. 'url': '%s//twitter.com/i/videos/tweet/%s' % (self.http_scheme(), twid),
  252. })
  253. return info
  254. raise ExtractorError('There\'s no video in this tweet.')
  255. class TwitterAmplifyIE(TwitterBaseIE):
  256. IE_NAME = 'twitter:amplify'
  257. _VALID_URL = 'https?://amp\.twimg\.com/v/(?P<id>[0-9a-f\-]{36})'
  258. _TEST = {
  259. 'url': 'https://amp.twimg.com/v/0ba0c3c7-0af3-4c0a-bed5-7efd1ffa2951',
  260. 'md5': '7df102d0b9fd7066b86f3159f8e81bf6',
  261. 'info_dict': {
  262. 'id': '0ba0c3c7-0af3-4c0a-bed5-7efd1ffa2951',
  263. 'ext': 'mp4',
  264. 'title': 'Twitter Video',
  265. 'thumbnail': 're:^https?://.*',
  266. },
  267. }
  268. def _real_extract(self, url):
  269. video_id = self._match_id(url)
  270. webpage = self._download_webpage(url, video_id)
  271. vmap_url = self._html_search_meta(
  272. 'twitter:amplify:vmap', webpage, 'vmap url')
  273. video_url = self._get_vmap_video_url(vmap_url, video_id)
  274. thumbnails = []
  275. thumbnail = self._html_search_meta(
  276. 'twitter:image:src', webpage, 'thumbnail', fatal=False)
  277. def _find_dimension(target):
  278. w = int_or_none(self._html_search_meta(
  279. 'twitter:%s:width' % target, webpage, fatal=False))
  280. h = int_or_none(self._html_search_meta(
  281. 'twitter:%s:height' % target, webpage, fatal=False))
  282. return w, h
  283. if thumbnail:
  284. thumbnail_w, thumbnail_h = _find_dimension('image')
  285. thumbnails.append({
  286. 'url': thumbnail,
  287. 'width': thumbnail_w,
  288. 'height': thumbnail_h,
  289. })
  290. video_w, video_h = _find_dimension('player')
  291. formats = [{
  292. 'url': video_url,
  293. 'width': video_w,
  294. 'height': video_h,
  295. }]
  296. return {
  297. 'id': video_id,
  298. 'title': 'Twitter Video',
  299. 'formats': formats,
  300. 'thumbnails': thumbnails,
  301. }