2 from __future__ 
import unicode_literals
 
   8 from .common 
import InfoExtractor
 
   9 from ..compat 
import compat_HTTPError
 
  22 class DailymotionBaseInfoExtractor(InfoExtractor
): 
  25         'Content-Type': 'application/json', 
  26         'Origin': 'https://www.dailymotion.com', 
  28     _NETRC_MACHINE 
= 'dailymotion' 
  30     def _get_dailymotion_cookies(self
): 
  31         return self
._get
_cookies
('https://www.dailymotion.com/') 
  34     def _get_cookie_value(cookies
, name
): 
  35         cookie 
= cookies
.get('name') 
  39     def _set_dailymotion_cookie(self
, name
, value
): 
  40         self
._set
_cookie
('www.dailymotion.com', name
, value
) 
  42     def _real_initialize(self
): 
  43         cookies 
= self
._get
_dailymotion
_cookies
() 
  44         ff 
= self
._get
_cookie
_value
(cookies
, 'ff') 
  45         self
._FAMILY
_FILTER 
= ff 
== 'on' if ff 
else age_restricted(18, self
._downloader
.params
.get('age_limit')) 
  46         self
._set
_dailymotion
_cookie
('ff', 'on' if self
._FAMILY
_FILTER 
else 'off') 
  48     def _call_api(self
, object_type
, xid
, object_fields
, note
, filter_extra
=None): 
  49         if not self
._HEADERS
.get('Authorization'): 
  50             cookies 
= self
._get
_dailymotion
_cookies
() 
  51             token 
= self
._get
_cookie
_value
(cookies
, 'access_token') or self
._get
_cookie
_value
(cookies
, 'client_token') 
  54                     'client_id': 'f1a362d288c1b98099c7', 
  55                     'client_secret': 'eea605b96e01c796ff369935357eca920c5da4c5', 
  57                 username
, password 
= self
._get
_login
_info
() 
  60                         'grant_type': 'password', 
  65                     data
['grant_type'] = 'client_credentials' 
  67                     token 
= self
._download
_json
( 
  68                         'https://graphql.api.dailymotion.com/oauth/token', 
  69                         None, 'Downloading Access Token', 
  70                         data
=urlencode_postdata(data
))['access_token'] 
  71                 except ExtractorError 
as e
: 
  72                     if isinstance(e
.cause
, compat_HTTPError
) and e
.cause
.code 
== 400: 
  73                         raise ExtractorError(self
._parse
_json
( 
  74                             e
.cause
.read().decode(), xid
)['error_description'], expected
=True) 
  76                 self
._set
_dailymotion
_cookie
('access_token' if username 
else 'client_token', token
) 
  77             self
._HEADERS
['Authorization'] = 'Bearer ' + token
 
  79         resp 
