twitter.py 12 KB

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