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. orderedSet,
  16. parse_iso8601,
  17. str_to_int,
  18. unescapeHTML,
  19. )
  20. class DailymotionBaseInfoExtractor(InfoExtractor):
  21. @staticmethod
  22. def _build_request(url):
  23. """Build a request with the family filter disabled"""
  24. request = compat_urllib_request.Request(url)
  25. request.add_header('Cookie', 'family_filter=off; ff=off')
  26. return request
  27. def _download_webpage_handle_no_ff(self, url, *args, **kwargs):
  28. request = self._build_request(url)
  29. return self._download_webpage_handle(request, *args, **kwargs)
  30. def _download_webpage_no_ff(self, url, *args, **kwargs):
  31. request = self._build_request(url)
  32. return self._download_webpage(request, *args, **kwargs)
  33. class DailymotionIE(DailymotionBaseInfoExtractor):
  34. _VALID_URL = r'(?i)(?:https?://)?(?:(www|touch)\.)?dailymotion\.[a-z]{2,3}/(?:(embed|#)/)?video/(?P<id>[^/?_]+)'
  35. IE_NAME = 'dailymotion'
  36. _FORMATS = [
  37. ('stream_h264_ld_url', 'ld'),
  38. ('stream_h264_url', 'standard'),
  39. ('stream_h264_hq_url', 'hq'),
  40. ('stream_h264_hd_url', 'hd'),
  41. ('stream_h264_hd1080_url', 'hd180'),
  42. ]
  43. _TESTS = [
  44. {
  45. 'url': 'https://www.dailymotion.com/video/x2iuewm_steam-machine-models-pricing-listed-on-steam-store-ign-news_videogames',
  46. 'md5': '2137c41a8e78554bb09225b8eb322406',
  47. 'info_dict': {
  48. 'id': 'x2iuewm',
  49. 'ext': 'mp4',
  50. 'title': 'Steam Machine Models, Pricing Listed on Steam Store - IGN News',
  51. 'description': 'Several come bundled with the Steam Controller.',
  52. 'thumbnail': 're:^https?:.*\.(?:jpg|png)$',
  53. 'duration': 74,
  54. 'timestamp': 1425657362,
  55. 'upload_date': '20150306',
  56. 'uploader': 'IGN',
  57. 'uploader_id': 'xijv66',
  58. 'age_limit': 0,
  59. 'view_count': int,
  60. 'comment_count': int,
  61. }
  62. },
  63. # Vevo video
  64. {
  65. 'url': 'http://www.dailymotion.com/video/x149uew_katy-perry-roar-official_musi',
  66. 'info_dict': {
  67. 'title': 'Roar (Official)',
  68. 'id': 'USUV71301934',
  69. 'ext': 'mp4',
  70. 'uploader': 'Katy Perry',
  71. 'upload_date': '20130905',
  72. },
  73. 'params': {
  74. 'skip_download': True,
  75. },
  76. 'skip': 'VEVO is only available in some countries',
  77. },
  78. # age-restricted video
  79. {
  80. 'url': 'http://www.dailymotion.com/video/xyh2zz_leanna-decker-cyber-girl-of-the-year-desires-nude-playboy-plus_redband',
  81. 'md5': '0d667a7b9cebecc3c89ee93099c4159d',
  82. 'info_dict': {
  83. 'id': 'xyh2zz',
  84. 'ext': 'mp4',
  85. 'title': 'Leanna Decker - Cyber Girl Of The Year Desires Nude [Playboy Plus]',
  86. 'uploader': 'HotWaves1012',
  87. 'age_limit': 18,
  88. }
  89. }
  90. ]
  91. def _real_extract(self, url):
  92. video_id = self._match_id(url)
  93. webpage = self._download_webpage_no_ff(
  94. 'https://www.dailymotion.com/video/%s' % video_id, video_id)
  95. age_limit = self._rta_search(webpage)
  96. description = self._og_search_description(webpage) or self._html_search_meta(
  97. 'description', webpage, 'description')
  98. view_count = str_to_int(self._search_regex(
  99. [r'<meta[^>]+itemprop="interactionCount"[^>]+content="UserPlays:(\d+)"',
  100. r'video_views_count[^>]+>\s+([\d\.,]+)'],
  101. webpage, 'view count', fatal=False))
  102. comment_count = int_or_none(self._search_regex(
  103. r'<meta[^>]+itemprop="interactionCount"[^>]+content="UserComments:(\d+)"',
  104. webpage, 'comment count', fatal=False))
  105. player_v5 = self._search_regex(
  106. r'playerV5\s*=\s*dmp\.create\([^,]+?,\s*({.+?})\);',
  107. webpage, 'player v5', default=None)
  108. if player_v5:
  109. player = self._parse_json(player_v5, video_id)
  110. metadata = player['metadata']
  111. formats = []
  112. for quality, media_list in metadata['qualities'].items():
  113. for media in media_list:
  114. media_url = media.get('url')
  115. if not media_url:
  116. continue
  117. type_ = media.get('type')
  118. if type_ == 'application/vnd.lumberjack.manifest':
  119. continue
  120. if type_ == 'application/x-mpegURL' or determine_ext(media_url) == 'm3u8':
  121. formats.extend(self._extract_m3u8_formats(
  122. media_url, video_id, 'mp4', m3u8_id='hls'))
  123. else:
  124. f = {
  125. 'url': media_url,
  126. 'format_id': quality,
  127. }
  128. m = re.search(r'H264-(?P<width>\d+)x(?P<height>\d+)', media_url)
  129. if m:
  130. f.update({
  131. 'width': int(m.group('width')),
  132. 'height': int(m.group('height')),
  133. })
  134. formats.append(f)
  135. self._sort_formats(formats)
  136. title = metadata['title']
  137. duration = int_or_none(metadata.get('duration'))
  138. timestamp = int_or_none(metadata.get('created_time'))
  139. thumbnail = metadata.get('poster_url')
  140. uploader = metadata.get('owner', {}).get('screenname')
  141. uploader_id = metadata.get('owner', {}).get('id')
  142. subtitles = {}
  143. for subtitle_lang, subtitle in metadata.get('subtitles', {}).get('data', {}).items():
  144. subtitles[subtitle_lang] = [{
  145. 'ext': determine_ext(subtitle_url),
  146. 'url': subtitle_url,
  147. } for subtitle_url in subtitle.get('urls', [])]
  148. return {
  149. 'id': video_id,
  150. 'title': title,
  151. 'description': description,
  152. 'thumbnail': thumbnail,
  153. 'duration': duration,
  154. 'timestamp': timestamp,
  155. 'uploader': uploader,
  156. 'uploader_id': uploader_id,
  157. 'age_limit': age_limit,
  158. 'view_count': view_count,
  159. 'comment_count': comment_count,
  160. 'formats': formats,
  161. 'subtitles': subtitles,
  162. }
  163. # vevo embed
  164. vevo_id = self._search_regex(
  165. r'<link rel="video_src" href="[^"]*?vevo.com[^"]*?video=(?P<id>[\w]*)',
  166. webpage, 'vevo embed', default=None)
  167. if vevo_id:
  168. return self.url_result('vevo:%s' % vevo_id, 'Vevo')
  169. # fallback old player
  170. embed_page = self._download_webpage_no_ff(
  171. 'https://www.dailymotion.com/embed/video/%s' % video_id,
  172. video_id, 'Downloading embed page')
  173. timestamp = parse_iso8601(self._html_search_meta(
  174. 'video:release_date', webpage, 'upload date'))
  175. info = self._parse_json(
  176. self._search_regex(
  177. r'var info = ({.*?}),$', embed_page,
  178. 'video info', flags=re.MULTILINE),
  179. video_id)
  180. if info.get('error') is not None:
  181. msg = 'Couldn\'t get video, Dailymotion says: %s' % info['error']['title']
  182. raise ExtractorError(msg, expected=True)
  183. formats = []
  184. for (key, format_id) in self._FORMATS:
  185. video_url = info.get(key)
  186. if video_url is not None:
  187. m_size = re.search(r'H264-(\d+)x(\d+)', video_url)
  188. if m_size is not None:
  189. width, height = map(int_or_none, (m_size.group(1), m_size.group(2)))
  190. else:
  191. width, height = None, None
  192. formats.append({
  193. 'url': video_url,
  194. 'ext': 'mp4',
  195. 'format_id': format_id,
  196. 'width': width,
  197. 'height': height,
  198. })
  199. self._sort_formats(formats)
  200. # subtitles
  201. video_subtitles = self.extract_subtitles(video_id, webpage)
  202. title = self._og_search_title(webpage, default=None)
  203. if title is None:
  204. title = self._html_search_regex(
  205. r'(?s)<span\s+id="video_title"[^>]*>(.*?)</span>', webpage,
  206. 'title')
  207. return {
  208. 'id': video_id,
  209. 'formats': formats,
  210. 'uploader': info['owner.screenname'],
  211. 'timestamp': timestamp,
  212. 'title': title,
  213. 'description': description,
  214. 'subtitles': video_subtitles,
  215. 'thumbnail': info['thumbnail_url'],
  216. 'age_limit': age_limit,
  217. 'view_count': view_count,
  218. 'duration': info['duration']
  219. }
  220. def _get_subtitles(self, video_id, webpage):
  221. try:
  222. sub_list = self._download_webpage(
  223. 'https://api.dailymotion.com/video/%s/subtitles?fields=id,language,url' % video_id,
  224. video_id, note=False)
  225. except ExtractorError as err:
  226. self._downloader.report_warning('unable to download video subtitles: %s' % compat_str(err))
  227. return {}
  228. info = json.loads(sub_list)
  229. if (info['total'] > 0):
  230. sub_lang_list = dict((l['language'], [{'url': l['url'], 'ext': 'srt'}]) for l in info['list'])
  231. return sub_lang_list
  232. self._downloader.report_warning('video doesn\'t have subtitles')
  233. return {}
  234. class DailymotionPlaylistIE(DailymotionBaseInfoExtractor):
  235. IE_NAME = 'dailymotion:playlist'
  236. _VALID_URL = r'(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/playlist/(?P<id>.+?)/'
  237. _MORE_PAGES_INDICATOR = r'(?s)<div class="pages[^"]*">.*?<a\s+class="[^"]*?icon-arrow_right[^"]*?"'
  238. _PAGE_TEMPLATE = 'https://www.dailymotion.com/playlist/%s/%s'
  239. _TESTS = [{
  240. 'url': 'http://www.dailymotion.com/playlist/xv4bw_nqtv_sport/1#video=xl8v3q',
  241. 'info_dict': {
  242. 'title': 'SPORT',
  243. 'id': 'xv4bw_nqtv_sport',
  244. },
  245. 'playlist_mincount': 20,
  246. }]
  247. def _extract_entries(self, id):
  248. video_ids = []
  249. processed_urls = set()
  250. for pagenum in itertools.count(1):
  251. page_url = self._PAGE_TEMPLATE % (id, pagenum)
  252. webpage, urlh = self._download_webpage_handle_no_ff(
  253. page_url, id, 'Downloading page %s' % pagenum)
  254. if urlh.geturl() in processed_urls:
  255. self.report_warning('Stopped at duplicated page %s, which is the same as %s' % (
  256. page_url, urlh.geturl()), id)
  257. break
  258. processed_urls.add(urlh.geturl())
  259. video_ids.extend(re.findall(r'data-xid="(.+?)"', webpage))
  260. if re.search(self._MORE_PAGES_INDICATOR, webpage) is None:
  261. break
  262. return [self.url_result('http://www.dailymotion.com/video/%s' % video_id, 'Dailymotion')
  263. for video_id in orderedSet(video_ids)]
  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. }