You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

401 lines
15 KiB

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