Merge pull request #1 from phihag/youporn-hd-pr
[youtube-dl] / youtube_dl / extractor / youporn.py
1 import json
2 import os
3 import re
4 import sys
5
6 from .common import InfoExtractor
7 from ..utils import (
8     compat_str,
9     compat_urllib_parse_urlparse,
10     compat_urllib_request,
11
12     ExtractorError,
13     unescapeHTML,
14     unified_strdate,
15 )
16 from ..aes import (
17     aes_decrypt_text
18 )
19
20 class YouPornIE(InfoExtractor):
21     _VALID_URL = r'^(?:https?://)?(?:\w+\.)?youporn\.com/watch/(?P<videoid>[0-9]+)/(?P<title>[^/]+)'
22     _TEST = {
23         u'url': u'http://www.youporn.com/watch/505835/sex-ed-is-it-safe-to-masturbate-daily/',
24         u'file': u'505835.mp4',
25         u'md5': u'71ec5fcfddacf80f495efa8b6a8d9a89',
26         u'info_dict': {
27             u"upload_date": u"20101221", 
28             u"description": u"Love & Sex Answers: http://bit.ly/DanAndJenn -- Is It Unhealthy To Masturbate Daily?", 
29             u"uploader": u"Ask Dan And Jennifer", 
30             u"title": u"Sex Ed: Is It Safe To Masturbate Daily?"
31         }
32     }
33
34     def _print_formats(self, formats):
35         """Print all available formats"""
36         print(u'Available formats:')
37         print(u'ext\t\tformat')
38         print(u'---------------------------------')
39         for format in formats:
40             print(u'%s\t\t%s'  % (format['ext'], format['format']))
41
42     def _specific(self, req_format, formats):
43         for x in formats:
44             if x["format"] == req_format:
45                 return x
46         return None
47
48     def _real_extract(self, url):
49         mobj = re.match(self._VALID_URL, url)
50         video_id = mobj.group('videoid')
51
52         req = compat_urllib_request.Request(url)
53         req.add_header('Cookie', 'age_verified=1')
54         webpage = self._download_webpage(req, video_id)
55
56         # Get JSON parameters
57         json_params = self._search_regex(r'var currentVideo = new Video\((.*)\);', webpage, u'JSON parameters')
58         try:
59             params = json.loads(json_params)
60         except:
61             raise ExtractorError(u'Invalid JSON')
62
63         self.report_extraction(video_id)
64         try:
65             video_title = params['title']
66             upload_date = unified_strdate(params['release_date_f'])
67             video_description = params['description']
68             video_uploader = params['submitted_by']
69             thumbnail = params['thumbnails'][0]['image']
70         except KeyError:
71             raise ExtractorError('Missing JSON parameter: ' + sys.exc_info()[1])
72
73         # Get all of the formats available
74         DOWNLOAD_LIST_RE = r'(?s)<ul class="downloadList">(?P<download_list>.*?)</ul>'
75         download_list_html = self._search_regex(DOWNLOAD_LIST_RE,
76             webpage, u'download list').strip()
77
78         # Get all of the links from the page
79         LINK_RE = r'(?s)<a href="(?P<url>[^"]+)">'
80         links = re.findall(LINK_RE, download_list_html)
81         
82         # Get link of hd video
83         encrypted_video_url = self._html_search_regex(
84             r'var encrypted(?:Quality[0-9]+)?URL = \'(?P<encrypted_video_url>[a-zA-Z0-9+/]+={0,2})\';',
85             webpage, u'encrypted_video_url')
86         video_url = aes_decrypt_text(encrypted_video_url, video_title, 32)
87         print(video_url)
88         assert isinstance(video_url, compat_str)
89         if video_url.split('/')[6].split('_')[0] == u'720p': # only add if 720p to avoid duplicates
90             links = [video_url] + links
91         
92         if not links:
93             raise ExtractorError(u'ERROR: no known formats available for video')
94
95         self.to_screen(u'Links found: %d' % len(links))
96
97         formats = []
98         for link in links:
99
100             # A link looks like this:
101             # http://cdn1.download.youporn.phncdn.com/201210/31/8004515/480p_370k_8004515/YouPorn%20-%20Nubile%20Films%20The%20Pillow%20Fight.mp4?nvb=20121113051249&nva=20121114051249&ir=1200&sr=1200&hash=014b882080310e95fb6a0
102             # A path looks like this:
103             # /201210/31/8004515/480p_370k_8004515/YouPorn%20-%20Nubile%20Films%20The%20Pillow%20Fight.mp4
104             video_url = unescapeHTML( link )
105             path = compat_urllib_parse_urlparse( video_url ).path
106             extension = os.path.splitext( path )[1][1:]
107             format = path.split('/')[4].split('_')[:2]
108             # size = format[0]
109             # bitrate = format[1]
110             format = "-".join( format )
111             # title = u'%s-%s-%s' % (video_title, size, bitrate)
112
113             formats.append({
114                 'id': video_id,
115                 'url': video_url,
116                 'uploader': video_uploader,
117                 'upload_date': upload_date,
118                 'title': video_title,
119                 'ext': extension,
120                 'format': format,
121                 'thumbnail': thumbnail,
122                 'description': video_description
123             })
124
125         if self._downloader.params.get('listformats', None):
126             self._print_formats(formats)
127             return
128
129         req_format = self._downloader.params.get('format', 'best')
130         self.to_screen(u'Format: %s' % req_format)
131
132         if req_format is None or req_format == 'best':
133             return [formats[0]]
134         elif req_format == 'worst':
135             return [formats[-1]]
136         elif req_format in ('-1', 'all'):
137             return formats
138         else:
139             format = self._specific( req_format, formats )
140             if format is None:
141                 raise ExtractorError(u'Requested format not available')
142             return [format]