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