2 from __future__ 
import unicode_literals
 
  13 from .common 
import InfoExtractor
 
  14 from ..compat 
import compat_struct_pack
 
  30 class DailymotionBaseInfoExtractor(InfoExtractor
): 
  32     def _build_request(url
): 
  33         """Build a request with the family filter disabled""" 
  34         request 
= sanitized_Request(url
) 
  35         request
.add_header('Cookie', 'family_filter=off; ff=off') 
  38     def _download_webpage_handle_no_ff(self
, url
, *args
, **kwargs
): 
  39         request 
= self
._build
_request
(url
) 
  40         return self
._download
_webpage
_handle
(request
, *args
, **kwargs
) 
  42     def _download_webpage_no_ff(self
, url
, *args
, **kwargs
): 
  43         request 
= self
._build
_request
(url
) 
  44         return self
._download
_webpage
(request
, *args
, **kwargs
) 
  47 class DailymotionIE(DailymotionBaseInfoExtractor
): 
  48     _VALID_URL 
= r
'(?i)https?://(?:(www|touch)\.)?dailymotion\.[a-z]{2,3}/(?:(?:(?:embed|swf|#)/)?video|swf)/(?P<id>[^/?_]+)' 
  49     IE_NAME 
= 'dailymotion' 
  52         ('stream_h264_ld_url', 'ld'), 
  53         ('stream_h264_url', 'standard'), 
  54         ('stream_h264_hq_url', 'hq'), 
  55         ('stream_h264_hd_url', 'hd'), 
  56         ('stream_h264_hd1080_url', 'hd180'), 
  60         'url': 'http://www.dailymotion.com/video/x5kesuj_office-christmas-party-review-jason-bateman-olivia-munn-t-j-miller_news', 
  61         'md5': '074b95bdee76b9e3654137aee9c79dfe', 
  65             'title': 'Office Christmas Party Review –  Jason Bateman, Olivia Munn, T.J. Miller', 
  66             'description': 'Office Christmas Party Review -  Jason Bateman, Olivia Munn, T.J. Miller', 
  67             'thumbnail': r
're:^https?:.*\.(?:jpg|png)$', 
  69             'timestamp': 1493651285, 
  70             'upload_date': '20170501', 
  71             'uploader': 'Deadline', 
  72             'uploader_id': 'x1xm8ri', 
  76         'url': 'https://www.dailymotion.com/video/x2iuewm_steam-machine-models-pricing-listed-on-steam-store-ign-news_videogames', 
  77         'md5': '2137c41a8e78554bb09225b8eb322406', 
  81             'title': 'Steam Machine Models, Pricing Listed on Steam Store - IGN News', 
  82             'description': 'Several come bundled with the Steam Controller.', 
  83             'thumbnail': r
're:^https?:.*\.(?:jpg|png)$', 
  85             'timestamp': 1425657362, 
  86             'upload_date': '20150306', 
  88             'uploader_id': 'xijv66', 
  95         'url': 'http://www.dailymotion.com/video/x149uew_katy-perry-roar-official_musi', 
  97             'title': 'Roar (Official)', 
 100             'uploader': 'Katy Perry', 
 101             'upload_date': '20130905', 
 104             'skip_download': True, 
 106         'skip': 'VEVO is only available in some countries', 
 108         # age-restricted video 
 109         'url': 'http://www.dailymotion.com/video/xyh2zz_leanna-decker-cyber-girl-of-the-year-desires-nude-playboy-plus_redband', 
 110         'md5': '0d667a7b9cebecc3c89ee93099c4159d', 
 114             'title': 'Leanna Decker - Cyber Girl Of The Year Desires Nude [Playboy Plus]', 
 115             'uploader': 'HotWaves1012', 
 118         'skip': 'video gone', 
 120         # geo-restricted, player v5 
 121         'url': 'http://www.dailymotion.com/video/xhza0o', 
 122         'only_matching': True, 
 125         'url': 'http://www.dailymotion.com/video/x20su5f_the-power-of-nightmares-1-the-rise-of-the-politics-of-fear-bbc-2004_news', 
 126         'only_matching': True, 
 128         'url': 'http://www.dailymotion.com/swf/video/x3n92nf', 
 129         'only_matching': True, 
 131         'url': 'http://www.dailymotion.com/swf/x3ss1m_funny-magic-trick-barry-and-stuart_fun', 
 132         'only_matching': True, 
 136     def _extract_urls(webpage
): 
 137         # Look for embedded Dailymotion player 
 138         matches 
