wecom_sync_service.py 18.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
from __future__ import annotations

from dataclasses import dataclass
from datetime import datetime, timezone
import logging
from typing import Any, Iterable, Protocol

from sqlalchemy.orm import Session

from app.jobs.log_context import format_job_log
from app.model.wecom_sync import (
    WeComBot,
    WeComCustomerGroup,
    WeComJobConfig,
    WeComMessage,
    WeComSyncCheckpoint,
)


logger = logging.getLogger(__name__)


def _utcnow() -> datetime:
    return datetime.now(timezone.utc)


def _parse_dt(value: Any) -> datetime | None:
    if value is None or value == "":
        return None
    if isinstance(value, datetime):
        return value.astimezone(timezone.utc) if value.tzinfo else value.replace(tzinfo=timezone.utc)
    if isinstance(value, str):
        parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
        return parsed.astimezone(timezone.utc) if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
    return None


def _ensure_utc(value: datetime | None) -> datetime | None:
    if value is None:
        return None
    return value.astimezone(timezone.utc) if value.tzinfo else value.replace(tzinfo=timezone.utc)


def _join_display(values: list[str]) -> str:
    cleaned = [str(item).strip() for item in values if str(item).strip()]
    return "、".join(cleaned) if cleaned else "-"


class DispatchError(Exception):
    pass


class WeComSyncClient(Protocol):
    def list_bots(self, *, page: int, page_size: int) -> dict[str, Any]:
        ...

    def list_customers(
        self,
        *,
        bot_id: str,
        start_time: datetime | None,
        end_time: datetime | None,
        page: int,
        page_size: int,
        contact_type: str | None = None,
        keyword: str | None = None,
    ) -> dict[str, Any]:
        ...

    def list_messages(
        self,
        *,
        bot_id: str,
        group_id: str | None,
        start_time: datetime | None,
        end_time: datetime | None,
        page: int,
        page_size: int,
        order: str = "asc",
    ) -> dict[str, Any]:
        ...

    def create_group(
        self,
        *,
        bot_code: str,
        group_name: str,
        member_list: list[str],
        group_announcement: str | None,
        biz_rela_no: str,
    ) -> dict[str, Any]:
        ...

    def get_task(self, *, task_id: str) -> dict[str, Any]:
        ...


class WeComMessageDispatcher(Protocol):
    def dispatch(self, message: WeComMessage) -> None:
        ...


class NoopWeComMessageDispatcher:
    def dispatch(self, message: WeComMessage) -> None:
        return None


@dataclass
class SyncWindow:
    start_time: datetime | None
    end_time: datetime | None


