logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

imgur.py (13298B)


  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import re
  4. from .common import InfoExtractor
  5. from ..utils import (
  6. determine_ext,
  7. ExtractorError,
  8. float_or_none,
  9. int_or_none,
  10. js_to_json,
  11. merge_dicts,
  12. mimetype2ext,
  13. parse_iso8601,
  14. T,
  15. traverse_obj,
  16. txt_or_none,
  17. url_or_none,
  18. )
  19. class ImgurBaseIE(InfoExtractor):
  20. # hard-coded value, as also used by ArchiveTeam
  21. _CLIENT_ID = '546c25a59c58ad7'
  22. @classmethod
  23. def _imgur_result(cls, item_id):
  24. return cls.url_result('imgur:%s' % item_id, ImgurIE.ie_key(), item_id)
  25. def _call_api(self, endpoint, video_id, **kwargs):
  26. return self._download_json(
  27. 'https://api.imgur.com/post/v1/%s/%s?client_id=%s&include=media,account' % (endpoint, video_id, self._CLIENT_ID),
  28. video_id, **kwargs)
  29. @staticmethod
  30. def get_description(s):
  31. if 'Discover the magic of the internet at Imgur' in s:
  32. return None
  33. return txt_or_none(s)
  34. class ImgurIE(ImgurBaseIE):
  35. _VALID_URL = r'''(?x)
  36. (?:
  37. https?://(?:i\.)?imgur\.com/(?!(?:a|gallery|t|topic|r)/)|
  38. imgur:
  39. )(?P<id>[a-zA-Z0-9]+)
  40. '''
  41. _TESTS = [{
  42. 'url': 'https://imgur.com/A61SaA1',
  43. 'info_dict': {
  44. 'id': 'A61SaA1',
  45. 'ext': 'mp4',
  46. 'title': 're:Imgur GIF$|MRW gifv is up and running without any bugs$',
  47. 'timestamp': 1416446068,
  48. 'upload_date': '20141120',
  49. },
  50. }, {
  51. 'url': 'https://i.imgur.com/A61SaA1.gifv',
  52. 'only_matching': True,
  53. }, {
  54. 'url': 'https://i.imgur.com/crGpqCV.mp4',
  55. 'only_matching': True,
  56. }, {
  57. # previously, no title
  58. 'url': 'https://i.imgur.com/jxBXAMC.gifv',
  59. 'info_dict': {
  60. 'id': 'jxBXAMC',
  61. 'ext': 'mp4',
  62. 'title': 'Fahaka puffer feeding',
  63. 'timestamp': 1533835503,
  64. 'upload_date': '20180809',
  65. },
  66. }]
  67. def _extract_twitter_formats(self, html, tw_id='twitter', **kwargs):
  68. fatal = kwargs.pop('fatal', False)
  69. tw_stream = self._html_search_meta('twitter:player:stream', html, fatal=fatal, **kwargs)
  70. if not tw_stream:
  71. return []
  72. ext = mimetype2ext(self._html_search_meta(
  73. 'twitter:player:stream:content_type', html, default=None))
  74. width, height = (int_or_none(self._html_search_meta('twitter:player:' + v, html, default=None))
  75. for v in ('width', 'height'))
  76. return [{
  77. 'format_id': tw_id,
  78. 'url': tw_stream,
  79. 'ext': ext or determine_ext(tw_stream),
  80. 'width': width,
  81. 'height': height,
  82. }]
  83. def _real_extract(self, url):
  84. video_id = self._match_id(url)
  85. data = self._call_api('media', video_id, fatal=False, expected_status=404)
  86. webpage = self._download_webpage(
  87. 'https://i.imgur.com/{id}.gifv'.format(id=video_id), video_id, fatal=not data) or ''
  88. if not traverse_obj(data, ('media', 0, (
  89. ('type', T(lambda t: t == 'video' or None)),
  90. ('metadata', 'is_animated'))), get_all=False):
  91. raise ExtractorError(
  92. '%s is not a video or animated image' % video_id,
  93. expected=True)
  94. media_fmt = traverse_obj(data, ('media', 0, {
  95. 'url': ('url', T(url_or_none)),
  96. 'ext': 'ext',
  97. 'width': ('width', T(int_or_none)),
  98. 'height': ('height', T(int_or_none)),
  99. 'filesize': ('size', T(int_or_none)),
  100. 'acodec': ('metadata', 'has_sound', T(lambda b: None if b else 'none')),
  101. }))
  102. media_url = traverse_obj(media_fmt, 'url')
  103. if media_url:
  104. if not media_fmt.get('ext'):
  105. media_fmt['ext'] = mimetype2ext(traverse_obj(
  106. data, ('media', 0, 'mime_type'))) or determine_ext(media_url)
  107. if traverse_obj(data, ('media', 0, 'type')) == 'image':
  108. media_fmt['acodec'] = 'none'
  109. media_fmt.setdefault('preference', -10)
  110. tw_formats = self._extract_twitter_formats(webpage)
  111. if traverse_obj(tw_formats, (0, 'url')) == media_url:
  112. tw_formats = []
  113. else:
  114. # maybe this isn't an animated image/video?
  115. self._check_formats(tw_formats, video_id)
  116. video_elements = self._search_regex(
  117. r'(?s)<div class="video-elements">(.*?)</div>',
  118. webpage, 'video elements', default=None)
  119. if not (video_elements or tw_formats or media_url):
  120. raise ExtractorError(
  121. 'No sources found for video %s. Maybe a plain image?' % video_id,
  122. expected=True)
  123. def mung_format(fmt, *extra):
  124. fmt.update({
  125. 'http_headers': {
  126. 'User-Agent': 'youtube-dl (like wget)',
  127. },
  128. })
  129. for d in extra:
  130. fmt.update(d)
  131. return fmt
  132. if video_elements:
  133. def og_get_size(media_type):
  134. return dict((p, int_or_none(self._og_search_property(
  135. ':'.join((media_type, p)), webpage, default=None)))
  136. for p in ('width', 'height'))
  137. size = og_get_size('video')
  138. if all(v is None for v in size.values()):
  139. size = og_get_size('image')
  140. formats = traverse_obj(
  141. re.finditer(r'<source\s+src="(?P<src>[^"]+)"\s+type="(?P<type>[^"]+)"', video_elements),
  142. (Ellipsis, {
  143. 'format_id': ('type', T(lambda s: s.partition('/')[2])),
  144. 'url': ('src', T(self._proto_relative_url)),
  145. 'ext': ('type', T(mimetype2ext)),
  146. }, T(lambda f: mung_format(f, size))))
  147. gif_json = self._search_regex(
  148. r'(?s)var\s+videoItem\s*=\s*(\{.*?\})',
  149. webpage, 'GIF code', fatal=False)
  150. MUST_BRANCH = (None, T(lambda _: None))
  151. formats.extend(traverse_obj(gif_json, (
  152. T(lambda j: self._parse_json(
  153. j, video_id, transform_source=js_to_json, fatal=False)), {
  154. 'url': ('gifUrl', T(self._proto_relative_url)),
  155. 'filesize': ('size', T(int_or_none)),
  156. }, T(lambda f: mung_format(f, size, {
  157. 'format_id': 'gif',
  158. 'preference': -10, # gifs are worse than videos
  159. 'ext': 'gif',
  160. 'acodec': 'none',
  161. 'vcodec': 'gif',
  162. 'container': 'gif',
  163. })), MUST_BRANCH)))
  164. else:
  165. formats = []
  166. # maybe add formats from JSON or page Twitter metadata
  167. if not any((u == media_url) for u in traverse_obj(formats, (Ellipsis, 'url'))):
  168. formats.append(mung_format(media_fmt))
  169. tw_url = traverse_obj(tw_formats, (0, 'url'))
  170. if not any((u == tw_url) for u in traverse_obj(formats, (Ellipsis, 'url'))):
  171. formats.extend(mung_format(f) for f in tw_formats)
  172. self._sort_formats(formats)
  173. return merge_dicts(traverse_obj(data, {
  174. 'uploader_id': ('account_id', T(txt_or_none),
  175. T(lambda a: a if int_or_none(a) != 0 else None)),
  176. 'uploader': ('account', 'username', T(txt_or_none)),
  177. 'uploader_url': ('account', 'avatar_url', T(url_or_none)),
  178. 'like_count': ('upvote_count', T(int_or_none)),
  179. 'dislike_count': ('downvote_count', T(int_or_none)),
  180. 'comment_count': ('comment_count', T(int_or_none)),
  181. 'age_limit': ('is_mature', T(lambda x: 18 if x else None)),
  182. 'timestamp': (('updated_at', 'created_at'), T(parse_iso8601)),
  183. 'release_timestamp': ('created_at', T(parse_iso8601)),
  184. }, get_all=False), traverse_obj(data, ('media', 0, 'metadata', {
  185. 'title': ('title', T(txt_or_none)),
  186. 'description': ('description', T(self.get_description)),
  187. 'duration': ('duration', T(float_or_none)),
  188. 'timestamp': (('updated_at', 'created_at'), T(parse_iso8601)),
  189. 'release_timestamp': ('created_at', T(parse_iso8601)),
  190. })), {
  191. 'id': video_id,
  192. 'formats': formats,
  193. 'title': self._og_search_title(webpage, default='Imgur video ' + video_id),
  194. 'description': self.get_description(self._og_search_description(webpage)),
  195. 'thumbnail': url_or_none(self._html_search_meta('thumbnailUrl', webpage, default=None)),
  196. })
  197. class ImgurGalleryBaseIE(ImgurBaseIE):
  198. _GALLERY = True
  199. def _real_extract(self, url):
  200. gallery_id = self._match_id(url)
  201. data = self._call_api('albums', gallery_id, fatal=False, expected_status=404)
  202. info = traverse_obj(data, {
  203. 'title': ('title', T(txt_or_none)),
  204. 'description': ('description', T(self.get_description)),
  205. })
  206. if traverse_obj(data, 'is_album'):
  207. def yield_media_ids():
  208. for m_id in traverse_obj(data, (
  209. 'media', lambda _, v: v.get('type') == 'video' or v['metadata']['is_animated'],
  210. 'id', T(txt_or_none))):
  211. yield m_id
  212. # if a gallery with exactly one video, apply album metadata to video
  213. media_id = (
  214. self._GALLERY
  215. and traverse_obj(data, ('image_count', T(lambda c: c == 1)))
  216. and next(yield_media_ids(), None))
  217. if not media_id:
  218. result = self.playlist_result(
  219. map(self._imgur_result, yield_media_ids()), gallery_id)
  220. result.update(info)
  221. return result
  222. gallery_id = media_id
  223. result = self._imgur_result(gallery_id)
  224. info['_type'] = 'url_transparent'
  225. result.update(info)
  226. return result
  227. class ImgurGalleryIE(ImgurGalleryBaseIE):
  228. IE_NAME = 'imgur:gallery'
  229. _VALID_URL = r'https?://(?:i\.)?imgur\.com/(?:gallery|(?:t(?:opic)?|r)/[^/]+)/(?P<id>[a-zA-Z0-9]+)'
  230. _TESTS = [{
  231. 'url': 'http://imgur.com/gallery/Q95ko',
  232. 'info_dict': {
  233. 'id': 'Q95ko',
  234. 'title': 'Adding faces make every GIF better',
  235. },
  236. 'playlist_count': 25,
  237. 'skip': 'Zoinks! You\'ve taken a wrong turn.',
  238. }, {
  239. # TODO: static images - replace with animated/video gallery
  240. 'url': 'http://imgur.com/topic/Aww/ll5Vk',
  241. 'only_matching': True,
  242. }, {
  243. 'url': 'https://imgur.com/gallery/YcAQlkx',
  244. 'add_ies': ['Imgur'],
  245. 'info_dict': {
  246. 'id': 'YcAQlkx',
  247. 'ext': 'mp4',
  248. 'title': 'Classic Steve Carell gif...cracks me up everytime....damn the repost downvotes....',
  249. 'timestamp': 1358554297,
  250. 'upload_date': '20130119',
  251. 'uploader_id': '1648642',
  252. 'uploader': 'wittyusernamehere',
  253. },
  254. }, {
  255. # TODO: static image - replace with animated/video gallery
  256. 'url': 'http://imgur.com/topic/Funny/N8rOudd',
  257. 'only_matching': True,
  258. }, {
  259. 'url': 'http://imgur.com/r/aww/VQcQPhM',
  260. 'add_ies': ['Imgur'],
  261. 'info_dict': {
  262. 'id': 'VQcQPhM',
  263. 'ext': 'mp4',
  264. 'title': 'The boss is here',
  265. 'timestamp': 1476494751,
  266. 'upload_date': '20161015',
  267. 'uploader_id': '19138530',
  268. 'uploader': 'thematrixcam',
  269. },
  270. },
  271. # from PR #16674
  272. {
  273. 'url': 'https://imgur.com/t/unmuted/6lAn9VQ',
  274. 'info_dict': {
  275. 'id': '6lAn9VQ',
  276. 'title': 'Penguins !',
  277. },
  278. 'playlist_count': 3,
  279. }, {
  280. 'url': 'https://imgur.com/t/unmuted/kx2uD3C',
  281. 'add_ies': ['Imgur'],
  282. 'info_dict': {
  283. 'id': 'ZVMv45i',
  284. 'ext': 'mp4',
  285. 'title': 'Intruder',
  286. 'timestamp': 1528129683,
  287. 'upload_date': '20180604',
  288. },
  289. }, {
  290. 'url': 'https://imgur.com/t/unmuted/wXSK0YH',
  291. 'add_ies': ['Imgur'],
  292. 'info_dict': {
  293. 'id': 'JCAP4io',
  294. 'ext': 'mp4',
  295. 'title': 're:I got the blues$',
  296. 'description': 'Luka’s vocal stylings.\n\nFP edit: don’t encourage me. I’ll never stop posting Luka and friends.',
  297. 'timestamp': 1527809525,
  298. 'upload_date': '20180531',
  299. },
  300. }]
  301. class ImgurAlbumIE(ImgurGalleryBaseIE):
  302. IE_NAME = 'imgur:album'
  303. _VALID_URL = r'https?://(?:i\.)?imgur\.com/a/(?P<id>[a-zA-Z0-9]+)'
  304. _GALLERY = False
  305. _TESTS = [{
  306. # TODO: only static images - replace with animated/video gallery
  307. 'url': 'http://imgur.com/a/j6Orj',
  308. 'only_matching': True,
  309. },
  310. # from PR #21693
  311. {
  312. 'url': 'https://imgur.com/a/iX265HX',
  313. 'info_dict': {
  314. 'id': 'iX265HX',
  315. 'title': 'enen-no-shouboutai'
  316. },
  317. 'playlist_count': 2,
  318. }, {
  319. 'url': 'https://imgur.com/a/8pih2Ed',
  320. 'info_dict': {
  321. 'id': '8pih2Ed'
  322. },
  323. 'playlist_mincount': 1,
  324. }]