[theonion] Add new extractor (closes #3928)
[youtube-dl] / youtube_dl / extractor / theonion.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5
6 from .common import InfoExtractor
7 from ..utils import ExtractorError
8
9
10 class TheOnionIE(InfoExtractor):
11     _VALID_URL = r'(?x)https?://(?:www\.)?theonion\.com/video/[^,]+,(?P<article_id>[0-9]+)/?'
12     _TEST = {
13         'url': 'http://www.theonion.com/video/man-wearing-mm-jacket-gods-image,36918/',
14         'md5': '19eaa9a39cf9b9804d982e654dc791ee',
15         'info_dict': {
16             'id': '2133',
17             'ext': 'mp4',
18             'title': 'Man Wearing M&M Jacket Apparently Made In God\'s Image',
19             'description': 'md5:cc12448686b5600baae9261d3e180910',
20             'thumbnail': 're:^https?://.*\.jpg\?\d+$',
21         }
22     }
23
24     def _real_extract(self, url):
25         mobj = re.match(self._VALID_URL, url)
26         article_id = mobj.group('article_id')
27
28         webpage = self._download_webpage(url, article_id)
29
30         video_id = self._search_regex(
31             r'"videoId":\s(\d+),', webpage, 'video ID')
32         title = self._og_search_title(webpage)
33         description = self._og_search_description(webpage)
34         thumbnail = self._og_search_thumbnail(webpage)
35
36         sources = re.findall(r'<source src="([^"]+)" type="([^"]+)"', webpage)
37         if not sources:
38             raise ExtractorError(
39                 'No sources found for video %s' % (self.IE_NAME, video_id),
40                 expected=True)
41
42         formats = []
43         for src, type_ in sources:
44             if type_ == 'video/mp4':
45                 formats.append({
46                     'format_id': 'mp4_sd',
47                     'preference': 1,
48                     'url': src,
49                 })
50             elif type_ == 'video/webm':
51                 formats.append({
52                     'format_id': 'webm_sd',
53                     'preference': 0,
54                     'url': src,
55                 })
56             elif type_ == 'application/x-mpegURL':
57                 formats.extend(
58                     self._extract_m3u8_formats(src, video_id, preference=-1))
59             else:
60                 self.report_warning(
61                     'Encountered unexpected format: %s' % type_)
62
63         self._sort_formats(formats)
64
65         return {
66             'id': video_id,
67             'title': title,
68             'formats': formats,
69             'thumbnail': thumbnail,
70             'description': description,
71         }