twitter.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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. def _search_dimensions_in_video_url(a_format, video_url):
  94. m = re.search(r'/(?P<width>\d+)x(?P<height>\d+)/', video_url)
  95. if m:
  96. a_format.update({
  97. 'width': int(m.group('width')),
  98. 'height': int(m.group('height')),
  99. })
  100. video_url = config.get('video_url') or config.get('playlist', [{}])[0].get('source')
  101. if video_url:
  102. f = {
  103. 'url': video_url,
  104. }
  105. _search_dimensions_in_video_url(f, video_url)
  106. formats.append(f)
  107. vmap_url = config.get('vmapUrl') or config.get('vmap_url')
  108. if vmap_url:
  109. formats.append({
  110. 'url': self._get_vmap_video_url(vmap_url, video_id),
  111. })
  112. media_info = None
  113. for entity in config.get('status', {}).get('entities', []):
  114. if 'mediaInfo' in entity:
  115. media_info = entity['mediaInfo']
  116. if media_info:
  117. for media_variant in media_info['variants']:
  118. media_url = media_variant['url']
  119. if media_url.endswith('.m3u8'):
  120. formats.extend(self._extract_m3u8_formats(media_url, video_id, ext='mp4', m3u8_id='hls'))
  121. elif media_url.endswith('.mpd'):
  122. formats.extend(self._extract_mpd_formats(media_url, video_id, mpd_id='dash'))
  123. else:
  124. vbr = int_or_none(media_variant.get('bitRate'), scale=1000)
  125. a_format = {
  126. 'url': media_url,
  127. 'format_id': 'http-%d' % vbr if vbr else 'http',
  128. 'vbr': vbr,
  129. }
  130. # Reported bitRate may be zero
  131. if not a_format['vbr']:
  132. del a_format['vbr']
  133. _search_dimensions_in_video_url(a_format, media_url)
  134. formats.append(a_format)
  135. duration = float_or_none(media_info.get('duration', {}).get('nanos'), scale=1e9)
  136. self._sort_formats(formats)
  137. title = self._search_regex(r'<title>([^<]+)</title>', webpage, 'title')
  138. thumbnail = config.get('posterImageUrl') or config.get('image_src')
  139. duration = float_or_none(config.get('duration')) or duration
  140. return {
  141. 'id': video_id,
  142. 'title': title,
  143. 'thumbnail': thumbnail,
  144. 'duration': duration,
  145. 'formats': formats,
  146. }
  147. class TwitterIE(InfoExtractor):
  148. IE_NAME = 'twitter'
  149. _VALID_URL = r'https?://(?:www\.|m\.|mobile\.)?twitter\.com/(?P<user_id>[^/]+)/status/(?P<id>\d+)'
  150. _TEMPLATE_URL = 'https://twitter.com/%s/status/%s'
  151. _TESTS = [{
  152. 'url': 'https://twitter.com/freethenipple/status/643211948184596480',
  153. 'info_dict': {
  154. 'id': '643211948184596480',
  155. 'ext': 'mp4',
  156. 'title': 'FREE THE NIPPLE - FTN supporters on Hollywood Blvd today!',
  157. 'thumbnail': 're:^https?://.*\.jpg',
  158. 'description': 'FREE THE NIPPLE on Twitter: "FTN supporters on Hollywood Blvd today! http://t.co/c7jHH749xJ"',
  159. 'uploader': 'FREE THE NIPPLE',
  160. 'uploader_id': 'freethenipple',
  161. },
  162. 'params': {
  163. 'skip_download': True, # requires ffmpeg
  164. },
  165. }, {
  166. 'url': 'https://twitter.com/giphz/status/657991469417025536/photo/1',
  167. 'md5': 'f36dcd5fb92bf7057f155e7d927eeb42',
  168. 'info_dict': {
  169. 'id': '657991469417025536',
  170. 'ext': 'mp4',
  171. 'title': 'Gifs - tu vai cai tu vai cai tu nao eh capaz disso tu vai cai',
  172. 'description': 'Gifs on Twitter: "tu vai cai tu vai cai tu nao eh capaz disso tu vai cai https://t.co/tM46VHFlO5"',
  173. 'thumbnail': 're:^https?://.*\.png',
  174. 'uploader': 'Gifs',
  175. 'uploader_id': 'giphz',
  176. },
  177. 'expected_warnings': ['height', 'width'],
  178. }, {
  179. 'url': 'https://twitter.com/starwars/status/665052190608723968',
  180. 'md5': '39b7199856dee6cd4432e72c74bc69d4',
  181. 'info_dict': {
  182. 'id': '665052190608723968',
  183. 'ext': 'mp4',
  184. 'title': 'Star Wars - A new beginning is coming December 18. Watch the official 60 second #TV spot for #StarWars: #TheForceAwakens.',
  185. 'description': 'Star Wars on Twitter: "A new beginning is coming December 18. Watch the official 60 second #TV spot for #StarWars: #TheForceAwakens."',
  186. 'uploader_id': 'starwars',
  187. 'uploader': 'Star Wars',
  188. },
  189. }, {
  190. 'url': 'https://twitter.com/BTNBrentYarina/status/705235433198714880',
  191. 'info_dict': {
  192. 'id': '705235433198714880',
  193. 'ext': 'mp4',
  194. 'title': 'Brent Yarina - Khalil Iverson\'s missed highlight dunk. And made highlight dunk. In one highlight.',
  195. 'description': 'Brent Yarina on Twitter: "Khalil Iverson\'s missed highlight dunk. And made highlight dunk. In one highlight."',
  196. 'uploader_id': 'BTNBrentYarina',
  197. 'uploader': 'Brent Yarina',
  198. },
  199. 'params': {
  200. # The same video as https://twitter.com/i/videos/tweet/705235433198714880
  201. # Test case of TwitterCardIE
  202. 'skip_download': True,
  203. },
  204. }, {
  205. 'url': 'https://twitter.com/jaydingeer/status/700207533655363584',
  206. 'md5': '',
  207. 'info_dict': {
  208. 'id': '700207533655363584',
  209. 'ext': 'mp4',
  210. 'title': 'jay - BEAT PROD: @suhmeduh #Damndaniel',
  211. 'description': 'jay on Twitter: "BEAT PROD: @suhmeduh https://t.co/HBrQ4AfpvZ #Damndaniel https://t.co/byBooq2ejZ"',
  212. 'thumbnail': 're:^https?://.*\.jpg',
  213. 'uploader': 'jay',
  214. 'uploader_id': 'jaydingeer',
  215. },
  216. 'params': {
  217. 'skip_download': True, # requires ffmpeg
  218. },
  219. }]
  220. def _real_extract(self, url):
  221. mobj = re.match(self._VALID_URL, url)
  222. user_id = mobj.group('user_id')
  223. twid = mobj.group('id')
  224. webpage = self._download_webpage(self._TEMPLATE_URL % (user_id, twid), twid)
  225. username = remove_end(self._og_search_title(webpage), ' on Twitter')
  226. title = description = self._og_search_description(webpage).strip('').replace('\n', ' ').strip('“”')
  227. # strip 'https -_t.co_BJYgOjSeGA' junk from filenames
  228. title = re.sub(r'\s+(https?://[^ ]+)', '', title)
  229. info = {
  230. 'uploader_id': user_id,
  231. 'uploader': username,
  232. 'webpage_url': url,
  233. 'description': '%s on Twitter: "%s"' % (username, description),
  234. 'title': username + ' - ' + title,
  235. }
  236. card_id = self._search_regex(
  237. r'["\']/i/cards/tfw/v1/(\d+)', webpage, 'twitter card url', default=None)
  238. if card_id:
  239. card_url = 'https://twitter.com/i/cards/tfw/v1/' + card_id
  240. info.update({
  241. '_type': 'url_transparent',
  242. 'ie_key': 'TwitterCard',
  243. 'url': card_url,
  244. })
  245. return info
  246. mobj = re.search(r'''(?x)
  247. <video[^>]+class="animated-gif"(?P<more_info>[^>]+)>\s*
  248. <source[^>]+video-src="(?P<url>[^"]+)"
  249. ''', webpage)
  250. if mobj:
  251. more_info = mobj.group('more_info')
  252. height = int_or_none(self._search_regex(
  253. r'data-height="(\d+)"', more_info, 'height', fatal=False))
  254. width = int_or_none(self._search_regex(
  255. r'data-width="(\d+)"', more_info, 'width', fatal=False))
  256. thumbnail = self._search_regex(
  257. r'poster="([^"]+)"', more_info, 'poster', fatal=False)
  258. info.update({
  259. 'id': twid,
  260. 'url': mobj.group('url'),
  261. 'height': height,
  262. 'width': width,
  263. 'thumbnail': thumbnail,
  264. })
  265. return info
  266. if 'class="PlayableMedia' in webpage:
  267. info.update({
  268. '_type': 'url_transparent',
  269. 'ie_key': 'TwitterCard',
  270. 'url': '%s//twitter.com/i/videos/tweet/%s' % (self.http_scheme(), twid),
  271. })
  272. return info
  273. raise ExtractorError('There\'s no video in this tweet.')
  274. class TwitterAmplifyIE(TwitterBaseIE):
  275. IE_NAME = 'twitter:amplify'
  276. _VALID_URL = 'https?://amp\.twimg\.com/v/(?P<id>[0-9a-f\-]{36})'
  277. _TEST = {
  278. 'url': 'https://amp.twimg.com/v/0ba0c3c7-0af3-4c0a-bed5-7efd1ffa2951',
  279. 'md5': '7df102d0b9fd7066b86f3159f8e81bf6',
  280. 'info_dict': {
  281. 'id': '0ba0c3c7-0af3-4c0a-bed5-7efd1ffa2951',
  282. 'ext': 'mp4',
  283. 'title': 'Twitter Video',
  284. 'thumbnail': 're:^https?://.*',
  285. },
  286. }
  287. def _real_extract(self, url):
  288. video_id = self._match_id(url)
  289. webpage = self._download_webpage(url, video_id)
  290. vmap_url = self._html_search_meta(
  291. 'twitter:amplify:vmap', webpage, 'vmap url')
  292. video_url = self._get_vmap_video_url(vmap_url, video_id)
  293. thumbnails = []
  294. thumbnail = self._html_search_meta(
  295. 'twitter:image:src', webpage, 'thumbnail', fatal=False)
  296. def _find_dimension(target):
  297. w = int_or_none(self._html_search_meta(
  298. 'twitter:%s:width' % target, webpage, fatal=False))
  299. h = int_or_none(self._html_search_meta(
  300. 'twitter:%s:height' % target, webpage, fatal=False))
  301. return w, h
  302. if thumbnail:
  303. thumbnail_w, thumbnail_h = _find_dimension('image')
  304. thumbnails.append({
  305. 'url': thumbnail,
  306. 'width': thumbnail_w,
  307. 'height': thumbnail_h,
  308. })
  309. video_w, video_h = _find_dimension('player')
  310. formats = [{
  311. 'url': video_url,
  312. 'width': video_w,
  313. 'height': video_h,
  314. }]
  315. return {
  316. 'id': video_id,
  317. 'title': 'Twitter Video',
  318. 'formats': formats,
  319. 'thumbnails': thumbnails,
  320. }