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