dailymotion.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import re
  4. import json
  5. import itertools
  6. from .common import InfoExtractor
  7. from ..utils import (
  8. determine_ext,
  9. error_to_compat_str,
  10. ExtractorError,
  11. int_or_none,
  12. parse_iso8601,
  13. sanitized_Request,
  14. str_to_int,
  15. unescapeHTML,
  16. mimetype2ext,
  17. )
  18. class DailymotionBaseInfoExtractor(InfoExtractor):
  19. @staticmethod
  20. def _build_request(url):
  21. """Build a request with the family filter disabled"""
  22. request = sanitized_Request(url)
  23. request.add_header('Cookie', 'family_filter=off; ff=off')
  24. return request
  25. def _download_webpage_handle_no_ff(self, url, *args, **kwargs):
  26. request = self._build_request(url)
  27. return self._download_webpage_handle(request, *args, **kwargs)
  28. def _download_webpage_no_ff(self, url, *args, **kwargs):
  29. request = self._build_request(url)
  30. return self._download_webpage(request, *args, **kwargs)
  31. class DailymotionIE(DailymotionBaseInfoExtractor):
  32. _VALID_URL = r'(?i)https?://(?:(www|touch)\.)?dailymotion\.[a-z]{2,3}/(?:(?:(?:embed|swf|#)/)?video|swf)/(?P<id>[^/?_]+)'
  33. IE_NAME = 'dailymotion'
  34. _FORMATS = [
  35. ('stream_h264_ld_url', 'ld'),
  36. ('stream_h264_url', 'standard'),
  37. ('stream_h264_hq_url', 'hq'),
  38. ('stream_h264_hd_url', 'hd'),
  39. ('stream_h264_hd1080_url', 'hd180'),
  40. ]
  41. _TESTS = [{
  42. 'url': 'http://www.dailymotion.com/video/x5kesuj_office-christmas-party-review-jason-bateman-olivia-munn-t-j-miller_news',
  43. 'md5': '074b95bdee76b9e3654137aee9c79dfe',
  44. 'info_dict': {
  45. 'id': 'x5kesuj',
  46. 'ext': 'mp4',
  47. 'title': 'Office Christmas Party Review – Jason Bateman, Olivia Munn, T.J. Miller',
  48. 'description': 'Office Christmas Party Review - Jason Bateman, Olivia Munn, T.J. Miller',
  49. 'thumbnail': r're:^https?:.*\.(?:jpg|png)$',
  50. 'duration': 187,
  51. 'timestamp': 1493651285,
  52. 'upload_date': '20170501',
  53. 'uploader': 'Deadline',
  54. 'uploader_id': 'x1xm8ri',
  55. 'age_limit': 0,
  56. 'view_count': int,
  57. },
  58. }, {
  59. 'url': 'https://www.dailymotion.com/video/x2iuewm_steam-machine-models-pricing-listed-on-steam-store-ign-news_videogames',
  60. 'md5': '2137c41a8e78554bb09225b8eb322406',
  61. 'info_dict': {
  62. 'id': 'x2iuewm',
  63. 'ext': 'mp4',
  64. 'title': 'Steam Machine Models, Pricing Listed on Steam Store - IGN News',
  65. 'description': 'Several come bundled with the Steam Controller.',
  66. 'thumbnail': r're:^https?:.*\.(?:jpg|png)$',
  67. 'duration': 74,
  68. 'timestamp': 1425657362,
  69. 'upload_date': '20150306',
  70. 'uploader': 'IGN',
  71. 'uploader_id': 'xijv66',
  72. 'age_limit': 0,
  73. 'view_count': int,
  74. },
  75. 'skip': 'video gone',
  76. }, {
  77. # Vevo video
  78. 'url': 'http://www.dailymotion.com/video/x149uew_katy-perry-roar-official_musi',
  79. 'info_dict': {
  80. 'title': 'Roar (Official)',
  81. 'id': 'USUV71301934',
  82. 'ext': 'mp4',
  83. 'uploader': 'Katy Perry',
  84. 'upload_date': '20130905',
  85. },
  86. 'params': {
  87. 'skip_download': True,
  88. },
  89. 'skip': 'VEVO is only available in some countries',
  90. }, {
  91. # age-restricted video
  92. 'url': 'http://www.dailymotion.com/video/xyh2zz_leanna-decker-cyber-girl-of-the-year-desires-nude-playboy-plus_redband',
  93. 'md5': '0d667a7b9cebecc3c89ee93099c4159d',
  94. 'info_dict': {
  95. 'id': 'xyh2zz',
  96. 'ext': 'mp4',
  97. 'title': 'Leanna Decker - Cyber Girl Of The Year Desires Nude [Playboy Plus]',
  98. 'uploader': 'HotWaves1012',
  99. 'age_limit': 18,
  100. },
  101. 'skip': 'video gone',
  102. }, {
  103. # geo-restricted, player v5
  104. 'url': 'http://www.dailymotion.com/video/xhza0o',
  105. 'only_matching': True,
  106. }, {
  107. # with subtitles
  108. 'url': 'http://www.dailymotion.com/video/x20su5f_the-power-of-nightmares-1-the-rise-of-the-politics-of-fear-bbc-2004_news',
  109. 'only_matching': True,
  110. }, {
  111. 'url': 'http://www.dailymotion.com/swf/video/x3n92nf',
  112. 'only_matching': True,
  113. }, {
  114. 'url': 'http://www.dailymotion.com/swf/x3ss1m_funny-magic-trick-barry-and-stuart_fun',
  115. 'only_matching': True,
  116. }]
  117. @staticmethod
  118. def _extract_urls(webpage):
  119. # Look for embedded Dailymotion player
  120. matches = re.findall(
  121. r'<(?:(?:embed|iframe)[^>]+?src=|input[^>]+id=[\'"]dmcloudUrlEmissionSelect[\'"][^>]+value=)(["\'])(?P<url>(?:https?:)?//(?:www\.)?dailymotion\.com/(?:embed|swf)/video/.+?)\1', webpage)
  122. return list(map(lambda m: unescapeHTML(m[1]), matches))
  123. def _real_extract(self, url):
  124. video_id = self._match_id(url)
  125. webpage = self._download_webpage_no_ff(
  126. 'https://www.dailymotion.com/video/%s' % video_id, video_id)
  127. age_limit = self._rta_search(webpage)
  128. description = self._og_search_description(webpage) or self._html_search_meta(
  129. 'description', webpage, 'description')
  130. view_count_str = self._search_regex(
  131. (r'<meta[^>]+itemprop="interactionCount"[^>]+content="UserPlays:([\s\d,.]+)"',
  132. r'video_views_count[^>]+>\s+([\s\d\,.]+)'),
  133. webpage, 'view count', default=None)
  134. if view_count_str:
  135. view_count_str = re.sub(r'\s', '', view_count_str)
  136. view_count = str_to_int(view_count_str)
  137. comment_count = int_or_none(self._search_regex(
  138. r'<meta[^>]+itemprop="interactionCount"[^>]+content="UserComments:(\d+)"',
  139. webpage, 'comment count', default=None))
  140. player_v5 = self._search_regex(
  141. [r'buildPlayer\(({.+?})\);\n', # See https://github.com/rg3/youtube-dl/issues/7826
  142. r'playerV5\s*=\s*dmp\.create\([^,]+?,\s*({.+?})\);',
  143. r'buildPlayer\(({.+?})\);',
  144. r'var\s+config\s*=\s*({.+?});',
  145. # New layout regex (see https://github.com/rg3/youtube-dl/issues/13580)
  146. r'__PLAYER_CONFIG__\s*=\s*({.+?});'],
  147. webpage, 'player v5', default=None)
  148. if player_v5:
  149. player = self._parse_json(player_v5, video_id)
  150. metadata = player['metadata']
  151. self._check_error(metadata)
  152. formats = []
  153. for quality, media_list in metadata['qualities'].items():
  154. for media in media_list:
  155. media_url = media.get('url')
  156. if not media_url:
  157. continue
  158. type_ = media.get('type')
  159. if type_ == 'application/vnd.lumberjack.manifest':
  160. continue
  161. ext = mimetype2ext(type_) or determine_ext(media_url)
  162. if ext == 'm3u8':
  163. formats.extend(self._extract_m3u8_formats(
  164. media_url, video_id, 'mp4', preference=-1,
  165. m3u8_id='hls', fatal=False))
  166. elif ext == 'f4m':
  167. formats.extend(self._extract_f4m_formats(
  168. media_url, video_id, preference=-1, f4m_id='hds', fatal=False))
  169. else:
  170. f = {
  171. 'url': media_url,
  172. 'format_id': 'http-%s' % quality,
  173. 'ext': ext,
  174. }
  175. m = re.search(r'H264-(?P<width>\d+)x(?P<height>\d+)', media_url)
  176. if m:
  177. f.update({
  178. 'width': int(m.group('width')),
  179. 'height': int(m.group('height')),
  180. })
  181. formats.append(f)
  182. self._sort_formats(formats)
  183. title = metadata['title']
  184. duration = int_or_none(metadata.get('duration'))
  185. timestamp = int_or_none(metadata.get('created_time'))
  186. thumbnail = metadata.get('poster_url')
  187. uploader = metadata.get('owner', {}).get('screenname')
  188. uploader_id = metadata.get('owner', {}).get('id')
  189. subtitles = {}
  190. subtitles_data = metadata.get('subtitles', {}).get('data', {})
  191. if subtitles_data and isinstance(subtitles_data, dict):
  192. for subtitle_lang, subtitle in subtitles_data.items():
  193. subtitles[subtitle_lang] = [{
  194. 'ext': determine_ext(subtitle_url),
  195. 'url': subtitle_url,
  196. } for subtitle_url in subtitle.get('urls', [])]
  197. return {
  198. 'id': video_id,
  199. 'title': title,
  200. 'description': description,
  201. 'thumbnail': thumbnail,
  202. 'duration': duration,
  203. 'timestamp': timestamp,
  204. 'uploader': uploader,
  205. 'uploader_id': uploader_id,
  206. 'age_limit': age_limit,
  207. 'view_count': view_count,
  208. 'comment_count': comment_count,
  209. 'formats': formats,
  210. 'subtitles': subtitles,
  211. }
  212. # vevo embed
  213. vevo_id = self._search_regex(
  214. r'<link rel="video_src" href="[^"]*?vevo\.com[^"]*?video=(?P<id>[\w]*)',
  215. webpage, 'vevo embed', default=None)
  216. if vevo_id:
  217. return self.url_result('vevo:%s' % vevo_id, 'Vevo')
  218. # fallback old player
  219. embed_page = self._download_webpage_no_ff(
  220. 'https://www.dailymotion.com/embed/video/%s' % video_id,
  221. video_id, 'Downloading embed page')
  222. timestamp = parse_iso8601(self._html_search_meta(
  223. 'video:release_date', webpage, 'upload date'))
  224. info = self._parse_json(
  225. self._search_regex(
  226. r'var info = ({.*?}),$', embed_page,
  227. 'video info', flags=re.MULTILINE),
  228. video_id)
  229. self._check_error(info)
  230. formats = []
  231. for (key, format_id) in self._FORMATS:
  232. video_url = info.get(key)
  233. if video_url is not None:
  234. m_size = re.search(r'H264-(\d+)x(\d+)', video_url)
  235. if m_size is not None:
  236. width, height = map(int_or_none, (m_size.group(1), m_size.group(2)))
  237. else:
  238. width, height = None, None
  239. formats.append({
  240. 'url': video_url,
  241. 'ext': 'mp4',
  242. 'format_id': format_id,
  243. 'width': width,
  244. 'height': height,
  245. })
  246. self._sort_formats(formats)
  247. # subtitles
  248. video_subtitles = self.extract_subtitles(video_id, webpage)
  249. title = self._og_search_title(webpage, default=None)
  250. if title is None:
  251. title = self._html_search_regex(
  252. r'(?s)<span\s+id="video_title"[^>]*>(.*?)</span>', webpage,
  253. 'title')
  254. return {
  255. 'id': video_id,
  256. 'formats': formats,
  257. 'uploader': info['owner.screenname'],
  258. 'timestamp': timestamp,
  259. 'title': title,
  260. 'description': description,
  261. 'subtitles': video_subtitles,
  262. 'thumbnail': info['thumbnail_url'],
  263. 'age_limit': age_limit,
  264. 'view_count': view_count,
  265. 'duration': info['duration']
  266. }
  267. def _check_error(self, info):
  268. error = info.get('error')
  269. if info.get('error') is not None:
  270. title = error['title']
  271. # See https://developer.dailymotion.com/api#access-error
  272. if error.get('code') == 'DM007':
  273. self.raise_geo_restricted(msg=title)
  274. raise ExtractorError(
  275. '%s said: %s' % (self.IE_NAME, title), expected=True)
  276. def _get_subtitles(self, video_id, webpage):
  277. try:
  278. sub_list = self._download_webpage(
  279. 'https://api.dailymotion.com/video/%s/subtitles?fields=id,language,url' % video_id,
  280. video_id, note=False)
  281. except ExtractorError as err:
  282. self._downloader.report_warning('unable to download video subtitles: %s' % error_to_compat_str(err))
  283. return {}
  284. info = json.loads(sub_list)
  285. if (info['total'] > 0):
  286. sub_lang_list = dict((l['language'], [{'url': l['url'], 'ext': 'srt'}]) for l in info['list'])
  287. return sub_lang_list
  288. self._downloader.report_warning('video doesn\'t have subtitles')
  289. return {}
  290. class DailymotionPlaylistIE(DailymotionBaseInfoExtractor):
  291. IE_NAME = 'dailymotion:playlist'
  292. _VALID_URL = r'(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/playlist/(?P<id>[^/?#&]+)'
  293. _MORE_PAGES_INDICATOR = r'(?s)<div class="pages[^"]*">.*?<a\s+class="[^"]*?icon-arrow_right[^"]*?"'
  294. _PAGE_TEMPLATE = 'https://www.dailymotion.com/playlist/%s/%s'
  295. _TESTS = [{
  296. 'url': 'http://www.dailymotion.com/playlist/xv4bw_nqtv_sport/1#video=xl8v3q',
  297. 'info_dict': {
  298. 'title': 'SPORT',
  299. 'id': 'xv4bw_nqtv_sport',
  300. },
  301. 'playlist_mincount': 20,
  302. }]
  303. def _extract_entries(self, id):
  304. video_ids = set()
  305. processed_urls = set()
  306. for pagenum in itertools.count(1):
  307. page_url = self._PAGE_TEMPLATE % (id, pagenum)
  308. webpage, urlh = self._download_webpage_handle_no_ff(
  309. page_url, id, 'Downloading page %s' % pagenum)
  310. if urlh.geturl() in processed_urls:
  311. self.report_warning('Stopped at duplicated page %s, which is the same as %s' % (
  312. page_url, urlh.geturl()), id)
  313. break
  314. processed_urls.add(urlh.geturl())
  315. for video_id in re.findall(r'data-xid="(.+?)"', webpage):
  316. if video_id not in video_ids:
  317. yield self.url_result(
  318. 'http://www.dailymotion.com/video/%s' % video_id,
  319. DailymotionIE.ie_key(), video_id)
  320. video_ids.add(video_id)
  321. if re.search(self._MORE_PAGES_INDICATOR, webpage) is None:
  322. break
  323. def _real_extract(self, url):
  324. mobj = re.match(self._VALID_URL, url)
  325. playlist_id = mobj.group('id')
  326. webpage = self._download_webpage(url, playlist_id)
  327. return {
  328. '_type': 'playlist',
  329. 'id': playlist_id,
  330. 'title': self._og_search_title(webpage),
  331. 'entries': self._extract_entries(playlist_id),
  332. }
  333. class DailymotionUserIE(DailymotionPlaylistIE):
  334. IE_NAME = 'dailymotion:user'
  335. _VALID_URL = r'https?://(?:www\.)?dailymotion\.[a-z]{2,3}/(?!(?:embed|swf|#|video|playlist)/)(?:(?:old/)?user/)?(?P<user>[^/]+)'
  336. _PAGE_TEMPLATE = 'http://www.dailymotion.com/user/%s/%s'
  337. _TESTS = [{
  338. 'url': 'https://www.dailymotion.com/user/nqtv',
  339. 'info_dict': {
  340. 'id': 'nqtv',
  341. 'title': 'Rémi Gaillard',
  342. },
  343. 'playlist_mincount': 100,
  344. }, {
  345. 'url': 'http://www.dailymotion.com/user/UnderProject',
  346. 'info_dict': {
  347. 'id': 'UnderProject',
  348. 'title': 'UnderProject',
  349. },
  350. 'playlist_mincount': 1800,
  351. 'expected_warnings': [
  352. 'Stopped at duplicated page',
  353. ],
  354. 'skip': 'Takes too long time',
  355. }]
  356. def _real_extract(self, url):
  357. mobj = re.match(self._VALID_URL, url)
  358. user = mobj.group('user')
  359. webpage = self._download_webpage(
  360. 'https://www.dailymotion.com/user/%s' % user, user)
  361. full_user = unescapeHTML(self._html_search_regex(
  362. r'<a class="nav-image" title="([^"]+)" href="/%s">' % re.escape(user),
  363. webpage, 'user'))
  364. return {
  365. '_type': 'playlist',
  366. 'id': user,
  367. 'title': full_user,
  368. 'entries': self._extract_entries(user),
  369. }
  370. class DailymotionCloudIE(DailymotionBaseInfoExtractor):
  371. _VALID_URL_PREFIX = r'https?://api\.dmcloud\.net/(?:player/)?embed/'
  372. _VALID_URL = r'%s[^/]+/(?P<id>[^/?]+)' % _VALID_URL_PREFIX
  373. _VALID_EMBED_URL = r'%s[^/]+/[^\'"]+' % _VALID_URL_PREFIX
  374. _TESTS = [{
  375. # From http://www.francetvinfo.fr/economie/entreprises/les-entreprises-familiales-le-secret-de-la-reussite_933271.html
  376. # Tested at FranceTvInfo_2
  377. 'url': 'http://api.dmcloud.net/embed/4e7343f894a6f677b10006b4/556e03339473995ee145930c?auth=1464865870-0-jyhsm84b-ead4c701fb750cf9367bf4447167a3db&autoplay=1',
  378. 'only_matching': True,
  379. }, {
  380. # http://www.francetvinfo.fr/societe/larguez-les-amarres-le-cobaturage-se-developpe_980101.html
  381. 'url': 'http://api.dmcloud.net/player/embed/4e7343f894a6f677b10006b4/559545469473996d31429f06?auth=1467430263-0-90tglw2l-a3a4b64ed41efe48d7fccad85b8b8fda&autoplay=1',
  382. 'only_matching': True,
  383. }]
  384. @classmethod
  385. def _extract_dmcloud_url(cls, webpage):
  386. mobj = re.search(r'<iframe[^>]+src=[\'"](%s)[\'"]' % cls._VALID_EMBED_URL, webpage)
  387. if mobj:
  388. return mobj.group(1)
  389. mobj = re.search(
  390. r'<input[^>]+id=[\'"]dmcloudUrlEmissionSelect[\'"][^>]+value=[\'"](%s)[\'"]' % cls._VALID_EMBED_URL,
  391. webpage)
  392. if mobj:
  393. return mobj.group(1)
  394. def _real_extract(self, url):
  395. video_id = self._match_id(url)
  396. webpage = self._download_webpage_no_ff(url, video_id)
  397. title = self._html_search_regex(r'<title>([^>]+)</title>', webpage, 'title')
  398. video_info = self._parse_json(self._search_regex(
  399. r'var\s+info\s*=\s*([^;]+);', webpage, 'video info'), video_id)
  400. # TODO: parse ios_url, which is in fact a manifest
  401. video_url = video_info['mp4_url']
  402. return {
  403. 'id': video_id,
  404. 'url': video_url,
  405. 'title': title,
  406. 'thumbnail': video_info.get('thumbnail_url'),
  407. }