= self
._download
_json
( 
  80             'https://graphql.api.dailymotion.com/', xid
, note
, data
=json
.dumps({ 
  85 }''' % (object_type
, xid
, ', ' + filter_extra 
if filter_extra 
else '', object_fields
), 
  86             }).encode(), headers
=self
._HEADERS
) 
  87         obj 
= resp
['data'][object_type
] 
  89             raise ExtractorError(resp
['errors'][0]['message'], expected
=True) 
  93 class DailymotionIE(DailymotionBaseInfoExtractor
): 
  94     _VALID_URL 
= r
'''(?ix) 
  97                             (?:(?:www|touch)\.)?dailymotion\.[a-z]{2,3}/(?:(?:(?:embed|swf|\#)/)?video|swf)| 
  98                             (?:www\.)?lequipe\.fr/video 
 100                         /(?P<id>[^/?_]+)(?:.+?\bplaylist=(?P<playlist_id>x[0-9a-z]+))? 
 102     IE_NAME 
= 'dailymotion' 
 104         'url': 'http://www.dailymotion.com/video/x5kesuj_office-christmas-party-review-jason-bateman-olivia-munn-t-j-miller_news', 
 105         'md5': '074b95bdee76b9e3654137aee9c79dfe', 
 109             'title': 'Office Christmas Party Review –  Jason Bateman, Olivia Munn, T.J. Miller', 
 110             'description': 'Office Christmas Party Review -  Jason Bateman, Olivia Munn, T.J. Miller', 
 112             'timestamp': 1493651285, 
 113             'upload_date': '20170501', 
 114             'uploader': 'Deadline', 
 115             'uploader_id': 'x1xm8ri', 
 119         'url': 'https://www.dailymotion.com/video/x2iuewm_steam-machine-models-pricing-listed-on-steam-store-ign-news_videogames', 
 120         'md5': '2137c41a8e78554bb09225b8eb322406', 
 124             'title': 'Steam Machine Models, Pricing Listed on Steam Store - IGN News', 
 125             'description': 'Several come bundled with the Steam Controller.', 
 126             'thumbnail': r
're:^https?:.*\.(?:jpg|png)$', 
 128             'timestamp': 1425657362, 
 129             'upload_date': '20150306', 
 131             'uploader_id': 'xijv66', 
 135         'skip': 'video gone', 
 138         'url': 'http://www.dailymotion.com/video/x149uew_katy-perry-roar-official_musi', 
 140             'title': 'Roar (Official)', 
 141             'id': 'USUV71301934', 
 143             'uploader': 'Katy Perry', 
 144             'upload_date': '20130905', 
 147             'skip_download': True, 
 149         'skip': 'VEVO is only available in some countries', 
 151         # age-restricted video 
 152         'url': 'http://www.dailymotion.com/video/xyh2zz_leanna-decker-cyber-girl-of-the-year-desires-nude-playboy-plus_redband', 
 153         'md5': '0d667a7b9cebecc3c89ee93099c4159d', 
 157             'title': 'Leanna Decker - Cyber Girl Of The Year Desires Nude [Playboy Plus]', 
 158             'uploader': 'HotWaves1012', 
 161         'skip': 'video gone', 
 163         # geo-restricted, player v5 
 164         'url': 'http://www.dailymotion.com/video/xhza0o', 
 165         'only_matching': True, 
 168         'url': 'http://www.dailymotion.com/video/x20su5f_the-power-of-nightmares-1-the-rise-of-the-politics-of-fear-bbc-2004_news', 
 169         'only_matching': True, 
 171         'url': 'http://www.dailymotion.com/swf/video/x3n92nf', 
 172         'only_matching': True, 
 174         'url': 'http://www.dailymotion.com/swf/x3ss1m_funny-magic-trick-barry-and-stuart_fun', 
 175         'only_matching': True, 
 177         'url': 'https://www.lequipe.fr/video/x791mem', 
 178         'only_matching': True, 
 180         'url': 'https://www.lequipe.fr/video/k7MtHciueyTcrFtFKA2', 
 181         'only_matching': True, 
 183         'url': 'https://www.dailymotion.com/video/x3z49k?playlist=xv4bw', 
 184         'only_matching': True, 
 187     _COMMON_MEDIA_FIELDS 
= '''description 
 188       geoblockedCountries { 
 194     def _extract_urls(webpage
): 
 196         # Look for embedded Dailymotion player 
 197         # https://developer.dailymotion.com/player#player-parameters 
 198         for mobj 
in re
.finditer( 
 199                 r
'<(?:(?:embed|iframe)[^>]+?src=|input[^>]+id=[\'"]dmcloudUrlEmissionSelect[\'"][^
>]+value
=)(["\'])(?P<url>(?:https?:)?//(?:www\.)?dailymotion\.com/(?:embed|swf)/video/.+?)\1', webpage): 
 200             urls.append(unescapeHTML(mobj.group('url'))) 
 201         for mobj in re.finditer( 
 202                 r'(?s)DM\.player\([^,]+,\s*{.*?video[\'"]?\s
*:\s
*["\']?(?P<id>[0-9a-zA-Z]+).+?}\s*\);', webpage): 
 203             urls.append('https://www.dailymotion.com/embed/video/' + mobj.group('id')) 
 206     def _real_extract(self, url): 
 207         video_id, playlist_id = re.match(self._VALID_URL, url).groups() 
 210             if not self._downloader.params.get('noplaylist'): 
 211                 self.to_screen('Downloading playlist %s - add --no-playlist to just download video' % playlist_id) 
 212                 return self.url_result( 
 213                     'http://www.dailymotion.com/playlist/' + playlist_id, 
 214                     'DailymotionPlaylist', playlist_id) 
 215             self.to_screen('Downloading just video %s because of --no-playlist' % video_id) 
 217         password = self._downloader.params.get('videopassword') 
 218         media = self._call_api( 
 219             'media', video_id, '''... on Video { 
 234     }''' % (self._COMMON_MEDIA_FIELDS, self._COMMON_MEDIA_FIELDS), 'Downloading media JSON metadata', 
 235             'password: "%s"' % self._downloader.params.get('videopassword') if password else None) 
 238         metadata = self._download_json( 
 239             'https://www.dailymotion.com/player/metadata/video/' + xid, 
 240             xid, 'Downloading metadata JSON', 
 241             query={'app': 'com.dailymotion.neon'}) 
 243         error = metadata.get('error') 
 245             title = error.get('title') or error['raw_message'] 
 246             # See https://developer.dailymotion.com/api#access-error 
 247             if error.get('code') == 'DM007': 
 248                 allowed_countries = try_get(media, lambda x: x['geoblockedCountries']['allowed'], list) 
 249                 self.raise_geo_restricted(msg=title, countries=allowed_countries) 
 250             raise ExtractorError( 
 251                 '%s said: %s' % (self.IE_NAME, title), expected=True) 
 253         title = metadata['title'] 
 254         is_live = media.get('isOnAir') 
 256         for quality, media_list in metadata['qualities'].items(): 
 258                 media_url = m.get('url') 
 259                 media_type = m.get('type') 
 260                 if not media_url or media_type == 'application/vnd.lumberjack.manifest': 
 262                 if media_type == 'application/x-mpegURL': 
 263                     formats.extend(self._extract_m3u8_formats( 
 264                         media_url, video_id, 'mp4', 
 265                         'm3u8' if is_live else 'm3u8_native', 
 266                         m3u8_id='hls', fatal=False)) 
 270                         'format_id': 'http-' + quality, 
 272                     m = re.search(r'/H264-(\d+)x(\d+)(?:-(60)/)?', media_url) 
 274                         width, height, fps = map(int_or_none, m.groups()) 
 282             f['url'] = f['url'].split('#')[0] 
 283             if not f.get('fps') and f['format_id'].endswith('@60'): 
 285         self._sort_formats(formats) 
 288         subtitles_data = try_get(metadata, lambda x: x['subtitles']['data'], dict) or {} 
 289         for subtitle_lang, subtitle in subtitles_data.items(): 
 290             subtitles[subtitle_lang] = [{ 
 292             } for subtitle_url in subtitle.get('urls', [])] 
 295         for height, poster_url in metadata.get('posters', {}).items(): 
 297                 'height': int_or_none(height), 
 302         owner = metadata.get('owner') or {} 
 303         stats = media.get('stats') or {} 
 304         get_count = lambda x: int_or_none(try_get(stats, lambda y: y[x + 's']['total'])) 
 308             'title': self._live_title(title) if is_live else title, 
 309             'description': clean_html(media.get('description')), 
 310             'thumbnails': thumbnails, 
 311             'duration': int_or_none(metadata.get('duration')) or None, 
 312             'timestamp': int_or_none(metadata.get('created_time')), 
 313             'uploader': owner.get('screenname'), 
 314             'uploader_id': owner.get('id') or metadata.get('screenname'), 
 315             'age_limit': 18 if metadata.get('explicit') else 0, 
 316             'tags': metadata.get('tags'), 
 317             'view_count': get_count('view') or int_or_none(media.get('audienceCount')), 
 318             'like_count': get_count('like'), 
 320             'subtitles': subtitles, 
 325 class DailymotionPlaylistBaseIE(DailymotionBaseInfoExtractor): 
 328     def _fetch_page(self, playlist_id, page): 
 330         videos = self._call_api( 
 331             self._OBJECT_TYPE, playlist_id, 
 332             '''videos(allowExplicit: %s, first: %d, page: %d) { 
 339     }''' % ('false' if self._FAMILY_FILTER else 'true', self._PAGE_SIZE, page), 
 340             'Downloading page %d' % page)['videos'] 
 341         for edge in videos['edges']: 
 343             yield self.url_result( 
 344                 node['url'], DailymotionIE.ie_key(), node['xid']) 
 346     def _real_extract(self, url): 
 347         playlist_id = self._match_id(url) 
 348         entries = OnDemandPagedList(functools.partial( 
 349             self._fetch_page, playlist_id), self._PAGE_SIZE) 
 350         return self.playlist_result( 
 351             entries, playlist_id) 
 354 class DailymotionPlaylistIE(DailymotionPlaylistBaseIE): 
 355     IE_NAME = 'dailymotion:playlist' 
 356     _VALID_URL = r'(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/playlist/(?P<id>x[0-9a-z]+)' 
 358         'url': 'http://www.dailymotion.com/playlist/xv4bw_nqtv_sport/1#video=xl8v3q', 
 362         'playlist_mincount': 20, 
 364     _OBJECT_TYPE = 'collection' 
 367 class DailymotionUserIE(DailymotionPlaylistBaseIE): 
 368     IE_NAME = 'dailymotion:user' 
 369     _VALID_URL = r'https?://(?:www\.)?dailymotion\.[a-z]{2,3}/(?!(?:embed|swf|#|video|playlist)/)(?:(?:old/)?user/)?(?P<id>[^/]+)' 
 371         'url': 'https://www.dailymotion.com/user/nqtv', 
 375         'playlist_mincount': 152, 
 377         'url': 'http://www.dailymotion.com/user/UnderProject', 
 379             'id': 'UnderProject', 
 381         'playlist_mincount': 1000, 
 382         'skip': 'Takes too long time', 
 384         'url': 'https://www.dailymotion.com/user/nqtv', 
 388         'playlist_mincount': 148, 
 393     _OBJECT_TYPE = 'channel'