dailymotion.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. import functools
  2. import json
  3. import re
  4. import urllib.parse
  5. from .common import InfoExtractor
  6. from ..networking.exceptions import HTTPError
  7. from ..utils import (
  8. ExtractorError,
  9. OnDemandPagedList,
  10. age_restricted,
  11. clean_html,
  12. int_or_none,
  13. traverse_obj,
  14. try_get,
  15. unescapeHTML,
  16. unsmuggle_url,
  17. urlencode_postdata,
  18. )
  19. class DailymotionBaseInfoExtractor(InfoExtractor):
  20. _FAMILY_FILTER = None
  21. _HEADERS = {
  22. 'Content-Type': 'application/json',
  23. 'Origin': 'https://www.dailymotion.com',
  24. }
  25. _NETRC_MACHINE = 'dailymotion'
  26. def _get_dailymotion_cookies(self):
  27. return self._get_cookies('https://www.dailymotion.com/')
  28. @staticmethod
  29. def _get_cookie_value(cookies, name):
  30. cookie = cookies.get(name)
  31. if cookie:
  32. return cookie.value
  33. def _set_dailymotion_cookie(self, name, value):
  34. self._set_cookie('www.dailymotion.com', name, value)
  35. def _real_initialize(self):
  36. cookies = self._get_dailymotion_cookies()
  37. ff = self._get_cookie_value(cookies, 'ff')
  38. self._FAMILY_FILTER = ff == 'on' if ff else age_restricted(18, self.get_param('age_limit'))
  39. self._set_dailymotion_cookie('ff', 'on' if self._FAMILY_FILTER else 'off')
  40. def _get_token(self, xid):
  41. cookies = self._get_dailymotion_cookies()
  42. token = self._get_cookie_value(cookies, 'access_token') or self._get_cookie_value(cookies, 'client_token')
  43. if token:
  44. return token
  45. data = {
  46. 'client_id': 'f1a362d288c1b98099c7',
  47. 'client_secret': 'eea605b96e01c796ff369935357eca920c5da4c5',
  48. }
  49. username, password = self._get_login_info()
  50. if username:
  51. data.update({
  52. 'grant_type': 'password',
  53. 'password': password,
  54. 'username': username,
  55. })
  56. else:
  57. data['grant_type'] = 'client_credentials'
  58. try:
  59. token = self._download_json(
  60. 'https://graphql.api.dailymotion.com/oauth/token',
  61. None, 'Downloading Access Token',
  62. data=urlencode_postdata(data))['access_token']
  63. except ExtractorError as e:
  64. if isinstance(e.cause, HTTPError) and e.cause.status == 400:
  65. raise ExtractorError(self._parse_json(
  66. e.cause.response.read().decode(), xid)['error_description'], expected=True)
  67. raise
  68. self._set_dailymotion_cookie('access_token' if username else 'client_token', token)
  69. return token
  70. def _call_api(self, object_type, xid, object_fields, note, filter_extra=None):
  71. if not self._HEADERS.get('Authorization'):
  72. self._HEADERS['Authorization'] = f'Bearer {self._get_token(xid)}'
  73. resp = self._download_json(
  74. 'https://graphql.api.dailymotion.com/', xid, note, data=json.dumps({
  75. 'query': '''{
  76. %s(xid: "%s"%s) {
  77. %s
  78. }
  79. }''' % (object_type, xid, ', ' + filter_extra if filter_extra else '', object_fields), # noqa: UP031
  80. }).encode(), headers=self._HEADERS)
  81. obj = resp['data'][object_type]
  82. if not obj:
  83. raise ExtractorError(resp['errors'][0]['message'], expected=True)
  84. return obj
  85. class DailymotionIE(DailymotionBaseInfoExtractor):
  86. _VALID_URL = r'''(?ix)
  87. https?://
  88. (?:
  89. (?:(?:www|touch|geo)\.)?dailymotion\.[a-z]{2,3}/(?:(?:(?:(?:embed|swf|\#)/)|player(?:/\w+)?\.html\?)?video|swf)|
  90. (?:www\.)?lequipe\.fr/video
  91. )
  92. [/=](?P<id>[^/?_&]+)(?:.+?\bplaylist=(?P<playlist_id>x[0-9a-z]+))?
  93. '''
  94. IE_NAME = 'dailymotion'
  95. _EMBED_REGEX = [r'<(?:(?:embed|iframe)[^>]+?src=|input[^>]+id=[\'"]dmcloudUrlEmissionSelect[\'"][^>]+value=)(["\'])(?P<url>(?:https?:)?//(?:www\.)?dailymotion\.com/(?:embed|swf)/video/.+?)\1']
  96. _TESTS = [{
  97. 'url': 'http://www.dailymotion.com/video/x5kesuj_office-christmas-party-review-jason-bateman-olivia-munn-t-j-miller_news',
  98. 'md5': '074b95bdee76b9e3654137aee9c79dfe',
  99. 'info_dict': {
  100. 'id': 'x5kesuj',
  101. 'ext': 'mp4',
  102. 'title': 'Office Christmas Party Review – Jason Bateman, Olivia Munn, T.J. Miller',
  103. 'description': 'Office Christmas Party Review - Jason Bateman, Olivia Munn, T.J. Miller',
  104. 'duration': 187,
  105. 'timestamp': 1493651285,
  106. 'upload_date': '20170501',
  107. 'uploader': 'Deadline',
  108. 'uploader_id': 'x1xm8ri',
  109. 'age_limit': 0,
  110. 'view_count': int,
  111. 'like_count': int,
  112. 'tags': ['hollywood', 'celeb', 'celebrity', 'movies', 'red carpet'],
  113. 'thumbnail': r're:https://(?:s[12]\.)dmcdn\.net/v/K456B1aXqIx58LKWQ/x1080',
  114. },
  115. }, {
  116. 'url': 'https://geo.dailymotion.com/player.html?video=x89eyek&mute=true',
  117. 'md5': 'e2f9717c6604773f963f069ca53a07f8',
  118. 'info_dict': {
  119. 'id': 'x89eyek',
  120. 'ext': 'mp4',
  121. 'title': "En quête d'esprit du 27/03/2022",
  122. 'description': 'md5:66542b9f4df2eb23f314fc097488e553',
  123. 'duration': 2756,
  124. 'timestamp': 1648383669,
  125. 'upload_date': '20220327',
  126. 'uploader': 'CNEWS',
  127. 'uploader_id': 'x24vth',
  128. 'age_limit': 0,
  129. 'view_count': int,
  130. 'like_count': int,
  131. 'tags': ['en_quete_d_esprit'],
  132. 'thumbnail': r're:https://(?:s[12]\.)dmcdn\.net/v/Tncwi1YNg_RUl7ueu/x1080',
  133. },
  134. }, {
  135. 'url': 'https://www.dailymotion.com/video/x2iuewm_steam-machine-models-pricing-listed-on-steam-store-ign-news_videogames',
  136. 'md5': '2137c41a8e78554bb09225b8eb322406',
  137. 'info_dict': {
  138. 'id': 'x2iuewm',
  139. 'ext': 'mp4',
  140. 'title': 'Steam Machine Models, Pricing Listed on Steam Store - IGN News',
  141. 'description': 'Several come bundled with the Steam Controller.',
  142. 'thumbnail': r're:^https?:.*\.(?:jpg|png)$',
  143. 'duration': 74,
  144. 'timestamp': 1425657362,
  145. 'upload_date': '20150306',
  146. 'uploader': 'IGN',
  147. 'uploader_id': 'xijv66',
  148. 'age_limit': 0,
  149. 'view_count': int,
  150. },
  151. 'skip': 'video gone',
  152. }, {
  153. # Vevo video
  154. 'url': 'http://www.dailymotion.com/video/x149uew_katy-perry-roar-official_musi',
  155. 'info_dict': {
  156. 'title': 'Roar (Official)',
  157. 'id': 'USUV71301934',
  158. 'ext': 'mp4',
  159. 'uploader': 'Katy Perry',
  160. 'upload_date': '20130905',
  161. },
  162. 'params': {
  163. 'skip_download': True,
  164. },
  165. 'skip': 'VEVO is only available in some countries',
  166. }, {
  167. # age-restricted video
  168. 'url': 'http://www.dailymotion.com/video/xyh2zz_leanna-decker-cyber-girl-of-the-year-desires-nude-playboy-plus_redband',
  169. 'md5': '0d667a7b9cebecc3c89ee93099c4159d',
  170. 'info_dict': {
  171. 'id': 'xyh2zz',
  172. 'ext': 'mp4',
  173. 'title': 'Leanna Decker - Cyber Girl Of The Year Desires Nude [Playboy Plus]',
  174. 'uploader': 'HotWaves1012',
  175. 'age_limit': 18,
  176. },
  177. 'skip': 'video gone',
  178. }, {
  179. # geo-restricted, player v5
  180. 'url': 'http://www.dailymotion.com/video/xhza0o',
  181. 'only_matching': True,
  182. }, {
  183. # with subtitles
  184. 'url': 'http://www.dailymotion.com/video/x20su5f_the-power-of-nightmares-1-the-rise-of-the-politics-of-fear-bbc-2004_news',
  185. 'only_matching': True,
  186. }, {
  187. 'url': 'http://www.dailymotion.com/swf/video/x3n92nf',
  188. 'only_matching': True,
  189. }, {
  190. 'url': 'http://www.dailymotion.com/swf/x3ss1m_funny-magic-trick-barry-and-stuart_fun',
  191. 'only_matching': True,
  192. }, {
  193. 'url': 'https://www.lequipe.fr/video/x791mem',
  194. 'only_matching': True,
  195. }, {
  196. 'url': 'https://www.lequipe.fr/video/k7MtHciueyTcrFtFKA2',
  197. 'only_matching': True,
  198. }, {
  199. 'url': 'https://www.dailymotion.com/video/x3z49k?playlist=xv4bw',
  200. 'only_matching': True,
  201. }, {
  202. 'url': 'https://geo.dailymotion.com/player/x86gw.html?video=k46oCapRs4iikoz9DWy',
  203. 'only_matching': True,
  204. }, {
  205. 'url': 'https://geo.dailymotion.com/player/xakln.html?video=x8mjju4&customConfig%5BcustomParams%5D=%2Ffr-fr%2Ftennis%2Fwimbledon-mens-singles%2Farticles-video',
  206. 'only_matching': True,
  207. }]
  208. _GEO_BYPASS = False
  209. _COMMON_MEDIA_FIELDS = '''description
  210. geoblockedCountries {
  211. allowed
  212. }
  213. xid'''
  214. @classmethod
  215. def _extract_embed_urls(cls, url, webpage):
  216. # https://developer.dailymotion.com/player#player-parameters
  217. yield from super()._extract_embed_urls(url, webpage)
  218. for mobj in re.finditer(
  219. r'(?s)DM\.player\([^,]+,\s*{.*?video[\'"]?\s*:\s*["\']?(?P<id>[0-9a-zA-Z]+).+?}\s*\);', webpage):
  220. yield from 'https://www.dailymotion.com/embed/video/' + mobj.group('id')
  221. def _real_extract(self, url):
  222. url, smuggled_data = unsmuggle_url(url)
  223. video_id, playlist_id = self._match_valid_url(url).groups()
  224. if playlist_id:
  225. if self._yes_playlist(playlist_id, video_id):
  226. return self.url_result(
  227. 'http://www.dailymotion.com/playlist/' + playlist_id,
  228. 'DailymotionPlaylist', playlist_id)
  229. password = self.get_param('videopassword')
  230. media = self._call_api(
  231. 'media', video_id, '''... on Video {
  232. %s
  233. stats {
  234. likes {
  235. total
  236. }
  237. views {
  238. total
  239. }
  240. }
  241. }
  242. ... on Live {
  243. %s
  244. audienceCount
  245. isOnAir
  246. }''' % (self._COMMON_MEDIA_FIELDS, self._COMMON_MEDIA_FIELDS), 'Downloading media JSON metadata', # noqa: UP031
  247. 'password: "{}"'.format(self.get_param('videopassword')) if password else None)
  248. xid = media['xid']
  249. metadata = self._download_json(
  250. 'https://www.dailymotion.com/player/metadata/video/' + xid,
  251. xid, 'Downloading metadata JSON',
  252. query=traverse_obj(smuggled_data, 'query') or {'app': 'com.dailymotion.neon'})
  253. error = metadata.get('error')
  254. if error:
  255. title = error.get('title') or error['raw_message']
  256. # See https://developer.dailymotion.com/api#access-error
  257. if error.get('code') == 'DM007':
  258. allowed_countries = try_get(media, lambda x: x['geoblockedCountries']['allowed'], list)
  259. self.raise_geo_restricted(msg=title, countries=allowed_countries)
  260. raise ExtractorError(
  261. f'{self.IE_NAME} said: {title}', expected=True)
  262. title = metadata['title']
  263. is_live = media.get('isOnAir')
  264. formats = []
  265. for quality, media_list in metadata['qualities'].items():
  266. for m in media_list:
  267. media_url = m.get('url')
  268. media_type = m.get('type')
  269. if not media_url or media_type == 'application/vnd.lumberjack.manifest':
  270. continue
  271. if media_type == 'application/x-mpegURL':
  272. formats.extend(self._extract_m3u8_formats(
  273. media_url, video_id, 'mp4', live=is_live, m3u8_id='hls', fatal=False))
  274. else:
  275. f = {
  276. 'url': media_url,
  277. 'format_id': 'http-' + quality,
  278. }
  279. m = re.search(r'/H264-(\d+)x(\d+)(?:-(60)/)?', media_url)
  280. if m:
  281. width, height, fps = map(int_or_none, m.groups())
  282. f.update({
  283. 'fps': fps,
  284. 'height': height,
  285. 'width': width,
  286. })
  287. formats.append(f)
  288. for f in formats:
  289. f['url'] = f['url'].split('#')[0]
  290. if not f.get('fps') and f['format_id'].endswith('@60'):
  291. f['fps'] = 60
  292. subtitles = {}
  293. subtitles_data = try_get(metadata, lambda x: x['subtitles']['data'], dict) or {}
  294. for subtitle_lang, subtitle in subtitles_data.items():
  295. subtitles[subtitle_lang] = [{
  296. 'url': subtitle_url,
  297. } for subtitle_url in subtitle.get('urls', [])]
  298. thumbnails = []
  299. for height, poster_url in metadata.get('posters', {}).items():
  300. thumbnails.append({
  301. 'height': int_or_none(height),
  302. 'id': height,
  303. 'url': poster_url,
  304. })
  305. owner = metadata.get('owner') or {}
  306. stats = media.get('stats') or {}
  307. get_count = lambda x: int_or_none(try_get(stats, lambda y: y[x + 's']['total']))
  308. return {
  309. 'id': video_id,
  310. 'title': title,
  311. 'description': clean_html(media.get('description')),
  312. 'thumbnails': thumbnails,
  313. 'duration': int_or_none(metadata.get('duration')) or None,
  314. 'timestamp': int_or_none(metadata.get('created_time')),
  315. 'uploader': owner.get('screenname'),
  316. 'uploader_id': owner.get('id') or metadata.get('screenname'),
  317. 'age_limit': 18 if metadata.get('explicit') else 0,
  318. 'tags': metadata.get('tags'),
  319. 'view_count': get_count('view') or int_or_none(media.get('audienceCount')),
  320. 'like_count': get_count('like'),
  321. 'formats': formats,
  322. 'subtitles': subtitles,
  323. 'is_live': is_live,
  324. }
  325. class DailymotionPlaylistBaseIE(DailymotionBaseInfoExtractor):
  326. _PAGE_SIZE = 100
  327. def _fetch_page(self, playlist_id, page):
  328. page += 1
  329. videos = self._call_api(
  330. self._OBJECT_TYPE, playlist_id,
  331. '''videos(allowExplicit: %s, first: %d, page: %d) {
  332. edges {
  333. node {
  334. xid
  335. url
  336. }
  337. }
  338. }''' % ('false' if self._FAMILY_FILTER else 'true', self._PAGE_SIZE, page),
  339. f'Downloading page {page}')['videos']
  340. for edge in videos['edges']:
  341. node = edge['node']
  342. yield self.url_result(
  343. node['url'], DailymotionIE.ie_key(), node['xid'])
  344. def _real_extract(self, url):
  345. playlist_id = self._match_id(url)
  346. entries = OnDemandPagedList(functools.partial(
  347. self._fetch_page, playlist_id), self._PAGE_SIZE)
  348. return self.playlist_result(
  349. entries, playlist_id)
  350. class DailymotionPlaylistIE(DailymotionPlaylistBaseIE):
  351. IE_NAME = 'dailymotion:playlist'
  352. _VALID_URL = r'(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/playlist/(?P<id>x[0-9a-z]+)'
  353. _TESTS = [{
  354. 'url': 'http://www.dailymotion.com/playlist/xv4bw_nqtv_sport/1#video=xl8v3q',
  355. 'info_dict': {
  356. 'id': 'xv4bw',
  357. },
  358. 'playlist_mincount': 20,
  359. }]
  360. _OBJECT_TYPE = 'collection'
  361. @classmethod
  362. def _extract_embed_urls(cls, url, webpage):
  363. # Look for embedded Dailymotion playlist player (#3822)
  364. for mobj in re.finditer(
  365. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?dailymotion\.[a-z]{2,3}/widget/jukebox\?.+?)\1',
  366. webpage):
  367. for p in re.findall(r'list\[\]=/playlist/([^/]+)/', unescapeHTML(mobj.group('url'))):
  368. yield f'//dailymotion.com/playlist/{p}'
  369. class DailymotionSearchIE(DailymotionPlaylistBaseIE):
  370. IE_NAME = 'dailymotion:search'
  371. _VALID_URL = r'https?://(?:www\.)?dailymotion\.[a-z]{2,3}/search/(?P<id>[^/?#]+)/videos'
  372. _PAGE_SIZE = 20
  373. _TESTS = [{
  374. 'url': 'http://www.dailymotion.com/search/king of turtles/videos',
  375. 'info_dict': {
  376. 'id': 'king of turtles',
  377. 'title': 'king of turtles',
  378. },
  379. 'playlist_mincount': 90,
  380. }]
  381. _SEARCH_QUERY = 'query SEARCH_QUERY( $query: String! $page: Int $limit: Int ) { search { videos( query: $query first: $limit page: $page ) { edges { node { xid } } } } } '
  382. def _call_search_api(self, term, page, note):
  383. if not self._HEADERS.get('Authorization'):
  384. self._HEADERS['Authorization'] = f'Bearer {self._get_token(term)}'
  385. resp = self._download_json(
  386. 'https://graphql.api.dailymotion.com/', None, note, data=json.dumps({
  387. 'operationName': 'SEARCH_QUERY',
  388. 'query': self._SEARCH_QUERY,
  389. 'variables': {
  390. 'limit': 20,
  391. 'page': page,
  392. 'query': term,
  393. },
  394. }).encode(), headers=self._HEADERS)
  395. obj = traverse_obj(resp, ('data', 'search', {dict}))
  396. if not obj:
  397. raise ExtractorError(
  398. traverse_obj(resp, ('errors', 0, 'message', {str})) or 'Could not fetch search data')
  399. return obj
  400. def _fetch_page(self, term, page):
  401. page += 1
  402. response = self._call_search_api(term, page, f'Searching "{term}" page {page}')
  403. for xid in traverse_obj(response, ('videos', 'edges', ..., 'node', 'xid')):
  404. yield self.url_result(f'https://www.dailymotion.com/video/{xid}', DailymotionIE, xid)
  405. def _real_extract(self, url):
  406. term = urllib.parse.unquote_plus(self._match_id(url))
  407. return self.playlist_result(
  408. OnDemandPagedList(functools.partial(self._fetch_page, term), self._PAGE_SIZE), term, term)
  409. class DailymotionUserIE(DailymotionPlaylistBaseIE):
  410. IE_NAME = 'dailymotion:user'
  411. _VALID_URL = r'https?://(?:www\.)?dailymotion\.[a-z]{2,3}/(?!(?:embed|swf|#|video|playlist|search)/)(?:(?:old/)?user/)?(?P<id>[^/?#]+)'
  412. _TESTS = [{
  413. 'url': 'https://www.dailymotion.com/user/nqtv',
  414. 'info_dict': {
  415. 'id': 'nqtv',
  416. },
  417. 'playlist_mincount': 152,
  418. }, {
  419. 'url': 'http://www.dailymotion.com/user/UnderProject',
  420. 'info_dict': {
  421. 'id': 'UnderProject',
  422. },
  423. 'playlist_mincount': 1000,
  424. 'skip': 'Takes too long time',
  425. }, {
  426. 'url': 'https://www.dailymotion.com/user/nqtv',
  427. 'info_dict': {
  428. 'id': 'nqtv',
  429. },
  430. 'playlist_mincount': 148,
  431. 'params': {
  432. 'age_limit': 0,
  433. },
  434. }]
  435. _OBJECT_TYPE = 'channel'