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.

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