You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

429 lines
16 KiB

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