class WeComSyncService:
    def __init__(
        self,
        db: Session,
        client: WeComSyncClient,
        dispatcher: WeComMessageDispatcher | None = None,
        page_size: int = 100,
    ) -> None:
        self.db = db
        self.client = client
        self.dispatcher = dispatcher or NoopWeComMessageDispatcher()
        self.page_size = page_size

    def sync_all_full(self, *, message_start_time: datetime | None, message_end_time: datetime | None) -> dict[str, int]:
        return self.sync_wecom_bots_groups_messages(
            bot_ids=None,
            start_time=message_start_time,
            end_time=message_end_time,
        )

    def sync_wecom_bots_groups_messages(
        self,
        *,
        bot_ids: Iterable[str] | None,
        start_time: datetime | None,
        end_time: datetime | None,
    ) -> dict[str, int]:
        bots = self.sync_bots_full()
        resolved_bot_ids = [
            bot.bot_id
            for bot in self.db.query(WeComBot).filter(WeComBot.online == True).all()
            if bot.bot_id
        ]
        if bot_ids is not None:
            allowed_bot_ids = {str(bot_id) for bot_id in bot_ids if str(bot_id).strip()}
            resolved_bot_ids = [item for item in resolved_bot_ids if item in allowed_bot_ids]
        messages = self.sync_messages_incremental(
            bot_ids=resolved_bot_ids,
            start_time=start_time,
            end_time=end_time,
        )
        return {
            "bots": bots,
            "messages": messages,
        }

    def sync_bots_full(self) -> int:
        count = 0
        latest_time: datetime | None = None
        latest_id: str | None = None
        for item in self._paginate(lambda page: self.client.list_bots(page=page, page_size=self.page_size)):
            if not self._is_online_bot(item):
                continue
            bot = self._upsert_bot(item)
            count += 1
            candidate_time = _parse_dt(item.get("updated_at")) or _parse_dt(item.get("created_at"))
            latest_time, latest_id = self._max_key(latest_time, latest_id, candidate_time, bot.bot_code)
        self._complete_checkpoint("bots", "global", latest_time, latest_id)
        return count

    def sync_messages_incremental(
        self,
        *,
        bot_ids: Iterable[str],
        start_time: datetime | None,
        end_time: datetime | None,
    ) -> int:
        total = 0
        for bot_id in bot_ids:
            bot_code = self._resolve_bot_code(None, bot_id)
            bot_row = self.db.query(WeComBot).filter(WeComBot.bot_code == bot_code).first()
            bot_name = str((bot_row.bot_name if bot_row else "") or "").strip()
            bound_groups = (
                self.db.query(WeComCustomerGroup)
                .filter(
                    WeComCustomerGroup.bot_code == bot_code,
                    WeComCustomerGroup.group_id.isnot(None),
                    WeComCustomerGroup.group_status == "active",
                    WeComCustomerGroup.is_deleted == False,
                )
                .order_by(WeComCustomerGroup.id.asc())
                .all()
            )
            if bound_groups:
                logger.info(
                    format_job_log(
                        "正在获取机器人[%s](bot_id=%s)的客户群消息,共%s个群"
                        % (bot_name or bot_id, bot_id, len(bound_groups))
                    )
                )
                for group in bound_groups:
                    member_list = group.member_bot_ids if isinstance(group.member_bot_ids, list) else []
                    logger.info(
                        format_job_log(
                            "机器人[%s](bot_id=%s)已知群: %s(group_id=%s) 成员机器人=%s"
                            % (
                                bot_name or bot_id,
                                bot_id,
                                group.group_name or "-",
                                group.group_id or "-",
                                _join_display([str(item) for item in member_list]),
                            )
                        )
                    )
                    logger.info(
                        format_job_log(
                            "从 %s 群(group_id=%s)获取消息"
                            % (group.group_name or "-", group.group_id or "-")
                        )
                    )
            else:
                logger.info(
                    format_job_log(
                        "正在获取机器人[%s](bot_id=%s)的客户群消息,当前没有已绑定的活跃客户群"
                        % (bot_name or bot_id, bot_id)
                    )
                )
            for group in bound_groups:
                group_id = str(group.group_id or "").strip()
                if not group_id:
                    continue
                checkpoint = self._get_checkpoint("messages", f"group:{group_id}")
                window = self._resolve_message_window(checkpoint, start_time, end_time)
                latest_time = checkpoint.last_sync_time if checkpoint else None
                latest_id = checkpoint.last_external_id if checkpoint else None

                for item in self._paginate(
                    lambda page, current_bot_id=bot_id, current_group_id=group_id: self.client.list_messages(
                        bot_id=current_bot_id,
                        group_id=current_group_id,
                        start_time=window.start_time,
                        end_time=window.end_time,
                        page=page,
                        page_size=self.page_size,
                        order="asc",
                    )
                ):
                    msg_time = _parse_dt(item.get("msg_time"))
                    msg_id = str(item.get("msg_id") or "")
                    if self._is_message_already_consumed(checkpoint, msg_time, msg_id):
                        continue
                    message = self._upsert_message(item)
                    total += 1
                    latest_time, latest_id = self._max_key(latest_time, latest_id, message.msg_time, message.msg_id)
                self._complete_checkpoint("messages", f"group:{group_id}", latest_time, latest_id)
        return total

    def dispatch_pending_messages(self, *, bot_ids: Iterable[str] | None = None) -> int:
        query = (
            self.db.query(WeComMessage)
            .filter(
                WeComMessage.bot_send == False,
                WeComMessage.dispatch_status.in_(("pending", "failed")),
            )
            .order_by(WeComMessage.msg_time.asc(), WeComMessage.id.asc())
        )
        if bot_ids:
            query = query.filter(WeComMessage.bot_id.in_(list(bot_ids)))

        messages = query.all()
        dispatched = 0
        for message in messages:
            self._dispatch_message_if_needed(message)
            if message.dispatch_status == "success":
                dispatched += 1
        self.db.commit()
        return dispatched

    def ensure_job_config(self, job_key: str, enabled: bool = True) -> WeComJobConfig:
        config = self.db.query(WeComJobConfig).filter(WeComJobConfig.job_key == job_key).first()
        if config is None:
            config = WeComJobConfig(job_key=job_key, enabled=enabled)
            self.db.add(config)
            self.db.commit()
            self.db.refresh(config)
        return config

    def list_job_configs(self) -> list[WeComJobConfig]:
        job_keys = [
            "sync_wecom_bots_groups_messages",
            "sync_customer_groups",
            "dispatch_customer_group_messages",
        ]
        for job_key in job_keys:
            self.ensure_job_config(job_key)
        return self.db.query(WeComJobConfig).order_by(WeComJobConfig.job_key.asc()).all()

    def set_job_enabled(self, job_key: str, enabled: bool) -> WeComJobConfig:
        config = self.ensure_job_config(job_key)
        config.enabled = enabled
        self.db.commit()
        self.db.refresh(config)
        return config

    def mark_job_result(self, job_key: str, status: str, error: str | None = None) -> None:
        config = self.ensure_job_config(job_key)
        config.last_run_at = _utcnow()
        config.last_status = status
        config.last_error = error
        self.db.commit()

    def _paginate(self, fetch_page) -> Iterable[dict[str, Any]]:
        page = 1
        while True:
            payload = fetch_page(page)
            items = payload.get("items") or []
            for item in items:
                yield item
            meta = payload.get("meta") or {}
            total = meta.get("total")
            page_size = meta.get("page_size") or self.page_size
            if not items:
                break
            if total is not None and page * page_size >= total:
                break
            page += 1

    def _upsert_bot(self, data: dict[str, Any]) -> WeComBot:
        bot_code = self._resolve_bot_code(data.get("bot_code"), data.get("bot_id"), data.get("channel"))
        record = self.db.query(WeComBot).filter(WeComBot.bot_code == bot_code).first()
        if record is None:
            record = WeComBot(bot_code=bot_code, bot_id=str(data.get("bot_id") or ""), channel=str(data.get("channel") or ""))
            self.db.add(record)
        record.channel = str(data.get("channel") or record.channel)
        record.bot_id = str(data.get("bot_id") or record.bot_id)
        record.bot_code = bot_code
        record.bot_name = str(data.get("bot_name") or data.get("name") or bot_code)
        record.corp_name = data.get("corp_name")
        record.online = self._to_bool_or_none(data.get("online"))
        record.status = data.get("status")
        record.config = data.get("config")
        record.queue_count = data.get("queue_count")
        record.pending_count = data.get("pending_count")
        record.last_active = _parse_dt(data.get("last_active"))
        record.last_fail = _parse_dt(data.get("last_fail"))
        record.external_created_at = _parse_dt(data.get("created_at"))
        record.external_updated_at = _parse_dt(data.get("updated_at"))
        self.db.flush()
        return record

    def _upsert_message(self, data: dict[str, Any]) -> WeComMessage:
        bot_code = self._resolve_bot_code(data.get("bot_code"), data.get("bot_id"), data.get("channel"))
        msg_id = str(data.get("msg_id") or "")
        record = (
            self.db.query(WeComMessage)
            .filter(WeComMessage.bot_code == bot_code, WeComMessage.msg_id == msg_id)
            .first()
        )
        if record is None:
            record = WeComMessage(
                bot_code=bot_code,
                channel=str(data.get("channel") or ""),
                bot_id=str(data.get("bot_id") or ""),
                msg_id=msg_id,
                msg_time=_parse_dt(data.get("msg_time")) or _utcnow(),
                payload={},
                bot_send=False,
            )
            self.db.add(record)
        record.bot_code = bot_code
        record.channel = str(data.get("channel") or record.channel)
        record.bot_id = str(data.get("bot_id") or record.bot_id)
        record.msg_id = msg_id
        record.msg_time = _parse_dt(data.get("msg_time")) or record.msg_time
        record.msg_type = data.get("msg_type")
        record.msg_content = data.get("msg_content")
        record.sender_id = data.get("sender_id")
        record.sender_name = data.get("sender_name")
        record.contact_id = data.get("contact_id")
        record.session_title = data.get("session_title")
        record.bot_send = bool(data.get("bot_send"))
        record.payload = dict(data)
        if not record.bot_send and record.dispatch_status is None:
            record.dispatch_status = "pending"
            record.dispatch_error = None
        self.db.flush()
        return record

    def _dispatch_message_if_needed(self, message: WeComMessage) -> None:
        if message.bot_send:
            return
        if message.dispatch_status not in {"pending", "failed"}:
            return
        try:
            self.dispatcher.dispatch(message)
            message.dispatch_status = "success"
            message.dispatch_error = None
            message.dispatch_at = _utcnow()
        except DispatchError as exc:
            message.dispatch_status = "failed"
            message.dispatch_error = str(exc)
            message.dispatch_at = None
        self.db.flush()

    def _resolve_message_window(
        self,
        checkpoint: WeComSyncCheckpoint | None,
        start_time: datetime | None,
        end_time: datetime | None,
    ) -> SyncWindow:
        normalized_start = _ensure_utc(start_time)
        normalized_end = _ensure_utc(end_time)
        checkpoint_time = _ensure_utc(checkpoint.last_sync_time) if checkpoint is not None else None
        if checkpoint_time is not None and normalized_start is None:
            return SyncWindow(start_time=checkpoint_time, end_time=normalized_end)
        return SyncWindow(start_time=normalized_start, end_time=normalized_end)

    def _is_message_already_consumed(
        self,
        checkpoint: WeComSyncCheckpoint | None,
        msg_time: datetime | None,
        msg_id: str,
    ) -> bool:
        if checkpoint is None or checkpoint.last_sync_time is None or msg_time is None:
            return False
        last_time = checkpoint.last_sync_time
        if last_time.tzinfo is None:
            last_time = last_time.replace(tzinfo=timezone.utc)
        if msg_time < last_time:
            return True
        if msg_time == last_time and checkpoint.last_external_id and msg_id <= checkpoint.last_external_id:
            return True
        return False

    def _get_checkpoint(self, resource_type: str, scope_key: str) -> WeComSyncCheckpoint | None:
        return (
            self.db.query(WeComSyncCheckpoint)
            .filter(
                WeComSyncCheckpoint.resource_type == resource_type,
                WeComSyncCheckpoint.scope_key == scope_key,
            )
            .first()
        )

    def _complete_checkpoint(
        self,
        resource_type: str,
        scope_key: str,
        last_sync_time: datetime | None,
        last_external_id: str | None,
    ) -> None:
        checkpoint = self._get_checkpoint(resource_type, scope_key)
        if checkpoint is None:
            checkpoint = WeComSyncCheckpoint(resource_type=resource_type, scope_key=scope_key)
            self.db.add(checkpoint)
        now = _utcnow()
        checkpoint.last_sync_time = last_sync_time
        checkpoint.last_external_id = last_external_id
        checkpoint.last_status = "success"
        checkpoint.last_error = None
        checkpoint.last_finished_at = now
        if checkpoint.last_started_at is None:
            checkpoint.last_started_at = now
        self.db.commit()

    def _resolve_bot_code(self, bot_code: str | None, bot_id: str | None, channel: str | None = None) -> str:
        if bot_code:
            return str(bot_code)
        if channel and bot_id:
            return f"{channel}:{bot_id}"
        if bot_id:
            existing = self.db.query(WeComBot).filter(WeComBot.bot_id == str(bot_id)).first()
            if existing:
                return existing.bot_code
        return str(bot_id or "")

    def _max_key(
        self,
        current_time: datetime | None,
        current_id: str | None,
        candidate_time: datetime | None,
        candidate_id: str | None,
    ) -> tuple[datetime | None, str | None]:
        candidate_time = _ensure_utc(candidate_time)
        current_time = _ensure_utc(current_time)
        if candidate_time is None:
            return current_time, current_id
        if current_time is None or candidate_time > current_time:
            return candidate_time, candidate_id
        if candidate_time == current_time and (current_id is None or (candidate_id or "") > current_id):
            return candidate_time, candidate_id
        return current_time, current_id

    def _to_bool_or_none(self, value: Any) -> bool | None:
        if value is None:
            return None
        if isinstance(value, bool):
            return value
        if isinstance(value, int):
            return bool(value)
        if isinstance(value, str):
            return value.lower() in {"1", "true", "yes", "online", "enable"}
        return bool(value)

    def _is_online_bot(self, data: dict[str, Any]) -> bool:
        return bool(self._to_bool_or_none(data.get("online")))