imgur.py 14 KB

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