dailymotion.py 18 KB

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