[vk.com] Updated the description to include vk.com.
[youtube-dl] / youtube_dl / extractor / vk.py
1 # encoding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5 import json
6
7 from .common import InfoExtractor
8 from ..utils import (
9     ExtractorError,
10     compat_urllib_request,
11     compat_urllib_parse,
12     compat_str,
13     unescapeHTML,
14     unified_strdate)
15
16
17 class VKIE(InfoExtractor):
18     IE_NAME = 'vk.com'
19     _VALID_URL = r'https?://(?:m\.)?vk\.com/(?:video_ext\.php\?.*?\boid=(?P<oid>-?\d+).*?\bid=(?P<id>\d+)|(?:.+?\?.*?z=)?video(?P<videoid>[^s].*?)(?:\?|%2F|$))'
20     _NETRC_MACHINE = 'vk'
21
22     _TESTS = [
23         {
24             'url': 'http://vk.com/videos-77521?z=video-77521_162222515%2Fclub77521',
25             'md5': '0deae91935c54e00003c2a00646315f0',
26             'info_dict': {
27                 'id': '162222515',
28                 'ext': 'flv',
29                 'title': 'ProtivoGunz - Хуёвая песня',
30                 'uploader': 're:Noize MC.*',
31                 'duration': 195,
32                 'upload_date': '20120212',
33             },
34         },
35         {
36             'url': 'http://vk.com/video205387401_165548505',
37             'md5': '6c0aeb2e90396ba97035b9cbde548700',
38             'info_dict': {
39                 'id': '165548505',
40                 'ext': 'mp4',
41                 'uploader': 'Tom Cruise',
42                 'title': 'No name',
43                 'duration': 9,
44                 'upload_date': '20130721'
45             }
46         },
47         {
48             'note': 'Embedded video',
49             'url': 'http://vk.com/video_ext.php?oid=32194266&id=162925554&hash=7d8c2e0d5e05aeaa&hd=1',
50             'md5': 'c7ce8f1f87bec05b3de07fdeafe21a0a',
51             'info_dict': {
52                 'id': '162925554',
53                 'ext': 'mp4',
54                 'uploader': 'Vladimir Gavrin',
55                 'title': 'Lin Dan',
56                 'duration': 101,
57                 'upload_date': '20120730',
58             }
59         },
60         {
61             # VIDEO NOW REMOVED
62             # please update if you find a video whose URL follows the same pattern
63             'url': 'http://vk.com/video-8871596_164049491',
64             'md5': 'a590bcaf3d543576c9bd162812387666',
65             'note': 'Only available for registered users',
66             'info_dict': {
67                 'id': '164049491',
68                 'ext': 'mp4',
69                 'uploader': 'Триллеры',
70                 'title': '► Бойцовский клуб / Fight Club 1999 [HD 720]',
71                 'duration': 8352,
72                 'upload_date': '20121218'
73             },
74             'skip': 'Requires vk account credentials',
75         },
76         {
77             # VIDEO NOW REMOVED
78             # please update if you find a video whose URL follows the same pattern
79             'url': 'http://vk.com/feed?z=video-43215063_166094326%2Fbb50cacd3177146d7a',
80             'md5': 'd82c22e449f036282d1d3f7f4d276869',
81             'info_dict': {
82                 'id': '166094326',
83                 'ext': 'mp4',
84                 'uploader': 'Киномания - лучшее из мира кино',
85                 'title': 'Запах женщины (1992)',
86                 'duration': 9392,
87                 'upload_date': '20130914'
88             },
89             'skip': 'Requires vk account credentials',
90         },
91         {
92             'url': 'http://vk.com/hd_kino_mania?z=video-43215063_168067957%2F15c66b9b533119788d',
93             'md5': '4d7a5ef8cf114dfa09577e57b2993202',
94             'info_dict': {
95                 'id': '168067957',
96                 'ext': 'mp4',
97                 'uploader': 'Киномания - лучшее из мира кино',
98                 'title': ' ',
99                 'duration': 7291,
100                 'upload_date': '20140328',
101             },
102             'skip': 'Requires vk account credentials',
103         },
104         {
105             'url': 'http://m.vk.com/video-43215063_169084319?list=125c627d1aa1cebb83&from=wall-43215063_2566540',
106             'md5': '0c45586baa71b7cb1d0784ee3f4e00a6',
107             'note': 'ivi.ru embed',
108             'info_dict': {
109                 'id': '60690',
110                 'ext': 'mp4',
111                 'title': 'Книга Илая',
112                 'duration': 6771,
113                 'upload_date': '20140626',
114             },
115             'skip': 'Only works from Russia',
116         },
117     ]
118
119     def _login(self):
120         (username, password) = self._get_login_info()
121         if username is None:
122             return
123
124         login_form = {
125             'act': 'login',
126             'role': 'al_frame',
127             'expire': '1',
128             'email': username,
129             'pass': password,
130         }
131
132         request = compat_urllib_request.Request('https://login.vk.com/?act=login',
133             compat_urllib_parse.urlencode(login_form).encode('utf-8'))
134         login_page = self._download_webpage(request, None, note='Logging in as %s' % username)
135
136         if re.search(r'onLoginFailed', login_page):
137             raise ExtractorError('Unable to login, incorrect username and/or password', expected=True)
138
139     def _real_initialize(self):
140         self._login()
141
142     def _real_extract(self, url):
143         mobj = re.match(self._VALID_URL, url)
144         video_id = mobj.group('videoid')
145
146         if not video_id:
147             video_id = '%s_%s' % (mobj.group('oid'), mobj.group('id'))
148
149         info_url = 'http://vk.com/al_video.php?act=show&al=1&video=%s' % video_id
150         info_page = self._download_webpage(info_url, video_id)
151
152         ERRORS = {
153             r'>Видеозапись .*? была изъята из публичного доступа в связи с обращением правообладателя.<':
154                 'Video %s has been removed from public access due to rightholder complaint.',
155             r'<!>Please log in or <':
156                 'Video %s is only available for registered users, '
157                 'use --username and --password options to provide account credentials.',
158             '<!>Unknown error':
159                 'Video %s does not exist.'
160         }
161
162         for error_re, error_msg in ERRORS.items():
163             if re.search(error_re, info_page):
164                 raise ExtractorError(error_msg % video_id, expected=True)
165
166         m_yt = re.search(r'src="(http://www.youtube.com/.*?)"', info_page)
167         if m_yt is not None:
168             self.to_screen('Youtube video detected')
169             return self.url_result(m_yt.group(1), 'Youtube')
170
171         m_opts = re.search(r'(?s)var\s+opts\s*=\s*({.*?});', info_page)
172         if m_opts:
173             m_opts_url = re.search(r"url\s*:\s*'([^']+)", m_opts.group(1))
174             if m_opts_url:
175                 opts_url = m_opts_url.group(1)
176                 if opts_url.startswith('//'):
177                     opts_url = 'http:' + opts_url
178                 return self.url_result(opts_url)
179
180         data_json = self._search_regex(r'var vars = ({.*?});', info_page, 'vars')
181         data = json.loads(data_json)
182
183         # Extract upload date
184         upload_date = None
185         mobj = re.search(r'id="mv_date_wrap".*?Added ([a-zA-Z]+ [0-9]+), ([0-9]+) at', info_page)
186         if mobj is not None:
187             x = mobj.group(1) + ' ' + mobj.group(2)
188             upload_date = unified_strdate(mobj.group(1) + ' ' + mobj.group(2))
189
190         formats = [{
191             'format_id': k,
192             'url': v,
193             'width': int(k[len('url'):]),
194         } for k, v in data.items()
195             if k.startswith('url')]
196         self._sort_formats(formats)
197
198         return {
199             'id': compat_str(data['vid']),
200             'formats': formats,
201             'title': unescapeHTML(data['md_title']),
202             'thumbnail': data.get('jpg'),
203             'uploader': data.get('md_author'),
204             'duration': data.get('duration'),
205             'upload_date': upload_date,
206         }
207
208
209 class VKUserVideosIE(InfoExtractor):
210     IE_NAME = 'vk.com:user-videos'
211     IE_DESC = 'vk.com:All of a user\'s videos'
212     _VALID_URL = r'https?://(?:m\.)?vk\.com/videos([0-9]+)(?:m\?.*)?'
213     _TEMPLATE_URL = 'https://vk.com/videos'
214     _TEST = {
215         'url': 'http://vk.com/videos205387401',
216         'playlist_mincount': 4,
217     }
218
219     def extract_videos_from_page(self, page):
220         ids_in_page = []
221         for mobj in re.finditer(r'href="/video([0-9_]+)"', page):
222             if mobj.group(1) not in ids_in_page:
223                 ids_in_page.append(mobj.group(1))
224         return ids_in_page
225
226     def _real_extract(self, url):
227         # Extract page id
228         mobj = re.match(self._VALID_URL, url)
229         if mobj is None:
230             raise ExtractorError('Invalid URL: %s' % url)
231
232         # Download page and get video ids
233         page_id = mobj.group(1)
234         page = self._download_webpage(url, page_id)
235         video_ids = self.extract_videos_from_page(page)
236
237         self._downloader.to_screen('[vk] User videos %s: Found %i videos' % (page_id, len(video_ids)))
238
239         url_entries = [self.url_result('http://vk.com/video' + video_id, 'VK', video_id=video_id)
240                        for video_id in video_ids]
241         return self.playlist_result(url_entries, page_id)