2 from __future__ 
import unicode_literals
 
  13 from .common 
import InfoExtractor
 
  14 from ..compat 
import compat_struct_pack
 
  33 class DailymotionBaseInfoExtractor(InfoExtractor
): 
  35     def _build_request(url
): 
  36         """Build a request with the family filter disabled""" 
  37         request 
= sanitized_Request(url
) 
  38         request
.add_header('Cookie', 'family_filter=off; ff=off') 
  41     def _download_webpage_handle_no_ff(self
, url
, *args
, **kwargs
): 
  42         request 
= self
._build
_request
(url
) 
  43         return self
._download
_webpage
_handle
(request
, *args
, **kwargs
) 
  45     def _download_webpage_no_ff(self
, url
, *args
, **kwargs
): 
  46         request 
= self
._build
_request
(url
) 
  47         return self
._download
_webpage
(request
, *args
, **kwargs
) 
  50 class DailymotionIE(DailymotionBaseInfoExtractor
): 
  51     _VALID_URL 
= r
'''(?ix) 
  54                             (?:(?:www|touch)\.)?dailymotion\.[a-z]{2,3}/(?:(?:(?:embed|swf|\#)/)?video|swf)| 
  55                             (?:www\.)?lequipe\.fr/video 
  59     IE_NAME 
= 'dailymotion' 
  62         ('stream_h264_ld_url', 'ld'), 
  63         ('stream_h264_url', 'standard'), 
  64         ('stream_h264_hq_url', 'hq'), 
  65         ('stream_h264_hd_url', 'hd'), 
  66         ('stream_h264_hd1080_url', 'hd180'), 
  70         'url': 'http://www.dailymotion.com/video/x5kesuj_office-christmas-party-review-jason-bateman-olivia-munn-t-j-miller_news', 
  71         'md5': '074b95bdee76b9e3654137aee9c79dfe', 
  75             'title': 'Office Christmas Party Review –  Jason Bateman, Olivia Munn, T.J. Miller', 
  76             'description': 'Office Christmas Party Review -  Jason Bateman, Olivia Munn, T.J. Miller', 
  77             'thumbnail': r
're:^https?:.*\.(?:jpg|png)$', 
  79             'timestamp': 1493651285, 
  80             'upload_date': '20170501', 
  81             'uploader': 'Deadline', 
  82             'uploader_id': 'x1xm8ri', 
  86         'url': 'https://www.dailymotion.com/video/x2iuewm_steam-machine-models-pricing-listed-on-steam-store-ign-news_videogames', 
  87         'md5': '2137c41a8e78554bb09225b8eb322406', 
  91             'title': 'Steam Machine Models, Pricing Listed on Steam Store - IGN News', 
  92             'description': 'Several come bundled with the Steam Controller.', 
  93             'thumbnail': r
're:^https?:.*\.(?:jpg|png)$', 
  95             'timestamp': 1425657362, 
  96             'upload_date': '20150306', 
  98             'uploader_id': 'xijv66', 
 102         'skip': 'video gone', 
 105         'url': 'http://www.dailymotion.com/video/x149uew_katy-perry-roar-official_musi', 
 107             'title': 'Roar (Official)', 
 108             'id': 'USUV71301934', 
 110             'uploader': 'Katy Perry', 
 111             'upload_date': '20130905', 
 114             'skip_download': True, 
 116         'skip': 'VEVO is only available in some countries', 
 118         # age-restricted video 
 119         'url': 'http://www.dailymotion.com/video/xyh2zz_leanna-decker-cyber-girl-of-the-year-desires-nude-playboy-plus_redband', 
 120         'md5': '0d667a7b9cebecc3c89ee93099c4159d', 
 124             'title': 'Leanna Decker - Cyber Girl Of The Year Desires Nude [Playboy Plus]', 
 125             'uploader': 'HotWaves1012', 
 128         'skip': 'video gone', 
 130         # geo-restricted, player v5 
 131         'url': 'http://www.dailymotion.com/video/xhza0o', 
 132         'only_matching': True, 
 135         'url': 'http://www.dailymotion.com/video/x20su5f_the-power-of-nightmares-1-the-rise-of-the-politics-of-fear-bbc-2004_news', 
 136         'only_matching': True, 
 138         'url': 'http://www.dailymotion.com/swf/video/x3n92nf', 
 139         'only_matching': True, 
 141         'url': 'http://www.dailymotion.com/swf/x3ss1m_funny-magic-trick-barry-and-stuart_fun', 
 142         'only_matching': True, 
 144         'url': 'https://www.lequipe.fr/video/x791mem', 
 145         'only_matching': True, 
 147         'url': 'https://www.lequipe.fr/video/k7MtHciueyTcrFtFKA2', 
 148         'only_matching': True, 
 152     def _extract_urls(webpage
): 
 154         # Look for embedded Dailymotion player 
 155         # https://developer.dailymotion.com/player#player-parameters 
 156         for mobj 
in re
.finditer( 
 157                 r
'<(?:(?:embed|iframe)[^>]+?src=|input[^>]+id=[\'"]dmcloudUrlEmissionSelect[\'"][^
>]+value
=)(["\'])(?P<url>(?:https?:)?//(?:www\.)?dailymotion\.com/(?:embed|swf)/video/.+?)\1', webpage): 
 158             urls.append(unescapeHTML(mobj.group('url'))) 
 159         for mobj in re.finditer( 
 160                 r'(?s)DM\.player\([^,]+,\s*{.*?video[\'"]?\s
*:\s
*["\']?(?P<id>[0-9a-zA-Z]+).+?}\s*\);', webpage): 
 161             urls.append('https://www.dailymotion.com/embed/video/' + mobj.group('id')) 
 164     def _real_extract(self, url): 
 165         video_id = self._match_id(url) 
 167         webpage = self._download_webpage_no_ff( 
 168             'https://www.dailymotion.com/video/%s' % video_id, video_id) 
 170         age_limit = self._rta_search(webpage) 
 172         description = self._og_search_description( 
 173             webpage, default=None) or self._html_search_meta( 
 174             'description', webpage, 'description') 
 176         view_count_str = self._search_regex( 
 177             (r'<meta[^>]+itemprop="interactionCount
"[^>]+content="UserPlays
:([\s\d
,.]+)"', 
 178              r'video_views_count[^>]+>\s+([\s\d\,.]+)'), 
 179             webpage, 'view count', default=None) 
 181             view_count_str = re.sub(r'\s', '', view_count_str) 
 182         view_count = str_to_int(view_count_str) 
 183         comment_count = int_or_none(self._search_regex( 
 184             r'<meta[^>]+itemprop="interactionCount
"[^>]+content="UserComments
:(\d
+)"', 
 185             webpage, 'comment count', default=None)) 
 187         player_v5 = self._search_regex( 
 188             [r'buildPlayer\(({.+?})\);\n',  # See https://github.com/ytdl-org/youtube-dl/issues/7826 
 189              r'playerV5\s*=\s*dmp\.create\([^,]+?,\s*({.+?})\);', 
 190              r'buildPlayer\(({.+?})\);', 
 191              r'var\s+config\s*=\s*({.+?});', 
 192              # New layout regex (see https://github.com/ytdl-org/youtube-dl/issues/13580) 
 193              r'__PLAYER_CONFIG__\s*=\s*({.+?});'], 
 194             webpage, 'player v5', default=None) 
 196             player = self._parse_json(player_v5, video_id, fatal=False) or {} 
 197             metadata = try_get(player, lambda x: x['metadata'], dict) 
 199                 metadata_url = url_or_none(try_get( 
 200                     player, lambda x: x['context']['metadata_template_url1'])) 
 202                     metadata_url = metadata_url.replace(':videoId', video_id) 
 204                     metadata_url = update_url_query( 
 205                         'https://www.dailymotion.com/player/metadata/video/%s' 
 208                             'integration': 'inline', 
 211                 metadata = self._download_json( 
 212                     metadata_url, video_id, 'Downloading metadata JSON') 
 214             if try_get(metadata, lambda x: x['error']['type']) == 'password_protected': 
 215                 password = self._downloader.params.get('videopassword') 
 217                     r = int(metadata['id'][1:], 36) 
 218                     us64e = lambda x: base64.urlsafe_b64encode(x).decode().strip('=') 
 219                     t = ''.join(random.choice(string.ascii_letters) for i in range(10)) 
 220                     n = us64e(compat_struct_pack('I', r)) 
 221                     i = us64e(hashlib.md5(('%s%d%s' % (password, r, t)).encode()).digest()) 
 222                     metadata = self._download_json( 
 223                         'http://www.dailymotion.com/player/metadata/video/p' + i + t + n, video_id) 
 225             self._check_error(metadata) 
 228             for quality, media_list in metadata['qualities'].items(): 
 229                 for media in media_list: 
 230                     media_url = media.get('url') 
 233                     type_ = media.get('type') 
 234                     if type_ == 'application/vnd.lumberjack.manifest': 
 236                     ext = mimetype2ext(type_) or determine_ext(media_url) 
 238                         m3u8_formats = self._extract_m3u8_formats( 
 239                             media_url, video_id, 'mp4', preference=-1, 
 240                             m3u8_id='hls', fatal=False) 
 241                         for f in m3u8_formats: 
 242                             f['url'] = f['url'].split('#')[0] 
 245                         formats.extend(self._extract_f4m_formats( 
 246                             media_url, video_id, preference=-1, f4m_id='hds', fatal=False)) 
 250                             'format_id': 'http-%s' % quality, 
 253                         m = re.search(r'H264-(?P<width>\d+)x(?P<height>\d+)', media_url) 
 256                                 'width': int(m.group('width')), 
 257                                 'height': int(m.group('height')), 
 260             self._sort_formats(formats) 
 262             title = metadata['title'] 
 263             duration = int_or_none(metadata.get('duration')) 
 264             timestamp = int_or_none(metadata.get('created_time')) 
 265             thumbnail = metadata.get('poster_url') 
 266             uploader = metadata.get('owner', {}).get('screenname') 
 267             uploader_id = metadata.get('owner', {}).get('id') 
 270             subtitles_data = metadata.get('subtitles', {}).get('data', {}) 
 271             if subtitles_data and isinstance(subtitles_data, dict): 
 272                 for subtitle_lang, subtitle in subtitles_data.items(): 
 273                     subtitles[subtitle_lang] = [{ 
 274                         'ext': determine_ext(subtitle_url), 
 276                     } for subtitle_url in subtitle.get('urls', [])] 
 281                 'description': description, 
 282                 'thumbnail': thumbnail, 
 283                 'duration': duration, 
 284                 'timestamp': timestamp, 
 285                 'uploader': uploader, 
 286                 'uploader_id': uploader_id, 
 287                 'age_limit': age_limit, 
 288                 'view_count': view_count, 
 289                 'comment_count': comment_count, 
 291                 'subtitles': subtitles, 
 295         vevo_id = self._search_regex( 
 296             r'<link rel="video_src
" href="[^
"]*?vevo\.com[^"]*?video
=(?P
<id>[\w
]*)', 
 297             webpage, 'vevo embed
', default=None) 
 299             return self.url_result('vevo
:%s' % vevo_id, 'Vevo
') 
 301         # fallback old player 
 302         embed_page = self._download_webpage_no_ff( 
 303             'https
://www
.dailymotion
.com
/embed
/video
/%s' % video_id, 
 304             video_id, 'Downloading embed page
') 
 306         timestamp = parse_iso8601(self._html_search_meta( 
 307             'video
:release_date
', webpage, 'upload date
')) 
 309         info = self._parse_json( 
 311                 r'var info 
= ({.*?
}),$
', embed_page, 
 312                 'video info
', flags=re.MULTILINE), 
 315         self._check_error(info) 
 318         for (key, format_id) in self._FORMATS: 
 319             video_url = info.get(key) 
 320             if video_url is not None: 
 321                 m_size = re.search(r'H264
-(\d
+)x(\d
+)', video_url) 
 322                 if m_size is not None: 
 323                     width, height = map(int_or_none, (m_size.group(1), m_size.group(2))) 
 325                     width, height = None, None 
 329                     'format_id
': format_id, 
 333         self._sort_formats(formats) 
 336         video_subtitles = self.extract_subtitles(video_id, webpage) 
 338         title = self._og_search_title(webpage, default=None) 
 340             title = self._html_search_regex( 
 341                 r'(?s
)<span\s
+id="video_title"[^
>]*>(.*?
)</span
>', webpage, 
 347             'uploader
': info['owner
.screenname
'], 
 348             'timestamp
': timestamp, 
 350             'description
': description, 
 351             'subtitles
': video_subtitles, 
 352             'thumbnail
': info['thumbnail_url
'], 
 353             'age_limit
': age_limit, 
 354             'view_count
': view_count, 
 355             'duration
': info['duration
'] 
 358     def _check_error(self, info): 
 359         error = info.get('error
') 
 361             title = error.get('title
') or error['message
'] 
 362             # See https://developer.dailymotion.com/api#access-error 
 363             if error.get('code
') == 'DM007
': 
 364                 self.raise_geo_restricted(msg=title) 
 365             raise ExtractorError( 
 366                 '%s said
: %s' % (self.IE_NAME, title), expected=True) 
 368     def _get_subtitles(self, video_id, webpage): 
 370             sub_list = self._download_webpage( 
 371                 'https
://api
.dailymotion
.com
/video
/%s/subtitles?fields
=id,language
,url
' % video_id, 
 372                 video_id, note=False) 
 373         except ExtractorError as err: 
 374             self._downloader.report_warning('unable to download video subtitles
: %s' % error_to_compat_str(err)) 
 376         info = json.loads(sub_list) 
 377         if (info['total
'] > 0): 
 378             sub_lang_list = dict((l['language
'], [{'url
': l['url
'], 'ext
': 'srt
'}]) for l in info['list']) 
 380         self._downloader.report_warning('video doesn
\'t have subtitles
') 
 384 class DailymotionPlaylistIE(DailymotionBaseInfoExtractor): 
 385     IE_NAME = 'dailymotion
:playlist
' 
 386     _VALID_URL = r'(?
:https?
://)?
(?
:www\
.)?dailymotion\
.[a
-z
]{2,3}/playlist
/(?P
<id>x
[0-9a
-z
]+)' 
 388         'url
': 'http
://www
.dailymotion
.com
/playlist
/xv4bw_nqtv_sport
/1#video=xl8v3q', 
 393         'playlist_mincount': 20, 
 397     def _fetch_page(self
, playlist_id
, authorizaion
, page
): 
 399         videos 
= self
._download
_json
( 
 400             'https://graphql.api.dailymotion.com', 
 401             playlist_id
, 'Downloading page %d' % page
, 
 404   collection(xid: "%s") { 
 405     videos(first: %d, page: %d) { 
 418 }''' % (playlist_id
, self
._PAGE
_SIZE
, page
) 
 419             }).encode(), headers
