[lifenews] Add support for video URLs (Closes #5660)
[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 ..utils import (
8     int_or_none,
9     unified_strdate,
10     ExtractorError,
11 )
12
13
14 class LifeNewsIE(InfoExtractor):
15     IE_NAME = 'lifenews'
16     IE_DESC = 'LIFE | NEWS'
17     _VALID_URL = r'http://lifenews\.ru/(?:mobile/)?(?P<section>news|video)/(?P<id>\d+)'
18
19     _TESTS = [{
20         'url': 'http://lifenews.ru/news/126342',
21         'md5': 'e1b50a5c5fb98a6a544250f2e0db570a',
22         'info_dict': {
23             'id': '126342',
24             'ext': 'mp4',
25             'title': 'МВД разыскивает мужчин, оставивших в IKEA сумку с автоматом',
26             'description': 'Камеры наблюдения гипермаркета зафиксировали троих мужчин, спрятавших оружейный арсенал в камере хранения.',
27             'thumbnail': 're:http://.*\.jpg',
28             'upload_date': '20140130',
29         }
30     }, {
31         # video in <iframe>
32         'url': 'http://lifenews.ru/news/152125',
33         'md5': '77d19a6f0886cd76bdbf44b4d971a273',
34         'info_dict': {
35             'id': '152125',
36             'ext': 'mp4',
37             'title': 'В Сети появилось видео захвата «Правым сектором» колхозных полей ',
38             'description': 'Жители двух поселков Днепропетровской области не простили радикалам угрозу лишения плодородных земель и пошли в лобовую. ',
39             'upload_date': '20150402',
40             'uploader': 'embed.life.ru',
41         }
42     }, {
43         'url': 'http://lifenews.ru/news/153461',
44         'md5': '9b6ef8bc0ffa25aebc8bdb40d89ab795',
45         'info_dict': {
46             'id': '153461',
47             'ext': 'mp4',
48             'title': 'В Москве спасли потерявшегося медвежонка, который спрятался на дереве',
49             'description': 'Маленький хищник не смог найти дорогу домой и обрел временное убежище на тополе недалеко от жилого массива, пока его не нашла соседская собака.',
50             'upload_date': '20150505',
51             'uploader': 'embed.life.ru',
52         }
53     }]
54
55     def _real_extract(self, url):
56         mobj = re.match(self._VALID_URL, url)
57         video_id = mobj.group('id')
58         section = mobj.group('section')
59
60         webpage = self._download_webpage(
61             'http://lifenews.ru/%s/%s' % (section, video_id),
62             video_id, 'Downloading page')
63
64         videos = re.findall(r'<video.*?poster="(?P<poster>[^"]+)".*?src="(?P<video>[^"]+)".*?></video>', webpage)
65         iframe_link = self._html_search_regex(
66             '<iframe[^>]+src=["\']([^"\']+)["\']', webpage, 'iframe link', default=None)
67         if not videos and not iframe_link:
68             raise ExtractorError('No media links available for %s' % video_id)
69
70         title = self._og_search_title(webpage)
71         TITLE_SUFFIX = ' - Первый по срочным новостям — LIFE | NEWS'
72         if title.endswith(TITLE_SUFFIX):
73             title = title[:-len(TITLE_SUFFIX)]
74
75         description = self._og_search_description(webpage)
76
77         view_count = self._html_search_regex(
78             r'<div class=\'views\'>\s*(\d+)\s*</div>', webpage, 'view count', fatal=False)
79         comment_count = self._html_search_regex(
80             r'<div class=\'comments\'>\s*<span class=\'counter\'>\s*(\d+)\s*</span>', webpage, 'comment count', fatal=False)
81
82         upload_date = self._html_search_regex(
83             r'<time datetime=\'([^\']+)\'>', webpage, 'upload date', fatal=False)
84         if upload_date is not None:
85             upload_date = unified_strdate(upload_date)
86
87         common_info = {
88             'description': description,
89             'view_count': int_or_none(view_count),
90             'comment_count': int_or_none(comment_count),
91             'upload_date': upload_date,
92         }
93
94         def make_entry(video_id, media, video_number=None):
95             cur_info = dict(common_info)
96             cur_info.update({
97                 'id': video_id,
98                 'url': media[1],
99                 'thumbnail': media[0],
100                 'title': title if video_number is None else '%s-video%s' % (title, video_number),
101             })
102             return cur_info
103
104         if iframe_link:
105             iframe_link = self._proto_relative_url(iframe_link, 'http:')
106             cur_info = dict(common_info)
107             cur_info.update({
108                 '_type': 'url_transparent',
109                 'id': video_id,
110                 'title': title,
111                 'url': iframe_link,
112             })
113             return cur_info
114
115         if len(videos) == 1:
116             return make_entry(video_id, videos[0])
117         else:
118             return [make_entry(video_id, media, video_number + 1) for video_number, media in enumerate(videos)]