3.1.0,很多更改丢失,重新恢复的文件
This commit is contained in:
1 parent
81001c4083
commit
6137f5e6f8
46 files changed
+3233
-3000
No files matched your search
@@ -0,0 +1,48 @@
|
||||
# -*- coding: utf-8 -*-#
|
||||
# -------------------------------------------------------------------------------
|
||||
# Name: __init__.py.py
|
||||
# Description:
|
||||
# Author: xaoyaoo
|
||||
# Date: 2024/04/15
|
||||
# -------------------------------------------------------------------------------
|
||||
import pandas as pd
|
||||
|
||||
from .utils import download_file
|
||||
|
||||
from .dbFavorite import FavoriteHandler
|
||||
from .dbMSG import MsgHandler
|
||||
from .dbMicro import MicroHandler
|
||||
from .dbMedia import MediaHandler
|
||||
from .dbOpenIMContact import OpenIMContactHandler
|
||||
from .dbPublicMsg import PublicMsgHandler
|
||||
from .dbOpenIMMedia import OpenIMMediaHandler
|
||||
|
||||
from .export.exportCSV import export_csv
|
||||
from .export.exportJSON import export_json
|
||||
|
||||
|
||||
class DBHandler(MicroHandler, MediaHandler, OpenIMContactHandler, PublicMsgHandler, OpenIMMediaHandler,
|
||||
FavoriteHandler):
|
||||
_class_name = "DBHandler"
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.MSG_exist = self.Msg_tables_exist()
|
||||
self.Micro_exist = self.Micro_tables_exist()
|
||||
self.Media_exist = self.Media_tables_exist()
|
||||
self.OpenIMContact_exist = self.OpenIMContact_tables_exist()
|
||||
self.PublicMsg_exist = self.PublicMSG_tables_exist()
|
||||
self.OpenIMMedia_exist = self.OpenIMMedia_tables_exist()
|
||||
self.Favorite_exist = self.Favorite_tables_exist()
|
||||
|
||||
# print(self.MSG_exist, self.Micro_exist, self.Media_exist, self.OpenIMContact_exist, self.PublicMsg_exist,
|
||||
# self.OpenIMMedia_exist, self.Favorite_exist)
|
||||
|
||||
def get_user(self, word=None, wxids=None, labels=None):
|
||||
"""
|
||||
获取联系人列表
|
||||
"""
|
||||
users = self.get_user_list(word=word, wxids=wxids, label_ids=labels)
|
||||
if self.OpenIMContact_exist:
|
||||
users.update(self.get_im_user_list(word=word, wxids=wxids))
|
||||
return users
|
||||
@@ -0,0 +1,158 @@
|
||||
# -*- coding: utf-8 -*-#
|
||||
# -------------------------------------------------------------------------------
|
||||
# Name: parsingFavorite.py
|
||||
# Description:
|
||||
# Author: xaoyaoo
|
||||
# Date: 2024/05/18
|
||||
# -------------------------------------------------------------------------------
|
||||
import pandas as pd
|
||||
|
||||
from .dbbase import DatabaseBase
|
||||
from .utils import timestamp2str, xml2dict
|
||||
|
||||
|
||||
# * FavItems:收藏的消息条目列表
|
||||
# * FavDataItem:收藏的具体数据。大概可以确定以下两点
|
||||
# * 即使只是简单收藏一篇公众号文章也会在 FavDataItem 中有一个对应的记录
|
||||
# * 对于收藏的合并转发类型的消息,合并转发中的每一条消息在 FavDataItem 中都是一个独立的记录
|
||||
# * FavTags:为收藏内容添加的标签
|
||||
|
||||
|
||||
class FavoriteHandler(DatabaseBase):
|
||||
_class_name = "Favorite"
|
||||
Favorite_required_tables = ["FavItems", "FavDataItem", "FavTagDatas", "FavBindTagDatas"]
|
||||
|
||||
def Favorite_tables_exist(self):
|
||||
"""
|
||||
判断该类所需要的表是否存在
|
||||
"""
|
||||
return self.check_tables_exist(self.Favorite_required_tables)
|
||||
|
||||
def get_tags(self, LocalID):
|
||||
"""
|
||||
return: {LocalID: TagName}
|
||||
"""
|
||||
if LocalID is None:
|
||||
sql = "select LocalID, TagName from FavTagDatas order by ServerSeq"
|
||||
else:
|
||||
sql = "select LocalID, TagName from FavTagDatas where LocalID = '%s' order by ServerSeq " % LocalID
|
||||
tags = self.execute(sql) # [(1, 797940830, '程序语言类'), (2, 806153863, '账单')]
|
||||
# 转换为字典
|
||||
tags = {tag[0]: tag[1] for tag in tags}
|
||||
return tags
|
||||
|
||||
def get_FavBindTags(self):
|
||||
"""
|
||||
return: [(FavLocalID, TagName)]
|
||||
"""
|
||||
sql = "select A.FavLocalID, B.TagName from FavBindTagDatas A, FavTagDatas B where A.TagLocalID = B.LocalID"
|
||||
FavBindTags = self.execute(sql)
|
||||
return FavBindTags
|
||||
|
||||
def get_favorite(self):
|
||||
"""
|
||||
return: [{FavItemsFields}, {FavItemsFields}]
|
||||
"""
|
||||
FavItemsFields = {
|
||||
"FavLocalID": "本地收藏ID",
|
||||
"SvrFavId": "服务器收藏ID",
|
||||
"SourceId": "源ID",
|
||||
"Type": "类型",
|
||||
"SourceType": "源类型",
|
||||
"LocalStatus": "本地状态",
|
||||
"Flag": "标记",
|
||||
"Status": "状态",
|
||||
"FromUser": "源用户",
|
||||
"RealChatName": "实际聊天名称",
|
||||
"SearchKey": "搜索关键字",
|
||||
"UpdateTime": "更新时间",
|
||||
"reseverd0": "预留字段0",
|
||||
"XmlBuf": "XML缓冲区"
|
||||
}
|
||||
FavDataItemFields = {
|
||||
"FavLocalID": "本地收藏ID",
|
||||
"Type": "类型",
|
||||
"DataId": "数据ID",
|
||||
"HtmlId": "HTML ID",
|
||||
"Datasourceid": "数据源ID",
|
||||
"Datastatus": "数据状态",
|
||||
"Datafmt": "数据格式",
|
||||
"Datatitle": "数据标题",
|
||||
"Datadesc": "数据描述",
|
||||
"Thumbfullmd5": "缩略图全MD5",
|
||||
"Thumbhead256md5": "缩略图头256MD5",
|
||||
"Thumbfullsize": "缩略图全尺寸",
|
||||
"fullmd5": "全MD5",
|
||||
"head256md5": "头256MD5",
|
||||
"fullsize": "全尺寸",
|
||||
"cdn_thumburl": "CDN缩略图URL",
|
||||
"cdn_thumbkey": "CDN缩略图KEY",
|
||||
"thumb_width": "缩略图宽度",
|
||||
"thumb_height": "缩略图高度",
|
||||
"cdn_dataurl": "CDN数据URL",
|
||||
"cdn_datakey": "CDN数据KEY",
|
||||
"cdn_encryver": "CDN加密版本",
|
||||
"duration": "时长",
|
||||
"stream_weburl": "流媒体WEB URL",
|
||||
"stream_dataurl": "流媒体数据URL",
|
||||
"stream_lowbandurl": "流媒体低带宽URL",
|
||||
"sourcethumbpath": "源缩略图路径",
|
||||
"sourcedatapath": "源数据路径",
|
||||
"stream_videoid": "流媒体视频ID",
|
||||
"Rerserved1": "保留字段1",
|
||||
"Rerserved2": "保留字段2",
|
||||
"Rerserved3": "保留字段3",
|
||||
"Rerserved4": "保留字段4",
|
||||
"Rerserved5": "保留字段5",
|
||||
"Rerserved6": "保留字段6",
|
||||
"Rerserved7": "保留字段7"
|
||||
}
|
||||
|
||||
sql1 = "select " + ",".join(FavItemsFields.keys()) + " from FavItems order by UpdateTime desc"
|
||||
sql2 = "select " + ",".join(FavDataItemFields.keys()) + " from FavDataItem B order by B.RecId asc"
|
||||
|
||||
FavItemsList = self.execute(sql1)
|
||||
FavDataItemList = self.execute(sql2)
|
||||
if FavItemsList is None or len(FavItemsList) == 0:
|
||||
return False
|
||||
|
||||
FavDataDict = {}
|
||||
if FavDataItemList and len(FavDataItemList) >= 0:
|
||||
for item in FavDataItemList:
|
||||
data_dict = {}
|
||||
for i, key in enumerate(FavDataItemFields.keys()):
|
||||
data_dict[key] = item[i]
|
||||
FavDataDict[item[0]] = FavDataDict.get(item[0], []) + [data_dict]
|
||||
# 获取标签
|
||||
FavTags = self.get_FavBindTags()
|
||||
FavTagsDict = {}
|
||||
for FavLocalID, TagName in FavTags:
|
||||
FavTagsDict[FavLocalID] = FavTagsDict.get(FavLocalID, []) + [TagName]
|
||||
|
||||
pf = pd.DataFrame(FavItemsList)
|
||||
pf.columns = FavItemsFields.keys() # set column names
|
||||
pf["UpdateTime"] = pf["UpdateTime"].apply(timestamp2str) # 处理时间
|
||||
pf["XmlBuf"] = pf["XmlBuf"].apply(xml2dict) # 处理xml
|
||||
pf["TypeName"] = pf["Type"].apply(FavoriteTypeId2Name) # 添加类型名称列
|
||||
pf["FavData"] = pf["FavLocalID"].apply(lambda x: FavDataDict.get(x, [])) # 添加数据列
|
||||
pf["Tags"] = pf["FavLocalID"].apply(lambda x: FavTagsDict.get(x, [])) # 添加标签列
|
||||
pf = pf.fillna("") # 去掉Nan
|
||||
rdata = pf.to_dict(orient="records")
|
||||
return rdata
|
||||
|
||||
|
||||
def FavoriteTypeId2Name(Type):
|
||||
TypeNameDict = {
|
||||
1: "文本", # 文本 已测试
|
||||
2: "图片", # 图片 已测试
|
||||
3: "语音", # 语音
|
||||
4: "视频", # 视频 已测试
|
||||
5: "链接", # 链接 已测试
|
||||
6: "位置", # 位置
|
||||
7: "小程序", # 小程序
|
||||
8: "文件", # 文件 已测试
|
||||
14: "聊天记录", # 聊天记录 已测试
|
||||
16: "群聊视频", # 群聊中的视频 可能
|
||||
18: "笔记" # 笔记 已测试
|
||||
}
|
||||
return TypeNameDict.get(Type, "未知")
|
||||
@@ -0,0 +1,522 @@
|
||||
# -*- coding: utf-8 -*-#
|
||||
# -------------------------------------------------------------------------------
|
||||
# Name: parsingMSG.py
|
||||
# Description:
|
||||
# Author: xaoyaoo
|
||||
# Date: 2024/04/15
|
||||
# -------------------------------------------------------------------------------
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
# import time
|
||||
|
||||
# import pandas as pd
|
||||
|
||||
from .dbbase import DatabaseBase
|
||||
from .utils import db_error, timestamp2str, xml2dict, match_BytesExtra, type_converter, \
|
||||
get_md5, name2typeid, db_loger
|
||||
import lz4.block
|
||||
import blackboxprotobuf
|
||||
|
||||
|
||||
class MsgHandler(DatabaseBase):
|
||||
_class_name = "MSG"
|
||||
MSG_required_tables = ["MSG"]
|
||||
|
||||
def Msg_tables_exist(self):
|
||||
"""
|
||||
判断该类所需要的表是否存在
|
||||
"""
|
||||
return self.check_tables_exist(self.MSG_required_tables)
|
||||
|
||||
@db_error
|
||||
def get_msg_count(self, wxids: list = ""):
|
||||
"""
|
||||
获取聊天记录数量,根据wxid获取单个联系人的聊天记录数量,不传wxid则获取所有联系人的聊天记录数量
|
||||
:param wxids: wxid list
|
||||
:return: 聊天记录数量列表 {wxid: chat_count}
|
||||
"""
|
||||
if isinstance(wxids, str):
|
||||
wxids = [wxids]
|
||||
if wxids:
|
||||
wxids = "('" + "','".join(wxids) + "')"
|
||||
sql = f"SELECT StrTalker, COUNT(*) FROM MSG WHERE StrTalker IN {wxids} GROUP BY StrTalker ORDER BY COUNT(*) DESC;"
|
||||
else:
|
||||
sql = f"SELECT StrTalker, COUNT(*) FROM MSG GROUP BY StrTalker ORDER BY COUNT(*) DESC;"
|
||||
sql_total = f"SELECT COUNT(*) FROM MSG;"
|
||||
|
||||
result = self.execute(sql)
|
||||
total_ret = self.execute(sql_total)
|
||||
|
||||
if not result:
|
||||
return {}
|
||||
total = 0
|
||||
if total_ret and len(total_ret) > 0:
|
||||
total = total_ret[0][0]
|
||||
|
||||
msg_count = {"total": total}
|
||||
msg_count.update({row[0]: row[1] for row in result})
|
||||
return msg_count
|
||||
|
||||
# 单条消息处理
|
||||
@db_error
|
||||
def get_msg_detail(self, row):
|
||||
"""
|
||||
获取单条消息详情,格式化输出
|
||||
"""
|
||||
(localId, TalkerId, MsgSvrID, Type, SubType, CreateTime, IsSender, Sequence, StatusEx, FlagEx, Status,
|
||||
MsgSequence, StrContent, MsgServerSeq, StrTalker, DisplayContent, Reserved0, Reserved1, Reserved3,
|
||||
Reserved4, Reserved5, Reserved6, CompressContent, BytesExtra, BytesTrans, Reserved2, _id) = row
|
||||
|
||||
CreateTime = timestamp2str(CreateTime)
|
||||
|
||||
type_id = (Type, SubType)
|
||||
type_name = type_converter(type_id)
|
||||
|
||||
msg = StrContent
|
||||
src = ""
|
||||
|
||||
if type_id == (1, 0): # 文本
|
||||
msg = StrContent
|
||||
|
||||
elif type_id == (3, 0): # 图片
|
||||
DictExtra = get_BytesExtra(BytesExtra)
|
||||
DictExtra_str = str(DictExtra)
|
||||
img_paths = [i for i in re.findall(r"(FileStorage.*?)'", DictExtra_str)]
|
||||
img_paths = sorted(img_paths, key=lambda p: "Image" in p, reverse=True)
|
||||
if img_paths:
|
||||
img_path = img_paths[0].replace("'", "")
|
||||
img_path = [i for i in img_path.split("\\") if i]
|
||||
img_path = os.path.join(*img_path)
|
||||
src = img_path
|
||||
else:
|
||||
src = ""
|
||||
msg = "图片"
|
||||
elif type_id == (34, 0): # 语音
|
||||
tmp_c = xml2dict(StrContent)
|
||||
voicelength = tmp_c.get("voicemsg", {}).get("voicelength", "")
|
||||
transtext = tmp_c.get("voicetrans", {}).get("transtext", "")
|
||||
if voicelength.isdigit():
|
||||
voicelength = int(voicelength) / 1000
|
||||
voicelength = f"{voicelength:.2f}"
|
||||
msg = f"语音时长:{voicelength}秒\n翻译结果:{transtext}" if transtext else f"语音时长:{voicelength}秒"
|
||||
src = os.path.join("audio", f"{StrTalker}",
|
||||
f"{CreateTime.replace(':', '-').replace(' ', '_')}_{IsSender}_{MsgSvrID}.wav")
|
||||
elif type_id == (43, 0): # 视频
|
||||
DictExtra = get_BytesExtra(BytesExtra)
|
||||
DictExtra = str(DictExtra)
|
||||
|
||||
DictExtra_str = str(DictExtra)
|
||||
video_paths = [i for i in re.findall(r"(FileStorage.*?)'", DictExtra_str)]
|
||||
video_paths = sorted(video_paths, key=lambda p: "mp4" in p, reverse=True)
|
||||
if video_paths:
|
||||
video_path = video_paths[0].replace("'", "")
|
||||
video_path = [i for i in video_path.split("\\") if i]
|
||||
video_path = os.path.join(*video_path)
|
||||
src = video_path
|
||||
else:
|
||||
src = ""
|
||||
msg = "视频"
|
||||
|
||||
elif type_id == (47, 0): # 动画表情
|
||||
content_tmp = xml2dict(StrContent)
|
||||
cdnurl = content_tmp.get("emoji", {}).get("cdnurl", "")
|
||||
if not cdnurl:
|
||||
DictExtra = get_BytesExtra(BytesExtra)
|
||||
cdnurl = match_BytesExtra(DictExtra)
|
||||
if cdnurl:
|
||||
content = {"src": cdnurl, "msg": "表情"}
|
||||
|
||||
elif type_id == (48, 0): # 地图信息
|
||||
content_tmp = xml2dict(StrContent)
|
||||
location = content_tmp.get("location", {})
|
||||
msg = (f"纬度:【{location.pop('x')}】 经度:【{location.pop('y')}】\n"
|
||||
f"位置:{location.pop('label')} {location.pop('poiname')}\n"
|
||||
f"其他信息:{json.dumps(location, ensure_ascii=False, indent=4)}"
|
||||
)
|
||||
src = ""
|
||||
elif type_id == (49, 0): # 文件
|
||||
DictExtra = get_BytesExtra(BytesExtra)
|
||||
url = match_BytesExtra(DictExtra)
|
||||
src = url
|
||||
file_name = os.path.basename(url)
|
||||
msg = file_name
|
||||
|
||||
elif type_id == (49, 5): # (分享)卡片式链接
|
||||
CompressContent = decompress_CompressContent(CompressContent)
|
||||
CompressContent_tmp = xml2dict(CompressContent)
|
||||
appmsg = CompressContent_tmp.get("appmsg", {})
|
||||
title = appmsg.get("title", "")
|
||||
des = appmsg.get("des", "")
|
||||
url = appmsg.get("url", "")
|
||||
msg = f"{title}\n{des}\n\n{url}"
|
||||
src = url
|
||||
|
||||
elif type_id == (49, 19): # 合并转发的聊天记录
|
||||
CompressContent = decompress_CompressContent(CompressContent)
|
||||
content_tmp = xml2dict(CompressContent)
|
||||
title = content_tmp.get("appmsg", {}).get("title", "")
|
||||
des = content_tmp.get("appmsg", {}).get("des", "")
|
||||
recorditem = content_tmp.get("appmsg", {}).get("recorditem", "")
|
||||
recorditem = xml2dict(recorditem)
|
||||
msg = f"{title}\n{des}"
|
||||
src = recorditem
|
||||
|
||||
elif type_id == (49, 57): # 带有引用的文本消息
|
||||
CompressContent = decompress_CompressContent(CompressContent)
|
||||
content_tmp = xml2dict(CompressContent)
|
||||
appmsg = content_tmp.get("appmsg", {})
|
||||
title = appmsg.get("title", "")
|
||||
refermsg = appmsg.get("refermsg", {})
|
||||
displayname = refermsg.get("displayname", "")
|
||||
display_content = refermsg.get("content", "")
|
||||
display_createtime = refermsg.get("createtime", "")
|
||||
display_createtime = timestamp2str(
|
||||
int(display_createtime)) if display_createtime.isdigit() else display_createtime
|
||||
if display_content.startswith("<?xml"):
|
||||
display_content = xml2dict(display_content)
|
||||
appmsg1 = display_content.get("appmsg", {})
|
||||
title1 = appmsg1.get("title", "")
|
||||
if title1: display_content = title1
|
||||
msg = f"{title}\n\n[引用]({display_createtime}){displayname}:{display_content}"
|
||||
src = ""
|
||||
|
||||
elif type_id == (49, 2000): # 转账消息
|
||||
CompressContent = decompress_CompressContent(CompressContent)
|
||||
content_tmp = xml2dict(CompressContent)
|
||||
wcpayinfo = content_tmp.get("appmsg", {}).get("wcpayinfo", {})
|
||||
paysubtype = wcpayinfo.get("paysubtype", "") # 转账类型
|
||||
feedesc = wcpayinfo.get("feedesc", "") # 转账金额
|
||||
pay_memo = wcpayinfo.get("pay_memo", "") # 转账备注
|
||||
begintransfertime = wcpayinfo.get("begintransfertime", "") # 转账开始时间
|
||||
msg = (f"{'已收款' if paysubtype == '3' else '转账'}:{feedesc}\n"
|
||||
f"转账说明:{pay_memo if pay_memo else ''}\n"
|
||||
f"转账时间:{timestamp2str(begintransfertime)}\n"
|
||||
)
|
||||
src = ""
|
||||
|
||||
elif type_id[0] == 49 and type_id[1] != 0:
|
||||
DictExtra = get_BytesExtra(BytesExtra)
|
||||
url = match_BytesExtra(DictExtra)
|
||||
src = url
|
||||
msg = type_name
|
||||
|
||||
elif type_id == (50, 0): # 语音通话
|
||||
msg = "语音/视频通话[%s]" % DisplayContent
|
||||
|
||||
# elif type_id == (10000, 0):
|
||||
# msg = StrContent
|
||||
# elif type_id == (10000, 4):
|
||||
# msg = StrContent
|
||||
# elif type_id == (10000, 8000):
|
||||
# msg = StrContent
|
||||
|
||||
talker = "未知"
|
||||
if IsSender == 1:
|
||||
talker = "我"
|
||||
else:
|
||||
if StrTalker.endswith("@chatroom"):
|
||||
bytes_extra = get_BytesExtra(BytesExtra)
|
||||
if bytes_extra:
|
||||
try:
|
||||
talker = bytes_extra['3'][0]['2']
|
||||
if "publisher-id" in talker:
|
||||
talker = "系统"
|
||||
except:
|
||||
pass
|
||||
else:
|
||||
talker = StrTalker
|
||||
|
||||
row_data = {"id": _id, "MsgSvrID": str(MsgSvrID), "type_name": type_name, "is_sender": IsSender,
|
||||
"talker": talker, "room_name": StrTalker, "msg": msg, "src": src, "extra": {},
|
||||
"CreateTime": CreateTime, }
|
||||
return row_data
|
||||
|
||||
@db_error
|
||||
def get_msg_list(self, wxid="", start_index=0, page_size=500, msg_type: str = "", msg_sub_type: str = "",
|
||||
start_createtime=None, end_createtime=None):
|
||||
sql_base = ("SELECT localId,TalkerId,MsgSvrID,Type,SubType,CreateTime,IsSender,Sequence,StatusEx,FlagEx,Status,"
|
||||
"MsgSequence,StrContent,MsgServerSeq,StrTalker,DisplayContent,Reserved0,Reserved1,Reserved3,"
|
||||
"Reserved4,Reserved5,Reserved6,CompressContent,BytesExtra,BytesTrans,Reserved2,"
|
||||
"ROW_NUMBER() OVER (ORDER BY CreateTime ASC) AS id "
|
||||
"FROM MSG ")
|
||||
|
||||
param = ()
|
||||
sql_wxid, param = ("AND StrTalker=? ", param + (wxid,)) if wxid else ("", param)
|
||||
sql_type, param = ("AND Type=? ", param + (msg_type,)) if msg_type else ("", param)
|
||||
sql_sub_type, param = ("AND SubType=? ", param + (msg_sub_type,)) if msg_type and msg_sub_type else ("", param)
|
||||
sql_start_createtime, param = ("AND CreateTime>=? ", param + (start_createtime,)) if start_createtime else (
|
||||
"", param)
|
||||
sql_end_createtime, param = ("AND CreateTime<=? ", param + (end_createtime,)) if end_createtime else ("", param)
|
||||
|
||||
sql = (
|
||||
f"{sql_base} WHERE 1=1 "
|
||||
f"{sql_wxid}"
|
||||
f"{sql_type}"
|
||||
f"{sql_sub_type}"
|
||||
f"{sql_start_createtime}"
|
||||
f"{sql_end_createtime}"
|
||||
f"ORDER BY CreateTime ASC LIMIT ?,?"
|
||||
)
|
||||
param = param + (start_index, page_size)
|
||||
result = self.execute(sql, param)
|
||||
if not result:
|
||||
return [], []
|
||||
|
||||
result_data = (self.get_msg_detail(row) for row in result)
|
||||
rdata = list(result_data) # 转为列表
|
||||
wxid_list = {d['talker'] for d in rdata} # 创建一个无重复的 wxid 列表
|
||||
|
||||
return rdata, list(wxid_list)
|
||||
|
||||
|
||||
@db_error
|
||||
def decompress_CompressContent(data):
|
||||
"""
|
||||
解压缩Msg:CompressContent内容
|
||||
:param data: CompressContent内容 bytes
|
||||
:return:
|
||||
"""
|
||||
if data is None or not isinstance(data, bytes):
|
||||
return None
|
||||
try:
|
||||
dst = lz4.block.decompress(data, uncompressed_size=len(data) << 8)
|
||||
dst = dst.replace(b'\x00', b'') # 已经解码完成后,还含有0x00的部分,要删掉,要不后面ET识别的时候会报错
|
||||
uncompressed_data = dst.decode('utf-8', errors='ignore')
|
||||
return uncompressed_data
|
||||
except Exception as e:
|
||||
return data.decode('utf-8', errors='ignore')
|
||||
|
||||
|
||||
@db_error
|
||||
def get_BytesExtra(BytesExtra):
|
||||
BytesExtra_message_type = {
|
||||
"1": {
|
||||
"type": "message",
|
||||
"message_typedef": {
|
||||
"1": {
|
||||
"type": "int",
|
||||
"name": ""
|
||||
},
|
||||
"2": {
|
||||
"type": "int",
|
||||
"name": ""
|
||||
}
|
||||
},
|
||||
"name": "1"
|
||||
},
|
||||
"3": {
|
||||
"type": "message",
|
||||
"message_typedef": {
|
||||
"1": {
|
||||
"type": "int",
|
||||
"name": ""
|
||||
},
|
||||
"2": {
|
||||
"type": "str",
|
||||
"name": ""
|
||||
}
|
||||
},
|
||||
"name": "3",
|
||||
"alt_typedefs": {
|
||||
"1": {
|
||||
"1": {
|
||||
"type": "int",
|
||||
"name": ""
|
||||
},
|
||||
"2": {
|
||||
"type": "message",
|
||||
"message_typedef": {},
|
||||
"name": ""
|
||||
}
|
||||
},
|
||||
"2": {
|
||||
"1": {
|
||||
"type": "int",
|
||||
"name": ""
|
||||
},
|
||||
"2": {
|
||||
"type": "message",
|
||||
"message_typedef": {
|
||||
"13": {
|
||||
"type": "fixed32",
|
||||
"name": ""
|
||||
},
|
||||
"12": {
|
||||
"type": "fixed32",
|
||||
"name": ""
|
||||
}
|
||||
},
|
||||
"name": ""
|
||||
}
|
||||
},
|
||||
"3": {
|
||||
"1": {
|
||||
"type": "int",
|
||||
"name": ""
|
||||
},
|
||||
"2": {
|
||||
"type": "message",
|
||||
"message_typedef": {
|
||||
"15": {
|
||||
"type": "fixed64",
|
||||
"name": ""
|
||||
}
|
||||
},
|
||||
"name": ""
|
||||
}
|
||||
},
|
||||
"4": {
|
||||
"1": {
|
||||
"type": "int",
|
||||
"name": ""
|
||||
},
|
||||
"2": {
|
||||
"type": "message",
|
||||
"message_typedef": {
|
||||
"15": {
|
||||
"type": "int",
|
||||
"name": ""
|
||||
},
|
||||
"14": {
|
||||
"type": "fixed32",
|
||||
"name": ""
|
||||
}
|
||||
},
|
||||
"name": ""
|
||||
}
|
||||
},
|
||||
"5": {
|
||||
"1": {
|
||||
"type": "int",
|
||||
"name": ""
|
||||
},
|
||||
"2": {
|
||||
"type": "message",
|
||||
"message_typedef": {
|
||||
"12": {
|
||||
"type": "fixed32",
|
||||
"name": ""
|
||||
},
|
||||
"7": {
|
||||
"type": "fixed64",
|
||||
"name": ""
|
||||
},
|
||||
"6": {
|
||||
"type": "fixed64",
|
||||
"name": ""
|
||||
}
|
||||
},
|
||||
"name": ""
|
||||
}
|
||||
},
|
||||
"6": {
|
||||
"1": {
|
||||
"type": "int",
|
||||
"name": ""
|
||||
},
|
||||
"2": {
|
||||
"type": "message",
|
||||
"message_typedef": {
|
||||
"7": {
|
||||
"type": "fixed64",
|
||||
"name": ""
|
||||
},
|
||||
"6": {
|
||||
"type": "fixed32",
|
||||
"name": ""
|
||||
}
|
||||
},
|
||||
"name": ""
|
||||
}
|
||||
},
|
||||
"7": {
|
||||
"1": {
|
||||
"type": "int",
|
||||
"name": ""
|
||||
},
|
||||
"2": {
|
||||
"type": "message",
|
||||
"message_typedef": {
|
||||
"12": {
|
||||
"type": "fixed64",
|
||||
"name": ""
|
||||
}
|
||||
},
|
||||
"name": ""
|
||||
}
|
||||
},
|
||||
"8": {
|
||||
"1": {
|
||||
"type": "int",
|
||||
"name": ""
|
||||
},
|
||||
"2": {
|
||||
"type": "message",
|
||||
"message_typedef": {
|
||||
"6": {
|
||||
"type": "fixed64",
|
||||
"name": ""
|
||||
},
|
||||
"12": {
|
||||
"type": "fixed32",
|
||||
"name": ""
|
||||
}
|
||||
},
|
||||
"name": ""
|
||||
}
|
||||
},
|
||||
"9": {
|
||||
"1": {
|
||||
"type": "int",
|
||||
"name": ""
|
||||
},
|
||||
"2": {
|
||||
"type": "message",
|
||||
"message_typedef": {
|
||||
"15": {
|
||||
"type": "int",
|
||||
"name": ""
|
||||
},
|
||||
"12": {
|
||||
"type": "fixed64",
|
||||
"name": ""
|
||||
},
|
||||
"6": {
|
||||
"type": "int",
|
||||
"name": ""
|
||||
}
|
||||
},
|
||||
"name": ""
|
||||
}
|
||||
},
|
||||
"10": {
|
||||
"1": {
|
||||
"type": "int",
|
||||
"name": ""
|
||||
},
|
||||
"2": {
|
||||
"type": "message",
|
||||
"message_typedef": {
|
||||
"6": {
|
||||
"type": "fixed32",
|
||||
"name": ""
|
||||
},
|
||||
"12": {
|
||||
"type": "fixed64",
|
||||
"name": ""
|
||||
}
|
||||
},
|
||||
"name": ""
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
if BytesExtra is None or not isinstance(BytesExtra, bytes):
|
||||
return None
|
||||
try:
|
||||
deserialize_data, message_type = blackboxprotobuf.decode_message(BytesExtra, BytesExtra_message_type)
|
||||
return deserialize_data
|
||||
except Exception as e:
|
||||
return None
|
||||
@@ -0,0 +1,34 @@
|
||||
# -*- coding: utf-8 -*-#
|
||||
# -------------------------------------------------------------------------------
|
||||
# Name: MediaMSG_parsing.py
|
||||
# Description:
|
||||
# Author: xaoyaoo
|
||||
# Date: 2024/04/15
|
||||
# -------------------------------------------------------------------------------
|
||||
from .dbbase import DatabaseBase
|
||||
from .utils import silk2audio
|
||||
|
||||
|
||||
class MediaHandler(DatabaseBase):
|
||||
_class_name = "MediaMSG"
|
||||
Media_required_tables = ["Media"]
|
||||
|
||||
def Media_tables_exist(self):
|
||||
"""
|
||||
判断该类所需要的表是否存在
|
||||
"""
|
||||
return self.check_tables_exist(self.Media_required_tables)
|
||||
|
||||
def get_audio(self, MsgSvrID, is_play=False, is_wave=False, save_path=None, rate=24000):
|
||||
sql = "select Buf from Media where Reserved0=? "
|
||||
DBdata = self.execute(sql, (MsgSvrID,))
|
||||
if not DBdata:
|
||||
return False
|
||||
if len(DBdata) == 0:
|
||||
return False
|
||||
data = DBdata[0][0] # [1:] + b'\xFF\xFF'
|
||||
try:
|
||||
pcm_data = silk2audio(buf_data=data, is_play=is_play, is_wave=is_wave, save_path=save_path, rate=rate)
|
||||
return pcm_data
|
||||
except Exception as e:
|
||||
return False
|
||||
@@ -0,0 +1,306 @@
|
||||
# -*- coding: utf-8 -*-#
|
||||
# -------------------------------------------------------------------------------
|
||||
# Name: parsingMicroMsg.py
|
||||
# Description:
|
||||
# Author: xaoyaoo
|
||||
# Date: 2024/04/15
|
||||
# -------------------------------------------------------------------------------
|
||||
import logging
|
||||
|
||||
from .dbbase import DatabaseBase
|
||||
from .utils import timestamp2str, bytes2str, db_loger, db_error
|
||||
|
||||
import blackboxprotobuf
|
||||
|
||||
|
||||
class MicroHandler(DatabaseBase):
|
||||
_class_name = "MicroMsg"
|
||||
Micro_required_tables = ["ContactLabel", "Contact", "ContactHeadImgUrl", "Session", "ChatInfo", "ChatRoom",
|
||||
"ChatRoomInfo"]
|
||||
|
||||
def Micro_tables_exist(self):
|
||||
"""
|
||||
判断该类所需要的表是否存在
|
||||
"""
|
||||
return self.check_tables_exist(self.Micro_required_tables)
|
||||
|
||||
@db_error
|
||||
def get_labels(self, id_is_key=True):
|
||||
"""
|
||||
读取标签列表
|
||||
:param id_is_key: id_is_key: True: id作为key,False: name作为key
|
||||
:return:
|
||||
"""
|
||||
sql = "SELECT LabelId, LabelName FROM ContactLabel ORDER BY LabelName ASC;"
|
||||
result = self.execute(sql)
|
||||
if not result:
|
||||
return []
|
||||
if id_is_key:
|
||||
labels = {row[0]: row[1] for row in result}
|
||||
else:
|
||||
labels = {row[1]: row[0] for row in result}
|
||||
return labels
|
||||
|
||||
@db_error
|
||||
def get_session_list(self):
|
||||
"""
|
||||
获取会话列表
|
||||
:return: 会话列表
|
||||
"""
|
||||
sessions = {}
|
||||
sql = (
|
||||
"SELECT S.strUsrName,S.nOrder,S.nUnReadCount, S.strNickName, S.nStatus, S.nIsSend, S.strContent, "
|
||||
"S.nMsgLocalID, S.nMsgStatus, S.nTime, S.nMsgType, S.Reserved2 AS nMsgSubType, C.UserName, C.Alias, "
|
||||
"C.DelFlag, C.Type, C.VerifyFlag, C.Reserved1, C.Reserved2, C.Remark, C.NickName, C.LabelIDList, "
|
||||
"C.ChatRoomType, C.ChatRoomNotify, C.Reserved5, C.Reserved6 as describe, C.ExtraBuf, H.bigHeadImgUrl "
|
||||
"FROM (SELECT strUsrName, MAX(nTime) AS MaxnTime FROM Session GROUP BY strUsrName) AS SubQuery "
|
||||
"JOIN Session S ON S.strUsrName = SubQuery.strUsrName AND S.nTime = SubQuery.MaxnTime "
|
||||
"left join Contact C ON C.UserName = S.strUsrName "
|
||||
"LEFT JOIN ContactHeadImgUrl H ON C.UserName = H.usrName "
|
||||
"ORDER BY S.nOrder DESC;"
|
||||
)
|
||||
ret = self.execute(sql)
|
||||
if not ret:
|
||||
return sessions
|
||||
|
||||
id2label = self.get_labels()
|
||||
for row in ret:
|
||||
(strUsrName, nOrder, nUnReadCount, strNickName, nStatus, nIsSend, strContent,
|
||||
nMsgLocalID, nMsgStatus, nTime, nMsgType, nMsgSubType,
|
||||
UserName, Alias, DelFlag, Type, VerifyFlag, Reserved1, Reserved2, Remark, NickName, LabelIDList,
|
||||
ChatRoomType, ChatRoomNotify, Reserved5, describe, ExtraBuf, bigHeadImgUrl) = row
|
||||
|
||||
ExtraBuf = get_ExtraBuf(ExtraBuf)
|
||||
LabelIDList = LabelIDList.split(",") if LabelIDList else []
|
||||
LabelIDList = [id2label.get(int(label_id), label_id) for label_id in LabelIDList if label_id]
|
||||
nTime = timestamp2str(nTime) if nTime else None
|
||||
|
||||
sessions[strUsrName] = {
|
||||
"wxid": strUsrName, "nOrder": nOrder, "nUnReadCount": nUnReadCount, "strNickName": strNickName,
|
||||
"nStatus": nStatus, "nIsSend": nIsSend, "strContent": strContent, "nMsgLocalID": nMsgLocalID,
|
||||
"nMsgStatus": nMsgStatus, "nTime": nTime, "nMsgType": nMsgType, "nMsgSubType": nMsgSubType,
|
||||
"nickname": NickName, "remark": Remark, "account": Alias,
|
||||
"describe": describe, "headImgUrl": bigHeadImgUrl if bigHeadImgUrl else "",
|
||||
"ExtraBuf": ExtraBuf, "LabelIDList": tuple(LabelIDList)
|
||||
}
|
||||
return sessions
|
||||
|
||||
@db_error
|
||||
def get_recent_chat_wxid(self):
|
||||
"""
|
||||
获取最近聊天的联系人
|
||||
:return: 最近聊天的联系人
|
||||
"""
|
||||
users = []
|
||||
sql = (
|
||||
"SELECT A.Username, LastReadedCreateTime, LastReadedSvrId "
|
||||
"FROM ( SELECT Username, MAX(LastReadedCreateTime) AS MaxLastReadedCreateTime FROM ChatInfo "
|
||||
"WHERE LastReadedCreateTime IS NOT NULL AND LastReadedCreateTime > 1007911408000 GROUP BY Username "
|
||||
") AS SubQuery JOIN ChatInfo A "
|
||||
"ON A.Username = SubQuery.Username AND LastReadedCreateTime = SubQuery.MaxLastReadedCreateTime "
|
||||
"ORDER BY A.LastReadedCreateTime DESC;"
|
||||
)
|
||||
result = self.execute(sql)
|
||||
if not result:
|
||||
return []
|
||||
for row in result:
|
||||
# 获取用户名、昵称、备注和聊天记录数量
|
||||
username, LastReadedCreateTime, LastReadedSvrId = row
|
||||
LastReadedCreateTime = timestamp2str(LastReadedCreateTime) if LastReadedCreateTime else None
|
||||
users.append(
|
||||
{"wxid": username, "LastReadedCreateTime": LastReadedCreateTime, "LastReadedSvrId": LastReadedSvrId})
|
||||
return users
|
||||
|
||||
@db_error
|
||||
def get_user_list(self, word: str = None, wxids: list = None, label_ids: list = None):
|
||||
"""
|
||||
获取联系人列表
|
||||
[ 注意:如果修改这个函数,要同时修改dbOpenIMContact.py中的get_im_user_list函数 ]
|
||||
:param word: 查询关键字,可以是wxid,用户名、昵称、备注、描述,允许拼音
|
||||
:param wxids: wxid列表
|
||||
:param label_ids: 标签id
|
||||
:return: 联系人字典
|
||||
"""
|
||||
if isinstance(wxids, str):
|
||||
wxids = [wxids]
|
||||
if isinstance(label_ids, str):
|
||||
label_ids = [label_ids]
|
||||
|
||||
users = {}
|
||||
|
||||
sql = (
|
||||
"SELECT A.UserName, A.Alias, A.DelFlag, A.Type, A.VerifyFlag, A.Reserved1, A.Reserved2,"
|
||||
"A.Remark, A.NickName, A.LabelIDList, A.ChatRoomType, A.ChatRoomNotify, A.Reserved5,"
|
||||
"A.Reserved6 as describe, A.ExtraBuf, B.bigHeadImgUrl "
|
||||
"FROM Contact A LEFT JOIN ContactHeadImgUrl B ON A.UserName = B.usrName WHERE 1==1 ;"
|
||||
)
|
||||
if word:
|
||||
sql = sql.replace(";",
|
||||
f"AND ( A.UserName LIKE '%{word}%' "
|
||||
f"OR A.NickName LIKE '%{word}%' "
|
||||
f"OR A.Remark LIKE '%{word}%' "
|
||||
f"OR A.Alias LIKE '%{word}%' "
|
||||
f"OR LOWER(A.QuanPin) LIKE LOWER('%{word}%') "
|
||||
f"OR LOWER(A.PYInitial) LIKE LOWER('%{word}%') "
|
||||
f"OR LOWER(A.RemarkQuanPin) LIKE LOWER('%{word}%') "
|
||||
f"OR LOWER(A.RemarkPYInitial) LIKE LOWER('%{word}%') "
|
||||
f") "
|
||||
";")
|
||||
if wxids:
|
||||
sql = sql.replace(";", f"AND A.UserName IN ('" + "','".join(wxids) + "') ;")
|
||||
|
||||
if label_ids:
|
||||
sql_label = [f"A.LabelIDList LIKE '%{i}%' " for i in label_ids]
|
||||
sql_label = " OR ".join(sql_label)
|
||||
sql = sql.replace(";", f"AND ({sql_label}) ;")
|
||||
|
||||
result = self.execute(sql)
|
||||
if not result:
|
||||
return users
|
||||
id2label = self.get_labels()
|
||||
for row in result:
|
||||
# 获取wxid,昵称,备注,描述,头像,标签
|
||||
(UserName, Alias, DelFlag, Type, VerifyFlag, Reserved1, Reserved2, Remark, NickName, LabelIDList,
|
||||
ChatRoomType, ChatRoomNotify, Reserved5, describe, ExtraBuf, bigHeadImgUrl) = row
|
||||
|
||||
ExtraBuf = get_ExtraBuf(ExtraBuf)
|
||||
LabelIDList = LabelIDList.split(",") if LabelIDList else []
|
||||
LabelIDList = [id2label.get(int(label_id), label_id) for label_id in LabelIDList if label_id]
|
||||
|
||||
# print(f"{UserName=}\n{Alias=}\n{DelFlag=}\n{Type=}\n{VerifyFlag=}\n{Reserved1=}\n{Reserved2=}\n"
|
||||
# f"{Remark=}\n{NickName=}\n{LabelIDList=}\n{ChatRoomType=}\n{ChatRoomNotify=}\n{Reserved5=}\n"
|
||||
# f"{describe=}\n{ExtraBuf=}\n{bigHeadImgUrl=}")
|
||||
users[UserName] = {
|
||||
"wxid": UserName, "nickname": NickName, "remark": Remark, "account": Alias,
|
||||
"describe": describe, "headImgUrl": bigHeadImgUrl if bigHeadImgUrl else "",
|
||||
"ExtraBuf": ExtraBuf, "LabelIDList": tuple(LabelIDList)}
|
||||
return users
|
||||
|
||||
@db_error
|
||||
def get_room_list(self, word=None, roomwxids: list = None):
|
||||
"""
|
||||
获取群聊列表
|
||||
:param word: 群聊搜索词
|
||||
:param roomwxids: 群聊wxid列表
|
||||
:return: 群聊字典
|
||||
"""
|
||||
# 连接 MicroMsg.db 数据库,并执行查询
|
||||
if isinstance(roomwxids, str):
|
||||
roomwxids = [roomwxids]
|
||||
|
||||
sql = (
|
||||
"SELECT A.ChatRoomName,A.UserNameList,A.DisplayNameList,A.ChatRoomFlag,A.IsShowName,"
|
||||
"A.SelfDisplayName,A.Reserved2,A.RoomData, "
|
||||
"B.Announcement,B.AnnouncementEditor,B.AnnouncementPublishTime "
|
||||
"FROM ChatRoom A LEFT JOIN ChatRoomInfo B ON A.ChatRoomName==B.ChatRoomName "
|
||||
"WHERE 1==1 ;")
|
||||
if word:
|
||||
sql = sql.replace(";",
|
||||
f"AND A.ChatRoomName LIKE '%{word}%' ;")
|
||||
if roomwxids:
|
||||
sql = sql.replace(";", f"AND A.UserName IN ('" + "','".join(roomwxids) + "') ;")
|
||||
|
||||
rooms = {}
|
||||
result = self.execute(sql)
|
||||
if not result:
|
||||
return rooms
|
||||
|
||||
for row in result:
|
||||
# 获取用户名、昵称、备注和聊天记录数量
|
||||
(ChatRoomName, UserNameList, DisplayNameList, ChatRoomFlag, IsShowName, SelfDisplayName,
|
||||
Reserved2, RoomData,
|
||||
Announcement, AnnouncementEditor, AnnouncementPublishTime) = row
|
||||
|
||||
UserNameList = UserNameList.split("^G")
|
||||
DisplayNameList = DisplayNameList.split("^G")
|
||||
|
||||
RoomData = ChatRoom_RoomData(RoomData)
|
||||
wxid2remark = {}
|
||||
if RoomData:
|
||||
rd = []
|
||||
for k, v in RoomData.items():
|
||||
if isinstance(v, list):
|
||||
rd += v
|
||||
for i in rd:
|
||||
try:
|
||||
if isinstance(i, dict) and isinstance(i.get('1'), str) and i.get('2'):
|
||||
wxid2remark[i['1']] = i["2"]
|
||||
except Exception as e:
|
||||
db_loger.error(f"wxid2remark: ChatRoomName:{ChatRoomName}, {i} error:{e}", exc_info=True)
|
||||
rooms[ChatRoomName] = {
|
||||
"wxid": ChatRoomName, "UserNameList": UserNameList, "DisplayNameList": DisplayNameList,
|
||||
"ChatRoomFlag": ChatRoomFlag, "IsShowName": IsShowName, "SelfDisplayName": SelfDisplayName,
|
||||
"owner": Reserved2, "wxid2remark": wxid2remark,
|
||||
"Announcement": Announcement, "AnnouncementEditor": AnnouncementEditor,
|
||||
"AnnouncementPublishTime": AnnouncementPublishTime}
|
||||
return rooms
|
||||
|
||||
|
||||
@db_error
|
||||
def ChatRoom_RoomData(RoomData):
|
||||
# 读取群聊数据,主要为 wxid,以及对应昵称
|
||||
if RoomData is None or not isinstance(RoomData, bytes):
|
||||
return None
|
||||
data = get_BytesExtra(RoomData)
|
||||
bytes2str(data) if data else None
|
||||
return data
|
||||
|
||||
|
||||
@db_error
|
||||
def get_BytesExtra(BytesExtra):
|
||||
if BytesExtra is None or not isinstance(BytesExtra, bytes):
|
||||
return None
|
||||
try:
|
||||
deserialize_data, message_type = blackboxprotobuf.decode_message(BytesExtra)
|
||||
return deserialize_data
|
||||
except Exception as e:
|
||||
db_loger.warning(f"\nget_BytesExtra: {e}\n{BytesExtra}", exc_info=True)
|
||||
return None
|
||||
|
||||
|
||||
@db_error
|
||||
def get_ExtraBuf(ExtraBuf: bytes):
|
||||
"""
|
||||
读取ExtraBuf(联系人表)
|
||||
:param ExtraBuf:
|
||||
:return:
|
||||
"""
|
||||
if not ExtraBuf:
|
||||
return None
|
||||
buf_dict = {
|
||||
'74752C06': '性别[1男2女]', '46CF10C4': '个性签名', 'A4D9024A': '国', 'E2EAA8D1': '省', '1D025BBF': '市',
|
||||
'F917BCC0': '公司名称', '759378AD': '手机号', '4EB96D85': '企微属性', '81AE19B4': '朋友圈背景',
|
||||
'0E719F13': '备注图片', '945f3190': '备注图片2',
|
||||
'DDF32683': '0', '88E28FCE': '1', '761A1D2D': '2', '0263A0CB': '3', '0451FF12': '4', '228C66A8': '5',
|
||||
'4D6C4570': '6', '4335DFDD': '7', 'DE4CDAEB': '8', 'A72BC20A': '9', '069FED52': '10', '9B0F4299': '11',
|
||||
'3D641E22': '12', '1249822C': '13', 'B4F73ACB': '14', '0959EB92': '15', '3CF4A315': '16',
|
||||
'C9477AC60201E44CD0E8': '17', 'B7ACF0F5': '18', '57A7B5A8': '19', '695F3170': '20', 'FB083DD9': '21',
|
||||
'0240E37F': '22', '315D02A3': '23', '7DEC0BC3': '24', '16791C90': '25'
|
||||
}
|
||||
|
||||
rdata = {}
|
||||
for buf_name in buf_dict:
|
||||
rdata_name = buf_dict[buf_name]
|
||||
buf_name = bytes.fromhex(buf_name)
|
||||
offset = ExtraBuf.find(buf_name)
|
||||
if offset == -1:
|
||||
rdata[rdata_name] = ""
|
||||
continue
|
||||
offset += len(buf_name)
|
||||
type_id = ExtraBuf[offset: offset + 1]
|
||||
offset += 1
|
||||
|
||||
if type_id == b"\x04":
|
||||
rdata[rdata_name] = int.from_bytes(ExtraBuf[offset: offset + 4], "little")
|
||||
|
||||
elif type_id == b"\x18":
|
||||
length = int.from_bytes(ExtraBuf[offset: offset + 4], "little")
|
||||
rdata[rdata_name] = ExtraBuf[offset + 4: offset + 4 + length].decode("utf-16").rstrip("\x00")
|
||||
|
||||
elif type_id == b"\x17":
|
||||
length = int.from_bytes(ExtraBuf[offset: offset + 4], "little")
|
||||
rdata[rdata_name] = ExtraBuf[offset + 4: offset + 4 + length].decode("utf-8", errors="ignore").rstrip(
|
||||
"\x00")
|
||||
elif type_id == b"\x05":
|
||||
rdata[rdata_name] = f"0x{ExtraBuf[offset: offset + 8].hex()}"
|
||||
return rdata
|
||||
@@ -0,0 +1,111 @@
|
||||
# -*- coding: utf-8 -*-#
|
||||
# -------------------------------------------------------------------------------
|
||||
# Name: parsingOpenIMContact.py
|
||||
# Description:
|
||||
# Author: xaoyaoo
|
||||
# Date: 2024/04/16
|
||||
# -------------------------------------------------------------------------------
|
||||
from .dbbase import DatabaseBase
|
||||
from .utils import db_error
|
||||
|
||||
|
||||
class OpenIMContactHandler(DatabaseBase):
|
||||
_class_name = "OpenIMContact"
|
||||
OpenIMContact_required_tables = ["OpenIMContact"]
|
||||
|
||||
def OpenIMContact_tables_exist(self):
|
||||
"""
|
||||
判断该类所需要的表是否存在
|
||||
"""
|
||||
return self.check_tables_exist(self.OpenIMContact_required_tables)
|
||||
|
||||
def get_im_user_list(self, word=None, wxids=None):
|
||||
"""
|
||||
获取联系人列表
|
||||
[ 注意:如果修改这个函数,要同时修改dbMicro.py中的get_user_list函数 ]
|
||||
:param word: 查询关键字,可以是用户名、昵称、备注、描述,允许拼音
|
||||
:param wxids: 微信id列表
|
||||
:return: 联系人字典
|
||||
"""
|
||||
if not wxids:
|
||||
wxids = []
|
||||
if isinstance(wxids, str):
|
||||
wxids = [wxids]
|
||||
sql = ("SELECT UserName,NickName,Type,Remark,BigHeadImgUrl,CustomInfoDetail,CustomInfoDetailVisible,"
|
||||
"AntiSpamTicket,AppId,Sex,DescWordingId,ExtraBuf "
|
||||
"FROM OpenIMContact WHERE 1==1 ;")
|
||||
if word:
|
||||
sql = sql.replace(";",
|
||||
f"AND (UserName LIKE '%{word}%' "
|
||||
f"OR NickName LIKE '%{word}%' "
|
||||
f"OR Remark LIKE '%{word}%' "
|
||||
f"OR LOWER(NickNamePYInit) LIKE LOWER('%{word}%') "
|
||||
f"OR LOWER(NickNameQuanPin) LIKE LOWER('%{word}%') "
|
||||
f"OR LOWER(RemarkPYInit) LIKE LOWER('%{word}%') "
|
||||
f"OR LOWER(RemarkQuanPin) LIKE LOWER('%{word}%') "
|
||||
") ;")
|
||||
if wxids:
|
||||
sql = sql.replace(";", f"AND UserName IN ('" + "','".join(wxids) + "') ;")
|
||||
|
||||
result = self.execute(sql)
|
||||
if not result:
|
||||
return []
|
||||
|
||||
users = {}
|
||||
for row in result:
|
||||
# 获取用户名、昵称、备注和聊天记录数量
|
||||
(UserName, NickName, Type, Remark, BigHeadImgUrl, CustomInfoDetail, CustomInfoDetailVisible,
|
||||
AntiSpamTicket, AppId, Sex, DescWordingId, ExtraBuf) = row
|
||||
|
||||
users[UserName] = {
|
||||
"wxid": UserName, "nickname": NickName, "remark": Remark, "account": UserName,
|
||||
"describe": '', "headImgUrl": BigHeadImgUrl if BigHeadImgUrl else "",
|
||||
"ExtraBuf": None, "LabelIDList": tuple()}
|
||||
return users
|
||||
|
||||
|
||||
@db_error
|
||||
def get_ExtraBuf(ExtraBuf: bytes):
|
||||
"""
|
||||
读取ExtraBuf(联系人表)
|
||||
:param ExtraBuf:
|
||||
:return:
|
||||
"""
|
||||
if not ExtraBuf:
|
||||
return None
|
||||
buf_dict = {
|
||||
'74752C06': '性别[1男2女]', '46CF10C4': '个性签名', 'A4D9024A': '国', 'E2EAA8D1': '省', '1D025BBF': '市',
|
||||
'F917BCC0': '公司名称', '759378AD': '手机号', '4EB96D85': '企微属性', '81AE19B4': '朋友圈背景',
|
||||
'0E719F13': '备注图片', '945f3190': '备注图片2',
|
||||
'DDF32683': '0', '88E28FCE': '1', '761A1D2D': '2', '0263A0CB': '3', '0451FF12': '4', '228C66A8': '5',
|
||||
'4D6C4570': '6', '4335DFDD': '7', 'DE4CDAEB': '8', 'A72BC20A': '9', '069FED52': '10', '9B0F4299': '11',
|
||||
'3D641E22': '12', '1249822C': '13', 'B4F73ACB': '14', '0959EB92': '15', '3CF4A315': '16',
|
||||
'C9477AC60201E44CD0E8': '17', 'B7ACF0F5': '18', '57A7B5A8': '19', '695F3170': '20', 'FB083DD9': '21',
|
||||
'0240E37F': '22', '315D02A3': '23', '7DEC0BC3': '24', '16791C90': '25'
|
||||
}
|
||||
rdata = {}
|
||||
for buf_name in buf_dict:
|
||||
rdata_name = buf_dict[buf_name]
|
||||
buf_name = bytes.fromhex(buf_name)
|
||||
offset = ExtraBuf.find(buf_name)
|
||||
if offset == -1:
|
||||
rdata[rdata_name] = ""
|
||||
continue
|
||||
offset += len(buf_name)
|
||||
type_id = ExtraBuf[offset: offset + 1]
|
||||
offset += 1
|
||||
|
||||
if type_id == b"\x04":
|
||||
rdata[rdata_name] = int.from_bytes(ExtraBuf[offset: offset + 4], "little")
|
||||
|
||||
elif type_id == b"\x18":
|
||||
length = int.from_bytes(ExtraBuf[offset: offset + 4], "little")
|
||||
rdata[rdata_name] = ExtraBuf[offset + 4: offset + 4 + length].decode("utf-16").rstrip("\x00")
|
||||
|
||||
elif type_id == b"\x17":
|
||||
length = int.from_bytes(ExtraBuf[offset: offset + 4], "little")
|
||||
rdata[rdata_name] = ExtraBuf[offset + 4: offset + 4 + length].decode("utf-8", errors="ignore").rstrip(
|
||||
"\x00")
|
||||
elif type_id == b"\x05":
|
||||
rdata[rdata_name] = f"0x{ExtraBuf[offset: offset + 8].hex()}"
|
||||
return rdata
|
||||
@@ -0,0 +1,35 @@
|
||||
# -*- coding: utf-8 -*-#
|
||||
# -------------------------------------------------------------------------------
|
||||
# Name: MediaMSG_parsing.py
|
||||
# Description:
|
||||
# Author: xaoyaoo
|
||||
# Date: 2024/04/15
|
||||
# -------------------------------------------------------------------------------
|
||||
from .dbbase import DatabaseBase
|
||||
from .utils import silk2audio, db_loger
|
||||
|
||||
|
||||
class OpenIMMediaHandler(DatabaseBase):
|
||||
_class_name = "OpenIMMedia"
|
||||
OpenIMMedia_required_tables = ["OpenIMMedia"]
|
||||
|
||||
def OpenIMMedia_tables_exist(self):
|
||||
"""
|
||||
判断该类所需要的表是否存在
|
||||
"""
|
||||
return self.check_tables_exist(self.OpenIMMedia_required_tables)
|
||||
|
||||
def get_im_audio(self, MsgSvrID, is_play=False, is_wave=False, save_path=None, rate=24000):
|
||||
sql = "select Buf from OpenIMMedia where Reserved0=? "
|
||||
DBdata = self.execute(sql, (MsgSvrID,))
|
||||
if not DBdata:
|
||||
return False
|
||||
if len(DBdata) == 0:
|
||||
return False
|
||||
data = DBdata[0][0] # [1:] + b'\xFF\xFF'
|
||||
try:
|
||||
pcm_data = silk2audio(buf_data=data, is_play=is_play, is_wave=is_wave, save_path=save_path, rate=rate)
|
||||
return pcm_data
|
||||
except Exception as e:
|
||||
db_loger.warning(e, exc_info=True)
|
||||
return False
|
||||
@@ -0,0 +1,106 @@
|
||||
# -*- coding: utf-8 -*-#
|
||||
# -------------------------------------------------------------------------------
|
||||
# Name: parsingPublicMsg.py
|
||||
# Description:
|
||||
# Author: xaoyaoo
|
||||
# Date: 2024/07/03
|
||||
# -------------------------------------------------------------------------------
|
||||
|
||||
# -*- coding: utf-8 -*-#
|
||||
# -------------------------------------------------------------------------------
|
||||
# Name: parsingMSG.py
|
||||
# Description:
|
||||
# Author: xaoyaoo
|
||||
# Date: 2024/04/15
|
||||
# -------------------------------------------------------------------------------
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from typing import Union, Tuple
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from .dbbase import DatabaseBase
|
||||
from .dbMSG import MsgHandler
|
||||
from .utils import get_md5, name2typeid, typeid2name, type_converter, timestamp2str, xml2dict, match_BytesExtra, \
|
||||
db_error
|
||||
import lz4.block
|
||||
import blackboxprotobuf
|
||||
|
||||
|
||||
class PublicMsgHandler(MsgHandler):
|
||||
_class_name = "PublicMSG"
|
||||
PublicMSG_required_tables = ["PublicMsg"]
|
||||
|
||||
@db_error
|
||||
def PublicMSG_tables_exist(self):
|
||||
"""
|
||||
判断该类所需要的表是否存在
|
||||
"""
|
||||
return self.check_tables_exist(self.PublicMSG_required_tables)
|
||||
|
||||
@db_error
|
||||
def get_plc_msg_count(self, wxids: list = ""):
|
||||
"""
|
||||
获取聊天记录数量,根据wxid获取单个联系人的聊天记录数量,不传wxid则获取所有联系人的聊天记录数量
|
||||
:param wxids: wxid list
|
||||
:return: 聊天记录数量列表 {wxid: chat_count}
|
||||
"""
|
||||
if isinstance(wxids, str):
|
||||
wxids = [wxids]
|
||||
if wxids:
|
||||
wxids = "('" + "','".join(wxids) + "')"
|
||||
sql = f"SELECT StrTalker, COUNT(*) FROM PublicMsg WHERE StrTalker IN {wxids} GROUP BY StrTalker ORDER BY COUNT(*) DESC;"
|
||||
else:
|
||||
sql = f"SELECT StrTalker, COUNT(*) FROM PublicMsg GROUP BY StrTalker ORDER BY COUNT(*) DESC;"
|
||||
sql_total = f"SELECT COUNT(*) FROM MSG;"
|
||||
|
||||
result = self.execute(sql)
|
||||
total_ret = self.execute(sql_total)
|
||||
|
||||
if not result:
|
||||
return {}
|
||||
total = 0
|
||||
if total_ret and len(total_ret) > 0:
|
||||
total = total_ret[0][0]
|
||||
|
||||
msg_count = {"total": total}
|
||||
msg_count.update({row[0]: row[1] for row in result})
|
||||
return msg_count
|
||||
|
||||
@db_error
|
||||
def get_plc_msg_list(self, wxid="", start_index=0, page_size=500, msg_type: str = "", msg_sub_type: str = "",
|
||||
start_createtime=None, end_createtime=None):
|
||||
sql_base = ("SELECT localId,TalkerId,MsgSvrID,Type,SubType,CreateTime,IsSender,Sequence,StatusEx,FlagEx,Status,"
|
||||
"MsgSequence,StrContent,MsgServerSeq,StrTalker,DisplayContent,Reserved0,Reserved1,Reserved3,"
|
||||
"Reserved4,Reserved5,Reserved6,CompressContent,BytesExtra,BytesTrans,Reserved2,"
|
||||
"ROW_NUMBER() OVER (ORDER BY CreateTime ASC) AS id "
|
||||
"FROM PublicMsg ")
|
||||
|
||||
param = ()
|
||||
sql_wxid, param = ("AND StrTalker=? ", param + (wxid,)) if wxid else ("", param)
|
||||
sql_type, param = ("AND Type=? ", param + (msg_type,)) if msg_type else ("", param)
|
||||
sql_sub_type, param = ("AND SubType=? ", param + (msg_sub_type,)) if msg_type and msg_sub_type else ("", param)
|
||||
sql_start_createtime, param = ("AND CreateTime>=? ", param + (start_createtime,)) if start_createtime else (
|
||||
"", param)
|
||||
sql_end_createtime, param = ("AND CreateTime<=? ", param + (end_createtime,)) if end_createtime else ("", param)
|
||||
|
||||
sql = (
|
||||
f"{sql_base} WHERE 1=1 "
|
||||
f"{sql_wxid}"
|
||||
f"{sql_type}"
|
||||
f"{sql_sub_type}"
|
||||
f"{sql_start_createtime}"
|
||||
f"{sql_end_createtime}"
|
||||
f"ORDER BY CreateTime ASC LIMIT ?,?"
|
||||
)
|
||||
param = param + (start_index, page_size)
|
||||
result = self.execute(sql, param)
|
||||
if not result:
|
||||
return [], []
|
||||
|
||||
result_data = (self.get_msg_detail(row) for row in result)
|
||||
rdata = list(result_data) # 转为列表
|
||||
wxid_list = {d['talker'] for d in rdata} # 创建一个无重复的 wxid 列表
|
||||
|
||||
return rdata, list(wxid_list)
|
||||
@@ -0,0 +1,205 @@
|
||||
# -*- coding: utf-8 -*-#
|
||||
# -------------------------------------------------------------------------------
|
||||
# Name: dbbase.py
|
||||
# Description:
|
||||
# Author: xaoyaoo
|
||||
# Date: 2024/04/15
|
||||
# -------------------------------------------------------------------------------
|
||||
import importlib
|
||||
import os
|
||||
import sqlite3
|
||||
import time
|
||||
|
||||
from .utils import db_loger
|
||||
from dbutils.pooled_db import PooledDB
|
||||
|
||||
|
||||
# import logging
|
||||
#
|
||||
# db_loger = logging.getLogger("db_prepare")
|
||||
|
||||
|
||||
class DatabaseSingletonBase:
|
||||
# _singleton_instances = {} # 使用字典存储不同db_path对应的单例实例
|
||||
_class_name = "DatabaseSingletonBase"
|
||||
_db_pool = {} # 使用字典存储不同db_path对应的连接池
|
||||
|
||||
# def __new__(cls, *args, **kwargs):
|
||||
# if cls._class_name not in cls._singleton_instances:
|
||||
# cls._singleton_instances[cls._class_name] = super().__new__(cls)
|
||||
# return cls._singleton_instances[cls._class_name]
|
||||
|
||||
@classmethod
|
||||
def connect(cls, db_config):
|
||||
"""
|
||||
连接数据库,如果增加其他数据库连接,则重写该方法
|
||||
:param db_config: 数据库配置
|
||||
:return: 连接池
|
||||
"""
|
||||
if not db_config:
|
||||
raise ValueError("db_config 不能为空")
|
||||
db_key = db_config["key"]
|
||||
db_type = db_config["type"]
|
||||
if db_key in cls._db_pool and cls._db_pool[db_key] is not None:
|
||||
return cls._db_pool[db_key]
|
||||
|
||||
if db_type == "sqlite":
|
||||
db_path = db_config["path"]
|
||||
if not os.path.exists(db_path):
|
||||
raise FileNotFoundError(f"文件不存在: {db_path}")
|
||||
pool = PooledDB(
|
||||
creator=sqlite3, # 使用 sqlite3 作为连接创建者
|
||||
ping=0, # ping 数据库判断是否服务正常
|
||||
database=db_path
|
||||
)
|
||||
elif db_type == "mysql":
|
||||
mysql_config = {
|
||||
'user': db_config['user'],
|
||||
'host': db_config['host'],
|
||||
'password': db_config['password'],
|
||||
'database': db_config['database'],
|
||||
'port': db_config['port']
|
||||
}
|
||||
pool = PooledDB(
|
||||
creator=importlib.import_module('pymysql'), # 使用 mysql 作为连接创建者
|
||||
ping=1, # ping 数据库判断是否服务正常
|
||||
**mysql_config
|
||||
)
|
||||
else:
|
||||
raise ValueError(f"不支持的数据库类型: {db_type}")
|
||||
|
||||
db_loger.info(f"{pool} 连接句柄创建 {db_config}")
|
||||
cls._db_pool[db_key] = pool
|
||||
return pool
|
||||
|
||||
|
||||
class DatabaseBase(DatabaseSingletonBase):
|
||||
_class_name = "DatabaseBase"
|
||||
|
||||
def __init__(self, db_config):
|
||||
"""
|
||||
db_config = {
|
||||
"key": "test1",
|
||||
"type": "sqlite",
|
||||
"path": r"C:\***\wxdump_work\merge_all.db"
|
||||
}
|
||||
"""
|
||||
self.config = db_config
|
||||
self.pool = self.connect(self.config)
|
||||
|
||||
def execute(self, sql, params=None):
|
||||
"""
|
||||
执行SQL语句
|
||||
:param sql: SQL语句 (str)
|
||||
:param params: 参数 (tuple)
|
||||
:return: 查询结果 (list)
|
||||
"""
|
||||
connection = self.pool.connection()
|
||||
try:
|
||||
# connection.text_factory = bytes
|
||||
cursor = connection.cursor()
|
||||
if params:
|
||||
cursor.execute(sql, params)
|
||||
else:
|
||||
cursor.execute(sql)
|
||||
return cursor.fetchall()
|
||||
except Exception as e1:
|
||||
try:
|
||||
connection.text_factory = bytes
|
||||
cursor = connection.cursor()
|
||||
if params:
|
||||
cursor.execute(sql, params)
|
||||
else:
|
||||
cursor.execute(sql)
|
||||
rdata = cursor.fetchall()
|
||||
connection.text_factory = str
|
||||
return rdata
|
||||
except Exception as e2:
|
||||
db_loger.error(f"{sql=}\n{params=}\n{e1=}\n{e2=}\n", exc_info=True)
|
||||
return None
|
||||
|
||||
def check_tables_exist(self, required_tables):
|
||||
"""
|
||||
判断该类所需要的表是否存在
|
||||
"""
|
||||
required_tables = required_tables or []
|
||||
required_tables_str = "'" + "','".join(required_tables) + "'"
|
||||
sql = (f"SELECT tbl_name FROM sqlite_master "
|
||||
f"WHERE type='table' AND tbl_name in ({required_tables_str});")
|
||||
existing_tables = self.execute(sql)
|
||||
existing_tables = [row[0] for row in existing_tables] # 将查询结果转换为列表
|
||||
# 检查所有必需的表是否都在现有表中
|
||||
return all(table in existing_tables for table in required_tables)
|
||||
|
||||
def close(self):
|
||||
self.pool.close()
|
||||
db_loger.info(f"关闭数据库 - {self.config}")
|
||||
|
||||
def __del__(self):
|
||||
self.close()
|
||||
|
||||
# class MsgDb(DatabaseBase):
|
||||
#
|
||||
# def p(self, *args, **kwargs):
|
||||
# sel = "select tbl_name from sqlite_master where type='table'"
|
||||
# data = self.execute(sel)
|
||||
# # print([i[0] for i in data])
|
||||
# return data
|
||||
#
|
||||
#
|
||||
# class MsgDb1(DatabaseBase):
|
||||
# _class_name = "MsgDb1"
|
||||
#
|
||||
# def p(self, *args, **kwargs):
|
||||
# sel = "select tbl_name from sqlite_master where type='table'"
|
||||
# data = self.execute(sel)
|
||||
# # print([i[0] for i in data])
|
||||
# return data
|
||||
#
|
||||
#
|
||||
# if __name__ == '__main__':
|
||||
# logging.basicConfig(level=logging.INFO,
|
||||
# style='{',
|
||||
# datefmt='%Y-%m-%d %H:%M:%S',
|
||||
# format='[{levelname[0]}] {asctime} [{name}:{levelno}] {pathname}:{lineno} {message}'
|
||||
# )
|
||||
#
|
||||
# config1 = {
|
||||
# "key": "test1",
|
||||
# "type": "sqlite",
|
||||
# "path": r"D:\e_all.db"
|
||||
# }
|
||||
# config2 = {
|
||||
# "key": "test2",
|
||||
# "type": "sqlite",
|
||||
# "path": r"D:\_call.db"
|
||||
# }
|
||||
#
|
||||
# t1 = MsgDb(config1)
|
||||
# t1.p()
|
||||
# t2 = MsgDb(config2)
|
||||
# t2.p()
|
||||
# t3 = MsgDb1(config1)
|
||||
# t3.p()
|
||||
# t4 = MsgDb1(config2)
|
||||
# t4.p()
|
||||
#
|
||||
# print(t4._db_pool)
|
||||
# # 销毁t1
|
||||
# del t1
|
||||
# # 销毁t2
|
||||
# del t2
|
||||
# del t3
|
||||
#
|
||||
# # 销毁t4
|
||||
# del t4
|
||||
# import time
|
||||
# time.sleep(1)
|
||||
#
|
||||
# t1 = MsgDb(config1)
|
||||
# t1.p()
|
||||
# t2 = MsgDb(config2)
|
||||
# t2.p()
|
||||
#
|
||||
#
|
||||
# print(t2._db_pool)
|
||||
@@ -0,0 +1,11 @@
|
||||
# -*- coding: utf-8 -*-#
|
||||
# -------------------------------------------------------------------------------
|
||||
# Name: __init__.py
|
||||
# Description:
|
||||
# Author: xaoyaoo
|
||||
# Date: 2024/04/20
|
||||
# -------------------------------------------------------------------------------
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
pass
|
||||
@@ -0,0 +1,60 @@
|
||||
# -*- coding: utf-8 -*-#
|
||||
# -------------------------------------------------------------------------------
|
||||
# Name: exportCSV.py
|
||||
# Description:
|
||||
# Author: xaoyaoo
|
||||
# Date: 2024/04/20
|
||||
# -------------------------------------------------------------------------------
|
||||
import csv
|
||||
import json
|
||||
import os
|
||||
from ..dbMSG import MsgHandler
|
||||
|
||||
|
||||
def export_csv(wxid, outpath, db_config, page_size=5000):
|
||||
if not os.path.exists(outpath):
|
||||
outpath = os.path.join(os.getcwd(), "export" + os.sep + wxid)
|
||||
if not os.path.exists(outpath):
|
||||
os.makedirs(outpath)
|
||||
|
||||
pmsg = MsgHandler(db_config)
|
||||
|
||||
count = pmsg.get_msg_count(wxid)
|
||||
chatCount = count.get(wxid, 0)
|
||||
if chatCount == 0:
|
||||
return False, "没有聊天记录"
|
||||
|
||||
if page_size > chatCount:
|
||||
page_size = chatCount + 1
|
||||
|
||||
for i in range(0, chatCount, page_size):
|
||||
start_index = i
|
||||
data, wxid_list = pmsg.get_msg_list(wxid, start_index, page_size)
|
||||
|
||||
if len(data) == 0:
|
||||
return False, "没有聊天记录"
|
||||
|
||||
save_path = os.path.join(outpath, f"{wxid}_{i}_{i + page_size}.csv")
|
||||
|
||||
with open(save_path, "w", encoding="utf-8", newline='') as f:
|
||||
csv_writer = csv.writer(f, quoting=csv.QUOTE_MINIMAL)
|
||||
|
||||
csv_writer.writerow(["id", "MsgSvrID", "type_name", "is_sender", "talker", "room_name", "msg", "src",
|
||||
"CreateTime"])
|
||||
for row in data:
|
||||
id = row.get("id", "")
|
||||
MsgSvrID = row.get("MsgSvrID", "")
|
||||
type_name = row.get("type_name", "")
|
||||
is_sender = row.get("is_sender", "")
|
||||
talker = row.get("talker", "")
|
||||
room_name = row.get("room_name", "")
|
||||
msg = row.get("msg", "")
|
||||
src = row.get("src", "")
|
||||
CreateTime = row.get("CreateTime", "")
|
||||
csv_writer.writerow([id, MsgSvrID, type_name, is_sender, talker, room_name, msg, src, CreateTime])
|
||||
|
||||
return True, f"导出成功: {outpath}"
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
pass
|
||||
@@ -0,0 +1,39 @@
|
||||
# -*- coding: utf-8 -*-#
|
||||
# -------------------------------------------------------------------------------
|
||||
# Name: exportCSV.py
|
||||
# Description:
|
||||
# Author: xaoyaoo
|
||||
# Date: 2024/04/20
|
||||
# -------------------------------------------------------------------------------
|
||||
import json
|
||||
import os
|
||||
from ..dbMSG import MsgHandler
|
||||
|
||||
|
||||
def export_json(wxid, outpath, db_config):
|
||||
if not os.path.exists(outpath):
|
||||
outpath = os.path.join(os.getcwd(), "export" + os.sep + wxid)
|
||||
if not os.path.exists(outpath):
|
||||
os.makedirs(outpath)
|
||||
|
||||
pmsg = MsgHandler(db_config)
|
||||
|
||||
count = pmsg.get_msg_count(wxid)
|
||||
chatCount = count.get(wxid, 0)
|
||||
if chatCount == 0:
|
||||
return False, "没有聊天记录"
|
||||
|
||||
page_size = chatCount + 1
|
||||
for i in range(0, chatCount, page_size):
|
||||
start_index = i
|
||||
data, wxid_list = pmsg.get_msg_list(wxid, start_index, page_size)
|
||||
if len(data) == 0:
|
||||
return False, "没有聊天记录"
|
||||
save_path = os.path.join(outpath, f"{wxid}_{i}_{i + page_size}.json")
|
||||
with open(save_path, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, ensure_ascii=False, indent=4)
|
||||
return True, f"导出成功: {outpath}"
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
pass
|
||||
@@ -0,0 +1,10 @@
|
||||
# -*- coding: utf-8 -*-#
|
||||
# -------------------------------------------------------------------------------
|
||||
# Name: __init__.py.py
|
||||
# Description:
|
||||
# Author: xaoyaoo
|
||||
# Date: 2024/07/23
|
||||
# -------------------------------------------------------------------------------
|
||||
from ._loger import db_loger
|
||||
from .common_utils import timestamp2str, xml2dict, silk2audio, bytes2str, get_md5, name2typeid, typeid2name, \
|
||||
type_converter, match_BytesExtra, db_error, download_file,dat2img
|
||||
@@ -0,0 +1,10 @@
|
||||
# -*- coding: utf-8 -*-#
|
||||
# -------------------------------------------------------------------------------
|
||||
# Name: _loger.py
|
||||
# Description:
|
||||
# Author: xaoyaoo
|
||||
# Date: 2024/07/23
|
||||
# -------------------------------------------------------------------------------
|
||||
import logging
|
||||
|
||||
db_loger = logging.getLogger("db_prepare")
|
||||
@@ -0,0 +1,385 @@
|
||||
# -*- coding: utf-8 -*-#
|
||||
# -------------------------------------------------------------------------------
|
||||
# Name: common_utils.py
|
||||
# Description:
|
||||
# Author: xaoyaoo
|
||||
# Date: 2024/04/15
|
||||
# -------------------------------------------------------------------------------
|
||||
import hashlib
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import wave
|
||||
|
||||
import requests
|
||||
from io import BytesIO
|
||||
import pysilk
|
||||
import lxml.etree as ET # 这个模块更健壮些,微信XML格式有时有非标格式,会导致xml.etree.ElementTree处理失败
|
||||
from collections import defaultdict
|
||||
|
||||
from ._loger import db_loger
|
||||
|
||||
|
||||
def db_error(func):
|
||||
"""
|
||||
错误处理装饰器
|
||||
:param func:
|
||||
:return:
|
||||
"""
|
||||
|
||||
def wrapper(*args, **kwargs):
|
||||
try:
|
||||
return func(*args, **kwargs)
|
||||
except Exception as e:
|
||||
db_loger.error(f"db_error: {e}", exc_info=True)
|
||||
return None
|
||||
|
||||
return wrapper
|
||||
|
||||
|
||||
def type_converter(type_id_or_name: [str, tuple]):
|
||||
"""
|
||||
消息类型ID与名称转换
|
||||
名称(str)=>ID(tuple)
|
||||
ID(tuple)=>名称(str)
|
||||
:param type_id_or_name: 消息类型ID或名称
|
||||
:return: 消息类型ID或名称
|
||||
"""
|
||||
type_name_dict = defaultdict(lambda: "未知", {
|
||||
(1, 0): "文本",
|
||||
(3, 0): "图片",
|
||||
(34, 0): "语音",
|
||||
(37, 0): "添加好友",
|
||||
(42, 0): "推荐公众号",
|
||||
(43, 0): "视频",
|
||||
(47, 0): "动画表情",
|
||||
(48, 0): "位置",
|
||||
|
||||
(49, 0): "文件",
|
||||
(49, 1): "粘贴的文本",
|
||||
(49, 3): "(分享)音乐",
|
||||
(49, 4): "(分享)卡片式链接",
|
||||
(49, 5): "(分享)卡片式链接",
|
||||
(49, 6): "文件",
|
||||
(49, 7): "游戏相关",
|
||||
(49, 8): "用户上传的GIF表情",
|
||||
(49, 15): "未知-49,15",
|
||||
(49, 17): "位置共享",
|
||||
(49, 19): "合并转发的聊天记录",
|
||||
(49, 24): "(分享)笔记",
|
||||
(49, 33): "(分享)小程序",
|
||||
(49, 36): "(分享)小程序",
|
||||
(49, 40): "(分享)收藏夹",
|
||||
(49, 44): "(分享)小说(猜)",
|
||||
(49, 50): "(分享)视频号名片",
|
||||
(49, 51): "(分享)视频号视频",
|
||||
(49, 53): "接龙",
|
||||
(49, 57): "引用回复",
|
||||
(49, 63): "视频号直播或直播回放",
|
||||
(49, 74): "文件(猜)",
|
||||
(49, 87): "群公告",
|
||||
(49, 88): "视频号直播或直播回放等",
|
||||
(49, 2000): "转账",
|
||||
(49, 2003): "赠送红包封面",
|
||||
|
||||
(50, 0): "语音通话",
|
||||
(65, 0): "企业微信打招呼(猜)",
|
||||
(66, 0): "企业微信添加好友(猜)",
|
||||
|
||||
(10000, 0): "系统通知",
|
||||
(10000, 1): "消息撤回1",
|
||||
(10000, 4): "拍一拍",
|
||||
(10000, 5): "消息撤回5",
|
||||
(10000, 6): "消息撤回6",
|
||||
(10000, 33): "消息撤回33",
|
||||
(10000, 36): "消息撤回36",
|
||||
(10000, 57): "消息撤回57",
|
||||
(10000, 8000): "邀请加群",
|
||||
(11000, 0): "未知-11000,0"
|
||||
})
|
||||
|
||||
if isinstance(type_id_or_name, tuple):
|
||||
return type_name_dict[type_id_or_name]
|
||||
elif isinstance(type_id_or_name, str):
|
||||
return next((k for k, v in type_name_dict.items() if v == type_id_or_name), (0, 0))
|
||||
else:
|
||||
raise ValueError("Invalid input type")
|
||||
|
||||
|
||||
def typeid2name(type_id: tuple):
|
||||
"""
|
||||
获取消息类型名称
|
||||
:param type_id: 消息类型ID 元组 eg: (1, 0)
|
||||
:return:
|
||||
"""
|
||||
return type_converter(type_id)
|
||||
|
||||
|
||||
def name2typeid(type_name: str):
|
||||
"""
|
||||
获取消息类型ID
|
||||
:param type_name: 消息类型名称
|
||||
:return:
|
||||
"""
|
||||
return type_converter(type_name)
|
||||
|
||||
|
||||
def get_md5(data):
|
||||
md5 = hashlib.md5()
|
||||
md5.update(data)
|
||||
return md5.hexdigest()
|
||||
|
||||
|
||||
def timestamp2str(timestamp):
|
||||
"""
|
||||
时间戳转换为时间字符串
|
||||
:param timestamp: 时间戳
|
||||
:return: 时间字符串
|
||||
"""
|
||||
if isinstance(timestamp, str) and timestamp.isdigit():
|
||||
timestamp = int(timestamp)
|
||||
elif isinstance(timestamp, int) or isinstance(timestamp, float):
|
||||
pass
|
||||
else:
|
||||
return timestamp
|
||||
|
||||
if len(str(timestamp)) == 13:
|
||||
timestamp = timestamp / 1000
|
||||
elif len(str(timestamp)) == 10:
|
||||
pass
|
||||
else:
|
||||
return timestamp
|
||||
|
||||
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timestamp))
|
||||
|
||||
|
||||
def dat2img(input_data):
|
||||
"""
|
||||
读取图片文件dat格式
|
||||
:param input_data: 图片文件路径或者图片文件数据
|
||||
:return: 图片格式,图片md5,图片数据
|
||||
"""
|
||||
# 常见图片格式的文件头
|
||||
img_head = {
|
||||
b"\xFF\xD8\xFF": ".jpg",
|
||||
b"\x89\x50\x4E\x47": ".png",
|
||||
b"\x47\x49\x46\x38": ".gif",
|
||||
b"\x42\x4D": ".BMP",
|
||||
b"\x49\x49": ".TIFF",
|
||||
b"\x4D\x4D": ".TIFF",
|
||||
b"\x00\x00\x01\x00": ".ICO",
|
||||
b"\x52\x49\x46\x46": ".WebP",
|
||||
b"\x00\x00\x00\x18\x66\x74\x79\x70\x68\x65\x69\x63": ".HEIC",
|
||||
}
|
||||
|
||||
if isinstance(input_data, str):
|
||||
with open(input_data, "rb") as f:
|
||||
input_bytes = f.read()
|
||||
else:
|
||||
input_bytes = input_data
|
||||
|
||||
try:
|
||||
import numpy as np
|
||||
input_bytes = np.frombuffer(input_bytes, dtype=np.uint8)
|
||||
for hcode in img_head: # 遍历文件头
|
||||
t = input_bytes[0] ^ hcode[0] # 异或解密
|
||||
if np.all(t == np.bitwise_xor(np.frombuffer(input_bytes[:len(hcode)], dtype=np.uint8),
|
||||
np.frombuffer(hcode, dtype=np.uint8))): # 使用NumPy进行向量化的异或解密操作,并进行类型转换
|
||||
fomt = img_head[hcode] # 获取文件格式
|
||||
|
||||
out_bytes = np.bitwise_xor(input_bytes, t) # 使用NumPy进行向量化的异或解密操作
|
||||
md5 = get_md5(out_bytes)
|
||||
return True, fomt, md5, out_bytes
|
||||
return False, False, False, False
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
for hcode in img_head:
|
||||
t = input_bytes[0] ^ hcode[0]
|
||||
for i in range(1, len(hcode)):
|
||||
if t == input_bytes[i] ^ hcode[i]:
|
||||
fomt = img_head[hcode]
|
||||
out_bytes = bytearray()
|
||||
for nowByte in input_bytes: # 读取文件
|
||||
newByte = nowByte ^ t # 异或解密
|
||||
out_bytes.append(newByte)
|
||||
md5 = get_md5(out_bytes)
|
||||
return True, fomt, md5, out_bytes
|
||||
return False, False, False, False
|
||||
|
||||
|
||||
def xml2dict(xml_string):
|
||||
"""
|
||||
解析 XML 字符串
|
||||
:param xml_string: 要解析的 XML 字符串
|
||||
:return: 解析结果,以字典形式返回
|
||||
"""
|
||||
|
||||
def parse_xml(element):
|
||||
"""
|
||||
递归解析 XML 元素
|
||||
:param element: 要解析的 XML 元素
|
||||
:return: 解析结果,以字典形式返回
|
||||
"""
|
||||
result = {}
|
||||
# 解析当前元素的属性
|
||||
if element is None or element.attrib is None: # 有时可能会遇到没有属性,要处理下
|
||||
return result
|
||||
for key, value in element.attrib.items():
|
||||
result[key] = value
|
||||
# 解析当前元素的子元素
|
||||
for child in element:
|
||||
child_result = parse_xml(child)
|
||||
# 如果子元素的标签已经在结果中存在,则将其转换为列表
|
||||
if child.tag in result:
|
||||
if not isinstance(result[child.tag], list):
|
||||
result[child.tag] = [result[child.tag]]
|
||||
result[child.tag].append(child_result)
|
||||
else:
|
||||
result[child.tag] = child_result
|
||||
# 如果当前元素没有子元素,则将其文本内容作为值保存
|
||||
if not result and element.text:
|
||||
result = element.text
|
||||
return result
|
||||
|
||||
if xml_string is None or not isinstance(xml_string, str):
|
||||
return None
|
||||
try:
|
||||
parser = ET.XMLParser(recover=True) # 有时微信的聊天记录里面,会冒出来xml格式不对的情况,这里把parser设置成忽略错误
|
||||
root = ET.fromstring(xml_string, parser)
|
||||
except Exception as e:
|
||||
return xml_string
|
||||
return parse_xml(root)
|
||||
|
||||
|
||||
def download_file(url, save_path=None):
|
||||
"""
|
||||
下载文件
|
||||
:param url: 文件下载地址
|
||||
:param save_path: 保存路径
|
||||
:return: 保存路径
|
||||
"""
|
||||
headers = {
|
||||
"User-Agent": "Mozilla/5.0 (Linux; Android 10; Redmi K40 Pro) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Mobile Safari/537.36"
|
||||
|
||||
}
|
||||
r = requests.get(url, headers=headers)
|
||||
if r.status_code != 200:
|
||||
return None
|
||||
data = r.content
|
||||
if save_path and isinstance(save_path, str):
|
||||
# 创建文件夹
|
||||
if not os.path.exists(os.path.dirname(save_path)):
|
||||
os.makedirs(os.path.dirname(save_path))
|
||||
with open(save_path, "wb") as f:
|
||||
f.write(data)
|
||||
return data
|
||||
|
||||
|
||||
def bytes2str(d):
|
||||
"""
|
||||
遍历字典并将bytes转换为字符串
|
||||
:param d:
|
||||
:return:
|
||||
"""
|
||||
for k, v in d.items():
|
||||
if isinstance(v, dict):
|
||||
bytes2str(v)
|
||||
elif isinstance(v, list):
|
||||
for item in v:
|
||||
if isinstance(item, dict):
|
||||
bytes2str(item)
|
||||
elif isinstance(item, bytes):
|
||||
item = item.decode('utf-8') # 将bytes转换为字符串
|
||||
elif isinstance(v, bytes):
|
||||
d[k] = v.decode('utf-8')
|
||||
|
||||
|
||||
def read_dict_all_values(data):
|
||||
"""
|
||||
读取字典中所有的值(单层)
|
||||
:param dict_data: 字典
|
||||
:return: 所有值的list
|
||||
"""
|
||||
result = []
|
||||
if isinstance(data, list):
|
||||
for item in data:
|
||||
result.extend(read_dict_all_values(item))
|
||||
elif isinstance(data, dict):
|
||||
for key, value in data.items():
|
||||
result.extend(read_dict_all_values(value))
|
||||
else:
|
||||
if isinstance(data, bytes):
|
||||
tmp = data.decode("utf-8")
|
||||
else:
|
||||
tmp = str(data) if isinstance(data, int) else data
|
||||
result.append(tmp)
|
||||
|
||||
for i in range(len(result)):
|
||||
if isinstance(result[i], bytes):
|
||||
result[i] = result[i].decode("utf-8")
|
||||
return result
|
||||
|
||||
|
||||
def match_BytesExtra(BytesExtra, pattern=r"FileStorage(.*?)'"):
|
||||
"""
|
||||
匹配 BytesExtra
|
||||
:param BytesExtra: BytesExtra
|
||||
:param pattern: 匹配模式
|
||||
:return:
|
||||
"""
|
||||
if not BytesExtra:
|
||||
return False
|
||||
BytesExtra = read_dict_all_values(BytesExtra)
|
||||
BytesExtra = "'" + "'".join(BytesExtra) + "'"
|
||||
# print(BytesExtra)
|
||||
|
||||
match = re.search(pattern, BytesExtra)
|
||||
if match:
|
||||
video_path = match.group(0).replace("'", "")
|
||||
return video_path
|
||||
else:
|
||||
return ""
|
||||
|
||||
|
||||
def silk2audio(buf_data, is_play=False, is_wave=False, save_path=None, rate=24000):
|
||||
silk_file = BytesIO(buf_data) # 读取silk文件
|
||||
pcm_file = BytesIO() # 创建pcm文件
|
||||
|
||||
pysilk.decode(silk_file, pcm_file, rate) # 解码silk文件->pcm文件
|
||||
pcm_data = pcm_file.getvalue() # 获取pcm文件数据
|
||||
|
||||
silk_file.close() # 关闭silk文件
|
||||
pcm_file.close() # 关闭pcm文件
|
||||
if is_play: # 播放音频
|
||||
def play_audio(pcm_data, rate):
|
||||
try:
|
||||
import pyaudio
|
||||
except ImportError:
|
||||
raise ImportError("请先安装pyaudio库[ pip install pyaudio ]")
|
||||
|
||||
p = pyaudio.PyAudio() # 实例化pyaudio
|
||||
stream = p.open(format=pyaudio.paInt16, channels=1, rate=rate, output=True) # 创建音频流对象
|
||||
stream.write(pcm_data) # 写入音频流
|
||||
stream.stop_stream() # 停止音频流
|
||||
stream.close() # 关闭音频流
|
||||
p.terminate() # 关闭pyaudio
|
||||
|
||||
play_audio(pcm_data, rate)
|
||||
|
||||
print(is_play, is_wave, save_path)
|
||||
|
||||
if is_wave: # 转换为wav文件
|
||||
wave_file = BytesIO() # 创建wav文件
|
||||
with wave.open(wave_file, 'wb') as wf:
|
||||
wf.setparams((1, 2, rate, 0, 'NONE', 'NONE')) # 设置wav文件参数
|
||||
wf.writeframes(pcm_data) # 写入wav文件
|
||||
rdata = wave_file.getvalue() # 获取wav文件数据
|
||||
wave_file.close() # 关闭wav文件
|
||||
if save_path and isinstance(save_path, str):
|
||||
with open(save_path, "wb") as f:
|
||||
f.write(rdata)
|
||||
print('saved wav file')
|
||||
return rdata
|
||||
|
||||
return pcm_data
|
||||
Reference in new issue
Block a user