diff --git a/SpotifyLyricWindow/common/api/lyric_api/cloud_api.py b/SpotifyLyricWindow/common/api/lyric_api/cloud_api.py index 1ce0925..e02cc4c 100644 --- a/SpotifyLyricWindow/common/api/lyric_api/cloud_api.py +++ b/SpotifyLyricWindow/common/api/lyric_api/cloud_api.py @@ -22,7 +22,7 @@ def search_song_id(self, keyword: str, page: int = 1) -> List[SongSearchInfo]: keyword = re.sub(r"|[!@#$%^&*/]+", "", keyword) url = self._SEARCH_SONG_ID_URL.format(keyword, (page - 1) * 20) - res_json = requests.post(url, timeout=4).json() + res_json = requests.post(url, timeout=4, proxies={"https": None, "http": None}).json() if res_json["result"] == {} or res_json['code'] == 400 or res_json["result"]['songCount'] == 0: # 该关键词没有结果 raise NoneResultError @@ -45,7 +45,7 @@ def search_song_id(self, keyword: str, page: int = 1) -> List[SongSearchInfo]: def search_song_info(self, song_id: str, *, download_pic: bool = False, pic_size: int = 0) -> SongInfo: url = self._SEARCH_SONG_INFO_URL.format(song_id, song_id) - res_json = requests.post(url, timeout=10).json() + res_json = requests.post(url, timeout=10, proxies={"https": None, "http": None}).json() if res_json['code'] == 400 or res_json['code'] == 406: raise requests.RequestException("访问过于频繁或接口失效") @@ -59,7 +59,7 @@ def search_song_info(self, song_id: str, *, download_pic: bool = False, pic_size else: param = {"param": f"{pic_size}y{pic_size}"} pic_url = song_json["album"]["picUrl"] - pic_data = requests.get(pic_url, timeout=10, params=param).content + pic_data = requests.get(pic_url, timeout=10, params=param, proxies={"https": None, "http": None}).content pic_buffer = io.BytesIO(pic_data) else: pic_buffer = None @@ -77,7 +77,7 @@ def search_song_info(self, song_id: str, *, download_pic: bool = False, pic_size return song_info def fetch_song_lyric(self, song_id: str) -> LrcFile: - res_json = requests.get(self._FETCH_LYRIC_URL.format(song_id), timeout=10).json() + res_json = requests.get(self._FETCH_LYRIC_URL.format(song_id), timeout=10, proxies={"https": None, "http": None}).json() lrc_file = LrcFile() lrc_file.load_content(res_json['lrc']['lyric'], TransType.NON) if res_json.get('tlyric', None): diff --git a/SpotifyLyricWindow/common/api/lyric_api/kugou_api.py b/SpotifyLyricWindow/common/api/lyric_api/kugou_api.py index 31e3c65..baa83a5 100644 --- a/SpotifyLyricWindow/common/api/lyric_api/kugou_api.py +++ b/SpotifyLyricWindow/common/api/lyric_api/kugou_api.py @@ -29,7 +29,7 @@ class KugouApi(BaseMusicApi): def search_song_id(self, keyword: str, page: int = 1) -> List[SongSearchInfo]: keyword = re.sub(r"|[!@#$%^&*/]+", "", keyword) url = self._SEARCH_SONG_ID_URL.format(keyword, page) - res_json = requests.get(url, headers=self.header, timeout=4).json() + res_json = requests.get(url, headers=self.header, timeout=4, proxies={"https": None, "http": None}).json() song_info_list = [] @@ -48,14 +48,15 @@ def search_song_id(self, keyword: str, page: int = 1) -> List[SongSearchInfo]: raise NoneResultError def search_song_info(self, md5: str, *, download_pic: bool = False, pic_size: int = 0) -> SongInfo: - song_json = requests.get(self._SEARCH_SONG_INFO_URL.format(md5), headers=self.header, timeout=4).json() + song_json = requests.get(self._SEARCH_SONG_INFO_URL.format(md5), headers=self.header, timeout=4, + proxies={"https": None, "http": None}).json() duration = song_json["timeLength"] album_img = str(song_json["album_img"]) year = album = None album_id = song_json["albumid"] # if not found, the 'album_id' is 0 if album_id: album_json = requests.get(self._SEARCH_ALBUM_INFO_URL.format(album_id), - headers=self.header, timeout=4).json() + headers=self.header, timeout=4, proxies={"https": None, "http": None}).json() album = album_json["data"].get("albumname", None) year = album_json["data"].get("publishtime", None) # like '2021-08-11 00:00:00' @@ -65,7 +66,7 @@ def search_song_info(self, md5: str, *, download_pic: bool = False, pic_size: in pic_url = album_img.replace("/{size}/", "/") # original pic if download_pic and pic_url: - pic_data = requests.get(pic_url, timeout=10).content + pic_data = requests.get(pic_url, timeout=10, proxies={"https": None, "http": None}).content pic_buffer = io.BytesIO(pic_data) else: pic_buffer = None @@ -94,7 +95,7 @@ def _get_lrc_info(self, md5: str) -> List[Dict[str, str]]: :return: Contains a list of basic lyrics data. """ url = self._GET_KEY_SEARCH_URL.format(md5) - res_json = requests.get(url, headers=self.header, timeout=4).json() + res_json = requests.get(url, headers=self.header, timeout=4, proxies={"https": None, "http": None}).json() if res_json['errcode'] != 200: raise requests.RequestException(res_json["info"]) res_list = [] @@ -122,7 +123,7 @@ def _get_lrc(self, lyric_info: dict) -> KrcFile: :return: Content of the lyrics. """ url = self._FETCH_LYRIC_URL.format(lyric_info["id"], lyric_info["key"], 'krc') - res_json = requests.get(url, timeout=4).json() + res_json = requests.get(url, timeout=4, proxies={"https": None, "http": None}).json() content = res_json['content'] result = base64.b64decode(content.encode()) diff --git a/SpotifyLyricWindow/common/api/lyric_api/spotify_api.py b/SpotifyLyricWindow/common/api/lyric_api/spotify_api.py index 6d4c984..5c9ed4c 100644 --- a/SpotifyLyricWindow/common/api/lyric_api/spotify_api.py +++ b/SpotifyLyricWindow/common/api/lyric_api/spotify_api.py @@ -8,6 +8,7 @@ from common.api.user_api.user_auth import SpotifyUserAuth from common.api.lyric_api.base_lyric_api import BaseMusicApi from common.song_metadata.metadata_type import SongInfo, SongSearchInfo +from common.config import Config class SpotifyApi(BaseMusicApi): @@ -23,7 +24,10 @@ def search_song_id(self, keyword: str, page: int = 1): url = self._SEARCH_SONG_ID_URL.format(keyword, (page - 1) * 10) - res_json = requests.get(url, headers=self._get_token()).json() + proxy_ip = Config.CommonConfig.ClientConfig.proxy_ip + proxy = {"https": proxy_ip} if proxy_ip else {} + + res_json = requests.get(url, headers=self._get_token(), proxies=proxy).json() song_info_list = [] for data in res_json['tracks']['items']: artists_list = [info["name"] for info in data["artists"]] @@ -39,7 +43,9 @@ def search_song_id(self, keyword: str, page: int = 1): def search_song_info(self, song_id: str, *, download_pic: bool = False, pic_size: int = 0): url = self._SEARCH_SONG_INFO_URL.format(song_id) - song_json = requests.get(url, headers=self._get_token()).json() + proxy_ip = Config.CommonConfig.ClientConfig.proxy_ip + proxy = {"https": proxy_ip} if proxy_ip else {} + song_json = requests.get(url, headers=self._get_token(), proxies=proxy).json() duration = int(song_json["duration_ms"]) // 1000 @@ -51,7 +57,9 @@ def search_song_info(self, song_id: str, *, download_pic: bool = False, pic_size if pic_jsons: pic_json = pic_jsons[0] pic_url = pic_json["url"] - pic_data = requests.get(pic_url, timeout=10).content + proxy_ip = Config.CommonConfig.ClientConfig.proxy_ip + proxy = {"https": proxy_ip} if proxy_ip else {} + pic_data = requests.get(pic_url, timeout=10, proxies=proxy).content pic_buffer = io.BytesIO(pic_data) else: pic_buffer = None diff --git a/SpotifyLyricWindow/common/api/user_api/user_api.py b/SpotifyLyricWindow/common/api/user_api/user_api.py index 062c4b3..b606618 100644 --- a/SpotifyLyricWindow/common/api/user_api/user_api.py +++ b/SpotifyLyricWindow/common/api/user_api/user_api.py @@ -7,6 +7,7 @@ from common.api.exceptions import * from common.api.user_api.user_auth import SpotifyUserAuth +from common.config import Config UserCurrentPlaying = namedtuple("UserCurrentPlaying", ["progress_ms", "artist", "track_name", "is_playing", "track_id", "duration", "api_offset"]) @@ -84,7 +85,9 @@ def _player_http(self, method, url_suffix, **kwargs): self.load_client_id_secret() url = self.USER_PLAYER_URL + url_suffix func = getattr(requests, method) - res = func(url, headers=self._get_auth_header(), params=kwargs) + proxy_ip = Config.CommonConfig.ClientConfig.proxy_ip + proxy = {"https": proxy_ip} if proxy_ip else {} + res = func(url, headers=self._get_auth_header(), params=kwargs, proxies=proxy) if res.status_code == 204 and url_suffix == "currently-playing": raise NoActiveUser("no user active") if res.status_code == 200: diff --git a/SpotifyLyricWindow/common/api/user_api/user_auth.py b/SpotifyLyricWindow/common/api/user_api/user_auth.py index 43804fe..a50cffc 100644 --- a/SpotifyLyricWindow/common/api/user_api/user_auth.py +++ b/SpotifyLyricWindow/common/api/user_api/user_auth.py @@ -34,6 +34,8 @@ def __init__(self): self.auth_code = None self.client_id = Config.CommonConfig.ClientConfig.client_id self.client_secret = Config.CommonConfig.ClientConfig.client_secret + self.proxy_ip = Config.CommonConfig.ClientConfig.proxy_ip + self.proxy = {"https": self.proxy_ip} if self.proxy_ip else {} auth = base64.b64encode((self.client_id + ":" + self.client_secret).encode("ascii")) self.auth_client_header = {'Authorization': 'Basic ' + auth.decode("ascii")} if TOKEN_PATH.exists(): @@ -45,6 +47,9 @@ def __init__(self): def load_client_config(self): self.client_id = Config.CommonConfig.ClientConfig.client_id self.client_secret = Config.CommonConfig.ClientConfig.client_secret + self.proxy_ip = Config.CommonConfig.ClientConfig.proxy_ip + self.proxy = {"https": self.proxy_ip} if self.proxy_ip else {} + auth = base64.b64encode((self.client_id + ":" + self.client_secret).encode("ascii")) self.auth_client_header = {'Authorization': 'Basic ' + auth.decode("ascii")} try: @@ -81,7 +86,7 @@ def get_user_auth_url(self) -> str: 'state': self.state } # suffix_url = "?" + "&".join(f"{it[0]}={it[1]}" for it in url_param.items()) - auth_code = requests.get(self.AUTH_AUTHORIZE_URL, url_param) + auth_code = requests.get(self.AUTH_AUTHORIZE_URL, url_param, proxies=self.proxy) return auth_code.url def receive_user_auth_code(self) -> str: @@ -117,7 +122,7 @@ def get_user_access_token(self): "redirect_uri": "http://localhost:8888/callback", "grant_type": 'authorization_code' } - self.user_token_info = requests.post(self.AUTH_TOKEN_URL, data=form, headers=self.auth_client_header).json() + self.user_token_info = requests.post(self.AUTH_TOKEN_URL, data=form, headers=self.auth_client_header, proxies=self.proxy).json() self.user_token_info["expires_at"] = int(time.time()) + self.user_token_info["expires_in"] self.save_token() @@ -127,7 +132,7 @@ def get_fresh_access_token(self): "grant_type": "refresh_token", "refresh_token": refresh_token, } - self.user_token_info = requests.post(self.AUTH_TOKEN_URL, headers=self.auth_client_header, data=payloads).json() + self.user_token_info = requests.post(self.AUTH_TOKEN_URL, headers=self.auth_client_header, data=payloads, proxies=self.proxy).json() if not self.user_token_info.get("expires_in"): # print(self.user_token_info) # {'error': 'invalid_grant', 'error_description': 'Refresh token revoked'} raise NoAuthError("请先引导用户完成验证") @@ -164,7 +169,7 @@ def get_client_token(self): def _fetch_client_access_token(self): """获取token""" payload = {"grant_type": "client_credentials"} - response = requests.post(self.AUTH_TOKEN_URL, headers=self.auth_client_header, data=payload) + response = requests.post(self.AUTH_TOKEN_URL, headers=self.auth_client_header, data=payload, proxies=self.proxy) if response.json().get("error") == 'invalid_client': raise NotImplementedError("请在设置输入您的client_id以及client_secret") response.raise_for_status() diff --git a/SpotifyLyricWindow/common/config.py b/SpotifyLyricWindow/common/config.py index 61dfe07..6734e6c 100644 --- a/SpotifyLyricWindow/common/config.py +++ b/SpotifyLyricWindow/common/config.py @@ -19,6 +19,7 @@ class CommonConfig: class ClientConfig: client_id: str = "" client_secret: str = "" + proxy_ip: str = "" class PathConfig: temp_file_path: str = "" diff --git a/SpotifyLyricWindow/view/setting_page/common_setting_page.py b/SpotifyLyricWindow/view/setting_page/common_setting_page.py index 2ff49af..9c40f14 100644 --- a/SpotifyLyricWindow/view/setting_page/common_setting_page.py +++ b/SpotifyLyricWindow/view/setting_page/common_setting_page.py @@ -2,6 +2,7 @@ # -*- coding:utf-8 -*- import weakref +from requests.exceptions import ProxyError from PyQt5.QtWidgets import * from common.api.user_api import SpotifyUserAuth @@ -94,6 +95,10 @@ def confirm_client_event(self): except NotImplementedError as e: self.lyric_window.error_msg_show_signal.emit(e) return + except ProxyError: + error = ProxyError("代理错误 请在配置文件检查代理并重启") + self.lyric_window.error_msg_show_signal.emit(error) + return self.lyric_window.text_show_signal.emit(1, "成功设置client配置!", 0) self.lyric_window.text_show_signal.emit(2, "♪(^∇^*)", 0) self.lyric_window.delay_calibration()