[lifenews] Add test for #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         'url': 'http://lifenews.ru/video/13035',
55         'only_matching': True,
56     }]
57
58     def _real_extract(self, url):
59         mobj = re.match(self._VALID_URL, url)
60         video_id = mobj.group('id')
61         section = mobj.group('section')
62
63         webpage = self._download_webpage(
64             'http://lifenews.ru/%s/%s' % (section, video_id),
65             video_id, 'Downloading page')
66
67         videos = re.findall(r'<video.*?poster="(?P<poster>[^"]+)".*?src="(?P<video>[^"]+)".*?></video>', webpage)
68         iframe_link = self._html_search_regex(
69             '<iframe[^>]+src=["\']([^"\']+)["\']', webpage, 'iframe link', default=None)
70         if not videos and not iframe_link:
71             raise ExtractorError('No media links available for %s' % video_id)
72
73         title = self._og_search_title(webpage)
74         TITLE_SUFFIX = ' - Первый по срочным новостям — LIFE | NEWS'
75         if title.endswith(TITLE_SUFFIX):
76             title = title[:-len(TITLE_SUFFIX)]
77
78         description = self._og_search_description(webpage)
79
80         view_count = self._html_search_regex(
81             r'<div class=\'views\'>\s*(\d+)\s*</div>', webpage, 'view count', fatal=False)
82         comment_count = self._html_search_regex(
83             r'<div class=\'comments\'>\s*<span class=\'counter\'>\s*(\d+)\s*</span>', webpage, 'comment count', fatal=False)
84
85         upload_date = self._html_search_regex(
86             r'<time datetime=\'([^\']+)\'>', webpage, 'upload date', fatal=False)
87         if upload_date is not None:
88             upload_date = unified_strdate(upload_date)
89
90         common_info = {
91             'description': description,
92             'view_count': int_or_none(view_count),
93             'comment_count': int_or_none(comment_count),
94             'upload_date': upload_date,
95         }
96
97         def make_entry(video_id, media, video_number=None):
98             cur_info = dict(common_info)
99             cur_info.update({
100                 'id': video_id,
101                 'url': media[1],
102                 'thumbnail': media[0],
103                 'title': title if video_number is None else '%s-video%s' % (title, video_number),
104             })
105             return cur_info
106
107         if iframe_link:
108             iframe_link = self._proto_relative_url(iframe_link, 'http:')
109             cur_info = dict(common_info)
110             cur_info.update({
111                 '_type': 'url_transparent',
112                 'id': video_id,
113                 'title': title,
114                 'url': iframe_link,
115             })
116             return cur_info
117
118         if len(videos) == 1:
119             return make_entry(video_id, videos[0])
120         else:
121             return [make_entry(video_id, media, video_number + 1) for video_number, media in enumerate(videos)]