Skip to content

Commit

Permalink
perf(browser.py): 优化从浏览器读取 Cookie 功能
Browse files Browse the repository at this point in the history
  • Loading branch information
JoeanAmier committed Aug 31, 2024
1 parent 56b4f65 commit 0fe5feb
Show file tree
Hide file tree
Showing 2 changed files with 88 additions and 59 deletions.
22 changes: 12 additions & 10 deletions docs/Release_Notes.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,17 @@
1. 修复从文本文档读取链接异常的问题
2. 使用 rookiepy 替代 browser-cookie3
3. 修复调用 FFmpeg 下载直播功能
4. 优化作品文件名称处理逻辑
5. 适配最新版 FFmpeg 命令
6. 日志不再记录请求体数据
7. 捕获中断程序的异常错误
8. 优化重定向链接获取逻辑
9. 新增文件断点续传功能
10. 修复删除下载记录功能
11. 捕获响应码异常的错误
12. 修复其他已知问题
13. 其他细节优化
4. 优化从浏览器读取 Cookie 功能
5. 修复代理参数测试报错的问题
6. 优化作品文件名称处理逻辑
7. 适配最新版 FFmpeg 命令
8. 日志不再记录请求体数据
9. 捕获中断程序的异常错误
10. 优化重定向链接获取逻辑
11. 新增文件断点续传功能
12. 修复删除下载记录功能
13. 捕获响应码异常的错误
14. 修复其他已知问题
15. 其他细节优化

<p><strong>注意:Mac OS 平台可执行文件 <code>main</code> 可能需要从终端命令行启动;受设备限制,Mac OS 平台可执行文件尚未经过测试,无法保证可用性!</strong></p>
125 changes: 76 additions & 49 deletions src/tools/browser.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from contextlib import suppress
from sys import platform
from types import SimpleNamespace
from typing import TYPE_CHECKING

Expand All @@ -10,36 +12,34 @@
firefox,
librewolf,
opera,
# opera_gx,
# safari,
opera_gx,
vivaldi,
)

from src.custom import INFO
from src.custom import WARNING

if TYPE_CHECKING:
from src.module import Cookie
from src.config import Parameter
from typing import Callable

__all__ = ["Browser"]


class Browser:
browser = (
arc,
brave,
chrome,
chromium,
edge,
firefox,
librewolf,
opera,
# opera_gx,
# safari,
vivaldi,
)
platform = {
SUPPORT_BROWSER = {
"Arc": (arc, "Linux, macOS, Windows"),
"Chrome": (chrome, "Linux, macOS, Windows"),
"Chromium": (chromium, "Linux, macOS, Windows"),
"Opera": (opera, "Linux, macOS, Windows"),
"OperaGX": (opera_gx, "macOS, Windows"),
"Brave": (brave, "Linux, macOS, Windows"),
"Edge": (edge, "Linux, macOS, Windows"),
"Vivaldi": (vivaldi, "Linux, macOS, Windows"),
"Firefox": (firefox, "Linux, macOS, Windows"),
"LibreWolf": (librewolf, "Linux, macOS, Windows"),
}
PLATFORM = {
False: SimpleNamespace(
name="抖音",
domain=[
Expand All @@ -60,39 +60,66 @@ def __init__(self, parameters: "Parameter", cookie_object: "Cookie"):
self.console = parameters.console
self.cookie_object = cookie_object

def run(self, tiktok=False):
browser = self.console.input(
f"自动读取指定浏览器的 {self.platform[tiktok].name} Cookie 并写入配置文件\n"
"1. Arc: Linux, macOS, Windows\n"
"2. Brave: Linux, macOS, Windows\n"
"3. Chrome: Linux, macOS, Windows\n"
"4. Chromium: Linux, macOS, Windows\n"
"5. Edge: Linux, macOS, Windows\n"
"6. Firefox: Linux, macOS, Windows\n"
"7. LibreWolf: Linux, macOS, Windows\n"
"8. Opera: Linux, macOS, Windows\n"
# "9. Opera GX: macOS, Windows\n"
# "10. Safari: macOS\n"
# "11. Vivaldi: Linux, macOS, Windows\n"
"9. Vivaldi: Linux, macOS, Windows\n"
"请输入浏览器序号:")
def run(self, tiktok=False, ):
options = "\n".join(
f"{i}. {k}: {v[1]}" for i, (k, v) in enumerate(
self.SUPPORT_BROWSER.items(), start=1))
if browser := self.console.input(
f"读取指定浏览器的 {self.PLATFORM[tiktok].name} Cookie 并写入配置文件\n{options}\n请输入浏览器名称或序号:",
):
if cookie := self.get(browser, self.PLATFORM[tiktok].domain, ):
self.__save_cookie(cookie, tiktok, )
self.console.print("读取 Cookie 成功!", style=INFO, )
else:
self.console.print("未选择浏览器!")

def __save_cookie(self, cookie: dict, tiktok: bool):
self.cookie_object.save_cookie(cookie, self.PLATFORM[tiktok].key)

def get(self, browser: str | int, domains: list[str], ) -> dict[str, str]:
if not (browser := self.__browser_object(browser)):
self.console.print("浏览器名称或序号输入错误!", style=WARNING, )
return {}
try:
cookie = self.__read_cookie(
self.browser[int(browser) - 1], tiktok, )
self.__save_cookie(cookie, tiktok)
return True
except ValueError:
self.console.print("浏览器序号输入错误,未写入 Cookie!")
cookies = browser(domains=domains)
return {i["name"]: i["value"] for i in cookies}
except RuntimeError:
self.console.print(
"读取 Cookie 失败,未找到对应浏览器的 Cookie 数据!",
style=WARNING)
return False
self.console.print("读取 Cookie 失败,未找到 Cookie 数据!", style=WARNING, )
return {}

def __read_cookie(self, browser: "Callable", tiktok: bool) -> dict:
platform = self.platform[tiktok]
cookies = browser(domains=platform.domain, )
return {i["name"]: i["value"] for i in cookies}
@classmethod
def __browser_object(cls, browser: str | int):
with suppress(ValueError):
browser = int(browser) - 1
if isinstance(browser, int):
try:
return list(cls.SUPPORT_BROWSER.values())[browser][0]
except IndexError:
return None
if isinstance(browser, str):
try:
return cls.__match_browser(browser)
except KeyError:
return None
raise TypeError

def __save_cookie(self, cookie: dict, tiktok: bool):
self.cookie_object.save_cookie(cookie, self.platform[tiktok].key)
@classmethod
def __match_browser(cls, browser: str):
for i, j in cls.SUPPORT_BROWSER.items():
if i.lower() == browser.lower():
return j[0]


match platform:
case "darwin":
from rookiepy import safari

Browser.SUPPORT_BROWSER |= {
"Safari": (safari, "macOS"),
}
case "linux":
Browser.SUPPORT_BROWSER.pop("OperaGX")
case "win32":
pass
case _:
print("从浏览器读取 Cookie 功能不支持当前平台!")

0 comments on commit 0fe5feb

Please sign in to comment.