= re
.findall( 
 139             r
'<(?:(?:embed|iframe)[^>]+?src=|input[^>]+id=[\'"]dmcloudUrlEmissionSelect[\'"][^
>]+value
=)(["\'])(?P<url>(?:https?:)?//(?:www\.)?dailymotion\.com/(?:embed|swf)/video/.+?)\1', webpage) 
 140         return list(map(lambda m: unescapeHTML(m[1]), matches)) 
 142     def _real_extract(self, url): 
 143         video_id = self._match_id(url) 
 145         webpage = self._download_webpage_no_ff( 
 146             'https://www.dailymotion.com/video/%s' % video_id, video_id) 
 148         age_limit = self._rta_search(webpage) 
 150         description = self._og_search_description( 
 151             webpage, default=None) or self._html_search_meta( 
 152             'description', webpage, 'description') 
 154         view_count_str = self._search_regex( 
 155             (r'<meta[^>]+itemprop="interactionCount
"[^>]+content="UserPlays
:([\s\d
,.]+)"', 
 156              r'video_views_count[^>]+>\s+([\s\d\,.]+)'), 
 157             webpage, 'view count', default=None) 
 159             view_count_str = re.sub(r'\s', '', view_count_str) 
 160         view_count = str_to_int(view_count_str) 
 161         comment_count = int_or_none(self._search_regex( 
 162             r'<meta[^>]+itemprop="interactionCount
"[^>]+content="UserComments
:(\d
+)"', 
 163             webpage, 'comment count', default=None)) 
 165         player_v5 = self._search_regex( 
 166             [r'buildPlayer\(({.+?})\);\n',  # See https://github.com/rg3/youtube-dl/issues/7826 
 167              r'playerV5\s*=\s*dmp\.create\([^,]+?,\s*({.+?})\);', 
 168              r'buildPlayer\(({.+?})\);', 
 169              r'var\s+config\s*=\s*({.+?});', 
 170              # New layout regex (see https://github.com/rg3/youtube-dl/issues/13580) 
 171              r'__PLAYER_CONFIG__\s*=\s*({.+?});'], 
 172             webpage, 'player v5', default=None) 
 174             player = self._parse_json(player_v5, video_id) 
 175             metadata = player['metadata'] 
 177             if metadata.get('error', {}).get('type') == 'password_protected': 
 178                 password = self._downloader.params.get('videopassword') 
 180                     r = int(metadata['id'][1:], 36) 
 181                     us64e = lambda x: base64.urlsafe_b64encode(x).decode().strip('=') 
 182                     t = ''.join(random.choice(string.ascii_letters) for i in range(10)) 
 183                     n = us64e(compat_struct_pack('I', r)) 
 184                     i = us64e(hashlib.md5(('%s%d%s' % (password, r, t)).encode()).digest()) 
 185                     metadata = self._download_json( 
 186                         'http://www.dailymotion.com/player/metadata/video/p' + i + t + n, video_id) 
 188             self._check_error(metadata) 
 191             for quality, media_list in metadata['qualities'].items(): 
 192                 for media in media_list: 
 193                     media_url = media.get('url') 
 196                     type_ = media.get('type') 
 197                     if type_ == 'application/vnd.lumberjack.manifest': 
 199                     ext = mimetype2ext(type_) or determine_ext(media_url) 
 201                         m3u8_formats = self._extract_m3u8_formats( 
 202                             media_url, video_id, 'mp4', preference=-1, 
 203                             m3u8_id='hls', fatal=False) 
 204                         for f in m3u8_formats: 
 205                             f['url'] = f['url'].split('#')[0] 
 208                         formats.extend(self._extract_f4m_formats( 
 209                             media_url, video_id, preference=-1, f4m_id='hds', fatal=False)) 
 213                             'format_id': 'http-%s' % quality, 
 216                         m = re.search(r'H264-(?P<width>\d+)x(?P<height>\d+)', media_url) 
 219                                 'width': int(m.group('width')), 
 220                                 'height': int(m.group('height')), 
 223             self._sort_formats(formats) 
 225             title = metadata['title'] 
 226             duration = int_or_none(metadata.get('duration')) 
 227             timestamp = int_or_none(metadata.get('created_time')) 
 228             thumbnail = metadata.get('poster_url') 
 229             uploader = metadata.get('owner', {}).get('screenname') 
 230             uploader_id = metadata.get('owner', {}).get('id') 
 233             subtitles_data = metadata.get('subtitles', {}).get('data', {}) 
 234             if subtitles_data and isinstance(subtitles_data, dict): 
 235                 for subtitle_lang, subtitle in subtitles_data.items(): 
 236                     subtitles[subtitle_lang] = [{ 
 237                         'ext': determine_ext(subtitle_url), 
 239                     } for subtitle_url in subtitle.get('urls', [])] 
 244                 'description': description, 
 245                 'thumbnail': thumbnail, 
 246                 'duration': duration, 
 247                 'timestamp': timestamp, 
 248                 'uploader': uploader, 
 249                 'uploader_id': uploader_id, 
 250                 'age_limit': age_limit, 
 251                 'view_count': view_count, 
 252                 'comment_count': comment_count, 
 254                 'subtitles': subtitles, 
 258         vevo_id = self._search_regex( 
 259             r'<link rel="video_src
" href="[^
"]*?vevo\.com[^"]*?video
=(?P
<id>[\w
]*)', 
 260             webpage, 'vevo embed
', default=None) 
 262             return self.url_result('vevo
:%s' % vevo_id, 'Vevo
') 
 264         # fallback old player 
 265         embed_page = self._download_webpage_no_ff( 
 266             'https
://www
.dailymotion
.com
/embed
/video
/%s' % video_id, 
 267             video_id, 'Downloading embed page
') 
 269         timestamp = parse_iso8601(self._html_search_meta( 
 270             'video
:release_date
', webpage, 'upload date
')) 
 272         info = self._parse_json( 
 274                 r'var info 
= ({.*?
}),$
', embed_page, 
 275                 'video info
', flags=re.MULTILINE), 
 278         self._check_error(info) 
 281         for (key, format_id) in self._FORMATS: 
 282             video_url = info.get(key) 
 283             if video_url is not None: 
 284                 m_size = re.search(r'H264
-(\d
+)x(\d
+)', video_url) 
 285                 if m_size is not None: 
 286                     width, height = map(int_or_none, (m_size.group(1), m_size.group(2))) 
 288                     width, height = None, None 
 292                     'format_id
': format_id, 
 296         self._sort_formats(formats) 
 299         video_subtitles = self.extract_subtitles(video_id, webpage) 
 301         title = self._og_search_title(webpage, default=None) 
 303             title = self._html_search_regex( 
 304                 r'(?s
)<span\s
+id="video_title"[^
>]*>(.*?
)</span
>', webpage, 
 310             'uploader
': info['owner
.screenname
'], 
 311             'timestamp
': timestamp, 
 313             'description
': description, 
 314             'subtitles
': video_subtitles, 
 315             'thumbnail
': info['thumbnail_url
'], 
 316             'age_limit
': age_limit, 
 317             'view_count
': view_count, 
 318             'duration
': info['duration
'] 
 321     def _check_error(self, info): 
 322         error = info.get('error
') 
 324             title = error.get('title
') or error['message
'] 
 325             # See https://developer.dailymotion.com/api#access-error 
 326             if error.get('code
') == 'DM007
': 
 327                 self.raise_geo_restricted(msg=title) 
 328             raise ExtractorError( 
 329                 '%s said
: %s' % (self.IE_NAME, title), expected=True) 
 331     def _get_subtitles(self, video_id, webpage): 
 333             sub_list = self._download_webpage( 
 334                 'https
://api
.dailymotion
.com
/video
/%s/subtitles?fields
=id,language
,url
' % video_id, 
 335                 video_id, note=False) 
 336         except ExtractorError as err: 
 337             self._downloader.report_warning('unable to download video subtitles
: %s' % error_to_compat_str(err)) 
 339         info = json.loads(sub_list) 
 340         if (info['total
'] > 0): 
 341             sub_lang_list = dict((l['language
'], [{'url
': l['url
'], 'ext
': 'srt
'}]) for l in info['list']) 
 343         self._downloader.report_warning('video doesn
\'t have subtitles
') 
 347 class DailymotionPlaylistIE(DailymotionBaseInfoExtractor): 
 348     IE_NAME = 'dailymotion
:playlist
' 
 349     _VALID_URL = r'(?
:https?
://)?
(?
:www\
.)?dailymotion\
.[a
-z
]{2,3}/playlist
/(?P
<id>x
[0-9a
-z
]+)' 
 351         'url
': 'http
://www
.dailymotion
.com
/playlist
/xv4bw_nqtv_sport
/1#video=xl8v3q', 
 356         'playlist_mincount': 20, 
 360     def _fetch_page(self
, playlist_id
, authorizaion
, page
): 
 362         videos 
= self
._download
_json
( 
 363             'https://graphql.api.dailymotion.com', 
 364             playlist_id
, 'Downloading page %d' % page
, 
 367   collection(xid: "%s") { 
 368     videos(first: %d, page: %d) { 
 381 }''' % (playlist_id
, self
._PAGE
_SIZE
, page
) 
 382             }).encode(), headers
={ 
 383                 'Authorization': authorizaion
, 
 384                 'Origin': 'https://www.dailymotion.com', 
 385             })['data']['collection']['videos'] 
 386         for edge 
in videos
['edges']: 
 388             yield self
.url_result( 
 389                 node
['url'], DailymotionIE
.ie_key(), node
['xid']) 
 391     def _real_extract(self
, url
): 
 392         playlist_id 
= self
._match
_id
(url
) 
 393         webpage 
= self
._download
_webpage
(url
, playlist_id
) 
 394         api 
= self
._parse
_json
(self
._search
_regex
( 
 395             r
'__PLAYER_CONFIG__\s*=\s*({.+?});', 
 396             webpage
, 'player config'), playlist_id
)['context']['api'] 
 397         auth 
= self
._download
_json
( 
 398             api
.get('auth_url', 'https://graphql.api.dailymotion.com/oauth/token'), 
 399             playlist_id
, data
=urlencode_postdata({ 
 400                 'client_id': api
.get('client_id', 'f1a362d288c1b98099c7'), 
 401                 'client_secret': api
.get('client_secret', 'eea605b96e01c796ff369935357eca920c5da4c5'), 
 402                 'grant_type': 'client_credentials', 
 404         authorizaion 
= '%s %s' % (auth
.get('token_type', 'Bearer'), auth
['access_token']) 
 405         entries 
= OnDemandPagedList(functools
.partial( 
 406             self
._fetch
_page
, playlist_id
, authorizaion
), self
._PAGE
_SIZE
) 
 407         return self
.playlist_result( 
 408             entries
, playlist_id
, 
 409             self
._og
_search
_title
(webpage
)) 
 412 class DailymotionUserIE(DailymotionBaseInfoExtractor
): 
 413     IE_NAME 
= 'dailymotion:user' 
 414     _VALID_URL 
= r
'https?://(?:www\.)?dailymotion\.[a-z]{2,3}/(?!(?:embed|swf|#|video|playlist)/)(?:(?:old/)?user/)?(?P<user>[^/]+)' 
 415     _MORE_PAGES_INDICATOR 
= r
'(?s)<div class="pages[^"]*">.*?<a\s+class="[^"]*?icon-arrow_right[^"]*?"' 
 416     _PAGE_TEMPLATE 
= 'http://www.dailymotion.com/user/%s/%s' 
 418         'url': 'https://www.dailymotion.com/user/nqtv', 
 421             'title': 'Rémi Gaillard', 
 423         'playlist_mincount': 100, 
 425         'url': 'http://www.dailymotion.com/user/UnderProject', 
 427             'id': 'UnderProject', 
 428             'title': 'UnderProject', 
 430         'playlist_mincount': 1800, 
 431         'expected_warnings': [ 
 432             'Stopped at duplicated page', 
 434         'skip': 'Takes too long time', 
 437     def _extract_entries(self
, id): 
 439         processed_urls 
= set() 
 440         for pagenum 
in itertools
.count(1): 
 441             page_url 
= self
._PAGE
_TEMPLATE 
% (id, pagenum
) 
 442             webpage
, urlh 
= self
._download
_webpage
_handle
_no
_ff
( 
 443                 page_url
, id, 'Downloading page %s' % pagenum
) 
 444             if urlh
.geturl() in processed_urls
: 
 445                 self
.report_warning('Stopped at duplicated page %s, which is the same as %s' % ( 
 446                     page_url
, urlh
.geturl()), id) 
 449             processed_urls
.add(urlh
.geturl()) 
 451             for video_id 
in re
.findall(r
'data-xid="(.+?)"', webpage
): 
 452                 if video_id 
not in video_ids
: 
 453                     yield self
.url_result( 
 454                         'http://www.dailymotion.com/video/%s' % video_id
, 
 455                         DailymotionIE
.ie_key(), video_id
) 
 456                     video_ids
.add(video_id
) 
 458             if re
.search(self
._MORE
_PAGES
_INDICATOR
, webpage
) is None: 
 461     def _real_extract(self
, url
): 
 462         mobj 
= re
.match(self
._VALID
_URL
, url
) 
 463         user 
= mobj
.group('user') 
 464         webpage 
= self
._download
_webpage
( 
 465             'https://www.dailymotion.com/user/%s' % user
, user
) 
 466         full_user 
= unescapeHTML(self
._html
_search
_regex
( 
 467             r
'<a class="nav-image" title="([^"]+)" href="/%s">' % re
.escape(user
), 
 474             'entries': self
._extract
_entries
(user
),