dailymotion.py 17 KB

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