[canal+] Improve extraction (Closes #9718)
[youtube-dl] / youtube_dl / extractor / canalplus.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_urllib_parse_urlparse
8 from ..utils import (
9     ExtractorError,
10     HEADRequest,
11     unified_strdate,
12     qualities,
13     int_or_none,
14 )
15
16
17 class CanalplusIE(InfoExtractor):
18     IE_DESC = 'canalplus.fr, piwiplus.fr and d8.tv'
19     _VALID_URL = r'''(?x)
20                         https?://
21                             (?:
22                                 (?:
23                                     (?:(?:www|m)\.)?canalplus\.fr|
24                                     (?:www\.)?piwiplus\.fr|
25                                     (?:www\.)?d8\.tv|
26                                     (?:www\.)?itele\.fr
27                                 )/(?:(?:[^/]+/)*(?P<display_id>[^/?#&]+))?(?:\?.*\bvid=(?P<vid>\d+))?|
28                                 player\.canalplus\.fr/#/(?P<id>\d+)
29                             )
30
31                     '''
32     _VIDEO_INFO_TEMPLATE = 'http://service.canal-plus.com/video/rest/getVideosLiees/%s/%s?format=json'
33     _SITE_ID_MAP = {
34         'canalplus': 'cplus',
35         'piwiplus': 'teletoon',
36         'd8': 'd8',
37         'itele': 'itele',
38     }
39
40     _TESTS = [{
41         'url': 'http://www.canalplus.fr/c-emissions/pid1830-c-zapping.html?vid=1263092',
42         'md5': '12164a6f14ff6df8bd628e8ba9b10b78',
43         'info_dict': {
44             'id': '1263092',
45             'ext': 'mp4',
46             'title': 'Le Zapping - 13/05/15',
47             'description': 'md5:09738c0d06be4b5d06a0940edb0da73f',
48             'upload_date': '20150513',
49         },
50     }, {
51         'url': 'http://www.piwiplus.fr/videos-piwi/pid1405-le-labyrinthe-boing-super-ranger.html?vid=1108190',
52         'info_dict': {
53             'id': '1108190',
54             'ext': 'flv',
55             'title': 'Le labyrinthe - Boing super ranger',
56             'description': 'md5:4cea7a37153be42c1ba2c1d3064376ff',
57             'upload_date': '20140724',
58         },
59         'skip': 'Only works from France',
60     }, {
61         'url': 'http://www.d8.tv/d8-docs-mags/pid6589-d8-campagne-intime.html',
62         'info_dict': {
63             'id': '966289',
64             'ext': 'flv',
65             'title': 'Campagne intime - Documentaire exceptionnel',
66             'description': 'md5:d2643b799fb190846ae09c61e59a859f',
67             'upload_date': '20131108',
68         },
69         'skip': 'videos get deleted after a while',
70     }, {
71         'url': 'http://www.itele.fr/france/video/aubervilliers-un-lycee-en-colere-111559',
72         'md5': '38b8f7934def74f0d6f3ba6c036a5f82',
73         'info_dict': {
74             'id': '1213714',
75             'ext': 'mp4',
76             'title': 'Aubervilliers : un lycée en colère - Le 11/02/2015 à 06h45',
77             'description': 'md5:8216206ec53426ea6321321f3b3c16db',
78             'upload_date': '20150211',
79         },
80     }, {
81         'url': 'http://m.canalplus.fr/?vid=1398231',
82         'only_matching': True,
83     }]
84
85     def _real_extract(self, url):
86         mobj = re.match(self._VALID_URL, url)
87         video_id = mobj.groupdict().get('id') or mobj.groupdict().get('vid')
88
89         site_id = self._SITE_ID_MAP[compat_urllib_parse_urlparse(url).netloc.rsplit('.', 2)[-2]]
90
91         # Beware, some subclasses do not define an id group
92         display_id = mobj.group('display_id') or video_id
93
94         if video_id is None:
95             webpage = self._download_webpage(url, display_id)
96             video_id = self._search_regex(
97                 [r'<canal:player[^>]+?videoId=(["\'])(?P<id>\d+)', r'id=["\']canal_video_player(?P<id>\d+)'],
98                 webpage, 'video id', group='id')
99
100         info_url = self._VIDEO_INFO_TEMPLATE % (site_id, video_id)
101         video_data = self._download_json(info_url, video_id, 'Downloading video JSON')
102
103         if isinstance(video_data, list):
104             video_data = [video for video in video_data if video.get('ID') == video_id][0]
105         media = video_data['MEDIA']
106         infos = video_data['INFOS']
107
108         preference = qualities(['MOBILE', 'BAS_DEBIT', 'HAUT_DEBIT', 'HD'])
109
110         fmt_url = next(iter(media.get('VIDEOS')))
111         if '/geo' in fmt_url.lower():
112             response = self._request_webpage(
113                 HEADRequest(fmt_url), video_id,
114                 'Checking if the video is georestricted')
115             if '/blocage' in response.geturl():
116                 raise ExtractorError(
117                     'The video is not available in your country',
118                     expected=True)
119
120         formats = []
121         for format_id, format_url in media['VIDEOS'].items():
122             if not format_url:
123                 continue
124             if format_id == 'HLS':
125                 formats.extend(self._extract_m3u8_formats(
126                     format_url, video_id, 'mp4', 'm3u8_native', m3u8_id=format_id, fatal=False))
127             elif format_id == 'HDS':
128                 formats.extend(self._extract_f4m_formats(
129                     format_url + '?hdcore=2.11.3', video_id, f4m_id=format_id, fatal=False))
130             else:
131                 formats.append({
132                     # the secret extracted ya function in http://player.canalplus.fr/common/js/canalPlayer.js
133                     'url': format_url + '?secret=pqzerjlsmdkjfoiuerhsdlfknaes',
134                     'format_id': format_id,
135                     'preference': preference(format_id),
136                 })
137         self._sort_formats(formats)
138
139         thumbnails = [{
140             'id': image_id,
141             'url': image_url,
142         } for image_id, image_url in media.get('images', {}).items()]
143
144         titrage = infos['TITRAGE']
145
146         return {
147             'id': video_id,
148             'display_id': display_id,
149             'title': '%s - %s' % (titrage['TITRE'],
150                                   titrage['SOUS_TITRE']),
151             'upload_date': unified_strdate(infos.get('PUBLICATION', {}).get('DATE')),
152             'thumbnails': thumbnails,
153             'description': infos.get('DESCRIPTION'),
154             'duration': int_or_none(infos.get('DURATION')),
155             'view_count': int_or_none(infos.get('NB_VUES')),
156             'like_count': int_or_none(infos.get('NB_LIKES')),
157             'comment_count': int_or_none(infos.get('NB_COMMENTS')),
158             'formats': formats,
159         }