2 from __future__ 
import unicode_literals
 
  12 from .common 
import InfoExtractor
 
  13 from ..compat 
import compat_struct_pack
 
  27 class DailymotionBaseInfoExtractor(InfoExtractor
): 
  29     def _build_request(url
): 
  30         """Build a request with the family filter disabled""" 
  31         request 
= sanitized_Request(url
) 
  32         request
.add_header('Cookie', 'family_filter=off; ff=off') 
  35     def _download_webpage_handle_no_ff(self
, url
, *args
, **kwargs
): 
  36         request 
= self
._build
_request
(url
) 
  37         return self
._download
_webpage
_handle
(request
, *args
, **kwargs
) 
  39     def _download_webpage_no_ff(self
, url
, *args
, **kwargs
): 
  40         request 
= self
._build
_request
(url
) 
  41         return self
._download
_webpage
(request
, *args
, **kwargs
) 
  44 class DailymotionIE(DailymotionBaseInfoExtractor
): 
  45     _VALID_URL 
= r
'(?i)https?://(?:(www|touch)\.)?dailymotion\.[a-z]{2,3}/(?:(?:(?:embed|swf|#)/)?video|swf)/(?P<id>[^/?_]+)' 
  46     IE_NAME 
= 'dailymotion' 
  49         ('stream_h264_ld_url', 'ld'), 
  50         ('stream_h264_url', 'standard'), 
  51         ('stream_h264_hq_url', 'hq'), 
  52         ('stream_h264_hd_url', 'hd'), 
  53         ('stream_h264_hd1080_url', 'hd180'), 
  57         'url': 'http://www.dailymotion.com/video/x5kesuj_office-christmas-party-review-jason-bateman-olivia-munn-t-j-miller_news', 
  58         'md5': '074b95bdee76b9e3654137aee9c79dfe', 
  62             'title': 'Office Christmas Party Review –  Jason Bateman, Olivia Munn, T.J. Miller', 
  63             'description': 'Office Christmas Party Review -  Jason Bateman, Olivia Munn, T.J. Miller', 
  64             'thumbnail': r
're:^https?:.*\.(?:jpg|png)$', 
  66             'timestamp': 1493651285, 
  67             'upload_date': '20170501', 
  68             'uploader': 'Deadline', 
  69             'uploader_id': 'x1xm8ri', 
  73         'url': 'https://www.dailymotion.com/video/x2iuewm_steam-machine-models-pricing-listed-on-steam-store-ign-news_videogames', 
  74         'md5': '2137c41a8e78554bb09225b8eb322406', 
  78             'title': 'Steam Machine Models, Pricing Listed on Steam Store - IGN News', 
  79             'description': 'Several come bundled with the Steam Controller.', 
  80             'thumbnail': r
're:^https?:.*\.(?:jpg|png)$', 
  82             'timestamp': 1425657362, 
  83             'upload_date': '20150306', 
  85             'uploader_id': 'xijv66', 
  92         'url': 'http://www.dailymotion.com/video/x149uew_katy-perry-roar-official_musi', 
  94             'title': 'Roar (Official)', 
  97             'uploader': 'Katy Perry', 
  98             'upload_date': '20130905', 
 101             'skip_download': True, 
 103         'skip': 'VEVO is only available in some countries', 
 105         # age-restricted video 
 106         'url': 'http://www.dailymotion.com/video/xyh2zz_leanna-decker-cyber-girl-of-the-year-desires-nude-playboy-plus_redband', 
 107         'md5': '0d667a7b9cebecc3c89ee93099c4159d', 
 111             'title': 'Leanna Decker - Cyber Girl Of The Year Desires Nude [Playboy Plus]', 
 112             'uploader': 'HotWaves1012', 
 115         'skip': 'video gone', 
 117         # geo-restricted, player v5 
 118         'url': 'http://www.dailymotion.com/video/xhza0o', 
 119         'only_matching': True, 
 122         'url': 'http://www.dailymotion.com/video/x20su5f_the-power-of-nightmares-1-the-rise-of-the-politics-of-fear-bbc-2004_news', 
 123         'only_matching': True, 
 125         'url': 'http://www.dailymotion.com/swf/video/x3n92nf', 
 126         'only_matching': True, 
 128         'url': 'http://www.dailymotion.com/swf/x3ss1m_funny-magic-trick-barry-and-stuart_fun', 
 129         'only_matching': True, 
 133     def _extract_urls(webpage
): 
 134         # Look for embedded Dailymotion player 
 135         matches 
