[YouPornIE] Extract all encrypted links and remove doubles at the end
[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_urllib_parse_urlparse,
9     compat_urllib_request,
10
11     ExtractorError,
12     unescapeHTML,
13     unified_strdate,
14 )
15 from ..aes import (
16     aes_decrypt_text
17 )
18
19 class YouPornIE(InfoExtractor):
20     _VALID_URL = r'^(?:https?://)?(?:\w+\.)?youporn\.com/watch/(?P<videoid>[0-9]+)/(?P<title>[^/]+)'
21     _TEST = {
22         u'url': u'http://www.youporn.com/watch/505835/sex-ed-is-it-safe-to-masturbate-daily/',
23         u'file': u'505835.mp4',
24         u'md5': u'71ec5fcfddacf80f495efa8b6a8d9a89',
25         u'info_dict': {
26             u"upload_date": u"20101221", 
27             u"description": u"Love & Sex Answers: http://bit.ly/DanAndJenn -- Is It Unhealthy To Masturbate Daily?", 
28             u"uploader": u"Ask Dan And Jennifer", 
29             u"title": u"Sex Ed: Is It Safe To Masturbate Daily?",
30             u"age_limit": 18,
31         }
32     }
33
34     def _real_extract(self, url):
35         mobj = re.match(self._VALID_URL, url)
36         video_id = mobj.group('videoid')
37
38         req = compat_urllib_request.Request(url)
39         req.add_header('Cookie', 'age_verified=1')
40         webpage = self._download_webpage(req, video_id)
41         age_limit = self._rta_search(webpage)
42
43         # Get JSON parameters
44         json_params = self._search_regex(r'var currentVideo = new Video\((.*)\);', webpage, u'JSON parameters')
45         try:
46             params = json.loads(json_params)
47         except:
48             raise ExtractorError(u'Invalid JSON')
49
50         self.report_extraction(video_id)
51         try:
52             video_title = params['title']
53             upload_date = unified_strdate(params['release_date_f'])
54             video_description = params['description']
55             video_uploader = params['submitted_by']
56             thumbnail = params['thumbnails'][0]['image']
57         except KeyError:
58             raise ExtractorError('Missing JSON parameter: ' + sys.exc_info()[1])
59
60         # Get all of the links from the page
61         DOWNLOAD_LIST_RE = r'(?s)<ul class="downloadList">(?P<download_list>.*?)</ul>'
62         download_list_html = self._search_regex(DOWNLOAD_LIST_RE,
63             webpage, u'download list').strip()
64         LINK_RE = r'<a href="([^"]+)">'
65         links = re.findall(LINK_RE, download_list_html)
66
67         # Get all encrypted links
68         encrypted_links = re.findall(r'var encryptedQuality[0-9]{3}URL = \'([a-zA-Z0-9+/]+={0,2})\';', webpage)
69         for encrypted_link in encrypted_links:
70             link = aes_decrypt_text(encrypted_link, video_title, 32).decode('utf-8')
71             links.append(link)
72         
73         if not links:
74             raise ExtractorError(u'ERROR: no known formats available for video')
75
76         formats = []
77         for link in links:
78
79             # A link looks like this:
80             # 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
81             # A path looks like this:
82             # /201210/31/8004515/480p_370k_8004515/YouPorn%20-%20Nubile%20Films%20The%20Pillow%20Fight.mp4
83             video_url = unescapeHTML( link )
84             path = compat_urllib_parse_urlparse( video_url ).path
85             extension = os.path.splitext( path )[1][1:]
86             format = path.split('/')[4].split('_')[:2]
87
88             # size = format[0]
89             # bitrate = format[1]
90             format = "-".join( format )
91             # title = u'%s-%s-%s' % (video_title, size, bitrate)
92
93             formats.append({
94                 'url': video_url,
95                 'ext': extension,
96                 'format': format,
97                 'format_id': format,
98             })
99
100         # Sort and remove doubles
101         formats.sort(key=lambda format: list(map(lambda s: s.zfill(6), format['format'].split('-'))))
102         for i in range(len(formats)-1,0,-1):
103             if formats[i]['format_id'] == formats[i-1]['format_id']:
104                 del formats[i]
105         
106         return {
107             'id': video_id,
108             'uploader': video_uploader,
109             'upload_date': upload_date,
110             'title': video_title,
111             'thumbnail': thumbnail,
112             'description': video_description,
113             'age_limit': age_limit,
114             'formats': formats,
115         }