This commit is contained in:
LibraHp_0928 2024-11-03 13:46:39 +08:00
parent 81965c3143
commit 6af6d8f069
3 changed files with 55 additions and 54 deletions

88
main.py
View File

@ -14,11 +14,12 @@ import pandas.io.clipboard as cb
import platform import platform
from pathlib import Path from pathlib import Path
import traceback import traceback
import dateparser
# 程序版本 # 程序版本
version = "1.0.2" version = "1.0.2"
is_debug = True is_debug = False
# 初始化所有消息列表 # 初始化所有消息列表
all_messages = [] all_messages = []
@ -118,18 +119,14 @@ def process_old_html(message):
def parse_time_strings(time_str): def parse_time_strings(time_str):
today = datetime.today().date() # 获取今天的日期 time_str = time_str.replace(' ', '')
try: date_obj = dateparser.parse(time_str)
if len(time_str) == 5: # 格式为 HH:MM if date_obj is None:
return datetime.combine(today, datetime.strptime(time_str, "%H:%M").time()) current_year = str(datetime.now().year)
elif "" in time_str: # 包含“年”的格式 time_str_with_year = current_year + "" + time_str
return datetime.strptime(time_str, "%Y年%m月%d%H:%M") date_obj = dateparser.parse(time_str_with_year)
elif "" in time_str: # 包含“月”的格式
return datetime.strptime(time_str, "%m月%d%H:%M").replace(year=today.year) return date_obj if date_obj is not None else datetime.now()
else:
return datetime.now() # 不符合任何格式时返回最早的时间
except ValueError:
return datetime.now() # 如果解析失败,返回最早的时间
def get_big_img_dlg(img_url): def get_big_img_dlg(img_url):
@ -144,7 +141,7 @@ def get_big_img_dlg(img_url):
) )
def log(message, type="info"): def log(message, type="INFO"):
now = time.strftime("%Y-%m-%d %H:%M:%S") now = time.strftime("%Y-%m-%d %H:%M:%S")
log_info_ref.current.value = f"[{now}] - [{type}] {message}" log_info_ref.current.value = f"[{now}] - [{type}] {message}"
@ -153,11 +150,11 @@ def log(message, type="info"):
with open(f"log.txt", "a", encoding="utf-8") as f: with open(f"log.txt", "a", encoding="utf-8") as f:
f.write(f"[{now}] - {message}\n") f.write(f"[{now}] - {message}\n")
if type == "success": if type == "SUCCESS":
log_info_ref.current.color = "green" log_info_ref.current.color = "green"
elif type == "error": elif type == "ERROR":
log_info_ref.current.color = "red" log_info_ref.current.color = "red"
elif type == "debug": elif type == "DEBUG":
log_info_ref.current.color = "yellow" log_info_ref.current.color = "yellow"
else: else:
log_info_ref.current.color = "blue" log_info_ref.current.color = "blue"
@ -201,7 +198,7 @@ def clean_content():
message.content = content.replace(now_login_user.username, '') message.content = content.replace(now_login_user.username, '')
except Exception as e: except Exception as e:
print(traceback.format_exc()) print(traceback.format_exc())
log(f"清理内容时发生错误: {e}", "error") log(f"清理内容时发生错误: {e}", "ERROR")
def save_image(url, file_name): def save_image(url, file_name):
@ -214,7 +211,7 @@ def save_image(url, file_name):
f.write(response.content) f.write(response.content)
log(f"图片保存成功:{save_path}/{valid_file_name}.jpg") log(f"图片保存成功:{save_path}/{valid_file_name}.jpg")
except Exception as e: except Exception as e:
log(e, "error") log(e, "ERROR")
class PaginatedContainer(ft.Column): class PaginatedContainer(ft.Column):
@ -306,9 +303,9 @@ class PaginatedContainer(ft.Column):
self.current_page = target_page self.current_page = target_page
self.update_page_info() self.update_page_info()
else: else:
log("请输入有效的页码。", "error") log("请输入有效的页码。", "ERROR")
except ValueError: except ValueError:
log("请输入有效的页码。", "error") log("请输入有效的页码。", "ERROR")
def export_json(self, e): def export_json(self, e):
json_data = [] json_data = []
@ -336,9 +333,9 @@ class PaginatedContainer(ft.Column):
try: try:
with open(f"{save_path}/{now_login_user.uin}_{self.title}_data.json", "w", encoding="utf-8") as f: with open(f"{save_path}/{now_login_user.uin}_{self.title}_data.json", "w", encoding="utf-8") as f:
f.write(json_string) f.write(json_string)
log(f"导出成功 请查看 {save_path}/{now_login_user.uin}_{self.title}_data.json", "success") log(f"导出成功 请查看 {save_path}/{now_login_user.uin}_{self.title}_data.json", "SUCCESS")
except Exception as e: except Exception as e:
log(e, "error") log(e, "ERROR")
def export_excel(self, e): def export_excel(self, e):
export_data = [] export_data = []
@ -365,9 +362,9 @@ class PaginatedContainer(ft.Column):
df = pd.DataFrame(export_data) df = pd.DataFrame(export_data)
# 保存为 Excel 文件 # 保存为 Excel 文件
df.to_excel(f"{save_path}/{now_login_user.uin}_{self.title}_data.xlsx", index=False) df.to_excel(f"{save_path}/{now_login_user.uin}_{self.title}_data.xlsx", index=False)
log(f"导出成功 请查看 {save_path}/{now_login_user.uin}_{self.title}_data.xlsx", "success") log(f"导出成功 请查看 {save_path}/{now_login_user.uin}_{self.title}_data.xlsx", "SUCCESS")
except Exception as e: except Exception as e:
log(e, "error") log(e, "ERROR")
def export_html(self, e): def export_html(self, e):
# HTML 头部和样式 # HTML 头部和样式
@ -500,9 +497,9 @@ class PaginatedContainer(ft.Column):
with open(file_path, 'w', encoding='utf-8') as f: with open(file_path, 'w', encoding='utf-8') as f:
f.write(html_content) f.write(html_content)
# 日志记录 # 日志记录
log(f"导出成功 请查看 {save_path}/{file_name}", "success") log(f"导出成功 请查看 {save_path}/{file_name}", "SUCCESS")
except Exception as e: except Exception as e:
log(f"导出失败 {e}", "error") log(f"导出失败 {e}", "ERROR")
def export_markdown(self, e): def export_markdown(self, e):
# 创建 Markdown 内容的列表 # 创建 Markdown 内容的列表
@ -537,10 +534,10 @@ class PaginatedContainer(ft.Column):
with open(f"{save_path}/{now_login_user.uin}_{self.title}_data.md", 'w', encoding='utf-8') as f: with open(f"{save_path}/{now_login_user.uin}_{self.title}_data.md", 'w', encoding='utf-8') as f:
f.write(markdown_content) f.write(markdown_content)
log(f"导出成功 请查看 {save_path}/{now_login_user.uin}_{self.title}_data.md", "success") log(f"导出成功 请查看 {save_path}/{now_login_user.uin}_{self.title}_data.md", "SUCCESS")
except Exception as e: except Exception as e:
print(traceback.format_exc()) print(traceback.format_exc())
log(e, "error") log(e, "ERROR")
def did_mount(self): def did_mount(self):
"""This method is called when the control is added to the page.""" """This method is called when the control is added to the page."""
@ -719,6 +716,7 @@ def main(page: ft.Page):
page.title = f"QQ空间历史内容获取 v{version} Powered by LibraHp" page.title = f"QQ空间历史内容获取 v{version} Powered by LibraHp"
page.horizontal_alignment = "start" page.horizontal_alignment = "start"
page.vertical_alignment = "center" page.vertical_alignment = "center"
page.window.icon = "assets/icon.ico"
# page.window.resizable = False # page.window.resizable = False
page.padding = ft.padding.only(20, 20, 20, 5) page.padding = ft.padding.only(20, 20, 20, 5)
page.window.min_height = 700 page.window.min_height = 700
@ -781,7 +779,7 @@ def main(page: ft.Page):
except Exception as e: except Exception as e:
print(traceback.format_exc()) print(traceback.format_exc())
log("二维码获取问题:" + e, "error") log("二维码获取问题:" + e, "ERROR")
return None return None
def get_login_user_info(): def get_login_user_info():
@ -908,13 +906,13 @@ def main(page: ft.Page):
os.makedirs(user_path, exist_ok=True) os.makedirs(user_path, exist_ok=True)
save_path = user_path # 更新全局保存路径 save_path = user_path # 更新全局保存路径
log(f"用户目录创建成功: {save_path}", "success") log(f"用户目录创建成功: {save_path}", "SUCCESS")
except PermissionError as e: except PermissionError as e:
log(f"文件权限不足: {e}. 请尝试选择不同的目录或以管理员身份运行。", "error") log(f"文件权限不足: {e}. 请尝试选择不同的目录或以管理员身份运行。", "ERROR")
except Exception as e: except Exception as e:
print(traceback.format_exc()) print(traceback.format_exc())
log(f"创建用户目录时发生错误: {e}", "error") log(f"创建用户目录时发生错误: {e}", "ERROR")
# 获取内容页面 # 获取内容页面
def create_get_content_page(): def create_get_content_page():
@ -958,7 +956,7 @@ def main(page: ft.Page):
r = requests.get(url, cookies=cookies, allow_redirects=False) r = requests.get(url, cookies=cookies, allow_redirects=False)
target_cookies = requests.utils.dict_from_cookiejar(r.cookies) target_cookies = requests.utils.dict_from_cookiejar(r.cookies)
page.session.set("user_cookies", target_cookies) page.session.set("user_cookies", target_cookies)
log(f"登录成功,欢迎您,{page.session.get('user_cookies')['uin']}", "success") log(f"登录成功,欢迎您,{page.session.get('user_cookies')['uin']}", "SUCCESS")
get_login_user_info() get_login_user_info()
create_user_dir() create_user_dir()
progress_bar, login_text = show_login_content() progress_bar, login_text = show_login_content()
@ -966,11 +964,11 @@ def main(page: ft.Page):
# p_skey = requests.utils.dict_from_cookiejar(r.cookies).get('p_skey') # p_skey = requests.utils.dict_from_cookiejar(r.cookies).get('p_skey')
return return
except Exception as e: except Exception as e:
log("登录过程问题:" + e, "error") log("登录过程问题:" + e, "ERROR")
return return
except Exception as e: except Exception as e:
print(traceback.format_exc()) print(traceback.format_exc())
log("二维码状态问题:" + e, "error") log("二维码状态问题:" + e, "ERROR")
return return
page.update() page.update()
@ -1054,8 +1052,8 @@ def main(page: ft.Page):
headers=headers, headers=headers,
timeout=(5, 10) # 设置连接超时为5秒读取超时为10秒 timeout=(5, 10) # 设置连接超时为5秒读取超时为10秒
) )
except requests.Timeout: except Exception as e:
return None return 'None'
return response return response
@ -1081,7 +1079,7 @@ def main(page: ft.Page):
except Exception as e: except Exception as e:
print(traceback.format_exc()) print(traceback.format_exc())
if is_debug: if is_debug:
log(e, "error") log(e, "ERROR")
return total return total
def get_hitokoto(): def get_hitokoto():
@ -1113,7 +1111,7 @@ def main(page: ft.Page):
message_content = get_message(i * 100, 100).content message_content = get_message(i * 100, 100).content
message = message_content.decode('utf-8') if message_content else None message = message_content.decode('utf-8') if message_content else None
# if is_debug: # if is_debug:
# log(message, "debug") # log(message, "DEBUG")
# 确保消息内容存在 # 确保消息内容存在
if not message: if not message:
continue continue
@ -1122,7 +1120,7 @@ def main(page: ft.Page):
html = process_old_html(message) html = process_old_html(message)
# 确保 HTML 中包含有效信息 # 确保 HTML 中包含有效信息
if is_debug: if is_debug:
log(html, "debug") log(html, "DEBUG")
if "li" not in html: if "li" not in html:
continue continue
@ -1189,12 +1187,12 @@ def main(page: ft.Page):
except Exception as e: except Exception as e:
print(traceback.format_exc()) print(traceback.format_exc())
log(f"处理消息时发生错误: {e}", "error") log(f"处理消息时发生错误: {e}", "ERROR")
continue continue
# 完成消息获取 # 完成消息获取
content_area.content.clean() content_area.content.clean()
log("获取成功!", "success") log("获取成功!", "SUCCESS")
clean_content() clean_content()
unlock_tabs() unlock_tabs()
content_area.content.controls.append(get_message_result()) content_area.content.controls.append(get_message_result())
@ -1202,7 +1200,7 @@ def main(page: ft.Page):
except Exception as e: except Exception as e:
print(traceback.format_exc()) print(traceback.format_exc())
log(f"获取消息时发生错误: {e}", "error") log(f"获取消息时发生错误: {e}", "ERROR")
def get_message_result(): def get_message_result():
# 用户信息栏 # 用户信息栏
@ -1453,7 +1451,7 @@ def main(page: ft.Page):
log_list = ft.Text(ref=log_info_ref, size=12, color="blue") log_list = ft.Text(ref=log_info_ref, size=12, color="blue")
page.add(main_layout) page.add(main_layout)
page.add(log_list) page.add(log_list)
log("开始运行...", "success") log("开始运行...", "SUCCESS")
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -2,4 +2,5 @@ beautifulsoup4==4.12.2
flet==0.24.1 flet==0.24.1
pandas==2.2.3 pandas==2.2.3
Requests==2.31.0 Requests==2.31.0
openpyxl==3.1.5 openpyxl==3.1.5
dateparser==1.2.0

