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.

412 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. # geo-restricted, player v5
  90. {
  91. 'url': 'http://www.dailymotion.com/video/xhza0o',
  92. 'only_matching': True,
  93. }
  94. ]
  95. def _real_extract(self, url):
  96. video_id = self._match_id(url)
  97. webpage = self._download_webpage_no_ff(
  98. 'https://www.dailymotion.com/video/%s' % video_id, video_id)
  99. age_limit = self._rta_search(webpage)
  100. description = self._og_search_description(webpage) or self._html_search_meta(
  101. 'description', webpage, 'description')
  102. view_count = str_to_int(self._search_regex(
  103. [r'<meta[^>]+itemprop="interactionCount"[^>]+content="UserPlays:(\d+)"',
  104. r'video_views_count[^>]+>\s+([\d\.,]+)'],
  105. webpage, 'view count', fatal=False))
  106. comment_count = int_or_none(self._search_regex(
  107. r'<meta[^>]+itemprop="interactionCount"[^>]+content="UserComments:(\d+)"',
  108. webpage, 'comment count', fatal=False))
  109. player_v5 = self._search_regex(
  110. [r'buildPlayer\(({.+?})\);', r'playerV5\s*=\s*dmp\.create\([^,]+?,\s*({.+?})\);'],
  111. webpage, 'player v5', default=None)
  112. if player_v5:
  113. player = self._parse_json(player_v5, video_id)
  114. metadata = player['metadata']
  115. self._check_error(metadata)
  116. formats = []
  117. for quality, media_list in metadata['qualities'].items():
  118. for media in media_list:
  119. media_url = media.get('url')
  120. if not media_url:
  121. continue
  122. type_ = media.get('type')
  123. if type_ == 'application/vnd.lumberjack.manifest':
  124. continue
  125. if type_ == 'application/x-mpegURL' or determine_ext(media_url) == 'm3u8':
  126. formats.extend(self._extract_m3u8_formats(
  127. media_url, video_id, 'mp4', m3u8_id='hls'))
  128. else:
  129. f = {
  130. 'url': media_url,
  131. 'format_id': quality,
  132. }
  133. m = re.search(r'H264-(?P<width>\d+)x(?P<height>\d+)', media_url)
  134. if m:
  135. f.update({
  136. 'width': int(m.group('width')),
  137. 'height': int(m.group('height')),
  138. })
  139. formats.append(f)
  140. self._sort_formats(formats)
  141. title = metadata['title']
  142. duration = int_or_none(metadata.get('duration'))
  143. timestamp = int_or_none(metadata.get('created_time'))
  144. thumbnail = metadata.get('poster_url')
  145. uploader = metadata.get('owner', {}).get('screenname')
  146. uploader_id = metadata.get('owner', {}).get('id')
  147. subtitles = {}
  148. for subtitle_lang, subtitle in metadata.get('subtitles', {}).get('data', {}).items():
  149. subtitles[subtitle_lang] = [{
  150. 'ext': determine_ext(subtitle_url),
  151. 'url': subtitle_url,
  152. } for subtitle_url in subtitle.get('urls', [])]
  153. return {
  154. 'id': video_id,
  155. 'title': title,
  156. 'description': description,
  157. 'thumbnail': thumbnail,
  158. 'duration': duration,
  159. 'timestamp': timestamp,
  160. 'uploader': uploader,
  161. 'uploader_id': uploader_id,
  162. 'age_limit': age_limit,
  163. 'view_count': view_count,
  164. 'comment_count': comment_count,
  165. 'formats': formats,
  166. 'subtitles': subtitles,
  167. }
  168. # vevo embed
  169. vevo_id = self._search_regex(
  170. r'<link rel="video_src" href="[^"]*?vevo.com[^"]*?video=(?P<id>[\w]*)',
  171. webpage, 'vevo embed', default=None)
  172. if vevo_id:
  173. return self.url_result('vevo:%s' % vevo_id, 'Vevo')
  174. # fallback old player
  175. embed_page = self._download_webpage_no_ff(
  176. 'https://www.dailymotion.com/embed/video/%s' % video_id,
  177. video_id, 'Downloading embed page')
  178. timestamp = parse_iso8601(self._html_search_meta(
  179. 'video:release_date', webpage, 'upload date'))
  180. info = self._parse_json(
  181. self._search_regex(
  182. r'var info = ({.*?}),$', embed_page,
  183. 'video info', flags=re.MULTILINE),
  184. video_id)
  185. self._check_error(info)
  186. formats = []
  187. for (key, format_id) in self._FORMATS:
  188. video_url = info.get(key)
  189. if video_url is not None:
  190. m_size = re.search(r'H264-(\d+)x(\d+)', video_url)
  191. if m_size is not None:
  192. width, height = map(int_or_none, (m_size.group(1), m_size.group(2)))
  193. else:
  194. width, height = None, None
  195. formats.append({
  196. 'url': video_url,
  197. 'ext': 'mp4',
  198. 'format_id': format_id,
  199. 'width': width,
  200. 'height': height,
  201. })
  202. self._sort_formats(formats)
  203. # subtitles
  204. video_subtitles = self.extract_subtitles(video_id, webpage)
  205. title = self._og_search_title(webpage, default=None)
  206. if title is None:
  207. title = self._html_search_regex(
  208. r'(?s)<span\s+id="video_title"[^>]*>(.*?)</span>', webpage,
  209. 'title')
  210. return {
  211. 'id': video_id,
  212. 'formats': formats,
  213. 'uploader': info['owner.screenname'],
  214. 'timestamp': timestamp,
  215. 'title': title,
  216. 'description': description,
  217. 'subtitles': video_subtitles,
  218. 'thumbnail': info['thumbnail_url'],
  219. 'age_limit': age_limit,
  220. 'view_count': view_count,
  221. 'duration': info['duration']
  222. }
  223. def _check_error(self, info):
  224. if info.get('error') is not None:
  225. raise ExtractorError(
  226. '%s said: %s' % (self.IE_NAME, info['error']['title']), expected=True)
  227. def _get_subtitles(self, video_id, webpage):
  228. try:
  229. sub_list = self._download_webpage(
  230. 'https://api.dailymotion.com/video/%s/subtitles?fields=id,language,url' % video_id,
  231. video_id, note=False)
  232. except ExtractorError as err:
  233. self._downloader.report_warning('unable to download video subtitles: %s' % compat_str(err))
  234. return {}
  235. info = json.loads(sub_list)
  236. if (info['total'] > 0):
  237. sub_lang_list = dict((l['language'], [{'url': l['url'], 'ext': 'srt'}]) for l in info['list'])
  238. return sub_lang_list
  239. self._downloader.report_warning('video doesn\'t have subtitles')
  240. return {}
  241. class DailymotionPlaylistIE(DailymotionBaseInfoExtractor):
  242. IE_NAME = 'dailymotion:playlist'
  243. _VALID_URL = r'(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/playlist/(?P<id>.+?)/'
  244. _MORE_PAGES_INDICATOR = r'(?s)<div class="pages[^"]*">.*?<a\s+class="[^"]*?icon-arrow_right[^"]*?"'
  245. _PAGE_TEMPLATE = 'https://www.dailymotion.com/playlist/%s/%s'
  246. _TESTS = [{
  247. 'url': 'http://www.dailymotion.com/playlist/xv4bw_nqtv_sport/1#video=xl8v3q',
  248. 'info_dict': {
  249. 'title': 'SPORT',
  250. 'id': 'xv4bw_nqtv_sport',
  251. },
  252. 'playlist_mincount': 20,
  253. }]
  254. def _extract_entries(self, id):
  255. video_ids = set()
  256. processed_urls = set()
  257. for pagenum in itertools.count(1):
  258. page_url = self._PAGE_TEMPLATE % (id, pagenum)
  259. webpage, urlh = self._download_webpage_handle_no_ff(
  260. page_url, id, 'Downloading page %s' % pagenum)
  261. if urlh.geturl() in processed_urls:
  262. self.report_warning('Stopped at duplicated page %s, which is the same as %s' % (
  263. page_url, urlh.geturl()), id)
  264. break
  265. processed_urls.add(urlh.geturl())
  266. for video_id in re.findall(r'data-xid="(.+?)"', webpage):
  267. if video_id not in video_ids:
  268. yield self.url_result('http://www.dailymotion.com/video/%s' % video_id, 'Dailymotion')
  269. video_ids.add(video_id)
  270. if re.search(self._MORE_PAGES_INDICATOR, webpage) is None:
  271. break
  272. def _real_extract(self, url):
  273. mobj = re.match(self._VALID_URL, url)
  274. playlist_id = mobj.group('id')
  275. webpage = self._download_webpage(url, playlist_id)
  276. return {
  277. '_type': 'playlist',
  278. 'id': playlist_id,
  279. 'title': self._og_search_title(webpage),
  280. 'entries': self._extract_entries(playlist_id),
  281. }
  282. class DailymotionUserIE(DailymotionPlaylistIE):
  283. IE_NAME = 'dailymotion:user'
  284. _VALID_URL = r'https?://(?:www\.)?dailymotion\.[a-z]{2,3}/(?!(?:embed|#|video|playlist)/)(?:(?:old/)?user/)?(?P<user>[^/]+)'
  285. _PAGE_TEMPLATE = 'http://www.dailymotion.com/user/%s/%s'
  286. _TESTS = [{
  287. 'url': 'https://www.dailymotion.com/user/nqtv',
  288. 'info_dict': {
  289. 'id': 'nqtv',
  290. 'title': 'Rémi Gaillard',
  291. },
  292. 'playlist_mincount': 100,
  293. }, {
  294. 'url': 'http://www.dailymotion.com/user/UnderProject',
  295. 'info_dict': {
  296. 'id': 'UnderProject',
  297. 'title': 'UnderProject',
  298. },
  299. 'playlist_mincount': 1800,
  300. 'expected_warnings': [
  301. 'Stopped at duplicated page',
  302. ],
  303. 'skip': 'Takes too long time',
  304. }]
  305. def _real_extract(self, url):
  306. mobj = re.match(self._VALID_URL, url)
  307. user = mobj.group('user')
  308. webpage = self._download_webpage(
  309. 'https://www.dailymotion.com/user/%s' % user, user)
  310. full_user = unescapeHTML(self._html_search_regex(
  311. r'<a class="nav-image" title="([^"]+)" href="/%s">' % re.escape(user),
  312. webpage, 'user'))
  313. return {
  314. '_type': 'playlist',
  315. 'id': user,
  316. 'title': full_user,
  317. 'entries': self._extract_entries(user),
  318. }
  319. class DailymotionCloudIE(DailymotionBaseInfoExtractor):
  320. _VALID_URL_PREFIX = r'http://api\.dmcloud\.net/(?:player/)?embed/'
  321. _VALID_URL = r'%s[^/]+/(?P<id>[^/?]+)' % _VALID_URL_PREFIX
  322. _VALID_EMBED_URL = r'%s[^/]+/[^\'"]+' % _VALID_URL_PREFIX
  323. _TESTS = [{
  324. # From http://www.francetvinfo.fr/economie/entreprises/les-entreprises-familiales-le-secret-de-la-reussite_933271.html
  325. # Tested at FranceTvInfo_2
  326. 'url': 'http://api.dmcloud.net/embed/4e7343f894a6f677b10006b4/556e03339473995ee145930c?auth=1464865870-0-jyhsm84b-ead4c701fb750cf9367bf4447167a3db&autoplay=1',
  327. 'only_matching': True,
  328. }, {
  329. # http://www.francetvinfo.fr/societe/larguez-les-amarres-le-cobaturage-se-developpe_980101.html
  330. 'url': 'http://api.dmcloud.net/player/embed/4e7343f894a6f677b10006b4/559545469473996d31429f06?auth=1467430263-0-90tglw2l-a3a4b64ed41efe48d7fccad85b8b8fda&autoplay=1',
  331. 'only_matching': True,
  332. }]
  333. @classmethod
  334. def _extract_dmcloud_url(self, webpage):
  335. mobj = re.search(r'<iframe[^>]+src=[\'"](%s)[\'"]' % self._VALID_EMBED_URL, webpage)
  336. if mobj:
  337. return mobj.group(1)
  338. mobj = re.search(
  339. r'<input[^>]+id=[\'"]dmcloudUrlEmissionSelect[\'"][^>]+value=[\'"](%s)[\'"]' % self._VALID_EMBED_URL,
  340. webpage)
  341. if mobj:
  342. return mobj.group(1)
  343. def _real_extract(self, url):
  344. video_id = self._match_id(url)
  345. webpage = self._download_webpage_no_ff(url, video_id)
  346. title = self._html_search_regex(r'<title>([^>]+)</title>', webpage, 'title')
  347. video_info = self._parse_json(self._search_regex(
  348. r'var\s+info\s*=\s*([^;]+);', webpage, 'video info'), video_id)
  349. # TODO: parse ios_url, which is in fact a manifest
  350. video_url = video_info['mp4_url']
  351. return {
  352. 'id': video_id,
  353. 'url': video_url,
  354. 'title': title,
  355. 'thumbnail': video_info.get('thumbnail_url'),
  356. }