re-format code to pass flake8
[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(
56             'https://passport.weibo.com/visitor/genvisitor',
57             data=data,
58             headers=headers,
59             method='POST'
60         )
61         webpage, urlh = self._download_webpage_handle(r_genvisitor, video_id, note="gen visitor")
62
63         p = webpage.split("&&")[1]  # split "gen_callback && gen_callback(...)"
64         i1 = p.find('{')
65         i2 = p.rfind('}')
66         j = p[i1:i2 + 1]  # get JSON object
67         d = json.loads(j)
68         tid = d["data"]["tid"]
69         cnfd = "%03d" % d["data"]["confidence"]
70
71         param = urlencode({
72             'a': 'incarnate',
73             't': tid,
74             'w': 2,
75             'c': cnfd,
76             'cb': 'cross_domain',
77             'from': 'weibo',
78             '_rand': rnd.random()
79         })
80         gencallback_url = "https://passport.weibo.com/visitor/visitor?" + param
81         webpage, urlh = self._download_webpage_handle(gencallback_url, video_id, note="gen callback")
82
83         webpage, urlh = self._download_webpage_handle(url, video_id, headers=headers, note="retry to visit the page")
84
85         # TODO more code goes here, for example ...
86         title = self._html_search_regex(r'<title>(.+?)</title>', webpage, 'title')
87
88         video_sources_text = self._search_regex("video-sources=\\\\\"(.+?)\"", webpage, 'video_sources')
89
90         video_formats = parse.parse_qs(video_sources_text)
91
92         formats = []
93         supported_resolutions = ['720', '480']
94         for res in supported_resolutions:
95             f = video_formats.get(res)
96             if isinstance(f, list):
97                 if len(f) > 0:
98                     vid_url = f[0]
99                     formats.append({
100                         'url': vid_url,
101                         'format': 'mp4',
102                         'height': int(res),
103                     })
104         self._sort_formats(formats)
105         uploader = self._og_search_property('nick-name', webpage, 'uploader', default=None)
106         return {
107             'id': video_id,
108             'title': title,
109             'uploader': uploader,
110             'formats': formats
111             # TODO more properties (see youtube_dl/extractor/common.py)
112         }
113
114
115 class WeiboMobileIE(InfoExtractor):
116     _VALID_URL = r'https?://m.weibo.cn/status/(?P<id>[0-9]+)(\?.+)?'
117     _TEST = {
118         'url': 'https://m.weibo.cn/status/4189191225395228?wm=3333_2001&sourcetype=weixin&featurecode=newtitle&from=singlemessage&isappinstalled=0',
119         'info_dict': {
120             'id': '4189191225395228',
121             'ext': 'mp4',
122             'title': '午睡当然是要甜甜蜜蜜的啦',
123             'uploader': '柴犬柴犬'
124         }
125     }
126
127     def _real_extract(self, url):
128         video_id = self._match_id(url)
129         headers = {
130             'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
131             'Accept-Encoding': 'gzip, deflate, br',
132             'Accept-Language': 'en,zh-CN;q=0.9,zh;q=0.8',
133             'Upgrade-Insecure-Requests': '1',
134         }
135         # to get Referer url for genvisitor
136         webpage, urlh = self._download_webpage_handle(url, video_id, headers=headers, note="visit the page")
137         js_code = self._search_regex(r'var\s+\$render_data\s*=\s*\[({.*})\]\[0\] \|\| {};', webpage, 'js_code', flags=re.DOTALL)
138         weibo_info = self._parse_json(js_code, video_id, transform_source=js_to_json)
139         page_info = weibo_info['status']['page_info']
140         title = weibo_info['status']['status_title']
141         format = {
142             'url': page_info['media_info']['stream_url'],
143             'format': 'mp4',
144         }
145         formats = [format]
146         uploader = weibo_info['status']['user']['screen_name']
147
148         return {
149             'id': video_id,
150             'title': title,
151             'uploader': uploader,
152             'formats': formats
153             # TODO more properties (see youtube_dl/extractor/common.py)
154         }