= re
.findall( 
 136             r
'<(?:(?:embed|iframe)[^>]+?src=|input[^>]+id=[\'"]dmcloudUrlEmissionSelect[\'"][^
>]+value
=)(["\'])(?P<url>(?:https?:)?//(?:www\.)?dailymotion\.com/(?:embed|swf)/video/.+?)\1', webpage) 
 137         return list(map(lambda m: unescapeHTML(m[1]), matches)) 
 139     def _real_extract(self, url): 
 140         video_id = self._match_id(url) 
 142         webpage = self._download_webpage_no_ff( 
 143             'https://www.dailymotion.com/video/%s' % video_id, video_id) 
 145         age_limit = self._rta_search(webpage) 
 147         description = self._og_search_description(webpage) or self._html_search_meta( 
 148             'description', webpage, 'description') 
 150         view_count_str = self._search_regex( 
 151             (r'<meta[^>]+itemprop="interactionCount
"[^>]+content="UserPlays
:([\s\d
,.]+)"', 
 152              r'video_views_count[^>]+>\s+([\s\d\,.]+)'), 
 153             webpage, 'view count', default=None) 
 155             view_count_str = re.sub(r'\s', '', view_count_str) 
 156         view_count = str_to_int(view_count_str) 
 157         comment_count = int_or_none(self._search_regex( 
 158             r'<meta[^>]+itemprop="interactionCount
"[^>]+content="UserComments
:(\d
+)"', 
 159             webpage, 'comment count', default=None)) 
 161         player_v5 = self._search_regex( 
 162             [r'buildPlayer\(({.+?})\);\n',  # See https://github.com/rg3/youtube-dl/issues/7826 
 163              r'playerV5\s*=\s*dmp\.create\([^,]+?,\s*({.+?})\);', 
 164              r'buildPlayer\(({.+?})\);', 
 165              r'var\s+config\s*=\s*({.+?});', 
 166              # New layout regex (see https://github.com/rg3/youtube-dl/issues/13580) 
 167              r'__PLAYER_CONFIG__\s*=\s*({.+?});'], 
 168             webpage, 'player v5', default=None) 
 170             player = self._parse_json(player_v5, video_id) 
 171             metadata = player['metadata'] 
 173             if metadata.get('error', {}).get('type') == 'password_protected': 
 174                 password = self._downloader.params.get('videopassword') 
 176                     r = int(metadata['id'][1:], 36) 
 177                     us64e = lambda x: base64.urlsafe_b64encode(x).decode().strip('=') 
 178                     t = ''.join(random.choice(string.ascii_letters) for i in range(10)) 
 179                     n = us64e(compat_struct_pack('I', r)) 
 180                     i = us64e(hashlib.md5(('%s%d%s' % (password, r, t)).encode()).digest()) 
 181                     metadata = self._download_json( 
 182                         'http://www.dailymotion.com/player/metadata/video/p' + i + t + n, video_id) 
 184             self._check_error(metadata) 
 187             for quality, media_list in metadata['qualities'].items(): 
 188                 for media in media_list: 
 189                     media_url = media.get('url') 
 192                     type_ = media.get('type') 
 193                     if type_ == 'application/vnd.lumberjack.manifest': 
 195                     ext = mimetype2ext(type_) or determine_ext(media_url) 
 197                         m3u8_formats = self._extract_m3u8_formats( 
 198                             media_url, video_id, 'mp4', preference=-1, 
 199                             m3u8_id='hls', fatal=False) 
 200                         for f in m3u8_formats: 
 201                             f['url'] = f['url'].split('#')[0] 
 204                         formats.extend(self._extract_f4m_formats( 
 205                             media_url, video_id, preference=-1, f4m_id='hds', fatal=False)) 
 209                             'format_id': 'http-%s' % quality, 
 212                         m = re.search(r'H264-(?P<width>\d+)x(?P<height>\d+)', media_url) 
 215                                 'width': int(m.group('width')), 
 216                                 'height': int(m.group('height')), 
 219             self._sort_formats(formats) 
 221             title = metadata['title'] 
 222             duration = int_or_none(metadata.get('duration')) 
 223             timestamp = int_or_none(metadata.get('created_time')) 
 224             thumbnail = metadata.get('poster_url') 
 225             uploader = metadata.get('owner', {}).get('screenname') 
 226             uploader_id = metadata.get('owner', {}).get('id') 
 229             subtitles_data = metadata.get('subtitles', {}).get('data', {}) 
 230             if subtitles_data and isinstance(subtitles_data, dict): 
 231                 for subtitle_lang, subtitle in subtitles_data.items(): 
 232                     subtitles[subtitle_lang] = [{ 
 233                         'ext': determine_ext(subtitle_url), 
 235                     } for subtitle_url in subtitle.get('urls', [])] 
 240                 'description': description, 
 241                 'thumbnail': thumbnail, 
 242                 'duration': duration, 
 243                 'timestamp': timestamp, 
 244                 'uploader': uploader, 
 245                 'uploader_id': uploader_id, 
 246                 'age_limit': age_limit, 
 247                 'view_count': view_count, 
 248                 'comment_count': comment_count, 
 250                 'subtitles': subtitles, 
 254         vevo_id = self._search_regex( 
 255             r'<link rel="video_src
" href="[^
"]*?vevo\.com[^"]*?video
=(?P
<id>[\w
]*)', 
 256             webpage, 'vevo embed
', default=None) 
 258             return self.url_result('vevo
:%s' % vevo_id, 'Vevo
') 
 260         # fallback old player 
 261         embed_page = self._download_webpage_no_ff( 
 262             'https
://www
.dailymotion
.com
/embed
/video
/%s' % video_id, 
 263             video_id, 'Downloading embed page
') 
 265         timestamp = parse_iso8601(self._html_search_meta( 
 266             'video
:release_date
', webpage, 'upload date
')) 
 268         info = self._parse_json( 
 270                 r'var info 
= ({.*?
}),$
', embed_page, 
 271                 'video info
', flags=re.MULTILINE), 
 274         self._check_error(info) 
 277         for (key, format_id) in self._FORMATS: 
 278             video_url = info.get(key) 
 279             if video_url is not None: 
 280                 m_size = re.search(r'H264
-(\d
+)x(\d
+)', video_url) 
 281                 if m_size is not None: 
 282                     width, height = map(int_or_none, (m_size.group(1), m_size.group(2))) 
 284                     width, height = None, None 
 288                     'format_id
': format_id, 
 292         self._sort_formats(formats) 
 295         video_subtitles = self.extract_subtitles(video_id, webpage) 
 297         title = self._og_search_title(webpage, default=None) 
 299             title = self._html_search_regex( 
 300                 r'(?s
)<span\s
+id="video_title"[^
>]*>(.*?
)</span
>', webpage, 
 306             'uploader
': info['owner
.screenname
'], 
 307             'timestamp
': timestamp, 
 309             'description
': description, 
 310             'subtitles
': video_subtitles, 
 311             'thumbnail
': info['thumbnail_url
'], 
 312             'age_limit
': age_limit, 
 313             'view_count
': view_count, 
 314             'duration
': info['duration
'] 
 317     def _check_error(self, info): 
 318         error = info.get('error
') 
 320             title = error.get('title
') or error['message
'] 
 321             # See https://developer.dailymotion.com/api#access-error 
 322             if error.get('code
') == 'DM007
': 
 323                 self.raise_geo_restricted(msg=title) 
 324             raise ExtractorError( 
 325                 '%s said
: %s' % (self.IE_NAME, title), expected=True) 
 327     def _get_subtitles(self, video_id, webpage): 
 329             sub_list = self._download_webpage( 
 330                 'https
://api
.dailymotion
.com
/video
/%s/subtitles?fields
=id,language
,url
' % video_id, 
 331                 video_id, note=False) 
 332         except ExtractorError as err: 
 333             self._downloader.report_warning('unable to download video subtitles
: %s' % error_to_compat_str(err)) 
 335         info = json.loads(sub_list) 
 336         if (info['total
'] > 0): 
 337             sub_lang_list = dict((l['language
'], [{'url
': l['url
'], 'ext
': 'srt
'}]) for l in info['list']) 
 339         self._downloader.report_warning('video doesn
\'t have subtitles
') 
 343 class DailymotionPlaylistIE(DailymotionBaseInfoExtractor): 
 344     IE_NAME = 'dailymotion
:playlist
' 
 345     _VALID_URL = r'(?
:https?
://)?
(?
:www\
.)?dailymotion\
.[a
-z
]{2,3}/playlist
/(?P
<id>[^
/?
#&]+)' 
 346     _MORE_PAGES_INDICATOR 
= r
'(?s)<div class="pages[^"]*">.*?<a\s+class="[^"]*?icon-arrow_right[^"]*?"' 
 347     _PAGE_TEMPLATE 
= 'https://www.dailymotion.com/playlist/%s/%s' 
 349         'url': 'http://www.dailymotion.com/playlist/xv4bw_nqtv_sport/1#video=xl8v3q', 
 352             'id': 'xv4bw_nqtv_sport', 
 354         'playlist_mincount': 20, 
 357     def _extract_entries(self
, id): 
 359         processed_urls 
= set() 
 360         for pagenum 
in itertools
.count(1): 
 361             page_url 
= self
._PAGE
_TEMPLATE 
% (id, pagenum
) 
 362             webpage
, urlh 
= self
._download
_webpage
_handle
_no
_ff
( 
 363                 page_url
, id, 'Downloading page %s' % pagenum
) 
 364             if urlh
.geturl() in processed_urls
: 
 365                 self
.report_warning('Stopped at duplicated page %s, which is the same as %s' % ( 
 366                     page_url
, urlh
.geturl()), id) 
 369             processed_urls
.add(urlh
.geturl()) 
 371             for video_id 
in re
.findall(r
'data-xid="(.+?)"', webpage
): 
 372                 if video_id 
not in video_ids
: 
 373                     yield self
.url_result( 
 374                         'http://www.dailymotion.com/video/%s' % video_id
, 
 375                         DailymotionIE
.ie_key(), video_id
) 
 376                     video_ids
.add(video_id
) 
 378             if re
.search(self
._MORE
_PAGES
_INDICATOR
, webpage
) is None: 
 381     def _real_extract(self
, url
): 
 382         mobj 
= re
.match(self
._VALID
_URL
, url
) 
 383         playlist_id 
= mobj
.group('id') 
 384         webpage 
= self
._download
_webpage
(url
, playlist_id
) 
 389             'title': self
._og
_search
_title
(webpage
), 
 390             'entries': self
._extract
_entries
(playlist_id
), 
 394 class DailymotionUserIE(DailymotionPlaylistIE
): 
 395     IE_NAME 
= 'dailymotion:user' 
 396     _VALID_URL 
= r
'https?://(?:www\.)?dailymotion\.[a-z]{2,3}/(?!(?:embed|swf|#|video|playlist)/)(?:(?:old/)?user/)?(?P<user>[^/]+)' 
 397     _PAGE_TEMPLATE 
= 'http://www.dailymotion.com/user/%s/%s' 
 399         'url': 'https://www.dailymotion.com/user/nqtv', 
 402             'title': 'Rémi Gaillard', 
 404         'playlist_mincount': 100, 
 406         'url': 'http://www.dailymotion.com/user/UnderProject', 
 408             'id': 'UnderProject', 
 409             'title': 'UnderProject', 
 411         'playlist_mincount': 1800, 
 412         'expected_warnings': [ 
 413             'Stopped at duplicated page', 
 415         'skip': 'Takes too long time', 
 418     def _real_extract(self
, url
): 
 419         mobj 
= re
.match(self
._VALID
_URL
, url
) 
 420         user 
= mobj
.group('user') 
 421         webpage 
= self
._download
_webpage
( 
 422             'https://www.dailymotion.com/user/%s' % user
, user
) 
 423         full_user 
= unescapeHTML(self
._html
_search
_regex
( 
 424             r
'<a class="nav-image" title="([^"]+)" href="/%s">' % re
.escape(user
), 
 431             'entries': self
._extract
_entries
(user
),