fix compat_urllib_request for python2.7
[youtube-dl] / youtube_dl / extractor / weibo.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 from .common import InfoExtractor
5
6 import json
7 import random as rnd
8 import re
9
10 from ..compat import (
11     compat_urllib_parse_urlencode as urlencode,
12     compat_urllib_request as request,
13     compat_urlparse as parse,
14 )
15 from ..utils import (
16     js_to_json,
17 )
18
19
20 class WeiboIE(InfoExtractor):
21     _VALID_URL = r'https?://weibo\.com/[0-9]+/(?P<id>[a-zA-Z0-9]+)'
22     _TEST = {
23         'url': 'https://weibo.com/6275294458/Fp6RGfbff?type=comment',
24         'info_dict': {
25             'id': 'Fp6RGfbff',
26             'ext': 'mp4',
27             'title': 'You should have servants to massage you,... 来自Hosico_猫 - 微博',
28         }
29     }
30
31     def _real_extract(self, url):
32         video_id = self._match_id(url)
33         headers = {
34             'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
35             'Accept-Encoding': 'gzip, deflate, br',
36             'Accept-Language': 'en,zh-CN;q=0.9,zh;q=0.8',
37             'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36',
38             'Upgrade-Insecure-Requests': '1',
39         }
40         # to get Referer url for genvisitor
41         webpage, urlh = self._download_webpage_handle(url, video_id, headers=headers, note="first visit the page")
42
43         visitor_url = urlh.geturl()
44
45         data = urlencode({
46             "cb": "gen_callback",
47             "fp": '{"os":"2","browser":"Gecko57,0,0,0","fonts":"undefined","screenInfo":"1440*900*24","plugins":""}',
48         }).encode()
49         headers = {
50             'Accept-Encoding': 'gzip, deflate, br',
51             'Accept': '*/*',
52             'Referer': visitor_url,
53         }
54
55         r_genvisitor = request.Request(
56             'https://passport.weibo.com/visitor/genvisitor',
57             data=data,
58             headers=headers,
59         )
60         webpage, urlh = self._download_webpage_handle(r_genvisitor, video_id, note="gen visitor")
61
62         p = webpage.split("&&")[1]  # split "gen_callback && gen_callback(...)"
63         i1 = p.find('{')
64         i2 = p.rfind('}')
65         j = p[i1:i2 + 1]  # get JSON object
66         d = json.loads(j)
67         tid = d["data"]["tid"]
68         cnfd = "%03d" % d["data"]["confidence"]
69
70         param = urlencode({
71             'a': 'incarnate',
72             't': tid,
73             'w': 2,
74             'c': cnfd,
75             'cb': 'cross_domain',
76             'from': 'weibo',
77             '_rand': rnd.random()
78         })
79         gencallback_url = "https://passport.weibo.com/visitor/visitor?" + param
80         webpage, urlh = self._download_webpage_handle(gencallback_url, video_id, note="gen callback")
81
82         webpage, urlh = self._download_webpage_handle(url, video_id, headers=headers, note="retry to visit the page")
83
84         # TODO more code goes here, for example ...
85         title = self._html_search_regex(r'<title>(.+?)</title>', webpage, 'title')
86
87         video_sources_text = self._search_regex(r'video-sources=\\\"(.+?)\"', webpage, 'video_sources')
88
89         video_formats = parse.parse_qs(video_sources_text)
90
91         formats = []
92         supported_resolutions = ['720', '480']
93         for res in supported_resolutions:
94             f = video_formats.get(res)
95             if isinstance(f, list):
96                 if len(f) > 0:
97                     vid_url = f[0]
98                     formats.append({
99                         'url': vid_url,
100                         'format': 'mp4',
101                         'height': int(res),
102                     })
103         self._sort_formats(formats)
104         uploader = self._og_search_property('nick-name', webpage, 'uploader', default=None)
105         return {
106             'id': video_id,
107             'title': title,
108             'uploader': uploader,
109             'formats': formats
110             # TODO more properties (see youtube_dl/extractor/common.py)
111         }
112
113
114 class WeiboMobileIE(InfoExtractor):
115     _VALID_URL = r'https?://m.weibo.cn/status/(?P<id>[0-9]+)(\?.+)?'
116     _TEST = {
117         'url': 'https://m.weibo.cn/status/4189191225395228?wm=3333_2001&sourcetype=weixin&featurecode=newtitle&from=singlemessage&isappinstalled=0',
118         'info_dict': {
119             'id': '4189191225395228',
120             'ext': 'mp4',
121             'title': '午睡当然是要甜甜蜜蜜的啦',
122             'uploader': '柴犬柴犬'
123         }
124     }
125
126     def _real_extract(self, url):
127         video_id = self._match_id(url)
128         headers = {
129             'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
130             'Accept-Encoding': 'gzip, deflate, br',
131             'Accept-Language': 'en,zh-CN;q=0.9,zh;q=0.8',
132             'Upgrade-Insecure-Requests': '1',
133         }
134         # to get Referer url for genvisitor
135         webpage, urlh = self._download_webpage_handle(url, video_id, headers=headers, note="visit the page")
136         js_code = self._search_regex(r'var\s+\$render_data\s*=\s*\[({.*})\]\[0\] \|\| {};', webpage, 'js_code', flags=re.DOTALL)
137         weibo_info = self._parse_json(js_code, video_id, transform_source=js_to_json)
138         page_info = weibo_info['status']['page_info']
139         title = weibo_info['status']['status_title']
140         format = {
141             'url': page_info['media_info']['stream_url'],
142             'format': 'mp4',
143         }
144         formats = [format]
145         uploader = weibo_info['status']['user']['screen_name']
146
147         return {
148             'id': video_id,
149             'title': title,
150             'uploader': uploader,
151             'formats': formats
152             # TODO more properties (see youtube_dl/extractor/common.py)
153         }