View File

@ -1,3 +1,4 @@
# UTF-8
VSVersionInfo( VSVersionInfo(
ffi=FixedFileInfo( ffi=FixedFileInfo(
filevers=(1, 0, 2, 0), filevers=(1, 0, 2, 0),
@ -13,15 +14,16 @@ VSVersionInfo(
StringFileInfo( StringFileInfo(
[ [
StringTable( StringTable(
'040904B0', '040904e4',
[StringStruct('CompanyName', 'LibraHp'), [StringStruct('CompanyName', 'GetQzoneHistory'),
StringStruct('FileDescription', '获取QQ空间发布的历史内容'), StringStruct('FileDescription', 'GetQzoneHistory'),
StringStruct('FileVersion', '1.0.2'), StringStruct('FileVersion', '1.0.2.0'),
StringStruct('InternalName', 'GetQzoneHistory'), StringStruct('InternalName', 'GetQzoneHistory'),
StringStruct('LegalCopyright', 'LibraHp'),
StringStruct('OriginalFilename', 'GetQzoneHistory.exe'), StringStruct('OriginalFilename', 'GetQzoneHistory.exe'),
StringStruct('ProductName', 'GetQzoneHistory'), StringStruct('ProductName', 'GetQzoneHistory'),
StringStruct('ProductVersion', '1.0.2')] StringStruct('ProductVersion', '1.0.2')])
)]), ]),
VarFileInfo([VarStruct('Translation', [0, 1200])]) VarFileInfo([VarStruct('Translation', [2052, 1252])])
] ]
) )