提交代码调整。
This commit is contained in:
@@ -13,6 +13,7 @@ from db.connection import DBConnectionManager
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ContactsDBOperator(BaseDBOperator):
|
||||
"""微信联系人数据库操作类"""
|
||||
|
||||
@@ -20,9 +21,7 @@ class ContactsDBOperator(BaseDBOperator):
|
||||
"""初始化联系人数据库操作类"""
|
||||
super().__init__(db_manager or DBConnectionManager.get_instance())
|
||||
self.logger = logging.getLogger("ContactsDBOperator")
|
||||
|
||||
# 确保数据库表存在
|
||||
# self._ensure_table_exists()
|
||||
|
||||
|
||||
def _ensure_table_exists(self):
|
||||
"""确保联系人表存在"""
|
||||
@@ -57,7 +56,7 @@ class ContactsDBOperator(BaseDBOperator):
|
||||
UNIQUE KEY `idx_user_name` (`user_name`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='微信联系人信息表';
|
||||
""")
|
||||
|
||||
|
||||
# 创建群成员表 - 增加了更多字段以支持详细信息
|
||||
self.execute_update("""
|
||||
CREATE TABLE IF NOT EXISTS t_chatroom_member (
|
||||
@@ -89,12 +88,12 @@ class ContactsDBOperator(BaseDBOperator):
|
||||
UNIQUE KEY `idx_chatroom_member` (`chatroom_id`, `wxid`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='微信群成员信息表';
|
||||
""")
|
||||
|
||||
|
||||
self.logger.info("成功创建或确认微信联系人表和群成员表存在")
|
||||
except Exception as e:
|
||||
self.logger.error(f"创建微信联系人表或群成员表失败: {e}")
|
||||
raise
|
||||
|
||||
|
||||
def save_contacts(self, contacts_data: List[Dict], contact_type: str) -> bool:
|
||||
"""保存联系人信息到数据库
|
||||
|
||||
@@ -108,7 +107,7 @@ class ContactsDBOperator(BaseDBOperator):
|
||||
if not contacts_data:
|
||||
self.logger.warning(f"没有{contact_type}类型的联系人数据需要保存")
|
||||
return True
|
||||
|
||||
|
||||
try:
|
||||
for contact in contacts_data:
|
||||
# 将驼峰命名转换为下划线命名
|
||||
@@ -132,33 +131,34 @@ class ContactsDBOperator(BaseDBOperator):
|
||||
'description': contact.get('description', ''),
|
||||
'card_img_url': contact.get('cardImgUrl', ''),
|
||||
'label_list': contact.get('labelList', ''),
|
||||
'phone_num_list': json.dumps(contact.get('phoneNumList', [])) if contact.get('phoneNumList') else '',
|
||||
'phone_num_list': json.dumps(contact.get('phoneNumList', [])) if contact.get(
|
||||
'phoneNumList') else '',
|
||||
'type': contact_type
|
||||
}
|
||||
|
||||
|
||||
# 构建SQL语句
|
||||
fields = ', '.join(data.keys())
|
||||
placeholders = ', '.join(['%s'] * len(data))
|
||||
values = tuple(data.values())
|
||||
|
||||
|
||||
# 使用INSERT ... ON DUPLICATE KEY UPDATE语法
|
||||
update_clause = ', '.join([f"{k}=VALUES({k})" for k in data.keys() if k != 'user_name'])
|
||||
|
||||
|
||||
sql = f"""
|
||||
INSERT INTO t_wechat_contacts ({fields})
|
||||
VALUES ({placeholders})
|
||||
ON DUPLICATE KEY UPDATE {update_clause}
|
||||
"""
|
||||
|
||||
|
||||
self.execute_update(sql, values)
|
||||
|
||||
|
||||
self.logger.info(f"成功保存{len(contacts_data)}个{contact_type}类型的联系人")
|
||||
return True
|
||||
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error(f"保存{contact_type}类型的联系人失败: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def save_simple_contacts(self, contact_list: List[str], contact_type: str) -> bool:
|
||||
"""保存简单联系人列表(只有user_name)到数据库
|
||||
|
||||
@@ -172,7 +172,7 @@ class ContactsDBOperator(BaseDBOperator):
|
||||
if not contact_list:
|
||||
self.logger.warning(f"没有{contact_type}类型的联系人数据需要保存")
|
||||
return True
|
||||
|
||||
|
||||
try:
|
||||
for user_name in contact_list:
|
||||
# 构建SQL语句
|
||||
@@ -181,16 +181,16 @@ class ContactsDBOperator(BaseDBOperator):
|
||||
VALUES (%s, %s)
|
||||
ON DUPLICATE KEY UPDATE type = VALUES(type), update_time = CURRENT_TIMESTAMP
|
||||
"""
|
||||
|
||||
|
||||
self.execute_update(sql, (user_name, contact_type))
|
||||
|
||||
|
||||
self.logger.info(f"成功保存{len(contact_list)}个{contact_type}类型的简单联系人")
|
||||
return True
|
||||
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error(f"保存{contact_type}类型的简单联系人失败: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def get_contacts_by_type(self, contact_type: str) -> List[Dict]:
|
||||
"""根据类型获取联系人列表
|
||||
|
||||
@@ -206,13 +206,13 @@ class ContactsDBOperator(BaseDBOperator):
|
||||
WHERE type = %s
|
||||
ORDER BY nick_name
|
||||
"""
|
||||
|
||||
|
||||
results = self.execute_query(sql, (contact_type,))
|
||||
return results
|
||||
except Exception as e:
|
||||
self.logger.error(f"获取{contact_type}类型的联系人失败: {e}")
|
||||
return []
|
||||
|
||||
|
||||
def get_contact_by_user_name(self, user_name: str) -> Optional[Dict]:
|
||||
"""根据user_name获取联系人信息
|
||||
|
||||
@@ -228,13 +228,13 @@ class ContactsDBOperator(BaseDBOperator):
|
||||
WHERE user_name = %s
|
||||
LIMIT 1
|
||||
"""
|
||||
|
||||
|
||||
result = self.execute_query(sql, (user_name,), fetch_one=True)
|
||||
return result
|
||||
except Exception as e:
|
||||
self.logger.error(f"获取联系人{user_name}失败: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def get_display_name(self, user_name: str) -> str:
|
||||
"""获取联系人的显示名称(优先使用备注,其次是昵称,最后是微信ID)
|
||||
|
||||
@@ -247,9 +247,9 @@ class ContactsDBOperator(BaseDBOperator):
|
||||
contact = self.get_contact_by_user_name(user_name)
|
||||
if not contact:
|
||||
return user_name
|
||||
|
||||
|
||||
return contact.get('remark') or contact.get('nick_name') or user_name
|
||||
|
||||
|
||||
def get_all_contacts_name_map(self) -> Dict[str, str]:
|
||||
"""获取所有联系人的ID到显示名称的映射
|
||||
|
||||
@@ -260,9 +260,9 @@ class ContactsDBOperator(BaseDBOperator):
|
||||
sql = """
|
||||
SELECT user_name, remark, nick_name FROM t_wechat_contacts
|
||||
"""
|
||||
|
||||
|
||||
results = self.execute_query(sql)
|
||||
|
||||
|
||||
name_map = {}
|
||||
for result in results:
|
||||
user_name = result.get('user_name')
|
||||
@@ -270,7 +270,7 @@ class ContactsDBOperator(BaseDBOperator):
|
||||
nick_name = result.get('nick_name')
|
||||
display_name = remark or nick_name or user_name
|
||||
name_map[user_name] = display_name
|
||||
|
||||
|
||||
return name_map
|
||||
except Exception as e:
|
||||
self.logger.error(f"获取所有联系人名称映射失败: {e}")
|
||||
@@ -289,7 +289,7 @@ class ContactsDBOperator(BaseDBOperator):
|
||||
if not member_details or not chatroom_id:
|
||||
self.logger.warning(f"没有群聊{chatroom_id}的成员详细信息需要保存")
|
||||
return False
|
||||
|
||||
|
||||
try:
|
||||
# 获取现有的群成员信息,以便更新而不是替换
|
||||
existing_members_sql = """
|
||||
@@ -297,26 +297,26 @@ class ContactsDBOperator(BaseDBOperator):
|
||||
WHERE chatroom_id = %s
|
||||
"""
|
||||
existing_members_result = self.execute_query(existing_members_sql, (chatroom_id,))
|
||||
existing_members = {row.get('wxid'): (row.get('is_owner'), row.get('is_admin'))
|
||||
for row in existing_members_result}
|
||||
|
||||
existing_members = {row.get('wxid'): (row.get('is_owner'), row.get('is_admin'))
|
||||
for row in existing_members_result}
|
||||
|
||||
for member in member_details:
|
||||
wxid = member.get('userName', '')
|
||||
if not wxid:
|
||||
continue
|
||||
|
||||
|
||||
# 保留现有的群主和管理员标识
|
||||
is_owner, is_admin = 0, 0
|
||||
if wxid in existing_members:
|
||||
is_owner, is_admin = existing_members[wxid]
|
||||
|
||||
|
||||
# 处理电话号码列表
|
||||
phone_num_list = member.get('phoneNumList', [])
|
||||
if phone_num_list:
|
||||
phone_num_str = json.dumps(phone_num_list)
|
||||
else:
|
||||
phone_num_str = ''
|
||||
|
||||
|
||||
# 构建数据
|
||||
data = {
|
||||
'chatroom_id': chatroom_id,
|
||||
@@ -343,26 +343,26 @@ class ContactsDBOperator(BaseDBOperator):
|
||||
'remark_py_initial': member.get('remarkPyInitial', ''),
|
||||
'remark_quan_pin': member.get('remarkQuanPin', '')
|
||||
}
|
||||
|
||||
|
||||
# 构建SQL语句 - 使用REPLACE INTO确保更新现有记录
|
||||
fields = ', '.join(data.keys())
|
||||
placeholders = ', '.join(['%s'] * len(data))
|
||||
values = tuple(data.values())
|
||||
|
||||
|
||||
sql = f"""
|
||||
REPLACE INTO t_chatroom_member ({fields})
|
||||
VALUES ({placeholders})
|
||||
"""
|
||||
|
||||
|
||||
self.execute_update(sql, values)
|
||||
|
||||
|
||||
self.logger.info(f"成功保存群聊{chatroom_id}的{len(member_details)}个成员详细信息")
|
||||
return True
|
||||
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error(f"保存群聊{chatroom_id}的成员详细信息失败: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def process_chatroom_member_detail_response(self, chatroom_id: str, response: Dict) -> bool:
|
||||
"""处理获取群成员详情的API响应
|
||||
|
||||
@@ -377,14 +377,14 @@ class ContactsDBOperator(BaseDBOperator):
|
||||
if response.get('ret') != 200:
|
||||
self.logger.error(f"获取群聊{chatroom_id}成员详情失败: {response.get('msg')}")
|
||||
return False
|
||||
|
||||
|
||||
data = response.get('data', [])
|
||||
if not data:
|
||||
self.logger.warning(f"群聊{chatroom_id}成员详情数据为空")
|
||||
return False
|
||||
|
||||
|
||||
return self.save_chatroom_member_detail(chatroom_id, data)
|
||||
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error(f"处理群聊{chatroom_id}成员详情数据失败: {e}")
|
||||
return False
|
||||
return False
|
||||
|
||||
@@ -22,7 +22,8 @@ class MessageStorageDB(BaseDBOperator):
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||
"""
|
||||
params = (
|
||||
msg.roomid, now_time, msg.sender, msg.content, msg.msg_type, msg.content, msg.msg_id, msg.msg_source, "")
|
||||
msg.roomid, now_time, msg.sender, msg.content, msg.msg_type, msg.content.xml_content, msg.msg_id,
|
||||
msg.msg_source, "")
|
||||
result = self.execute_update(sql, params)
|
||||
return result
|
||||
|
||||
|
||||
Reference in New Issue
Block a user