]> gitweb @ CieloNegro.org - youtube-dl.git/blob - youtube_dl/extractor/dailymotion.py
[dailymotion] Added support for subtitles + new InfoExtractor for
[youtube-dl.git] / youtube_dl / extractor / dailymotion.py
1 import re
2 import json
3 import itertools
4 import socket
5
6 from .common import InfoExtractor
7 from .subtitles import SubtitlesIE
8
9 from ..utils import (
10     compat_http_client,
11     compat_urllib_error,
12     compat_urllib_request,
13     compat_str,
14     get_element_by_attribute,
15     get_element_by_id,
16
17     ExtractorError,
18 )
19
20
21 class DailyMotionSubtitlesIE(SubtitlesIE):
22
23     def _get_available_subtitles(self, video_id):
24         request = compat_urllib_request.Request('https://api.dailymotion.com/video/%s/subtitles?fields=id,language,url' % video_id)
25         try:
26             sub_list = compat_urllib_request.urlopen(request).read().decode('utf-8')
27         except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
28             self._downloader.report_warning(u'unable to download video subtitles: %s' % compat_str(err))
29             return {}
30         info = json.loads(sub_list)
31         if (info['total'] > 0):
32             sub_lang_list = dict((l['language'], l['url']) for l in info['list'])
33             return sub_lang_list
34         self._downloader.report_warning(u'video doesn\'t have subtitles')
35         return {}
36
37     def _get_subtitle_url(self, sub_lang, sub_name, video_id, format):
38         sub_lang_list = self._get_available_subtitles(video_id)
39         return sub_lang_list[sub_lang]
40
41     def _request_automatic_caption(self, video_id, webpage):
42         self._downloader.report_warning(u'Automatic Captions not supported by dailymotion')
43         return {}
44
45
46 class DailymotionIE(DailyMotionSubtitlesIE): #,InfoExtractor):
47     """Information Extractor for Dailymotion"""
48
49     _VALID_URL = r'(?i)(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/video/([^/]+)'
50     IE_NAME = u'dailymotion'
51     _TEST = {
52         u'url': u'http://www.dailymotion.com/video/x33vw9_tutoriel-de-youtubeur-dl-des-video_tech',
53         u'file': u'x33vw9.mp4',
54         u'md5': u'392c4b85a60a90dc4792da41ce3144eb',
55         u'info_dict': {
56             u"uploader": u"Alex and Van .",
57             u"title": u"Tutoriel de Youtubeur\"DL DES VIDEO DE YOUTUBE\""
58         }
59     }
60
61     def _real_extract(self, url):
62         # Extract id and simplified title from URL
63         mobj = re.match(self._VALID_URL, url)
64
65         video_id = mobj.group(1).split('_')[0].split('?')[0]
66
67         video_extension = 'mp4'
68
69         # Retrieve video webpage to extract further information
70         request = compat_urllib_request.Request(url)
71         request.add_header('Cookie', 'family_filter=off')
72         webpage = self._download_webpage(request, video_id)
73
74         # Extract URL, uploader and title from webpage
75         self.report_extraction(video_id)
76
77         video_uploader = self._search_regex([r'(?im)<span class="owner[^\"]+?">[^<]+?<a [^>]+?>([^<]+?)</a>',
78                                              # Looking for official user
79                                              r'<(?:span|a) .*?rel="author".*?>([^<]+?)</'],
80                                             webpage, 'video uploader')
81
82         video_upload_date = None
83         mobj = re.search(r'<div class="[^"]*uploaded_cont[^"]*" title="[^"]*">([0-9]{2})-([0-9]{2})-([0-9]{4})</div>', webpage)
84         if mobj is not None:
85             video_upload_date = mobj.group(3) + mobj.group(2) + mobj.group(1)
86
87         embed_url = 'http://www.dailymotion.com/embed/video/%s' % video_id
88         embed_page = self._download_webpage(embed_url, video_id,
89                                             u'Downloading embed page')
90         info = self._search_regex(r'var info = ({.*?}),', embed_page, 'video info')
91         info = json.loads(info)
92
93         # TODO: support choosing qualities
94
95         for key in ['stream_h264_hd1080_url', 'stream_h264_hd_url',
96                     'stream_h264_hq_url', 'stream_h264_url',
97                     'stream_h264_ld_url']:
98             if info.get(key):  # key in info and info[key]:
99                 max_quality = key
100                 self.to_screen(u'%s: Using %s' % (video_id, key))
101                 break
102         else:
103             raise ExtractorError(u'Unable to extract video URL')
104         video_url = info[max_quality]
105
106         # subtitles
107         video_subtitles = None
108         video_webpage = None
109
110         if self._downloader.params.get('writesubtitles', False) or self._downloader.params.get('allsubtitles', False):
111             video_subtitles = self._extract_subtitles(video_id)
112         elif self._downloader.params.get('writeautomaticsub', False):
113             video_subtitles = self._request_automatic_caption(video_id, video_webpage)
114
115         if self._downloader.params.get('listsubtitles', False):
116             self._list_available_subtitles(video_id)
117             return
118
119         if 'length_seconds' not in info:
120             self._downloader.report_warning(u'unable to extract video duration')
121             video_duration = ''
122         else:
123             video_duration = compat_urllib_parse.unquote_plus(video_info['length_seconds'][0])
124
125         return [{
126             'id':       video_id,
127             'url':      video_url,
128             'uploader': video_uploader,
129             'upload_date':  video_upload_date,
130             'title':    self._og_search_title(webpage),
131             'ext':      video_extension,
132             'subtitles':    video_subtitles,
133             'thumbnail': info['thumbnail_url']
134         }]