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.

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