[life:embed] Move to separated extractor and extract m3u8 formats
[youtube-dl] / youtube_dl / extractor / lifenews.py
1 # encoding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5
6 from .common import InfoExtractor
7 from ..compat import compat_urlparse
8 from ..utils import (
9     determine_ext,
10     int_or_none,
11     unified_strdate,
12     ExtractorError,
13 )
14
15
16 class LifeNewsIE(InfoExtractor):
17     IE_NAME = 'lifenews'
18     IE_DESC = 'LIFE | NEWS'
19     _VALID_URL = r'http://lifenews\.ru/(?:mobile/)?(?P<section>news|video)/(?P<id>\d+)'
20
21     _TESTS = [{
22         'url': 'http://lifenews.ru/news/126342',
23         'md5': 'e1b50a5c5fb98a6a544250f2e0db570a',
24         'info_dict': {
25             'id': '126342',
26             'ext': 'mp4',
27             'title': 'МВД разыскивает мужчин, оставивших в IKEA сумку с автоматом',
28             'description': 'Камеры наблюдения гипермаркета зафиксировали троих мужчин, спрятавших оружейный арсенал в камере хранения.',
29             'thumbnail': 're:http://.*\.jpg',
30             'upload_date': '20140130',
31         }
32     }, {
33         # video in <iframe>
34         'url': 'http://lifenews.ru/news/152125',
35         'md5': '77d19a6f0886cd76bdbf44b4d971a273',
36         'info_dict': {
37             'id': '152125',
38             'ext': 'mp4',
39             'title': 'В Сети появилось видео захвата «Правым сектором» колхозных полей ',
40             'description': 'Жители двух поселков Днепропетровской области не простили радикалам угрозу лишения плодородных земель и пошли в лобовую. ',
41             'upload_date': '20150402',
42             'uploader': 'embed.life.ru',
43         }
44     }, {
45         'url': 'http://lifenews.ru/news/153461',
46         'md5': '9b6ef8bc0ffa25aebc8bdb40d89ab795',
47         'info_dict': {
48             'id': '153461',
49             'ext': 'mp4',
50             'title': 'В Москве спасли потерявшегося медвежонка, который спрятался на дереве',
51             'description': 'Маленький хищник не смог найти дорогу домой и обрел временное убежище на тополе недалеко от жилого массива, пока его не нашла соседская собака.',
52             'upload_date': '20150505',
53             'uploader': 'embed.life.ru',
54         }
55     }, {
56         'url': 'http://lifenews.ru/video/13035',
57         'only_matching': True,
58     }]
59
60     def _real_extract(self, url):
61         mobj = re.match(self._VALID_URL, url)
62         video_id = mobj.group('id')
63         section = mobj.group('section')
64
65         webpage = self._download_webpage(
66             'http://lifenews.ru/%s/%s' % (section, video_id),
67             video_id, 'Downloading page')
68
69         videos = re.findall(r'<video.*?poster="(?P<poster>[^"]+)".*?src="(?P<video>[^"]+)".*?></video>', webpage)
70         iframe_link = self._html_search_regex(
71             '<iframe[^>]+src=["\']([^"\']+)["\']', webpage, 'iframe link', default=None)
72         if not videos and not iframe_link:
73             raise ExtractorError('No media links available for %s' % video_id)
74
75         title = self._og_search_title(webpage)
76         TITLE_SUFFIX = ' - Первый по срочным новостям — LIFE | NEWS'
77         if title.endswith(TITLE_SUFFIX):
78             title = title[:-len(TITLE_SUFFIX)]
79
80         description = self._og_search_description(webpage)
81
82         view_count = self._html_search_regex(
83             r'<div class=\'views\'>\s*(\d+)\s*</div>', webpage, 'view count', fatal=False)
84         comment_count = self._html_search_regex(
85             r'<div class=\'comments\'>\s*<span class=\'counter\'>\s*(\d+)\s*</span>', webpage, 'comment count', fatal=False)
86
87         upload_date = self._html_search_regex(
88             r'<time datetime=\'([^\']+)\'>', webpage, 'upload date', fatal=False)
89         if upload_date is not None:
90             upload_date = unified_strdate(upload_date)
91
92         common_info = {
93             'description': description,
94             'view_count': int_or_none(view_count),
95             'comment_count': int_or_none(comment_count),
96             'upload_date': upload_date,
97         }
98
99         def make_entry(video_id, media, video_number=None):
100             cur_info = dict(common_info)
101             cur_info.update({
102                 'id': video_id,
103                 'url': media[1],
104                 'thumbnail': media[0],
105                 'title': title if video_number is None else '%s-video%s' % (title, video_number),
106             })
107             return cur_info
108
109         if iframe_link:
110             iframe_link = self._proto_relative_url(iframe_link, 'http:')
111             cur_info = dict(common_info)
112             cur_info.update({
113                 '_type': 'url_transparent',
114                 'id': video_id,
115                 'title': title,
116                 'url': iframe_link,
117             })
118             return cur_info
119
120         if len(videos) == 1:
121             return make_entry(video_id, videos[0])
122         else:
123             return [make_entry(video_id, media, video_number + 1) for video_number, media in enumerate(videos)]
124
125
126 class LifeEmbedIE(InfoExtractor):
127     IE_NAME = 'life:embed'
128     _VALID_URL = r'http://embed\.life\.ru/embed/(?P<id>[\da-f]{32})'
129
130     _TEST = {
131         'url': 'http://embed.life.ru/embed/e50c2dec2867350528e2574c899b8291',
132         'md5': 'b889715c9e49cb1981281d0e5458fbbe',
133         'info_dict': {
134             'id': 'e50c2dec2867350528e2574c899b8291',
135             'ext': 'mp4',
136             'title': 'e50c2dec2867350528e2574c899b8291',
137             'thumbnail': 're:http://.*\.jpg',
138         }
139     }
140
141     def _real_extract(self, url):
142         video_id = self._match_id(url)
143
144         webpage = self._download_webpage(url, video_id)
145
146         formats = []
147         for video_url in re.findall(r'"file"\s*:\s*"([^"]+)', webpage):
148             video_url = compat_urlparse.urljoin(url, video_url)
149             ext = determine_ext(video_url)
150             if ext == 'm3u8':
151                 formats.extend(self._extract_m3u8_formats(
152                     video_url, video_id, 'mp4', m3u8_id='m3u8'))
153             else:
154                 formats.append({
155                     'url': video_url,
156                     'format_id': ext,
157                     'preference': 1,
158                 })
159
160         thumbnail = self._search_regex(
161             r'"image"\s*:\s*"([^"]+)', webpage, 'thumbnail', default=None)
162
163         return {
164             'id': video_id,
165             'title': video_id,
166             'thumbnail': thumbnail,
167             'formats': formats,
168         }