142 lines
6.1 KiB
Python
142 lines
6.1 KiB
Python
# -*- coding: utf-8 -*-
|
|
from datetime import datetime
|
|
from typing import Dict, List, Optional
|
|
|
|
from db.base import BaseDBOperator
|
|
from db.connection import DBConnectionManager
|
|
|
|
|
|
class EmojiAssetDBOperator(BaseDBOperator):
|
|
"""表情资产数据库操作"""
|
|
|
|
def __init__(self, db_manager: DBConnectionManager):
|
|
super().__init__(db_manager)
|
|
self._create_tables()
|
|
|
|
def _create_tables(self):
|
|
try:
|
|
self.execute_update("""
|
|
CREATE TABLE IF NOT EXISTS t_emoji_asset (
|
|
id INT AUTO_INCREMENT PRIMARY KEY,
|
|
md5 VARCHAR(64) NOT NULL COMMENT '表情MD5',
|
|
total_length INT NOT NULL DEFAULT 0 COMMENT '表情长度',
|
|
file_path VARCHAR(255) NOT NULL COMMENT '本地访问路径',
|
|
file_ext VARCHAR(16) DEFAULT '' COMMENT '文件扩展名',
|
|
source_message_id BIGINT DEFAULT NULL COMMENT '来源消息ID',
|
|
source_chatroom_id VARCHAR(64) DEFAULT '' COMMENT '来源群ID',
|
|
source_wxid VARCHAR(64) DEFAULT '' COMMENT '来源发送人',
|
|
usage_count INT NOT NULL DEFAULT 0 COMMENT '使用次数',
|
|
last_used_at DATETIME DEFAULT NULL COMMENT '最近采集时间',
|
|
last_sent_at DATETIME DEFAULT NULL COMMENT '最近发送时间',
|
|
create_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
|
update_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
|
UNIQUE KEY idx_emoji_asset_md5 (md5),
|
|
KEY idx_emoji_asset_recent (update_time),
|
|
KEY idx_emoji_asset_group (source_chatroom_id, update_time)
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='表情资产表';
|
|
""")
|
|
except Exception as e:
|
|
self.LOG.error(f"创建表情资产表失败: {e}")
|
|
|
|
def save_asset(self, asset: Dict) -> bool:
|
|
try:
|
|
sql = """
|
|
INSERT INTO t_emoji_asset (
|
|
md5, total_length, file_path, file_ext,
|
|
source_message_id, source_chatroom_id, source_wxid,
|
|
usage_count, last_used_at, last_sent_at
|
|
)
|
|
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
|
|
ON DUPLICATE KEY UPDATE
|
|
total_length = VALUES(total_length),
|
|
file_path = VALUES(file_path),
|
|
file_ext = VALUES(file_ext),
|
|
source_message_id = COALESCE(VALUES(source_message_id), source_message_id),
|
|
source_chatroom_id = CASE
|
|
WHEN VALUES(source_chatroom_id) IS NULL OR VALUES(source_chatroom_id) = '' THEN source_chatroom_id
|
|
ELSE VALUES(source_chatroom_id)
|
|
END,
|
|
source_wxid = CASE
|
|
WHEN VALUES(source_wxid) IS NULL OR VALUES(source_wxid) = '' THEN source_wxid
|
|
ELSE VALUES(source_wxid)
|
|
END,
|
|
usage_count = usage_count + 1,
|
|
last_used_at = VALUES(last_used_at)
|
|
"""
|
|
now = asset.get("last_used_at") or datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
params = (
|
|
asset.get("md5", ""),
|
|
int(asset.get("total_length", 0) or 0),
|
|
asset.get("file_path", ""),
|
|
asset.get("file_ext", ""),
|
|
asset.get("source_message_id"),
|
|
asset.get("source_chatroom_id", ""),
|
|
asset.get("source_wxid", ""),
|
|
int(asset.get("usage_count", 1) or 1),
|
|
now,
|
|
asset.get("last_sent_at"),
|
|
)
|
|
return self.execute_update(sql, params)
|
|
except Exception as e:
|
|
self.LOG.error(f"保存表情资产失败: {e}")
|
|
return False
|
|
|
|
def list_assets(self, limit: int = 60, chatroom_id: str = "") -> List[Dict]:
|
|
try:
|
|
sql = """
|
|
SELECT id, md5, total_length, file_path, file_ext, source_message_id,
|
|
source_chatroom_id, source_wxid, usage_count, last_used_at,
|
|
last_sent_at, create_time, update_time
|
|
FROM t_emoji_asset
|
|
WHERE file_path IS NOT NULL AND file_path <> ''
|
|
"""
|
|
params = []
|
|
if chatroom_id:
|
|
sql += " AND source_chatroom_id = %s "
|
|
params.append(chatroom_id)
|
|
sql += " ORDER BY COALESCE(last_sent_at, last_used_at, update_time) DESC LIMIT %s "
|
|
params.append(limit)
|
|
rows = self.execute_query(sql, tuple(params)) or []
|
|
return [self._serialize_row(row) for row in rows]
|
|
except Exception as e:
|
|
self.LOG.error(f"查询表情资产失败: {e}")
|
|
return []
|
|
|
|
def get_asset_by_md5(self, md5: str) -> Optional[Dict]:
|
|
try:
|
|
sql = """
|
|
SELECT id, md5, total_length, file_path, file_ext, source_message_id,
|
|
source_chatroom_id, source_wxid, usage_count, last_used_at,
|
|
last_sent_at, create_time, update_time
|
|
FROM t_emoji_asset
|
|
WHERE md5 = %s
|
|
LIMIT 1
|
|
"""
|
|
row = self.execute_query(sql, (md5,), fetch_one=True)
|
|
return self._serialize_row(row) if row else None
|
|
except Exception as e:
|
|
self.LOG.error(f"查询表情资产详情失败: {e}")
|
|
return None
|
|
|
|
def mark_sent(self, md5: str) -> bool:
|
|
try:
|
|
sql = """
|
|
UPDATE t_emoji_asset
|
|
SET last_sent_at = NOW()
|
|
WHERE md5 = %s
|
|
"""
|
|
return self.execute_update(sql, (md5,))
|
|
except Exception as e:
|
|
self.LOG.error(f"更新表情发送时间失败: {e}")
|
|
return False
|
|
|
|
@staticmethod
|
|
def _serialize_row(row: Dict) -> Dict:
|
|
if not row:
|
|
return row
|
|
for key in ("last_used_at", "last_sent_at", "create_time", "update_time"):
|
|
value = row.get(key)
|
|
if isinstance(value, datetime):
|
|
row[key] = value.strftime("%Y-%m-%d %H:%M:%S")
|
|
return row
|