dailymotion.py 14 KB

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