={ 
 420                 'Authorization': authorizaion
, 
 421                 'Origin': 'https://www.dailymotion.com', 
 422             })['data']['collection']['videos'] 
 423         for edge 
in videos
['edges']: 
 425             yield self
.url_result( 
 426                 node
['url'], DailymotionIE
.ie_key(), node
['xid']) 
 428     def _real_extract(self
, url
): 
 429         playlist_id 
= self
._match
_id
(url
) 
 430         webpage 
= self
._download
_webpage
(url
, playlist_id
) 
 431         api 
= self
._parse
_json
(self
._search
_regex
( 
 432             r
'__PLAYER_CONFIG__\s*=\s*({.+?});', 
 433             webpage
, 'player config'), playlist_id
)['context']['api'] 
 434         auth 
= self
._download
_json
( 
 435             api
.get('auth_url', 'https://graphql.api.dailymotion.com/oauth/token'), 
 436             playlist_id
, data
=urlencode_postdata({ 
 437                 'client_id': api
.get('client_id', 'f1a362d288c1b98099c7'), 
 438                 'client_secret': api
.get('client_secret', 'eea605b96e01c796ff369935357eca920c5da4c5'), 
 439                 'grant_type': 'client_credentials', 
 441         authorizaion 
= '%s %s' % (auth
.get('token_type', 'Bearer'), auth
['access_token']) 
 442         entries 
= OnDemandPagedList(functools
.partial( 
 443             self
._fetch
_page
, playlist_id
, authorizaion
), self
._PAGE
_SIZE
) 
 444         return self
.playlist_result( 
 445             entries
, playlist_id
, 
 446             self
._og
_search
_title
(webpage
)) 
 449 class DailymotionUserIE(DailymotionBaseInfoExtractor
): 
 450     IE_NAME 
= 'dailymotion:user' 
 451     _VALID_URL 
= r
'https?://(?:www\.)?dailymotion\.[a-z]{2,3}/(?!(?:embed|swf|#|video|playlist)/)(?:(?:old/)?user/)?(?P<user>[^/]+)' 
 452     _MORE_PAGES_INDICATOR 
= r
'(?s)<div class="pages[^"]*">.*?<a\s+class="[^"]*?icon-arrow_right[^"]*?"' 
 453     _PAGE_TEMPLATE 
= 'http://www.dailymotion.com/user/%s/%s' 
 455         'url': 'https://www.dailymotion.com/user/nqtv', 
 458             'title': 'Rémi Gaillard', 
 460         'playlist_mincount': 100, 
 462         'url': 'http://www.dailymotion.com/user/UnderProject', 
 464             'id': 'UnderProject', 
 465             'title': 'UnderProject', 
 467         'playlist_mincount': 1800, 
 468         'expected_warnings': [ 
 469             'Stopped at duplicated page', 
 471         'skip': 'Takes too long time', 
 474     def _extract_entries(self
, id): 
 476         processed_urls 
= set() 
 477         for pagenum 
in itertools
.count(1): 
 478             page_url 
= self
._PAGE
_TEMPLATE 
% (id, pagenum
) 
 479             webpage
, urlh 
= self
._download
_webpage
_handle
_no
_ff
( 
 480                 page_url
, id, 'Downloading page %s' % pagenum
) 
 481             if urlh
.geturl() in processed_urls
: 
 482                 self
.report_warning('Stopped at duplicated page %s, which is the same as %s' % ( 
 483                     page_url
, urlh
.geturl()), id) 
 486             processed_urls
.add(urlh
.geturl()) 
 488             for video_id 
in re
.findall(r
'data-xid="(.+?)"', webpage
): 
 489                 if video_id 
not in video_ids
: 
 490                     yield self
.url_result( 
 491                         'http://www.dailymotion.com/video/%s' % video_id
, 
 492                         DailymotionIE
.ie_key(), video_id
) 
 493                     video_ids
.add(video_id
) 
 495             if re
.search(self
._MORE
_PAGES
_INDICATOR
, webpage
) is None: 
 498     def _real_extract(self
, url
): 
 499         mobj 
= re
.match(self
._VALID
_URL
, url
) 
 500         user 
= mobj
.group('user') 
 501         webpage 
= self
._download
_webpage
( 
 502             'https://www.dailymotion.com/user/%s' % user
, user
) 
 503         full_user 
= unescapeHTML(self
._html
_search
_regex
( 
 504             r
'<a class="nav-image" title="([^"]+)" href="/%s">' % re
.escape(user
), 
 511             'entries': self
._extract
_entries
(user
),