diff --git a/app/src/doctor_workstation/app.py b/app/src/doctor_workstation/app.py
index 6e19721f4..316d153a1 100644
--- a/app/src/doctor_workstation/app.py
+++ b/app/src/doctor_workstation/app.py
@@ -5,8 +5,9 @@ from __future__ import annotations
import logging
import os
import sys
-import time
-from contextlib import suppress
+import time
+from collections.abc import Mapping, Sequence
+from contextlib import suppress
from typing import Any
from PySide6.QtCore import QLibraryInfo, QLocale, QObject, Qt, QTimer, QTranslator
@@ -34,17 +35,179 @@ from doctor_workstation.services import (
build_repository,
)
from doctor_workstation.ui import LoginWindow, ShellWindow, apply_theme
-from doctor_workstation.ui.dialogs.app_update import AppUpdateSession
-from doctor_workstation.ui.widgets import (
- friendly_error,
- run_async,
+from doctor_workstation.ui.dialogs.app_update import AppUpdateSession
+from doctor_workstation.ui.widgets import (
+ first_value,
+ friendly_error,
+ gender_text,
+ get_value,
+ run_async,
set_authentication_expired_handler,
show_toast,
)
from doctor_workstation.video import BackendMode, launch_video_call
from doctor_workstation.video.window import WEBENGINE_AVAILABLE
-LOGGER = logging.getLogger(__name__)
+LOGGER = logging.getLogger(__name__)
+
+
+def _video_case_text(value: Any, *, limit: int = 2000) -> str:
+ """Render a bounded, JSON-safe clinical value for the trusted call rail."""
+
+ if value in (None, "", [], {}):
+ return ""
+ if isinstance(value, Mapping):
+ parts = [
+ f"{key}:{_video_case_text(item, limit=limit)}"
+ for key, item in value.items()
+ if item not in (None, "", [], {})
+ ]
+ return ";".join(part for part in parts if not part.endswith(":"))[:limit]
+ if isinstance(value, Sequence) and not isinstance(value, (str, bytes, bytearray)):
+ return "、".join(
+ part
+ for item in value
+ if (part := _video_case_text(item, limit=limit))
+ )[:limit]
+ return str(value).strip()[:limit]
+
+
+def _video_identity(value: Any) -> str:
+ if value in (None, "") or isinstance(value, bool):
+ return ""
+ text = str(value).strip()
+ if not text:
+ return ""
+ with suppress(ValueError, TypeError):
+ return str(int(text))
+ return text
+
+
+def _video_identity_matches(expected: Any, actual: Any) -> bool:
+ normalized_actual = _video_identity(actual)
+ return not normalized_actual or normalized_actual == _video_identity(expected)
+
+
+def _build_video_patient_case(
+ detail: Any,
+ fallback_record: Any,
+ *,
+ diagnosis_id: Any,
+ patient_id: Any,
+ patient_name: str,
+) -> dict[str, str]:
+ """Reduce the readonly diagnosis aggregate to the fields needed in-call."""
+
+ if isinstance(detail, Mapping) and not get_value(detail, "diagnosis", None):
+ nested = get_value(detail, "data", None)
+ if isinstance(nested, Mapping):
+ detail = nested
+ diagnosis = get_value(detail, "diagnosis", None)
+ if not diagnosis and isinstance(detail, Mapping):
+ diagnosis = detail
+ diagnosis = diagnosis or {}
+ patient = get_value(detail, "patient", None) or {}
+ appointment = get_value(detail, "appointment", None) or {}
+
+ detail_diagnosis_id = first_value(diagnosis, "id", "diagnosis_id", default=None)
+ detail_patient_id = first_value(
+ diagnosis,
+ "source_patient_id",
+ default=first_value(
+ patient,
+ "source_patient_id",
+ default=None,
+ ),
+ )
+ if not _video_identity_matches(
+ diagnosis_id,
+ detail_diagnosis_id,
+ ) or not _video_identity_matches(patient_id, detail_patient_id):
+ detail = diagnosis = patient = appointment = {}
+
+ fallback_diagnosis_id = first_value(
+ fallback_record,
+ "diagnosis_id",
+ "id",
+ default=None,
+ )
+ fallback_patient_id = first_value(
+ fallback_record,
+ "source_patient_id",
+ "patient_id",
+ default=None,
+ )
+ if not _video_identity_matches(
+ diagnosis_id,
+ fallback_diagnosis_id,
+ ) or not _video_identity_matches(patient_id, fallback_patient_id):
+ fallback_record = {}
+ sources = (diagnosis, patient, appointment, fallback_record)
+
+ def pick(*keys: str, limit: int = 2000) -> str:
+ for source in sources:
+ value = first_value(source, *keys, default=None)
+ text = _video_case_text(value, limit=limit)
+ if text:
+ return text
+ return ""
+
+ raw_gender = next(
+ (
+ first_value(source, "gender_desc", "gender", default=None)
+ for source in sources
+ if first_value(source, "gender_desc", "gender", default=None) not in (None, "")
+ ),
+ None,
+ )
+ return {
+ "diagnosisId": _video_case_text(diagnosis_id, limit=80),
+ "name": pick("patient_name", "name", limit=120)
+ or _video_case_text(patient_name, limit=120)
+ or "患者",
+ "gender": "" if raw_gender in (None, "") else gender_text(raw_gender),
+ "age": pick("age", limit=20),
+ "height": pick("height", limit=20),
+ "weight": pick("weight", limit=20),
+ "diagnosisDate": pick("diagnosis_date", "diagnosis_date_text", limit=80),
+ "appointmentDate": pick(
+ "appointment_date",
+ "latest_appointment_date",
+ limit=80,
+ ),
+ "clinicalDiagnosis": pick(
+ "clinical_diagnosis",
+ "diagnosis_name",
+ "disease_name",
+ ),
+ "chiefComplaint": pick("chief_complaint", "complaint"),
+ "presentIllness": pick("present_illness", "present_illness_history", "symptoms"),
+ "pastHistory": pick("past_history_text", "past_history_desc", "past_history"),
+ "allergyHistory": pick(
+ "allergy_history_text",
+ "allergy_history_desc",
+ "allergy_history",
+ ),
+ "personalHistory": pick(
+ "personal_history_text",
+ "personal_history_desc",
+ "personal_history",
+ ),
+ "familyHistory": pick(
+ "family_history_text",
+ "family_history_desc",
+ "family_history",
+ ),
+ "currentMedication": pick(
+ "current_medications",
+ "current_medicine",
+ "current_medication",
+ ),
+ "tongue": pick("tongue", "tongue_coating"),
+ "pulse": pick("pulse", "pulse_condition"),
+ "prescriptionOpinion": pick("prescription_opinion", "prescription_advice"),
+ "remark": pick("remark"),
+ }
class _ChineseQtTranslator(QTranslator):
@@ -247,9 +410,11 @@ class ApplicationController(QObject):
self.shell_window: ShellWindow | None = None
self.current_repository: Any = None
self.current_demo_mode = config.demo_mode
- self.video_calls: dict[str, Any] = {}
- self.video_pending: dict[str, object] = {}
- self.demo_video_dialogs: dict[str, DemoVideoDialog] = {}
+ self.video_calls: dict[str, Any] = {}
+ self.video_pending: dict[str, object] = {}
+ self.demo_video_dialogs: dict[str, DemoVideoDialog] = {}
+ self._video_preview_state: dict[str, Any] | None = None
+ self._video_preview_generation = 0
self._restore_generation = 0
self._restore_in_progress = False
self._restore_worker: Any = None
@@ -547,16 +712,17 @@ class ApplicationController(QObject):
self._logout(message="登录状态已失效,请重新登录。")
return True
- def _logout(self, *, message: str = "") -> None:
- """Clear authenticated resources and return to the login window."""
-
- calls = tuple(self.video_calls.values())
+ def _logout(self, *, message: str = "") -> None:
+ """Clear authenticated resources and return to the login window."""
+
+ self._restore_video_preview(activate=False)
+ calls = tuple(self.video_calls.values())
for call in calls:
with suppress(Exception):
call.close()
self._wait_for_video_lifecycle(calls, timeout=1.25)
- self.video_calls.clear()
- self.video_pending.clear()
+ self.video_calls.clear()
+ self.video_pending.clear()
for dialog in self.demo_video_dialogs.values():
dialog.close()
self.demo_video_dialogs.clear()
@@ -579,7 +745,8 @@ class ApplicationController(QObject):
patient_id = payload.get("patient_id")
diagnosis_id = payload.get("diagnosis_id")
patient_name = str(payload.get("patient_name") or "患者")
- open_im = str(payload.get("mode") or "video").lower() == "im"
+ open_im = str(payload.get("mode") or "video").lower() == "im"
+ fallback_record = payload.get("record")
if patient_id in (None, "") or diagnosis_id in (None, ""):
show_toast(parent, "患者或诊单信息不完整,无法发起视频。", "danger", 4200)
return
@@ -633,27 +800,49 @@ class ApplicationController(QObject):
marker = object()
self.video_pending[call_key] = marker
- def get_ticket() -> Any:
- return repository.get_call_ticket(
- patient_id=int(patient_id),
- diagnosis_id=int(diagnosis_id),
- )
+ def get_video_context() -> tuple[Any, dict[str, str]]:
+ ticket = repository.get_call_ticket(
+ patient_id=int(patient_id),
+ diagnosis_id=int(diagnosis_id),
+ )
+ detail: Any = {}
+ detail_loader = getattr(repository, "patient_detail", None)
+ if callable(detail_loader):
+ try:
+ detail = detail_loader(int(diagnosis_id))
+ except Exception as error:
+ LOGGER.warning(
+ "patient detail could not be loaded for video call",
+ extra={
+ "diagnosis_id": diagnosis_id,
+ "error_type": type(error).__name__,
+ },
+ )
+ patient_case = _build_video_patient_case(
+ detail,
+ fallback_record,
+ diagnosis_id=diagnosis_id,
+ patient_id=patient_id,
+ patient_name=patient_name,
+ )
+ return ticket, patient_case
def request_ticket() -> None:
if self.video_pending.get(call_key) is not marker:
return
- run_async(
- get_ticket,
- on_success=lambda ticket: self._launch_video(
- ticket,
- diagnosis_id=diagnosis_id,
- patient_id=patient_id,
- repository=repository,
+ run_async(
+ get_video_context,
+ on_success=lambda context: self._launch_video(
+ context[0],
+ diagnosis_id=diagnosis_id,
+ patient_id=patient_id,
+ repository=repository,
call_key=call_key,
marker=marker,
- open_im=open_im,
- patient_name=patient_name,
- ),
+ open_im=open_im,
+ patient_name=patient_name,
+ patient_case=context[1],
+ ),
on_error=lambda error: self._video_ticket_error(
call_key,
marker,
@@ -696,8 +885,9 @@ class ApplicationController(QObject):
repository: Any,
call_key: str,
marker: object,
- open_im: bool = False,
- patient_name: str = "患者",
+ open_im: bool = False,
+ patient_name: str = "患者",
+ patient_case: Mapping[str, Any] | None = None,
) -> None:
if self.video_pending.get(call_key) is not marker:
return
@@ -723,9 +913,13 @@ class ApplicationController(QObject):
local_dist=video_dist_path(),
remote_url=self.config.video_web_url or None,
logger=logging.getLogger("doctor_workstation.video"),
- open_im=open_im,
- patient_name=patient_name,
- )
+ open_im=open_im,
+ patient_name=patient_name,
+ patient_case=patient_case,
+ on_open_diagnosis=lambda current_id=diagnosis_id: (
+ self._open_video_diagnosis(current_id)
+ ),
+ )
except Exception as error:
LOGGER.exception("video call could not be launched")
show_toast(
@@ -734,20 +928,123 @@ class ApplicationController(QObject):
"danger",
5600,
)
- return
- self.video_calls[call_key] = call
+ return
+ self.video_calls[call_key] = call
qt_window = getattr(call, "qt_window", None)
if qt_window is not None:
qt_window.destroyed.connect(
lambda _obj=None, key=call_key, expected=call: self._release_video_call(
key,
expected,
- )
- )
-
- def _release_video_call(self, call_key: str, call: Any) -> None:
- if self.video_calls.get(call_key) is call:
- self.video_calls.pop(call_key, None)
+ )
+ )
+
+ def _open_video_diagnosis(self, diagnosis_id: Any) -> None:
+ """Open the diagnosis while keeping its live video visible as a preview."""
+
+ shell = self.shell_window
+ if shell is None or self.current_repository is None:
+ return
+ dialog = shell.open_diagnosis_by_id(diagnosis_id, modeless=True)
+ if dialog is None:
+ return
+ call = self.video_calls.get(str(diagnosis_id))
+ video_window = getattr(call, "qt_window", None)
+ if video_window is not None:
+ self._show_video_preview(video_window, dialog)
+
+ def _show_video_preview(self, video_window: Any, dialog: QDialog) -> None:
+ """Pin a compact call window above the modeless diagnosis drawer."""
+
+ current = self._video_preview_state
+ if current is not None and current.get("window") is not video_window:
+ self._restore_video_preview(activate=False)
+
+ self._video_preview_generation += 1
+ generation = self._video_preview_generation
+ if current is None or current.get("window") is not video_window:
+ try:
+ state = {
+ "window": video_window,
+ "geometry": video_window.geometry(),
+ "minimum_size": video_window.minimumSize(),
+ "maximized": video_window.isMaximized(),
+ "full_screen": video_window.isFullScreen(),
+ "stays_on_top": bool(
+ video_window.windowFlags()
+ & Qt.WindowType.WindowStaysOnTopHint
+ ),
+ }
+ screen = video_window.screen() or QGuiApplication.primaryScreen()
+ available = screen.availableGeometry()
+ preview_width = min(540, max(460, round(available.width() * 0.29)))
+ preview_height = min(380, max(320, round(preview_width * 0.66)))
+ margin = 18
+
+ video_window.showNormal()
+ video_window.setMinimumSize(440, 300)
+ video_window.setWindowFlag(Qt.WindowType.WindowStaysOnTopHint, True)
+ video_window.resize(preview_width, preview_height)
+ video_window.move(
+ available.x() + available.width() - preview_width - margin,
+ available.y() + margin,
+ )
+ video_window.show()
+ self._video_preview_state = state
+ except RuntimeError:
+ self._video_preview_state = None
+ return
+
+ dialog.finished.connect(
+ lambda _result, expected=generation: self._restore_video_preview(expected)
+ )
+ try:
+ video_window.raise_()
+ dialog.raise_()
+ dialog.activateWindow()
+ except RuntimeError:
+ self._video_preview_state = None
+
+ def _restore_video_preview(
+ self,
+ generation: int | None = None,
+ *,
+ activate: bool = True,
+ ) -> None:
+ if generation is not None and generation != self._video_preview_generation:
+ return
+ state = self._video_preview_state
+ if state is None:
+ return
+ self._video_preview_state = None
+ self._video_preview_generation += 1
+ window = state.get("window")
+ try:
+ window.setWindowFlag(
+ Qt.WindowType.WindowStaysOnTopHint,
+ bool(state.get("stays_on_top")),
+ )
+ window.setMinimumSize(state["minimum_size"])
+ window.setGeometry(state["geometry"])
+ if state.get("full_screen"):
+ window.showFullScreen()
+ elif state.get("maximized"):
+ window.showMaximized()
+ else:
+ window.showNormal()
+ window.raise_()
+ if activate:
+ window.activateWindow()
+ except (AttributeError, RuntimeError):
+ return
+
+ def _release_video_call(self, call_key: str, call: Any) -> None:
+ preview = self._video_preview_state
+ if preview is not None and preview.get("window") is getattr(call, "qt_window", None):
+ self._video_preview_state = None
+ self._video_preview_generation += 1
+ if self.video_calls.get(call_key) is call:
+ self.video_calls.pop(call_key, None)
def _forget_demo_dialog(self, call_key: str, dialog: DemoVideoDialog) -> None:
if self.demo_video_dialogs.get(call_key) is dialog:
@@ -778,15 +1075,16 @@ class ApplicationController(QObject):
if icon_file.exists():
window.setWindowIcon(QIcon(str(icon_file)))
- def shutdown(self) -> None:
+ def shutdown(self) -> None:
"""Invalidate asynchronous restoration and release owned resources."""
if self._shutting_down:
return
self._shutting_down = True
- self._cancel_session_restore()
- set_authentication_expired_handler(None)
- calls = tuple(self.video_calls.values())
+ self._cancel_session_restore()
+ set_authentication_expired_handler(None)
+ self._restore_video_preview(activate=False)
+ calls = tuple(self.video_calls.values())
for call in calls:
with suppress(Exception):
call.close()
diff --git a/app/src/doctor_workstation/ui/dialogs/ai_consult.py b/app/src/doctor_workstation/ui/dialogs/ai_consult.py
index f6d29eaba..f8125c18e 100644
--- a/app/src/doctor_workstation/ui/dialogs/ai_consult.py
+++ b/app/src/doctor_workstation/ui/dialogs/ai_consult.py
@@ -15,6 +15,7 @@ from urllib.parse import urlsplit
from PySide6.QtCore import QObject, QPointF, QRunnable, QSize, Qt, QThreadPool, QTimer, Signal, Slot
from PySide6.QtGui import (
QColor,
+ QFont,
QIcon,
QKeyEvent,
QPainter,
@@ -22,6 +23,9 @@ from PySide6.QtGui import (
QPen,
QPixmap,
QPolygonF,
+ QTextBlockFormat,
+ QTextCharFormat,
+ QTextCursor,
)
from PySide6.QtWidgets import (
QDialog,
@@ -44,7 +48,7 @@ from PySide6.QtWidgets import (
from ..diagnosis_drawer import CaseGrid, _RemoteImageButton
from ..diagnosis_media import open_safe_http_url, safe_http_url
-from ..theme import crisp_pixmap, mark_business_dialog
+from ..theme import apply_reading_rhythm, crisp_pixmap, mark_business_dialog
from ..widgets import (
display_text,
first_value,
@@ -790,14 +794,24 @@ _DOCTOR_DOCUMENT_CSS = (
"li { margin:3px 0; line-height:1.58; } "
"a { color:#DDE1FF; } code,pre { color:#FFFFFF; }"
)
+# 模型回复几乎都是“分节标题 + 两层要点”的长文。早期样式里标题只比正文大 1px、
+# 段落与列表项的间距也几乎相同,整段读起来就是一堵字墙。这里把层级、行距和分节
+# 留白拉开:标题明显更大更重,顶层小节之间留出整行空白,嵌套要点单独收紧缩进。
_AI_DOCUMENT_CSS = (
- "body { color:#34436B; font-size:14px; line-height:1.68; } "
- "h1,h2,h3,h4 { color:#15224A; font-size:15px; margin:12px 0 6px; line-height:1.45; } "
- "p { margin:6px 0; line-height:1.68; } ul,ol { margin:7px 0 7px 21px; } "
- "li { margin:4px 0; line-height:1.62; } "
- "strong { color:#15224A; } a { color:#5B67F1; } "
+ "body { color:#3A4870; font-size:14px; line-height:200%; } "
+ "h1,h2 { color:#111B3F; font-size:17px; margin:22px 0 10px; line-height:160%; } "
+ "h3,h4 { color:#15224A; font-size:15px; margin:18px 0 8px; line-height:160%; } "
+ "p { margin:10px 0; line-height:200%; } "
+ "ol { margin:12px 0 12px 22px; } "
+ "ul { margin:8px 0 8px 20px; } "
+ "li { margin:6px 0; line-height:190%; } "
+ # 顶层小节之间留出整行空白,让四个小节一眼可数。
+ "ol > li { margin:16px 0; } "
+ "ol > li > strong { color:#111B3F; font-size:15px; } "
+ "strong { color:#1B2A55; } a { color:#5B67F1; } "
+ "hr { margin:20px 0; } "
"code { color:#33406B; background:#EEF1FF; } "
- "pre { color:#33406B; background:#F0F3FA; margin:8px 0; padding:8px; }"
+ "pre { color:#33406B; background:#F0F3FA; margin:12px 0; padding:10px; }"
)
_STRUCTURED_FIELD_LABELS = {
"diagnosis": "诊断建议",
@@ -1257,6 +1271,7 @@ def render_chat_payload(browser: QTextBrowser, raw: Any, *, role: str = "ai") ->
return
if isinstance(raw, (Mapping, list, tuple)):
browser.setMarkdown(_structured_markdown(raw))
+ apply_reading_rhythm(browser, role=role)
return
text = str(raw).strip()
if not text:
@@ -1269,12 +1284,15 @@ def render_chat_payload(browser: QTextBrowser, raw: Any, *, role: str = "ai") ->
parsed = None
if parsed is not None:
browser.setMarkdown(_structured_markdown(parsed))
+ apply_reading_rhythm(browser, role=role)
return
lowered = text[:240].lower()
if text.startswith("<") and any(marker in lowered for marker in _HTML_MARKERS):
browser.setHtml(text)
+ apply_reading_rhythm(browser, role=role)
return
browser.setMarkdown(text)
+ apply_reading_rhythm(browser, role=role)
def _unwrap_analysis(payload: Any) -> dict[str, Any]:
@@ -1894,6 +1912,75 @@ def _parse_clinical_analysis(raw: Any) -> _ClinicalAnalysisModel | None:
)
+#: One section of a generic structured reply: a title plus its bullet points.
+_ReportSection = namedtuple("_ReportSection", "title items")
+
+_REPORT_NUMBERED_RE = re.compile(r"^\s*(\d{1,2})\s*[.、))]\s*(.+?)\s*$")
+_REPORT_BULLET_RE = re.compile(r"^\s*[-*+•○]\s*(.+?)\s*$")
+
+
+def parse_structured_report(raw: Any) -> tuple[str, tuple[_ReportSection, ...], str] | None:
+ """Split a sectioned reply into ``(intro, sections, disclaimer)``.
+
+ The clinical panel only recognises four fixed section names (证候分析,
+ 信息缺口, 建议下一步, 风险提示), so the sectioned answers models actually
+ return — "症状演变与疗效评估", "血糖控制与监测细节", … — fell through to plain
+ text. This accepts any reply that is genuinely sectioned: two or more
+ numbered or ``#`` headings, each carrying at least one bullet.
+ """
+
+ if not isinstance(raw, str):
+ return None
+ text = raw.strip()
+ if len(text) < 120 or text[0] in "[{<" or "```" in text:
+ return None
+
+ intro: list[str] = []
+ disclaimer: list[str] = []
+ sections: list[_ReportSection] = []
+ collecting_disclaimer = False
+ for line in text.replace("\r\n", "\n").splitlines():
+ stripped = line.strip()
+ if not stripped or set(stripped) <= {"-", "*", "_"}:
+ continue
+ plain = _plain_markdown(stripped)
+ if collecting_disclaimer or plain.startswith(("重要提示", "免责声明", "提示:", "安全提示")):
+ collecting_disclaimer = True
+ disclaimer.append(plain)
+ continue
+
+ bullet = _REPORT_BULLET_RE.match(line)
+ if bullet is not None and sections:
+ sections[-1].items.append(_plain_markdown(bullet.group(1)))
+ continue
+
+ heading = ""
+ if stripped.startswith("#"):
+ heading = _plain_markdown(stripped.lstrip("#").strip())
+ else:
+ numbered = _REPORT_NUMBERED_RE.match(_plain_markdown(stripped))
+ # 顶层小节标题很短;带句号的长句是正文,不是标题。
+ if numbered is not None and len(numbered.group(2)) <= 28:
+ heading = numbered.group(2)
+ if heading:
+ sections.append(_ReportSection(heading, []))
+ continue
+
+ if sections:
+ sections[-1].items.append(plain)
+ elif bullet is None:
+ intro.append(plain)
+
+ usable = [section for section in sections if section.items]
+ if len(usable) < 2:
+ return None
+ return (
+ " ".join(intro).strip(),
+ tuple(_ReportSection(s.title, tuple(s.items)) for s in usable),
+ " ".join(disclaimer).strip(),
+ )
+
+
_InsightItem = namedtuple("_InsightItem", "kind marker label text")
_INSIGHT_LIST_RE = re.compile(r"^\s*(\d{1,2})\s*([\.、))]\s*)")
@@ -2088,6 +2175,110 @@ class _RichMessage(QTextBrowser):
self._fitting = False
+class _StructuredReportPanel(QWidget):
+ """Scan-first report for any sectioned reply.
+
+ Renders each section as its own card with a numbered chip, so a doctor can
+ count and jump between sections instead of reading a continuous column of
+ bullets.
+ """
+
+ def __init__(
+ self,
+ intro: str,
+ sections: Sequence[_ReportSection],
+ disclaimer: str,
+ *,
+ time_text: str = "",
+ parent: QWidget | None = None,
+ ) -> None:
+ super().__init__(parent)
+ self.setObjectName("AiConsultClinicalPanel")
+ self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum)
+ self.sections = tuple(sections)
+ root = QVBoxLayout(self)
+ root.setContentsMargins(0, 0, 0, 0)
+ root.setSpacing(12)
+
+ header = QHBoxLayout()
+ header.setContentsMargins(0, 0, 0, 0)
+ header.setSpacing(9)
+ title = QLabel("AI 结构化报告")
+ title.setObjectName("AiConsultClinicalTitle")
+ header.addWidget(title)
+ self.meta_label = QLabel(time_text)
+ self.meta_label.setObjectName("AiConsultClinicalMeta")
+ header.addWidget(self.meta_label)
+ header.addStretch(1)
+ badge = QLabel(f"{len(self.sections)} 个要点")
+ badge.setObjectName("AiConsultClinicalBadge")
+ badge.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
+ header.addWidget(badge, 0, Qt.AlignmentFlag.AlignVCenter)
+ root.addLayout(header)
+
+ if intro:
+ summary = QFrame(self)
+ summary.setObjectName("AiConsultClinicalSummary")
+ summary.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Fixed)
+ _style_surface(summary)
+ summary_layout = QVBoxLayout(summary)
+ summary_layout.setContentsMargins(13, 11, 13, 11)
+ summary_layout.setSpacing(4)
+ body = QLabel(intro, summary)
+ body.setObjectName("AiConsultClinicalSummaryBody")
+ body.setWordWrap(True)
+ summary_layout.addWidget(body)
+ root.addWidget(summary)
+
+ for index, section in enumerate(self.sections, start=1):
+ root.addWidget(self._section_card(index, section))
+
+ if disclaimer:
+ note = QLabel(disclaimer, self)
+ note.setObjectName("AiConsultClinicalDisclaimer")
+ note.setWordWrap(True)
+ note.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Fixed)
+ root.addWidget(note)
+ # 富余高度归到底部,否则会被平摊进每张卡片,把报告拉得空空荡荡。
+ root.addStretch(1)
+
+ def _section_card(self, index: int, section: _ReportSection) -> QFrame:
+ card = QFrame(self)
+ card.setObjectName("AiConsultClinicalSection")
+ card.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Fixed)
+ _style_surface(card)
+ layout = QVBoxLayout(card)
+ layout.setContentsMargins(14, 12, 14, 12)
+ layout.setSpacing(8)
+
+ head = QHBoxLayout()
+ head.setContentsMargins(0, 0, 0, 0)
+ head.setSpacing(8)
+ chip = QLabel(str(index), card)
+ chip.setObjectName("AiConsultHypothesisTag")
+ chip.setAlignment(Qt.AlignmentFlag.AlignCenter)
+ head.addWidget(chip)
+ title = QLabel(section.title, card)
+ title.setObjectName("AiConsultClinicalSectionTitle")
+ title.setWordWrap(True)
+ head.addWidget(title, 1)
+ layout.addLayout(head)
+
+ for item in section.items:
+ row = QFrame(card)
+ row.setObjectName("AiConsultGapRow")
+ _style_surface(row)
+ row_layout = QHBoxLayout(row)
+ row_layout.setContentsMargins(11, 9, 11, 9)
+ row_layout.setSpacing(8)
+ body = QLabel(item, row)
+ body.setObjectName("AiConsultClinicalBody")
+ body.setWordWrap(True)
+ row_layout.addWidget(body, 1)
+ layout.addWidget(row)
+ return card
+
+
class _ClinicalAnalysisPanel(QWidget):
"""High-contrast, scan-first presentation for completed clinical replies."""
@@ -2499,14 +2690,27 @@ class _ChatBubble(QWidget):
if self._role != "ai" or self.body is None:
return False
model = _parse_clinical_analysis(self._raw_payload)
- if model is None:
+ panel: QWidget | None = None
+ if model is not None:
+ panel = _ClinicalAnalysisPanel(
+ model,
+ time_text=self.stamp.text(),
+ parent=self._bubble_frame,
+ )
+ else:
+ # 临床面板只认四个固定小节名;其余同样分好节的长回复走通用结构化报告,
+ # 而不是退回成一整段纯文本。
+ report = parse_structured_report(self._raw_payload)
+ if report is not None:
+ panel = _StructuredReportPanel(
+ *report,
+ time_text=self.stamp.text(),
+ parent=self._bubble_frame,
+ )
+ if panel is None:
return False
self._reset_clinical_panel()
- panel = _ClinicalAnalysisPanel(
- model,
- time_text=self.stamp.text(),
- parent=self._bubble_frame,
- )
+ panel.setParent(self._bubble_frame)
self._clinical_panel = panel
self._role_name.hide()
self.stamp.hide()
@@ -2691,6 +2895,14 @@ class _ClickCard(QFrame):
# the doctor can see exactly what material is going to the model.
AI_CONTEXT_MAX_CHARS = 320
AI_PROMPT_LIMIT = 500
+
+#: 首个增量到达前显示的占位文案,避免留下一块没有任何说明的空白气泡。
+AI_STREAM_PENDING_TEXT = "正在生成…"
+
+#: 连接结束但一个字都没收到时的兜底文案。
+AI_STREAM_SILENT_TEXT = (
+ "AI 助手没有返回内容,可能是服务端未响应或连接中断,请稍后重试。"
+)
AI_CONTEXT_SEPARATOR = "\n\n— 医生提问 —\n"
@@ -2998,6 +3210,10 @@ class AiConsultDialog(QDialog):
self._patient_ai_context: str = ""
self._patient_ai_context_labels: list[str] = []
self._patient_ai_context_bubble: _ChatBubble | None = None
+ # 全量上下文说明每轮问答都一样,只在本次会话第一次提问时提示一次。
+ self._context_notice_shown = False
+ # done 事件是否到达。用于区分“模型没内容”和“连接直接断了”。
+ self._stream_completed = False
self._follow_chat = True
self._flush_timer = QTimer(self)
self._flush_timer.setSingleShot(True)
@@ -3005,6 +3221,14 @@ class AiConsultDialog(QDialog):
self._flush_timer.timeout.connect(self._flush_stream_chunks)
self.setObjectName("AiConsultDialog")
self.setWindowTitle("问诊详情")
+ # QDialog 默认只带关闭按钮,医生无法把这个信息密度很高的窗口放大到整屏。
+ # 显式补上最大化/最小化按钮,并允许拖拽边角调整大小。
+ self.setWindowFlags(
+ self.windowFlags()
+ | Qt.WindowType.WindowMinimizeButtonHint
+ | Qt.WindowType.WindowMaximizeButtonHint
+ )
+ self.setSizeGripEnabled(True)
self.resize(1280, 820)
self.setMinimumSize(1080, 680)
self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True)
@@ -3047,6 +3271,8 @@ class AiConsultDialog(QDialog):
self._patient_ai_context = ""
self._patient_ai_context_labels = []
self._patient_ai_context_bubble = None
+ # 换患者等于开启新会话,全量上下文说明需要再提示一次。
+ self._context_notice_shown = False
# Appointment seeds are presentation hints only. In the admin list,
# ``patient_id`` may actually be the diagnosis id, so it must never
# replace the separately supplied patient owner.
@@ -5281,12 +5507,18 @@ class AiConsultDialog(QDialog):
self._append_bubble(
"doctor", text, time_text=datetime.now().strftime("%H:%M")
)
- self._append_bubble(
- "ai",
- "服务端将按当前诊单实时附带患者全部纵向资料(病历、备注/舌苔、报告、日常记录、视频转写及历史处方)。",
- time_text="全量上下文",
- )
- self._stream_bubble = self._append_bubble("ai", "")
+ if not self._context_notice_shown:
+ self._append_bubble(
+ "ai",
+ "服务端将按当前诊单实时附带患者全部纵向资料"
+ "(病历、备注/舌苔、报告、日常记录、视频转写及历史处方)。",
+ time_text="全量上下文",
+ )
+ self._context_notice_shown = True
+ # 首帧到达前先占位。空气泡在后端无响应时会一直是一块空白卡片,
+ # 医生无法判断是还在生成还是已经失败。
+ self._stream_bubble = self._append_bubble("ai", AI_STREAM_PENDING_TEXT)
+ self._stream_completed = False
self._stream_text = ""
self._pending_chunks.clear()
self._stream_meta.clear()
@@ -5341,6 +5573,7 @@ class AiConsultDialog(QDialog):
if kind != "done":
return
self._stream_meta.update(payload)
+ self._stream_completed = True
if not self._stream_text and not self._pending_chunks:
answer = first_value(payload, "answer", "content", default="")
if answer not in (None, ""):
@@ -5396,6 +5629,16 @@ class AiConsultDialog(QDialog):
return
if self._stream_worker is worker:
self._stream_worker = None
+ # 连接结束却既没有 done 也没有报错时(服务端静默断开),占位气泡会永远
+ # 停在“正在生成…”。这里补一条明确说明,而不是留一块空白卡片。
+ if (
+ not self._stream_completed
+ and not self._stream_text
+ and self._stream_bubble is not None
+ ):
+ self._stream_text = AI_STREAM_SILENT_TEXT
+ self._stream_bubble.set_payload(self._stream_text)
+ self._stream_bubble.set_time_text(datetime.now().strftime("%H:%M"))
self._asking = False
self.send_button.setEnabled(True)
@@ -5408,6 +5651,7 @@ class AiConsultDialog(QDialog):
self._stream_bubble = None
self._pending_chunks.clear()
self._stream_text = ""
+ self._stream_completed = False
self._stream_meta.clear()
self._asking = False
self.send_button.setEnabled(True)
diff --git a/app/src/doctor_workstation/ui/dialogs/diagnosis.py b/app/src/doctor_workstation/ui/dialogs/diagnosis.py
index cf8265e4d..0329a91b4 100644
--- a/app/src/doctor_workstation/ui/dialogs/diagnosis.py
+++ b/app/src/doctor_workstation/ui/dialogs/diagnosis.py
@@ -1911,8 +1911,20 @@ class DiagnosisDialog(QDialog):
)
present_diagnosis_ai_report(self.repository, self.permissions, self, row)
- def open_view_only(self, diagnosis_id: int, *, seed: Any = None) -> None:
- self.open_for(diagnosis_id, editable=False, seed=seed, view_only=True)
+ def open_view_only(
+ self,
+ diagnosis_id: int,
+ *,
+ seed: Any = None,
+ modeless: bool = False,
+ ) -> None:
+ self.open_for(
+ diagnosis_id,
+ editable=False,
+ seed=seed,
+ view_only=True,
+ modeless=modeless,
+ )
def open_for(
self,
@@ -1921,6 +1933,7 @@ class DiagnosisDialog(QDialog):
editable: bool = False,
seed: Any = None,
view_only: bool = False,
+ modeless: bool = False,
) -> None:
"""Open immediately, then replace the seed with authoritative server data."""
@@ -1973,7 +1986,7 @@ class DiagnosisDialog(QDialog):
self.view_stack.setCurrentWidget(
self.readonly_page if self._standalone_readonly else self.drawer_overlay
)
- self.setModal(not self._standalone_readonly)
+ self.setModal(not modeless and not self._standalone_readonly)
self.setWindowTitle(
"患者信息详情"
if self._standalone_readonly
diff --git a/app/src/doctor_workstation/ui/dialogs/prescription_ai.py b/app/src/doctor_workstation/ui/dialogs/prescription_ai.py
index df9e153ce..abbab06ec 100644
--- a/app/src/doctor_workstation/ui/dialogs/prescription_ai.py
+++ b/app/src/doctor_workstation/ui/dialogs/prescription_ai.py
@@ -1,72 +1,74 @@
-"""AI prescription-interpretation dialog matching the admin library workflow."""
-
-from __future__ import annotations
-
+"""AI prescription-interpretation dialog matching the admin library workflow."""
+
+from __future__ import annotations
+
import html
import json
from collections.abc import Callable
from dataclasses import dataclass, field
from typing import Any
-
-from PySide6.QtCore import QCoreApplication, QEvent, Qt
-from PySide6.QtWidgets import (
- QDialog,
- QFrame,
+
+from PySide6.QtCore import QCoreApplication, QEvent, QMimeData, Qt
+from PySide6.QtGui import QTextDocument
+from PySide6.QtWidgets import (
+ QDialog,
+ QFrame,
QGridLayout,
QHBoxLayout,
QLabel,
- QLayout,
- QMessageBox,
- QPushButton,
- QScrollArea,
- QTabWidget,
- QTextEdit,
- QVBoxLayout,
- QWidget,
-)
-
-from ..widgets import (
- EmptyState,
- MessageBanner,
- StatusBadge,
- display_text,
- first_value,
- friendly_error,
- get_value,
- has_permission,
- invoke,
- run_async,
- show_toast,
-)
-
+ QMessageBox,
+ QPushButton,
+ QScrollArea,
+ QTabWidget,
+ QTextBrowser,
+ QTextEdit,
+ QVBoxLayout,
+ QWidget,
+)
+
+from ..theme import apply_reading_rhythm
+from ..widgets import (
+ EmptyState,
+ MessageBanner,
+ StatusBadge,
+ display_text,
+ first_value,
+ friendly_error,
+ get_value,
+ has_permission,
+ invoke,
+ run_async,
+ show_toast,
+)
+
AI_MODELS: tuple[tuple[str, str, str], ...] = (
- ("qwen", "千问", "qwen3.6-35b"),
- ("openai", "OpenAI", "gpt-5.6-sol"),
+ ("qwen", "千问", "qwen3.6-35b"),
+ ("openai", "OpenAI", "gpt-5.6-sol"),
)
AI_MODEL_KEYS = frozenset(profile for profile, _label, _name in AI_MODELS)
-AI_REPORT_EDIT_PERMISSIONS = (
- "tcm.prescriptionLibrary/editAiReport",
- "wcf.prescription/editAiReport",
-)
-STRUCTURED_REPORT_SECTIONS = (
- "核心判断",
- "可能症状与证候",
- "主治方向",
- "主要功效",
- "可能适用人群",
- "配伍分析",
- "用药与复核提醒",
- "免责声明",
-)
-MEDICAL_NOTICE = "AI 仅依据药材组合推测可能证候与主治方向,不能替代四诊、辨证和处方审核。"
-DIAGNOSIS_MEDICAL_NOTICE = (
- "AI 仅依据当前病历摘要推测可能证候与诊疗方向,不能替代四诊、辨证和临床决策。"
-)
+AI_REPORT_EDIT_PERMISSIONS = (
+ "tcm.prescriptionLibrary/editAiReport",
+ "wcf.prescription/editAiReport",
+)
+STRUCTURED_REPORT_SECTIONS = (
+ "核心判断",
+ "可能症状与证候",
+ "主治方向",
+ "主要功效",
+ "可能适用人群",
+ "配伍分析",
+ "用药与复核提醒",
+ "免责声明",
+)
+MEDICAL_NOTICE = "AI 仅依据药材组合推测可能证候与主治方向,不能替代四诊、辨证和处方审核。"
+DIAGNOSIS_MEDICAL_NOTICE = (
+ "AI 仅依据当前病历摘要推测可能证候与诊疗方向,不能替代四诊、辨证和临床决策。"
+)
CASE_PLACEHOLDERS = {
- "",
- "—",
- "尚未填写病例信息",
- "尚未填写病例信息。",
+ "",
+ "—",
+ "尚未填写病例信息",
+ "尚未填写病例信息。",
"正在加载病例…",
}
@@ -227,6 +229,15 @@ QLabel#PrescriptionAiBody {
font-size: 13px;
line-height: 1.75;
}
+QTextBrowser#PrescriptionAiAnswer {
+ color: #34436B;
+ background-color: #FFFFFF;
+ border: 1px solid #E3E8F4;
+ border-radius: 10px;
+ padding: 12px 14px;
+ selection-color: #17203F;
+ selection-background-color: #DDE2FF;
+}
QLabel#PrescriptionAiMuted {
color: #8A94AA;
font-size: 12px;
@@ -293,440 +304,495 @@ QDialog#PrescriptionAiDialog QScrollBar::sub-line:vertical {
}
"""
+_AI_ANSWER_DOCUMENT_CSS = (
+ "body { color:#34436B; font-size:14px; line-height:1.72; } "
+ "h1 { color:#15224A; font-size:20px; margin:14px 0 8px; line-height:1.4; } "
+ "h2 { color:#15224A; font-size:17px; margin:14px 0 7px; line-height:1.42; } "
+ "h3,h4 { color:#15224A; font-size:15px; margin:12px 0 6px; line-height:1.45; } "
+ "p { margin:6px 0; line-height:1.72; } "
+ "ul,ol { margin:7px 0 8px 22px; } li { margin:4px 0; line-height:1.65; } "
+ "strong { color:#15224A; font-weight:700; } "
+ "blockquote { color:#596788; background:#F5F7FC; border-left:3px solid #7B84F7; "
+ "margin:9px 0; padding:7px 10px; } "
+ "code { color:#33406B; background:#EEF1FF; } "
+ "pre { color:#33406B; background:#F0F3FA; margin:8px 0; padding:9px; } "
+ "table { border-collapse:collapse; margin:8px 0; } "
+ "th,td { border:1px solid #DCE3F2; padding:6px 8px; } "
+ "th { color:#15224A; background:#F5F7FC; font-weight:700; }"
+)
+_AI_ANSWER_MARKDOWN_FEATURES = (
+ QTextDocument.MarkdownFeature.MarkdownDialectGitHub
+ | QTextDocument.MarkdownFeature.MarkdownNoHTML
+)
+
+
+class _AiAnswerBrowser(QTextBrowser):
+ """Selectable Markdown output that never fetches model-supplied images."""
+
+ def __init__(self, parent: QWidget | None = None) -> None:
+ super().__init__(parent)
+ self.setObjectName("PrescriptionAiAnswer")
+ self.setReadOnly(True)
+ self.setOpenLinks(False)
+ self.setOpenExternalLinks(False)
+ self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
+ self.document().setDocumentMargin(2)
+ self.document().setDefaultStyleSheet(_AI_ANSWER_DOCUMENT_CSS)
+
+ def set_answer(self, markdown: str) -> None:
+ document = self.document()
+ document.setDefaultStyleSheet(_AI_ANSWER_DOCUMENT_CSS)
+ document.setMarkdown(markdown, _AI_ANSWER_MARKDOWN_FEATURES)
+ # setMarkdown 绕开 defaultStyleSheet,排版必须作用在解析后的文档上,
+ # 否则这一份长回复仍然是一堵没有层级的字墙。与问诊对话共用同一套节奏。
+ apply_reading_rhythm(self, role="ai")
+ self.moveCursor(self.textCursor().MoveOperation.Start)
+
+ def loadResource(self, resource_type: int, name: Any) -> Any: # noqa: N802
+ if resource_type == QTextDocument.ResourceType.ImageResource:
+ return None
+ return super().loadResource(resource_type, name)
+
+ def createMimeDataFromSelection(self) -> QMimeData: # noqa: N802
+ mime_data = QMimeData()
+ selected = self.textCursor().selectedText().replace("\u2029", "\n")
+ mime_data.setText(selected)
+ return mime_data
+
@dataclass
class ReportState:
- error: str = ""
- data: dict[str, Any] | None = None
- editing: bool = False
- structured_edit: bool = False
- saving: bool = False
- draft: str = ""
- original_content: str = ""
- edit_error: str = ""
-
-
-@dataclass
-class DialogState:
- states: dict[str, ReportState] = field(
- default_factory=lambda: {key: ReportState() for key, _label, _name in AI_MODELS}
- )
-
-
-def formula_label(value: Any) -> str:
- text = str(value or "").strip().lower()
- if text in {"2", "aux", "auxiliary", "secondary", "辅方"}:
- return "辅方"
- if text in {"1", "main", "primary", "主方"}:
- return "主方"
- return str(value or "").strip()
-
-
-def herb_summary(row: Any) -> str:
- herbs = get_value(row, "herbs", None) or []
- if not isinstance(herbs, (list, tuple)) or not herbs:
- return "暂无药材"
- pieces = []
- for herb in herbs:
- name = str(first_value(herb, "name", "medicine_name", default="未命名药材") or "").strip()
- dosage = str(first_value(herb, "dosage", "amount", default="") or "").strip()
- if dosage and not dosage.lower().endswith("g"):
- dosage = f"{dosage}g"
- pieces.append(f"{name} {dosage}".strip())
- return "、".join(pieces)
-
-
-_CASE_FIELDS: tuple[tuple[str, tuple[str, ...]], ...] = (
- ("诊断日期", ("diagnosis_date",)),
- ("诊断类型", ("diagnosis_type_text", "diagnosis_type_desc", "consultation_type", "diagnosis_type")),
- ("婚姻状态", ("marital_status_text", "marital_status_desc", "marital_status")),
- ("主诉", ("chief_complaint", "complaint")),
- ("主要症状", ("symptoms", "main_symptoms")),
- ("现病史", ("present_illness", "present_illness_history")),
- ("发现糖尿病病史", ("diabetes_discovery_year_text", "diabetes_discovery_year")),
- ("当地就诊医院", ("local_hospital_name", "local_hospital")),
- ("当地医院诊断结果", ("local_hospital_diagnosis", "local_diagnosis")),
- ("口腔感觉", ("appetite_text", "appetite_desc", "appetite")),
- ("每日饮水量", ("water_intake_text", "water_intake_desc", "water_intake")),
- ("近月体重变化", ("weight_change_text", "weight_change_desc", "weight_change")),
- ("脂肪肝程度", ("fatty_liver_degree_text", "fatty_liver_degree_desc", "fatty_liver_degree")),
- ("饮食情况", ("diet_condition_text", "diet_condition_desc", "diet_condition")),
- ("肢体感觉", ("body_feeling_text", "body_feeling_desc", "body_feeling")),
- ("睡眠情况", ("sleep_condition_text", "sleep_condition_desc", "sleep_condition")),
- ("眼睛情况", ("eye_condition_text", "eye_condition_desc", "eye_condition")),
- ("头部感觉", ("head_feeling_text", "head_feeling_desc", "head_feeling")),
- ("出汗情况", ("sweat_condition_text", "sweat_condition_desc", "sweat_condition")),
- ("皮肤情况", ("skin_condition_text", "skin_condition_desc", "skin_condition")),
- ("小便情况", ("urine_condition_text", "urine_condition_desc", "urine_condition")),
- ("大便情况", ("stool_condition_text", "stool_condition_desc", "stool_condition")),
- ("腰肾情况", ("kidney_condition_text", "kidney_condition_desc", "kidney_condition")),
- ("既往史", ("past_history_text", "past_history_desc", "past_history")),
- ("外伤史", ("trauma_history_text", "trauma_history_desc", "trauma_history")),
- ("手术史", ("surgery_history_text", "surgery_history_desc", "surgery_history")),
- ("过敏史", ("allergy_history_text", "allergy_history_desc", "allergy_history")),
- ("个人史", ("personal_history_text", "personal_history_desc", "personal_history")),
- ("家族史", ("family_history_text", "family_history_desc", "family_history")),
- ("妊娠哺乳史", ("pregnancy_history_text", "pregnancy_history_desc", "pregnancy_history")),
- ("糖尿病史", ("diabetes_history_text", "diabetes_history", "diabetes_desc")),
- ("当前用药", ("current_medications", "current_medicine", "current_medication")),
- ("临床诊断", ("clinical_diagnosis", "diagnosis")),
- ("舌象", ("tongue", "tongue_coating")),
- ("脉象", ("pulse", "pulse_condition")),
- ("治则", ("treatment_principle",)),
- ("处方意见", ("prescription_opinion", "prescription_advice")),
- ("其他病史", ("other_history", "medical_history_other")),
- ("病例备注", ("remark",)),
-)
-
-
-def diagnosis_case_summary(row: Any, extra: Any = None) -> str:
- """Build a compact clinical snapshot, omitting identity documents and phones."""
-
- sources = [item for item in (row, extra) if item not in (None, "")]
- explicit = str(first_value(row, "case_summary", default="") or "").strip()
- if explicit not in CASE_PLACEHOLDERS:
- return explicit
-
- def pick(*keys: str) -> Any:
- for source in sources:
- value = first_value(source, *keys, default=None)
- if value not in (None, "", [], {}):
- return value
- return None
-
- lines: list[str] = []
- systolic = pick("systolic", "systolic_pressure", "high_pressure")
- diastolic = pick("diastolic", "diastolic_pressure", "low_pressure")
- if systolic not in (None, "") or diastolic not in (None, ""):
- lines.append(f"血压:{display_text(systolic)}/{display_text(diastolic)} mmHg")
- else:
- pressure = pick("blood_pressure")
- if pressure not in (None, ""):
- lines.append(f"血压:{display_text(pressure)}")
- blood_sugar = pick(
- "fasting_blood_sugar", "fasting_glucose", "fasting_blood_glucose", "blood_sugar"
- )
- if blood_sugar not in (None, ""):
- lines.append(f"空腹血糖:{display_text(blood_sugar)} mmol/L")
- height = pick("height")
- weight = pick("weight")
- if height not in (None, ""):
- lines.append(f"身高:{display_text(height)} cm")
- if weight not in (None, ""):
- lines.append(f"体重:{display_text(weight)} kg")
- for caption, keys in _CASE_FIELDS:
- value = pick(*keys)
- if value in (None, "", [], {}):
- continue
- if isinstance(value, (list, tuple, set)):
- value = "、".join(str(item) for item in value if str(item).strip())
- if value not in (None, ""):
- lines.append(f"{caption}:{value}")
- return "\n".join(lines) if lines else "尚未填写病例信息。"
-
-
-def _prescription_subtitle(row: Any) -> str:
- return display_text(first_value(row, "prescription_name", "name", default="未选择处方"))
-
-
-def _prescription_badge(row: Any) -> str:
- return formula_label(first_value(row, "formula_type", default=""))
-
-
-def _diagnosis_subtitle(row: Any) -> str:
- return display_text(first_value(row, "patient_name", "name", default="未选择患者"))
-
-
-def _diagnosis_badge(row: Any) -> str:
- return display_text(
- first_value(
- row,
- "consultation_type",
- "diagnosis_type_text",
- "diagnosis_type_desc",
- "diagnosis_type",
- default="",
- )
- )
-
-
-@dataclass(frozen=True)
-class AiReportKind:
- title: str
- snapshot_label: str
- medical_notice: str
- id_keys: tuple[str, ...]
- id_kwarg: str
- list_method: str
- generate_method: str
- edit_method: str
- view_permissions: tuple[str, ...]
- edit_permissions: tuple[str, ...]
- missing_id_error: str
- subtitle: Callable[[Any], str]
- badge: Callable[[Any], str]
- snapshot_text: Callable[[Any], str]
- generate_label: str = "生成诊断报告"
- regenerate_label: str = "重新生成整个诊断报告"
- regenerate_title: str = "重新生成诊断报告"
- regenerate_body: str = (
- "重新生成会再次调用全部模型,并以新结果覆盖当前诊断报告。确定继续吗?"
- )
-
-
-PRESCRIPTION_AI_KIND = AiReportKind(
- title="AI 处方解释",
- snapshot_label="药材组合",
- medical_notice=MEDICAL_NOTICE,
- id_keys=("id", "template_id"),
- id_kwarg="template_id",
- list_method="list_prescription_template_ai_reports",
- generate_method="generate_prescription_template_ai_reports",
- edit_method="edit_prescription_template_ai_report",
- view_permissions=("tcm.prescriptionLibrary/aiReports", "wcf.prescription/read"),
- edit_permissions=AI_REPORT_EDIT_PERMISSIONS,
- missing_id_error="处方标识缺失,请关闭窗口后重试",
- subtitle=_prescription_subtitle,
- badge=_prescription_badge,
- snapshot_text=herb_summary,
-)
-DIAGNOSIS_AI_KIND = AiReportKind(
- title="AI 报告",
- snapshot_label="完整病历",
- medical_notice=DIAGNOSIS_MEDICAL_NOTICE,
- id_keys=("id", "diagnosis_id"),
- id_kwarg="diagnosis_id",
- list_method="list_diagnosis_ai_reports",
- generate_method="generate_diagnosis_ai_reports",
- edit_method="edit_diagnosis_ai_report",
- view_permissions=(
- "tcm.diagnosis/aiReports",
- "doctor.appointment/reception",
- "tcm.diagnosis/readonlyDetail",
- ),
- edit_permissions=("tcm.diagnosis/editAiReport", "tcm.diagnosis/edit"),
- missing_id_error="诊单标识缺失,请关闭窗口后重试",
- subtitle=_diagnosis_subtitle,
- badge=_diagnosis_badge,
- snapshot_text=diagnosis_case_summary,
-)
-
-
-def error_message(error: Any) -> str:
- if isinstance(error, str) and error.strip():
- return error.strip()
- if isinstance(error, dict):
- message = error.get("msg") or error.get("message") or error.get("error")
- if isinstance(message, str) and message.strip():
- return message.strip()
- text = friendly_error(error) if error else ""
- return text or "模型服务暂时不可用,请稍后重试"
-
-
-def structured_report_to_text(report: dict[str, Any] | None) -> str:
- if not report:
- return ""
-
- def list_block(items: Any) -> str:
- values = [str(item).strip() for item in (items or []) if str(item).strip()]
- return "\n".join(f"- {item}" for item in values) if values else "暂无"
-
- return "\n\n".join(
- [
- f"核心判断\n{report.get('summary') or '暂无'}",
- f"可能症状与证候\n{list_block(report.get('possible_symptoms'))}",
- f"主治方向\n{report.get('main_indications') or '暂无'}",
- f"主要功效\n{list_block(report.get('efficacy'))}",
- f"可能适用人群\n{list_block(report.get('suitable_people'))}",
- f"配伍分析\n{report.get('compatibility_analysis') or '暂无'}",
- f"用药与复核提醒\n{list_block(report.get('cautions'))}",
- f"免责声明\n{report.get('disclaimer') or '仅供专业人员辅助审方,不替代辨证、诊断和处方审核。'}",
- ]
- )
-
-
-def structured_text_to_report(content: str) -> dict[str, Any]:
- lines = content.replace("\ufeff", "").replace("\r\n", "\n").replace("\r", "\n").split("\n")
- heading_indexes: list[int] = []
- for heading in STRUCTURED_REPORT_SECTIONS:
- matches = [index for index, line in enumerate(lines) if line.strip() == heading]
- if not matches:
- return {
- "ok": False,
- "error": f"缺少章节标题“{heading}”。请保留全部八个中文章节标题后再保存。",
- }
- if len(matches) > 1:
- return {
- "ok": False,
- "error": f"章节标题“{heading}”出现了多次,请仅保留一个标题。",
- }
- heading_indexes.append(matches[0])
- for index in range(1, len(heading_indexes)):
- if heading_indexes[index] <= heading_indexes[index - 1]:
- return {
- "ok": False,
- "error": f"章节顺序不正确,请依次保留:{'、'.join(STRUCTURED_REPORT_SECTIONS)}。",
- }
-
- def section(index: int) -> str:
- start = heading_indexes[index] + 1
- end = heading_indexes[index + 1] if index + 1 < len(heading_indexes) else len(lines)
- return "\n".join(lines[start:end]).strip()
-
- values = [section(index) for index in range(len(STRUCTURED_REPORT_SECTIONS))]
- empty = next((index for index, value in enumerate(values) if not value), -1)
- if empty >= 0:
- return {
- "ok": False,
- "error": f"章节“{STRUCTURED_REPORT_SECTIONS[empty]}”内容不能为空;如无内容请填写“暂无”。",
- }
-
- def text_value(value: str) -> str:
- return "" if value == "暂无" else value
-
- def list_value(value: str) -> list[str]:
- if value == "暂无":
- return []
- items = []
- for line in value.split("\n"):
- cleaned = line.strip()
- if not cleaned:
- continue
- for prefix in ("- ", "* ", "• "):
- if cleaned.startswith(prefix):
- cleaned = cleaned[len(prefix) :].strip()
- break
- else:
- if len(cleaned) > 2 and cleaned[0].isdigit() and cleaned[1] in ".)、":
- cleaned = cleaned[2:].strip()
- if cleaned:
- items.append(cleaned)
- return items
-
- return {
- "ok": True,
- "report": {
- "summary": text_value(values[0]),
- "possible_symptoms": list_value(values[1]),
- "main_indications": text_value(values[2]),
- "efficacy": list_value(values[3]),
- "suitable_people": list_value(values[4]),
- "compatibility_analysis": text_value(values[5]),
- "cautions": list_value(values[6]),
- "disclaimer": text_value(values[7]),
- },
- }
-
-
+ error: str = ""
+ data: dict[str, Any] | None = None
+ editing: bool = False
+ structured_edit: bool = False
+ saving: bool = False
+ draft: str = ""
+ original_content: str = ""
+ edit_error: str = ""
+
+
+@dataclass
+class DialogState:
+ states: dict[str, ReportState] = field(
+ default_factory=lambda: {key: ReportState() for key, _label, _name in AI_MODELS}
+ )
+
+
+def formula_label(value: Any) -> str:
+ text = str(value or "").strip().lower()
+ if text in {"2", "aux", "auxiliary", "secondary", "辅方"}:
+ return "辅方"
+ if text in {"1", "main", "primary", "主方"}:
+ return "主方"
+ return str(value or "").strip()
+
+
+def herb_summary(row: Any) -> str:
+ herbs = get_value(row, "herbs", None) or []
+ if not isinstance(herbs, (list, tuple)) or not herbs:
+ return "暂无药材"
+ pieces = []
+ for herb in herbs:
+ name = str(first_value(herb, "name", "medicine_name", default="未命名药材") or "").strip()
+ dosage = str(first_value(herb, "dosage", "amount", default="") or "").strip()
+ if dosage and not dosage.lower().endswith("g"):
+ dosage = f"{dosage}g"
+ pieces.append(f"{name} {dosage}".strip())
+ return "、".join(pieces)
+
+
+_CASE_FIELDS: tuple[tuple[str, tuple[str, ...]], ...] = (
+ ("诊断日期", ("diagnosis_date",)),
+ ("诊断类型", ("diagnosis_type_text", "diagnosis_type_desc", "consultation_type", "diagnosis_type")),
+ ("婚姻状态", ("marital_status_text", "marital_status_desc", "marital_status")),
+ ("主诉", ("chief_complaint", "complaint")),
+ ("主要症状", ("symptoms", "main_symptoms")),
+ ("现病史", ("present_illness", "present_illness_history")),
+ ("发现糖尿病病史", ("diabetes_discovery_year_text", "diabetes_discovery_year")),
+ ("当地就诊医院", ("local_hospital_name", "local_hospital")),
+ ("当地医院诊断结果", ("local_hospital_diagnosis", "local_diagnosis")),
+ ("口腔感觉", ("appetite_text", "appetite_desc", "appetite")),
+ ("每日饮水量", ("water_intake_text", "water_intake_desc", "water_intake")),
+ ("近月体重变化", ("weight_change_text", "weight_change_desc", "weight_change")),
+ ("脂肪肝程度", ("fatty_liver_degree_text", "fatty_liver_degree_desc", "fatty_liver_degree")),
+ ("饮食情况", ("diet_condition_text", "diet_condition_desc", "diet_condition")),
+ ("肢体感觉", ("body_feeling_text", "body_feeling_desc", "body_feeling")),
+ ("睡眠情况", ("sleep_condition_text", "sleep_condition_desc", "sleep_condition")),
+ ("眼睛情况", ("eye_condition_text", "eye_condition_desc", "eye_condition")),
+ ("头部感觉", ("head_feeling_text", "head_feeling_desc", "head_feeling")),
+ ("出汗情况", ("sweat_condition_text", "sweat_condition_desc", "sweat_condition")),
+ ("皮肤情况", ("skin_condition_text", "skin_condition_desc", "skin_condition")),
+ ("小便情况", ("urine_condition_text", "urine_condition_desc", "urine_condition")),
+ ("大便情况", ("stool_condition_text", "stool_condition_desc", "stool_condition")),
+ ("腰肾情况", ("kidney_condition_text", "kidney_condition_desc", "kidney_condition")),
+ ("既往史", ("past_history_text", "past_history_desc", "past_history")),
+ ("外伤史", ("trauma_history_text", "trauma_history_desc", "trauma_history")),
+ ("手术史", ("surgery_history_text", "surgery_history_desc", "surgery_history")),
+ ("过敏史", ("allergy_history_text", "allergy_history_desc", "allergy_history")),
+ ("个人史", ("personal_history_text", "personal_history_desc", "personal_history")),
+ ("家族史", ("family_history_text", "family_history_desc", "family_history")),
+ ("妊娠哺乳史", ("pregnancy_history_text", "pregnancy_history_desc", "pregnancy_history")),
+ ("糖尿病史", ("diabetes_history_text", "diabetes_history", "diabetes_desc")),
+ ("当前用药", ("current_medications", "current_medicine", "current_medication")),
+ ("临床诊断", ("clinical_diagnosis", "diagnosis")),
+ ("舌象", ("tongue", "tongue_coating")),
+ ("脉象", ("pulse", "pulse_condition")),
+ ("治则", ("treatment_principle",)),
+ ("处方意见", ("prescription_opinion", "prescription_advice")),
+ ("其他病史", ("other_history", "medical_history_other")),
+ ("病例备注", ("remark",)),
+)
+
+
+def diagnosis_case_summary(row: Any, extra: Any = None) -> str:
+ """Build a compact clinical snapshot, omitting identity documents and phones."""
+
+ sources = [item for item in (row, extra) if item not in (None, "")]
+ explicit = str(first_value(row, "case_summary", default="") or "").strip()
+ if explicit not in CASE_PLACEHOLDERS:
+ return explicit
+
+ def pick(*keys: str) -> Any:
+ for source in sources:
+ value = first_value(source, *keys, default=None)
+ if value not in (None, "", [], {}):
+ return value
+ return None
+
+ lines: list[str] = []
+ systolic = pick("systolic", "systolic_pressure", "high_pressure")
+ diastolic = pick("diastolic", "diastolic_pressure", "low_pressure")
+ if systolic not in (None, "") or diastolic not in (None, ""):
+ lines.append(f"血压:{display_text(systolic)}/{display_text(diastolic)} mmHg")
+ else:
+ pressure = pick("blood_pressure")
+ if pressure not in (None, ""):
+ lines.append(f"血压:{display_text(pressure)}")
+ blood_sugar = pick(
+ "fasting_blood_sugar", "fasting_glucose", "fasting_blood_glucose", "blood_sugar"
+ )
+ if blood_sugar not in (None, ""):
+ lines.append(f"空腹血糖:{display_text(blood_sugar)} mmol/L")
+ height = pick("height")
+ weight = pick("weight")
+ if height not in (None, ""):
+ lines.append(f"身高:{display_text(height)} cm")
+ if weight not in (None, ""):
+ lines.append(f"体重:{display_text(weight)} kg")
+ for caption, keys in _CASE_FIELDS:
+ value = pick(*keys)
+ if value in (None, "", [], {}):
+ continue
+ if isinstance(value, (list, tuple, set)):
+ value = "、".join(str(item) for item in value if str(item).strip())
+ if value not in (None, ""):
+ lines.append(f"{caption}:{value}")
+ return "\n".join(lines) if lines else "尚未填写病例信息。"
+
+
+def _prescription_subtitle(row: Any) -> str:
+ return display_text(first_value(row, "prescription_name", "name", default="未选择处方"))
+
+
+def _prescription_badge(row: Any) -> str:
+ return formula_label(first_value(row, "formula_type", default=""))
+
+
+def _diagnosis_subtitle(row: Any) -> str:
+ return display_text(first_value(row, "patient_name", "name", default="未选择患者"))
+
+
+def _diagnosis_badge(row: Any) -> str:
+ return display_text(
+ first_value(
+ row,
+ "consultation_type",
+ "diagnosis_type_text",
+ "diagnosis_type_desc",
+ "diagnosis_type",
+ default="",
+ )
+ )
+
+
+@dataclass(frozen=True)
+class AiReportKind:
+ title: str
+ snapshot_label: str
+ medical_notice: str
+ id_keys: tuple[str, ...]
+ id_kwarg: str
+ list_method: str
+ generate_method: str
+ edit_method: str
+ view_permissions: tuple[str, ...]
+ edit_permissions: tuple[str, ...]
+ missing_id_error: str
+ subtitle: Callable[[Any], str]
+ badge: Callable[[Any], str]
+ snapshot_text: Callable[[Any], str]
+ generate_label: str = "生成诊断报告"
+ regenerate_label: str = "重新生成整个诊断报告"
+ regenerate_title: str = "重新生成诊断报告"
+ regenerate_body: str = (
+ "重新生成会再次调用全部模型,并以新结果覆盖当前诊断报告。确定继续吗?"
+ )
+
+
+PRESCRIPTION_AI_KIND = AiReportKind(
+ title="AI 处方解释",
+ snapshot_label="药材组合",
+ medical_notice=MEDICAL_NOTICE,
+ id_keys=("id", "template_id"),
+ id_kwarg="template_id",
+ list_method="list_prescription_template_ai_reports",
+ generate_method="generate_prescription_template_ai_reports",
+ edit_method="edit_prescription_template_ai_report",
+ view_permissions=("tcm.prescriptionLibrary/aiReports", "wcf.prescription/read"),
+ edit_permissions=AI_REPORT_EDIT_PERMISSIONS,
+ missing_id_error="处方标识缺失,请关闭窗口后重试",
+ subtitle=_prescription_subtitle,
+ badge=_prescription_badge,
+ snapshot_text=herb_summary,
+)
+DIAGNOSIS_AI_KIND = AiReportKind(
+ title="AI 报告",
+ snapshot_label="完整病历",
+ medical_notice=DIAGNOSIS_MEDICAL_NOTICE,
+ id_keys=("id", "diagnosis_id"),
+ id_kwarg="diagnosis_id",
+ list_method="list_diagnosis_ai_reports",
+ generate_method="generate_diagnosis_ai_reports",
+ edit_method="edit_diagnosis_ai_report",
+ view_permissions=(
+ "tcm.diagnosis/aiReports",
+ "doctor.appointment/reception",
+ "tcm.diagnosis/readonlyDetail",
+ ),
+ edit_permissions=("tcm.diagnosis/editAiReport", "tcm.diagnosis/edit"),
+ missing_id_error="诊单标识缺失,请关闭窗口后重试",
+ subtitle=_diagnosis_subtitle,
+ badge=_diagnosis_badge,
+ snapshot_text=diagnosis_case_summary,
+)
+
+
+def error_message(error: Any) -> str:
+ if isinstance(error, str) and error.strip():
+ return error.strip()
+ if isinstance(error, dict):
+ message = error.get("msg") or error.get("message") or error.get("error")
+ if isinstance(message, str) and message.strip():
+ return message.strip()
+ text = friendly_error(error) if error else ""
+ return text or "模型服务暂时不可用,请稍后重试"
+
+
+def structured_report_to_text(report: dict[str, Any] | None) -> str:
+ if not report:
+ return ""
+
+ def list_block(items: Any) -> str:
+ values = [str(item).strip() for item in (items or []) if str(item).strip()]
+ return "\n".join(f"- {item}" for item in values) if values else "暂无"
+
+ return "\n\n".join(
+ [
+ f"核心判断\n{report.get('summary') or '暂无'}",
+ f"可能症状与证候\n{list_block(report.get('possible_symptoms'))}",
+ f"主治方向\n{report.get('main_indications') or '暂无'}",
+ f"主要功效\n{list_block(report.get('efficacy'))}",
+ f"可能适用人群\n{list_block(report.get('suitable_people'))}",
+ f"配伍分析\n{report.get('compatibility_analysis') or '暂无'}",
+ f"用药与复核提醒\n{list_block(report.get('cautions'))}",
+ f"免责声明\n{report.get('disclaimer') or '仅供专业人员辅助审方,不替代辨证、诊断和处方审核。'}",
+ ]
+ )
+
+
+def structured_text_to_report(content: str) -> dict[str, Any]:
+ lines = content.replace("\ufeff", "").replace("\r\n", "\n").replace("\r", "\n").split("\n")
+ heading_indexes: list[int] = []
+ for heading in STRUCTURED_REPORT_SECTIONS:
+ matches = [index for index, line in enumerate(lines) if line.strip() == heading]
+ if not matches:
+ return {
+ "ok": False,
+ "error": f"缺少章节标题“{heading}”。请保留全部八个中文章节标题后再保存。",
+ }
+ if len(matches) > 1:
+ return {
+ "ok": False,
+ "error": f"章节标题“{heading}”出现了多次,请仅保留一个标题。",
+ }
+ heading_indexes.append(matches[0])
+ for index in range(1, len(heading_indexes)):
+ if heading_indexes[index] <= heading_indexes[index - 1]:
+ return {
+ "ok": False,
+ "error": f"章节顺序不正确,请依次保留:{'、'.join(STRUCTURED_REPORT_SECTIONS)}。",
+ }
+
+ def section(index: int) -> str:
+ start = heading_indexes[index] + 1
+ end = heading_indexes[index + 1] if index + 1 < len(heading_indexes) else len(lines)
+ return "\n".join(lines[start:end]).strip()
+
+ values = [section(index) for index in range(len(STRUCTURED_REPORT_SECTIONS))]
+ empty = next((index for index, value in enumerate(values) if not value), -1)
+ if empty >= 0:
+ return {
+ "ok": False,
+ "error": f"章节“{STRUCTURED_REPORT_SECTIONS[empty]}”内容不能为空;如无内容请填写“暂无”。",
+ }
+
+ def text_value(value: str) -> str:
+ return "" if value == "暂无" else value
+
+ def list_value(value: str) -> list[str]:
+ if value == "暂无":
+ return []
+ items = []
+ for line in value.split("\n"):
+ cleaned = line.strip()
+ if not cleaned:
+ continue
+ for prefix in ("- ", "* ", "• "):
+ if cleaned.startswith(prefix):
+ cleaned = cleaned[len(prefix) :].strip()
+ break
+ else:
+ if len(cleaned) > 2 and cleaned[0].isdigit() and cleaned[1] in ".)、":
+ cleaned = cleaned[2:].strip()
+ if cleaned:
+ items.append(cleaned)
+ return items
+
+ return {
+ "ok": True,
+ "report": {
+ "summary": text_value(values[0]),
+ "possible_symptoms": list_value(values[1]),
+ "main_indications": text_value(values[2]),
+ "efficacy": list_value(values[3]),
+ "suitable_people": list_value(values[4]),
+ "compatibility_analysis": text_value(values[5]),
+ "cautions": list_value(values[6]),
+ "disclaimer": text_value(values[7]),
+ },
+ }
+
+
class PrescriptionAiReportDialog(QDialog):
- """Read, generate and edit dual-model AI interpretation reports."""
-
- def __init__(
- self,
- repository: Any,
- permissions: Any = None,
- parent: QWidget | None = None,
- *,
- kind: AiReportKind | None = None,
- ) -> None:
- super().__init__(parent)
- self.repository = repository
- self.permissions = permissions
- self.kind = kind or PRESCRIPTION_AI_KIND
- self.prescription: Any = None
- self.active_profile = "qwen"
- self.dialog_generation = 0
- self.load_generation = 0
- self.load_loading = False
- self.generation_loading = False
- self.load_error = ""
- self.generation_error = ""
- self.can_refresh = False
- self.can_edit = False
- self.bundle = DialogState()
- self.setObjectName("PrescriptionAiDialog")
- self.setWindowTitle(self.kind.title)
- self.resize(920, 760)
- self.setMinimumSize(720, 560)
- self.setStyleSheet(PRESCRIPTION_AI_QSS)
- self.setCursor(Qt.CursorShape.ArrowCursor)
-
- root = QVBoxLayout(self)
- root.setContentsMargins(22, 18, 22, 18)
- root.setSpacing(12)
-
- heading = QHBoxLayout()
- titles = QVBoxLayout()
- titles.setSpacing(3)
- self.title_label = QLabel(self.kind.title)
- self.title_label.setObjectName("PrescriptionAiTitle")
- self.subtitle_label = QLabel("未选择")
- self.subtitle_label.setObjectName("PrescriptionAiSubtitle")
- titles.addWidget(self.title_label)
- titles.addWidget(self.subtitle_label)
- heading.addLayout(titles, 1)
- self.formula_badge = StatusBadge("", "info")
- self.formula_badge.hide()
- heading.addWidget(self.formula_badge, 0, Qt.AlignmentFlag.AlignTop)
- root.addLayout(heading)
-
- snapshot = QFrame()
- snapshot.setObjectName("PrescriptionAiSnapshot")
- snapshot_layout = QHBoxLayout(snapshot)
- snapshot_layout.setContentsMargins(14, 12, 14, 12)
- snapshot_layout.setSpacing(12)
- self.snapshot_caption = QLabel(self.kind.snapshot_label)
- self.snapshot_caption.setObjectName("PrescriptionAiSnapshotLabel")
- self.snapshot_caption.setFixedWidth(72)
- self.snapshot_body = QLabel("暂无内容")
- self.snapshot_body.setObjectName("PrescriptionAiSnapshotBody")
- self.snapshot_body.setWordWrap(True)
- snapshot_layout.addWidget(self.snapshot_caption, 0, Qt.AlignmentFlag.AlignTop)
- snapshot_layout.addWidget(self.snapshot_body, 1)
- root.addWidget(snapshot)
-
+ """Read, generate and edit dual-model AI interpretation reports."""
+
+ def __init__(
+ self,
+ repository: Any,
+ permissions: Any = None,
+ parent: QWidget | None = None,
+ *,
+ kind: AiReportKind | None = None,
+ ) -> None:
+ super().__init__(parent)
+ self.repository = repository
+ self.permissions = permissions
+ self.kind = kind or PRESCRIPTION_AI_KIND
+ self.prescription: Any = None
+ self.active_profile = "qwen"
+ self.dialog_generation = 0
+ self.load_generation = 0
+ self.load_loading = False
+ self.generation_loading = False
+ self.load_error = ""
+ self.generation_error = ""
+ self.can_refresh = False
+ self.can_edit = False
+ self.bundle = DialogState()
+ self.setObjectName("PrescriptionAiDialog")
+ self.setWindowTitle(self.kind.title)
+ self.resize(920, 760)
+ self.setMinimumSize(720, 560)
+ self.setStyleSheet(PRESCRIPTION_AI_QSS)
+ self.setCursor(Qt.CursorShape.ArrowCursor)
+
+ root = QVBoxLayout(self)
+ root.setContentsMargins(22, 18, 22, 18)
+ root.setSpacing(12)
+
+ heading = QHBoxLayout()
+ titles = QVBoxLayout()
+ titles.setSpacing(3)
+ self.title_label = QLabel(self.kind.title)
+ self.title_label.setObjectName("PrescriptionAiTitle")
+ self.subtitle_label = QLabel("未选择")
+ self.subtitle_label.setObjectName("PrescriptionAiSubtitle")
+ titles.addWidget(self.title_label)
+ titles.addWidget(self.subtitle_label)
+ heading.addLayout(titles, 1)
+ self.formula_badge = StatusBadge("", "info")
+ self.formula_badge.hide()
+ heading.addWidget(self.formula_badge, 0, Qt.AlignmentFlag.AlignTop)
+ root.addLayout(heading)
+
+ snapshot = QFrame()
+ snapshot.setObjectName("PrescriptionAiSnapshot")
+ snapshot_layout = QHBoxLayout(snapshot)
+ snapshot_layout.setContentsMargins(14, 12, 14, 12)
+ snapshot_layout.setSpacing(12)
+ self.snapshot_caption = QLabel(self.kind.snapshot_label)
+ self.snapshot_caption.setObjectName("PrescriptionAiSnapshotLabel")
+ self.snapshot_caption.setFixedWidth(72)
+ self.snapshot_body = QLabel("暂无内容")
+ self.snapshot_body.setObjectName("PrescriptionAiSnapshotBody")
+ self.snapshot_body.setWordWrap(True)
+ snapshot_layout.addWidget(self.snapshot_caption, 0, Qt.AlignmentFlag.AlignTop)
+ snapshot_layout.addWidget(self.snapshot_body, 1)
+ root.addWidget(snapshot)
+
self.notice = MessageBanner()
self.notice.show_message(self.kind.medical_notice, "warning")
- root.addWidget(self.notice)
- self.operation_error = MessageBanner()
- self.operation_error.hide()
- root.addWidget(self.operation_error)
-
- self.tabs = QTabWidget()
- self.tabs.setDocumentMode(True)
- for profile, label, name in AI_MODELS:
- pane = QWidget()
- pane.setObjectName(f"PrescriptionAiPane_{profile}")
- pane_layout = QVBoxLayout(pane)
- pane_layout.setContentsMargins(0, 0, 0, 0)
- self.tabs.addTab(pane, f"{label} {name}")
- root.addWidget(self.tabs, 1)
-
- self.report_scroll = QScrollArea()
- self.report_scroll.setWidgetResizable(True)
- self.report_scroll.setFrameShape(QFrame.Shape.NoFrame)
- self.report_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
- self.host = QWidget()
- self.host_layout = QVBoxLayout(self.host)
- self.host_layout.setContentsMargins(4, 4, 12, 8)
- self.host_layout.setSpacing(12)
- self.report_scroll.setWidget(self.host)
- self.tabs.widget(0).layout().addWidget(self.report_scroll)
- self.tabs.currentChanged.connect(self._tab_changed)
-
- footer = QHBoxLayout()
- footer.addStretch(1)
- self.close_button = QPushButton("关闭")
- self.close_button.setCursor(Qt.CursorShape.PointingHandCursor)
- self.close_button.clicked.connect(self.reject)
- footer.addWidget(self.close_button)
- self.generate_button = QPushButton("生成诊断报告")
- self.generate_button.setProperty("variant", "primary")
- self.generate_button.setCursor(Qt.CursorShape.PointingHandCursor)
- self.generate_button.clicked.connect(self._request_generate)
- footer.addWidget(self.generate_button)
- root.addLayout(footer)
- self._render()
-
+ root.addWidget(self.notice)
+ self.operation_error = MessageBanner()
+ self.operation_error.hide()
+ root.addWidget(self.operation_error)
+
+ self.tabs = QTabWidget()
+ self.tabs.setDocumentMode(True)
+ for profile, label, name in AI_MODELS:
+ pane = QWidget()
+ pane.setObjectName(f"PrescriptionAiPane_{profile}")
+ pane_layout = QVBoxLayout(pane)
+ pane_layout.setContentsMargins(0, 0, 0, 0)
+ self.tabs.addTab(pane, f"{label} {name}")
+ root.addWidget(self.tabs, 1)
+
+ self.report_scroll = QScrollArea()
+ self.report_scroll.setWidgetResizable(True)
+ self.report_scroll.setFrameShape(QFrame.Shape.NoFrame)
+ self.report_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
+ self.host = QWidget()
+ self.host_layout = QVBoxLayout(self.host)
+ self.host_layout.setContentsMargins(4, 4, 12, 8)
+ self.host_layout.setSpacing(12)
+ self.report_scroll.setWidget(self.host)
+ self.tabs.widget(0).layout().addWidget(self.report_scroll)
+ self.tabs.currentChanged.connect(self._tab_changed)
+
+ footer = QHBoxLayout()
+ footer.addStretch(1)
+ self.close_button = QPushButton("关闭")
+ self.close_button.setCursor(Qt.CursorShape.PointingHandCursor)
+ self.close_button.clicked.connect(self.reject)
+ footer.addWidget(self.close_button)
+ self.generate_button = QPushButton("生成诊断报告")
+ self.generate_button.setProperty("variant", "primary")
+ self.generate_button.setCursor(Qt.CursorShape.PointingHandCursor)
+ self.generate_button.clicked.connect(self._request_generate)
+ footer.addWidget(self.generate_button)
+ root.addLayout(footer)
+ self._render()
+
def open_for(self, row: Any, *, preferred_model: str | None = None) -> None:
self.prescription = row
self.active_profile = (
@@ -737,49 +803,49 @@ class PrescriptionAiReportDialog(QDialog):
)
self.tabs.blockSignals(True)
self.tabs.setCurrentIndex(active_index)
- self.tabs.blockSignals(False)
- self._reset_states()
- self.load_error = ""
- self.generation_error = ""
- self.can_refresh = False
- self.can_edit = False
- self.load_loading = False
- self.generation_loading = False
- self.setWindowTitle(self.kind.title)
- self.title_label.setText(self.kind.title)
- self.subtitle_label.setText(self.kind.subtitle(row))
- badge = self.kind.badge(row)
- self.formula_badge.set_status(badge, "info" if badge != "辅方" else "warning")
- self.formula_badge.setVisible(bool(badge))
- self.snapshot_caption.setText(self.kind.snapshot_label)
- self.snapshot_body.setText(self.kind.snapshot_text(row))
+ self.tabs.blockSignals(False)
+ self._reset_states()
+ self.load_error = ""
+ self.generation_error = ""
+ self.can_refresh = False
+ self.can_edit = False
+ self.load_loading = False
+ self.generation_loading = False
+ self.setWindowTitle(self.kind.title)
+ self.title_label.setText(self.kind.title)
+ self.subtitle_label.setText(self.kind.subtitle(row))
+ badge = self.kind.badge(row)
+ self.formula_badge.set_status(badge, "info" if badge != "辅方" else "warning")
+ self.formula_badge.setVisible(bool(badge))
+ self.snapshot_caption.setText(self.kind.snapshot_label)
+ self.snapshot_body.setText(self.kind.snapshot_text(row))
question = str(first_value(row, "assistant_question", default="") or "").strip()
notice = self.kind.medical_notice
if question:
notice = f"{notice}\n当前分析方向:{question[:160]}"
self.notice.show_message(notice, "warning")
- self.dialog_generation += 1
- self._load_saved(self.dialog_generation)
- self._render()
-
- def _reset_states(self) -> None:
- self.bundle = DialogState()
-
- def _state(self, profile: str) -> ReportState:
- return self.bundle.states[profile]
-
- def _has_any_report(self) -> bool:
- return any(state.data or state.error for state in self.bundle.states.values())
-
- def _any_saving(self) -> bool:
- return any(state.saving for state in self.bundle.states.values())
-
- def _any_editing(self) -> bool:
- return any(state.editing for state in self.bundle.states.values())
-
- def _entity_id(self) -> int:
- return int(first_value(self.prescription, *self.kind.id_keys, default=0) or 0)
-
+ self.dialog_generation += 1
+ self._load_saved(self.dialog_generation)
+ self._render()
+
+ def _reset_states(self) -> None:
+ self.bundle = DialogState()
+
+ def _state(self, profile: str) -> ReportState:
+ return self.bundle.states[profile]
+
+ def _has_any_report(self) -> bool:
+ return any(state.data or state.error for state in self.bundle.states.values())
+
+ def _any_saving(self) -> bool:
+ return any(state.saving for state in self.bundle.states.values())
+
+ def _any_editing(self) -> bool:
+ return any(state.editing for state in self.bundle.states.values())
+
+ def _entity_id(self) -> int:
+ return int(first_value(self.prescription, *self.kind.id_keys, default=0) or 0)
+
def _has_edit_permission(self) -> bool:
return has_permission(self.permissions, self.kind.edit_permissions)
@@ -790,302 +856,302 @@ class PrescriptionAiReportDialog(QDialog):
else "tcm.diagnosis/generateAiReports"
)
return has_permission(self.permissions, permission)
-
- def _can_edit_report(self, profile: str) -> bool:
- return bool(self._state(profile).data) and self.can_edit and self._has_edit_permission()
-
- def _is_current(self, generation: int) -> bool:
- return generation == self.dialog_generation and self.prescription is not None
-
- def _tab_changed(self, index: int) -> None:
- if 0 <= index < len(AI_MODELS):
- self.active_profile = AI_MODELS[index][0]
- layout = self.tabs.widget(index).layout()
- if layout is None:
- host_layout = QVBoxLayout(self.tabs.widget(index))
- host_layout.setContentsMargins(0, 0, 0, 0)
- layout = host_layout
- if self.report_scroll.parentWidget() is not self.tabs.widget(index):
- layout.addWidget(self.report_scroll)
- self._render()
-
- def _load_saved(self, generation: int, *, silent: bool = False) -> None:
- entity_id = self._entity_id()
- if entity_id <= 0:
- return
- request_id = self.load_generation + 1
- self.load_generation = request_id
- if not silent:
- self.load_loading = True
- self.load_error = ""
- self._render()
-
- def operation() -> Any:
- return invoke(
- self.repository,
- self.kind.list_method,
- **{self.kind.id_kwarg: entity_id},
- )
-
- run_async(
- operation,
- on_success=lambda result: self._saved_loaded(result, generation, request_id, silent),
- on_error=lambda error: self._saved_failed(error, generation, request_id, silent),
- )
-
- def _saved_loaded(self, result: Any, generation: int, request_id: int, silent: bool) -> None:
- if not self._is_current(generation) or request_id != self.load_generation:
- return
- self._apply_reports(result if isinstance(result, dict) else {})
- self.load_error = ""
- if not silent:
- self.load_loading = False
- self._render()
-
- def _saved_failed(self, error: Exception, generation: int, request_id: int, silent: bool) -> None:
- if not self._is_current(generation) or request_id != self.load_generation:
- return
- message = error_message(error)
- if silent:
- self.generation_error = f"报告已保存,但刷新最新内容失败:{message}"
- else:
- self.load_error = message
- self.load_loading = False
- self._render()
-
- def _apply_reports(self, response: dict[str, Any]) -> None:
- self._reset_states()
- capabilities = response.get("capabilities") if isinstance(response.get("capabilities"), dict) else {}
+
+ def _can_edit_report(self, profile: str) -> bool:
+ return bool(self._state(profile).data) and self.can_edit and self._has_edit_permission()
+
+ def _is_current(self, generation: int) -> bool:
+ return generation == self.dialog_generation and self.prescription is not None
+
+ def _tab_changed(self, index: int) -> None:
+ if 0 <= index < len(AI_MODELS):
+ self.active_profile = AI_MODELS[index][0]
+ layout = self.tabs.widget(index).layout()
+ if layout is None:
+ host_layout = QVBoxLayout(self.tabs.widget(index))
+ host_layout.setContentsMargins(0, 0, 0, 0)
+ layout = host_layout
+ if self.report_scroll.parentWidget() is not self.tabs.widget(index):
+ layout.addWidget(self.report_scroll)
+ self._render()
+
+ def _load_saved(self, generation: int, *, silent: bool = False) -> None:
+ entity_id = self._entity_id()
+ if entity_id <= 0:
+ return
+ request_id = self.load_generation + 1
+ self.load_generation = request_id
+ if not silent:
+ self.load_loading = True
+ self.load_error = ""
+ self._render()
+
+ def operation() -> Any:
+ return invoke(
+ self.repository,
+ self.kind.list_method,
+ **{self.kind.id_kwarg: entity_id},
+ )
+
+ run_async(
+ operation,
+ on_success=lambda result: self._saved_loaded(result, generation, request_id, silent),
+ on_error=lambda error: self._saved_failed(error, generation, request_id, silent),
+ )
+
+ def _saved_loaded(self, result: Any, generation: int, request_id: int, silent: bool) -> None:
+ if not self._is_current(generation) or request_id != self.load_generation:
+ return
+ self._apply_reports(result if isinstance(result, dict) else {})
+ self.load_error = ""
+ if not silent:
+ self.load_loading = False
+ self._render()
+
+ def _saved_failed(self, error: Exception, generation: int, request_id: int, silent: bool) -> None:
+ if not self._is_current(generation) or request_id != self.load_generation:
+ return
+ message = error_message(error)
+ if silent:
+ self.generation_error = f"报告已保存,但刷新最新内容失败:{message}"
+ else:
+ self.load_error = message
+ self.load_loading = False
+ self._render()
+
+ def _apply_reports(self, response: dict[str, Any]) -> None:
+ self._reset_states()
+ capabilities = response.get("capabilities") if isinstance(response.get("capabilities"), dict) else {}
server_can_refresh = bool(
response.get("can_refresh") or capabilities.get("can_refresh")
)
server_can_edit = bool(response.get("can_edit") or capabilities.get("can_edit"))
self.can_refresh = server_can_refresh and self._has_generate_permission()
self.can_edit = server_can_edit and self._has_edit_permission()
- reports = response.get("reports") if isinstance(response.get("reports"), list) else []
- for report in reports:
- if not isinstance(report, dict):
- continue
- profile = str(report.get("model_key") or "")
- if profile in self.bundle.states:
- self.bundle.states[profile].data = report
- results = response.get("results") if isinstance(response.get("results"), list) else []
- for result in results:
- if not isinstance(result, dict) or result.get("status") != "error":
- continue
- profile = str(result.get("model_key") or "")
- state = self.bundle.states.get(profile)
- if state is None:
- continue
- state.error = str(result.get("error_message") or "该模型报告生成失败,请重新生成整个报告")
- current = self._state(self.active_profile)
- if not current.data and not current.error:
- for profile, _label, _name in AI_MODELS:
- candidate = self._state(profile)
- if candidate.data or candidate.error:
- self.active_profile = profile
- index = next(i for i, item in enumerate(AI_MODELS) if item[0] == profile)
- self.tabs.blockSignals(True)
- self.tabs.setCurrentIndex(index)
- self.tabs.blockSignals(False)
- break
-
- def _request_generate(self) -> None:
- if self._any_editing():
- show_toast(self, "请先保存或取消正在编辑的报告", "warning")
- return
- if self._has_any_report():
- answer = QMessageBox.warning(
- self,
- self.kind.regenerate_title,
- self.kind.regenerate_body,
- QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.Cancel,
- QMessageBox.StandardButton.Cancel,
- )
- if answer != QMessageBox.StandardButton.Yes:
- return
- self._generate()
-
+ reports = response.get("reports") if isinstance(response.get("reports"), list) else []
+ for report in reports:
+ if not isinstance(report, dict):
+ continue
+ profile = str(report.get("model_key") or "")
+ if profile in self.bundle.states:
+ self.bundle.states[profile].data = report
+ results = response.get("results") if isinstance(response.get("results"), list) else []
+ for result in results:
+ if not isinstance(result, dict) or result.get("status") != "error":
+ continue
+ profile = str(result.get("model_key") or "")
+ state = self.bundle.states.get(profile)
+ if state is None:
+ continue
+ state.error = str(result.get("error_message") or "该模型报告生成失败,请重新生成整个报告")
+ current = self._state(self.active_profile)
+ if not current.data and not current.error:
+ for profile, _label, _name in AI_MODELS:
+ candidate = self._state(profile)
+ if candidate.data or candidate.error:
+ self.active_profile = profile
+ index = next(i for i, item in enumerate(AI_MODELS) if item[0] == profile)
+ self.tabs.blockSignals(True)
+ self.tabs.setCurrentIndex(index)
+ self.tabs.blockSignals(False)
+ break
+
+ def _request_generate(self) -> None:
+ if self._any_editing():
+ show_toast(self, "请先保存或取消正在编辑的报告", "warning")
+ return
+ if self._has_any_report():
+ answer = QMessageBox.warning(
+ self,
+ self.kind.regenerate_title,
+ self.kind.regenerate_body,
+ QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.Cancel,
+ QMessageBox.StandardButton.Cancel,
+ )
+ if answer != QMessageBox.StandardButton.Yes:
+ return
+ self._generate()
+
def _generate(self) -> None:
entity_id = self._entity_id()
if entity_id <= 0 or self.generation_loading or not self.can_refresh:
return
- generation = self.dialog_generation
- self.generation_loading = True
- self.generation_error = ""
- self._render()
-
- def operation() -> Any:
- return invoke(
- self.repository,
- self.kind.generate_method,
- **{self.kind.id_kwarg: entity_id},
- )
-
- run_async(
- operation,
- on_success=lambda result: self._generate_done(result, generation),
- on_error=lambda error: self._generate_failed(error, generation),
- )
-
- def _generate_done(self, result: Any, generation: int) -> None:
- if not self._is_current(generation):
- return
- payload = result if isinstance(result, dict) else {}
- self._apply_reports(payload)
- status = str(payload.get("status") or "")
- if status == "partial":
- self.generation_error = (
- "部分模型重新生成失败;成功结果已保存,失败模型仍显示上一次保存版本。"
- )
- show_toast(self, "诊断报告部分生成成功", "warning")
- elif status == "error":
- self.generation_error = "全部模型重新生成失败,已保留原有报告。"
- show_toast(self, "诊断报告生成失败", "danger")
- else:
- show_toast(self, "诊断报告已生成并保存", "success")
- self.generation_loading = False
- self._render()
-
- def _generate_failed(self, error: Exception, generation: int) -> None:
- if not self._is_current(generation):
- return
- self.generation_error = error_message(error)
- self.generation_loading = False
- self._render()
-
- def _begin_edit(self) -> None:
- profile = self.active_profile
- state = self._state(profile)
- data = state.data
- if not data or not self._can_edit_report(profile):
- return
- structured = data.get("report") if isinstance(data.get("report"), dict) else None
- if structured is None and data.get("content"):
- parsed = structured_text_to_report(str(data.get("content") or ""))
- if parsed.get("ok"):
- structured = parsed["report"]
- state.structured_edit = bool(structured)
- content = structured_report_to_text(structured) if structured else str(data.get("content") or "")
- state.original_content = content
- state.draft = content
- state.edit_error = ""
- state.editing = True
- self._render()
-
- def _cancel_edit(self) -> None:
- state = self._state(self.active_profile)
- state.draft = state.original_content
- state.edit_error = ""
- state.editing = False
- state.structured_edit = False
- self._render()
-
- def _save_edit(self) -> None:
- profile = self.active_profile
- state = self._state(profile)
- data = state.data
- if not data or state.saving or not self._can_edit_report(profile):
- return
- if not state.draft.strip():
- state.edit_error = "报告内容不能为空"
- self._render()
- return
- structured_for_save: dict[str, Any] | None = None
- content_for_save = state.draft
- if state.structured_edit:
- parsed = structured_text_to_report(state.draft)
- if not parsed.get("ok"):
- state.edit_error = str(parsed.get("error") or "报告格式不正确")
- self._render()
- return
- structured_for_save = parsed["report"]
- content_for_save = json.dumps(structured_for_save, ensure_ascii=False)
- if len(content_for_save) > 12000:
- state.edit_error = "报告保存内容不能超过 12000 个字符,请精简后再保存"
- self._render()
- return
- report_id = int(data.get("report_id") or data.get("id") or 0)
- entity_id = self._entity_id()
- if report_id <= 0:
- state.edit_error = "报告标识缺失,请重新加载后再试"
- self._render()
- return
- if entity_id <= 0:
- state.edit_error = self.kind.missing_id_error
- self._render()
- return
- generation = self.dialog_generation
- state.saving = True
- state.edit_error = ""
- self._render()
-
- def operation() -> Any:
- return invoke(
- self.repository,
- self.kind.edit_method,
- **{
- self.kind.id_kwarg: entity_id,
- "report_id": report_id,
- "content": content_for_save,
- },
- )
-
- run_async(
- operation,
- on_success=lambda result: self._edit_saved(
- result, generation, profile, structured_for_save
- ),
- on_error=lambda error: self._edit_failed(error, generation, profile),
- )
-
- def _edit_saved(
- self,
- result: Any,
- generation: int,
- profile: str,
- structured: dict[str, Any] | None,
- ) -> None:
- if not self._is_current(generation):
- return
- payload = result if isinstance(result, dict) else {}
- updated = payload.get("report") if isinstance(payload.get("report"), dict) else None
- state = self._state(profile)
- if updated is None:
- state.edit_error = "保存成功但未返回报告内容,请重新加载"
- state.saving = False
- self._render()
- return
- if structured and not updated.get("report"):
- updated = dict(updated)
- updated["report"] = structured
- state.data = updated
- state.error = ""
- self.can_edit = bool(payload.get("can_edit", True))
- self.can_refresh = bool(payload.get("can_refresh", True))
- state.original_content = (
- structured_report_to_text(structured)
- if structured
- else str(updated.get("content") or state.draft)
- )
- state.draft = state.original_content
- state.editing = False
- state.structured_edit = False
- state.saving = False
- show_toast(self, "报告修改已保存", "success")
- self._load_saved(generation, silent=True)
- self._render()
-
- def _edit_failed(self, error: Exception, generation: int, profile: str) -> None:
- if not self._is_current(generation):
- return
- state = self._state(profile)
- state.edit_error = error_message(error)
- state.saving = False
- self._render()
-
- def _clear_host(self) -> None:
- while self.host_layout.count():
+ generation = self.dialog_generation
+ self.generation_loading = True
+ self.generation_error = ""
+ self._render()
+
+ def operation() -> Any:
+ return invoke(
+ self.repository,
+ self.kind.generate_method,
+ **{self.kind.id_kwarg: entity_id},
+ )
+
+ run_async(
+ operation,
+ on_success=lambda result: self._generate_done(result, generation),
+ on_error=lambda error: self._generate_failed(error, generation),
+ )
+
+ def _generate_done(self, result: Any, generation: int) -> None:
+ if not self._is_current(generation):
+ return
+ payload = result if isinstance(result, dict) else {}
+ self._apply_reports(payload)
+ status = str(payload.get("status") or "")
+ if status == "partial":
+ self.generation_error = (
+ "部分模型重新生成失败;成功结果已保存,失败模型仍显示上一次保存版本。"
+ )
+ show_toast(self, "诊断报告部分生成成功", "warning")
+ elif status == "error":
+ self.generation_error = "全部模型重新生成失败,已保留原有报告。"
+ show_toast(self, "诊断报告生成失败", "danger")
+ else:
+ show_toast(self, "诊断报告已生成并保存", "success")
+ self.generation_loading = False
+ self._render()
+
+ def _generate_failed(self, error: Exception, generation: int) -> None:
+ if not self._is_current(generation):
+ return
+ self.generation_error = error_message(error)
+ self.generation_loading = False
+ self._render()
+
+ def _begin_edit(self) -> None:
+ profile = self.active_profile
+ state = self._state(profile)
+ data = state.data
+ if not data or not self._can_edit_report(profile):
+ return
+ structured = data.get("report") if isinstance(data.get("report"), dict) else None
+ if structured is None and data.get("content"):
+ parsed = structured_text_to_report(str(data.get("content") or ""))
+ if parsed.get("ok"):
+ structured = parsed["report"]
+ state.structured_edit = bool(structured)
+ content = structured_report_to_text(structured) if structured else str(data.get("content") or "")
+ state.original_content = content
+ state.draft = content
+ state.edit_error = ""
+ state.editing = True
+ self._render()
+
+ def _cancel_edit(self) -> None:
+ state = self._state(self.active_profile)
+ state.draft = state.original_content
+ state.edit_error = ""
+ state.editing = False
+ state.structured_edit = False
+ self._render()
+
+ def _save_edit(self) -> None:
+ profile = self.active_profile
+ state = self._state(profile)
+ data = state.data
+ if not data or state.saving or not self._can_edit_report(profile):
+ return
+ if not state.draft.strip():
+ state.edit_error = "报告内容不能为空"
+ self._render()
+ return
+ structured_for_save: dict[str, Any] | None = None
+ content_for_save = state.draft
+ if state.structured_edit:
+ parsed = structured_text_to_report(state.draft)
+ if not parsed.get("ok"):
+ state.edit_error = str(parsed.get("error") or "报告格式不正确")
+ self._render()
+ return
+ structured_for_save = parsed["report"]
+ content_for_save = json.dumps(structured_for_save, ensure_ascii=False)
+ if len(content_for_save) > 12000:
+ state.edit_error = "报告保存内容不能超过 12000 个字符,请精简后再保存"
+ self._render()
+ return
+ report_id = int(data.get("report_id") or data.get("id") or 0)
+ entity_id = self._entity_id()
+ if report_id <= 0:
+ state.edit_error = "报告标识缺失,请重新加载后再试"
+ self._render()
+ return
+ if entity_id <= 0:
+ state.edit_error = self.kind.missing_id_error
+ self._render()
+ return
+ generation = self.dialog_generation
+ state.saving = True
+ state.edit_error = ""
+ self._render()
+
+ def operation() -> Any:
+ return invoke(
+ self.repository,
+ self.kind.edit_method,
+ **{
+ self.kind.id_kwarg: entity_id,
+ "report_id": report_id,
+ "content": content_for_save,
+ },
+ )
+
+ run_async(
+ operation,
+ on_success=lambda result: self._edit_saved(
+ result, generation, profile, structured_for_save
+ ),
+ on_error=lambda error: self._edit_failed(error, generation, profile),
+ )
+
+ def _edit_saved(
+ self,
+ result: Any,
+ generation: int,
+ profile: str,
+ structured: dict[str, Any] | None,
+ ) -> None:
+ if not self._is_current(generation):
+ return
+ payload = result if isinstance(result, dict) else {}
+ updated = payload.get("report") if isinstance(payload.get("report"), dict) else None
+ state = self._state(profile)
+ if updated is None:
+ state.edit_error = "保存成功但未返回报告内容,请重新加载"
+ state.saving = False
+ self._render()
+ return
+ if structured and not updated.get("report"):
+ updated = dict(updated)
+ updated["report"] = structured
+ state.data = updated
+ state.error = ""
+ self.can_edit = bool(payload.get("can_edit", True))
+ self.can_refresh = bool(payload.get("can_refresh", True))
+ state.original_content = (
+ structured_report_to_text(structured)
+ if structured
+ else str(updated.get("content") or state.draft)
+ )
+ state.draft = state.original_content
+ state.editing = False
+ state.structured_edit = False
+ state.saving = False
+ show_toast(self, "报告修改已保存", "success")
+ self._load_saved(generation, silent=True)
+ self._render()
+
+ def _edit_failed(self, error: Exception, generation: int, profile: str) -> None:
+ if not self._is_current(generation):
+ return
+ state = self._state(profile)
+ state.edit_error = error_message(error)
+ state.saving = False
+ self._render()
+
+ def _clear_host(self) -> None:
+ while self.host_layout.count():
item = self.host_layout.takeAt(0)
widget = item.widget()
if widget is not None:
@@ -1095,264 +1161,264 @@ class PrescriptionAiReportDialog(QDialog):
widget.hide()
widget.deleteLater()
QCoreApplication.sendPostedEvents(widget, QEvent.Type.DeferredDelete)
-
- def _add_label(
- self,
- text: str,
- object_name: str,
- *,
- rich: bool = False,
- ) -> QLabel:
- label = QLabel(text)
- label.setObjectName(object_name)
- label.setWordWrap(True)
- label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
- if rich:
- label.setTextFormat(Qt.TextFormat.RichText)
- self.host_layout.addWidget(label)
- return label
-
- def _list_html(self, items: Any, empty: str) -> str:
+
+ def _add_label(
+ self,
+ text: str,
+ object_name: str,
+ *,
+ rich: bool = False,
+ ) -> QLabel:
+ label = QLabel(text)
+ label.setObjectName(object_name)
+ label.setWordWrap(True)
+ label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
+ if rich:
+ label.setTextFormat(Qt.TextFormat.RichText)
+ self.host_layout.addWidget(label)
+ return label
+
+ def _list_html(self, items: Any, empty: str) -> str:
values = [str(item).strip() for item in (items or []) if str(item).strip()]
if not values:
return f'{html.escape(empty)}'
- bullets = "".join(f"
{html.escape(item)}" for item in values)
- return f''
-
- def _section(self, title: str, body: str, *, rich: bool = False, caution: bool = False) -> None:
- frame = QFrame()
- frame.setObjectName("PrescriptionAiCaution" if caution else "PrescriptionAiSection")
- layout = QVBoxLayout(frame)
- layout.setContentsMargins(16 if caution else 0, 12, 16 if caution else 0, 12)
- layout.setSpacing(8)
- heading = QLabel(title)
- heading.setObjectName("PrescriptionAiSectionTitle")
- body_label = QLabel(body)
- body_label.setObjectName("PrescriptionAiBody")
- body_label.setWordWrap(True)
- if rich:
- body_label.setTextFormat(Qt.TextFormat.RichText)
- layout.addWidget(heading)
- layout.addWidget(body_label)
- self.host_layout.addWidget(frame)
-
- def _render(self) -> None:
- generating = self.generation_loading
- has_report = self._has_any_report()
- self.generate_button.setVisible(self.can_refresh)
- self.generate_button.setEnabled(
- bool(self.prescription)
- and self.can_refresh
- and not self.load_loading
- and not generating
- and not self._any_saving()
- and not self._any_editing()
- )
- self.generate_button.setText(
- "正在生成…"
- if generating
- else (self.kind.regenerate_label if has_report else self.kind.generate_label)
- )
- if self.generation_error:
- self.operation_error.show_message(self.generation_error, "danger")
- else:
- self.operation_error.hide()
- for index, (profile, label, name) in enumerate(AI_MODELS):
- state = self._state(profile)
- status = "更新中" if generating else (
- "更新失败" if state.error and not state.data else (
- "已保存" if state.data else "未生成"
- )
- )
- model_label = (state.data or {}).get("model_label") or label
- model_name = (state.data or {}).get("model_name") or name
- self.tabs.setTabText(index, f"{model_label} {model_name} {status}")
- self._clear_host()
- if self.load_loading:
- self._add_label("正在加载已保存的 AI 诊断报告…", "PrescriptionAiMuted")
- self.host_layout.addStretch(1)
- return
- if self.load_error:
- empty = EmptyState("已保存报告加载失败", self.load_error, "重新加载")
- empty.action_requested.connect(lambda: self._load_saved(self.dialog_generation))
- self.host_layout.addWidget(empty, 1)
- return
- if not has_report:
- empty = EmptyState(
- "暂无已保存的 AI 诊断报告",
- "打开窗口不会自动调用模型;需要时请手动生成。",
- "生成报告" if self.can_refresh else "",
- )
- if self.can_refresh:
- empty.action_requested.connect(self._request_generate)
- else:
- empty.action_button.hide()
- hint = QLabel("当前账号无生成权限")
- hint.setObjectName("PrescriptionAiMuted")
- self.host_layout.addWidget(empty, 1)
- self.host_layout.addWidget(hint, 0, Qt.AlignmentFlag.AlignHCenter)
- return
- self.host_layout.addWidget(empty, 1)
- return
- self._render_profile(self.active_profile)
- self.host_layout.addStretch(1)
-
- def _render_profile(self, profile: str) -> None:
- state = self._state(profile)
- if state.error and not state.data:
- empty = EmptyState("这份模型报告生成失败", state.error, "重新生成整个报告")
- if self.can_refresh:
- empty.action_requested.connect(self._request_generate)
- else:
- empty.action_button.hide()
- self.host_layout.addWidget(empty, 1)
- return
- data = state.data
- if data is None:
- empty = EmptyState("该模型暂无已保存报告", "可重新生成整个诊断报告。", "重新生成整个报告")
- if self.can_refresh:
- empty.action_requested.connect(self._request_generate)
- else:
- empty.action_button.hide()
- self.host_layout.addWidget(empty, 1)
- return
-
- meta = QFrame()
- meta.setObjectName("PrescriptionAiMeta")
- meta_layout = QHBoxLayout(meta)
- meta_layout.setContentsMargins(0, 4, 0, 12)
- meta_main = QVBoxLayout()
- meta_main.setSpacing(4)
- title_row = QHBoxLayout()
- title = QLabel(f"{data.get('model_label') or '模型'}建议报告")
- title.setObjectName("PrescriptionAiSectionTitle")
- title_row.addWidget(title)
- title_row.addWidget(QLabel(str(data.get("model_name") or "")))
- if data.get("is_stale"):
- badge = StatusBadge("处方已变更", "warning")
- title_row.addWidget(badge)
- if data.get("is_edited"):
- badge = StatusBadge("已人工编辑", "info")
- title_row.addWidget(badge)
- title_row.addStretch(1)
- meta_main.addLayout(title_row)
- times = QLabel(
- f"生成时间:{data.get('generated_at') or '—'}"
- + (f" 编辑时间:{data.get('edited_at')}" if data.get("edited_at") else "")
- )
- times.setObjectName("PrescriptionAiMuted")
- meta_main.addWidget(times)
- meta_layout.addLayout(meta_main, 1)
- if self._can_edit_report(profile) and not state.editing:
- edit_button = QPushButton("编辑报告")
- edit_button.setProperty("variant", "link")
- edit_button.setCursor(Qt.CursorShape.PointingHandCursor)
- edit_button.setEnabled(not self.generation_loading and not self._any_saving())
- edit_button.clicked.connect(self._begin_edit)
- meta_layout.addWidget(edit_button, 0, Qt.AlignmentFlag.AlignTop)
- self.host_layout.addWidget(meta)
-
- if state.error:
- warning = MessageBanner()
- warning.show_message(
- f"本次重新生成失败,当前展示上一次保存的版本:{state.error}",
- "warning",
- )
- self.host_layout.addWidget(warning)
-
- if state.editing:
- if state.structured_edit:
- notice = MessageBanner()
- notice.show_message(
- "结构化报告会按下方八个中文章节保存;请勿删除、重命名或调整章节标题顺序。",
- "info",
- )
- self.host_layout.addWidget(notice)
- editor = QTextEdit()
- editor.setPlainText(state.draft)
- editor.setPlaceholderText("请输入报告内容")
- editor.textChanged.connect(lambda: setattr(state, "draft", editor.toPlainText()))
- editor.setMinimumHeight(280)
- self.host_layout.addWidget(editor)
- if state.edit_error:
- error_banner = MessageBanner()
- error_banner.show_message(state.edit_error, "danger")
- self.host_layout.addWidget(error_banner)
- actions = QHBoxLayout()
- actions.addStretch(1)
- cancel = QPushButton("取消")
- cancel.setCursor(Qt.CursorShape.PointingHandCursor)
- cancel.setEnabled(not state.saving)
- cancel.clicked.connect(self._cancel_edit)
- save = QPushButton("保存修改")
- save.setProperty("variant", "primary")
- save.setCursor(Qt.CursorShape.PointingHandCursor)
- save.setEnabled(not state.saving)
- save.setText("保存中…" if state.saving else "保存修改")
- save.clicked.connect(self._save_edit)
- actions.addWidget(cancel)
- actions.addWidget(save)
- self.host_layout.addLayout(actions)
- return
-
- report = data.get("report") if isinstance(data.get("report"), dict) else None
- if report:
- if report.get("summary"):
- summary = QFrame()
- summary.setObjectName("PrescriptionAiSummary")
- summary_layout = QVBoxLayout(summary)
- summary_layout.setContentsMargins(18, 16, 18, 16)
- heading = QLabel("核心判断")
- heading.setObjectName("PrescriptionAiSectionTitle")
- body = QLabel(str(report.get("summary") or ""))
- body.setObjectName("PrescriptionAiBody")
- body.setWordWrap(True)
- summary_layout.addWidget(heading)
- summary_layout.addWidget(body)
- self.host_layout.addWidget(summary)
- grid_host = QWidget()
- grid = QGridLayout(grid_host)
- grid.setContentsMargins(0, 0, 0, 0)
- grid.setHorizontalSpacing(28)
- cells = (
- ("可能症状与证候", self._list_html(report.get("possible_symptoms"), "模型未给出明确症状推测")),
- ("主治方向", html.escape(str(report.get("main_indications") or "暂无"))),
- ("主要功效", self._list_html(report.get("efficacy"), "暂无")),
- ("可能适用人群", self._list_html(report.get("suitable_people"), "暂无")),
- )
- for index, (title, body) in enumerate(cells):
- cell = QFrame()
- cell_layout = QVBoxLayout(cell)
- cell_layout.setContentsMargins(0, 12, 0, 12)
- heading = QLabel(title)
- heading.setObjectName("PrescriptionAiSectionTitle")
- content = QLabel(body)
- content.setObjectName("PrescriptionAiBody")
- content.setWordWrap(True)
- content.setTextFormat(Qt.TextFormat.RichText)
- cell_layout.addWidget(heading)
- cell_layout.addWidget(content)
- grid.addWidget(cell, index // 2, index % 2)
- self.host_layout.addWidget(grid_host)
- if report.get("compatibility_analysis"):
- self._section("配伍分析", str(report.get("compatibility_analysis") or ""))
- self._section(
- "用药与复核提醒",
- self._list_html(report.get("cautions"), "仍需结合患者情况完成禁忌与相互作用复核"),
- rich=True,
- caution=True,
- )
- disclaimer = str(
- report.get("disclaimer")
- or "仅供专业人员辅助审方,不替代辨证、诊断和处方审核。"
- )
- self._add_label(disclaimer, "PrescriptionAiMuted")
- return
- self._section("报告正文", str(data.get("content") or "暂无报告正文"))
-
+ bullets = "".join(f"{html.escape(item)}" for item in values)
+ return f''
+
+ def _section(self, title: str, body: str, *, rich: bool = False, caution: bool = False) -> None:
+ frame = QFrame()
+ frame.setObjectName("PrescriptionAiCaution" if caution else "PrescriptionAiSection")
+ layout = QVBoxLayout(frame)
+ layout.setContentsMargins(16 if caution else 0, 12, 16 if caution else 0, 12)
+ layout.setSpacing(8)
+ heading = QLabel(title)
+ heading.setObjectName("PrescriptionAiSectionTitle")
+ body_label = QLabel(body)
+ body_label.setObjectName("PrescriptionAiBody")
+ body_label.setWordWrap(True)
+ if rich:
+ body_label.setTextFormat(Qt.TextFormat.RichText)
+ layout.addWidget(heading)
+ layout.addWidget(body_label)
+ self.host_layout.addWidget(frame)
+
+ def _render(self) -> None:
+ generating = self.generation_loading
+ has_report = self._has_any_report()
+ self.generate_button.setVisible(self.can_refresh)
+ self.generate_button.setEnabled(
+ bool(self.prescription)
+ and self.can_refresh
+ and not self.load_loading
+ and not generating
+ and not self._any_saving()
+ and not self._any_editing()
+ )
+ self.generate_button.setText(
+ "正在生成…"
+ if generating
+ else (self.kind.regenerate_label if has_report else self.kind.generate_label)
+ )
+ if self.generation_error:
+ self.operation_error.show_message(self.generation_error, "danger")
+ else:
+ self.operation_error.hide()
+ for index, (profile, label, name) in enumerate(AI_MODELS):
+ state = self._state(profile)
+ status = "更新中" if generating else (
+ "更新失败" if state.error and not state.data else (
+ "已保存" if state.data else "未生成"
+ )
+ )
+ model_label = (state.data or {}).get("model_label") or label
+ model_name = (state.data or {}).get("model_name") or name
+ self.tabs.setTabText(index, f"{model_label} {model_name} {status}")
+ self._clear_host()
+ if self.load_loading:
+ self._add_label("正在加载已保存的 AI 诊断报告…", "PrescriptionAiMuted")
+ self.host_layout.addStretch(1)
+ return
+ if self.load_error:
+ empty = EmptyState("已保存报告加载失败", self.load_error, "重新加载")
+ empty.action_requested.connect(lambda: self._load_saved(self.dialog_generation))
+ self.host_layout.addWidget(empty, 1)
+ return
+ if not has_report:
+ empty = EmptyState(
+ "暂无已保存的 AI 诊断报告",
+ "打开窗口不会自动调用模型;需要时请手动生成。",
+ "生成报告" if self.can_refresh else "",
+ )
+ if self.can_refresh:
+ empty.action_requested.connect(self._request_generate)
+ else:
+ empty.action_button.hide()
+ hint = QLabel("当前账号无生成权限")
+ hint.setObjectName("PrescriptionAiMuted")
+ self.host_layout.addWidget(empty, 1)
+ self.host_layout.addWidget(hint, 0, Qt.AlignmentFlag.AlignHCenter)
+ return
+ self.host_layout.addWidget(empty, 1)
+ return
+ self._render_profile(self.active_profile)
+ self.host_layout.addStretch(1)
+
+ def _render_profile(self, profile: str) -> None:
+ state = self._state(profile)
+ if state.error and not state.data:
+ empty = EmptyState("这份模型报告生成失败", state.error, "重新生成整个报告")
+ if self.can_refresh:
+ empty.action_requested.connect(self._request_generate)
+ else:
+ empty.action_button.hide()
+ self.host_layout.addWidget(empty, 1)
+ return
+ data = state.data
+ if data is None:
+ empty = EmptyState("该模型暂无已保存报告", "可重新生成整个诊断报告。", "重新生成整个报告")
+ if self.can_refresh:
+ empty.action_requested.connect(self._request_generate)
+ else:
+ empty.action_button.hide()
+ self.host_layout.addWidget(empty, 1)
+ return
+
+ meta = QFrame()
+ meta.setObjectName("PrescriptionAiMeta")
+ meta_layout = QHBoxLayout(meta)
+ meta_layout.setContentsMargins(0, 4, 0, 12)
+ meta_main = QVBoxLayout()
+ meta_main.setSpacing(4)
+ title_row = QHBoxLayout()
+ title = QLabel(f"{data.get('model_label') or '模型'}建议报告")
+ title.setObjectName("PrescriptionAiSectionTitle")
+ title_row.addWidget(title)
+ title_row.addWidget(QLabel(str(data.get("model_name") or "")))
+ if data.get("is_stale"):
+ badge = StatusBadge("处方已变更", "warning")
+ title_row.addWidget(badge)
+ if data.get("is_edited"):
+ badge = StatusBadge("已人工编辑", "info")
+ title_row.addWidget(badge)
+ title_row.addStretch(1)
+ meta_main.addLayout(title_row)
+ times = QLabel(
+ f"生成时间:{data.get('generated_at') or '—'}"
+ + (f" 编辑时间:{data.get('edited_at')}" if data.get("edited_at") else "")
+ )
+ times.setObjectName("PrescriptionAiMuted")
+ meta_main.addWidget(times)
+ meta_layout.addLayout(meta_main, 1)
+ if self._can_edit_report(profile) and not state.editing:
+ edit_button = QPushButton("编辑报告")
+ edit_button.setProperty("variant", "link")
+ edit_button.setCursor(Qt.CursorShape.PointingHandCursor)
+ edit_button.setEnabled(not self.generation_loading and not self._any_saving())
+ edit_button.clicked.connect(self._begin_edit)
+ meta_layout.addWidget(edit_button, 0, Qt.AlignmentFlag.AlignTop)
+ self.host_layout.addWidget(meta)
+
+ if state.error:
+ warning = MessageBanner()
+ warning.show_message(
+ f"本次重新生成失败,当前展示上一次保存的版本:{state.error}",
+ "warning",
+ )
+ self.host_layout.addWidget(warning)
+
+ if state.editing:
+ if state.structured_edit:
+ notice = MessageBanner()
+ notice.show_message(
+ "结构化报告会按下方八个中文章节保存;请勿删除、重命名或调整章节标题顺序。",
+ "info",
+ )
+ self.host_layout.addWidget(notice)
+ editor = QTextEdit()
+ editor.setPlainText(state.draft)
+ editor.setPlaceholderText("请输入报告内容")
+ editor.textChanged.connect(lambda: setattr(state, "draft", editor.toPlainText()))
+ editor.setMinimumHeight(280)
+ self.host_layout.addWidget(editor)
+ if state.edit_error:
+ error_banner = MessageBanner()
+ error_banner.show_message(state.edit_error, "danger")
+ self.host_layout.addWidget(error_banner)
+ actions = QHBoxLayout()
+ actions.addStretch(1)
+ cancel = QPushButton("取消")
+ cancel.setCursor(Qt.CursorShape.PointingHandCursor)
+ cancel.setEnabled(not state.saving)
+ cancel.clicked.connect(self._cancel_edit)
+ save = QPushButton("保存修改")
+ save.setProperty("variant", "primary")
+ save.setCursor(Qt.CursorShape.PointingHandCursor)
+ save.setEnabled(not state.saving)
+ save.setText("保存中…" if state.saving else "保存修改")
+ save.clicked.connect(self._save_edit)
+ actions.addWidget(cancel)
+ actions.addWidget(save)
+ self.host_layout.addLayout(actions)
+ return
+
+ report = data.get("report") if isinstance(data.get("report"), dict) else None
+ if report:
+ if report.get("summary"):
+ summary = QFrame()
+ summary.setObjectName("PrescriptionAiSummary")
+ summary_layout = QVBoxLayout(summary)
+ summary_layout.setContentsMargins(18, 16, 18, 16)
+ heading = QLabel("核心判断")
+ heading.setObjectName("PrescriptionAiSectionTitle")
+ body = QLabel(str(report.get("summary") or ""))
+ body.setObjectName("PrescriptionAiBody")
+ body.setWordWrap(True)
+ summary_layout.addWidget(heading)
+ summary_layout.addWidget(body)
+ self.host_layout.addWidget(summary)
+ grid_host = QWidget()
+ grid = QGridLayout(grid_host)
+ grid.setContentsMargins(0, 0, 0, 0)
+ grid.setHorizontalSpacing(28)
+ cells = (
+ ("可能症状与证候", self._list_html(report.get("possible_symptoms"), "模型未给出明确症状推测")),
+ ("主治方向", html.escape(str(report.get("main_indications") or "暂无"))),
+ ("主要功效", self._list_html(report.get("efficacy"), "暂无")),
+ ("可能适用人群", self._list_html(report.get("suitable_people"), "暂无")),
+ )
+ for index, (title, body) in enumerate(cells):
+ cell = QFrame()
+ cell_layout = QVBoxLayout(cell)
+ cell_layout.setContentsMargins(0, 12, 0, 12)
+ heading = QLabel(title)
+ heading.setObjectName("PrescriptionAiSectionTitle")
+ content = QLabel(body)
+ content.setObjectName("PrescriptionAiBody")
+ content.setWordWrap(True)
+ content.setTextFormat(Qt.TextFormat.RichText)
+ cell_layout.addWidget(heading)
+ cell_layout.addWidget(content)
+ grid.addWidget(cell, index // 2, index % 2)
+ self.host_layout.addWidget(grid_host)
+ if report.get("compatibility_analysis"):
+ self._section("配伍分析", str(report.get("compatibility_analysis") or ""))
+ self._section(
+ "用药与复核提醒",
+ self._list_html(report.get("cautions"), "仍需结合患者情况完成禁忌与相互作用复核"),
+ rich=True,
+ caution=True,
+ )
+ disclaimer = str(
+ report.get("disclaimer")
+ or "仅供专业人员辅助审方,不替代辨证、诊断和处方审核。"
+ )
+ self._add_label(disclaimer, "PrescriptionAiMuted")
+ return
+ self._section("报告正文", str(data.get("content") or "暂无报告正文"))
+
def reject(self) -> None:
- self.dialog_generation += 1
- self.load_generation += 1
+ self.dialog_generation += 1
+ self.load_generation += 1
super().reject()
@@ -1395,24 +1461,8 @@ class DiagnosisAiAssistantDialog(QDialog):
self.model_label = QLabel("")
self.model_label.setObjectName("PrescriptionAiMuted")
root.addWidget(self.model_label)
- self.answer_label = QLabel("")
- self.answer_label.setObjectName("PrescriptionAiBody")
- self.answer_label.setTextFormat(Qt.TextFormat.PlainText)
- self.answer_label.setWordWrap(True)
- self.answer_label.setAlignment(
- Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop
- )
- self.answer_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
- self.answer_scroll = QScrollArea()
- self.answer_scroll.setWidgetResizable(True)
- self.answer_scroll.setFrameShape(QFrame.Shape.NoFrame)
- self.answer_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
- answer_host = QWidget()
- answer_layout = QVBoxLayout(answer_host)
- answer_layout.setContentsMargins(2, 2, 8, 2)
- answer_layout.setSizeConstraint(QLayout.SizeConstraint.SetMinAndMaxSize)
- answer_layout.addWidget(self.answer_label)
- self.answer_scroll.setWidget(answer_host)
+ self.answer_label = _AiAnswerBrowser()
+ self.answer_scroll = self.answer_label
root.addWidget(self.answer_scroll, 1)
actions = QHBoxLayout()
actions.addStretch(1)
@@ -1468,7 +1518,7 @@ class DiagnosisAiAssistantDialog(QDialog):
or "服务端自动匹配"
)
self.model_label.setText(f"本次模型:{model}")
- self.answer_label.setText(answer)
+ self.answer_label.set_answer(answer)
self.status_banner.show_message("分析完成", "success")
self.loading = False
self.retry_button.setEnabled(True)
@@ -1483,34 +1533,34 @@ class DiagnosisAiAssistantDialog(QDialog):
def reject(self) -> None:
self.request_generation += 1
super().reject()
-
-
-def can_open_ai_explain(permissions: Any) -> bool:
- return has_permission(permissions, PRESCRIPTION_AI_KIND.view_permissions)
-
-
+
+
+def can_open_ai_explain(permissions: Any) -> bool:
+ return has_permission(permissions, PRESCRIPTION_AI_KIND.view_permissions)
+
+
def can_open_diagnosis_ai_report(permissions: Any) -> bool:
return has_permission(permissions, DIAGNOSIS_AI_KIND.view_permissions)
def can_use_diagnosis_ai_assistant(permissions: Any) -> bool:
return has_permission(permissions, "tcm.diagnosis/aiAssistant")
-
-
+
+
def present_diagnosis_ai_report(
- repository: Any,
- permissions: Any,
- parent: QWidget | None,
+ repository: Any,
+ permissions: Any,
+ parent: QWidget | None,
row: Any,
*,
preferred_model: str | None = None,
) -> None:
- dialog = PrescriptionAiReportDialog(
- repository,
- permissions,
- parent=parent,
- kind=DIAGNOSIS_AI_KIND,
- )
+ dialog = PrescriptionAiReportDialog(
+ repository,
+ permissions,
+ parent=parent,
+ kind=DIAGNOSIS_AI_KIND,
+ )
dialog.open_for(row, preferred_model=preferred_model)
dialog.exec()
diff --git a/app/src/doctor_workstation/ui/shell.py b/app/src/doctor_workstation/ui/shell.py
index 7ceb93c34..12a94297d 100644
--- a/app/src/doctor_workstation/ui/shell.py
+++ b/app/src/doctor_workstation/ui/shell.py
@@ -43,6 +43,7 @@ from doctor_workstation.resources import app_icon_path
from .dialogs.ai_consult import can_open_ai_consult
from .dialogs.ai_consult_picker import select_and_present_ai_consult
+from .dialogs.diagnosis import DiagnosisDialog
from .dialogs.local_audio_queue import LocalAudioQueueDialog
from .pages import (
AppointmentsPage,
@@ -59,6 +60,7 @@ from .widgets import (
display_text,
first_value,
get_value,
+ has_permission,
show_toast,
)
@@ -895,6 +897,7 @@ class ShellWindow(QMainWindow):
self._activation_generation = 0
self._activation_refreshed = False
self._local_audio_settings_dialog: LocalAudioQueueDialog | None = None
+ self._global_diagnosis_dialog: DiagnosisDialog | None = None
self.setMinimumSize(_SHELL_MINIMUM_SIZE)
screen = self.screen() or QApplication.primaryScreen()
@@ -1845,6 +1848,54 @@ class ShellWindow(QMainWindow):
if callable(refresh):
refresh()
+ def _ensure_global_diagnosis_dialog(self) -> DiagnosisDialog:
+ dialog = self._global_diagnosis_dialog
+ if dialog is None:
+ dialog = DiagnosisDialog(
+ self.repository,
+ self,
+ permissions=self.permissions,
+ )
+ dialog.saved.connect(self.refresh_current_page)
+ self._global_diagnosis_dialog = dialog
+ else:
+ dialog.refresh_permissions(self.permissions)
+ return dialog
+
+ def open_diagnosis_by_id(
+ self,
+ diagnosis_id: Any,
+ *,
+ modeless: bool = False,
+ ) -> DiagnosisDialog | None:
+ """Open one authoritative diagnosis in the strongest permitted mode."""
+
+ try:
+ normalized_id = int(diagnosis_id)
+ except (TypeError, ValueError):
+ normalized_id = 0
+ if normalized_id <= 0:
+ show_toast(self, "当前视频缺少有效诊单编号。", "warning", 3600)
+ return None
+
+ if has_permission(self.permissions, "tcm.diagnosis/edit", default=False):
+ dialog = self._ensure_global_diagnosis_dialog()
+ dialog.open_for(normalized_id, editable=True, modeless=modeless)
+ elif has_permission(
+ self.permissions,
+ "tcm.diagnosis/readonlyDetail",
+ default=False,
+ ):
+ dialog = self._ensure_global_diagnosis_dialog()
+ dialog.open_view_only(normalized_id, modeless=modeless)
+ else:
+ show_toast(self, "当前账号没有查看该诊单的权限。", "danger", 4200)
+ return None
+
+ dialog.raise_()
+ dialog.activateWindow()
+ return dialog
+
def showEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
super().showEvent(event)
page = self.stack.currentWidget()
diff --git a/app/src/doctor_workstation/ui/theme.py b/app/src/doctor_workstation/ui/theme.py
index 5e9ec6366..970897ce4 100644
--- a/app/src/doctor_workstation/ui/theme.py
+++ b/app/src/doctor_workstation/ui/theme.py
@@ -15,9 +15,19 @@ import os
import sys
from pathlib import Path
from string import Template
+from typing import Any
from PySide6.QtCore import QEvent, QObject, Qt
-from PySide6.QtGui import QColor, QFont, QFontDatabase, QPalette, QPixmap
+from PySide6.QtGui import (
+ QColor,
+ QFont,
+ QFontDatabase,
+ QPalette,
+ QPixmap,
+ QTextBlockFormat,
+ QTextCharFormat,
+ QTextCursor,
+)
from PySide6.QtWidgets import (
QApplication,
QDialog,
@@ -25,6 +35,7 @@ from PySide6.QtWidgets import (
QFileDialog,
QInputDialog,
QMessageBox,
+ QTextBrowser,
)
# Canonical semantic tokens. The legacy teal/ink aliases remain available to
@@ -997,6 +1008,111 @@ QToolTip {
).substitute(_QSS_TOKENS)
+#: Per-block reading rhythm, in device pixels. ``(top, bottom, line%)``.
+#: QTextDocument's markdown importer builds block formats directly and ignores
+#: ``setDefaultStyleSheet``, so spacing has to be applied to the parsed
+#: document instead of being declared in CSS.
+# 行内收紧、行间放开:一条要点自己的折行必须比两条要点之间更紧,否则整段会散成
+# 一行一行的碎片,反而更难读。
+_BLOCK_RHYTHM = {
+ "heading": (22, 10, 148),
+ "subheading": (18, 8, 148),
+ # 顶层列表项通常就是小节标题,之间留出整行空白让各小节一眼可数。
+ "section": (20, 8, 150),
+ "item": (13, 5, 158), # nested bullet under a section
+ "paragraph": (10, 10, 168),
+}
+
+
+def _block_is_all_bold(block: Any) -> bool:
+ """True when every visible run in the block is bold.
+
+ Models title their sections as ``1. **症状演变与疗效评估**`` rather than as
+ real markdown headings, so a fully bold top-level list item is the only
+ reliable signal that a block is a section title and not a content bullet.
+ """
+
+ iterator = block.begin()
+ seen = False
+ while not iterator.atEnd():
+ fragment = iterator.fragment()
+ iterator += 1
+ if not fragment.isValid() or not fragment.text().strip():
+ continue
+ seen = True
+ if fragment.charFormat().fontWeight() < QFont.Weight.DemiBold.value:
+ return False
+ return seen
+
+
+def apply_reading_rhythm(browser: QTextBrowser, *, role: str) -> None:
+ """Give a parsed reply real hierarchy and breathing room.
+
+ Model answers are long "section heading + two levels of bullets" documents.
+ Qt renders every one of those blocks at the same size with 6px margins, so
+ the reply arrives as a wall of text. This walks the parsed document once
+ and applies a heading scale plus per-level spacing.
+ """
+
+ document = browser.document()
+ base_font = browser.font()
+ base_px = base_font.pixelSize()
+ if base_px <= 0:
+ base_px = max(12, round(base_font.pointSizeF() * 96 / 72))
+
+ cursor = QTextCursor(document)
+ cursor.beginEditBlock()
+ try:
+ block = document.begin()
+ while block.isValid():
+ heading = block.blockFormat().headingLevel()
+ text_list = block.textList()
+ indent = text_list.format().indent() if text_list is not None else 0
+ if heading:
+ kind = "heading" if heading <= 2 else "subheading"
+ size = base_px + (3 if heading <= 2 else 1)
+ elif indent >= 2:
+ kind, size = "item", None
+ elif indent == 1:
+ kind = "section"
+ # 只有整行加粗的顶层条目才是小节标题,普通要点保持正文字号。
+ size = base_px + 2 if _block_is_all_bold(block) else None
+ else:
+ kind, size = "paragraph", None
+
+ top, bottom, line = _BLOCK_RHYTHM[kind]
+ # 首块的上边距会在气泡顶部留出一段空白,视觉上像是排版错位。
+ if block.position() == 0:
+ top = 0
+ block_format = QTextBlockFormat(block.blockFormat())
+ block_format.setTopMargin(top)
+ block_format.setBottomMargin(bottom)
+ block_format.setLineHeight(
+ line, QTextBlockFormat.LineHeightTypes.ProportionalHeight.value
+ )
+ cursor.setPosition(block.position())
+ cursor.setBlockFormat(block_format)
+
+ if size is not None and block.length() > 1:
+ heading_font = QFont(base_font)
+ heading_font.setPixelSize(size)
+ heading_font.setBold(True)
+ char_format = QTextCharFormat()
+ char_format.setFont(heading_font)
+ if role != "doctor":
+ char_format.setForeground(QColor("#111B3F"))
+ cursor.setPosition(block.position())
+ cursor.setPosition(
+ block.position() + block.length() - 1,
+ QTextCursor.MoveMode.KeepAnchor,
+ )
+ cursor.mergeCharFormat(char_format)
+ block = block.next()
+ finally:
+ cursor.endEditBlock()
+
+
+
def _apply_group(
palette: QPalette,
group: QPalette.ColorGroup,
@@ -1085,17 +1201,48 @@ def _polish_dialog_buttons(button_box: QDialogButtonBox) -> None:
_refresh_widget_style(button)
+def allow_dialog_resize(dialog: QDialog) -> None:
+ """Give a business subwindow the usual minimise/maximise affordances.
+
+ ``QDialog`` ships with a close button only, so every AI panel, report and
+ editor was stuck at whatever size it was constructed with — unusable for the
+ long, dense clinical replies these windows carry. Transient prompts
+ (message and input boxes) are deliberately left alone, and a dialog that has
+ pinned itself to a fixed size keeps that decision.
+ """
+
+ if isinstance(dialog, (QMessageBox, QInputDialog, QFileDialog)):
+ return
+ if dialog.minimumSize() == dialog.maximumSize():
+ return
+ # Qt hides a window whose flags change while it is visible, so a dialog that
+ # is already on screen keeps the flags it was shown with.
+ if dialog.isVisible():
+ dialog.setSizeGripEnabled(True)
+ return
+ flags = dialog.windowFlags()
+ if flags & Qt.WindowType.WindowMaximizeButtonHint:
+ return
+ dialog.setWindowFlags(
+ flags
+ | Qt.WindowType.WindowMinimizeButtonHint
+ | Qt.WindowType.WindowMaximizeButtonHint
+ )
+ dialog.setSizeGripEnabled(True)
+
+
def mark_business_dialog(dialog: QDialog, object_name: str | None = None) -> None:
"""Opt a business subwindow into the shared visual contract.
The helper intentionally does not change modality, ownership or result
- handling. It only supplies stable styling metadata and semantic button
- roles, so existing workflows keep their original behavior.
+ handling. It only supplies stable styling metadata, semantic button roles
+ and window affordances, so existing workflows keep their original behavior.
"""
if object_name and not dialog.objectName():
dialog.setObjectName(object_name)
dialog.setProperty("businessDialog", True)
+ allow_dialog_resize(dialog)
for button_box in dialog.findChildren(QDialogButtonBox):
_polish_dialog_buttons(button_box)
_refresh_widget_style(dialog)
@@ -1119,6 +1266,12 @@ class _BusinessDialogStyleFilter(QObject):
QEvent.Type.Show,
}:
_polish_dialog_buttons(watched)
+ elif isinstance(watched, QDialog) and event_type == QEvent.Type.Polish:
+ # Window flags can only be changed before the dialog is on screen,
+ # so dynamically-created dialogs get their affordances at polish
+ # time rather than when they are already visible.
+ if not self._is_native_or_overlay(watched):
+ allow_dialog_resize(watched)
elif isinstance(watched, QDialog) and event_type == QEvent.Type.Show:
for button_box in watched.findChildren(QDialogButtonBox):
_polish_dialog_buttons(button_box)
@@ -1215,6 +1368,8 @@ def apply_theme(app: QApplication) -> None:
__all__ = [
"COLORS",
+ "allow_dialog_resize",
+ "apply_reading_rhythm",
"GLOBAL_QSS",
"METRICS",
"TYPE",
diff --git a/app/src/doctor_workstation/video/launcher.py b/app/src/doctor_workstation/video/launcher.py
index 8104efea9..d76579c8a 100644
--- a/app/src/doctor_workstation/video/launcher.py
+++ b/app/src/doctor_workstation/video/launcher.py
@@ -378,6 +378,8 @@ class VideoCallLauncher:
patient_id: Any = None,
open_im: bool = False,
patient_name: str = "患者",
+ patient_case: Mapping[str, Any] | None = None,
+ on_open_diagnosis: Callable[[], None] | None = None,
) -> Any:
request = self.prepare(
ticket,
@@ -395,6 +397,8 @@ class VideoCallLauncher:
browser_opener=self.browser_opener,
open_im=open_im,
patient_name=patient_name,
+ patient_case=patient_case,
+ on_open_diagnosis=on_open_diagnosis,
)
@@ -411,6 +415,8 @@ def launch_video_call(
browser_opener: Callable[[str], bool] | None = None,
open_im: bool = False,
patient_name: str = "患者",
+ patient_case: Mapping[str, Any] | None = None,
+ on_open_diagnosis: Callable[[], None] | None = None,
) -> Any:
"""Normalize a ticket and open a call with the requested backend."""
@@ -427,4 +433,6 @@ def launch_video_call(
patient_id=patient_id,
open_im=open_im,
patient_name=patient_name,
+ patient_case=patient_case,
+ on_open_diagnosis=on_open_diagnosis,
)
diff --git a/app/src/doctor_workstation/video/window.py b/app/src/doctor_workstation/video/window.py
index ee5aa6b35..fed70d4ed 100644
--- a/app/src/doctor_workstation/video/window.py
+++ b/app/src/doctor_workstation/video/window.py
@@ -296,6 +296,8 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
lifecycle_factory: Callable[[], OrderedCallLifecycle],
open_im: bool = False,
patient_name: str = "患者",
+ patient_case: Mapping[str, Any] | None = None,
+ on_open_diagnosis: Callable[[], None] | None = None,
) -> None:
super().__init__()
self.request = request
@@ -306,6 +308,8 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
self.logger = logger
self.open_im = bool(open_im)
self.patient_name = str(patient_name or "患者").strip() or "患者"
+ self.patient_case = dict(patient_case or {})
+ self._on_open_diagnosis = on_open_diagnosis
try:
self._policy = TrustedDocumentPolicy.from_url(
location.url,
@@ -451,6 +455,7 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
config = {
**self.request.to_web_config(),
"patientName": self.patient_name,
+ "patientCase": self.patient_case,
"mode": "chat" if self.open_im else "video",
}
config_json = json.dumps(config, ensure_ascii=True, separators=(",", ":"))
@@ -499,6 +504,10 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
if self._closing:
return
event = str(message.get("event", ""))
+ if event == "open-diagnosis-request":
+ if self._on_open_diagnosis is not None:
+ QTimer.singleShot(0, self._open_diagnosis_safely)
+ return
if event == "call-start-request":
self._start_call_cycle()
return
@@ -580,6 +589,17 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
if not self.open_im or self._shutdown_requested:
self._close_from_companion("companion-error")
+ def _open_diagnosis_safely(self) -> None:
+ if self._closing or self._on_open_diagnosis is None:
+ return
+ try:
+ self._on_open_diagnosis()
+ except Exception:
+ self.logger.exception(
+ "diagnosis drawer could not be opened from video companion",
+ extra={"video_call": self.request.safe_log_context()},
+ )
+
def _notify_room_completed(self, room_id: str, future: Future[bool]) -> None:
try:
succeeded = bool(future.result())
@@ -1214,6 +1234,8 @@ class VideoCallWindow:
browser_opener: Callable[[str], bool] | None = None,
open_im: bool = False,
patient_name: str = "患者",
+ patient_case: Mapping[str, Any] | None = None,
+ on_open_diagnosis: Callable[[], None] | None = None,
) -> None:
del browser_opener # Reserved for a future authenticated handoff implementation.
try:
@@ -1231,6 +1253,8 @@ class VideoCallWindow:
self.repository = repository
self.open_im = bool(open_im)
self.patient_name = str(patient_name or "患者").strip() or "患者"
+ self.patient_case = dict(patient_case or {})
+ self.on_open_diagnosis = on_open_diagnosis
self.logger = logger or _LOGGER
self.location = resolve_companion_location(
local_dist=local_dist,
@@ -1259,6 +1283,8 @@ class VideoCallWindow:
lifecycle_factory=self._new_lifecycle,
open_im=self.open_im,
patient_name=self.patient_name,
+ patient_case=self.patient_case,
+ on_open_diagnosis=self.on_open_diagnosis,
)
except Exception:
self.lifecycle.end("window-open-failed")
@@ -1302,6 +1328,8 @@ def open_video_call(
browser_opener: Callable[[str], bool] | None = None,
open_im: bool = False,
patient_name: str = "患者",
+ patient_case: Mapping[str, Any] | None = None,
+ on_open_diagnosis: Callable[[], None] | None = None,
) -> VideoCallWindow:
"""Create and immediately open a trusted embedded video window."""
@@ -1316,6 +1344,8 @@ def open_video_call(
browser_opener=browser_opener,
open_im=open_im,
patient_name=patient_name,
+ patient_case=patient_case,
+ on_open_diagnosis=on_open_diagnosis,
).open()
diff --git a/app/tests/test_ai_consult_ui.py b/app/tests/test_ai_consult_ui.py
index d19765a59..02ba38e40 100644
--- a/app/tests/test_ai_consult_ui.py
+++ b/app/tests/test_ai_consult_ui.py
@@ -1291,3 +1291,234 @@ def test_ask_sends_only_question_and_relies_on_server_full_context(
assert any("请结合资料分析当前证候" in text for text in all_bubble_texts)
assert any("服务端将按当前诊单实时附带患者全部纵向资料" in text for text in all_bubble_texts)
dialog.close()
+
+
+def _bubble_texts(dialog: AiConsultDialog) -> list[str]:
+ return [
+ widget.toPlainText()
+ for widget in dialog.findChildren(QTextBrowser)
+ if widget.objectName() == "AiConsultBubbleText"
+ ]
+
+
+def _silent_dialog(monkeypatch: pytest.MonkeyPatch) -> AiConsultDialog:
+ """A dialog whose stream workers are never actually started."""
+
+ monkeypatch.setattr(
+ ai_consult_module,
+ "QThreadPool",
+ SimpleNamespace(
+ globalInstance=lambda: SimpleNamespace(start=lambda worker: None)
+ ),
+ )
+ dialog = AiConsultDialog(
+ DemoDoctorRepository(),
+ PermissionSet(["tcm.diagnosis/aiAssistant"]),
+ )
+ dialog.open_for(diagnosis_id=501, patient_id=301)
+ return dialog
+
+
+def test_full_context_notice_is_shown_once_per_conversation(
+ application: QApplication,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # 每轮问答都重复同一句全量上下文说明会把真正的回答挤出可视区。
+ dialog = _silent_dialog(monkeypatch)
+ dialog.show()
+ application.processEvents()
+
+ notice = "服务端将按当前诊单实时附带患者全部纵向资料"
+ counts = []
+ for question in ("第一个问题", "第二个问题", "第三个问题"):
+ dialog._cancel_stream()
+ dialog._ask(question)
+ counts.append(sum(1 for text in _bubble_texts(dialog) if notice in text))
+ assert counts == [1, 1, 1]
+
+ # 换患者视为新会话,需要重新提示一次。
+ dialog.open_for(diagnosis_id=502, patient_id=302)
+ application.processEvents()
+ dialog._ask("新患者的问题")
+ assert sum(1 for text in _bubble_texts(dialog) if notice in text) == 1
+ dialog.close()
+
+
+def test_pending_and_silently_closed_streams_never_show_a_blank_bubble(
+ application: QApplication,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # 服务端既不发 done 也不报错时,占位气泡会永远停在空白状态。
+ dialog = _silent_dialog(monkeypatch)
+ dialog.show()
+ application.processEvents()
+
+ dialog._ask("请评估当前用药是否合理")
+ assert dialog._stream_bubble is not None
+ assert dialog._stream_bubble._raw_payload == ai_consult_module.AI_STREAM_PENDING_TEXT
+ assert any(
+ ai_consult_module.AI_STREAM_PENDING_TEXT in text for text in _bubble_texts(dialog)
+ )
+
+ dialog._stream_finished(
+ dialog._generation, dialog._stream_generation, dialog._stream_worker
+ )
+ application.processEvents()
+ assert dialog._stream_text == ai_consult_module.AI_STREAM_SILENT_TEXT
+ assert any(ai_consult_module.AI_STREAM_SILENT_TEXT in text for text in _bubble_texts(dialog))
+ assert dialog.send_button.isEnabled()
+ dialog.close()
+
+
+def test_answered_stream_replaces_the_pending_placeholder(
+ application: QApplication,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ dialog = _silent_dialog(monkeypatch)
+ dialog.show()
+ application.processEvents()
+
+ dialog._ask("请总结当前病情")
+ generation, stream_generation = dialog._generation, dialog._stream_generation
+ dialog._stream_event(generation, stream_generation, {"event": "delta", "text": "证候:"})
+ dialog._stream_event(generation, stream_generation, {"event": "delta", "text": "脾肾两虚"})
+ dialog._stream_event(generation, stream_generation, {"event": "done", "model_label": "千问"})
+ dialog._stream_finished(generation, stream_generation, dialog._stream_worker)
+ application.processEvents()
+
+ assert dialog._stream_text == "证候:脾肾两虚"
+ texts = _bubble_texts(dialog)
+ assert not any(ai_consult_module.AI_STREAM_PENDING_TEXT in text for text in texts)
+ assert not any(ai_consult_module.AI_STREAM_SILENT_TEXT in text for text in texts)
+ dialog.close()
+
+
+def test_ai_consult_window_can_be_maximized(
+ application: QApplication,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # 这个窗口信息密度很高,必须允许医生放大到整屏。
+ dialog = _silent_dialog(monkeypatch)
+ flags = dialog.windowFlags()
+ assert flags & Qt.WindowType.WindowMaximizeButtonHint
+ assert flags & Qt.WindowType.WindowMinimizeButtonHint
+ assert dialog.isSizeGripEnabled()
+ dialog.showMaximized()
+ application.processEvents()
+ assert dialog.isMaximized()
+ dialog.close()
+
+
+def test_long_reply_gets_section_hierarchy_and_breathing_room(
+ application: QApplication,
+) -> None:
+ """QTextDocument's markdown importer ignores setDefaultStyleSheet.
+
+ Spacing therefore has to be applied to the parsed document; without it every
+ block renders at one size with 6px margins and the reply reads as a wall.
+ """
+
+ browser = ai_consult_module._RichMessage("ai")
+ browser.resize(660, 400)
+ browser.set_payload(
+ "概述段落。\n\n"
+ "1. **症状演变与疗效评估**\n"
+ " - **麻木症状:** 服药十四天后是否缓解?\n"
+ " - **皮肤瘙痒:** 目前是否仍有发作?\n"
+ "2. **血糖控制与监测细节**\n"
+ " - **监测习惯:** 是否规律监测餐后血糖?\n"
+ )
+
+ document = browser.document()
+ base_px = browser.font().pixelSize()
+ seen: dict[str, list] = {"section": [], "item": [], "paragraph": []}
+ block = document.begin()
+ while block.isValid():
+ text_list = block.textList()
+ indent = text_list.format().indent() if text_list is not None else 0
+ kind = "item" if indent >= 2 else "section" if indent == 1 else "paragraph"
+ seen[kind].append(block)
+ block = block.next()
+
+ assert seen["section"] and seen["item"], "both list levels must be present"
+
+ # 小节标题比正文更大更重,否则四个小节无法一眼分辨。
+ section = seen["section"][0]
+ section_size = section.begin().fragment().charFormat().font().pixelSize()
+ assert section_size > base_px
+
+ # 小节之间的留白必须大于同一小节内要点之间的留白。
+ section_top = seen["section"][0].blockFormat().topMargin()
+ item_top = seen["item"][0].blockFormat().topMargin()
+ assert section_top > item_top > 0
+
+ # 一条要点的折行必须比两条要点之间更紧,否则整段会散成碎片。
+ item_line = seen["item"][0].blockFormat().lineHeight()
+ assert 0 < item_line < 170
+
+ # 首块不带上边距,避免气泡顶部出现一段空白。
+ assert document.begin().blockFormat().topMargin() == 0
+
+
+def test_short_reply_is_not_over_spaced(application: QApplication) -> None:
+ browser = ai_consult_module._RichMessage("ai")
+ browser.resize(660, 200)
+ browser.set_payload("血糖控制尚可,暂无需调整降糖方案。")
+ block = browser.document().begin()
+ assert block.blockFormat().topMargin() == 0
+ assert block.next().isValid() is False
+
+
+def test_sectioned_reply_becomes_a_structured_report(application: QApplication) -> None:
+ """The clinical panel only knows four fixed section names.
+
+ Real answers are sectioned as 症状演变 / 血糖控制 / 用药依从性 …, which matched
+ none of them and therefore fell back to a plain wall of text.
+ """
+
+ reply = (
+ "以下是针对该患者当前情况,建议向患者确认的关键问诊问题,用于补充现有病历中的信息缺口:\n\n"
+ "1. **症状演变与疗效评估**\n"
+ " - **麻木症状:** 服药十四天后四肢麻木是否有所缓解?\n"
+ " - **皮肤瘙痒:** 目前是否仍有发作?是否与血糖波动有关?\n"
+ "2. **血糖控制与监测细节**\n"
+ " - **空腹血糖波动:** 近期是否有反复的低血糖发作?\n"
+ "3. **用药依从性与生活方式**\n"
+ " - **西药服用情况:** 近期是否有漏服或自行调整剂量?\n\n"
+ "**提示:** 以上问题基于现有脱敏病例资料梳理,需由执业医师复核后确定。\n"
+ )
+ parsed = ai_consult_module.parse_structured_report(reply)
+ assert parsed is not None
+ intro, sections, disclaimer = parsed
+ assert [section.title for section in sections] == [
+ "症状演变与疗效评估",
+ "血糖控制与监测细节",
+ "用药依从性与生活方式",
+ ]
+ assert [len(section.items) for section in sections] == [2, 1, 1]
+ assert "信息缺口" in intro
+ assert "执业医师" in disclaimer
+
+ bubble = ai_consult_module._ChatBubble(role="ai", text=reply, time_text="千问 · 11:01")
+ assert bubble.finalize_clinical_analysis() is True
+ panel = bubble.findChild(ai_consult_module._StructuredReportPanel)
+ assert panel is not None
+ titles = [
+ label.text()
+ for label in panel.findChildren(QLabel)
+ if label.objectName() == "AiConsultClinicalSectionTitle"
+ ]
+ assert titles == ["症状演变与疗效评估", "血糖控制与监测细节", "用药依从性与生活方式"]
+ bubble.deleteLater()
+
+
+@pytest.mark.parametrize(
+ "reply",
+ [
+ "血糖控制尚可,暂无需调整降糖方案。",
+ "1. **只有一个小节**\n - 一条要点\n",
+ '{"summary": "结构化 JSON 走既有解析路径"}',
+ ],
+)
+def test_unsectioned_replies_stay_plain_text(reply: str, application: QApplication) -> None:
+ assert ai_consult_module.parse_structured_report(reply) is None
diff --git a/app/tests/test_prescription_ai_ui.py b/app/tests/test_prescription_ai_ui.py
index 99862a707..39e631600 100644
--- a/app/tests/test_prescription_ai_ui.py
+++ b/app/tests/test_prescription_ai_ui.py
@@ -7,7 +7,7 @@ from typing import Any
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
-from PySide6.QtWidgets import QApplication, QLabel
+from PySide6.QtWidgets import QApplication, QLabel, QTextBrowser
from doctor_workstation.core import PermissionSet
from doctor_workstation.core.errors import ApiTimeoutError
@@ -385,7 +385,10 @@ def test_diagnosis_assistant_calls_repository_with_exact_safe_payload(
task: str,
) -> dict[str, Any]:
calls.append({"diagnosis_id": diagnosis_id, "prompt": prompt, "task": task})
- return {"answer": "建议复核肾功能与眼底。", "model_key": "openai"}
+ return {
+ "answer": "### 核心建议\n\n**重点复核**\n\n- 肾功能\n- 眼底",
+ "model_key": "openai",
+ }
dialog = DiagnosisAiAssistantDialog(Repository())
dialog.open_for(501, "并发症筛查", task="complication_risk")
@@ -393,15 +396,57 @@ def test_diagnosis_assistant_calls_repository_with_exact_safe_payload(
assert calls == [
{"diagnosis_id": 501, "prompt": "并发症筛查", "task": "complication_risk"}
]
- assert dialog.answer_label.text() == "建议复核肾功能与眼底。"
+ assert dialog.answer_label.toPlainText() == "核心建议\n重点复核\n肾功能\n眼底"
+ assert "###" not in dialog.answer_label.toPlainText()
+ assert "**" not in dialog.answer_label.toPlainText()
+ rendered_html = dialog.answer_label.toHtml().lower()
+ assert " None:
+ class Repository:
+ def analyze_diagnosis_ai(self, *args: Any, **kwargs: Any) -> dict[str, Any]:
+ return {
+ "answer": "### 安全内容\n\n
\n\n- 建议复诊",
+ "model_key": "qwen",
+ }
+
+ dialog = DiagnosisAiAssistantDialog(Repository())
+ dialog.open_for(501, "复诊建议", task="custom")
+
+ assert "安全内容" in dialog.answer_label.toPlainText()
+ assert "建议复诊" in dialog.answer_label.toPlainText()
+ assert "
None:
+ opened: list[tuple[str, int]] = []
+ refresh_callbacks: list[Any] = []
+ created: list[Any] = []
+
+ class _SavedSignal:
+ def connect(self, callback: Any) -> None:
+ refresh_callbacks.append(callback)
+
+ class _DiagnosisDialogDouble:
+ def __init__(
+ self,
+ repository: Any,
+ parent: Any,
+ *,
+ permissions: Any,
+ ) -> None:
+ self.repository = repository
+ self.parent = parent
+ self.permissions = permissions
+ self.saved = _SavedSignal()
+ self.raise_count = 0
+ self.activate_count = 0
+ created.append(self)
+
+ def refresh_permissions(self, permissions: Any) -> None:
+ self.permissions = permissions
+
+ def open_for(
+ self,
+ diagnosis_id: int,
+ *,
+ editable: bool,
+ modeless: bool,
+ ) -> None:
+ assert editable is True
+ assert modeless is True
+ opened.append(("edit", diagnosis_id))
+
+ def open_view_only(self, diagnosis_id: int, *, modeless: bool) -> None:
+ assert modeless is True
+ opened.append(("view", diagnosis_id))
+
+ def raise_(self) -> None:
+ self.raise_count += 1
+
+ def activateWindow(self) -> None: # noqa: N802 - Qt-compatible test double
+ self.activate_count += 1
+
+ monkeypatch.setattr(shell_module, "DiagnosisDialog", _DiagnosisDialogDouble)
+ shell_window._global_diagnosis_dialog = None
+
+ shell_window.permissions = {"tcm.diagnosis/edit"}
+ assert shell_window.open_diagnosis_by_id(501, modeless=True) is created[0]
+ shell_window.permissions = {"tcm.diagnosis/readonlyDetail"}
+ assert shell_window.open_diagnosis_by_id("502", modeless=True) is created[0]
+ shell_window.permissions = {"tcm.diagnosis/*"}
+ assert shell_window.open_diagnosis_by_id(503, modeless=True) is created[0]
+
+ assert opened == [("edit", 501), ("view", 502), ("edit", 503)]
+ assert len(created) == 1
+ assert created[0].parent is shell_window
+ assert len(refresh_callbacks) == 1
+ assert created[0].raise_count == 3
+ assert created[0].activate_count == 3
+
+ shell_window.permissions = set()
+ assert shell_window.open_diagnosis_by_id(504, modeless=True) is None
+ assert shell_window.open_diagnosis_by_id(0, modeless=True) is None
+ assert shell_window.open_diagnosis_by_id("invalid", modeless=True) is None
+ assert opened == [("edit", 501), ("view", 502), ("edit", 503)]
+
+
def test_shell_ai_entry_without_selection_opens_patient_diagnosis_picker(
application: QApplication,
shell_window: ShellWindow,
diff --git a/app/tests/test_ui_contract.py b/app/tests/test_ui_contract.py
index d3fc5b2e7..7a260746c 100644
--- a/app/tests/test_ui_contract.py
+++ b/app/tests/test_ui_contract.py
@@ -95,7 +95,13 @@ def test_navigation_requires_each_pages_actual_list_capability() -> None:
def test_video_release_does_not_remove_a_newer_call() -> None:
older = object()
newer = object()
- controller = SimpleNamespace(video_calls={"501": newer})
+ # _release_video_call also clears the preview slot, so the double needs the
+ # same attributes the real controller sets up in __init__.
+ controller = SimpleNamespace(
+ video_calls={"501": newer},
+ _video_preview_state=None,
+ _video_preview_generation=0,
+ )
ApplicationController._release_video_call(controller, "501", older)
assert controller.video_calls == {"501": newer}
@@ -505,3 +511,37 @@ def test_certificate_error_opens_server_settings(tmp_path: Any) -> None:
assert "信任自签名证书" in window.error_banner.label.text()
window.close()
application.processEvents()
+
+
+def test_business_dialogs_can_be_maximized_but_prompts_cannot() -> None:
+ """Dense AI panels and editors were stuck at their constructed size."""
+
+ from PySide6.QtCore import Qt
+ from PySide6.QtWidgets import QApplication, QDialog, QMessageBox
+
+ from doctor_workstation.ui.theme import allow_dialog_resize
+
+ application = QApplication.instance() or QApplication([])
+ assert application is not None
+
+ dialog = QDialog()
+ dialog.resize(600, 400)
+ allow_dialog_resize(dialog)
+ flags = dialog.windowFlags()
+ assert flags & Qt.WindowType.WindowMaximizeButtonHint
+ assert flags & Qt.WindowType.WindowMinimizeButtonHint
+ assert dialog.isSizeGripEnabled()
+ dialog.deleteLater()
+
+ # Transient prompts keep their plain frame.
+ prompt = QMessageBox()
+ allow_dialog_resize(prompt)
+ assert not (prompt.windowFlags() & Qt.WindowType.WindowMaximizeButtonHint)
+ prompt.deleteLater()
+
+ # A dialog that pinned itself to a fixed size keeps that decision.
+ fixed = QDialog()
+ fixed.setFixedSize(420, 300)
+ allow_dialog_resize(fixed)
+ assert not (fixed.windowFlags() & Qt.WindowType.WindowMaximizeButtonHint)
+ fixed.deleteLater()
diff --git a/app/tests/test_video_contract.py b/app/tests/test_video_contract.py
index a5cf70ed9..adae3f9f7 100644
--- a/app/tests/test_video_contract.py
+++ b/app/tests/test_video_contract.py
@@ -5,7 +5,8 @@ import sys
import threading
import time
from pathlib import Path
-from types import SimpleNamespace
+from types import MethodType, SimpleNamespace
+from typing import Any
import pytest
@@ -52,7 +53,7 @@ def test_companion_archives_cloud_video_local_mixed_audio_and_transcript() -> No
assert "context.createMediaStreamDestination()" in source
assert "cloud.getAudioTrack({ processed: true })" in source
- assert "userId: activeConfig.targetUserId" in source
+ assert "attachPatientAudioTrack(cloud, activeConfig.targetUserId)" in source
assert "new MediaRecorder(destination.stream" in source
assert "recorder.start(1000)" in source
assert "bridge.startLocalAudioRecording(sessionId, mimeType)" in source
@@ -134,6 +135,12 @@ def test_companion_local_recording_waits_for_real_audio_and_has_runtime_fallback
assert "stream.getAudioTracks()" in source
assert "navigator.mediaDevices.getUserMedia" in source
assert "await waitForCallAudioTracks(cloud, sessionId)" in source
+ assert "if (!attached)" in source
+ assert "cloud.getAudioTrack(userId)" in source
+ assert "event.sourceTrack" in source
+ assert "cloud.on('remote-audio-available'" in source
+ assert "localAudioCloud.off('remote-audio-available'" in source
+ assert "!event.userId || event.userId === activeConfig?.userID" in source
assert "localRecordingAttachedSourceCount <= 0" in source
assert "localRecordingBytes < 1024" in source
assert "已阻止上传空文件" in source
@@ -201,6 +208,360 @@ def test_companion_shows_incremental_subtitles_but_only_persists_final_segments(
assert "caption.text" in component_source
+def test_companion_keeps_transcript_and_patient_case_visible_in_a_side_rail() -> None:
+ companion_root = PROJECT_ROOT / "video_companion" / "src"
+ main_source = (companion_root / "main.ts").read_text(encoding="utf-8")
+ component_source = (companion_root / "App.vue").read_text(encoding="utf-8")
+ styles = (companion_root / "style.css").read_text(encoding="utf-8")
+ window_source = (
+ PROJECT_ROOT / "src" / "doctor_workstation" / "video" / "window.py"
+ ).read_text(encoding="utf-8")
+
+ assert "liveCaptions.value = [...previous, caption].slice(-120)" in main_source
+ assert "liveCaptionClearTimer" not in main_source
+ assert 'aria-label="患者病例与实时对话"' in component_source
+ assert 'id="patient-case-title"' in component_source
+ assert 'id="live-transcript-title"' in component_source
+ assert 'aria-label="打开完整诊单"' in component_source
+ assert "runAction(onOpenDiagnosis)" in component_source
+ assert "detail.clinicalDiagnosis" in component_source
+ assert 'v-for="field in caseFields"' in component_source
+ assert "{{ field.value }}" in component_source
+ assert "{{ caption.time }}" in component_source
+ assert "'caption-entry--partial': !caption.completed" in component_source
+ assert ':allowed-full-screen="false"' in component_source
+ assert ".video-layer--with-rail" in styles
+ assert ".consultation-rail" in styles
+ assert '"patientCase": self.patient_case' in window_source
+ assert 'event == "open-diagnosis-request"' in window_source
+ assert "QTimer.singleShot(0, self._open_diagnosis_safely)" in window_source
+ stop_source = main_source.split("async function stopTranscription", 1)[1].split(
+ "function transcriptionResult", 1
+ )[0]
+ assert "clearLiveCaptions()" not in stop_source
+
+
+def test_video_diagnosis_entry_uses_existing_permission_scoped_drawer() -> None:
+ app_source = (
+ PROJECT_ROOT / "src" / "doctor_workstation" / "app.py"
+ ).read_text(encoding="utf-8")
+ launcher_source = (
+ PROJECT_ROOT / "src" / "doctor_workstation" / "video" / "launcher.py"
+ ).read_text(encoding="utf-8")
+ main_source = (
+ PROJECT_ROOT / "video_companion" / "src" / "main.ts"
+ ).read_text(encoding="utf-8")
+ shell_source = (
+ PROJECT_ROOT / "src" / "doctor_workstation" / "ui" / "shell.py"
+ ).read_text(encoding="utf-8")
+ diagnosis_source = (
+ PROJECT_ROOT / "src" / "doctor_workstation" / "ui" / "dialogs" / "diagnosis.py"
+ ).read_text(encoding="utf-8")
+ styles = (
+ PROJECT_ROOT / "video_companion" / "src" / "style.css"
+ ).read_text(encoding="utf-8")
+
+ assert "shell.open_diagnosis_by_id(diagnosis_id, modeless=True)" in app_source
+ assert "self._show_video_preview(video_window, dialog)" in app_source
+ assert "WindowStaysOnTopHint" in app_source
+ assert "dialog.finished.connect" in app_source
+ assert "modeless=modeless" in shell_source
+ assert "not modeless and not self._standalone_readonly" in diagnosis_source
+ compact_styles = styles.split("@media (max-width: 700px)", 1)[1]
+ assert ".consultation-rail { display: none; }" in compact_styles
+ assert ".capture-button { display: none; }" in compact_styles
+ assert "on_open_diagnosis=on_open_diagnosis" in launcher_source
+ assert "event: 'open-diagnosis-request'" in main_source
+
+
+def test_video_preview_is_compact_and_restores_after_diagnosis_closes() -> None:
+ from PySide6.QtCore import Qt
+
+ from doctor_workstation.app import ApplicationController
+
+ class _Rect:
+ def x(self) -> int:
+ return 0
+
+ def y(self) -> int:
+ return 0
+
+ def width(self) -> int:
+ return 1920
+
+ def height(self) -> int:
+ return 1040
+
+ class _Screen:
+ def availableGeometry(self) -> _Rect: # noqa: N802 - Qt-compatible double
+ return _Rect()
+
+ class _Window:
+ def __init__(self) -> None:
+ self.original_geometry = object()
+ self.original_minimum = object()
+ self.minimum = self.original_minimum
+ self.geometry_value = self.original_geometry
+ self.size = (900, 600)
+ self.position = (30, 40)
+ self.stays_on_top = False
+ self.activated = 0
+
+ def geometry(self) -> object:
+ return self.geometry_value
+
+ def minimumSize(self) -> object: # noqa: N802 - Qt-compatible double
+ return self.minimum
+
+ def isMaximized(self) -> bool: # noqa: N802 - Qt-compatible double
+ return False
+
+ def isFullScreen(self) -> bool: # noqa: N802 - Qt-compatible double
+ return False
+
+ def windowFlags(self) -> Qt.WindowType: # noqa: N802 - Qt-compatible double
+ return Qt.WindowType.Window
+
+ def screen(self) -> _Screen:
+ return _Screen()
+
+ def showNormal(self) -> None: # noqa: N802 - Qt-compatible double
+ return None
+
+ def showMaximized(self) -> None: # noqa: N802 - Qt-compatible double
+ return None
+
+ def showFullScreen(self) -> None: # noqa: N802 - Qt-compatible double
+ return None
+
+ def setMinimumSize(self, *value: object) -> None: # noqa: N802
+ self.minimum = value[0] if len(value) == 1 else value
+
+ def setWindowFlag(self, _flag: Any, enabled: bool) -> None: # noqa: N802
+ self.stays_on_top = enabled
+
+ def resize(self, width: int, height: int) -> None:
+ self.size = (width, height)
+
+ def move(self, x: int, y: int) -> None:
+ self.position = (x, y)
+
+ def setGeometry(self, geometry: object) -> None: # noqa: N802
+ self.geometry_value = geometry
+
+ def show(self) -> None:
+ return None
+
+ def raise_(self) -> None:
+ return None
+
+ def activateWindow(self) -> None: # noqa: N802 - Qt-compatible double
+ self.activated += 1
+
+ class _Signal:
+ def __init__(self) -> None:
+ self.callbacks: list[Any] = []
+
+ def connect(self, callback: Any) -> None:
+ self.callbacks.append(callback)
+
+ class _Dialog:
+ def __init__(self) -> None:
+ self.finished = _Signal()
+
+ def raise_(self) -> None:
+ return None
+
+ def activateWindow(self) -> None: # noqa: N802 - Qt-compatible double
+ return None
+
+ controller = SimpleNamespace(
+ _video_preview_state=None,
+ _video_preview_generation=0,
+ )
+ controller._restore_video_preview = MethodType( # type: ignore[attr-defined]
+ ApplicationController._restore_video_preview,
+ controller,
+ )
+ window = _Window()
+ dialog = _Dialog()
+
+ ApplicationController._show_video_preview(controller, window, dialog)
+
+ assert window.minimum == (440, 300)
+ assert window.size == (540, 356)
+ assert window.position == (1362, 18)
+ assert window.stays_on_top is True
+ assert len(dialog.finished.callbacks) == 1
+
+ dialog.finished.callbacks[0](0)
+
+ assert window.minimum is window.original_minimum
+ assert window.geometry_value is window.original_geometry
+ assert window.stays_on_top is False
+ assert window.activated == 1
+
+
+def test_video_patient_case_snapshot_is_bounded_and_clinically_useful() -> None:
+ from doctor_workstation.app import _build_video_patient_case
+
+ summary = _build_video_patient_case(
+ {
+ "diagnosis": {
+ "patient_name": "张三",
+ "id": 8279,
+ "source_patient_id": 42,
+ "gender": 1,
+ "age": 47,
+ "chief_complaint": "反复口渴三个月",
+ "present_illness": "近期空腹血糖偏高",
+ "allergy_history": "青霉素",
+ "current_medicine": ["二甲双胍", "阿卡波糖"],
+ "clinical_diagnosis": "2 型糖尿病",
+ },
+ "appointment": {"appointment_date": "2026-08-26"},
+ "internal_audit": {"token": "must-not-cross-the-bridge"},
+ },
+ {},
+ diagnosis_id=8279,
+ patient_id=42,
+ patient_name="患者",
+ )
+
+ assert summary["diagnosisId"] == "8279"
+ assert summary["name"] == "张三"
+ assert summary["gender"] == "男"
+ assert summary["age"] == "47"
+ assert summary["chiefComplaint"] == "反复口渴三个月"
+ assert summary["currentMedication"] == "二甲双胍、阿卡波糖"
+ assert summary["allergyHistory"] == "青霉素"
+ assert "internal_audit" not in summary
+ assert set(summary) == {
+ "diagnosisId",
+ "name",
+ "gender",
+ "age",
+ "height",
+ "weight",
+ "diagnosisDate",
+ "appointmentDate",
+ "clinicalDiagnosis",
+ "chiefComplaint",
+ "presentIllness",
+ "pastHistory",
+ "allergyHistory",
+ "personalHistory",
+ "familyHistory",
+ "currentMedication",
+ "tongue",
+ "pulse",
+ "prescriptionOpinion",
+ "remark",
+ }
+
+ bounded = _build_video_patient_case(
+ {},
+ {
+ "diagnosis_id": 8279,
+ "patient_id": 42,
+ "patient_name": "患" * 180,
+ "age": "4" * 40,
+ "remark": "病" * 2400,
+ },
+ diagnosis_id=8279,
+ patient_id=42,
+ patient_name="患者",
+ )
+ assert len(bounded["name"]) == 120
+ assert len(bounded["age"]) == 20
+ assert len(bounded["remark"]) == 2000
+
+
+@pytest.mark.parametrize(
+ "detail",
+ [
+ {
+ "id": 8279,
+ "source_patient_id": 42,
+ "patient_name": "张三",
+ "chief_complaint": "口渴",
+ },
+ {
+ "data": {
+ "id": 8279,
+ "source_patient_id": 42,
+ "patient_name": "张三",
+ "chief_complaint": "口渴",
+ }
+ },
+ {
+ "diagnosis": {
+ "id": 8279,
+ "source_patient_id": 42,
+ "patient_name": "张三",
+ "chief_complaint": "口渴",
+ }
+ },
+ ],
+)
+def test_video_patient_case_accepts_supported_readonly_detail_shapes(detail: object) -> None:
+ from doctor_workstation.app import _build_video_patient_case
+
+ summary = _build_video_patient_case(
+ detail,
+ {},
+ diagnosis_id=8279,
+ patient_id=42,
+ patient_name="患者",
+ )
+
+ assert summary["name"] == "张三"
+ assert summary["chiefComplaint"] == "口渴"
+
+
+def test_video_patient_case_fails_closed_on_identity_mismatch() -> None:
+ from doctor_workstation.app import _build_video_patient_case
+
+ summary = _build_video_patient_case(
+ {
+ "diagnosis": {
+ "id": 9001,
+ "source_patient_id": 7,
+ "patient_name": "其他患者",
+ "chief_complaint": "不得展示",
+ "allergy_history": "不得展示",
+ }
+ },
+ {
+ "diagnosis_id": 9001,
+ "patient_id": 7,
+ "chief_complaint": "也不得展示",
+ },
+ diagnosis_id=8279,
+ patient_id=42,
+ patient_name="张三",
+ )
+
+ assert summary["name"] == "张三"
+ assert summary["chiefComplaint"] == ""
+ assert summary["allergyHistory"] == ""
+
+
+def test_built_video_companion_contains_the_patient_case_rail() -> None:
+ dist_root = PROJECT_ROOT / "video_companion" / "dist"
+ styles = "\n".join(
+ path.read_text(encoding="utf-8") for path in (dist_root / "assets").glob("*.css")
+ )
+ scripts = "\n".join(
+ path.read_text(encoding="utf-8") for path in (dist_root / "assets").glob("*.js")
+ )
+
+ assert ".consultation-rail" in styles
+ assert ".video-layer--with-rail" in styles
+ assert "patientCase" in scripts
+ assert "患者病例与实时对话" in scripts
+
+
def test_companion_screenshot_requires_doctor_confirmation_before_upload() -> None:
source = (PROJECT_ROOT / "video_companion" / "src" / "App.vue").read_text(
encoding="utf-8"
diff --git a/app/video_companion/dist/assets/index-BMSk91Wa.css b/app/video_companion/dist/assets/index-BMSk91Wa.css
new file mode 100644
index 000000000..583f49d13
--- /dev/null
+++ b/app/video_companion/dist/assets/index-BMSk91Wa.css
@@ -0,0 +1 @@
+:root{font-family:Microsoft YaHei UI,PingFang SC,Noto Sans CJK SC,system-ui,sans-serif;color:#132238;background:#eef3fb;font-synthesis:none;text-rendering:optimizeLegibility}*{box-sizing:border-box}html,body,#app{width:100%;height:100%;margin:0;overflow:hidden}button,textarea,input{font:inherit}button{cursor:pointer}button:disabled{cursor:not-allowed;opacity:.55}.consultation-shell{width:100%;height:100%;min-width:760px;min-height:540px;background:#eef3fb}.chat-panel{display:grid;grid-template-rows:74px minmax(0,1fr) auto;width:100%;height:100%;background:#f7f9fd}.chat-header{display:flex;align-items:center;gap:14px;padding:12px 20px;border-bottom:1px solid #d7dfef;background:#fffffff5}.patient-avatar{display:grid;place-items:center;width:44px;height:44px;border-radius:14px;color:#fff;background:#5267df;font-size:18px;font-weight:700}.chat-heading{min-width:0;flex:1}.chat-heading h1{margin:0;font-size:18px;line-height:1.4}.chat-heading p{display:flex;align-items:center;gap:7px;margin:3px 0 0;color:#71809a;font-size:12px}.connection-dot{width:7px;height:7px;border-radius:50%;background:#a3adbd}.connection-dot--online{background:#24a77c;box-shadow:0 0 0 3px #24a77c1f}.primary-action,.send-button,.capture-button{border:1px solid #5166df;border-radius:9px;color:#fff;background:#5267df;font-weight:600}.secondary-action{padding:9px 13px;border:1px solid #c8d2e7;border-radius:9px;color:#43526b;background:#fff;font-weight:600}.secondary-action:hover{border-color:#7385e9;color:#4055ca;background:#f5f7ff}.primary-action{display:flex;gap:8px;align-items:center;padding:10px 16px}.primary-action:hover,.send-button:hover,.capture-button:hover{background:#4055ca}.message-list{overflow-y:auto;padding:18px max(24px,calc((100% - 920px)/2));background:radial-gradient(circle at 12% 16%,rgba(82,103,223,.055),transparent 25%),#f3f6fb}.load-more{display:block;margin:0 auto 18px;padding:6px 12px;border:1px solid #d6deed;border-radius:999px;color:#66758e;background:#fff;font-size:12px}.empty-chat{display:grid;justify-items:center;margin-top:min(16vh,110px);color:#7c89a0;text-align:center}.empty-chat__icon{display:grid;place-items:center;width:62px;height:62px;margin-bottom:12px;border:1px solid #d2daeb;border-radius:20px;color:#5267df;background:#fff;font-weight:800}.empty-chat h2{margin:0;color:#34425a;font-size:17px}.empty-chat p{margin:7px 0;font-size:13px}.message-row{display:flex;flex-direction:column;align-items:flex-start;margin:12px 0}.message-row--mine{align-items:flex-end}.message-row--call-status{align-items:center;margin:16px 0}.call-status-event{display:inline-flex;align-items:center;gap:8px;min-height:32px;padding:0 12px;border:1px solid #dce2f2;border-radius:999px;color:#617092;background:#ffffffeb;font-size:12px;box-shadow:0 4px 14px #111f460a}.call-status-event__icon{display:grid;place-items:center;width:20px;height:20px;border-radius:7px;color:#5761f4;background:#eef0ff;font-size:11px}.call-status-event strong{color:#34425f;font-weight:700}.call-status-event time{color:#8b97b2;font-variant-numeric:tabular-nums}.call-status-event--connected{border-color:#bdebdc;background:#f2fbf7}.call-status-event--connected .call-status-event__icon{color:#11986f;background:#dff7ee}.call-status-event--failed{border-color:#f3c8cf;background:#fff5f6}.call-status-event--failed .call-status-event__icon{color:#c43f50;background:#ffe6e9}.message-meta{margin:0 8px 5px;color:#8995a9;font-size:11px}.message-bubble{max-width:min(72%,620px);padding:10px 13px;border:1px solid #d8e0ed;border-radius:5px 15px 15px;background:#fff;box-shadow:0 4px 14px #1d2f500d;line-height:1.6;word-break:break-word}.message-row--mine .message-bubble{border-color:#5267df;border-radius:15px 5px 15px 15px;color:#fff;background:#5267df}.message-bubble p{margin:0;white-space:pre-wrap}.message-image,.message-video{display:block;max-width:360px;max-height:280px;border-radius:9px}.message-file{display:flex;align-items:center;gap:8px;color:inherit;text-decoration:none}.message-bubble audio{max-width:320px}.composer{padding:10px 18px 14px;border-top:1px solid #d7dfef;background:#fff}.composer-toolbar{display:flex;align-items:center;justify-content:space-between;min-height:30px;color:#8a96a9;font-size:11px}.composer-toolbar button{padding:5px 9px;border:0;border-radius:7px;color:#5267df;background:#eef1ff;font-size:12px}.composer-row{display:grid;grid-template-columns:minmax(0,1fr) 86px;gap:12px}.composer textarea{width:100%;min-height:68px;max-height:150px;padding:10px 12px;resize:vertical;border:1px solid #ced8ea;border-radius:10px;outline:none;color:#15233a;background:#fbfcff;line-height:1.5}.composer textarea:focus{border-color:#6678ed;box-shadow:0 0 0 3px #5267df1c}.send-button{align-self:end;height:40px}.inline-notice{margin-bottom:7px;color:#3f6f62;font-size:12px}.inline-notice--error{color:#c14455}.video-layer{position:relative;display:grid;grid-template-columns:minmax(0,1fr);width:100%;height:100%;min-height:420px;overflow:hidden;color:#f7f8fa;background:radial-gradient(circle at 50% 35%,rgba(60,86,130,.28),transparent 38%),#090d14}.video-layer--with-rail{grid-template-columns:minmax(0,1fr) clamp(330px,31vw,380px)}.video-layer--overlay{position:fixed;z-index:1000;inset:0}.video-stage{position:relative;min-width:0;min-height:0;overflow:hidden;background:radial-gradient(circle at 50% 35%,rgba(60,86,130,.28),transparent 38%),#090d14}.call-kit,.video-layer :is(.TUICallKit-desktop,.TUICallKit-mobile,#tuicallkit-id){width:100%!important;height:100%!important;max-width:none!important;max-height:none!important}.status-card{position:absolute;inset:50% auto auto 50%;display:grid;grid-template-columns:12px minmax(0,1fr);gap:18px;width:min(520px,calc(100% - 48px));padding:30px 32px;transform:translate(-50%,-50%);border:1px solid rgba(255,255,255,.1);border-radius:20px;background:#131920eb;box-shadow:0 24px 70px #00000052}.eyebrow{margin:0 0 12px;color:#a3afbf;font-size:12px;font-weight:700;letter-spacing:.12em}.status-card h2{margin:0;font-size:clamp(22px,3.2vw,34px);font-weight:600;line-height:1.25}.status-hint{margin:14px 0 0;color:#9aa5b1;font-size:14px}.status-dot{width:10px;height:10px;margin-top:5px;border-radius:50%;background:#77818c;box-shadow:0 0 0 5px #77818c1f}.status-dot--starting,.status-dot--live{background:#52c99a;box-shadow:0 0 0 5px #52c99a24}.status-dot--error{background:#f26d6d;box-shadow:0 0 0 5px #f26d6d24}.live-status{position:absolute;z-index:20;top:18px;left:50%;display:flex;align-items:center;gap:10px;padding:9px 14px;transform:translate(-50%);border:1px solid rgba(255,255,255,.1);border-radius:999px;background:#0b0f14cc;font-size:13px}.live-status .status-dot{width:7px;height:7px;margin:0;box-shadow:none}.consultation-rail{position:relative;z-index:55;display:grid;grid-template-rows:auto minmax(0,1.08fr) minmax(0,.92fr);min-width:0;min-height:0;overflow:hidden;border-left:1px solid #dce3f0;color:#15233a;background:#f6f8fc;box-shadow:-16px 0 38px #040c1a29}.consultation-rail__header{display:grid;grid-template-columns:42px minmax(0,1fr) auto;gap:11px;align-items:center;min-height:74px;padding:13px 16px;border-bottom:1px solid #e2e7f1;background:#fff}.consultation-rail__avatar{display:grid;place-items:center;width:42px;height:42px;border-radius:13px;color:#fff;background:#5761f4;font-size:17px;font-weight:700}.consultation-rail__identity{display:grid;gap:3px;min-width:0}.consultation-rail__identity strong{overflow:hidden;color:#111f46;font-size:16px;line-height:1.3;text-overflow:ellipsis;white-space:nowrap}.consultation-rail__identity span{overflow:hidden;color:#7886a3;font-size:11px;text-overflow:ellipsis;white-space:nowrap}.diagnosis-chip{padding:5px 7px;border-radius:6px;color:#4a56d5;background:#eef0ff;font-size:10px;font-weight:700;font-variant-numeric:tabular-nums;white-space:nowrap}.consultation-rail__actions{display:grid;flex:0 0 auto;justify-items:end;gap:5px}.open-diagnosis-button{display:inline-flex;align-items:center;gap:4px;min-height:28px;padding:5px 8px;border:1px solid #cfd5ff;border-radius:7px;color:#3f4bc5;background:#fff;font-size:11px;font-weight:700;white-space:nowrap}.open-diagnosis-button:hover,.open-diagnosis-button:focus-visible{border-color:#6874e7;background:#f3f4ff;outline:none}.open-diagnosis-button:disabled{cursor:not-allowed;opacity:.55}.case-panel,.transcript-panel{display:grid;grid-template-rows:auto minmax(0,1fr);min-height:0;overflow:hidden}.case-panel{border-bottom:1px solid #dde4f0}.rail-section-heading{display:flex;align-items:center;justify-content:space-between;gap:12px;min-height:48px;padding:10px 16px;border-bottom:1px solid #e5e9f2;background:#ffffffb8}.rail-section-heading>div{display:flex;align-items:center;gap:8px}.rail-section-heading h2{margin:0;color:#1b2945;font-size:14px;font-weight:700;letter-spacing:-.01em}.rail-section-heading>span{overflow:hidden;max-width:154px;color:#8b97ad;font-size:10px;text-overflow:ellipsis;white-space:nowrap}.rail-section-heading__index{color:#6874e7;font-family:Cascadia Mono,SFMono-Regular,Consolas,monospace;font-size:10px;font-weight:700}.case-panel__content,.live-captions{min-height:0;overflow-y:auto;overscroll-behavior:contain;scrollbar-color:#b9c3d5 transparent;scrollbar-width:thin}.case-panel__content{padding:5px 16px 14px}.case-field-list{display:grid}.case-field{display:grid;grid-template-columns:72px minmax(0,1fr);gap:10px;padding:10px 0;border-bottom:1px solid #e5e9f2}.case-field:last-child{border-bottom:0}.case-field>span{padding-top:2px;color:#7a879d;font-size:11px;font-weight:600}.case-field p{margin:0;color:#263551;font-size:12px;line-height:1.55;overflow-wrap:anywhere;white-space:pre-wrap}.case-field--risk>span{color:#bc3e4e}.case-field--risk p{color:#9f3141;font-weight:600}.live-captions{display:grid;align-content:start;gap:9px;padding:12px 14px 18px;background:#f2f5fa}.caption-entry{padding:10px 11px;border-left:2px solid #6571e8;border-radius:0 9px 9px 0;background:#fff;box-shadow:0 4px 14px #1e2e4c0b}.caption-entry--partial{border-left-color:#9ca6b7;opacity:.78}.caption-entry header{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:5px}.caption-entry strong{color:#4a56d5;font-size:11px}.caption-entry time{color:#9aa5b7;font-size:10px;font-variant-numeric:tabular-nums}.caption-entry p{margin:0;color:#24334e;font-size:13px;line-height:1.58;overflow-wrap:anywhere;white-space:pre-wrap}.transcript-state{position:relative;padding-left:12px}.transcript-state:before{position:absolute;top:50%;left:0;width:6px;height:6px;transform:translateY(-50%);border-radius:50%;background:#a5adbb;content:""}.transcript-state--active{color:#168260!important}.transcript-state--active:before{background:#24b987;box-shadow:0 0 0 3px #24b9871f}.rail-empty{display:grid;gap:5px;align-content:center;min-height:112px;padding:18px;color:#8a96aa;text-align:center}.rail-empty strong{color:#53617a;font-size:12px}.rail-empty span{font-size:11px;line-height:1.55}.rail-empty--case{min-height:100%}.video-actions{position:absolute;z-index:40;right:22px;bottom:24px;display:flex;gap:10px}.video-actions button{padding:10px 15px;border-radius:10px;font-weight:600}.recording-status{display:inline-flex;align-items:center;gap:8px;padding:10px 15px;border:1px solid rgba(255,255,255,.24);border-radius:10px;color:#fff;background:#161d27e0;font-size:13px;font-weight:600}.recording-status--active{border-color:#f46373a3;background:#7e2332e6}.recording-status--error{border-color:#f26d6d8f;color:#ffe4e7;background:#641f28e0}.recording-indicator{width:9px;height:9px;border-radius:50%;background:#f46373;box-shadow:0 0 0 4px #f4637329}.recording-status--active .recording-indicator{animation:recording-pulse 1.25s ease-in-out infinite}@keyframes recording-pulse{50%{box-shadow:0 0 0 8px #f463730a;opacity:.72}}.hangup-button{border:1px solid #b44755;color:#fff;background:#a12f3de6}.hangup-button:hover{background:#be394d}.video-notice{position:absolute;z-index:40;left:22px;bottom:26px;max-width:calc(100% - 420px);padding:9px 12px;border:1px solid rgba(82,201,154,.35);border-radius:9px;color:#d9f8eb;background:#144e3ed6;font-size:13px}.video-notice--error{border-color:#f26d6d66;color:#ffe4e7;background:#641f28e0}.screenshot-dialog-backdrop{position:absolute;z-index:120;inset:0;display:grid;place-items:center;padding:24px;background:#070b13c2;backdrop-filter:blur(5px)}.screenshot-dialog{display:grid;grid-template-rows:auto minmax(0,1fr) auto auto;gap:14px;width:min(920px,92vw);max-height:calc(100vh - 48px);padding:20px;overflow:hidden;border:1px solid #e2e7f4;border-radius:18px;color:#111f46;background:#fff;box-shadow:0 28px 90px #040a1b57}.screenshot-dialog>header,.screenshot-dialog>footer{display:flex;align-items:center;justify-content:space-between;gap:16px}.screenshot-dialog h2{margin:2px 0 0;font-size:20px;line-height:1.35}.screenshot-dialog .eyebrow{margin:0;color:#5761f4}.screenshot-dialog>header>button{width:36px;height:36px;border:0;border-radius:9px;color:#7886aa;background:#f2f4fb;font-size:24px}.screenshot-preview-frame{display:grid;place-items:center;min-height:260px;overflow:hidden;border-radius:12px;background:#0b0f16}.screenshot-preview-frame img{display:block;max-width:100%;max-height:min(62vh,650px);object-fit:contain}.screenshot-dialog__hint{margin:0;color:#617092;font-size:13px}.screenshot-dialog>footer{justify-content:flex-end}.screenshot-dialog>footer button{min-width:112px;padding:10px 18px;border-radius:9px;font-weight:700}.screenshot-cancel{border:1px solid #dfe4f1;color:#3f4e75;background:#fff}.screenshot-confirm{border:1px solid #5761f4;color:#fff;background:#5761f4}.screenshot-confirm:hover{background:#4c57e9}@media (max-width: 820px){.consultation-shell{min-width:620px}.message-list{padding-inline:18px}.message-bubble{max-width:82%}}@media (max-width: 980px){.consultation-shell{min-width:760px}.video-layer--with-rail{grid-template-columns:minmax(0,1fr) 310px}.video-actions{right:12px;bottom:14px;left:12px;flex-wrap:wrap;justify-content:flex-end}.recording-status{flex-basis:100%;width:fit-content;margin-left:auto;font-size:11px}.consultation-rail__header{padding-inline:12px}.diagnosis-chip{display:none}.case-panel__content,.rail-section-heading{padding-inline:12px}}@media (max-width: 700px){.consultation-shell{min-width:0}.video-layer,.video-stage{min-height:280px}.video-layer--with-rail{grid-template-columns:minmax(0,1fr)}.consultation-rail{display:none}.video-actions{right:10px;bottom:10px;left:auto;gap:6px}.recording-status,.capture-button{display:none}.video-actions button{padding:8px 11px;border-radius:8px;font-size:11px}.live-status{top:10px;padding:7px 10px;font-size:11px}}:root{color:#111f46;background:#eef3fd}.consultation-shell{background:#eef3fd}.chat-panel{background:#f7f9fe}.chat-header,.composer{border-color:#e6eaf5;background:#fffffffa}.patient-avatar{background:linear-gradient(135deg,#5761f4,#7769f7)}.chat-heading p,.empty-chat,.message-meta,.composer-toolbar{color:#7886aa}.connection-dot--online{background:#17a77d;box-shadow:0 0 0 3px #17a77d1f}.primary-action,.send-button,.capture-button{border-color:#5761f4;background:linear-gradient(90deg,#5761f4,#7769f7)}.primary-action:hover,.send-button:hover,.capture-button:hover{background:#4c57e9}.secondary-action{border-color:#e6eaf5;color:#3f4e75}.secondary-action:hover{border-color:#5761f4;color:#4451e2;background:#f0f2ff}.message-list{background:radial-gradient(circle at 12% 16%,rgba(87,97,244,.055),transparent 25%),#f7f9fe}.load-more,.empty-chat__icon,.message-bubble{border-color:#e6eaf5}.load-more{color:#7886aa}.empty-chat__icon{color:#5761f4}.empty-chat h2{color:#111f46}.message-bubble{box-shadow:0 4px 14px #111f460d}.message-row--mine .message-bubble{border-color:#5761f4;background:#5761f4}.composer-toolbar button{color:#4451e2;background:#f0f2ff}.composer textarea{border-color:#e6eaf5;color:#111f46;background:#fafbfe}.composer textarea:focus{border-color:#8d9bff;box-shadow:0 0 0 3px #5761f41c}.video-actions button{border-radius:9px}.recording-status{border-color:#e6eaf5e0;border-radius:9px;color:#3f4e75;background:#fffffff2}.recording-status--active,.recording-status--error{border-color:#f15b6773;color:#b63849;background:#fff1f3f5}.recording-indicator{background:#f15b67;box-shadow:0 0 0 4px #f15b6729}@keyframes recording-pulse{50%{box-shadow:0 0 0 8px #f15b670a;opacity:.72}}.hangup-button{border-color:#f15b67;background:#f15b67}.hangup-button:hover{background:#d94857}.video-notice{border-color:#17a77d59;color:#12765b;background:#eaf9f3f2}.video-notice--error{border-color:#f15b6766;color:#b63849;background:#fff1f3f5}
diff --git a/app/video_companion/dist/assets/index-DhmAWjut.js b/app/video_companion/dist/assets/index-B_ek5NUi.js
similarity index 71%
rename from app/video_companion/dist/assets/index-DhmAWjut.js
rename to app/video_companion/dist/assets/index-B_ek5NUi.js
index 9e92d0ff6..cfe9f983f 100644
--- a/app/video_companion/dist/assets/index-DhmAWjut.js
+++ b/app/video_companion/dist/assets/index-B_ek5NUi.js
@@ -1,4 +1,4 @@
-(function(){const i=document.createElement("link").relList;if(i&&i.supports&&i.supports("modulepreload"))return;for(const I of document.querySelectorAll('link[rel="modulepreload"]'))l(I);new MutationObserver(I=>{for(const h of I)if(h.type==="childList")for(const f of h.addedNodes)f.tagName==="LINK"&&f.rel==="modulepreload"&&l(f)}).observe(document,{childList:!0,subtree:!0});function r(I){const h={};return I.integrity&&(h.integrity=I.integrity),I.referrerPolicy&&(h.referrerPolicy=I.referrerPolicy),I.crossOrigin==="use-credentials"?h.credentials="include":I.crossOrigin==="anonymous"?h.credentials="omit":h.credentials="same-origin",h}function l(I){if(I.ep)return;I.ep=!0;const h=r(I);fetch(I.href,h)}})();var mg=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function BW(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function GU(t){if(t.__esModule)return t;var i=t.default;if(typeof i=="function"){var r=function l(){return this instanceof l?Reflect.construct(i,arguments,this.constructor):i.apply(this,arguments)};r.prototype=i.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(t).forEach(function(l){var I=Object.getOwnPropertyDescriptor(t,l);Object.defineProperty(r,l,I.get?I:{enumerable:!0,get:function(){return t[l]}})}),r}var W1={exports:{}},LoA=W1.exports,e8;function UoA(){return e8||(e8=1,function(t,i){(function(r,l){t.exports=l()})(LoA,function(){const r=s=>s===void 0,l=s=>typeof s=="string",I=s=>{var n;return(n=Object.prototype.toString.call(s).match(/^\[object (.*)\]$/))===null||n===void 0?void 0:n[1].toLowerCase()},h=s=>typeof Array.isArray=="function"?Array.isArray(s):I(s)==="array",f=s=>s!==null&&typeof s=="object",w=s=>h(s)||f(s),_=s=>{if(typeof s!="string")return!1;const n=s[0];return!/[^a-zA-Z0-9]/.test(n)},k=s=>{if(typeof s!="object"||s===null)return!1;const n=Object.getPrototypeOf(s);if(n===null)return!0;let g=n;for(;Object.getPrototypeOf(g)!==null;)g=Object.getPrototypeOf(g);return n===g};function U(s=99999999){return Math.round(Math.random()*s)}const j=(s,n,g,u)=>{if(!w(s)||!w(n))return 0;let E=0;const m=Object.keys(n);let D;for(let M=0,T=m.length;M"u"&&typeof uni.requireNativePlugin=="function",to=Le&&typeof wx.miniapp=="object",uo=typeof uni<"u",Vs=Dt&&typeof tt.enterChat=="function",ki=Le||je||Dt||Jt||gi||To||Fi,ns=typeof window>"u"&&!ki&&typeof mg<"u"&&mg.NativeScriptGlobals!==void 0,jo=typeof mg<"u"&&(mg.nativeModuleProxy!==void 0||mg.ReactNative!==void 0),$i=typeof wx<"u"&&typeof wx.getAccountInfoSync=="function"&&!!wx.getAccountInfoSync().plugin,jt=typeof uni<"u"?!ki:typeof window<"u"&&!ki&&!jo,io=je?qq:Dt?tt:Jt?swan:gi?my:Le?wx:To?uni:Fi?jd:{},bi=jt&&window&&window.navigator&&window.navigator.userAgent||"",vs=/(micromessenger|webbrowser)/i.test(bi),HA=function(){let s="WEB";return vs?s="WEB":je?s="QQ_MP":Dt?s="TT_MP":Jt?s="BAIDU_MP":gi?s="ALI_MP":Le?s=to?"DONUT_NATIVE_APP":"WX_MP":To?s="UNI_NATIVE_APP":ns?s="NS_NATIVE_APP":jo&&(s="RN_NATIVE_APP"),rA[s]}(),ce=/iPad/i.test(bi),Ve=/iPhone/i.test(bi)&&!ce,Ut=/iPod/i.test(bi),nt=Ve||ce||Ut,It=function(){const s=bi.match(/OS (\d+)_/i);return s&&s[1]?s[1]:null}(),Xt=/Android/i.test(bi),$t=function(){const s=bi.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(!s)return null;const n=s[1]&&parseFloat(s[1]),g=s[2]&&parseFloat(s[2]);return n&&g?parseFloat(`${s[1]}.${s[2]}`):n||null}(),be=/Firefox/i.test(bi),Xe=/Edge/i.test(bi),vt=!Xe&&/Chrome/i.test(bi),wt=/MSIE/.test(bi)||bi.indexOf("Trident")>-1&&bi.indexOf("rv:11.0")>-1,Oi=function(){const s=/MSIE\s(\d+)\.\d/.exec(bi);let n=s&&parseFloat(s[1]);return!n&&/Trident\/7.0/i.test(bi)&&/rv:11.0/.test(bi)&&(n=11),n}(),po=/Safari/i.test(bi)&&!vt&&!Xt&&!Xe,No=/Windows/i.test(bi),oo=/MAC OS X/i.test(bi),Go=jt&&typeof Worker<"u"&&!wt,An=Xt||nt,rn=function(){if(typeof window>"u"||window.navigator===void 0)return!1;const{standalone:s}=window.navigator;return!(!nt||s||po)}();function Es(){let s="unknown";if(oo&&(s="mac"),No&&(s="windows"),nt&&(s="ios"),Xt&&(s="android"),ki)try{const{platform:n}=io.getSystemInfoSync();n!==void 0&&(s=n)}catch(n){console.error(n)}return s}const an=typeof process<"u"&&process.versions!==void 0&&process.versions.node!==void 0&&typeof window>"u";function Do(s,n){var g={};for(var u in s)Object.prototype.hasOwnProperty.call(s,u)&&n.indexOf(u)<0&&(g[u]=s[u]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function"){var E=0;for(u=Object.getOwnPropertySymbols(s);E{io.request({url:g,data:u,method:n,timeout:E,header:{"content-type":zr},success:M=>m(M.data),fail:()=>D(new Error(`{"message":"Network error","code":${Jn}}`))})}):an?void 0:new Promise((m,D)=>{const M=new XMLHttpRequest,T=setTimeout(()=>{M.abort(),D(new Error(`{"message":"Request timeout","code":${Qr}}`))},E);M.onreadystatechange=function(){if(M.readyState===4)if(clearTimeout(T),M.status===200||M.status===304)try{m(M.responseText?JSON.parse(M.responseText):null)}catch{m(M.responseText)}else D(new Error(`{"message":"Network error","code":${Jn}}`))},M.open(n,g,!0),M.setRequestHeader("Content-type",zr),M.send(u||null)})})}function Rs(s){if(s==null)return!0;if(typeof s=="boolean")return!1;if(typeof s=="number")return s===0;if(typeof s=="string"||typeof s=="function"||Array.isArray(s))return s.length===0;if(s instanceof Error)return s.message==="";if(k(s)){for(const n in s)if(Object.prototype.hasOwnProperty.call(s,n))return!1;return!0}return(Object.prototype.toString.call(s)==="[object Map]"||Object.prototype.toString.call(s)==="[object Set]"||Object.prototype.toString.call(s)==="[object File]")&&s.size===0}function or(s,n){if(s===null||typeof s!="object")return s;const g=n||new WeakMap;if(g.has(s))return g.get(s);if(s instanceof Date)return new Date(s.getTime());if(s instanceof RegExp)return new RegExp(s.source,s.flags);if(s instanceof Map){const m=new Map;return g.set(s,m),s.forEach((D,M)=>{m.set(or(M,g),or(D,g))}),m}if(s instanceof Set){const m=new Set;return g.set(s,m),s.forEach(D=>{m.add(or(D,g))}),m}if(Array.isArray(s)){const m=[];return g.set(s,m),s.forEach(D=>{m.push(or(D,g))}),m}const u=Object.getPrototypeOf(s),E=Object.create(u);return g.set(s,E),[...Object.getOwnPropertyNames(s),...Object.getOwnPropertySymbols(s)].forEach(m=>{if(m==="__ob__"||m==="__v_skip"||m==="__v_isRef"||m==="__v_isReadonly")return;const D=Object.getOwnPropertyDescriptor(s,m);D&&(D.get||D.set?Object.defineProperty(E,m,D):E[m]=or(s[m],g))}),E}function en(s,n,g){const u=new WeakSet,E=(m,D)=>{if(n&&(D=n(m,D)),D===void 0)return"undefined";if(D===null)return null;if(Number.isNaN(D))return"NaN";if(D===1/0)return"Infinity";if(D===-1/0)return"-Infinity";if(typeof D=="function")return`[Function: ${D.name||"anonymous"}]`;if(typeof D=="symbol")return D.toString();if(typeof D=="bigint")return`${D.toString()}n`;if(typeof D=="object"&&D!==null){if(u.has(D))return"[Circular]";u.add(D)}return D instanceof Date?D.toISOString():D instanceof Error?{name:D.name,message:D.message}:D instanceof Map?{dataType:"Map",value:Array.from(D.entries())}:D instanceof Set?{dataType:"Set",value:Array.from(D.values())}:D};try{return JSON.stringify(s,E,g)}catch(m){return console.error("Failed to stringify:",m),""}}function wn(){let s,n;return{promise:new Promise((g,u)=>{s=g,n=u}),resolve:s,reject:n}}var Ht,yg=Object.freeze({__proto__:null,ANDROID_VERSION:$t,IE_VERSION:Oi,IN_ALIPAY_MINI_APP:gi,IN_BAIDU_MINI_APP:Jt,IN_BROWSER:jt,IN_DONUT_NATIVE_APP:to,IN_FEISHU_MINI_APP:Vs,IN_JD_MINI_APP:Fi,IN_MINI_APP:ki,IN_NODE:an,IN_NS_NATIVE_APP:ns,IN_QQ_MINI_APP:je,IN_RN_APP:jo,IN_TT_MINI_APP:Dt,IN_TT_MINI_GAME:ni,IN_UNI_APP:uo,IN_UNI_NATIVE_APP:To,IN_WX_MINI_APP:Le,IN_WX_MINI_APP_DESK:We,IN_WX_MINI_GAME:oe,IN_WX_MINI_PLUGIN:$i,IOS_VERSION:It,IS_ANDROID:Xt,IS_CHROME:vt,IS_EDGE:Xe,IS_FIREFOX:be,IS_IE:wt,IS_IOS:nt,IS_IPAD:ce,IS_IPHONE:Ve,IS_IPOD:Ut,IS_MAC:oo,IS_SAFARI:po,IS_WECHAT:vs,IS_WIN:No,IS_WORKER_AVAILABLE:Go,MINI_APP_NAMESPACE:io,USER_AGENT:bi,base16EncodeBinaryString:lA,deepCopyWithMethods:or,deepMerge:j,generatePromise:wn,getPlatformType:Es,getType:I,httpRequest:Pi,isArray:h,isArrayOrObject:w,isEmpty:Rs,isH5:An,isIOSWebView:rn,isNumber:s=>s!==null&&(typeof s=="number"&&!Number.isNaN(s-0)||typeof s=="object"&&s.constructor===Number),isObject:f,isPlainObject:k,isString:l,isUndefined:r,isUniIOSApp:function(){return To&&uni.getDeviceInfo().platform.toLocaleLowerCase()==="ios"},isValidRequestKey:_,platform:HA,randomInt:U,randomString:function(){const s="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let n="";for(let g=32;g>0;--g)n+=s[Math.floor(62*Math.random())];return n},safeStringify:en});class On{constructor(){this.listeners={}}on(n,g,u){this.listeners[n]||(this.listeners[n]=[]),this.listeners[n].push({fn:g,context:u})}off(n,g,u){var E;g&&(this.listeners[n]=(E=this.listeners[n])===null||E===void 0?void 0:E.filter(m=>{const D=m.fn===g,M=!u||m.context===u;return!(D&&M)}))}emit(n,...g){const u=this.listeners[n];u&&u.forEach(E=>{const{fn:m,context:D}=E;try{m.apply(D,g)}catch(M){console.warn(`Error in event handler for ${n} error: ${en(M)}`)}})}once(n,g,u){const E=(...m)=>{g.apply(u,m),this.off(n,E)};this.on(n,E)}}(function(s){s.BUSINESS_COMMAND="business_command",s.C2C_REALTIME_MESSAGE="c2c_realtime_message",s.C2C_MESSAGE_MODIFIED="c2c_message_modified",s.C2C_REVOKED_MESSAGE="c2c_message_revoked",s.GROUP_REALTIME_MESSAGE="group_realtime_message",s.GROUP_MESSAGE_MODIFIED="group_message_modified",s.GROUP_MESSAGE_REVOKED="group_message_revoked",s.C2C_MESSAGE_READ_RECEIPT="c2c_message_read_receipt",s.MESSAGE_REACTION_UPDATED="message_reaction_updated",s.MESSAGE_REACTION_UPDATED_SYNC="message_reaction_updated_sync",s.GROUP_AT_TIPS="group_at_tips",s.USER_STATUS_UPDATE="user_status_update",s.FRIEND_LIST_MODIFIED="friend_list_modified",s.PROFILE_MODIFIED="profile_modified",s.CONV_MODIFIED="conversation_modified",s.GROUP_TIPS_NOTIFICATION="group_tips_notification",s.GROUP_MESSAGE_READ_RECEIPT="group_message_read_receipt",s.GROUP_MESSAGE_READ_SYNC="group_message_read_sync",s.GROUP_SYSTEM_NOTIFICATION="group_system_notification",s.C2C_MESSAGE_PEER_READ="c2c_message_peer_read",s.C2C_MESSAGE_READ_SYNC="c2c_message_read_sync",s.C2C_REMIND_TYPE_SYNC="c2c_remind_type_sync",s.FOLLOW_LIST_UPDATED="follow_list_updated",s.MESSAGE_EXTENSIONS_UPDATED="message_extensions_updated",s.ALL_MESSAGE_READ="all_message_read",s.CONVERSATION_MARK_UPDATED="conversation_mark_updated",s.CONVERSATION_GROUP_ADD="conversation_group_add",s.CONVERSATION_GROUP_DELETED="conversation_group_deleted",s.CONVERSATION_GROUP_UPDATED="conversation_group_updated",s.ALL_RECEIVE_MESSAGE_OPTION="all_receive_message_option",s.TOPIC_AT_TIPS="topic_at_tips",s.TOPIC_TIPS_NOTIFICATION="topic_tips_notification",s.TOPIC_SYSTEM_NOTIFICATION="topic_system_notification",s.TOPIC_MESSAGE_READ_SYNC="topic_message_read_sync",s.TOPIC_LATEST_MESSAGE="topic_latest_message",s.GROUP_MESSAGE_PINNED="group_message_pinned"})(Ht||(Ht={}));const Gn=[16,17];function Js(s){var n;const g=[];return(n=s?.GroupTips)===null||n===void 0||n.forEach(u=>{var E;u.GroupInfo.MillionGroupFlag===2?g.push(Ht.TOPIC_TIPS_NOTIFICATION):Gn.includes((E=u?.MsgBody)===null||E===void 0?void 0:E.OpType)?g.push(Ht.GROUP_MESSAGE_PINNED):g.push(Ht.GROUP_TIPS_NOTIFICATION)}),g}const pr=[{conditions:[{type:"event",value:100}],subType:Ht.BUSINESS_COMMAND},{conditions:[{type:"event",value:24}],subType:Ht.ALL_RECEIVE_MESSAGE_OPTION},{conditions:[{type:"event",value:26}],subType:Ht.TOPIC_LATEST_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgArray"}],subType:Ht.C2C_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgModNotifys"}],subType:Ht.C2C_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"ProfileDataMod"}],subType:Ht.PROFILE_MODIFIED},{conditions:[{type:"hasKey",value:"UserStatusList"}],subType:Ht.USER_STATUS_UPDATE},{conditions:[{type:"hasKey",value:"FriendListMod"}],subType:Ht.FRIEND_LIST_MODIFIED},{conditions:[{type:"hasKey",value:"GroupMsgArray"}],subType:Ht.GROUP_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"GroupMsgModNotifys"}],subType:Ht.GROUP_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"C2cNotifyMsgArray"}],subTypeParser:function(s){var n;const g=[];return(n=s?.C2cNotifyMsgArray)===null||n===void 0||n.forEach(u=>{u.WithdrawC2cMsgNotify&&g.push(Ht.C2C_REVOKED_MESSAGE),u.C2cReadedReceipt&&g.push(Ht.C2C_MESSAGE_PEER_READ),u.ReadC2cMsgNotify&&g.push(Ht.C2C_MESSAGE_READ_SYNC),u.MuteNotificationsSync&&g.push(Ht.C2C_REMIND_TYPE_SYNC)}),g}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:4}],subTypeParser:Js},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:5}],subTypeParser:function(s){var n;const g=[];return(n=s?.GroupTips)===null||n===void 0||n.forEach(u=>{Array.isArray(u.MsgBody.GroupWithdrawInfoArray)?g.push(Ht.GROUP_MESSAGE_REVOKED):Array.isArray(u.MsgBody.GroupMsgReceiptList)?g.push(Ht.GROUP_MESSAGE_READ_RECEIPT):Array.isArray(u.MsgBody.GroupReadInfoArray)?u.MsgBody.GroupReadInfoArray[0].TopicId?g.push(Ht.TOPIC_MESSAGE_READ_SYNC):g.push(Ht.GROUP_MESSAGE_READ_SYNC):u.GroupInfo.MillionGroupFlag===2?g.push(Ht.TOPIC_SYSTEM_NOTIFICATION):g.push(Ht.GROUP_SYSTEM_NOTIFICATION)}),g}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:6}],subTypeParser:Js},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:12}],subTypeParser:function(s){var n;const g=[];return(n=s?.GroupTips)===null||n===void 0||n.forEach(u=>{const{GroupAtTips:{TopicId:E}}=u;E?g.push(Ht.TOPIC_AT_TIPS):g.push(Ht.GROUP_AT_TIPS)}),g}},{conditions:[{type:"hasKey",value:"RecentContactMod"}],subTypeParser:function(s){var n;const g=[];return(n=s?.RecentContactMod)===null||n===void 0||n.forEach(u=>{switch(u.PushType){case ze.CONV_MARK_UPDATED:g.push(Ht.CONVERSATION_MARK_UPDATED);break;case ze.CONV_GROUP_ADDED:g.push(Ht.CONVERSATION_GROUP_ADD);break;case ze.CONV_GROUP_DELETED:g.push(Ht.CONVERSATION_GROUP_DELETED);break;case ze.CONV_GROUP_UPDATED:g.push(Ht.CONVERSATION_GROUP_UPDATED);break;default:g.push(Ht.CONV_MODIFIED)}}),g}},{conditions:[{type:"hasKey",value:"MsgReactionNotifyList"}],subType:Ht.MESSAGE_REACTION_UPDATED},{conditions:[{type:"hasKey",value:"MsgReactionNotify"}],subType:Ht.MESSAGE_REACTION_UPDATED_SYNC},{conditions:[{type:"hasKey",value:"C2cMsgInfo"}],subType:Ht.C2C_MESSAGE_READ_RECEIPT},{conditions:[{type:"hasKey",value:"FollowChangeList"}],subType:Ht.FOLLOW_LIST_UPDATED},{conditions:[{type:"hasKey",value:"MsgExtensionNotify"}],subType:Ht.MESSAGE_EXTENSIONS_UPDATED},{conditions:[{type:"hasKey",value:"C2CReadAllMsg"}],subType:Ht.ALL_MESSAGE_READ}];var Pn;function mr(s){var n;const g=Array.isArray((n=s?.body)===null||n===void 0?void 0:n.EventArray)?s.body.EventArray:[],u=[];return g.forEach(E=>{E.Flag=s.body.Flag;const m=pr.find(M=>M.conditions.every(T=>{switch(T.type){case"event":return E.Event===T.value;case"hasKey":return Object.prototype.hasOwnProperty.call(E,T.value);default:return!1}}));if(!m)return null;let D=[];typeof m.subTypeParser=="function"?D=m.subTypeParser(E):m.subType&&(D=m.subType),Array.isArray(D)?D.forEach(M=>{u.push({type:`${Pn.SERVER_PUSH_MESSAGE}:${M}`,data:E})}):u.push({type:`${Pn.SERVER_PUSH_MESSAGE}:${D}`,data:E})}),u}(function(s){s.SERVER_PUSH_MESSAGE="im_open_push.msg_push",s.SERVER_PUSH_MESSAGE_MULTIPLE="im_open_push.multi_msg_push_ws",s.ERROR="error"})(Pn||(Pn={}));const mo={[Pn.SERVER_PUSH_MESSAGE]:mr,[Pn.SERVER_PUSH_MESSAGE_MULTIPLE]:mr,[Pn.ERROR]:function(s){const{errorCode:n}=s;return[{type:`error:${n}`,data:s}]}},gn=new class{constructor(){this._outerEventEmitter=null,this._innerEventEmitter=null,this._filteredCallbackMap=new Map,this._outerEventEmitter=new On,this._innerEventEmitter=new On,this.InnerEventSubType=Ht}subscribeInnerEvent(s,n,g,u,E){var m;let D,M,T,P;["string","number"].includes(typeof n)?(T=`${s}:${n}`,P=g,M=u,D=E):(T=s,P=n,M=g,D=typeof u=="function"?u:void 0),D?this._subscribeWithFilter(T,P,M,D):(m=this._innerEventEmitter)===null||m===void 0||m.on(T,P,M)}emitInnerEvent(s,n){var g,u;if((g=this._innerEventEmitter)===null||g===void 0||g.emit(s,n),Object.keys(mo).includes(s)){const E=(u=mo[s])===null||u===void 0?void 0:u.call(mo,n);E?.forEach(m=>{var D;m&&((D=this._innerEventEmitter)===null||D===void 0||D.emit(m.type,m.data))})}}subscribeOuterEvent(s,n,g){var u;(u=this._outerEventEmitter)===null||u===void 0||u.on(s,n,g)}unSubscribeOuterEvent(s,n,g){var u;(u=this._outerEventEmitter)===null||u===void 0||u.off(s,n,g)}unSubscribeInnerEvent(s,n,g,u){if(["string","number"].includes(typeof n)){const E=g,m=`${s}:${n}`;this._unsubscribeEvent(m,E,u)}else{const E=n;this._unsubscribeEvent(s,E,g)}}emitOuterEvent(s,n){var g;(g=this._outerEventEmitter)===null||g===void 0||g.emit(s,n)}getOuterEventEmitter(){return this._outerEventEmitter}rest(){this._outerEventEmitter=null,this._innerEventEmitter=null}_subscribeWithFilter(s,n,g,u){var E;const m=D=>{u.call(g,D)&&n.call(g,D)};this._filteredCallbackMap.has(s)||this._filteredCallbackMap.set(s,[]),this._filteredCallbackMap.get(s).push({originalCallback:n,filteredCallback:m,filter:u,context:g}),(E=this._innerEventEmitter)===null||E===void 0||E.on(s,m,g)}_unsubscribeEvent(s,n,g){var u,E;const m=this._filteredCallbackMap.get(s);if(m){const D=m.findIndex(M=>M.originalCallback===n&&M.context===g);if(D!==-1){const{filteredCallback:M}=m[D];return(u=this._innerEventEmitter)===null||u===void 0||u.off(s,M,g),m.splice(D,1),void(m.length===0&&this._filteredCallbackMap.delete(s))}}(E=this._innerEventEmitter)===null||E===void 0||E.off(s,n,g)}};class Dl{constructor(){this._socket=null}connectSocket(n){return this._socket=new WebSocket(n),this._socket}send(n){var g,u;try{(g=this._socket)===null||g===void 0||g.send(n)}catch(E){(u=this._onSendFail)===null||u===void 0||u.call(this,E)}}bindSocketHandlers(n){const{onOpen:g,onMessage:u,onClose:E,onError:m,onSendFail:D}=n;this._socket&&(this._socket.binaryType="arraybuffer",this._socket.onopen=g,this._socket.onmessage=u,this._socket.onclose=E,this._socket.onerror=m,this._onSendFail=D)}unbindSocketHandlers(){this._socket&&(this._socket.onopen=null,this._socket.onmessage=null,this._socket.onclose=null,this._socket.onerror=null)}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}class cn{constructor(n){this._onError=n.onError}connectSocket(n){const g=this;return this._socket=io.connectSocket({url:n,header:{"content-type":"application/json"},complete:()=>{},fail:u=>g._onError(u)}),this._socket}send(n){var g;(g=this._socket)===null||g===void 0||g.send({data:n,fail:this._onSendFail})}bindSocketHandlers(n){const{onOpen:g,onMessage:u,onClose:E,onError:m,onSendFail:D}=n;this._socket&&(this._socket.onClose(E),this._socket.onOpen(g),this._socket.onMessage(u),this._socket.onError(m),this._onSendFail=D)}unbindSocketHandlers(){this._socket&&(this._socket.onClose(()=>{}),this._socket.onOpen(()=>{}),this._socket.onMessage(()=>{}),this._socket.onError(()=>{}))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}const fr="CONNECT",Ls="SEND",Vc="DISCONNECT",ms="OPEN",as="MESSAGE",Su="CLOSE",Wa="ERROR",Cs="SEND_FAIL";class sg{constructor(){this._worker=null,this._blobUrl=null}connectSocket(n){const g=new Blob([`
+(function(){const i=document.createElement("link").relList;if(i&&i.supports&&i.supports("modulepreload"))return;for(const I of document.querySelectorAll('link[rel="modulepreload"]'))l(I);new MutationObserver(I=>{for(const h of I)if(h.type==="childList")for(const f of h.addedNodes)f.tagName==="LINK"&&f.rel==="modulepreload"&&l(f)}).observe(document,{childList:!0,subtree:!0});function r(I){const h={};return I.integrity&&(h.integrity=I.integrity),I.referrerPolicy&&(h.referrerPolicy=I.referrerPolicy),I.crossOrigin==="use-credentials"?h.credentials="include":I.crossOrigin==="anonymous"?h.credentials="omit":h.credentials="same-origin",h}function l(I){if(I.ep)return;I.ep=!0;const h=r(I);fetch(I.href,h)}})();var mg=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function QW(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function GU(t){if(t.__esModule)return t;var i=t.default;if(typeof i=="function"){var r=function l(){return this instanceof l?Reflect.construct(i,arguments,this.constructor):i.apply(this,arguments)};r.prototype=i.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(t).forEach(function(l){var I=Object.getOwnPropertyDescriptor(t,l);Object.defineProperty(r,l,I.get?I:{enumerable:!0,get:function(){return t[l]}})}),r}var j1={exports:{}},OoA=j1.exports,t8;function PoA(){return t8||(t8=1,function(t,i){(function(r,l){t.exports=l()})(OoA,function(){const r=s=>s===void 0,l=s=>typeof s=="string",I=s=>{var n;return(n=Object.prototype.toString.call(s).match(/^\[object (.*)\]$/))===null||n===void 0?void 0:n[1].toLowerCase()},h=s=>typeof Array.isArray=="function"?Array.isArray(s):I(s)==="array",f=s=>s!==null&&typeof s=="object",w=s=>h(s)||f(s),_=s=>{if(typeof s!="string")return!1;const n=s[0];return!/[^a-zA-Z0-9]/.test(n)},b=s=>{if(typeof s!="object"||s===null)return!1;const n=Object.getPrototypeOf(s);if(n===null)return!0;let g=n;for(;Object.getPrototypeOf(g)!==null;)g=Object.getPrototypeOf(g);return n===g};function U(s=99999999){return Math.round(Math.random()*s)}const j=(s,n,g,u)=>{if(!w(s)||!w(n))return 0;let E=0;const m=Object.keys(n);let D;for(let M=0,T=m.length;M"u"&&typeof uni.requireNativePlugin=="function",to=ut&&typeof wx.miniapp=="object",Eo=typeof uni<"u",Vs=_e&&typeof tt.enterChat=="function",ki=ut||XA||_e||Ut||gi||To||Fi,ns=typeof window>"u"&&!ki&&typeof mg<"u"&&mg.NativeScriptGlobals!==void 0,jo=typeof mg<"u"&&(mg.nativeModuleProxy!==void 0||mg.ReactNative!==void 0),$i=typeof wx<"u"&&typeof wx.getAccountInfoSync=="function"&&!!wx.getAccountInfoSync().plugin,Wt=typeof uni<"u"?!ki:typeof window<"u"&&!ki&&!jo,io=XA?qq:_e?tt:Ut?swan:gi?my:ut?wx:To?uni:Fi?jd:{},bi=Wt&&window&&window.navigator&&window.navigator.userAgent||"",vs=/(micromessenger|webbrowser)/i.test(bi),HA=function(){let s="WEB";return vs?s="WEB":XA?s="QQ_MP":_e?s="TT_MP":Ut?s="BAIDU_MP":gi?s="ALI_MP":ut?s=to?"DONUT_NATIVE_APP":"WX_MP":To?s="UNI_NATIVE_APP":ns?s="NS_NATIVE_APP":jo&&(s="RN_NATIVE_APP"),nA[s]}(),le=/iPad/i.test(bi),Ve=/iPhone/i.test(bi)&&!le,Ft=/iPod/i.test(bi),nt=Ve||le||Ft,It=function(){const s=bi.match(/OS (\d+)_/i);return s&&s[1]?s[1]:null}(),Ai=/Android/i.test(bi),ei=function(){const s=bi.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(!s)return null;const n=s[1]&&parseFloat(s[1]),g=s[2]&&parseFloat(s[2]);return n&&g?parseFloat(`${s[1]}.${s[2]}`):n||null}(),ke=/Firefox/i.test(bi),Ze=/Edge/i.test(bi),vt=!Ze&&/Chrome/i.test(bi),_t=/MSIE/.test(bi)||bi.indexOf("Trident")>-1&&bi.indexOf("rv:11.0")>-1,Oi=function(){const s=/MSIE\s(\d+)\.\d/.exec(bi);let n=s&&parseFloat(s[1]);return!n&&/Trident\/7.0/i.test(bi)&&/rv:11.0/.test(bi)&&(n=11),n}(),po=/Safari/i.test(bi)&&!vt&&!Ai&&!Ze,No=/Windows/i.test(bi),oo=/MAC OS X/i.test(bi),Go=Wt&&typeof Worker<"u"&&!_t,An=Ai||nt,rn=function(){if(typeof window>"u"||window.navigator===void 0)return!1;const{standalone:s}=window.navigator;return!(!nt||s||po)}();function Es(){let s="unknown";if(oo&&(s="mac"),No&&(s="windows"),nt&&(s="ios"),Ai&&(s="android"),ki)try{const{platform:n}=io.getSystemInfoSync();n!==void 0&&(s=n)}catch(n){console.error(n)}return s}const an=typeof process<"u"&&process.versions!==void 0&&process.versions.node!==void 0&&typeof window>"u";function Do(s,n){var g={};for(var u in s)Object.prototype.hasOwnProperty.call(s,u)&&n.indexOf(u)<0&&(g[u]=s[u]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function"){var E=0;for(u=Object.getOwnPropertySymbols(s);E{io.request({url:g,data:u,method:n,timeout:E,header:{"content-type":zr},success:M=>m(M.data),fail:()=>D(new Error(`{"message":"Network error","code":${Jn}}`))})}):an?void 0:new Promise((m,D)=>{const M=new XMLHttpRequest,T=setTimeout(()=>{M.abort(),D(new Error(`{"message":"Request timeout","code":${Qr}}`))},E);M.onreadystatechange=function(){if(M.readyState===4)if(clearTimeout(T),M.status===200||M.status===304)try{m(M.responseText?JSON.parse(M.responseText):null)}catch{m(M.responseText)}else D(new Error(`{"message":"Network error","code":${Jn}}`))},M.open(n,g,!0),M.setRequestHeader("Content-type",zr),M.send(u||null)})})}function Rs(s){if(s==null)return!0;if(typeof s=="boolean")return!1;if(typeof s=="number")return s===0;if(typeof s=="string"||typeof s=="function"||Array.isArray(s))return s.length===0;if(s instanceof Error)return s.message==="";if(b(s)){for(const n in s)if(Object.prototype.hasOwnProperty.call(s,n))return!1;return!0}return(Object.prototype.toString.call(s)==="[object Map]"||Object.prototype.toString.call(s)==="[object Set]"||Object.prototype.toString.call(s)==="[object File]")&&s.size===0}function or(s,n){if(s===null||typeof s!="object")return s;const g=n||new WeakMap;if(g.has(s))return g.get(s);if(s instanceof Date)return new Date(s.getTime());if(s instanceof RegExp)return new RegExp(s.source,s.flags);if(s instanceof Map){const m=new Map;return g.set(s,m),s.forEach((D,M)=>{m.set(or(M,g),or(D,g))}),m}if(s instanceof Set){const m=new Set;return g.set(s,m),s.forEach(D=>{m.add(or(D,g))}),m}if(Array.isArray(s)){const m=[];return g.set(s,m),s.forEach(D=>{m.push(or(D,g))}),m}const u=Object.getPrototypeOf(s),E=Object.create(u);return g.set(s,E),[...Object.getOwnPropertyNames(s),...Object.getOwnPropertySymbols(s)].forEach(m=>{if(m==="__ob__"||m==="__v_skip"||m==="__v_isRef"||m==="__v_isReadonly")return;const D=Object.getOwnPropertyDescriptor(s,m);D&&(D.get||D.set?Object.defineProperty(E,m,D):E[m]=or(s[m],g))}),E}function en(s,n,g){const u=new WeakSet,E=(m,D)=>{if(n&&(D=n(m,D)),D===void 0)return"undefined";if(D===null)return null;if(Number.isNaN(D))return"NaN";if(D===1/0)return"Infinity";if(D===-1/0)return"-Infinity";if(typeof D=="function")return`[Function: ${D.name||"anonymous"}]`;if(typeof D=="symbol")return D.toString();if(typeof D=="bigint")return`${D.toString()}n`;if(typeof D=="object"&&D!==null){if(u.has(D))return"[Circular]";u.add(D)}return D instanceof Date?D.toISOString():D instanceof Error?{name:D.name,message:D.message}:D instanceof Map?{dataType:"Map",value:Array.from(D.entries())}:D instanceof Set?{dataType:"Set",value:Array.from(D.values())}:D};try{return JSON.stringify(s,E,g)}catch(m){return console.error("Failed to stringify:",m),""}}function wn(){let s,n;return{promise:new Promise((g,u)=>{s=g,n=u}),resolve:s,reject:n}}var Ht,yg=Object.freeze({__proto__:null,ANDROID_VERSION:ei,IE_VERSION:Oi,IN_ALIPAY_MINI_APP:gi,IN_BAIDU_MINI_APP:Ut,IN_BROWSER:Wt,IN_DONUT_NATIVE_APP:to,IN_FEISHU_MINI_APP:Vs,IN_JD_MINI_APP:Fi,IN_MINI_APP:ki,IN_NODE:an,IN_NS_NATIVE_APP:ns,IN_QQ_MINI_APP:XA,IN_RN_APP:jo,IN_TT_MINI_APP:_e,IN_TT_MINI_GAME:je,IN_UNI_APP:Eo,IN_UNI_NATIVE_APP:To,IN_WX_MINI_APP:ut,IN_WX_MINI_APP_DESK:Kt,IN_WX_MINI_GAME:ge,IN_WX_MINI_PLUGIN:$i,IOS_VERSION:It,IS_ANDROID:Ai,IS_CHROME:vt,IS_EDGE:Ze,IS_FIREFOX:ke,IS_IE:_t,IS_IOS:nt,IS_IPAD:le,IS_IPHONE:Ve,IS_IPOD:Ft,IS_MAC:oo,IS_SAFARI:po,IS_WECHAT:vs,IS_WIN:No,IS_WORKER_AVAILABLE:Go,MINI_APP_NAMESPACE:io,USER_AGENT:bi,base16EncodeBinaryString:IA,deepCopyWithMethods:or,deepMerge:j,generatePromise:wn,getPlatformType:Es,getType:I,httpRequest:Pi,isArray:h,isArrayOrObject:w,isEmpty:Rs,isH5:An,isIOSWebView:rn,isNumber:s=>s!==null&&(typeof s=="number"&&!Number.isNaN(s-0)||typeof s=="object"&&s.constructor===Number),isObject:f,isPlainObject:b,isString:l,isUndefined:r,isUniIOSApp:function(){return To&&uni.getDeviceInfo().platform.toLocaleLowerCase()==="ios"},isValidRequestKey:_,platform:HA,randomInt:U,randomString:function(){const s="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let n="";for(let g=32;g>0;--g)n+=s[Math.floor(62*Math.random())];return n},safeStringify:en});class On{constructor(){this.listeners={}}on(n,g,u){this.listeners[n]||(this.listeners[n]=[]),this.listeners[n].push({fn:g,context:u})}off(n,g,u){var E;g&&(this.listeners[n]=(E=this.listeners[n])===null||E===void 0?void 0:E.filter(m=>{const D=m.fn===g,M=!u||m.context===u;return!(D&&M)}))}emit(n,...g){const u=this.listeners[n];u&&u.forEach(E=>{const{fn:m,context:D}=E;try{m.apply(D,g)}catch(M){console.warn(`Error in event handler for ${n} error: ${en(M)}`)}})}once(n,g,u){const E=(...m)=>{g.apply(u,m),this.off(n,E)};this.on(n,E)}}(function(s){s.BUSINESS_COMMAND="business_command",s.C2C_REALTIME_MESSAGE="c2c_realtime_message",s.C2C_MESSAGE_MODIFIED="c2c_message_modified",s.C2C_REVOKED_MESSAGE="c2c_message_revoked",s.GROUP_REALTIME_MESSAGE="group_realtime_message",s.GROUP_MESSAGE_MODIFIED="group_message_modified",s.GROUP_MESSAGE_REVOKED="group_message_revoked",s.C2C_MESSAGE_READ_RECEIPT="c2c_message_read_receipt",s.MESSAGE_REACTION_UPDATED="message_reaction_updated",s.MESSAGE_REACTION_UPDATED_SYNC="message_reaction_updated_sync",s.GROUP_AT_TIPS="group_at_tips",s.USER_STATUS_UPDATE="user_status_update",s.FRIEND_LIST_MODIFIED="friend_list_modified",s.PROFILE_MODIFIED="profile_modified",s.CONV_MODIFIED="conversation_modified",s.GROUP_TIPS_NOTIFICATION="group_tips_notification",s.GROUP_MESSAGE_READ_RECEIPT="group_message_read_receipt",s.GROUP_MESSAGE_READ_SYNC="group_message_read_sync",s.GROUP_SYSTEM_NOTIFICATION="group_system_notification",s.C2C_MESSAGE_PEER_READ="c2c_message_peer_read",s.C2C_MESSAGE_READ_SYNC="c2c_message_read_sync",s.C2C_REMIND_TYPE_SYNC="c2c_remind_type_sync",s.FOLLOW_LIST_UPDATED="follow_list_updated",s.MESSAGE_EXTENSIONS_UPDATED="message_extensions_updated",s.ALL_MESSAGE_READ="all_message_read",s.CONVERSATION_MARK_UPDATED="conversation_mark_updated",s.CONVERSATION_GROUP_ADD="conversation_group_add",s.CONVERSATION_GROUP_DELETED="conversation_group_deleted",s.CONVERSATION_GROUP_UPDATED="conversation_group_updated",s.ALL_RECEIVE_MESSAGE_OPTION="all_receive_message_option",s.TOPIC_AT_TIPS="topic_at_tips",s.TOPIC_TIPS_NOTIFICATION="topic_tips_notification",s.TOPIC_SYSTEM_NOTIFICATION="topic_system_notification",s.TOPIC_MESSAGE_READ_SYNC="topic_message_read_sync",s.TOPIC_LATEST_MESSAGE="topic_latest_message",s.GROUP_MESSAGE_PINNED="group_message_pinned"})(Ht||(Ht={}));const Gn=[16,17];function Js(s){var n;const g=[];return(n=s?.GroupTips)===null||n===void 0||n.forEach(u=>{var E;u.GroupInfo.MillionGroupFlag===2?g.push(Ht.TOPIC_TIPS_NOTIFICATION):Gn.includes((E=u?.MsgBody)===null||E===void 0?void 0:E.OpType)?g.push(Ht.GROUP_MESSAGE_PINNED):g.push(Ht.GROUP_TIPS_NOTIFICATION)}),g}const pr=[{conditions:[{type:"event",value:100}],subType:Ht.BUSINESS_COMMAND},{conditions:[{type:"event",value:24}],subType:Ht.ALL_RECEIVE_MESSAGE_OPTION},{conditions:[{type:"event",value:26}],subType:Ht.TOPIC_LATEST_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgArray"}],subType:Ht.C2C_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgModNotifys"}],subType:Ht.C2C_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"ProfileDataMod"}],subType:Ht.PROFILE_MODIFIED},{conditions:[{type:"hasKey",value:"UserStatusList"}],subType:Ht.USER_STATUS_UPDATE},{conditions:[{type:"hasKey",value:"FriendListMod"}],subType:Ht.FRIEND_LIST_MODIFIED},{conditions:[{type:"hasKey",value:"GroupMsgArray"}],subType:Ht.GROUP_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"GroupMsgModNotifys"}],subType:Ht.GROUP_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"C2cNotifyMsgArray"}],subTypeParser:function(s){var n;const g=[];return(n=s?.C2cNotifyMsgArray)===null||n===void 0||n.forEach(u=>{u.WithdrawC2cMsgNotify&&g.push(Ht.C2C_REVOKED_MESSAGE),u.C2cReadedReceipt&&g.push(Ht.C2C_MESSAGE_PEER_READ),u.ReadC2cMsgNotify&&g.push(Ht.C2C_MESSAGE_READ_SYNC),u.MuteNotificationsSync&&g.push(Ht.C2C_REMIND_TYPE_SYNC)}),g}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:4}],subTypeParser:Js},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:5}],subTypeParser:function(s){var n;const g=[];return(n=s?.GroupTips)===null||n===void 0||n.forEach(u=>{Array.isArray(u.MsgBody.GroupWithdrawInfoArray)?g.push(Ht.GROUP_MESSAGE_REVOKED):Array.isArray(u.MsgBody.GroupMsgReceiptList)?g.push(Ht.GROUP_MESSAGE_READ_RECEIPT):Array.isArray(u.MsgBody.GroupReadInfoArray)?u.MsgBody.GroupReadInfoArray[0].TopicId?g.push(Ht.TOPIC_MESSAGE_READ_SYNC):g.push(Ht.GROUP_MESSAGE_READ_SYNC):u.GroupInfo.MillionGroupFlag===2?g.push(Ht.TOPIC_SYSTEM_NOTIFICATION):g.push(Ht.GROUP_SYSTEM_NOTIFICATION)}),g}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:6}],subTypeParser:Js},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:12}],subTypeParser:function(s){var n;const g=[];return(n=s?.GroupTips)===null||n===void 0||n.forEach(u=>{const{GroupAtTips:{TopicId:E}}=u;E?g.push(Ht.TOPIC_AT_TIPS):g.push(Ht.GROUP_AT_TIPS)}),g}},{conditions:[{type:"hasKey",value:"RecentContactMod"}],subTypeParser:function(s){var n;const g=[];return(n=s?.RecentContactMod)===null||n===void 0||n.forEach(u=>{switch(u.PushType){case We.CONV_MARK_UPDATED:g.push(Ht.CONVERSATION_MARK_UPDATED);break;case We.CONV_GROUP_ADDED:g.push(Ht.CONVERSATION_GROUP_ADD);break;case We.CONV_GROUP_DELETED:g.push(Ht.CONVERSATION_GROUP_DELETED);break;case We.CONV_GROUP_UPDATED:g.push(Ht.CONVERSATION_GROUP_UPDATED);break;default:g.push(Ht.CONV_MODIFIED)}}),g}},{conditions:[{type:"hasKey",value:"MsgReactionNotifyList"}],subType:Ht.MESSAGE_REACTION_UPDATED},{conditions:[{type:"hasKey",value:"MsgReactionNotify"}],subType:Ht.MESSAGE_REACTION_UPDATED_SYNC},{conditions:[{type:"hasKey",value:"C2cMsgInfo"}],subType:Ht.C2C_MESSAGE_READ_RECEIPT},{conditions:[{type:"hasKey",value:"FollowChangeList"}],subType:Ht.FOLLOW_LIST_UPDATED},{conditions:[{type:"hasKey",value:"MsgExtensionNotify"}],subType:Ht.MESSAGE_EXTENSIONS_UPDATED},{conditions:[{type:"hasKey",value:"C2CReadAllMsg"}],subType:Ht.ALL_MESSAGE_READ}];var Pn;function mr(s){var n;const g=Array.isArray((n=s?.body)===null||n===void 0?void 0:n.EventArray)?s.body.EventArray:[],u=[];return g.forEach(E=>{E.Flag=s.body.Flag;const m=pr.find(M=>M.conditions.every(T=>{switch(T.type){case"event":return E.Event===T.value;case"hasKey":return Object.prototype.hasOwnProperty.call(E,T.value);default:return!1}}));if(!m)return null;let D=[];typeof m.subTypeParser=="function"?D=m.subTypeParser(E):m.subType&&(D=m.subType),Array.isArray(D)?D.forEach(M=>{u.push({type:`${Pn.SERVER_PUSH_MESSAGE}:${M}`,data:E})}):u.push({type:`${Pn.SERVER_PUSH_MESSAGE}:${D}`,data:E})}),u}(function(s){s.SERVER_PUSH_MESSAGE="im_open_push.msg_push",s.SERVER_PUSH_MESSAGE_MULTIPLE="im_open_push.multi_msg_push_ws",s.ERROR="error"})(Pn||(Pn={}));const mo={[Pn.SERVER_PUSH_MESSAGE]:mr,[Pn.SERVER_PUSH_MESSAGE_MULTIPLE]:mr,[Pn.ERROR]:function(s){const{errorCode:n}=s;return[{type:`error:${n}`,data:s}]}},gn=new class{constructor(){this._outerEventEmitter=null,this._innerEventEmitter=null,this._filteredCallbackMap=new Map,this._outerEventEmitter=new On,this._innerEventEmitter=new On,this.InnerEventSubType=Ht}subscribeInnerEvent(s,n,g,u,E){var m;let D,M,T,P;["string","number"].includes(typeof n)?(T=`${s}:${n}`,P=g,M=u,D=E):(T=s,P=n,M=g,D=typeof u=="function"?u:void 0),D?this._subscribeWithFilter(T,P,M,D):(m=this._innerEventEmitter)===null||m===void 0||m.on(T,P,M)}emitInnerEvent(s,n){var g,u;if((g=this._innerEventEmitter)===null||g===void 0||g.emit(s,n),Object.keys(mo).includes(s)){const E=(u=mo[s])===null||u===void 0?void 0:u.call(mo,n);E?.forEach(m=>{var D;m&&((D=this._innerEventEmitter)===null||D===void 0||D.emit(m.type,m.data))})}}subscribeOuterEvent(s,n,g){var u;(u=this._outerEventEmitter)===null||u===void 0||u.on(s,n,g)}unSubscribeOuterEvent(s,n,g){var u;(u=this._outerEventEmitter)===null||u===void 0||u.off(s,n,g)}unSubscribeInnerEvent(s,n,g,u){if(["string","number"].includes(typeof n)){const E=g,m=`${s}:${n}`;this._unsubscribeEvent(m,E,u)}else{const E=n;this._unsubscribeEvent(s,E,g)}}emitOuterEvent(s,n){var g;(g=this._outerEventEmitter)===null||g===void 0||g.emit(s,n)}getOuterEventEmitter(){return this._outerEventEmitter}rest(){this._outerEventEmitter=null,this._innerEventEmitter=null}_subscribeWithFilter(s,n,g,u){var E;const m=D=>{u.call(g,D)&&n.call(g,D)};this._filteredCallbackMap.has(s)||this._filteredCallbackMap.set(s,[]),this._filteredCallbackMap.get(s).push({originalCallback:n,filteredCallback:m,filter:u,context:g}),(E=this._innerEventEmitter)===null||E===void 0||E.on(s,m,g)}_unsubscribeEvent(s,n,g){var u,E;const m=this._filteredCallbackMap.get(s);if(m){const D=m.findIndex(M=>M.originalCallback===n&&M.context===g);if(D!==-1){const{filteredCallback:M}=m[D];return(u=this._innerEventEmitter)===null||u===void 0||u.off(s,M,g),m.splice(D,1),void(m.length===0&&this._filteredCallbackMap.delete(s))}}(E=this._innerEventEmitter)===null||E===void 0||E.off(s,n,g)}};class Sl{constructor(){this._socket=null}connectSocket(n){return this._socket=new WebSocket(n),this._socket}send(n){var g,u;try{(g=this._socket)===null||g===void 0||g.send(n)}catch(E){(u=this._onSendFail)===null||u===void 0||u.call(this,E)}}bindSocketHandlers(n){const{onOpen:g,onMessage:u,onClose:E,onError:m,onSendFail:D}=n;this._socket&&(this._socket.binaryType="arraybuffer",this._socket.onopen=g,this._socket.onmessage=u,this._socket.onclose=E,this._socket.onerror=m,this._onSendFail=D)}unbindSocketHandlers(){this._socket&&(this._socket.onopen=null,this._socket.onmessage=null,this._socket.onclose=null,this._socket.onerror=null)}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}class cn{constructor(n){this._onError=n.onError}connectSocket(n){const g=this;return this._socket=io.connectSocket({url:n,header:{"content-type":"application/json"},complete:()=>{},fail:u=>g._onError(u)}),this._socket}send(n){var g;(g=this._socket)===null||g===void 0||g.send({data:n,fail:this._onSendFail})}bindSocketHandlers(n){const{onOpen:g,onMessage:u,onClose:E,onError:m,onSendFail:D}=n;this._socket&&(this._socket.onClose(E),this._socket.onOpen(g),this._socket.onMessage(u),this._socket.onError(m),this._onSendFail=D)}unbindSocketHandlers(){this._socket&&(this._socket.onClose(()=>{}),this._socket.onOpen(()=>{}),this._socket.onMessage(()=>{}),this._socket.onError(()=>{}))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}const fr="CONNECT",Ls="SEND",Jc="DISCONNECT",ms="OPEN",as="MESSAGE",Mu="CLOSE",Wa="ERROR",Cs="SEND_FAIL";class sg{constructor(){this._worker=null,this._blobUrl=null}connectSocket(n){const g=new Blob([`
let _socket = null;
self.onmessage = (event) => {
@@ -95,26 +95,26 @@
_socket = null;
}
}
-`],{type:"application/javascript"});this._worker=new Worker(URL.createObjectURL(g)),this._worker.postMessage({type:fr,url:n})}send(n){var g,u;try{(g=this._worker)===null||g===void 0||g.postMessage({type:Ls,data:n})}catch(E){(u=this._onSendFail)===null||u===void 0||u.call(this,E)}}bindSocketHandlers(n){const{onOpen:g,onMessage:u,onClose:E,onError:m,onSendFail:D}=n;if(this._worker){const M={[ms]:g,[as]:u,[Su]:E,[Wa]:m,[Cs]:D};this._onSendFail=D,this._worker.onmessage=T=>{var P;const{type:W}=T?.data||{};typeof M[W]=="function"&&((P=M[W])===null||P===void 0||P.call(M,T?.data))}}}unbindSocketHandlers(){this._worker&&(this._worker.onmessage=null)}disconnect(){this._worker&&(this._worker.postMessage({type:Vc}),this._worker.terminate(),this._worker=null),this._blobUrl&&(URL.revokeObjectURL(this._blobUrl),this._blobUrl=null)}}class VI{}var $o,Xi=new class{constructor(){this._store=new Map}get(s){return this._store.get(s)}getStorage(s){return ki?gi?my.getStorageSync({key:s}).data:io.getStorageSync(s):this._canUseLocalStorage()?localStorage.getItem(s):{}}set(s,n){const g=this._store.get(s)||{};n instanceof Map?this._store.set(s,n):this._store.set(s,Object.assign(Object.assign({},g),n))}setStorage(s,n){ki?gi?my.setStorageSync({key:s,data:JSON.stringify(n)}):io.setStorageSync(s,JSON.stringify(n)):this._canUseLocalStorage()&&localStorage.setItem(s,JSON.stringify(n))}clear(s){typeof s=="string"?this._store.set(s,{}):this._store.clear()}clearLocalStorage(s){this._canUseLocalStorage()&&(typeof s=="string"?localStorage.setItem(s,""):localStorage.clear())}reset(){this.clear()}_canUseLocalStorage(){return typeof window<"u"&&navigator&&navigator.cookieEnabled&&localStorage}};class pc{connectSocket(n){return this._socket=io.connectSocket({url:n,header:{"content-type":"application/json"},multiple:!0,complete:()=>{}}),this._socket}send(n){var g;(g=this._socket)===null||g===void 0||g.send({data:n,fail:this._onSendFail})}bindSocketHandlers(n){const{onOpen:g,onMessage:u,onClose:E,onError:m,onSendFail:D}=n;this._socket&&(this._socket.onClose(E),this._socket.onOpen(g),this._socket.onMessage(M=>u(M?.data)),this._socket.onError(()=>m),this._onSendFail=D)}unbindSocketHandlers(){this._socket&&(this._socket.onClose(()=>{}),this._socket.onOpen(()=>{}),this._socket.onMessage(()=>{}),this._socket.onError(()=>{}))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}(function(s){s[s.CONNECTED=0]="CONNECTED",s[s.CONNECTING=1]="CONNECTING",s[s.DISCONNECTED=2]="DISCONNECTED"})($o||($o={}));class ng{constructor(n){this._url="",this._readyState=$o.DISCONNECTED,this._url=n,this._id=U(),this._emitter=new On,gi?this._socket=new pc:Le||To||Dt||je||Fi||Jt?this._socket=new cn({onError:this._onError.bind(this)}):an?this._socket=new VI:this._canUseWebWorker()?this._socket=new sg:this._socket=new Dl,this.connect()}connect(){this.doOpen(),this._bindSocketHandlers()}doOpen(){[$o.CONNECTED,$o.CONNECTING].includes(this._readyState)||(this._readyState=$o.CONNECTING,this._ws=this._socket.connectSocket(this._url))}send(n){this._readyState!==$o.CONNECTED?this.reconnect():this._socket.send(n)}reconnect(){[$o.CONNECTED,$o.CONNECTING].includes(this._readyState)||(this.disconnect(),this.doOpen())}getId(){return this._id}on(n,g,u){this._emitter.on(n,g,u)}off(n,g,u){this._emitter.off(n,g,u)}isConnected(){return this._readyState===$o.CONNECTED}disconnect(){this._readyState=$o.DISCONNECTED,this._unbindSocketHandlers(),this._socket.disconnect()}_onOpen(n){this._readyState===$o.CONNECTING&&(this._readyState=$o.CONNECTED,this._emitter.emit("connect",{socketId:this._id,event:n}))}_onMessage(n){this._emitter.emit("message",n)}_onClose(n){this._readyState=$o.DISCONNECTED,this._emitter.emit("close",{socketId:this._id,event:n})}_onError(n){this._readyState=$o.DISCONNECTED,this._emitter.emit("error",{socketId:this._id,error:n})}_onSendFail(n){this._readyState=$o.DISCONNECTED,this._emitter.emit("sendFail",{socketId:this._id,error:n})}_bindSocketHandlers(){this._socket.bindSocketHandlers({onOpen:this._onOpen.bind(this),onMessage:this._onMessage.bind(this),onClose:this._onClose.bind(this),onError:this._onError.bind(this),onSendFail:this._onSendFail.bind(this)})}_unbindSocketHandlers(){this._socket.unbindSocketHandlers()}_canUseWebWorker(){const n=Xi.get("cloudConfig")||{};return(r(n.isWorkerEnabled)||n.isWorkerEnabled==="1")&&Go}}const Dg={[ut.SINGAPORE]:[[2e7,3e7],[172e7,173e7]],[ut.KOREA]:[[3e7,4e7],[173e7,174e7]],[ut.GERMANY]:[[4e7,5e7],[174e7,175e7]],[ut.IND]:[[5e7,6e7],[175e7,176e7]],[ut.JPN]:[[6e7,7e7],[176e7,177e7]],[ut.USA]:[[7e7,8e7],[177e7,178e7]],[ut.INDONESIA]:[[8e7,9e7],[178e7,179e7]],[ut.KSA]:[[9e7,1e8],[179e7,18e8]]};function Ia(s){var n;if(!((n=Xi.get("instance"))===null||n===void 0)&&n.oversea)return ut.OVERSEA;for(const g of Object.keys(Dg))for(const[u,E]of Dg[g])if(s>=u&&s`${iA}=${W[iA]}`).join("&"));var W;return g?`${s}/binfo?${P}&compress=gzip`:`${s}/info?${P}`}function Hs(s){const n=Xi.get("instance"),{sdkAppId:g,testEnv:u,proxyServer:E}=n,m=Ia(g);if(u)return Hn(pt.TEST[m].DEFAULT,{isBinary:s});if(!Rs(E))return Hn(E,{isBinary:s});const D=pt.PRODUCTION[m],M=jt&&D.ANYCAST,T=jt,P=!!D.BACKUP_CN;return Hn({[bo.INITIAL]:()=>(_o=bo.DEFAULT,D.DEFAULT),[bo.DEFAULT]:()=>(_o=bo.IPV6,D.IPV6),[bo.IPV6]:()=>(_o=bo.BACKUP,D.BACKUP),[bo.BACKUP]:()=>T?(_o=bo.BACKUP_WEB_ONLY,function(W){const iA=Math.floor(10001*Math.random())+1e4;return W.replace("*",String(iA))}(D.BACKUP_WEB_ONLY)):P?(_o=bo.BACKUP_CN,D.BACKUP_CN):M?(_o=bo.ANYCAST,D.ANYCAST):D.DEFAULT,[bo.BACKUP_WEB_ONLY]:()=>P?(_o=bo.BACKUP_CN,D.BACKUP_CN):M?(_o=bo.ANYCAST,D.ANYCAST):D.DEFAULT,[bo.BACKUP_CN]:()=>(_o=M?bo.ANYCAST:bo.DEFAULT,D[_o]),[bo.ANYCAST]:()=>(_o=bo.DEFAULT,D.ANYCAST="",D.DEFAULT)}[_o](),{isBinary:s})}var Sg=new class{constructor(){this._timeOffsetWithServer=0}getServerTimeMs(){return Date.now()+this._timeOffsetWithServer}getServerTimeSeconds(){return Math.floor(this.getServerTimeMs()/1e3)}getTimeOffsetWithServer(){return this._timeOffsetWithServer}calculateTimeOffsetWithServer(s,n){const g=Date.now(),u=g-s;this._timeOffsetWithServer=n+u-g}};const mc=16;var fn=new class{constructor(){this._tasks=[],this._timer=null,this._taskMap=new Map}_addTaskToScheduler(s){const{id:n}=s;this.removeTask(n),this._tasks.push(s),this._taskMap.set(n,s),this._sort(),this._scheduleNextTask()}_createTask(s){const{id:n,callback:g,context:u,isOnce:E=!1,intervalMs:m=mc}=s,D=Math.max(m,mc);return{id:n,nextExecuteTime:Date.now()+D,intervalMs:m,callback:g,context:u,isOnce:E}}addTask(s){const n=this._createTask(s);this._addTaskToScheduler(n)}addOnceTask(s){const n=this._createTask(Object.assign(Object.assign({},s),{isOnce:!0}));this._addTaskToScheduler(n)}removeTask(s){const n=this._tasks.findIndex(g=>g.id===s);n>-1&&(this._tasks.splice(n,1),this._taskMap.delete(s),this._scheduleNextTask())}updateTaskInterval(s,n){const g=this._taskMap.get(s);g&&(g.intervalMs=n,g.nextExecuteTime=Date.now()+n,this._sort(),this._scheduleNextTask())}clearAllTasks(){this._tasks=[],this._taskMap.clear(),this._timer&&(clearTimeout(this._timer),this._timer=null)}dispose(){this.clearAllTasks()}_sort(){this._tasks.sort((s,n)=>s.nextExecuteTime-n.nextExecuteTime)}_scheduleNextTask(){this._timer&&(clearTimeout(this._timer),this._timer=null);const s=this._tasks[0];if(s){const n=Math.max(0,s.nextExecuteTime-Date.now());this._timer=setTimeout(()=>this._execute(),n)}}_execute(){const s=Date.now();for(;this._tasks.length&&this._tasks[0].nextExecuteTime<=s;){const n=this._tasks[0];try{n.context?n.callback.call(n.context):n.callback(),n.isOnce?this.removeTask(n.id):(n.nextExecuteTime=s+n.intervalMs,this._sort())}catch(g){console.warn(`Task ${n.id} execution failed:`,g),n.isOnce&&this.removeTask(n.id)}}this._scheduleNextTask()}};function Ga(s){const n=[];for(let g=0;g=55296&&u<=56319){const E=s.charCodeAt(++g)-56320+(u-55296<<10)+65536;n.push(240|E>>18,128|E>>12&63,128|E>>6&63,128|63&E)}else u<=127?n.push(u):u<=2047?n.push(192|u>>6,128|63&u):n.push(224|u>>12,128|u>>6&63,128|63&u)}return new Uint8Array(n)}function In(s){const n=Array.isArray(s)?[]:Object.create(null);for(const g in s)Object.prototype.hasOwnProperty.call(s,g)&&_(g)&&s[g]!=null&&(s[g]===null||typeof s[g]!="object"?n[g]=s[g]:n[g]=In(s[g]));return n}function fs(s,n){if(mA.includes(s))return 0;const g=Ga(JSON.stringify(n));let u=4294967295;const{length:E}=g;for(let m=0;m>>=1:u=u>>>1^3988292384}return(4294967295^u)>>>0}function ua(s){const{servcmd:n,data:g}=s,u=function(m){const D=Xi.get("login")||{},M=Xi.get("instance")||{};return{servcmd:m,ver:"v4",platform:HA,websdkappid:537048168,websdkversion:"1.7.3",a2:D.a2Key||void 0,tinyid:D.tinyID||void 0,status_instid:D.statusInstanceId||0,sdkappid:M.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:D.a2Key?void 0:D.userId,usersig:D.a2Key?void 0:D.userSig,sdkability:478343027,sdkability_ext:lA(""),cappid:M.applicationID||0,tjgID:"",seq:Sa(),cs:0}}(n),E=In(g);return u.cs=fs(n,E),{head:u,body:E}}function yn(s){const{servcmd:n,data:g}=s,u=function(m){const D=Xi.get("login")||{},M=Xi.get("instance")||{};return{servcmd:m,ver:"v4",platform:HA,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:M.sdkAppId,contenttype:"",reqtime:Math.floor(Date.now()/1e3),identifier:"",usersig:"",status_instid:D.statusInstanceId||0,sdkability:478343027,sdkability_ext:lA(""),cappid:M.applicationID||0,seq:Sa(),cs:0}}(n),E=In(g);return u.cs=fs(n,E),{head:u,body:E}}let ba=U();function Sa(){return ba=ba<2415919103?ba+1:U(),ba}function $(){var s;const n=Xi.get("login")||{},g=Xi.get("instance")||{};return{sdk_type:30,sdk_app_id:g.sdkAppId,sdk_version:"1.6.18",tiny_id:Number(n.tinyID),user_id:n.userId||((s=Xi.get("webPush"))===null||s===void 0?void 0:s.userId),platform:HA,instance_id:g.instanceId,trace_id:new Date().getTime()}}var K,vA=Object.freeze({__proto__:null,calcBodyCRC:fs,filterProtocolDataInvalidFields:In,generateCosSpecifiedData:function(s){const{servcmd:n,data:g}=s,u=function(m){const D=Xi.get("login")||{},M=Xi.get("instance")||{};return{servcmd:m,ver:"v4",platform:HA,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:M.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:D.userId,usersig:D.userSig,status_instid:D.statusInstanceId||0,sdkability:478343027,sdkability_ext:lA(""),cappid:M.applicationID||0,seq:Sa(),cs:0}}(n),E=In(g);return u.cs=fs(n,E),{head:u,body:E}},generateProtocolData:ua,generateSSOLogProtocolData:yn,generateSequence:Sa,getCommonHead:$,getHostSite:Ia,taskScheduler:fn,timeManager:Sg});(function(s){s[s.info=4]="info",s[s.warning=5]="warning",s[s.error=6]="error"})(K||(K={}));const qA={method:"extension",networkType:"network_type",eventType:"event_type",code:"error_code",message:"error_message",moreMessage:"more_message",duplicate:"duplicate",costTime:"cost_time",level:"level",uiPlatform:"ui_platform",timestamp:"timestamp"};class Ae{constructor(n){this.level=K.info,this._canSendLog=!0,this._logCreatedAt=Sg.getServerTimeMs(),this.timestamp=0,this.networkType=8,this.code=0,this.moreMessage="",this.method="",this.message="",this.costTime=0,this.duplicate=!1,this.eventType=0,this.uiPlatform=this._getUiPlatform(),this._sdkEdition=this._getSDKEdition();const{method:g,eventType:u=0,message:E="",costTime:m=0,error:D,uiPlatform:M,moreMessage:T="",code:P=0,startTime:W=0}=n||{};this.eventType=u,this.method=g,this.message=E,this.costTime=m,this.moreMessage=`${T} startTime:${W}`,this.code=P,D&&this.setError(D),Rs(M)||(this.uiPlatform=M)}setMoreMessage(n){this.moreMessage=`${this.moreMessage} ${n}`}updateLogCreatedAtByTimeOffset(){this._logCreatedAt+=Sg.getTimeOffsetWithServer()}end(n=!1){this._canSendLog&&(this._canSendLog=!1,this.timestamp=Sg.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe()),n&&this._ssoLogModule.uploadSSOLogData())}setError(n){var g;return n instanceof Error?this._canSendLog?(!((g=Xi.get("netWorkMonitor"))===null||g===void 0)&&g.isNetworkOnline&&(n.errorCode&&(this.code=n.errorCode),n.errorMessage&&this.setMoreMessage(n.errorMessage)),this.level=K.error,this):this:(console.warn("SSOLogData.setError value not instanceof Error, please check!"),this)}setLogInfo(n){return Object.keys(n).forEach(g=>{Object.keys(qA).includes(g)&&(this[g]=n[g])}),this}setSSOLogModule(n){this._ssoLogModule=n}_convertSSOLogDataKeyToServe(){const n={};return Object.keys(this).forEach(g=>{const u=g;qA[u]&&(n[qA[u]]=this[u])}),n}_getUiPlatform(){var n;const g=(n=Xi.get("instance"))===null||n===void 0?void 0:n.scene;if(typeof g=="string"){const u=Number(g);return isNaN(u)?void 0:u}}_getSDKEdition(){var n;return(n=Xi.get("instance"))===null||n===void 0?void 0:n.sdkEdition}}var pe;(function(s){s.RECONNECTED="reconnected",s.CLOUD_CONFIG_UPDATE="cloud_config_update",s.SOCKET_DISCONNECTED="socket_disconnected"})(pe||(pe={}));var Pe=pe;const Oe=20,rt=6e4,dt=[4,5,6],Mt="report-logger";var Pt=new class{constructor(){this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._reportLevel=[4,5,6],this._minThreshold=Oe,this._maxThreshold=100,this._waitingTime=rt,this._lastReportAt=Date.now(),this._ssoLogMap=new Map,this._logLevel=IA.DEBUG,this._throttleConfig={global:{throttleTime:xe,maxCount:Be},single:{throttleTime:ge,maxCount:ue}},this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap=new Map,gn.subscribeInnerEvent(Pe.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),fn.addTask({id:Mt,intervalMs:1e3,callback:this._checkAndReportIfDue,context:this}),this._logQueue=[],this._savePlatFormInfo()}_handleCloudConfigUpdate(s){const{evt_rpt_threshold:n=Oe,evt_rpt_waiting:g=rt,evt_rpt_level:u=dt,evt_rpt_sdkappid_bl:E="",evt_rpt_tinyid_wl:m="",evt_rpt_global_throttle_time:D=xe,evt_rpt_global_throttle_count:M=Be,evt_rpt_single_throttle_time:T=ge,evt_rpt_single_throttle_count:P=ue}=s||{};this._sdkAppIdBlackList=E.split(",").map(W=>Number(W)),this._waitingTime=Number(g),this._minThreshold=n,this._reportLevel=u,this._tinyIdWhiteList=m.split(","),this._throttleConfig={global:{throttleTime:D,maxCount:M},single:{throttleTime:T,maxCount:P}}}createSSOLogData(s){const n=new Ae(s);return n.setSSOLogModule(this),this._ssoLogMap.set(s.method,n),n}getSSOLogData(s){return this._ssoLogMap.get(s)||{}}pushToLogQueue(s){s&&(this._logQueue.push(s),this._shouldUploadImmediately()&&this.uploadSSOLogData())}setLogLevel(s){[IA.DEBUG,IA.ERROR,IA.INFO,IA.NONE,IA.WARN].includes(s)&&(this._logLevel=s)}debug(s,n="",g){this._log(IA.DEBUG,s,n,g)}info(s,n="",g){this._log(IA.INFO,s,n,g)}warn(s,n="",g){this._log(IA.WARN,s,n,g)}error(s,n="",g){this._log(IA.ERROR,s,n,g)}_shouldUploadImmediately(){return this._logQueue.length>=this._minThreshold}_isReportDue(){return Date.now()>=this._lastReportAt+this._waitingTime}_checkAndReportIfDue(){this._isReportDue()&&this._logQueue.length>0&&this.uploadSSOLogData()}uploadSSOLogData(){return pA(this,void 0,void 0,function*(){if(this._logQueue.length===0)return;const s=this._logQueue.slice();this._logQueue=[];try{const n=this._filterLogs(s);if(n.length===0)return void(this._lastReportAt=Date.now());const g={Header:$(),Event:n};Rs(g.Header.user_id)||(yield function(u){const E="imopenstat.tim_web_report_v2",m=yn({servcmd:E,data:u}),D=`${m.head.seq}${E}`;return ye.sendPacket(m,{requestId:D})}(g))}catch(n){this._requeueFailedLogs(s),this.debug("uploadSSOLogData",en(n))}finally{this._lastReportAt=Date.now()}})}_requeueFailedLogs(s){this._logQueue=s.concat(this._logQueue);const n=this._logQueue.length-200;n>0&&(this._logQueue.splice(0,n),this.debug("uploadSSOLogData",`log queue overflow, dropped ${n} oldest logs`))}_savePlatFormInfo(){var s,n;if(Le){const g=(n=(s=wx.getAccountInfoSync)===null||s===void 0?void 0:s.call(wx))===null||n===void 0?void 0:n.miniProgram;if(g){const{appId:u,envVersion:E}=g;Xi.set("instance",{appId:u,envVersion:E})}}else jt&&Xi.set("instance",{href:window.location.href})}_filterLogs(s){const{tinyID:n}=Xi.get("login")||{},{sdkAppId:g}=Xi.get("instance")||{};return this._sdkAppIdBlackList.includes(g)&&!this._tinyIdWhiteList.includes(n)?[]:s.filter(u=>this._reportLevel.includes(u.level))}_checkThrottle(s){return!!this._checkGlobalThrottle()||this._checkSingleThrottle(s)}_checkGlobalThrottle(){const s=Date.now();if(s-this._globalThrottle.startTime>=this._throttleConfig.global.throttleTime)this._globalThrottle.count=1,this._globalThrottle.startTime=s;else if(this._globalThrottle.count++,this._globalThrottle.count>this._throttleConfig.global.maxCount)return!0;return!1}_checkSingleThrottle(s){const n=Date.now(),g=this._singleThrottleMap.get(s);return g?n-g.startTime>=this._throttleConfig.single.throttleTime?(g.count=1,g.startTime=n,!1):g.count>=this._throttleConfig.single.maxCount||(g.count++,!1):(this._singleThrottleMap.set(s,{count:1,startTime:n}),!1)}_shouldLog(s){return s>=this._logLevel&&this._logLevel!==IA.NONE}_shouldReport(s){return this._reportLevel.includes(WA[s])}_formatLog(s,n,g,u){const E=new Date,m=`${E.getHours()}:${E.getMinutes()}:${E.getSeconds()}:${E.getMilliseconds()}`,D=`<${IA[s]}>`;return wt||ki?[`${cA} [${m}] ${D} [${n}] ${g}`]:["%c%s%c%s","background:#0abf5b; padding:1px; border-radius:3px; color: #fff",cA,"",`[${m}] ${D} [${n}] ${g} params: ${en(u)}`]}_log(s,n,g,u){if(this._shouldLog(s)){const E=this._formatLog(s,n,g,u);TA[s].apply(console,E)}if(this._shouldReport(s)){const E=this._getThrottleKey(n,g,u);this._checkThrottle(E)||this.createSSOLogData(Object.assign(Object.assign({message:g},u),{method:n})).end()}}_getThrottleKey(s,n,g){const u=`${s}${n}${en(Object.assign(Object.assign({},g),{costTime:""}))}`,E=Ga(JSON.stringify(u));let m=4294967295;const{length:D}=E;for(let M=0;M>>=1:m=m>>>1^3988292384}return`${(4294967295^m)>>>0}`}reset(){console.log("SSO_LOG_MODULE.reset"),fn.removeTask(Mt),gn.unSubscribeInnerEvent(Pe.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),this._lastReportAt=0,this.uploadSSOLogData(),this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._minThreshold=Oe,this._maxThreshold=100,this._waitingTime=rt,this._logQueue=[],this._logLevel=IA.DEBUG,this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap.clear()}};const li=15e3,ct="Channel",Ot="channel_schedule_task",Ji="channel_reconnect_task",qi="connected",qs="connecting",Mi="disconnected",zo=1e3,Mg="network_status_change",sr="activity_status_change",yr="send_fail",xn="reconnect_failed",Sl="socket_error",Ks="socket_close";function rI(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function Wg(s){return Wg=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(n){return typeof n}:function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},Wg(s)}function fc(s){throw new Error('Could not dynamically require "'+s+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Mu,Ma={exports:{}},Ml=(Mu||(Mu=1,function(s){s.exports=function n(g,u,E){function m(T,P){if(!u[T]){if(!g[T]){if(!P&&fc)return fc(T);if(D)return D(T,!0);var W=new Error("Cannot find module '"+T+"'");throw W.code="MODULE_NOT_FOUND",W}var iA=u[T]={exports:{}};g[T][0].call(iA.exports,function(EA){return m(g[T][1][EA]||EA)},iA,iA.exports,n,g,u,E)}return u[T].exports}for(var D=fc,M=0;M>>6:(EA<65536?iA[xA++]=224|EA>>>12:(iA[xA++]=240|EA>>>18,iA[xA++]=128|EA>>>12&63),iA[xA++]=128|EA>>>6&63),iA[xA++]=128|63&EA);return iA},u.buf2binstring=function(W){return P(W,W.length)},u.binstring2buf=function(W){for(var iA=new E.Buf8(W.length),EA=0,RA=iA.length;EA>10&1023,SA[RA++]=56320|1023&kA)}return P(SA,RA)},u.utf8border=function(W,iA){var EA;for((iA=iA||W.length)>W.length&&(iA=W.length),EA=iA-1;0<=EA&&(192&W[EA])==128;)EA--;return EA<0||EA===0?iA:EA+M[W[EA]]>iA?EA:iA}},{"./common":1}],3:[function(n,g,u){g.exports=function(E,m,D,M){for(var T=65535&E,P=E>>>16&65535,W=0;D!==0;){for(D-=W=2e3>>1:m>>>1;D[M]=m}return D}();g.exports=function(m,D,M,T){var P=E,W=T+M;m^=-1;for(var iA=T;iA>>8^P[255&(m^D[iA])];return-1^m}},{}],6:[function(n,g,u){g.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],7:[function(n,g,u){g.exports=function(E,m){var D,M,T,P,W,iA,EA,RA,kA,xA,LA,SA,OA,JA,ne,se,_i,Ti,Lt,Ni,cs,Se,mt,UA,oi;D=E.state,M=E.next_in,UA=E.input,T=M+(E.avail_in-5),P=E.next_out,oi=E.output,W=P-(m-E.avail_out),iA=P+(E.avail_out-257),EA=D.dmax,RA=D.wsize,kA=D.whave,xA=D.wnext,LA=D.window,SA=D.hold,OA=D.bits,JA=D.lencode,ne=D.distcode,se=(1<>>=Lt=Ti>>>24,OA-=Lt,(Lt=Ti>>>16&255)==0)oi[P++]=65535&Ti;else{if(!(16&Lt)){if(!(64&Lt)){Ti=JA[(65535&Ti)+(SA&(1<>>=Lt,OA-=Lt),OA<15&&(SA+=UA[M++]<>>=Lt=Ti>>>24,OA-=Lt,!(16&(Lt=Ti>>>16&255))){if(!(64&Lt)){Ti=ne[(65535&Ti)+(SA&(1<>>=Lt,OA-=Lt,(Lt=P-W)>3,SA&=(1<<(OA-=Ni<<3))-1,E.next_in=M,E.next_out=P,E.avail_in=M>>24&255)+(Se>>>8&65280)+((65280&Se)<<8)+((255&Se)<<24)}function SA(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new E.Buf16(320),this.work=new E.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function OA(Se){var mt;return Se&&Se.state?(mt=Se.state,Se.total_in=Se.total_out=mt.total=0,Se.msg="",mt.wrap&&(Se.adler=1&mt.wrap),mt.mode=RA,mt.last=0,mt.havedict=0,mt.dmax=32768,mt.head=null,mt.hold=0,mt.bits=0,mt.lencode=mt.lendyn=new E.Buf32(kA),mt.distcode=mt.distdyn=new E.Buf32(xA),mt.sane=1,mt.back=-1,iA):EA}function JA(Se){var mt;return Se&&Se.state?((mt=Se.state).wsize=0,mt.whave=0,mt.wnext=0,OA(Se)):EA}function ne(Se,mt){var UA,oi;return Se&&Se.state?(oi=Se.state,mt<0?(UA=0,mt=-mt):(UA=1+(mt>>4),mt<48&&(mt&=15)),mt&&(mt<8||15=Gi.wsize?(E.arraySet(Gi.window,mt,UA-Gi.wsize,Gi.wsize,0),Gi.wnext=0,Gi.whave=Gi.wsize):(oi<(_s=Gi.wsize-Gi.wnext)&&(_s=oi),E.arraySet(Gi.window,mt,UA-oi,_s,Gi.wnext),(oi-=_s)?(E.arraySet(Gi.window,mt,UA-oi,oi,0),Gi.wnext=oi,Gi.whave=Gi.wsize):(Gi.wnext+=_s,Gi.wnext===Gi.wsize&&(Gi.wnext=0),Gi.whave>>8&255,UA.check=D(UA.check,dg,2,0),Tt=_t=0,UA.mode=2;break}if(UA.flags=0,UA.head&&(UA.head.done=!1),!(1&UA.wrap)||(((255&_t)<<8)+(_t>>8))%31){Se.msg="incorrect header check",UA.mode=30;break}if((15&_t)!=8){Se.msg="unknown compression method",UA.mode=30;break}if(Tt-=4,Va=8+(15&(_t>>>=4)),UA.wbits===0)UA.wbits=Va;else if(Va>UA.wbits){Se.msg="invalid window size",UA.mode=30;break}UA.dmax=1<>8&1),512&UA.flags&&(dg[0]=255&_t,dg[1]=_t>>>8&255,UA.check=D(UA.check,dg,2,0)),Tt=_t=0,UA.mode=3;case 3:for(;Tt<32;){if(xi===0)break A;xi--,_t+=oi[Gi++]<>>8&255,dg[2]=_t>>>16&255,dg[3]=_t>>>24&255,UA.check=D(UA.check,dg,4,0)),Tt=_t=0,UA.mode=4;case 4:for(;Tt<16;){if(xi===0)break A;xi--,_t+=oi[Gi++]<>8),512&UA.flags&&(dg[0]=255&_t,dg[1]=_t>>>8&255,UA.check=D(UA.check,dg,2,0)),Tt=_t=0,UA.mode=5;case 5:if(1024&UA.flags){for(;Tt<16;){if(xi===0)break A;xi--,_t+=oi[Gi++]<>>8&255,UA.check=D(UA.check,dg,2,0)),Tt=_t=0}else UA.head&&(UA.head.extra=null);UA.mode=6;case 6:if(1024&UA.flags&&(xi<(Bo=UA.length)&&(Bo=xi),Bo&&(UA.head&&(Va=UA.head.extra_len-UA.length,UA.head.extra||(UA.head.extra=new Array(UA.head.extra_len)),E.arraySet(UA.head.extra,oi,Gi,Bo,Va)),512&UA.flags&&(UA.check=D(UA.check,oi,Bo,Gi)),xi-=Bo,Gi+=Bo,UA.length-=Bo),UA.length))break A;UA.length=0,UA.mode=7;case 7:if(2048&UA.flags){if(xi===0)break A;for(Bo=0;Va=oi[Gi+Bo++],UA.head&&Va&&UA.length<65536&&(UA.head.name+=String.fromCharCode(Va)),Va&&Bo>9&1,UA.head.done=!0),Se.adler=UA.check=0,UA.mode=12;break;case 10:for(;Tt<32;){if(xi===0)break A;xi--,_t+=oi[Gi++]<>>=7&Tt,Tt-=7&Tt,UA.mode=27;break}for(;Tt<3;){if(xi===0)break A;xi--,_t+=oi[Gi++]<>>=1)){case 0:UA.mode=14;break;case 1:if(Ni(UA),UA.mode=20,mt!==6)break;_t>>>=2,Tt-=2;break A;case 2:UA.mode=17;break;case 3:Se.msg="invalid block type",UA.mode=30}_t>>>=2,Tt-=2;break;case 14:for(_t>>>=7&Tt,Tt-=7&Tt;Tt<32;){if(xi===0)break A;xi--,_t+=oi[Gi++]<>>16^65535)){Se.msg="invalid stored block lengths",UA.mode=30;break}if(UA.length=65535&_t,Tt=_t=0,UA.mode=15,mt===6)break A;case 15:UA.mode=16;case 16:if(Bo=UA.length){if(xi>>=5,Tt-=5,UA.ndist=1+(31&_t),_t>>>=5,Tt-=5,UA.ncode=4+(15&_t),_t>>>=4,Tt-=4,286>>=3,Tt-=3}for(;UA.have<19;)UA.lens[tS[UA.have++]]=0;if(UA.lencode=UA.lendyn,UA.lenbits=7,wI={bits:UA.lenbits},xl=T(0,UA.lens,0,19,UA.lencode,0,UA.work,wI),UA.lenbits=wI.bits,xl){Se.msg="invalid code lengths set",UA.mode=30;break}UA.have=0,UA.mode=19;case 19:for(;UA.have>>16&255,RI=65535&Yg,!((wr=Yg>>>24)<=Tt);){if(xi===0)break A;xi--,_t+=oi[Gi++]<>>=wr,Tt-=wr,UA.lens[UA.have++]=RI;else{if(RI===16){for(AE=wr+2;Tt>>=wr,Tt-=wr,UA.have===0){Se.msg="invalid bit length repeat",UA.mode=30;break}Va=UA.lens[UA.have-1],Bo=3+(3&_t),_t>>>=2,Tt-=2}else if(RI===17){for(AE=wr+3;Tt>>=wr)),_t>>>=3,Tt-=3}else{for(AE=wr+7;Tt>>=wr)),_t>>>=7,Tt-=7}if(UA.have+Bo>UA.nlen+UA.ndist){Se.msg="invalid bit length repeat",UA.mode=30;break}for(;Bo--;)UA.lens[UA.have++]=Va}}if(UA.mode===30)break;if(UA.lens[256]===0){Se.msg="invalid code -- missing end-of-block",UA.mode=30;break}if(UA.lenbits=9,wI={bits:UA.lenbits},xl=T(P,UA.lens,0,UA.nlen,UA.lencode,0,UA.work,wI),UA.lenbits=wI.bits,xl){Se.msg="invalid literal/lengths set",UA.mode=30;break}if(UA.distbits=6,UA.distcode=UA.distdyn,wI={bits:UA.distbits},xl=T(W,UA.lens,UA.nlen,UA.ndist,UA.distcode,0,UA.work,wI),UA.distbits=wI.bits,xl){Se.msg="invalid distances set",UA.mode=30;break}if(UA.mode=20,mt===6)break A;case 20:UA.mode=21;case 21:if(6<=xi&&258<=gr){Se.next_out=Fr,Se.avail_out=gr,Se.next_in=Gi,Se.avail_in=xi,UA.hold=_t,UA.bits=Tt,M(Se,ln),Fr=Se.next_out,_s=Se.output,gr=Se.avail_out,Gi=Se.next_in,oi=Se.input,xi=Se.avail_in,_t=UA.hold,Tt=UA.bits,UA.mode===12&&(UA.back=-1);break}for(UA.back=0;xg=(Yg=UA.lencode[_t&(1<>>16&255,RI=65535&Yg,!((wr=Yg>>>24)<=Tt);){if(xi===0)break A;xi--,_t+=oi[Gi++]<>ac)])>>>16&255,RI=65535&Yg,!(ac+(wr=Yg>>>24)<=Tt);){if(xi===0)break A;xi--,_t+=oi[Gi++]<>>=ac,Tt-=ac,UA.back+=ac}if(_t>>>=wr,Tt-=wr,UA.back+=wr,UA.length=RI,xg===0){UA.mode=26;break}if(32&xg){UA.back=-1,UA.mode=12;break}if(64&xg){Se.msg="invalid literal/length code",UA.mode=30;break}UA.extra=15&xg,UA.mode=22;case 22:if(UA.extra){for(AE=UA.extra;Tt>>=UA.extra,Tt-=UA.extra,UA.back+=UA.extra}UA.was=UA.length,UA.mode=23;case 23:for(;xg=(Yg=UA.distcode[_t&(1<>>16&255,RI=65535&Yg,!((wr=Yg>>>24)<=Tt);){if(xi===0)break A;xi--,_t+=oi[Gi++]<>ac)])>>>16&255,RI=65535&Yg,!(ac+(wr=Yg>>>24)<=Tt);){if(xi===0)break A;xi--,_t+=oi[Gi++]<>>=ac,Tt-=ac,UA.back+=ac}if(_t>>>=wr,Tt-=wr,UA.back+=wr,64&xg){Se.msg="invalid distance code",UA.mode=30;break}UA.offset=RI,UA.extra=15&xg,UA.mode=24;case 24:if(UA.extra){for(AE=UA.extra;Tt>>=UA.extra,Tt-=UA.extra,UA.back+=UA.extra}if(UA.offset>UA.dmax){Se.msg="invalid distance too far back",UA.mode=30;break}UA.mode=25;case 25:if(gr===0)break A;if(Bo=ln-gr,UA.offset>Bo){if((Bo=UA.offset-Bo)>UA.whave&&UA.sane){Se.msg="invalid distance too far back",UA.mode=30;break}Bo>UA.wnext?(Bo-=UA.wnext,ll=UA.wsize-Bo):ll=UA.wnext-Bo,Bo>UA.length&&(Bo=UA.length),wC=UA.window}else wC=_s,ll=Fr-UA.offset,Bo=UA.length;for(gr_i?(Lt=ll[wC+xA[mt]],Ni=Tt[$u+xA[mt]]):(Lt=96,Ni=0),SA=1<>Fr)+(OA-=SA)]=Ti<<24|Lt<<16|Ni,OA!==0;);for(SA=1<>=1;if(SA!==0?(_t&=SA-1,_t+=SA):_t=0,mt++,--ln[Se]==0){if(Se===oi)break;Se=W[iA+xA[mt]]}if(_s{const M=new Uint8Array(D).slice(4);let T;try{T=Ml.inflate(M,{to:"string"})}catch(P){console.error("inflate error",P)}return T})(s.data):function(D){const M=new Uint8Array(D);let T="",P=0;const{length:W}=M;for(;P0)for(let kA=0;kA{var u;const{uplinkData:E,canResend:m,resolve:D,reject:M,timeout:T}=n;if(m){this._pendingRequests.set(g,{resolve:D,reject:M,timestamp:Date.now(),uplinkData:E,timeout:T,canResend:m});const P=this._isBinarySupported?Ga(E).buffer:E;(u=this._socketAdapter)===null||u===void 0||u.send(P)}else this._pendingRequests.delete(g)})}_onConnect(s){const{socketId:n,event:g={}}=s||{};this._connectionId=n,this._connectionEstablishedTime=Date.now();const u=Date.now()-this._connectionStartTime,E=`${ct}.onConnect cost:${u} ms. socketID:${n} res:${JSON.stringify(g)}`;if(this._ssoLog({method:"onConnect",message:E}),this._checkPendingRequestsAndResend(),this._sendHeartbeatIfReady(),this._isReconnecting){const m=`${ct}.reconnect success`;this._ssoLog({method:"reconnectSuccess",message:m}),gn.emitInnerEvent(Pe.RECONNECTED),this._isReconnecting=!1}this._resetReconnectDelay(),this._handleConnectStateChange({state:qi,shouldEmitEvent:!0,shouldAttemptReconnect:!1})}_sendAck(s){const n=ua({servcmd:"openim.ws_msg_push_ack",data:{SessionData:s}});this.sendPacket(n)}_executeScheduledTaskIfReady(){return pA(this,void 0,void 0,function*(){this._clearTimeoutRequest(),this._sendHeartbeatIfReady()})}_canSendHeartbeat(){var s;return((s=this._socketAdapter)===null||s===void 0?void 0:s.isConnected())&&Date.now()>=this._nextHeartbeatAt&&!this._isHeartbeatInProgress}_sendHeartbeat(){return pA(this,void 0,void 0,function*(){var s;const n=ua({servcmd:"heartbeat.alive",data:{}});try{const g=`${n.head.seq}${n.head.servcmd}`;yield this.sendPacket(n,{requestId:g,timeout:3e3})}catch(g){const u=(s=Xi.get("netWorkMonitor"))===null||s===void 0?void 0:s.isNetworkOnline,E=`${ct}.sendHeartbeat failed. isNetWorkOnline:${u} error: ${en(g)}`;this._ssoLog({method:"sendHeartbeatError",message:E}),this._handleConnectStateChange({state:Mi,shouldEmitEvent:!0,shouldAttemptReconnect:!0})}})}_sendHeartbeatIfReady(){return pA(this,void 0,void 0,function*(){this._canSendHeartbeat()&&(this._isHeartbeatInProgress=!0,yield this._sendHeartbeat(),this._isHeartbeatInProgress=!1)})}_updateHeartbeatTime(){this._nextHeartbeatAt=To?Date.now()+5e3:Date.now()+1e4}_handleNetworkStatusChange(s){const n=`${ct}.networkStatusChange ${JSON.stringify(s)}`;this._ssoLog({method:"networkStatusChange",message:n});const{isNetworkOnline:g,networkType:u}=s;g&&u!=="none"?this._handleConnectStateChange({state:qi,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Mg}):this._handleConnectStateChange({state:Mi,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Mg})}isPrivateNetWork(){const s=Xi.get("instance")||{};return s.proxyServer&&!s.fileDownloadProxy}_handleConnectStateChange(s){const{state:n,shouldAttemptReconnect:g,shouldEmitEvent:u,reason:E}=s,m=`${ct}._handleConnectStateChange currentConnectState: ${this._currentConnectState} shouldAttemptReconnect: ${g} shouldEmitEvent: ${u} reason: ${E}`;this._currentConnectState!==n&&(this._ssoLog({method:"handleConnectStateChange",message:m}),u&&(Pt.info("_handleConnectStateChange",` from ${this._currentConnectState} to ${n}`),gn.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:n}}),this._currentConnectState=n,n===Mi&&gn.emitInnerEvent(Pe.SOCKET_DISCONNECTED)),g&&(this._resetReconnectDelay(),fn.addTask({id:Ji,intervalMs:this._intendedDelay,callback:this._scheduleReconnectWithBackoff,context:this})))}_handleActivityStatusChange(s){var n,g;const u=(g=(n=this._socketAdapter)===null||n===void 0?void 0:n._ws)===null||g===void 0?void 0:g.readyState,E=`${ct}.activityStatusChange ${JSON.stringify(s)} readyState: ${u}`;Pt.debug("activityStatusChange",E),u===3&&this._handleConnectStateChange({state:Mi,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:sr})}_resetReconnectDelay(){var s;Pt.debug(`${ct}._resetReconnectDelay`),fn.removeTask(Ji);const n=(s=Xi.get("activityMonitor"))===null||s===void 0?void 0:s.isActive;this._intendedDelay=n?zo:1e3}_scheduleReconnectWithBackoff(){var s;const n=(s=Xi.get("activityMonitor"))===null||s===void 0?void 0:s.isActive;this._intendedDelay=n?Math.min(5e3,Math.max(zo,1.5*this._intendedDelay)):Math.min(3e5,Math.max(1e3,1.5*this._intendedDelay));const g=new Date().toTimeString().slice(0,8),u=`${ct}.scheduleReconnectWithBackoff timeStr: ${g} intendedDelay: ${this._intendedDelay}`;Pt.debug(u),this.reconnect(),fn.updateTaskInterval(Ji,this._intendedDelay)}_ssoLog(s){const{method:n,message:g}=s;Pt.info(n,g)}_diagnose(){this.isPrivateNetWork()||(this._lastDiagnoseAt=Date.now(),function(s){pA(this,void 0,void 0,function*(){const n=s.split("/")[2];if(!n.startsWith("ws"))return;const g=`https://${n}/v3/netcheck/getconninfo?${s.slice(s.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield Pi({method:"GET",url:g,data:{}})}catch(u){Pt.warn("diagnoseBySSO",`diagnoseBySSO failed. error:${u.message}`)}})}(this._url),function(s){pA(this,void 0,void 0,function*(){const n=`https://boce-cdn.my-imcloud.com/v3/netcheck/getconninfo?${s.slice(s.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield Pi({method:"GET",url:n,data:{}})}catch(g){Pt.warn(`diagnoseByCDN', 'diagnoseByCDN failed. error:${g.message}`)}})}(this._url),this._beforeSendInterceptors=[])}_clearTimeoutRequest(){for(const[s,n]of this._pendingRequests.entries()){const{reject:g,timestamp:u,timeout:E}=n;Date.now()-u>=E&&(this._pendingRequests.delete(s),Date.now()-this._lastDiagnoseAt>=3e4&&this._diagnose(),g({errorCode:Qr,errorInfo:"NETWORK_TIMEOUT",data:{requestId:s}}))}}_updateIsBinarySupported(){var s;if(!((s=Xi.get("instance"))===null||s===void 0)&&s.devMode)return void(this._isBinarySupported=!1);const n=Es();if((gi||Le&&n==="windows"||Vs)&&(this._isBinarySupported=!1),To){const{uniRuntimeVersion:g=""}=io.getSystemInfoSync();(function(u){const E=u.split(".").map(Number),[m=0,D=0,M=0]=E;return m>2||!(m<2)&&(D>2||!(D<2)&&M>=6)})(g)||(this._isBinarySupported=!1)}}_isCompressedData(s){const n=new Uint8Array(s);return n[0]===67&&n[1]===79&&n[2]===77&&n[3]===80}};const fe={init:function(s){Xi.set("instance",s),ye.init()},destroy:function(){ye.dispose(),Xi.clear(),fn.dispose()},notificationCenter:gn,channel:ye,store:Xi,ssoLog:Pt,utils:yg,common:vA,constants:_e},vg=s=>typeof s=="function";function rg(s,n,g){const u=g||[];if(!s||!n)return!1;const E=Object.keys(s).filter(D=>!u.includes(D)),m=Object.keys(n).filter(D=>!u.includes(D));return E.length===m.length&&E.every(D=>!!n.hasOwnProperty(D)&&(typeof s[D]=="object"&&s[D]!==null?rg(s[D],n[D],g):s[D]===n[D]))}var Rg;(function(s){s.SDK_READY="sdkStateReady",s.SDK_NOT_READY="sdkStateNotReady",s.SDK_DESTROY="sdkDestroy",s.MESSAGE_RECEIVED="onMessageReceived",s.ROOM_CUSTOM_DATA_RECEIVED="onRoomCustomDataReceived",s.MESSAGE_MODIFIED="onMessageModified",s.MESSAGE_REVOKED="onMessageRevoked",s.MESSAGE_READ_BY_PEER="onMessageReadByPeer",s.MESSAGE_READ_RECEIPT_RECEIVED="onMessageReadReceiptReceived",s.MESSAGE_EXTENSIONS_UPDATED="onMessageExtensionsUpdated",s.MESSAGE_EXTENSIONS_DELETED="onMessageExtensionsDeleted",s.MESSAGE_REACTIONS_UPDATED="onMessageReactionsUpdated",s.CONVERSATION_LIST_UPDATED="onConversationListUpdated",s.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED="onTotalUnreadMessageCountUpdated",s.CONVERSATION_GROUP_LIST_UPDATED="onConversationGroupListUpdated",s.CONVERSATION_IN_GROUP_UPDATED="onConversationInGroupUpdated",s.GROUP_LIST_UPDATED="onGroupListUpdated",s.GROUP_ATTRIBUTES_UPDATED="groupAttributesUpdated",s.GROUP_COUNTER_UPDATED="onGroupCounterUpdated",s.TOPIC_CREATED="onTopicCreated",s.TOPIC_DELETED="onTopicDeleted",s.TOPIC_UPDATED="onTopicUpdated",s.PROFILE_UPDATED="onProfileUpdated",s.USER_STATUS_UPDATED="onUserStatusUpdated",s.BLACKLIST_UPDATED="blacklistUpdated",s.FRIEND_LIST_UPDATED="onFriendListUpdated",s.FRIEND_GROUP_LIST_UPDATED="onFriendGroupListUpdated",s.FRIEND_APPLICATION_LIST_UPDATED="onFriendApplicationListUpdated",s.MY_FOLLOWERS_LIST_UPDATED="onMyFollowersListUpdated",s.MY_FOLLOWING_LIST_UPDATED="onMyFollowingListUpdated",s.MUTUAL_FOLLOWERS_LIST_UPDATED="onMutualFollowersListUpdated",s.KICKED_OUT="kickedOut",s.ERROR="error",s.NET_STATE_CHANGE="netStateChange",s.ALL_RECEIVE_MESSAGE_OPT_UPDATED="onAllReceiveMessageOptUpdated",s.SERVER_CONFIG_UPDATED="onServerConfigUpdated",s.PINNED_GROUP_MESSAGE_UPDATED="onPinnedGroupMessageUpdated",s.WEB_PUSH_MESSAGE_RECEIVED="onWebPushMessageReceived",s.GROUP_ONLINE_MEMBER_COUNT_CHANGED="onGroupOnlineMemberCountChanged",s.RICH_STATUS_CHANGED="onRichStatusChanged"})(Rg||(Rg={}));var Dn,Dr=Rg;(function(s){s.LOGOUT="logout",s.DESTROY="destroy",s.CLOUD_CONFIG_UPDATE="cloud_config_update",s.PROFILE_UPDATE="profile_updated",s.ERROR="error",s.RECONNECTED="reconnected",s.FORCE_OFFLINE="im_open_status.stat_forceoffline",s.COMMERCIAL_CONFIG_PUSH="im_sdk_config_mgr.push_imsdk_purchase_bitsv2",s.OVERLOAD_PUSH="OverLoadPush.notify2",s.NEW_MESSAGE="new_message",s.MESSAGE_PUSH="im_open_push.msg_push",s.MESSAGE_DELETED="message_deleted",s.MESSAGE_REVOKED="message_revoked",s.MESSAGE_MODIFIED="message_modified",s.SOCKET_DISCONNECTED="socket_disconnected",s.CONVERSATION_UPDATED="conversation_updated",s.TOPIC_MESSAGE_DELETED="topic_message_deleted",s.TOPIC_MESSAGE_REVOKED="topic_message_revoked",s.TOPIC_MESSAGE_MODIFIED="topic_message_modified",s.TOPIC_NEW_MESSAGE="topic_new_message",s.QUALITY_STAT="quality_stat",s.SYNC_CONVERSATION_LIST="sync_conversation_list",s.HISTORY_MESSAGE_FETCHED="history_message_fetched"})(Dn||(Dn={}));var Ii,so=Dn;(function(s){s.NEW_INVITATION_RECEIVED="newInvitationReceived",s.INVITEE_ACCEPTED="ts_invitee_accepted",s.INVITEE_REJECTED="ts_invitee_rejected",s.INVITATION_CANCELLED="ts_invitation_cancelled",s.INVITATION_TIMEOUT="ts_invitation_timeout",s.INVITATION_MODIFIED="ts_invitation_modified"})(Ii||(Ii={}));var Hc=Ii;const zg=Object.assign({},{KICKED_OUT_MULT_ACCOUNT:"multipleAccount",KICKED_OUT_MULT_DEVICE:"multipleDevice",KICKED_OUT_USERSIG_EXPIRED:"userSigExpired",KICKED_OUT_REST_API:"REST_API_Kick"}),wg={MSG_TEXT:"TIMTextElem",MSG_IMAGE:"TIMImageElem",MSG_AUDIO:"TIMSoundElem",MSG_FILE:"TIMFileElem",MSG_FACE:"TIMFaceElem",MSG_VIDEO:"TIMVideoFileElem",MSG_LOCATION:"TIMLocationElem",MSG_GRP_TIP:"TIMGroupTipElem",MSG_GRP_SYS_NOTICE:"TIMGroupSystemNoticeElem",MSG_CUSTOM:"TIMCustomElem",MSG_MERGER:"TIMRelayElem",MSG_STREAM:"TIMStreamElem"};var Yr;(function(s){s.UNSENT="unSend",s.SUCCESS="success",s.FAIL="fail"})(Yr||(Yr={}));const yc={modify:so.MESSAGE_MODIFIED,delete:so.MESSAGE_DELETED,revoke:so.MESSAGE_REVOKED};var qc;(function(s){s[s.FORWARD=0]="FORWARD",s[s.BACKWARD=1]="BACKWARD"})(qc||(qc={}));const ag=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},wg),{MSG_PRIORITY_HIGH:"High",MSG_PRIORITY_NORMAL:"Normal",MSG_PRIORITY_LOW:"Low",MSG_PRIORITY_LOWEST:"Lowest"}),{RECEIVE_WITH_OFFLINE_PUSH_EXCEPT_AT:"AcceptNotNotifyExceptAt",NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT:"AcceptNotNotifyExceptAt",NOT_RECEIVE_MSG_EXCEPT_AT:"NotReceiveMsgExceptAt",MSG_AT_ALL:"__kImSDK_MesssageAtALL__"}),{MSG_REMIND_ACPT_AND_NOTE:"AcceptAndNotify",MSG_REMIND_ACPT_NOT_NOTE:"AcceptNotNotify",MSG_REMIND_DISCARD:"Discard"}),{MessageStatus:Yr,Direction:qc}),vu={[yc.modify]:so.TOPIC_MESSAGE_MODIFIED,[yc.delete]:so.TOPIC_MESSAGE_DELETED,[yc.revoke]:so.TOPIC_MESSAGE_REVOKED},mE={GENDER_UNKNOWN:"Gender_Type_Unknown",GENDER_FEMALE:"Gender_Type_Female",GENDER_MALE:"Gender_Type_Male",USER_STATUS_UNKNOWN:0,USER_STATUS_ONLINE:1,USER_STATUS_OFFLINE:2,USER_STATUS_UNLOGINED:3,USER_NOT_FOUND:"@TLS#NOT_FOUND"},_g=Object.assign({},mE),ka={CONV_C2C:"C2C",CONV_GROUP:"GROUP",CONV_TOPIC:"TOPIC",CONV_SYSTEM:"@TIM#SYSTEM"},Dc=Object.assign(Object.assign(Object.assign(Object.assign({},ka),{CONV_AT_ME:1,CONV_AT_ALL:2,CONV_AT_ALL_AT_ME:3}),{CONV_MARK_TYPE_STAR:1,CONV_MARK_TYPE_UNREAD:2,CONV_MARK_TYPE_FOLD:4,CONV_MARK_TYPE_HIDE:8}),{READ_ALL_C2C_MSG:"readAllC2CMessage",READ_ALL_GROUP_MSG:"readAllGroupMessage",READ_ALL_MSG:"readAllMessage"}),fE=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},{SNS_TYPE_NO_RELATION:"CheckResult_Type_NoRelation",SNS_TYPE_A_WITH_B:"CheckResult_Type_AWithB",SNS_TYPE_B_WITH_A:"CheckResult_Type_BWithA",SNS_TYPE_BOTH_WAY:"CheckResult_Type_BothWay"}),{ALLOW_TYPE_ALLOW_ANY:"AllowType_Type_AllowAny",ALLOW_TYPE_NEED_CONFIRM:"AllowType_Type_NeedConfirm",ALLOW_TYPE_DENY_ANY:"AllowType_Type_DenyAny"}),{SNS_ADD_TYPE_SINGLE:"Add_Type_Single",SNS_ADD_TYPE_BOTH:"Add_Type_Both"}),{SNS_DELETE_TYPE_SINGLE:"Delete_Type_Single",SNS_DELETE_TYPE_BOTH:"Delete_Type_Both"}),{SNS_APPLICATION_TYPE_BOTH:"Pendency_Type_Both",SNS_APPLICATION_SENT_TO_ME:"Pendency_Type_ComeIn",SNS_APPLICATION_SENT_BY_ME:"Pendency_Type_SendOut",SNS_APPLICATION_AGREE:"Response_Action_Agree",SNS_APPLICATION_AGREE_AND_ADD:"Response_Action_AgreeAndAdd"}),{SNS_CHECK_TYPE_BOTH:"CheckResult_Type_Both",SNS_CHECK_TYPE_SINGLE:"CheckResult_Type_Single"}),{FORBID_TYPE_NONE:"AdminForbid_Type_None",FORBID_TYPE_SEND_OUT:"AdminForbid_Type_SendOut"}),La={GRP_WORK:"Private",GRP_PUBLIC:"Public",GRP_MEETING:"ChatRoom",GRP_AVCHATROOM:"AVChatRoom",GRP_COMMUNITY:"Community",GRP_ROOM:"Room",GRP_LIVE:"Live"},sa={COMMUNITY:"@TGS#_",TOPIC:"@TOPIC#_"},Tg={JOINED:1,QUITTED:2,KICKED:3,ADMIN_SET:4,ADMIN_CANCELED:5,GROUP_PROFILE_UPDATED:6,GROUP_MEMBER_PROFILE_UPDATED:7,TOPIC_PROFILE_UPDATED:8},aI=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},La),{GRP_MBR_ROLE_OWNER:"Owner",GRP_MBR_ROLE_ADMIN:"Admin",GRP_MBR_ROLE_MEMBER:"Member",GRP_MBR_ROLE_CUSTOM:"Custom"}),{GRP_TIP_MBR_JOIN:1,GRP_TIP_MBR_QUIT:2,GRP_TIP_MBR_KICKED_OUT:3,GRP_TIP_MBR_SET_ADMIN:4,GRP_TIP_MBR_CANCELED_ADMIN:5,GRP_TIP_GRP_PROFILE_UPDATED:6,GRP_TIP_MBR_PROFILE_UPDATED:7,GRP_TIP_BAN_AVCHATROOM_MEMBER:10,GRP_TIP_UNBAN_AVCHATROOM_MEMBER:11}),{JOIN_OPTIONS_FREE_ACCESS:"FreeAccess",JOIN_OPTIONS_NEED_PERMISSION:"NeedPermission",JOIN_OPTIONS_DISABLE_APPLY:"DisableApply",JOIN_STATUS_SUCCESS:"JoinedSuccess",JOIN_STATUS_ALREADY_IN_GROUP:"AlreadyInGroup",JOIN_STATUS_WAIT_APPROVAL:"WaitAdminApproval"}),{INVITE_OPTIONS_DISABLE_INVITE:"DisableInvite",INVITE_OPTIONS_NEED_PERMISSION:"NeedPermission",INVITE_OPTIONS_FREE_ACCESS:"FreeAccess"}),{GRP_PROFILE_OWNER_ID:"ownerID",GRP_PROFILE_CREATE_TIME:"createTime",GRP_PROFILE_LAST_INFO_TIME:"lastInfoTime",GRP_PROFILE_MEMBER_NUM:"memberNum",GRP_PROFILE_MAX_MEMBER_NUM:"maxMemberNum",GRP_PROFILE_JOIN_OPTION:"joinOption",GRP_PROFILE_INVITE_OPTION:"inviteOption",GRP_PROFILE_INTRODUCTION:"introduction",GRP_PROFILE_NOTIFICATION:"notification",GRP_PROFILE_MUTE_ALL_MBRS:"muteAllMembers"}),{GROUP_ID_PREFIX:sa,GROUP_TIPS_OPERATION_TYPE:Tg}),hs={IOS_OFFLINE_PUSH_NO_SOUND:"push.no_sound",IOS_OFFLINE_PUSH_DEFAULT_SOUND:"default"},Lo=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},zg),ag),_g),Dc),fE),aI),hs),{NET_STATE_CONNECTING:"connecting",NET_STATE_DISCONNECTED:"disconnected",NET_STATE_CONNECTED:"connected"}),Ea={NO_SDKAPPID:2e3,NO_TINYID:2022,NO_A2KEY:2023,USER_NOT_LOGGED_IN:2024,REPEAT_LOGIN:2025,MSG_SEND_FAIL:2100,MSG_SEND_FAIL_NOT_IN_AV:2101,MSG_SEND_GRP_WITH_TOPIC_FAIL:2115,MSG_INSTANCE_REQUIRED:2105,MSG_INVALID_CONV_TYPE:2106,MSG_REVOKE_FAIL:2110,MSG_DELETE_FAIL:2111,MSG_UNREAD_ALL_FAIL:2112,READ_RECEIPT_MSG_LIST_EMPTY:2114,CANNOT_DELETE_GRP_SYSTEM_NOTICE:2116,NOT_MY_FRIEND:2700,NETWORK_ERROR:2800,NETWORK_TIMEOUT:2801,NO_NETWORK:2805,UNCAUGHT_ERROR:2903,INVALID_OPERATION:2905,SDK_IS_NOT_READY:2999,LOGGING_IN:3e3,LOGIN_FAILED:3001,KICKED_OUT_MULT_DEVICE:3002,KICKED_OUT_MULT_ACCOUNT:3003,KICKED_OUT_USERSIG_EXPIRED:3004,LOGGED_OUT:3005,KICKED_OUT_REST_API:3006,NO_USE:3122,OPTIONS_IS_EMPTY:3153,MSG_A2KEY_EXPIRED:20002,ACCOUNT_A2KEY_EXPIRED:70001,HELLO_ANSWER_KICKED_OUT:1002,OPEN_SERVICE_OVERLOAD_ERROR:60022},nr={BASIC:"1",STANDARD:"2",PROFESSIONAL:"3",NODE:"4"},xt={SYNC_SERVER_INFO_AFTER_RE_ONLINE:"sync-server-info-after-re-online",SYNC_SERVER_INFO_AFTER_LOGIN:"sync-server-info-after-login",RECEIVE_C2C_NEW_MESSAGE:"receive-c2c-new-message",RECEIVE_GROUP_NEW_MESSAGE:"receive-group-new-message",RECEIVE_GROUP_TIPS_NOTIFICATION:"receive-group-tips-notification"},qt={USER_STATUS_UPDATE:"user-status-update",CONVERSATION_RECOVER:"conversation-recover",HISTORY_MESSAGE_RECOVER:"history-message-recover",BLACKLIST_RECOVER:"blacklist-recover",FRIEND_RECOVER:"friend-recover",GROUP_ATTRIBUTE_CACHE_CLEAR:"group-attribute-cache-clear",UNREAD_MESSAGE_RECOVER:"unread-message-recover",HANDLE_NEW_MESSAGE:"handle-new-message",HANDLE_CONVERSATION_PROFILE_UPDATED:"handle-conversation-profile-updated",COMMERCIAL_CONFIG_UPDATE:"commercial-config-update",UNREAD_MESSAGE_SYNC:"unread-message-sync",FRIEND_AND_BLACKLIST_SYNC:"friend-and-blacklist-sync",SIGNALING_MESSAGE_RECOVER:"signaling-message-recover",GROUP_LIST_SYNC:"group-list-sync",CONVERSATION_LIST_SYNC:"conversation-list-sync",USER_PROFILE_SYNC:"user-profile-sync",CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED:"conversation-update-after-unread-sync-finished",CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED:"conversation-update-after-group-list-sync-finished",HANDLE_C2C_NEW_MESSAGE:"handle-c2c-new-message",HANDLE_GROUP_NEW_MESSAGE:"handle-group-new-message",CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE:"create-or-update-conversation-by-receive-new-message",HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD:"handle-group-tips-from-sync-unread",HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD:"handle-c2c-revoked-message-from-sync-unread",GROUP_REVOKED_NOTICE_RECOVER:"group-revoked-notice-recover",CLOUD_CONFIG_SYNC:"cloud-config-sync",UPDATE_GROUP_NEXT_SEQUENCE:"update-group-next-sequence",EMIT_C2C_MESSAGE_EVENT:"emit-c2c-message-event",EMIT_GROUP_MESSAGE_EVENT:"emit-group-message-event",CONVERSATION_GROUP_LIST_SYNC:"conversation-group-list-sync",CONVERSATION_GROUP_UPDATE:"conversation-group-update",UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED:"update-topic-after-unread-sync-finished",UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE:"update-topic-by-received-new-message",TOPIC_REQUEST_INFO_RESET:"topic-request-info-reset",QUALITY_REPORT:"quality-report",GROUP_TIPS_RECOVER:"group-tips-recover",HANDLE_GROUP_TIPS_NOTIFICATION:"handle-group-tips-notification",C2C_HISTORY_MESSAGE_RECOVER:"c2c-history-message-recover",FRIEND_APPLICATION_LIST_RECOVER:"friend-application-list-recover",EMIT_GROUP_TIPS_EVENT:"emit-group-tips-event",STREAM_MESSAGE_RECOVER:"stream-message-recover"},Ng={[xt.SYNC_SERVER_INFO_AFTER_RE_ONLINE]:[{stepId:qt.USER_STATUS_UPDATE},{stepId:qt.GROUP_ATTRIBUTE_CACHE_CLEAR},{stepId:qt.UNREAD_MESSAGE_SYNC,dependency:qt.C2C_HISTORY_MESSAGE_RECOVER},{stepId:qt.CONVERSATION_RECOVER},{stepId:qt.HISTORY_MESSAGE_RECOVER,dependency:qt.CONVERSATION_RECOVER},{stepId:qt.BLACKLIST_RECOVER},{stepId:qt.FRIEND_RECOVER},{stepId:qt.FRIEND_APPLICATION_LIST_RECOVER},{stepId:qt.GROUP_REVOKED_NOTICE_RECOVER,dependency:qt.HISTORY_MESSAGE_RECOVER},{stepId:qt.GROUP_TIPS_RECOVER,dependency:qt.HISTORY_MESSAGE_RECOVER},{stepId:qt.TOPIC_REQUEST_INFO_RESET},{stepId:qt.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,dependency:qt.UNREAD_MESSAGE_SYNC},{stepId:qt.HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD,dependency:qt.UNREAD_MESSAGE_SYNC},{stepId:qt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[qt.UNREAD_MESSAGE_SYNC,qt.CONVERSATION_RECOVER]},{stepId:qt.EMIT_C2C_MESSAGE_EVENT,dependency:[qt.UNREAD_MESSAGE_SYNC,qt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED],skipIfDependencyMissing:!1},{stepId:qt.C2C_HISTORY_MESSAGE_RECOVER,dependency:qt.CONVERSATION_RECOVER},{stepId:qt.STREAM_MESSAGE_RECOVER}],[xt.SYNC_SERVER_INFO_AFTER_LOGIN]:[{stepId:qt.COMMERCIAL_CONFIG_UPDATE},{stepId:qt.CLOUD_CONFIG_SYNC},{stepId:qt.USER_PROFILE_SYNC},{stepId:qt.UNREAD_MESSAGE_SYNC},{stepId:qt.FRIEND_AND_BLACKLIST_SYNC},{stepId:qt.GROUP_LIST_SYNC},{stepId:qt.CONVERSATION_LIST_SYNC},{stepId:qt.SIGNALING_MESSAGE_RECOVER,dependency:qt.UNREAD_MESSAGE_SYNC},{stepId:qt.UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED,dependency:[qt.UNREAD_MESSAGE_SYNC]},{stepId:qt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[qt.UNREAD_MESSAGE_SYNC,qt.CONVERSATION_LIST_SYNC]},{stepId:qt.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,dependency:[qt.GROUP_LIST_SYNC,qt.CONVERSATION_LIST_SYNC]},{stepId:qt.CONVERSATION_GROUP_LIST_SYNC},{stepId:qt.CONVERSATION_GROUP_UPDATE,dependency:[qt.CONVERSATION_LIST_SYNC,qt.CONVERSATION_GROUP_LIST_SYNC]},{stepId:qt.QUALITY_REPORT}],[xt.RECEIVE_C2C_NEW_MESSAGE]:[{stepId:qt.HANDLE_C2C_NEW_MESSAGE},{stepId:qt.UNREAD_MESSAGE_SYNC},{stepId:qt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:qt.HANDLE_C2C_NEW_MESSAGE},{stepId:qt.EMIT_C2C_MESSAGE_EVENT,dependency:[qt.HANDLE_C2C_NEW_MESSAGE,qt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1},{stepId:qt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[qt.UNREAD_MESSAGE_SYNC]}],[xt.RECEIVE_GROUP_NEW_MESSAGE]:[{stepId:qt.HANDLE_GROUP_NEW_MESSAGE},{stepId:qt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:qt.HANDLE_GROUP_NEW_MESSAGE},{stepId:qt.UPDATE_GROUP_NEXT_SEQUENCE,dependency:qt.HANDLE_GROUP_NEW_MESSAGE},{stepId:qt.UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE,dependency:qt.HANDLE_GROUP_NEW_MESSAGE},{stepId:qt.EMIT_GROUP_MESSAGE_EVENT,dependency:[qt.HANDLE_GROUP_NEW_MESSAGE,qt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1}],[xt.RECEIVE_GROUP_TIPS_NOTIFICATION]:[{stepId:qt.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:qt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:qt.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:qt.EMIT_GROUP_TIPS_EVENT,dependency:[qt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,qt.HANDLE_GROUP_TIPS_NOTIFICATION],skipIfDependencyMissing:!1}]},gI={MESSAGE_SEND_SUCCESS_RATE:"messageSendSuccessRate"},rr={TOTAL_COUNT:"sendMessageTotalCount",SUCCESS_COUNT:"sendMessageSuccessCount",FAILED_COUNT:"sendMessageFailedCount",SEND_COST:"sendMessageCost"},JI=["login","getMyProfile","getUserProfile","updateMyProfile","setSelfStatus","getUserStatus","subscribeUserStatus","unsubscribeUserStatus","modifyMessage","deleteGroupMember","dismissGroup","getGroupMemberList","getGroupOnlineMemberCount","joinGroup","markGroupMemberList","quitGroup","searchCloudMessages","searchCloudGroups","searchCloudGroupMembers","searchCloudUsers","getMyFollowingList","getMyFollowersList","getMutualFollowersList","followUser","unfollowUser","getUserFollowInfo","checkFollowType","getFriendProfile","addFriend","deleteFriend","updateFriend","checkFriend","setFriendApplicationRead","createFriendGroup","deleteFriendGroup","addToFriendGroup","removeFromFriendGroup","renameFriendGroup","changeGroupOwner","createGroup","dismissGroup","getGroupList","getGroupOnlineMemberCount","getGroupProfile","searchGroupByID","updateGroupProfile","handleGroupApplication","deleteGroupAttributes","getGroupAttributes","initGroupAttributes","setGroupAttributes","addGroupMember","deleteGroupMember","getGroupMemberList","getGroupMemberProfile","setGroupMemberMuteTime","setGroupMemberNameCard","setGroupMemberRole","deleteMessage","revokeMessage","setMessageExtensions","getMessageExtensions","deleteMessageExtensions","getMessageList","addMessageReaction","removeMessageReaction","clearHistoryMessage","sendMessageReadReceipt","getMessageReadReceiptList","getGroupMessageReadMemberList","createMergerMessage","invite","accept","cancel","reject","modifyInvitation","deleteConversation","pinConversation","setMessageRead","setAllMessageRead","getConversationList","getTotalUnreadMessageCount","renameConversationGroup","deleteConversationGroup","markConversation","setConversationCustomData","deleteConversationsFromGroup","addConversationsToGroup","createConversationGroup"];var za=Object.freeze({__proto__:null,ERROR_CODE:Ea,InnerEvent:so,NEED_LOG_API:JI,OuterConstant:Lo,OuterEvent:Dr,PUSH:hs,QUALITY_METRICS:gI,SDK_EDITION:nr,SDK_INFO:{VERSION:"1.7.3",APPID:537048168},SEND_MESSAGE_STAT:rr,SignalingEvent:Hc,WEB_PUSH_ACCOUNT_TYPE:1,WORKFLOW_DEFINITIONS:Ng,WORKFLOW_NAME:xt,WORKFLOW_STEP:qt}),na,un,Sn;(function(s){s[s.USER_INITIATED=0]="USER_INITIATED",s[s.KICKED_OUT=1]="KICKED_OUT"})(na||(na={})),function(s){s[s.multipleAccount=1]="multipleAccount",s[s.multipleDevice=2]="multipleDevice",s[s.restApi=3]="restApi"}(un||(un={})),function(s){s[s.multipleDevice=3002]="multipleDevice",s[s.multipleAccount=3003]="multipleAccount",s[s.usersigExpired=70001]="usersigExpired",s[s.restApi=20002]="restApi"}(Sn||(Sn={}));const Ru={[un.multipleAccount]:"multipleAccount",[un.multipleDevice]:"multipleDevice",[un.restApi]:"REST_API_Kick",[Sn.multipleAccount]:"multipleAccount",[Sn.multipleDevice]:"multipleDevice",[Sn.restApi]:"REST_API_Kick",[Sn.usersigExpired]:"userSigExpired"},Gg="login_online_presence_task",{ERROR:Ua,DESTROY:Kc,FORCE_OFFLINE:HI}=so,{KICKED_OUT_MULT_ACCOUNT:yE,KICKED_OUT_MULT_DEVICE:cI,KICKED_OUT_REST_API:wu,ACCOUNT_A2KEY_EXPIRED:vl,MSG_A2KEY_EXPIRED:Sc}=Ea;class _u{init(){const{notificationCenter:n}=fe;n.subscribeInnerEvent(HI,this._handleForceOfflineFromServerPush,this),n.subscribeInnerEvent(Ua,Sc,this._handleForceOfflineFromResponse,this,this._isChatLoginEvent),n.subscribeInnerEvent(Ua,vl,this._handleForceOfflineFromResponse,this,this._isChatLoginEvent),n.subscribeInnerEvent(Ua,yE,this._handleForceOfflineFromResponse,this),n.subscribeInnerEvent(Ua,cI,this._handleForceOfflineFromResponse,this),n.subscribeInnerEvent(Ua,wu,this._handleForceOfflineFromResponse,this),n.subscribeInnerEvent(Kc,this._dispose,this)}_handleForceOfflineFromServerPush(n){var g;if(((g=fe.store.get("login"))===null||g===void 0?void 0:g.isLoggedIn)===!0){const{EventArray:u=[]}=n?.body||{};this._extractKickedOutMessages(u).forEach(E=>{const{KickoutMsgNotify:{KickType:m,NewInstInfo:D,Instid:M}}=E;this._isCurrentInstanceKickedOut(M)&&this._processKickedOutReasonInfo({kickedOutReasonCode:m,newInstanceInfo:D})})}}_extractKickedOutMessages(n){return n.reduce((g,u)=>[...g,...u.C2cNotifyMsgArray||[]],[]).filter(g=>{var u;return this._isKickedOut((u=g?.KickoutMsgNotify)===null||u===void 0?void 0:u.KickType)})}_handleForceOfflineFromResponse(n){const{errorCode:g}=n;this._processKickedOutReasonInfo({kickedOutReasonCode:g})}_processKickedOutReasonInfo(n){return pA(this,void 0,void 0,function*(){const{kickedOutReasonCode:g}=n,{ssoLog:u,utils:{safeStringify:E}}=fe;try{this._logKickedOutEvent(n),this._shouldLogoutAfterKickedOut(g)?yield fe.login.loginAction.logout(na.KICKED_OUT):fe.login.loginAction.handleLogoutCompleted()}catch(m){u.debug("_processKickedOutReasonInfo",` fail ${E(m)}`)}finally{fe.notificationCenter.emitOuterEvent(Dr.KICKED_OUT,{data:{type:Ru[g]},name:Dr.KICKED_OUT})}})}_logKickedOutEvent(n){const{kickedOutReasonCode:g,newInstanceInfo:u={}}=n,E=`type:${Ru[g]} newInstanceInfo: ${JSON.stringify(u)}`;fe.ssoLog.warn("kickedOut",E)}_isKickedOut(n){return[un.multipleAccount,un.multipleDevice,un.restApi].includes(n)}_isChatLoginEvent(n){const{requestHead:g}=n||{};return g?.idtype!==1}_shouldLogoutAfterKickedOut(n){return![Sn.usersigExpired,un.restApi].includes(n)}_isCurrentInstanceKickedOut(n){const{isLoggedIn:g,statusInstanceId:u}=fe.store.get("login")||{};return g===!0&&n===u}_dispose(){const{notificationCenter:n}=fe;n.unSubscribeInnerEvent(HI,this._handleForceOfflineFromServerPush,this),n.unSubscribeInnerEvent(Ua,vl,this._handleForceOfflineFromResponse,this),n.unSubscribeInnerEvent(Ua,Sc,this._handleForceOfflineFromResponse,this),n.unSubscribeInnerEvent(Ua,yE,this._handleForceOfflineFromResponse,this),n.unSubscribeInnerEvent(Ua,cI,this._handleForceOfflineFromResponse,this),n.unSubscribeInnerEvent(Ua,wu,this._handleForceOfflineFromResponse,this),n.unSubscribeInnerEvent(Kc,this._dispose,this)}}function Tu(s){return pA(this,void 0,void 0,function*(){const n="im_open_status.wslogin",g=fe.common.generateProtocolData({servcmd:n,data:{State:"Online",is_web_uniapp:0,InstType:0,CustomInfo:s}}),u=`${g.head.seq}${n}`,E=yield fe.channel.sendPacket(g,{timeout:9e4,requestId:u});if(E){const{HelloInterval:m,InstId:D,TinyId:M,TimeStamp:T,CustomStatus:P,PurchaseBits:W,A2Key:iA,RichMsgAuthKey:EA,ErrorCode:RA,ErrorInfo:kA,ActionStatus:xA}=E;return{helloInterval:m,instanceID:D,tinyID:M,timeStamp:T,customStatus:P,purchaseBits:W,a2Key:iA,authKey:EA,errorCode:RA,errorInfo:kA,actionStatus:xA}}})}function Rl(){const{store:s}=fe;return Ia(s.get("instance").sdkAppId)!==ut.CHINA}function rs(s){var n;try{const g=Xi.getStorage("errorMessage");if(!s||!g)return"";const u=((n=JSON.parse(g))===null||n===void 0?void 0:n.errorMessage)||{},{code:E,replacement1:m="",replacement2:D=""}=s;if(!E)return"";const M=Rl()?`${E}_en`:`${E}_cn`;let T=u[u[M]?M:E]||"";return T&&(m&&(T=T.replace("$replacement1",m)),D&&(T=T.replace("$replacement2",D))),T}catch(g){return console.warn("Error parsing stored error messages:",g),""}}class gs extends Error{constructor(n={}){n.code=n.code||n.errorCode;let{functionName:g="Unknown",code:u,message:E="",data:m="",moreMessage:D="",errorMessage:M=""}=n;M=(u?rs(n):"")||M||E;let T=u?`${g} failed. error: {"message": ${M}, "code": ${u}}`:`${g} failed. error: {"message": ${M}}`;T=`${T} ${D}`,super(),this.code=u,this.errorCode=u,this.errorMessage=M,this.message=T,this.data=m}}function Id(s,n){var g;if(s&&((g=fe.store.get("login"))===null||g===void 0?void 0:g.isLoggedIn)!==!0)throw new gs({code:Ea.USER_NOT_LOGGED_IN,functionName:n})}function lI(s,n,g){if(Array.isArray(s))for(let u=0;u{return P===(W=u,Object.prototype.toString.call(W).match(/^\[object (.*)\]$/)[1].toLowerCase());var W})){for(let W=0;W{const{interceptor:E,context:m}=u;E.apply(m,[g])})}(s)}function Mc(s,n){DE.push({interceptor:s,context:n})}function jc(s){const{params:n,auth:g}=s;n&&typeof n=="object"&&Object.assign(wl,n),g&&typeof g=="object"&&Object.assign(ud,g)}function tn(s){return fe.store.get("commercialConfig").get(s)}class ws{constructor(){this._handlers=new Map,this._activeWorkflows=new Map,this._stepStartTimes=new Map,this._logHandlers={start:(n,g)=>{const u=Date.now();g?(this._stepStartTimes.set(`${n}-${g}`,u),fe.ssoLog.debug("_executeWorkflowStep",`[Workflow ${n}] Step ${g} started at ${new Date(u).toISOString()}`)):(this._workflowStartTimes.set(n,u),fe.ssoLog.debug("_executeWorkflowStep",`[Workflow ${n}] started at ${new Date(u).toISOString()}`))},success:(n,g)=>{const u=Date.now();if(g){const E=this._stepStartTimes.get(`${n}-${g}`),m=E?u-E:0;this._stepStartTimes.delete(`${n}-${g}`),fe.ssoLog.debug("_executeWorkflowStep",`[Workflow ${n}] Step ${g} completed successfully at ${new Date(u).toISOString()} (${m}ms)`)}else{const E=this._workflowStartTimes.get(n),m=E?u-E:0;this._workflowStartTimes.delete(n),fe.ssoLog.debug("_executeWorkflowStep",`[Workflow ${n}] completed successfully at ${new Date(u).toISOString()} (${m}ms)`)}},error:(n,g,u)=>{const{ssoLog:E,utils:{safeStringify:m}}=fe,D=Date.now();if(g){const M=this._stepStartTimes.get(`${n}-${g}`),T=M?D-M:0;this._stepStartTimes.delete(`${n}-${g}`),E.error("_executeWorkflowStep",`[Workflow ${n}] Step ${g} failed at ${new Date(D).toISOString()} (${T}ms) ${m(u)}`,{error:u})}else{const M=this._workflowStartTimes.get(n),T=M?D-M:0;this._workflowStartTimes.delete(n),E.error("_executeWorkflowStep",`[Workflow ${n}] failed at ${new Date(D).toISOString()} (${T}ms) ${m(u)}`,{error:u})}}}}static getInstance(){return ws._instance||(ws._instance=new ws),ws._instance}static setInstance(n){ws._instance=n}init(){this._initializeWorkflows()}registerWorkflowStep(n,g,u,E){if(!this._handlers.has(n))return void fe.ssoLog.debug("registerWorkflowStep",`Workflow '${n}' not defined in core`);if(!Ng[n].find(D=>D.stepId===g))return void fe.ssoLog.debug("registerWorkflowStep",`Step '${g}' not defined in workflow '${n}'`);const m=this._handlers.get(n);m.has(g)||m.set(g,E?u.bind(E):u)}executeWorkflow(n,g){return pA(this,void 0,void 0,function*(){if(!this._validateWorkflow(n))return;fe.ssoLog.debug("executeWorkflow",`[Workflow ${n}] Started execution at ${new Date().toISOString()}`);const u=Ng[n],E={},m={cancelled:!1};this._activeWorkflows.set(n,{cancelToken:m});try{const D=new Map;u.forEach(T=>{D.set(T.stepId,T)});const M={workflowName:n,pendingSteps:new Set(u.map(T=>T.stepId)),completedSteps:new Set,runningSteps:new Set,stepMap:D,stepResults:E,data:g,cancelToken:m};yield new Promise((T,P)=>{const W=()=>{if(m.cancelled)return void T();this._getExecutableSteps({pendingSteps:M.pendingSteps,completedSteps:M.completedSteps,stepMap:M.stepMap,workflowName:n}).filter(iA=>!M.runningSteps.has(iA)).forEach(iA=>{M.completedSteps.has(iA)||M.runningSteps.has(iA)||this._executeWorkflowStep(iA,M,{onComplete:()=>{if(M.pendingSteps.size===0)return void T();this._getExecutableSteps({pendingSteps:M.pendingSteps,completedSteps:M.completedSteps,stepMap:M.stepMap,workflowName:n}).filter(EA=>!M.runningSteps.has(EA)).length===0&&M.runningSteps.size===0&&(fe.ssoLog.debug("executeWorkflow",`Workflow ${n} completed with some steps skipped due to dependency failures`),T())},onError:P,onStepComplete:W})})};W()}),fe.ssoLog.debug("executeWorkflow",`[Workflow ${n}] Completed execution at ${new Date().toISOString()}`)}catch(D){fe.ssoLog.error("executeWorkflow",`[Workflow ${n}] Failed execution at ${new Date().toISOString()}`,{error:D})}finally{this._activeWorkflows.delete(n)}})}_executeWorkflowStep(n,g,u){return pA(this,void 0,void 0,function*(){const{workflowName:E,runningSteps:m,stepMap:D,stepResults:M,data:T}=g;m.add(n),this._logWorkflowExecution(E,n,"start");try{const P=D.get(n);let W=null;P?.dependency&&(l(P.dependency)?W=M[P.dependency]:Array.isArray(P.dependency)&&(W={},P.dependency.forEach(EA=>{W[EA]=M[EA]})));const iA=this._handlers.get(E).get(n);if(iA){const EA=yield Promise.resolve(iA({data:T,result:W}));M[n]=EA,this._logWorkflowExecution(E,n,"success")}g.completedSteps.add(n)}catch(P){const W=`[Workflow].${E}.${n}`,{errorCode:iA,errorInfo:EA=`${W} failed`}=P||{},RA=new gs({functionName:W,code:iA,message:EA});fe.ssoLog.error(W,EA,{error:RA}),this._logWorkflowExecution(E,n,"error",P),u.onError(P)}finally{m.delete(n),g.pendingSteps.delete(n),u.onStepComplete(),u.onComplete()}})}reset(){this._cancelAllWorkflows()}destroy(){this.reset(),this._handlers.clear()}_initializeWorkflows(){Object.keys(Ng).forEach(n=>{this._handlers.has(n)||this._handlers.set(n,new Map)})}_cancelWorkFlow(n){const g=this._activeWorkflows.get(n);if(!g)return;const{cancelToken:u}=g;u.cancelled=!0,this._activeWorkflows.delete(n)}_cancelAllWorkflows(){Object.keys(Ng).forEach(n=>{this._cancelWorkFlow(n)})}_validateWorkflow(n){return Ng[n]?!!this._handlers.get(n):!1}_getExecutableSteps(n){const{pendingSteps:g,completedSteps:u,stepMap:E,workflowName:m}=n;return Array.from(g).filter(D=>{const M=E.get(D)||{},{dependency:T,skipIfDependencyMissing:P=!0}=M;if(!T)return!0;if(l(T))return this._isStepRegistered({workflowName:m,stepId:T})?u.has(T):!P;if(h(T)){if(T.filter(W=>!this._isStepRegistered({workflowName:m,stepId:W})).length>0&&P)return!1;for(const W of T)if(!u.has(W))return!1;return!0}return!1})}_isStepRegistered(n){var g;const{workflowName:u,stepId:E}=n;return(g=this._handlers.get(u))===null||g===void 0?void 0:g.has(E)}_logWorkflowExecution(n,g,u,E){this._logHandlers[u](n,g)}}const da=new Map,Xr=({type:s,groupID:n})=>s===Lo.GRP_COMMUNITY||`${n}`.startsWith(sa.COMMUNITY)&&!`${n}`.includes(sa.TOPIC),Wc=(s="")=>{const n=s.startsWith("GROUP")?s.replace("GROUP",""):s;return n.startsWith(sa.COMMUNITY)&&`${n}`.includes(sa.TOPIC)},Ed="openim",Zg="million_group_open_http_svc";function gg(s){return pA(this,void 0,void 0,function*(){const{servcmd:n,data:g}=function(m){const{data:D}=m;return SE(D)||Xg(D)}(s)?function(m){let{servcmd:D,data:M}=m;return Xg(M)?function(T){const{servcmd:P,data:W}=T;let{GroupId:iA=""}=W;const EA=iA;return[iA]=EA.split(sa.TOPIC),{servcmd:qn(P),data:Object.assign(Object.assign({},W),{GroupId:iA,TopicId:EA})}}(m):(SE(M)&&(D=qn(D)),{servcmd:D,data:M})}(s):s,u=fe.common.generateProtocolData({servcmd:n,data:g}),E=`${u.head.seq}${n}`;return fe.channel.sendPacket(u,{requestId:E,timeout:s.timeout})})}function SE(s){const{Type:n,GroupId:g,GroupIdList:u=[]}=s,E=g||u[0]||"";return Xr({type:n,groupID:E})}function Xg(s){const{GroupId:n=""}=s;return Wc(n)}function qn(s){if(s.includes(Ed))return s;const n=s.split(".")[1];return`${Zg}.${n}`}function Ar(){var s;return(s=fe.store.get("login"))===null||s===void 0?void 0:s.userId}const Fa=s=>h(s)||f(s),dd=(s,n,g,u)=>{if(!Fa(s)||!Fa(n))return 0;let E=0;const m=Object.keys(n);let D;for(let M=0,T=m.length;M{if(r(n))return"";if(s===Lo.MSG_TEXT)return n.text||"";const g=qI[s];return g?Nu(g):""},Zc=[{cmd:"ws_get_user_status",interval:5,count:20},{cmd:"ws_status_subscribe",interval:5,count:20},{cmd:"ws_status_unsubscribe",interval:5,count:20},{cmd:"get_group_self_member_info",interval:5,count:20},{cmd:"modify_group_base_info",interval:1,count:8},{cmd:"get_pendency",interval:1,count:15},{cmd:"set_group_attr",interval:5,count:10},{cmd:"modify_group_attr",interval:5,count:10},{cmd:"delete_group_attr",interval:5,count:10},{cmd:"clear_group_attr",interval:5,count:10},{cmd:"get_group_attr",interval:5,count:20},{cmd:"update_group_counter",interval:5,count:20},{cmd:"get_group_counter",interval:5,count:20},{cmd:"get_topic",interval:1,count:10},{cmd:"read_all_unread_msg",interval:1,count:1},{cmd:"query",interval:5,count:20}],KI="im_sdk_config_mgr.fetch_config",uI="im_sdk_config_mgr.push_configv2",Xc="cloud-config",$c=2996,va=new class{init(s){this.core=s}};function bg(s){return pA(this,void 0,void 0,function*(){const{sdkAppId:n}=va.core.store.get("instance")||{},g=va.core.helper.generateProtocolData({servcmd:KI,data:{uint32_sdkappid:n,uint64_version:s}}),u=`${g.head.seq}${KI}`;return va.core.channel.sendPacket(g,{requestId:u})})}var ys=new class{constructor(){this._core=null,this._expirationTime=0,this._version=0,this._isFetching=!1,this._cmdFrequencyLimitMap=new Map,this._methodCallFrequencyMap=new Map}install(s){this._core=s;const{notificationCenter:n,InnerEvent:g,helper:u,constants:{WORKFLOW_NAME:E,WORKFLOW_STEP:m},channel:D}=s;n.subscribeInnerEvent(uI,this._handlePushedConfig,this),u.registerWorkflowStep(E.SYNC_SERVER_INFO_AFTER_LOGIN,m.CLOUD_CONFIG_SYNC,this._handleLoginSuccess,this),n.subscribeInnerEvent(g.LOGOUT,this._reset,this),n.subscribeInnerEvent(g.DESTROY,this._dispose,this),u.registerExperimentalAPI("getServerConfig",this),this._updateCmdFreqLimitMap(Zc),D.registerBeforeSendInterceptor(this.checkMethodCallOverLimit,this)}getServerConfig(s){return pA(this,void 0,void 0,function*(){var n;const g={code:0,data:""};return s&&(g.data=((n=this._core.store.get("cloudConfig"))===null||n===void 0?void 0:n[s])||""),g})}checkMethodCallOverLimit(s){if(!this._cmdFrequencyLimitMap.has(s))return;if(!this._methodCallFrequencyMap.has(s))return void this._methodCallFrequencyMap.set(s,{startTime:Date.now(),methodCallCounter:1});const{count:n,interval:g}=this._cmdFrequencyLimitMap.get(s);let{startTime:u,methodCallCounter:E}=this._methodCallFrequencyMap.get(s);if(Date.now()-u>1e3*g)this._methodCallFrequencyMap.set(s,{startTime:Date.now(),methodCallCounter:1});else if(E+=1,this._methodCallFrequencyMap.set(s,{startTime:u,methodCallCounter:E}),E>n)throw new this._core.helper.ChatError({code:$c,replacement1:s})}_handlePushedConfig(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g}}=this._core;n.info("_handlePushedConfig",g(s)),yield this._updateCloudConfig(s)})}_handleLoginSuccess(){return pA(this,void 0,void 0,function*(){const{ssoLog:s,utils:{safeStringify:n}}=this._core;try{if(this._canFetch()){const g=yield bg(this._version);s.info("_fetchCloudConfigIfLogin",n(g)),yield this._updateCloudConfig(g)}this._core.helper.taskScheduler.addTask({id:Xc,intervalMs:1e3,callback:this._fetchCloudConfigIfReady,context:this})}catch(g){s.debug("_fetchCloudConfigIfLogin",n(g))}})}_fetchCloudConfigIfReady(){return pA(this,void 0,void 0,function*(){const{ssoLog:s,utils:{safeStringify:n}}=this._core;if(this._canFetch())try{const g=yield bg(this._version);s.info("_fetchCloudConfigIfReady",n(g)),yield this._updateCloudConfig(g)}catch(g){s.error("_fetchCloudConfigIfReady",n(g))}})}_updateCloudConfig(s){return pA(this,void 0,void 0,function*(){const n=this._parseCloudConfig(s);n&&(this._core.store.set("cloudConfig",n),yield this._parseCmdFreqLimit(),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.CLOUD_CONFIG_UPDATE,n),this._core.notificationCenter.emitOuterEvent(this._core.OuterEvent.SERVER_CONFIG_UPDATED,{name:this._core.OuterEvent.SERVER_CONFIG_UPDATED,data:{config:n}}))})}_canFetch(){const{isLoggedIn:s}=this._core.store.get("login")||{};return s&&!this._isFetching&&Date.now()>=this._expirationTime}_parseCloudConfig(s){const{int32_error_code:n,str_error_message:g,str_json_config:u,uint32_expired_time:E,uint32_sdkappid:m,uint64_version:D}=s;let M=null;if(n===0){if(this._version!==D)try{M=JSON.parse(u),this._version=D}catch{}this._expirationTime=Date.now()+1e3*E}else this._expirationTime=n===void 0?Date.now()+36e5:Date.now()+12e4;return M}_parseCmdFreqLimit(){return pA(this,void 0,void 0,function*(){var s;let n=(s=yield this.getServerConfig("cmd_frequency_limit"))===null||s===void 0?void 0:s.data;const{isEmpty:g}=this._core.utils;if(!g(n))try{n=JSON.parse(n),this._updateCmdFreqLimitMap(n)}catch(u){console.warn(u)}})}_updateCmdFreqLimitMap(s){s.forEach(n=>{this._cmdFrequencyLimitMap.set(n.cmd,{interval:n.interval,count:n.count})})}_reset(){this._core.helper.taskScheduler.removeTask(Xc),this._core.store.clear("cloudConfig"),this._updateCmdFreqLimitMap(Zc),this._methodCallFrequencyMap.clear(),this._expirationTime=0,this._version=0,this._isFetching=!1}_dispose(){const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(uI,this._handlePushedConfig,this),s.unSubscribeInnerEvent(n.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this),this._reset()}};class Kn{constructor(n=0,g=0){this.high=n,this.low=g}equal(n){return n!==null&&this.low===n.low&&this.high===n.high}toString(){const n=Number(this.high).toString(16);let g=Number(this.low).toString(16);if(g.length<8){let u=8-g.length;for(;u;)g=`0${g}`,u--}return n+g}}const vc={SEARCH_GRP_SNS:new Kn(0,Math.pow(2,1)).toString(),AV_HISTORY_MSG:new Kn(0,Math.pow(2,2)).toString(),GRP_COMMUNITY:new Kn(0,Math.pow(2,3)).toString(),MSG_TO_SPECIFIED_GRP_MBR:new Kn(0,Math.pow(2,4)).toString(),AV_MBR_LIST:new Kn(0,Math.pow(2,6)).toString(),USER_STATUS:new Kn(0,Math.pow(2,7)).toString(),CONV_MARK:new Kn(0,Math.pow(2,9)).toString(),CONV_GROUP:new Kn(0,Math.pow(2,10)).toString(),AV_BAN_MBR:new Kn(0,Math.pow(2,11)).toString(),MSG_EXT:new Kn(0,Math.pow(2,13)).toString(),GRP_COUNTER:new Kn(0,Math.pow(2,15)).toString(),PLUGIN_TRANSLATE:new Kn(Math.pow(2,6)).toString(),PLUGIN_VOICE_TO_TEXT:new Kn(Math.pow(2,7)).toString(),PLUGIN_CS:new Kn(Math.pow(2,8)).toString(),PLUGIN_PUSH:new Kn(Math.pow(2,9)).toString(),PLUGIN_BOT:new Kn(Math.pow(2,10)).toString(),MSG_REACTION:new Kn(Math.pow(2,16)).toString(),FOLLOW:new Kn(Math.pow(2,20)).toString()},jI="CommercialConfig",WI="commercial-config";var ME=new class{constructor(){this._core=null,this._expirationTime=0,this._isFetching=!1,this._featureMap=new Map,this._methodKeyMap=new Map,this._purchaseBits="0"}install(s){this._core=s;const{helper:n,notificationCenter:g,constants:{WORKFLOW_NAME:u,WORKFLOW_STEP:E,InnerEvent:m}}=s;g.subscribeInnerEvent(m.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),g.subscribeInnerEvent(m.LOGOUT,this._handleLogout,this),g.subscribeInnerEvent(m.DESTROY,this._dispose,this),n.registerWorkflowStep(u.SYNC_SERVER_INFO_AFTER_LOGIN,E.COMMERCIAL_CONFIG_UPDATE,this._syncCommercialConfig,this),s.helper.registerExperimentalAPI("isCommercialAbilityEnabled",this),s.helper.registerExperimentalAPI("queryCommercialAbility",this)}isCommercialAbilityEnabled(s){return pA(this,void 0,void 0,function*(){const n=parseInt(s,10).toString(2),{length:g}=n;let u,E=!0;for(let m=g-1,D=0;m>=0;m--,D++)if(n.charAt(m)==="1"&&(u=D<32?new Kn(0,2**D).toString():new Kn(2**(D-32),0).toString(),!this._featureMap.get(u))){E=!1;break}return this._core.ssoLog.debug("isFeatureEnabled",`${jI}.isFeatureEnabled decimalNumber:${s} key:${u} ret:${E}`),{code:0,data:{enabled:E}}})}queryCommercialAbility(){return this._purchaseBits}_fetchAndParseCommercialConfig(){return pA(this,void 0,void 0,function*(){var s;const{ssoLog:n,utils:{safeStringify:g},common:{buildAndSendPacket:u}}=this._core;try{this._isFetching=!0;const E=yield u({servcmd:"im_sdk_config_mgr.fetch_imsdk_purchase_bitsv2",data:{uint32_sdkappid:(s=this._core.store.get("instance"))===null||s===void 0?void 0:s.sdkAppId}});E&&(this._parseCommercialConfig(E),this._core.store.set("commercialConfig",this._methodKeyMap))}catch(E){n.error("_fetchAndParseCommercialConfig",g(E))}finally{this._isFetching=!1}})}_syncCommercialConfig(s){return pA(this,void 0,void 0,function*(){const{purchaseBits:n}=s?.data||{};n&&(this._parsePurchaseBits(n),this._core.store.set("commercialConfig",this._methodKeyMap)),this._canFetch()&&(yield this._fetchAndParseCommercialConfig()),this._core.helper.taskScheduler.addTask({id:WI,intervalMs:1e3,callback:this._fetchCommercialConfigIfReady,context:this})})}_canFetch(){var s;const n=(s=this._core.store.get("login"))===null||s===void 0?void 0:s.isLoggedIn,g=Date.now()>=this._expirationTime;return n&&!this._isFetching&&g}_handlePushedConfig(s){s?.body&&(this._parseCommercialConfig(s.body),this._core.store.set("commercialConfig",this._methodKeyMap))}_fetchCommercialConfigIfReady(){return pA(this,void 0,void 0,function*(){this._canFetch()&&(yield this._fetchAndParseCommercialConfig())})}_parseCommercialConfig(s){const{ssoLog:n}=this._core;if(typeof s!="object")return;const{int32_error_code:g,str_error_message:u,str_purchase_bits:E,uint32_expired_time:m}=s;g===0?(this._parsePurchaseBits(E),this._expirationTime=Date.now()+1e3*m):g===void 0?(n.warn("_parseCommercialConfig",`${jI}._parseCommercialConfig failed. Invalid message format:`,s),this._expirationTime=Date.now()+36e5):(n.warn("_parseCommercialConfig",`${jI}._parseCommercialConfig errorCode:${g} errorMessage:${u}`),this._expirationTime=Date.now()+12e4)}_isValidPurchaseBits(s){return s&&typeof s=="string"&&s.length>=1&&s.length<=64&&/[01]{1,64}/.test(s)}_parsePurchaseBits(s){const{ssoLog:n,utils:{safeStringify:g}}=this._core;if(this._isValidPurchaseBits(s)){this._purchaseBits=s,this._featureMap.clear(),this._methodKeyMap.clear();let u=null;for(let E=s.length-1,m=0;E>=0;E--,m++)if(u=m<32?new Kn(0,2**m).toString():new Kn(2**(m-32),0).toString(),s[E]==="1"){this._featureMap.set(u,!0);const D=this._getKeyByValue(vc,u);D&&this._methodKeyMap.set(D,!0)}else{this._featureMap.set(u,!1);const D=this._getKeyByValue(vc,u);D&&this._methodKeyMap.set(D,!1)}}else n.warn("_parsePurchaseBits",`${jI}.parsePurchaseBits invalid purchases:${g(s)}`)}_getKeyByValue(s,n){const g=Object.entries(s).find(([u,E])=>E===n);return g?g[0]:void 0}_handleLogout(){this._reset()}_dispose(){this._reset(),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._core.helper.taskScheduler.removeTask(WI),this._core.store.set("commercialConfig",{}),this._expirationTime=0,this._isFetching=!1,this._featureMap.clear(),this._purchaseBits="0"}},nh=new class{constructor(){this._core=null,this._serverOverloadInfoMap=new Map}install(s){this._core=s;const{notificationCenter:n,InnerEvent:g,channel:u}=this._core;n.subscribeInnerEvent(g.OVERLOAD_PUSH,this._handleOverLoadPush,this),n.subscribeInnerEvent(g.LOGOUT,this._reset,this),n.subscribeInnerEvent(g.DESTROY,this._dispose,this),u.registerBeforeSendInterceptor(this.checkServerOverload,this)}checkServerOverload(s){if(!this._serverOverloadInfoMap.has(s))return;const{overloadStartTimestamp:n,delaySeconds:g}=this._serverOverloadInfoMap.get(s);if(Date.now()-n<=1e3*g)throw new this._core.helper.ChatError({functionName:s,message:"service is busy, please try again later"});this._serverOverloadInfoMap.delete(s)}_handleOverLoadPush(s){const{OverLoadServCmd:n,DelaySecs:g}=s;this._serverOverloadInfoMap.set(n,{overloadStartTimestamp:Date.now(),delaySeconds:g})}_reset(){this._serverOverloadInfoMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(n.OVERLOAD_PUSH,this._handleOverLoadPush,this),s.unSubscribeInnerEvent(n.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this)}},lC=new class{constructor(){this.name="ConfigCenter"}install(s){va.init(s),ys.install(s),ME.install(s),nh.install(s)}},rh=new class{constructor(){this.name="ErrorMessage",this._core=null}install(s){return pA(this,void 0,void 0,function*(){if(this._core=s,this._canFetch()){const n=yield this._fetchErrorMessage();if(!n)return;const g=this._parseResponse(n);this._saveErrorMessage(g)}})}_canFetch(){const s=this._core.store.getStorage("errorMessage");return!s||this._isExpired(s)}_saveErrorMessage(s){this._core.store.setStorage("errorMessage",{errorMessage:s,errorMessageSavedTime:new Date().getTime()})}_fetchErrorMessage(){return pA(this,void 0,void 0,function*(){try{return yield this._core.helper.httpRequest({method:"GET",url:"https://web.sdk.qcloud.com/im/download/error-message/v3/0.0.6/tim-error-message.txt"})}catch(s){console.error(s)}})}_isExpired(s){if(!s)return!0;const{errorMessageSavedTime:n}=s;return n&&new Date().getTime()-n>=6048e5}_parseResponse(s){if(typeof s=="string"){const n=s.split(`;
-`),g={},u=new RegExp(/'/g);for(let E=0;E{var JA,ne,se;const _i=function(Ti,Lt){const{From_Account:Ni,From_AccountHeadurl:cs,From_AccountNick:Se,IsNeedReadReceipt:mt,MsgBody:UA,MsgClientTime:oi,MsgRandom:_s,MsgSeq:Gi,MsgTimeStamp:Fr,SendMsgControl:xi,SupportMessageExtension:gr,To_Account:_t,TinyId:Tt,MsgCheckResult:$u,CloudCustomData:ln,IsPeerRead:Bo,MsgFlagBits:ll,MsgVersion:wC,EventArray:wr}=Ti;return{from:Ni,avatar:cs,nick:Se,needReadReceipt:mt===1,readReceiptSentByPeer:Bo,clientTime:oi,messageFlagBits:ll,random:_s,sequence:Gi,time:Fr,messageControlInfo:xi,isSupportExtension:gr,to:_t,tinyID:Tt,checkResult:$u,cloudCustomData:ln,messageVersion:wC,eventArray:wr,elements:Lt.message.messageHelper.parseServerPushMessageElement(UA)}}(OA,xA);if(!((se=(ne=(JA=OA?.EventArray)===null||JA===void 0?void 0:JA[0])===null||ne===void 0?void 0:ne.hasOwnProperty)===null||se===void 0)&&se.call(ne,"C2cNotifyMsgArray"))SA.push(...function(Ti){var Lt;const Ni=[];return(Lt=Ti.EventArray)===null||Lt===void 0||Lt.forEach(cs=>{var Se,mt;const{C2cNotifyMsgArray:UA}=cs,oi=(mt=(Se=UA?.[0])===null||Se===void 0?void 0:Se.WithdrawC2cMsgNotify)===null||mt===void 0?void 0:mt.C2cWithdrawInfoArray;Array.isArray(oi)&&Ni.push(...oi)}),Ni}(OA));else{const Ti=xA.message.messageFactory.createMessage(Object.assign(Object.assign({},_i),{conversationType:"C2C",flow:"in"})),{elements:Lt}=_i;Ti.setElement(Lt),LA.push(Ti)}}),{unreadMessageList:LA,revokedMessageList:SA}}(T.MsgList,n);return{syncFlag:T?.SyncFlag,unreadMessageList:EA,revokedMessageList:RA,unreadCountList:P,overflowUnreadCountList:W,cookie:T?.Cookie,groupTipList:iA}}catch(T){console.warn(T)}})}var kg,no;(function(s){s[s.START_SYNC=0]="START_SYNC",s[s.SYNCING=1]="SYNCING",s[s.SYNC_COMPLETE=2]="SYNC_COMPLETE"})(kg||(kg={})),function(s){s[s.LOGIN_SUCCESS=0]="LOGIN_SUCCESS",s[s.NEW_MESSAGE_RECEIVED=1]="NEW_MESSAGE_RECEIVED"}(no||(no={}));var IC=new class{constructor(){this.name="UnreadMessageSynchronizer",this._unreadDBMessageMap=new Map,this._cookie="",this._localConversationIDListBeforeDisconnect=[]}install(s){this._core=s;const{constants:n}=s;s.helper.registerWorkflowStep(n.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,n.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterReOnline,this),s.helper.registerWorkflowStep(n.WORKFLOW_NAME.RECEIVE_C2C_NEW_MESSAGE,n.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterNewMessageReceived,this),s.helper.registerWorkflowStep(n.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_LOGIN,n.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterLogin,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.SOCKET_DISCONNECTED,this._handleDisconnect,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.LOGOUT,this._reset,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this)}_syncUnreadMessage(s){return pA(this,void 0,void 0,function*(){const{isAfterReOnline:n=!1,isAfterNewMessageReceived:g=!1,isAfterLogin:u=!1}=s||{};let E=kg.START_SYNC;const m=[],D=[],M=[],T=[];for(;this._canContinueSync({cookie:this._cookie,syncFlag:E});){const P=yield this._fetchUnreadDBMessage({cookie:this._cookie,syncFlag:E,syncTriggerEvent:g?no.NEW_MESSAGE_RECEIVED:no.LOGIN_SUCCESS});if(!P)break;const{unreadMessageList:W=[],revokedMessageList:iA=[],overflowUnreadCountList:EA,unreadCountList:RA,groupTipList:kA}=P;if(this._cookie=P?.cookie||"",E=P?.syncFlag,this._parseAndSaveUnreadMessageList(W),M.push(...iA),this._updateConversationUnreadOptions({unreadCountList:RA,overflowUnreadCountList:EA,conversationUpdateFieldList:m}),Array.isArray(kA)&&D.push(...kA),n){const{messages:xA}=this._handleNewMessageList(W);T.push(...xA)}}return n?{conversationUpdateFieldList:m,revokedMessageList:M,unreadMessageMap:this._unreadDBMessageMap,groupTipList:D,messages:T,isUnreadC2CMessage:!0}:{conversationUpdateFieldList:m,isInstantMessage:!u,isUnreadC2CMessage:!0,revokedMessageList:M,unreadMessageMap:this._unreadDBMessageMap,groupTipList:D}})}_syncUnreadDBMessageAfterLogin(){return pA(this,void 0,void 0,function*(){return this._cookie="",this._syncUnreadMessage({isAfterLogin:!0})})}_syncUnreadDBMessageAfterNewMessageReceived(s){return pA(this,void 0,void 0,function*(){if(s.data.Flag===1)return this._syncUnreadMessage({isAfterNewMessageReceived:!0})})}_updateConversationUnreadOptions(s){const{unreadCountList:n,overflowUnreadCountList:g,conversationUpdateFieldList:u}=s,{constants:{OuterConstant:{CONV_C2C:E,CONV_SYSTEM:m}}}=this._core;n?.forEach(D=>{const{From_Account:M,UnreadCount:T}=D;if(M!==m){const P=u.find(({conversationID:W})=>W===`${E}${M}`);P?P.unreadCount=T:u.push({conversationID:`${E}${M}`,unreadCount:T,type:E})}}),g?.forEach(D=>{const{From_Account:M,LastMsgTime:T}=D;M!==m&&(u.find(({conversationID:P})=>P===`${E}${M}`)||u.push({conversationID:`${E}${M}`,type:E,lastMsgTime:T}))})}_syncUnreadDBMessageAfterReOnline(){return pA(this,void 0,void 0,function*(){return this._syncUnreadMessage({isAfterReOnline:!0})})}_updateMessageProfile(s){var n;const{messageDataHandler:g}=this._core.message||{},u=(n=this._core.store.get("login"))===null||n===void 0?void 0:n.userId,{from:E,nick:m,avatar:D,conversationID:M=""}=s;if(E!==u){const T=g.getLatestMsgSentByPeer(M);if(T){const{nick:P,avatar:W}=T;m&&D?m===P&&D===W||g.updateNickAndAvatarOfSentMessage({conversationID:M,latestNick:m,latestAvatar:D,isSentByMe:!1}):(s.nick=P,s.avatar=W)}}else{const T=g.getLatestMsgSentByMe(M);!T||m===T.nick&&D===T.avatar||g.updateNickAndAvatarOfSentMessage({conversationID:M,latestNick:m,latestAvatar:D,isSentByMe:!0})}}_handleNewMessageList(s){const{messageDataHandler:n}=this._core.message||{},g=new Map,u=[];return s.forEach(E=>{this._updateMessageProfile(E);let m=E.isModified===1;if(n.isMessageSentByCurrentInstance(E)?E.isModified=m:m=!1,E.isOnlineMessage())E._onlineOnlyFlag=!0,n.isMessageSentByCurrentInstance(E)||u.push(E);else if(this._shouldStoreUnreadMessage(E)){if(n.storeConversationMessage(E)){const{conversationID:D,conversationType:M,conversationSubType:T,flow:P,_isExcludedFromUnreadCount:W,_isExcludedFromLastMessage:iA}=E,EA=iA?"":E;g.has(D)?(g.get(D).lastMessage=EA,P==="in"&&(W||g.get(D).unreadCount++)):g.set(D,{conversationID:D,type:M,subType:T,unreadCount:W||P!=="in"?0:1,lastMessage:EA})}n.isMessageSentByCurrentInstance(E)&&!m||u.push(E)}}),{messages:u,conversationOptions:g}}_shouldStoreUnreadMessage(s){var n;const{conversationID:g}=s,{message:u,appStore:E,utils:{isEmpty:m}}=this._core||{},D=Array.from(((n=E.conversationStore.getConversationMap())===null||n===void 0?void 0:n.keys())||[]),M=this._getLocalLastMessageTime(g);return!u.messageDataHandler.isInMessageList(s)&&D.includes(g)&&this._localConversationIDListBeforeDisconnect.includes(g)&&!m(M)}_fetchUnreadDBMessage(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g}}=this._core;try{n.debug("_fetchUnreadDBMessage",`unread-message-synchronizer._fetchUnreadDBMessage options:${g(s)}`);const E=yield Al(s,this._core);if(!E)return null;const{syncFlag:m,unreadMessageList:D,revokedMessageList:M,cookie:T,unreadCountList:P,overflowUnreadCountList:W,groupTipList:iA}=E;return this._parseAndSaveUnreadMessageList(D),{syncFlag:m,cookie:T,unreadMessageList:D,revokedMessageList:M,unreadCountList:P,overflowUnreadCountList:W,groupTipList:iA}}catch(u){console.log(u)}})}_canContinueSync({cookie:s,syncFlag:n}){var g;return n===kg.START_SYNC||n===kg.SYNCING&&!(!((g=this._core)===null||g===void 0)&&g.helper.isEmpty(s))}_parseAndSaveUnreadMessageList(s){s.forEach(n=>{const{ID:g}=n;this._unreadDBMessageMap.set(g,n)})}_handleDisconnect(){var s;const{appStore:n}=this._core;this._localConversationIDListBeforeDisconnect=Array.from(((s=n.conversationStore.getConversationMap())===null||s===void 0?void 0:s.keys())||[])}_getLocalLastMessageTime(s){const{message:n}=this._core,g=n.messageDataHandler.getLocalMessageList(s),u=g[g.length-1];return u?.time}_reset(){this._cookie="",this._unreadDBMessageMap.clear()}_dispose(){var s,n;(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),(n=this._core)===null||n===void 0||n.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),this._reset()}},vE=new class{init(s){var n;this._core=s,this._visibilityChangeHandler=this._handleVisibilityChange.bind(this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this),document?.addEventListener("visibilitychange",this._visibilityChangeHandler),(n=this._core)===null||n===void 0||n.store.set("activityMonitor",{isActive:!0})}_handleVisibilityChange(){var s,n;const g=document?.visibilityState==="visible";(s=this._core)===null||s===void 0||s.store.set("activityMonitor",{isActive:g}),(n=this._core)===null||n===void 0||n.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:g})}_reset(){var s;(s=this._core)===null||s===void 0||s.store.clear("activityMonitor")}_dispose(){document?.removeEventListener("visibilitychange",this._visibilityChangeHandler);const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this),this._reset()}},RE=new class{init(s){var n;this._core=s,this._bindAppActivityEvent(),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this),(n=this._core)===null||n===void 0||n.store.set("activityMonitor",{isActive:!0})}_bindAppActivityEvent(){var s,n,g,u,E;const{MINI_APP_NAMESPACE:m,IN_TT_MINI_GAME:D,IN_WX_MINI_GAME:M}=((s=this._core)===null||s===void 0?void 0:s.utils)||{};D||M?((n=m?.onShow)===null||n===void 0||n.call(m,()=>{var T,P;(T=this._core)===null||T===void 0||T.store.set("activityMonitor",{isActive:!0}),(P=this._core)===null||P===void 0||P.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})}),(g=m?.onHide)===null||g===void 0||g.call(m,()=>{var T,P;(T=this._core)===null||T===void 0||T.store.set("activityMonitor",{isActive:!1}),(P=this._core)===null||P===void 0||P.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})})):((u=m?.onAppShow)===null||u===void 0||u.call(m,()=>{var T,P;(T=this._core)===null||T===void 0||T.store.set("activityMonitor",{isActive:!0}),(P=this._core)===null||P===void 0||P.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})}),(E=m?.onAppHide)===null||E===void 0||E.call(m,()=>{var T,P;(T=this._core)===null||T===void 0||T.store.set("activityMonitor",{isActive:!1}),(P=this._core)===null||P===void 0||P.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})}))}_reset(){var s;(s=this._core)===null||s===void 0||s.store.clear("activityMonitor")}_dispose(){const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this),this._reset()}},Cd=new class{init(s){const{IN_MINI_APP:n,IN_WX_MINI_PLUGIN:g}=s.helper;g||(n?RE.init(s):vE.init(s))}};const wE="none",el="online";var EI=new class{init(s){this._core=s,this._activateNetworkMonitoring(),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return pA(this,void 0,void 0,function*(){navigator.onLine?this._onOnline():this._onOffline(),this._onOnlineCallback=this._onOnline.bind(this),this._onOfflineCallback=this._onOffline.bind(this),window.addEventListener("online",this._onOnlineCallback),window.addEventListener("offline",this._onOfflineCallback)})}_deactivateNetworkMonitoring(){this._onOnlineCallback!==null&&(window.removeEventListener("online",this._onOnlineCallback),this._onOnlineCallback=null),this._onOfflineCallback!==null&&(window.removeEventListener("offline",this._onOfflineCallback),this._onOfflineCallback=null)}_onNetworkStatusChange(s){var n,g;const{isConnected:u,networkType:E}=s;(n=this._core)===null||n===void 0||n.store.set("netWorkMonitor",{isNetworkOnline:u,networkType:E}),(g=this._core)===null||g===void 0||g.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:u,networkType:E})}_onOnline(){this._onNetworkStatusChange({isConnected:!0,networkType:el})}_onOffline(){this._onNetworkStatusChange({isConnected:!1,networkType:wE})}_reset(){var s;this._deactivateNetworkMonitoring(),(s=this._core)===null||s===void 0||s.store.clear("netWorkMonitor")}_dispose(){var s,n;(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent((n=this._core)===null||n===void 0?void 0:n.InnerEvent.DESTROY,this._dispose,this),this._reset()}},Gu=new class{init(s){this._core=s,this._activateNetworkMonitoring(),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return pA(this,void 0,void 0,function*(){try{const{utils:{MINI_APP_NAMESPACE:s}}=this._core;this._mpNetworkStatusCallback=this._onNetworkStatusChange.bind(this),s.onNetworkStatusChange(this._onNetworkStatusChange.bind(this))}catch(s){console.error(s)}})}_deactivateNetworkMonitoring(){if(this._mpNetworkStatusCallback!==null){const{utils:{MINI_APP_NAMESPACE:s}}=this._core;s.offNetworkStatusChange&&s.offNetworkStatusChange(this._mpNetworkStatusCallback),this._mpNetworkStatusCallback=null}}_onNetworkStatusChange(s){var n,g;const{isConnected:u,networkType:E}=s;(n=this._core)===null||n===void 0||n.store.set("netWorkMonitor",{isNetworkOnline:u,networkType:E}),(g=this._core)===null||g===void 0||g.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:u,networkType:E})}_reset(){var s;this._deactivateNetworkMonitoring(),(s=this._core)===null||s===void 0||s.store.clear("netWorkMonitor")}_dispose(){var s,n;(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent((n=this._core)===null||n===void 0?void 0:n.InnerEvent.DESTROY,this._dispose,this),this._reset()}},bu=new class{init(s){const{IN_MINI_APP:n}=s.utils;n?Gu.init(s):EI.init(s)}},uC=new class{constructor(){this.name="SystemStateMonitor"}install(s){Cd.init(s),bu.init(s)}};const vr=new Set(["tui_room_svr.*","callkit_records_svr.*","room_engine_srv.*","room_engine_http_srv.*","room_engine_mic.*","live_engine_srv.*","live_engine_http_srv.*","live_engine_pk.*","trtc_ai_service.*","call_engine_srv.*"]),cg="tui_room_svr.*";var Rc=new class{constructor(){this.name="BusinessCommandTransfer",this._transferredCommands=vr}install(s){this._core=s;const{notificationCenter:n,InnerEvent:g,helper:u}=s;n.subscribeInnerEvent(g.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),n.subscribeInnerEvent(g.LOGOUT,this._reset,this),n.subscribeInnerEvent(g.DESTROY,this._dispose,this),n.subscribeInnerEvent("im_open_push.msg_push",n.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this),u.registerExperimentalAPI("sendTRTCCustomData",this,"transferBusinessCommand"),u.registerExperimentalAPI("sendRoomCustomData",this,"transferBusinessCommand")}transferBusinessCommand(s){return pA(this,void 0,void 0,function*(){const n="transferBusinessCommand";try{const{serviceCommand:g=cg}=s||{};if(!this._isValidTransferredCommand(g))throw new this._core.helper.ChatError({code:2995,functionName:n});return{code:0,data:(yield function(E,m){return pA(this,void 0,void 0,function*(){const{helper:D,channel:M}=m,{serviceCommand:T=cg,data:P}=E||{};let W={};try{W=typeof P=="string"?JSON.parse(P):P}catch(RA){console.warn(RA)}const iA=D.generateProtocolData({servcmd:T,data:W}),EA=`${iA.head.seq}${T}`;return M.sendPacket(iA,{requestId:EA,shouldRejectOnError:!1})})}(s,this._core))||{}}}catch(g){throw console.warn(g),new this._core.helper.ChatError({code:g?.errorCode,message:g?.errorInfo,data:{},functionName:n})}})}_onCloudConfigUpdate(s={}){try{if(typeof s.rtc_cmd!="string")return;const n=JSON.parse(s.rtc_cmd);Array.isArray(n)&&(this._transferredCommands=new Set([...this._transferredCommands,...n]))}catch(n){console.log(n)}}_isValidTransferredCommand(s=""){const n=`${s?.split(".")[0]}.*`;return this._transferredCommands.has(n)}_onServerPushBusinessCommand(s){const{OuterEvent:n,notificationCenter:g}=this._core,{MsgContent:u}=s||{},{ROOM_CUSTOM_DATA_RECEIVED:E}=n;g.emitOuterEvent(E,{name:E,data:u})}_reset(){this._transferredCommands=vr}_dispose(){const{notificationCenter:s,InnerEvent:n}=this._core;this._reset(),s.unSubscribeInnerEvent(n.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),s.unSubscribeInnerEvent(n.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this),s.unSubscribeInnerEvent("im_open_push.msg_push",s.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this)}};const ku=1,_l=2,hd=3,$r=4,dI=5,_n="TIMCustomElem",EC="C2C",tl="GROUP",Bd="invite",CI="accept",Oa="cancel",dC="reject",Pa="modifyInvitation",ur="signaling",Qd=8010,Lu="signaling-timeout";function Er(s){return s.filter(n=>{if(n.type===_n){const{cloudCustomData:g="",payload:{data:u=""}={}}=n,E=g.match(/"type":"tsignaling"/),m=u.match(/inviteID/),D=u.match(/actionType/);return E||m&&D}return!1})}function wc(s){const{data:n}=s.payload;try{return JSON.parse(n)}catch(g){return console.error(g),null}}function il(s,n){return s.toString(16).padStart(n,"0")}function Lg(s){if(s<0||s>53)throw new Error("Number of digits must be between 0 and 53");if(s<=30)return Math.floor(Math.random()*(1<0;const M=this._core.common.getCurrentUserID();return D.includes(M)}return!0}updateSignaling(s){const n=`${ur}.updateSignaling`,{inviteID:g,inviter:u,inviteeList:E,groupID:m}=s;if(console.log(`${n} inviteID:${g} inviter:${u} groupID:${m}`),m&&this.hasSignaling(g)){const D=E[0],{inviteeList:M}=this._onlineSignalingMap.get(g);M.includes(D)&&(M.splice(M.indexOf(D),1),console.log(`${n} remove ${D}. localInviteeList.length:${M.length}`)),M.length===0&&this.removeSignaling(g)}else this.removeSignaling(g)}setSignalingListenStatus(s){this._isSignalingListening=s}getSignalingListenStatus(){return this._isSignalingListening}_dispose(){var s,n;this._reset(),(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),(n=this._core)===null||n===void 0||n.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._isSignalingListening=!1}_reset(){this._onlineSignalingMap.clear()}},$g=new class{init(s){this._core=s}createInviteSignaling(s){const n=this._generateInviteID(),g=this._createInviteSignalingData(Object.assign(Object.assign({},s),{inviteID:n})),{groupID:u,inviteeList:E}=g,m=u||E[0];return{signaling:this._createSignaling(g,m),signalingData:g,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createAcceptSignaling(s){const n=this._createAcceptSignalingData(s),{groupID:g,inviter:u}=n,E=g||u;return{signaling:this._createSignaling(n,E),signalingData:n,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createCancelSignaling(s){const n=this._createCancelSignalingData(s),{groupID:g,inviteeList:u}=n,E=g||u[0];return{signaling:this._createSignaling(n,E),signalingData:n,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createRejectSignaling(s){const n=this._createRejectSignalingData(s),{groupID:g,inviter:u}=n,E=g||u;return{signaling:this._createSignaling(n,E),signalingData:n,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createTimeoutSignaling(s){const{isInviter:n=!1}=s,g=this._createTimeoutSignalingData(s),{groupID:u,inviteeList:E,inviter:m}=g,D=u||(n?E[0]:m);return{signaling:this._createSignaling(g,D),signalingData:g,signalingExtensionOptions:this._createSignalingExtensionOptions(g)}}_createSignalingExtensionOptions(s){var n,g;const{data:u="",onlineUserOnly:E,inviteID:m="",offlinePushInfo:D,actionType:M}=s,T=((g=(n=Oo.getSignaling(m))===null||n===void 0?void 0:n.signaling)===null||g===void 0?void 0:g._onlineOnlyFlag)||!1;return{onlineUserOnly:E||T,offlinePushInfo:D,messageControlInfo:this._createMessageControlInfo(u,M)}}_createMessageControlInfo(s,n){const g=n===dI&&!!s.match(/excludeTimeoutSignalingFromHistoryMessage/),u=!!s.match(/excludeFromHistoryMessage/)||!!s.match(/excludeOriginalSignalingFromHistoryMessage/);return{excludedFromContentModeration:!0,excludedFromUnreadCount:g||u,excludedFromLastMessage:g||u}}_createInviteSignalingData(s){const n=`${ur}._createInviteSignalingData`,{userID:g,timeout:u=0,groupID:E="",inviteeList:m=[]}=s,D=this._core.common.getCurrentUserID(),M=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:ku,inviter:D,inviteeList:E?m:[g],timeout:u});return console.log(`${n} signalingData:`,M),M}_createAcceptSignalingData(s){const n=`${ur}._createAcceptSignalingData`,{inviteID:g}=s,u=this._core.common.getCurrentUserID(),{inviter:E,groupID:m}=Oo.getSignaling(g),D=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:hd,groupID:m,inviter:E,inviteeList:[u]});return console.log(`${n} signalingData:`,D),D}_createCancelSignalingData(s){const n=`${ur}._createCancelSignalingData`,{inviteID:g}=s,u=this._core.common.getCurrentUserID(),{inviteeList:E,groupID:m}=Oo.getSignaling(g),D=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:_l,groupID:m,inviter:u,inviteeList:E});return console.log(`${n} signalingData:`,D),D}_createRejectSignalingData(s){const n=`${ur}._createRejectSignalingData`,{inviteID:g}=s,u=this._core.common.getCurrentUserID(),{inviter:E,groupID:m}=Oo.getSignaling(g),D=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:$r,groupID:m,inviter:E,inviteeList:[u]});return console.log(`${n} signalingData:`,D),D}_createTimeoutSignalingData(s){const n=`${ur}._createTimeoutSignalingData`,{isInviter:g=!1,inviteID:u}=s,{inviteeList:E,inviter:m}=Oo.getSignaling(u),D=this._core.common.getCurrentUserID(),M=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:dI,inviter:m,inviteeList:g?E:[D]});return console.log(`${n} signalingData:`,M),M}_createSignaling(s,n){var g,u,E;const{groupID:m=""}=s,D={to:n,conversationType:m?tl:EC,priority:"High",payload:{data:JSON.stringify(s)}};return(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageFactory)===null||E===void 0?void 0:E.createCustomMessage(D)}_generateInviteID(){return[il(Lg(32),8),il(Lg(16),4),il(16384|Lg(12),4),il(32768|Lg(14),4),il(Lg(48),12)].join("-")}_generateBaseSignalData(s){const{data:n="",inviteID:g="",groupID:u=""}=s;return{businessID:1,timeout:0,data:n,inviteID:g,groupID:u}}},Za=new class{constructor(){this._isProcessingSignaling=!1}init(s){this._core=s,s.helper.registerApi({apiName:"invite",context:this}),s.helper.registerApi({apiName:"accept",context:this}),s.helper.registerApi({apiName:"cancel",context:this}),s.helper.registerApi({apiName:"reject",context:this}),s.helper.registerApi({apiName:"modifyInvitation",context:this}),s.helper.registerApi({apiName:"getSignalingInfo",context:this}),s.helper.registerApi({apiName:"addSignalingListener",context:this}),s.helper.registerApi({apiName:"removeSignalingListener",context:this}),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.LOGOUT,this._reset,this)}invite(s){return pA(this,void 0,void 0,function*(){var n;try{this._validateBeforeInvite(s);const{signaling:g,signalingData:u,signalingExtensionOptions:E}=$g.createInviteSignaling(s),m=yield this._sendSignaling(g,E);if(m?.code===0){const{inviteID:D,timeout:M}=u;return Oo.saveSignaling(D,Object.assign(Object.assign({},u),{signaling:g})),M>0&&((n=this._core)===null||n===void 0||n.helper.taskScheduler.addOnceTask({id:`${Lu}-${D}`,intervalMs:1e3*(M+5),callback:this.handleInvitationExpiryTimer.bind(this,D)})),Object.assign(Object.assign({},m),{inviteID:D})}return m}catch(g){throw g}})}accept(s){return pA(this,void 0,void 0,function*(){try{const{inviteID:n}=s;this._validateBeforeAccept(n),this._isProcessingSignaling=!0;const{signaling:g,signalingData:u,signalingExtensionOptions:E}=$g.createAcceptSignaling(s),m=yield this._sendSignaling(g,E);return m?.code===0?(Oo.updateSignaling(u),Object.assign(Object.assign({},m),{inviteID:n})):m}catch(n){throw n}finally{this._isProcessingSignaling=!1}})}cancel(s){return pA(this,void 0,void 0,function*(){try{const{inviteID:n}=s;this._validateBeforeCancel(n),this._isProcessingSignaling=!0;const{signaling:g,signalingExtensionOptions:u}=$g.createCancelSignaling(s),E=yield this._sendSignaling(g,u);return E?.code===0?(Oo.removeSignaling(n),Object.assign(Object.assign({},E),{inviteID:n})):E}catch(n){throw n}finally{this._isProcessingSignaling=!1}})}reject(s){return pA(this,void 0,void 0,function*(){try{const{inviteID:n}=s;this._validateBeforeReject(n),this._isProcessingSignaling=!0;const{signaling:g,signalingExtensionOptions:u}=$g.createRejectSignaling(s),E=yield this._sendSignaling(g,u);return E?.code===0?(Oo.removeSignaling(n),Object.assign(Object.assign({},E),{inviteID:n})):E}catch(n){throw n}finally{this._isProcessingSignaling=!1}})}modifyInvitation(s){return pA(this,void 0,void 0,function*(){var n,g;const{inviteID:u,data:E}=s;let m="";try{this._validateBeforeModifyInvitation(u);const D=Oo.getSignaling(u),{signaling:M}=D,T=Do(D,["signaling"]);m=M.payload.data,T.data=E,M.payload.data=JSON.stringify(T);const P=yield(g=(n=this._core)===null||n===void 0?void 0:n.message.messageAction)===null||g===void 0?void 0:g.modifyMessage(M);return Oo.hasSignaling(u)&&Oo.saveSignaling(u,Object.assign(Object.assign({},T),{signaling:M})),P}catch(D){if(m){const{signaling:M}=Oo.getSignaling(u);M.payload.data=m}throw D}})}getSignalingInfo(s){const{ssoLog:n,utils:{safeStringify:g}}=this._core;if(Er([s]).length===0)return;const u=wc(s),E={businessID:u.businessID||1,inviteID:u.inviteID,groupID:u.groupID||"",inviter:u.inviter||"",inviteeList:u.inviteeList||[],data:u.data||"",actionType:u.actionType||ku,timeout:u.timeout||0};return n.debug(`${ur} getSignalingInfo ${g(E)}`),E}addSignalingListener(s,n,g){var u,E;s===((u=this._core)===null||u===void 0?void 0:u.SignalingEvent.NEW_INVITATION_RECEIVED)&&Oo.setSignalingListenStatus(!0),(E=this._core)===null||E===void 0||E.notificationCenter.subscribeOuterEvent(s,n,g)}removeSignalingListener(s,n,g){var u,E;s===((u=this._core)===null||u===void 0?void 0:u.SignalingEvent.NEW_INVITATION_RECEIVED)&&Oo.setSignalingListenStatus(!1),(E=this._core)===null||E===void 0||E.notificationCenter.unSubscribeOuterEvent(s,n,g)}handleInvitationExpiryTimer(s){const n=Oo.getOnlineSignalingMap(),g=this._core.common.getCurrentUserID();if(!n.has(s))return;const u=n.get(s).inviter===g;this._sendTimeoutNotice({inviteID:s,isInviter:u})}_sendSignaling(s,n){return pA(this,void 0,void 0,function*(){var g,u,E;return(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageSender)===null||E===void 0?void 0:E.sendMessage(s,n)})}_sendTimeoutNotice(s){return pA(this,void 0,void 0,function*(){var n,g,u;this._core.ssoLog.debug("_sendTimeoutNotice",`${ur}._sendTimeoutNotice params:${JSON.stringify(s)}`);const{isInviter:E,inviteID:m}=s,{signaling:D,signalingData:M,signalingExtensionOptions:T}=$g.createTimeoutSignaling(s),P=yield this._sendSignaling(D,T);if(P?.code===0){const{data:W,groupID:iA,inviteeList:EA,inviter:RA}=M;(n=this._core)===null||n===void 0||n.notificationCenter.emitOuterEvent((g=this._core)===null||g===void 0?void 0:g.SignalingEvent.INVITATION_TIMEOUT,{name:(u=this._core)===null||u===void 0?void 0:u.SignalingEvent.INVITATION_TIMEOUT,data:{data:W,groupID:iA,inviteID:m,inviteeList:EA,inviter:RA,isSelfTimeout:!0,message:D}}),E?Oo.removeSignaling(m):Oo.updateSignaling(M)}})}_validateInviteId(s,n){if(!Oo.hasSignaling(n))throw new this._core.helper.ChatError({functionName:s,code:Qd})}_validateProcessStatus(s){if(this._isProcessingSignaling)throw new this._core.helper.ChatError({functionName:s,message:"processing other signaling operations"})}_validateBeforeInvite(s){const n=Bd,{userID:g}=s,u=this._core.common.getCurrentUserID();if(g===u)throw new this._core.helper.ChatError({functionName:n,message:`cannot invite yourself, currentUserId:${u}, inviteeId:${g}`})}_validateBeforeAccept(s){const n=CI;this._validateInviteId(n,s),this._validateProcessStatus(n);const g=this._core.common.getCurrentUserID(),{inviteeList:u}=Oo.getSignaling(s);if(!u.includes(g)){const E=`userID:${g} not in inviteeList. inviteID:${s}`;throw new this._core.helper.ChatError({functionName:n,message:E})}}_validateBeforeCancel(s){const n=Oa;this._validateInviteId(n,s),this._validateProcessStatus(n);const g=this._core.common.getCurrentUserID(),{inviter:u}=Oo.getSignaling(s);if(u!==g){const E=`unmatched inviter:${u} and my userID:${g}`;throw new this._core.helper.ChatError({functionName:n,message:E})}}_validateBeforeReject(s){const n=dC;this._validateInviteId(n,s),this._validateProcessStatus(n);const g=this._core.common.getCurrentUserID(),{inviteeList:u}=Oo.getSignaling(s);if(!u.includes(g)){const E=`userID:${g} not in inviteeList. inviteID:${s}`;throw new this._core.helper.ChatError({functionName:n,message:E})}}_validateBeforeModifyInvitation(s){const n=Pa;this._validateInviteId(n,s)}_dispose(){var s,n;this._reset(),(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),(n=this._core)===null||n===void 0||n.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this)}_reset(){this._isProcessingSignaling=!1}},Tl=new class{constructor(){this._actionProcessor=new Map([[ku,this._onNewInvitationReceived.bind(this)],[$r,this._onInviteeRejected.bind(this)],[hd,this._onInviteeAccepted.bind(this)],[_l,this._onInvitationCancelled.bind(this)],[dI,this._onInvitationTimeout.bind(this)]])}init(s){this._core=s,s.notificationCenter.subscribeOuterEvent(s.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),s.notificationCenter.subscribeOuterEvent(s.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this)}handleActionSignaling(s){s.forEach(n=>{const g=wc(n);if(g){const u=this._actionProcessor.get(g.actionType);u?.(g,n)}})}_handleMessageReceived(s){if(!Oo.getSignalingListenStatus())return;const n=Er(s.data);n.length!==0&&this.handleActionSignaling(n)}_handleMessageModified(s){if(!Oo.getSignalingListenStatus())return;const n=Er(s.data);n.length>0&&n.forEach(g=>{const u=wc(g);u&&this._onInvitationModified(u,g)})}_onNewInvitationReceived(s,n){var g,u;const E=`${ur}._onNewInvitationReceived`,{inviteID:m,inviteeList:D,groupID:M}=s,T=this._core.common.getCurrentUserID();if(this._core.ssoLog.debug("_onNewInvitationReceived",`${E} signalingData:${JSON.stringify(s)}}`),M&&!D.includes(T))return;let{timeout:P}=s;const W=Date.now()/1e3-n.time;P>0&&W>0&&P>W&&(P-=W);const iA=Oo.getSignaling(m);iA!==s&&(iA||Oo.saveSignaling(m,Object.assign(Object.assign({},s),{signaling:n})),P>0&&((g=this._core)===null||g===void 0||g.helper.taskScheduler.addOnceTask({id:`${Lu}-${m}`,intervalMs:1e3*P,callback:Za.handleInvitationExpiryTimer.bind(Za,m)})),this._emitEvent({name:(u=this._core)===null||u===void 0?void 0:u.SignalingEvent.NEW_INVITATION_RECEIVED,data:Object.assign(Object.assign({},this._generateBaseEmitData(s)),{inviteeList:D})}))}_onInviteeRejected(s){var n;const g=`${ur}._onInviteeRejected`,{inviteID:u,inviter:E,groupID:m,inviteeList:D}=s,M=Oo.hasSignaling(u);this._core.ssoLog.debug("_onInviteeRejected",`${g} inviteID:${u} hasInviteID:${M} inviter:${E} groupID:${m}`),M&&(Oo.updateSignaling(s),this._emitEvent({name:(n=this._core)===null||n===void 0?void 0:n.SignalingEvent.INVITEE_REJECTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(s)),{invitee:D[0]})}))}_onInviteeAccepted(s){var n;const g=`${ur}._onInviteeAccepted`,{inviteID:u,inviter:E,groupID:m,inviteeList:D}=s,M=Oo.hasSignaling(u);this._core.ssoLog.debug("_onInviteeAccepted",`${g} inviteID:${u} hasInviteID:${M} inviter:${E} groupID:${m}`),M&&(Oo.updateSignaling(s),this._emitEvent({name:(n=this._core)===null||n===void 0?void 0:n.SignalingEvent.INVITEE_ACCEPTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(s)),{invitee:D[0]})}))}_onInvitationCancelled(s){var n;const g=`${ur}._onInvitationCancelled`,{inviteID:u,inviter:E,groupID:m}=s,D=Oo.hasSignaling(u);this._core.ssoLog.debug("_onInvitationCancelled",`${g} inviteID:${u} hasInviteID:${D} inviter:${E} groupID:${m}`),D&&(Oo.removeSignaling(u),this._emitEvent({name:(n=this._core)===null||n===void 0?void 0:n.SignalingEvent.INVITATION_CANCELLED,data:this._generateBaseEmitData(s)}))}_onInvitationTimeout(s){var n;const g=`${ur}._onInvitationTimeout`,{inviteID:u,inviteeList:E}=s,m=Oo.hasSignaling(u);this._core.ssoLog.debug("_onInvitationTimeout",`${g} inviteID:${u} hasInviteID:${m} data:${s.data}`),m&&(Oo.updateSignaling(s),this._emitEvent({name:(n=this._core)===null||n===void 0?void 0:n.SignalingEvent.INVITATION_TIMEOUT,data:Object.assign(Object.assign({},this._generateBaseEmitData(s)),{inviteeList:E,isSelfTimeout:!1})}))}_onInvitationModified(s,n){var g;const u=`${ur}._onInvitationModified`,{inviteID:E,data:m}=s,D=Oo.hasSignaling(E);this._core.ssoLog.debug("_onInvitationModified",`${u} inviteID:${E} data:${m}`),D&&(Oo.saveSignaling(E,Object.assign(Object.assign({},s),{signaling:n})),this._emitEvent({name:(g=this._core)===null||g===void 0?void 0:g.SignalingEvent.INVITATION_MODIFIED,data:{inviteID:E,data:m}}))}_emitEvent(s){var n;(n=this._core)===null||n===void 0||n.notificationCenter.emitOuterEvent(s.name,s)}_generateBaseEmitData(s){const{inviteID:n,inviter:g,groupID:u,data:E}=s;return{inviteID:n,inviter:g,groupID:u,data:E||""}}_dispose(){var s,n,g;(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),(n=this._core)===null||n===void 0||n.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),(g=this._core)===null||g===void 0||g.notificationCenter.unSubscribeOuterEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}},Aa=new class{constructor(){this._offlineSignalingMap=new Map}init(s){this._core=s;const{notificationCenter:n,helper:g,constants:{InnerEvent:u,WORKFLOW_STEP:E,WORKFLOW_NAME:m}}=s;n.subscribeInnerEvent(u.DESTROY,this._dispose,this),n.subscribeInnerEvent(u.LOGOUT,this._reset,this),g.registerWorkflowStep(m.SYNC_SERVER_INFO_AFTER_LOGIN,E.SIGNALING_MESSAGE_RECOVER,this._handleC2COfflineMessage,this)}_handleC2COfflineMessage(s){const{result:{unreadMessageMap:n}={}}=s||{};if(!(n?.size!==0&&Oo.getSignalingListenStatus()))return;const g=Er([...n.values()]);if(g.length!==0&&(g.forEach(u=>{this._handleC2CActionType(u)}),this._offlineSignalingMap.size>0)){const u=this._sortOfflineSignalingByTime();Tl.handleActionSignaling(u)}}_handleC2CActionType(s){const n=wc(s);if(!n)return;const{actionType:g}=n;g===ku?this._saveValidOfflineInvite(n,s):this._removeOfflineInvite(n)}_saveValidOfflineInvite(s,n){const{inviteID:g,inviteeList:u=[],timeout:E=0}=s,m=this._core.common.getCurrentUserID();if(!u.includes(m))return;const D=Date.now()/1e3-n.time;E>0&&D>E&&E!==0||this._offlineSignalingMap.set(g,Object.assign(Object.assign({},s),{signalingList:[n]}))}_removeOfflineInvite(s){const{inviteID:n=""}=s;this._offlineSignalingMap.has(n)&&this._offlineSignalingMap.delete(n)}_sortOfflineSignalingByTime(){let s=[];return this._offlineSignalingMap.forEach(n=>{s=[...s,...n.signalingList]}),s.sort((n,g)=>n.time-g.time)}_dispose(){var s,n;this._reset(),(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),(n=this._core)===null||n===void 0||n.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._offlineSignalingMap.clear()}};const ah={invite:{userID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0},timeout:{required:!1,rules:["number"],allowEmpty:!1},onlineUserOnly:{required:!1,rules:["boolean"],allowEmpty:!1},offlinePushInfo:{required:!1,rules:["object"],allowEmpty:!1}},cancel:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},accept:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},reject:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},modifyInvitation:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}}},js={invite:!0,cancel:!0,accept:!0,reject:!0,modifyInvitation:!0};var zI=new class{constructor(){this.name="Signaling"}install(s){Za.init(s),Tl.init(s),$g.init(s),Oo.init(s),Aa.init(s),s.helper.registerValidateConfig({auth:js,params:ah})}};const Us=new class{init(s){this.core=s}};function _c(s){let n;const{message:g}=Us.core,{conversationID:u,messageID:E}=s;return n=g.messageDataHandler.getLocalMessageList(u).find(m=>m.ID===E),!n&&(n=g.messageDataHandler.getSparseMessageList(u).find(m=>m.ID===E)),n}function Ac(s){return s.map(n=>{const{from:g,to:u,cloudCustomData:E,avatar:m,nick:D,ID:M,clientSequence:T,clientTime:P,messageRandom:W,messageSequence:iA,time:EA}=n;return{ClientSeq:T,CloudCustomData:E,From_Account:g,From_AccountHeadurl:m,From_AccountNick:D,Id:M,MsgBody:JSON.parse(JSON.stringify(n.transformElementsToServerFormat())),MsgClientTime:P,MsgRandom:W,Random:W,MsgSeq:iA,MsgTimeStamp:EA,ReceiverId:u,SenderId:g,To_Account:u}})}function dr(s){var n;const{From_Account:g,From_AccountHeadurl:u,From_AccountNick:E,GroupId:m,MsgClientTime:D,ClientSeq:M,To_Account:T,MsgTimeStamp:P,TinyId:W,MsgRandom:iA,MsgSeq:EA}=s;return{from:g,avatar:u,nick:E,clientTime:D,time:P,tinyID:W,random:iA,sequence:EA,to:T,groupID:m,clientSequence:M,_elements:(n=s.MsgBody)===null||n===void 0?void 0:n.map(RA=>{const{MsgType:kA}=RA;return Us.core.message.messageFactory.getElementClass(kA).parseServerPushElement(RA)})}}var Vr,Xa;(function(s){s.MSG_TEXT="TIMTextElem",s.MSG_CUSTOM="TIMCustomElem",s.MSG_LOCATION="TIMLocationElem",s.MSG_FACE="TIMFaceElem",s.MSG_STREAM="TIMStreamElem"})(Vr||(Vr={})),function(s){s[s.FORWARD=0]="FORWARD",s[s.BACKWARD=1]="BACKWARD"}(Xa||(Xa={}));const _E="MSG_REACTION",CC="MSG_EXT",gh=0,ro=1,Tc={ZH_CN:"zh (cmn-Hans-CN)",EN_US:"en-US",YUE_HK:"yue-Hant-HK",JA_JP:"ja-JP",ZH_PY:"zh-PY"},Nl="16k_zh",hC="16k_en",BC="16k_yue",Gl="16k_ja",ZI="16k_zh-PY",hI={[Tc.ZH_CN]:Nl,[Tc.EN_US]:hC,[Tc.YUE_HK]:BC,[Tc.JA_JP]:Gl,[Tc.ZH_PY]:ZI},BI=/\.(wav|pcm|ogg-opus|speex|silk|mp3|m4a|aac|amr)/,TE={READ:0,UNREAD:1},bl=1,kl=2,Ug=3;var ec;(function(s){s.IN="in",s.OUT="out"})(ec||(ec={}));const pd=16,NE=17;var Nc;(function(s){s[s.DATA=0]="DATA",s[s.REVOKED=1]="REVOKED"})(Nc||(Nc={}));var XI;(function(s){s[s.NORMAL=0]="NORMAL",s[s.TIMEOUT=1]="TIMEOUT"})(XI||(XI={}));const co="StreamMsg.PushStreamHttp";var GE=new class{constructor(){this._reactionsMap=new Map}init(s){this._core=s;const{helper:n,notificationCenter:g,InnerEvent:{MESSAGE_PUSH:u},InnerEventSubType:{MESSAGE_REACTION_UPDATED:E,MESSAGE_REACTION_UPDATED_SYNC:m}}=s;n.registerApi({apiName:"addMessageReaction",context:this}),n.registerApi({apiName:"removeMessageReaction",context:this}),n.registerApi({apiName:"getMessageReactions",context:this}),n.registerApi({apiName:"getAllUserListOfMessageReaction",context:this}),g.subscribeInnerEvent(u,E,this._handleReactionUpdated,this),g.subscribeInnerEvent(u,m,this._handleReactionSync,this)}addMessageReaction(s,n){return pA(this,void 0,void 0,function*(){const{OuterConstant:g,ssoLog:u,helper:E}=this._core;this._validateMessageReactionBusinessCapability();const{conversationID:m,ID:D,conversationType:M,from:T,to:P,clientSequence:W,random:iA,time:EA,sequence:RA}=s,kA=`conversationID:${m} messageID:${D} reactionID:${n}`;try{return this._recordMessageReactedByMe(D,n),M===g.CONV_C2C?yield function(xA,LA){return pA(this,void 0,void 0,function*(){var SA;const{from:OA,to:JA,clientSequence:ne,random:se,time:_i,reactionID:Ti}=xA,Lt={From_Account:OA,To_Account:JA,MsgKey:`${ne}_${se}_${_i}`,Reaction:Ti,Add_Account:[(SA=LA.store.get("login"))===null||SA===void 0?void 0:SA.userId]};return Us.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_add",data:Lt})})}({from:T,to:P,clientSequence:W,random:iA,time:EA,reactionID:n},this._core):M===g.CONV_GROUP&&(yield function(xA,LA){return pA(this,void 0,void 0,function*(){var SA;const{to:OA,reactionID:JA,sequence:ne}=xA,se={GroupId:OA,MsgSeq:ne,Reaction:JA,Add_Account:[(SA=LA.store.get("login"))===null||SA===void 0?void 0:SA.userId]};return Us.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_add",data:se})})}({to:P,reactionID:n,sequence:RA},this._core)),{code:0,successLog:{message:kA}}}catch(xA){this._removeMyReactionRecord(D,n);const{errorCode:LA}=xA||{};throw new E.ChatError({functionName:"addMessageReaction",code:LA,moreMessage:kA})}})}removeMessageReaction(s,n){return pA(this,void 0,void 0,function*(){const{OuterConstant:g,helper:u}=this._core;this._validateMessageReactionBusinessCapability();const{conversationID:E,ID:m,conversationType:D,from:M,to:T,clientSequence:P,random:W,time:iA,sequence:EA}=s,RA=`conversationID:${E} messageID:${m} reactionID:${n}`;try{return this._removeMyReactionRecord(m,n),D===g.CONV_C2C?yield function(kA,xA){return pA(this,void 0,void 0,function*(){var LA;const{from:SA,to:OA,clientSequence:JA,random:ne,time:se,reactionID:_i}=kA,Ti={From_Account:SA,To_Account:OA,MsgKey:`${JA}_${ne}_${se}`,Reaction:_i,Del_Account:[(LA=xA.store.get("login"))===null||LA===void 0?void 0:LA.userId]};return Us.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_del",data:Ti})})}({from:M,to:T,clientSequence:P,random:W,time:iA,reactionID:n},this._core):D===g.CONV_GROUP&&(yield function(kA,xA){return pA(this,void 0,void 0,function*(){var LA;const{to:SA,reactionID:OA,sequence:JA}=kA,ne={GroupId:SA,MsgSeq:JA,Reaction:OA,Del_Account:[(LA=xA.store.get("login"))===null||LA===void 0?void 0:LA.userId]};return Us.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_del",data:ne},xA)})}({to:T,reactionID:n,sequence:EA},this._core)),{code:0,successLog:{message:RA}}}catch(kA){const{errorCode:xA}=kA||{};throw new u.ChatError({functionName:"removeMessageReaction",code:xA,moreMessage:RA})}})}getAllUserListOfMessageReaction(s){return pA(this,void 0,void 0,function*(){this._validateMessageReactionBusinessCapability();const{message:n,reactionID:g,nextSeq:u=0}=s,E=s.count>100?100:s.count,{conversationID:m}=n,{ssoLog:D,helper:M,constants:T}=this._core;try{let P=null;if(P=m.startsWith(T.OuterConstant.CONV_C2C)?yield function(W){return pA(this,void 0,void 0,function*(){const{message:iA,nextSeq:EA,reactionID:RA,count:kA}=W,{from:xA,to:LA,clientSequence:SA,random:OA,time:JA}=iA,ne={Reaction:RA,NextSeq:EA,Count:kA,From_Account:xA,To_Account:LA,MsgKey:`${SA}_${OA}_${JA}`};return Us.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_iterate",data:ne})})}({message:n,reactionID:g,nextSeq:u,count:E}):yield function(W){return pA(this,void 0,void 0,function*(){const{message:iA,nextSeq:EA,reactionID:RA,count:kA}=W,{sequence:xA,to:LA}=iA,SA={Reaction:RA,NextSeq:EA,GroupId:LA,Count:kA,MsgSeq:xA};return Us.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_iterate",data:SA})})}({message:n,reactionID:g,nextSeq:u,count:E}),P){const{Reaction_Account:W,NextSeq:iA}=P,EA=yield this._getUserProfileList(W);return{code:0,data:{nextSeq:iA,isCompleted:u===0,userList:EA}}}}catch(P){const{errorCode:W}=P||{};throw new M.ChatError({functionName:"getAllUserListOfMessageReaction",code:W})}})}getMessageReactions(s){return pA(this,void 0,void 0,function*(){const{constants:n}=this._core;this._validateMessageReactionBusinessCapability();const{messageList:g,maxUserCountPerReaction:u=10}=s,E=g[0];let m=null;const D=new Map,{from:M,to:T,conversationType:P}=E,W=this._generateMessageKeyList(g,D);P===n.OuterConstant.CONV_C2C?m=yield function(kA){return pA(this,void 0,void 0,function*(){const{from:xA,to:LA,messageKeyList:SA,maxUserCountPerReaction:OA}=kA,JA={From_Account:xA,To_Account:LA,MsgKeyList:SA,Count:OA};return Us.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_multi_stat",data:JA})})}({from:M,to:T,messageKeyList:W,maxUserCountPerReaction:u}):P===n.OuterConstant.CONV_GROUP&&(m=yield function(kA){return pA(this,void 0,void 0,function*(){const{groupId:xA,messageSequenceList:LA,maxUserCountPerReaction:SA}=kA,OA={GroupId:xA,MsgSeqList:LA,Count:SA};return Us.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_multi_stat",data:OA})})}({groupId:T,messageSequenceList:W,maxUserCountPerReaction:u}));const{Results:iA=[]}=m||{},EA=this._extractUserIDsFromReactionResults(iA),RA=yield this._getUserProfileMap(EA);return{code:0,data:{resultList:iA.map(kA=>{const{ReactionList:xA,MsgSeq:LA,MsgKey:SA}=kA;return{messageID:this._generateMessageID({messageSequence:LA,messageKey:SA,messageIDMap:D}),reactionList:xA.map(OA=>{const{Reaction:JA,Count:ne,Reaction_Account:se,ReactedByMe:_i}=OA;return{reactionID:JA,totalUserCount:ne,partialUserList:this._generatePartialUserInfo({userIDList:se,userProfileMap:RA}),reactedByMyself:_i===1}})}})}}})}dispose(){this._reactionsMap.clear()}_extractUserIDsFromReactionResults(s){const n=[];return s?.forEach(g=>{const{ReactionList:u=[]}=g;u.forEach(E=>{E.Reaction_Account&&n.push(...E.Reaction_Account)})}),n}_getUserProfileList(s){return pA(this,void 0,void 0,function*(){var n;try{const g=yield(n=this._core.user.userProfile)===null||n===void 0?void 0:n.getUserProfile({userIDList:s});return g?g.data:[]}catch{return[]}})}_getUserProfileMap(s){return pA(this,void 0,void 0,function*(){const n=new Map;return(yield this._getUserProfileList(s)).forEach(g=>{const{nick:u,avatar:E,userID:m}=g;n.set(m,{nick:u,avatar:E,userID:m})}),n})}_recordMessageReactedByMe(s,n){const g=`${s}-${n}`;this._reactionsMap.has(g)?this._reactionsMap.get(g).reactedByMe=!0:this._reactionsMap.set(g,{reactedByMe:!0})}_removeMyReactionRecord(s,n){const g=`${s}-${n}`;this._reactionsMap.has(g)&&(this._reactionsMap.get(g).reactedByMe=!1)}_recordMessageReactionInfo(s){const{messageID:n,reactionID:g,reactionInfo:u}=s,E=`${n}-${g}`,m=this._reactionsMap.get(E)||{};this._reactionsMap.set(E,Object.assign(Object.assign({},m),u))}_validateMessageReactionBusinessCapability(){const{helper:s,constants:n}=this._core;if(!s.checkBusinessCapabilityBits(_E))throw new s.ChatError({functionName:"addMessageReaction",code:n.ERROR_CODE.NO_USE,replacement1:"addMessageReaction"})}_handleReactionUpdated(s){const{MsgReactionNotifyList:n}=s,{notificationCenter:g,constants:u}=this._core;n.forEach(E=>pA(this,void 0,void 0,function*(){const{C2CMsgInfo:m,GroupMsgInfo:D,MsgReactionSummary:M}=E,{TinyId:T,MsgClientTime:P,MsgRandom:W}=Object.assign(Object.assign({},m),D),iA=`${T}-${P}-${W}`,EA=this._extractUserIDsFromReactionResults([{ReactionList:M}]),RA=yield this._getUserProfileMap(EA),kA=M.map(xA=>{var LA;const{Reaction:SA,Reaction_Account:OA}=xA,JA=this._generatePartialUserInfo({userIDList:OA,userProfileMap:RA}),ne=OA?xA.Count:0,se=((LA=this._reactionsMap.get(`${iA}-${SA}`))===null||LA===void 0?void 0:LA.reactedByMe)||!1;return this._recordMessageReactionInfo({messageID:iA,reactionID:SA,reactionInfo:{reactionID:SA,totalUserCount:ne,partialUserList:JA}}),{reactionID:SA,totalUserCount:ne,partialUserList:JA,reactedByMyself:se}});g.emitOuterEvent(u.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:u.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:iA,reactionList:kA}})}))}_handleReactionSync(s){var n;const{notificationCenter:g,constants:u}=this._core,{C2CMsgInfo:E={},GroupMsgInfo:m={},Reaction:D,OperateType:M}=s.MsgReactionNotify,{TinyId:T="",MsgClientTime:P=0,MsgRandom:W=0}=Object.assign(Object.assign({},E),m),iA=`${T}-${P}-${W}`,EA=`${iA}-${D}`;if(M===1?this._recordMessageReactedByMe(iA,D):this._removeMyReactionRecord(iA,D),(n=this._reactionsMap.get(EA))===null||n===void 0?void 0:n.reactionID){const RA=this._reactionsMap.get(EA);RA.reactedByMyself=M===1,g.emitOuterEvent(u.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:u.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:iA,reactionList:[RA]}})}}_generatePartialUserInfo({userIDList:s,userProfileMap:n}){const g=[];return s?.forEach(u=>{n.has(u)&&g.push(n.get(u))}),g}_generateMessageID(s){const{messageSequence:n,messageKey:g,messageIDMap:u}=s;return g?u.get(g):u.get(n)}_generateMessageKeyList(s,n){const{constants:g}=this._core,u=s[0],{conversationType:E}=u;let m=[];return E===g.OuterConstant.CONV_C2C?m=s.map(D=>{const{clientSequence:M,random:T,time:P,ID:W}=D,iA=`${M}_${T}_${P}`;return n.set(iA,W),iA}):E===g.OuterConstant.CONV_GROUP&&(m=s.map(D=>{const{ID:M,sequence:T}=D;return n.set(T,M),T})),m}},$a=new class{init(s){this._core=s;const{helper:n,InnerEvent:{MESSAGE_PUSH:g},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:u,GROUP_MESSAGE_READ_RECEIPT:E},notificationCenter:m}=s;n.registerApi({apiName:"sendMessageReadReceipt",context:this}),n.registerApi({apiName:"getMessageReadReceiptList",context:this}),n.registerApi({apiName:"getGroupMessageReadMemberList",context:this}),m.subscribeInnerEvent(g,u,this._handleC2CMessageReadReceipt,this),m.subscribeInnerEvent(g,E,this._handleGroupMessageReadReceipt,this)}sendMessageReadReceipt(s){return pA(this,void 0,void 0,function*(){var n;const{common:g,constants:u}=this._core,E=this._filterValidMessageSendByOther(s);if(E.length===0)throw new g.ChatError({code:u.ERROR_CODE.READ_RECEIPT_MSG_LIST_EMPTY});try{const{conversationType:m}=E[0];return m===u.OuterConstant.CONV_C2C?yield function(D){return pA(this,void 0,void 0,function*(){const{common:M,constants:T}=Us.core,P=D[0].conversationID.replace(T.OuterConstant.CONV_C2C,""),W=D.map(EA=>{const{from:RA,to:kA,sequence:xA,random:LA,time:SA,clientTime:OA}=EA;return{From_Account:RA,To_Account:kA,MsgSeq:xA,MsgRandom:LA,MsgTime:SA,MsgClientTime:OA}}),iA={Peer_Account:P,C2CMsgInfo:W};return M.buildAndSendPacket({servcmd:"openim.c2c_msg_read_receipt",data:iA})})}(E):yield function(D){return pA(this,void 0,void 0,function*(){const{common:M,constants:T}=Us.core,P={GroupId:D[0].conversationID.replace(T.OuterConstant.CONV_GROUP,""),MsgSeqList:D.map(W=>({MsgSeq:W.sequence}))};return M.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_receipt",data:P})})}(E),{code:0,data:{}}}catch(m){const{errorCode:D,errorInfo:M}=m;throw new g.ChatError({code:D,message:M,moreMessage:`peerAccount:${(n=E?.[0])===null||n===void 0?void 0:n.conversationID}`})}})}getMessageReadReceiptList(s){return pA(this,void 0,void 0,function*(){const{common:n,constants:g}=this._core;try{const{conversationType:u}=s[0];if(u===g.OuterConstant.CONV_GROUP){const E=this._filterValidMessageSendByMe(s);if(E?.length>0){const m=yield function(M){return pA(this,void 0,void 0,function*(){const{common:T,constants:P}=Us.core,W={GroupId:M[0].conversationID.replace(P.OuterConstant.CONV_GROUP,""),MsgSeqList:M.map(iA=>({MsgSeq:iA.sequence}))};return T.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt",data:W})})}(E),{GroupMsgReceiptList:D}=m||{};this._updateGroupMessagesReadReceiptInfo({messageList:s,readReceiptList:D})}}return{code:0,data:{messageList:s}}}catch(u){const{errorCode:E,errorInfo:m}=u;throw new n.ChatError({code:E,message:m})}})}getGroupMessageReadMemberList(s){return pA(this,void 0,void 0,function*(){const{constants:n,common:g}=this._core,{message:u,filter:E=TE.READ,cursor:m=""}=s,{conversationID:D,sequence:M,ID:T}=u,P=D.replace(n.OuterConstant.CONV_GROUP,""),W=s.count>=100?100:s.count;try{const iA=yield function(EA){return pA(this,void 0,void 0,function*(){const{sequence:RA,groupID:kA,filter:xA,cursor:LA,count:SA}=EA,OA={MsgSeq:RA,GroupId:kA,Filter:xA,Cursor:LA,Num:SA};return Us.core.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt_detail",data:OA})})}({groupID:P,sequence:M,filter:E,cursor:m,count:W});if(iA){const{Cursor:EA,IsFinish:RA,UnreadList:kA,ReadList:xA}=iA,LA={cursor:EA,isCompleted:RA===1,messageID:T,unreadUserIDList:[],readUserIDList:[]};return E===TE.READ?LA.readUserIDList=xA.map(SA=>SA.Read_Account):E===TE.UNREAD&&(LA.unreadUserIDList=kA.map(SA=>SA.Unread_Account)),{code:0,data:LA}}}catch(iA){const{errorCode:EA,errorInfo:RA}=iA;throw new g.ChatError({code:EA,message:RA})}})}_handleC2CMessageReadReceipt(s){const n=[],{constants:g,helper:u}=this._core,{C2cMsgInfo:E,PeerReadTime:m,Peer_Account:D}=s;if(u.isEmpty(E))return;const M=`${g.OuterConstant.CONV_C2C}${D}`;E?.forEach(T=>{const{TinyId:P,MsgClientTime:W,MsgRandom:iA}=T,EA=`${P}-${W}-${iA}`,RA=_c({conversationID:M,messageID:EA});RA&&!RA.readReceiptInfo.isPeerRead&&(RA.readReceiptInfo.isPeerRead=!0,RA.readReceiptInfo.timestamp=m,n.push({userID:D,messageID:EA,isPeerRead:!0,timestamp:m}))}),this._emitReadReceiptEventIfNeed(n)}_updateGroupMessagesReadReceiptInfo(s){const{messageList:n,readReceiptList:g}=s,u=new Map;n.forEach(E=>{u.set(E.sequence,E)}),g?.forEach(E=>{if(E.Code===0){const{MsgSeq:m,ReadNum:D,UnreadNum:M}=E,T=u.get(m);T&&(T.readReceiptInfo.readCount=D,T.readReceiptInfo.unreadCount=M)}})}_handleGroupMessageReadReceipt(s){const n=[],{constants:g}=this._core,{GroupTips:u}=s;u.forEach(E=>{const{MsgBody:{GroupMsgReceiptList:m},GroupInfo:{GroupId:D}}=E,M=`${g.OuterConstant.CONV_GROUP}${D}`;m?.forEach(T=>{const{TinyId:P,MsgClientTime:W,MsgRandom:iA,ReadNum:EA,UnreadNum:RA}=T,kA=`${P}-${W}-${iA}`,xA=_c({conversationID:M,messageID:kA}),LA={groupID:D,messageID:kA,readCount:0,unreadCount:0};xA&&(typeof EA=="number"&&(xA.readReceiptInfo.readCount=EA,LA.readCount=EA),typeof RA=="number"&&(xA.readReceiptInfo.unreadCount=RA,LA.unreadCount=RA),n.push(LA))})}),this._emitReadReceiptEventIfNeed(n)}_emitReadReceiptEventIfNeed(s){const{notificationCenter:n,OuterEvent:g}=this._core;s.length>0&&n.emitOuterEvent(g.MESSAGE_READ_RECEIPT_RECEIVED,{name:g.MESSAGE_READ_RECEIPT_RECEIVED,data:s})}_filterValidMessageSendByOther(s){return this._filterNeedReadReceiptMessages(s).filter(n=>{const{from:g}=n;return g!==this._core.common.getCurrentUserID()})}_filterValidMessageSendByMe(s){const{OuterConstant:n}=this._core.constants;return this._filterNeedReadReceiptMessages(s).filter(g=>{const{from:u,status:E}=g;return u===this._core.common.getCurrentUserID()&&E===n.MessageStatus.SUCCESS})}_filterNeedReadReceiptMessages(s){return s.filter(n=>n.needReadReceipt===!0)}dispose(){const{InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:n,GROUP_MESSAGE_READ_RECEIPT:g},notificationCenter:u}=this._core;u.unSubscribeInnerEvent(s,n,this._handleC2CMessageReadReceipt,this),u.unSubscribeInnerEvent(s,g,this._handleGroupMessageReadReceipt,this)}};function $I(s,n,g){return pA(this,void 0,void 0,function*(){const{common:{buildAndSendPacket:u}}=Us.core,{from:E,to:m,clientSequence:D,random:M,time:T}=s;return u({servcmd:"openim_msg_ext_http_svc.set_key_values",data:{From_Account:E,To_Account:m,MsgKey:`${D}_${M}_${T}`,OperateType:g,ExtensionList:n}})})}function Uu(s,n,g){return pA(this,void 0,void 0,function*(){const{common:{buildAndSendPacket:u}}=Us.core,{to:E,sequence:m}=s;return u({servcmd:"openim_msg_ext_http_svc.group_set_key_values",data:{GroupId:E,MsgSeq:m,OperateType:g,ExtensionList:n}})})}var Gc=new class{constructor(){this._messageExtensionsMap=new Map,this._extensionsLatestSequenceMap=new Map,this._completedFetchExtensions=new Set}init(s){this._core=s;const{notificationCenter:n,helper:{registerApi:g},InnerEvent:{MESSAGE_PUSH:u,LOGOUT:E},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:m}}=s;g({apiName:"setMessageExtensions",context:this}),g({apiName:"getMessageExtensions",context:this}),g({apiName:"deleteMessageExtensions",context:this}),n.subscribeInnerEvent(u,m,this._handleMessageExtensionsNotify,this),n.subscribeInnerEvent(E,this.reset,this)}setMessageExtensions(s,n){return pA(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("setMessageExtensions");const{constants:{OuterConstant:g},ssoLog:u}=this._core,{ID:E,conversationID:m,sequence:D,time:M,conversationType:T}=s;let P=n;n.length>20&&(P=n.slice(0,20),u.warn("setMessageExtensions","the length of extensions cannot exceed 20"));const W=this._generateServerExtensions(s,P),iA=`convID:${m} messageID:${E} sequence:${D} time:${M} count:${P.length}`;try{let EA;if(T===g.CONV_C2C?EA=yield $I(s,W,bl):T===g.CONV_GROUP&&(EA=yield Uu(s,W,bl)),EA){const{resultList:RA,successCount:kA,failureCount:xA}=this._handleModifyMessageExtensions(s,EA);return{code:0,data:{extensions:RA},successLog:{message:`${iA} successCount:${kA} failCount:${xA}`}}}return{code:0,data:{extensions:[]}}}catch(EA){const{errorCode:RA}=EA;throw new this._core.helper.ChatError({functionName:"setMessageExtensions",code:RA,moreMessage:iA})}})}getMessageExtensions(s){return pA(this,void 0,void 0,function*(){const{utils:{isUndefined:n}}=this._core;this._validateMessageExtensionBusinessCapability("getMessageExtensions");const{conversationID:g,ID:u,sequence:E,time:m}=s,D=`convID:${g} messageID:${u} sequence:${E} time:${m}`;try{let M;this._completedFetchExtensions.has(u)&&(M=this._extensionsLatestSequenceMap.get(u));const T=yield this._fetchMessageExtensions(s,M);return n(M)&&T.length>1&&this._completedFetchExtensions.add(u),{code:0,data:{extensions:T},successLog:{message:D}}}catch(M){const{errorCode:T,errorInfo:P=""}=M||{};throw new this._core.common.ChatError({code:T,message:P,moreMessage:D})}})}deleteMessageExtensions(s,n){return pA(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("deleteMessageExtensions");const{utils:{isEmpty:g},constants:{OuterConstant:u}}=this._core,{conversationType:E,conversationID:m,sequence:D,ID:M,time:T}=s;let P=Ug;const W=[];g(n)||(P=kl,n?.forEach(RA=>{W.push({key:RA,value:"",seq:0})}));const iA=`convID:${m} messageID:${M} sequence:${D} time:${T} operateType:${P}`,EA=this._generateServerExtensions(s,W);try{let RA;if(E===u.CONV_C2C?RA=yield $I(s,EA,P):E===u.CONV_GROUP&&(RA=yield Uu(s,EA,P)),RA){const{resultList:kA,successCount:xA,failureCount:LA}=this._handleModifyMessageExtensions(s,RA);return{code:0,data:{extensions:kA},successLog:{message:`${iA}successCount:${xA} failCount:${LA}`}}}return{code:0,data:{extensions:[]}}}catch(RA){const{errorCode:kA}=RA;throw new this._core.helper.ChatError({functionName:"deleteMessageExtensions",code:kA,moreMessage:iA})}})}reset(){this._messageExtensionsMap.clear(),this._extensionsLatestSequenceMap.clear(),this._completedFetchExtensions.clear()}dispose(){this.reset();const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:n,LOGOUT:g},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:u}}=this._core;s.unSubscribeInnerEvent(n,u,this._handleMessageExtensionsNotify,this),s.subscribeInnerEvent(g,this.reset,this)}_handleModifyMessageExtensions(s,n){const{ID:g}=s,{Seq:u}=n,E=n.ExtensionList||[],m=[];let D=0,M=0,T=[];return E.forEach(P=>{const{ErrorCode:W,Extension:iA}=P,{Key:EA,Value:RA,Seq:kA}=iA;m.push({code:W,key:EA,value:RA}),W===0?D++:M++,T.push({key:EA,value:RA,seq:kA})}),this._extensionsLatestSequenceMap.set(g,u),T.length>0&&this._updateLocalExtensions(s.ID,T),{resultList:m,successCount:D,failureCount:M}}_updateLocalExtensions(s,n){this._messageExtensionsMap.has(s)||this._messageExtensionsMap.set(s,new Map);const g=this._messageExtensionsMap.get(s);n?.forEach(u=>{const{key:E,seq:m,value:D=""}=u;g?.set(E,{value:D,seq:m})})}_fetchMessageExtensions(s,n){return pA(this,void 0,void 0,function*(){const{constants:{OuterConstant:g},utils:{isEmpty:u}}=this._core;try{let E;const{conversationType:m,ID:D}=s;if(m===g.CONV_C2C?E=yield function(M,T){const{common:{buildAndSendPacket:P}}=Us.core,{from:W,to:iA,clientSequence:EA,random:RA,time:kA}=M;return P({servcmd:"openim_msg_ext_http_svc.get_key_values",data:{From_Account:W,To_Account:iA,MsgKey:`${EA}_${RA}_${kA}`,StartSeq:T}})}(s,n):m===g.CONV_GROUP&&(E=yield function(M,T){const{common:{buildAndSendPacket:P}}=Us.core,{to:W,sequence:iA}=M;return P({servcmd:"openim_msg_ext_http_svc.group_get_key_values",data:{GroupId:W,MsgSeq:iA,StartSeq:T}})}(s,n)),E){const{LatestSeq:M,ClearSeq:T,CompleteFlag:P}=E,W=(E.ExtensionList||[]).map(EA=>({key:EA.Key,value:EA.Value,seq:EA.Seq}));if(this._updateLocalExtensions(D,W),this._clearLocationExtensions(D,T),this._extensionsLatestSequenceMap.set(D,M),P!==1){const EA=W[W.length-1].seq+1;return this._fetchMessageExtensions(s,EA)}const iA=[];if(this._messageExtensionsMap.has(D)){const EA=this._messageExtensionsMap.get(D);EA?.forEach((RA,kA)=>{const{value:xA}=RA;u(xA)||iA.push({key:kA,value:xA})})}return iA}}catch(E){throw E}})}_clearLocationExtensions(s,n){if(!(n<=0)&&this._messageExtensionsMap.has(s)){const g=this._messageExtensionsMap.get(s);g?.forEach((u,E)=>{u.seq<=n&&g.delete(E)})}}_generateServerExtensions(s,n){const{ID:g}=s;if(this._messageExtensionsMap.has(g)){const u=this._messageExtensionsMap.get(g);return n.map(E=>{var m;const{key:D,value:M}=E;let T=0;return u?.has(D)&&(T=(m=u.get(D))===null||m===void 0?void 0:m.seq),{Key:D,Value:M,Seq:T}})}return n.map(u=>({Key:u.key,Value:u.value,Seq:0}))}_validateMessageExtensionBusinessCapability(s){const{helper:n,constants:g}=this._core;if(!n.checkBusinessCapabilityBits(CC))throw new n.ChatError({functionName:s,code:g.ERROR_CODE.NO_USE,replacement1:s})}_handleMessageExtensionsNotify(s){const{SetKVInfo:n,DeleteKVInfo:g,ClearKVInfo:u,MsgOptType:E,TinyId:m,MsgLastSeq:D,ExtensionC2cMsgInfo:M,ExtensionGroupMsgInfo:T}=s?.MsgExtensionNotify||{},P=M||T||{},{MsgClientTime:W,MsgRandom:iA}=P,EA=`${m}-${W}-${iA}`;this._extensionsLatestSequenceMap.set(EA,D),E===bl?this._handleMessageExtensionsUpdated({messageID:EA,updateMessageExtensionsInfo:n}):E===kl?this._handleMessageExtensionsDeleted({messageID:EA,deleteMessageExtensionsInfo:g}):E===Ug&&this._handleMessageExtensionsCleared({messageID:EA,clearMessageExtensionsInfo:u})}_handleMessageExtensionsUpdated(s){const{notificationCenter:n,OuterEvent:g}=this._core,{messageID:u,updateMessageExtensionsInfo:E=[]}=s,m=[];E.forEach(D=>{const{MsgKeyValue:M=[]}=D,T=M.map(P=>(m.push({key:P.Key,value:P.Value}),{key:P.Key,value:P.Value,seq:P.Seq}));this._updateLocalExtensions(u,T)}),n.emitOuterEvent(g.MESSAGE_EXTENSIONS_UPDATED,{name:g.MESSAGE_EXTENSIONS_UPDATED,data:{messageID:u,extensions:m}})}_handleMessageExtensionsDeleted(s){const{notificationCenter:n,OuterEvent:g}=this._core,{messageID:u,deleteMessageExtensionsInfo:E=[]}=s,m=[];E.forEach(D=>{const{MsgKeyValue:M=[]}=D,T=M.map(P=>(m.push(P.Key),{key:P.Key,seq:P.Seq}));this._updateLocalExtensions(u,T)}),n.emitOuterEvent(g.MESSAGE_EXTENSIONS_DELETED,{name:g.MESSAGE_EXTENSIONS_DELETED,data:{messageID:u,keyList:m}})}_handleMessageExtensionsCleared(s){const{notificationCenter:n,OuterEvent:{MESSAGE_EXTENSIONS_DELETED:g},utils:{isEmpty:u}}=this._core,{messageID:E,clearMessageExtensionsInfo:m=[]}=s,D=[];m.forEach(M=>{const{ClearMsgSeq:T}=M;this._messageExtensionsMap.has(E)&&(this._messageExtensionsMap.get(E)||[]).forEach((P,W)=>{P.seq<=T&&!u(P.value)&&D.push(W)}),this._clearLocationExtensions(E,T)}),n.emitOuterEvent(g,{name:g,data:{messageID:E,keyList:D}})}};const QI={key:"message",required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>{const{constants:{OuterConstant:n}}=Us.core;return s.status!==n.MessageStatus.SUCCESS?"message is not success":s.isSupportExtension===!0||"message is not support extension"}},ol={setMessageExtensions:[QI,{key:"extensions",required:!0,rules:["array"],allowEmpty:!1}],getMessageExtensions:[QI],deleteMessageExtensions:[QI]},sl=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({deleteMessage:[{required:!0,rules:["array"],allowEmpty:!1}],revokeMessage:[{required:!0,rules:["object"],allowEmpty:!1}],resendMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"options",required:!1,rules:["object"],allowEmpty:!1}],getMessageList:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},nextReqMessageID:{required:!1,rules:["string"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}},getMessageListHopping:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},sequence:{required:!1,rules:["number"],allowEmpty:!0},direction:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}},createTextAtMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>{const n=function(g){var u;return typeof g?.text!="string"||typeof g.text=="string"&&((u=g?.text)===null||u===void 0?void 0:u.length)===0?"payload.text is invalid.":!0}(s);return n!==!0?n:!(s?.atUserList&&!Array.isArray(s.atUserList))||"atUserList should be an array or undefind."}}},findMessage:[{required:!0,rules:["string"],allowEmpty:!1}],translateText:{sourceTextList:{required:!0,rules:["array"],allowEmpty:!1},sourceLanguage:{required:!0,rules:["string"],allowEmpty:!1},targetLanguage:{required:!0,rules:["string"],allowEmpty:!1}},createForwardMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!(!s.startsWith("C2C")&&!s.startsWith("GROUP"))||"conversationType is invalid."},payload:{required:!0,rules:["object"],allowEmpty:!1}},createLocationMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>{const{utils:{isString:n,isNumber:g}}=Us.core;return n(s?.description)?g(s?.longitude)?!!g(s?.latitude)||"payload.latitude must be a number.":"payload.longitude must be a number.":"payload.description must be a string."}}}},{addMessageReaction:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"reactionID",required:!0,rules:["string"],allowEmpty:!1}],removeMessageReaction:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"reactionID",required:!0,rules:["string"],allowEmpty:!1}],getMessageReactions:{messageList:{required:!0,rules:["array"],allowEmpty:!1},maxUserCountPerReaction:{required:!1,rules:["number"],allowEmpty:!0,customValidator:s=>typeof s!="number"?"maxUserCountPerReaction is invalid.":!(s<0||s>10)||"maxUserCountPerReaction should between [0, 10]."}},getAllUserListOfMessageReaction:{message:{required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>s.status==="success"||"message is invalid."},reactionID:{required:!0,rules:["string"],allowEmpty:!1},nextSeq:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}}}),{sendMessageReadReceipt:[{required:!0,rules:["array"],allowEmpty:!1}],getMessageReadReceiptList:[{required:!0,rules:["array"],allowEmpty:!1}],getGroupMessageReadMemberList:{message:{required:!0,rules:["object"],allowEmpty:!1},filter:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0},cursor:{required:!1,rules:["string"],allowEmpty:!0}}}),ol),{pinGroupMessage:{groupID:{required:!0,rules:["string"],allowEmpty:!1},message:{required:!0,rules:["object"],allowEmpty:!1},isPinned:{required:!0,rules:["boolean"],allowEmpty:!1}},getPinnedGroupMessageList:[{key:"groupID",required:!0,rules:["string"],allowEmpty:!1}]}),{createQuoteMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"quotedMessage",required:!0,rules:["object"],allowEmpty:!1}]}),xa=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({deleteMessage:!0,revokeMessage:!0,resendMessage:!0,getMessageList:!0,getMessageListHopping:!0,createTextAtMessage:!0,findMessage:!0,translateText:!0,createForwardMessage:!0,createLocationMessage:!0},{addMessageReaction:!0,removeMessageReaction:!0,getMessageReactions:!0,getAllUserListOfMessageReaction:!0}),{sendMessageReadReceipt:!0,getMessageReadReceiptList:!0,getGroupMessageReadMemberList:!0}),{setMessageExtensions:!0,getMessageExtensions:!0,deleteMessageExtensions:!0}),{pinGroupMessage:!0,getPinnedGroupMessageList:!0}),{createQuoteMessage:!0});class bE{constructor(n){this._core=n}deleteMessage(n){return pA(this,void 0,void 0,function*(){const{to:g,messageIdentifiers:u}=n,E={From_Account:this._core.common.getCurrentUserID(),To_Account:g,MsgKeyList:u};return this._core.common.buildAndSendPacket({servcmd:"openim.delete_c2c_msg_ramble",data:E})})}revokeMessage(n){return pA(this,void 0,void 0,function*(){const{to:g,from:u,sequence:E,time:m,random:D}=n,M={MsgInfo:{From_Account:u,To_Account:g,MsgSeq:E,MsgRandom:D,MsgTimeStamp:m}};return this._core.common.buildAndSendPacket({servcmd:"openim.msgwithdraw",data:M})})}}class ra{constructor(n){this._core=n}deleteMessage(n){return pA(this,void 0,void 0,function*(){const{to:g,messageIdentifiers:u}=n,E={GroupId:g,Deleter_Account:this._core.common.getCurrentUserID(),Seqs:u};return this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_ramble_msg_by_seq",data:E})})}revokeMessage(n){return pA(this,void 0,void 0,function*(){const{to:g,sequence:u}=n,E={GroupId:g,MsgSeqList:[{MsgSeq:u}]};return this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_recall",data:E})})}}const Mn=2116;class br{constructor(n){this._core=n}generateRevokeMessage(n){const{conversationID:g,sequence:u,random:E,tinyID:m,clientTime:D,revokeReason:M,revoker:T}=n;let P={};const{messageDataHandler:W}=this._core.message;return P=W.revokeMessage({conversationID:g,sequence:u,random:E,revoker:T}),P||(P={conversationID:g,sequence:u},m&&D&&E&&(P.ID=`${m}-${D}-${E}`)),P.revoker=T,P.revokeReason=M,P.revokerInfo={userID:T,nick:"",avatar:""},P}updateRevokerInfo(n){return pA(this,void 0,void 0,function*(){const g=n.map(u=>u.revoker);try{const u=yield this._fetchUserInfos(g);u&&n.forEach(E=>{const{revoker:m}=E;u[m]&&(E.revokerInfo.nick=u[m].nick||"",E.revokerInfo.avatar=u[m].avatar||"",E.revokerInfo.userID=m)})}catch(u){console.debug(u)}})}_fetchUserInfos(n){return pA(this,void 0,void 0,function*(){var g,u;const E=yield(g=this._core.user.userProfile)===null||g===void 0?void 0:g.getUserProfile({userIDList:n});return E?.data?(u=E.data)===null||u===void 0?void 0:u.reduce((m,{userID:D,nick:M,avatar:T})=>(m[D]={nick:M||"",avatar:T||""},m),{}):null})}}var nl=new class{constructor(){this._core=null,this._c2cMessageAction=null,this._groupMessageAction=null}init(s){this._core=s,this._groupMessageAction=new ra(s),this._c2cMessageAction=new bE(s),this._messageHelper=new br(s);const{helper:n}=s;n.registerApi({apiName:"deleteMessage",context:this}),n.registerApi({apiName:"revokeMessage",context:this}),n.registerApi({apiName:"resendMessage",context:this}),n.registerApi({apiName:"findMessage",context:this}),n.registerApi({apiName:"createQuoteMessage",context:this})}deleteMessage(s){return pA(this,void 0,void 0,function*(){let n=[],g=[];const{conversationID:u,conversationType:E}=s[0],m=u.replace(E,"");if(E==="@TIM#SYSTEM")throw new this._core.helper.ChatError({code:Mn});if(s.forEach(D=>{const{conversationID:M,conversationType:T,status:P,_onlineOnlyFlag:W,sequence:iA,random:EA,time:RA}=D||{};if(P==="success"&&M===u&&T===E){if(!W){const kA=T==="C2C"?`${iA}_${EA}_${RA}`:String(iA);n.push(kA)}g.push(D)}}),n.length===0)return this._handleDeleteMessageSuccess(g),{code:0,data:{messageList:g}};n.length>30&&(n=n.slice(0,30),g=g.slice(0,30));try{return E==="C2C"?yield this._c2cMessageAction.deleteMessage({to:m,messageIdentifiers:n}):yield this._groupMessageAction.deleteMessage({to:m,messageIdentifiers:n}),this._handleDeleteMessageSuccess(g),{code:0,data:{messageList:g}}}catch(D){const{utils:{safeStringify:M}}=this._core,{errorCode:T,errorInfo:P}=D;throw new this._core.helper.ChatError({functionName:"deleteMessage",code:T,message:P,moreMessage:`messageIdentifiers: ${M(n)}`})}})}revokeMessage(s){return pA(this,void 0,void 0,function*(){var n;const{conversationType:g,isRevoked:u,ID:E,type:m,from:D,to:M}=s;let T=null;const P=`type:${m} from:${D} to:${M} ID:${E}`;if(g==="@TIM#SYSTEM")throw new this._core.helper.ChatError({message:"system message cannot be revoked"});if(u)throw new this._core.helper.ChatError({message:"message has been revoked",moreMessage:P});try{if(T=g==="C2C"?yield this._c2cMessageAction.revokeMessage(s):yield this._groupMessageAction.revokeMessage(s),T){const{RecallRetList:W}=T,iA=((n=W?.[0])===null||n===void 0?void 0:n.RetCode)||0;if(iA!==0)throw new this._core.helper.ChatError({code:iA,moreMessage:P});return s.isRevoked=!0,yield this._handleRevokeMessageSuccess(s),{code:0,data:{message:s},successLog:{message:P}}}}catch(W){const{errorCode:iA}=W;throw new this._core.helper.ChatError({functionName:"revokeMessage",code:iA,moreMessage:P})}})}resendMessage(s,n){return pA(this,void 0,void 0,function*(){var g,u;return s.isResend=!0,s.status="unSend",(u=(g=this._core)===null||g===void 0?void 0:g.apiMap)===null||u===void 0?void 0:u.sendMessage(s,n)})}findMessage(s){return this._core.message.messageDataHandler.findMessage(s)}createQuoteMessage(s,n){const{ID:g,time:u,sequence:E}=n;return s.quoteInfo={msgID:g,messageTime:u,messageSequence:E},s}_handleDeleteMessageSuccess(s){if(s.length===0)return;const{message:{messageDataHandler:n},common:{isTopic:g},notificationCenter:u,InnerEvent:E}=this._core;s.forEach(D=>{D.isDeleted=!0;const M=n.getLocalMessageList(D.conversationID);M?.forEach(T=>{T.ID===D.ID&&(T.isDeleted=!0)})});const{conversationID:m=""}=s[0];g(m)?u.emitInnerEvent(E.TOPIC_MESSAGE_DELETED,m):u.emitInnerEvent(E.MESSAGE_DELETED,m)}_handleRevokeMessageSuccess(s){return pA(this,void 0,void 0,function*(){var n;const g=(n=this._core.store.get("login"))===null||n===void 0?void 0:n.userId,{conversationID:u,sequence:E,random:m}=s;this._core.message.messageDataHandler.revokeMessage({conversationID:u,sequence:E,random:m,revoker:g}),yield this._messageHelper.updateRevokerInfo([s])})}};class Ll{static parseServerPushElement(n){const{MsgContent:g={}}=n,{Index:u,Data:E}=g;return new Ll({index:u,data:E})}constructor(n){this.type=Vr.MSG_FACE;const{index:g,data:u}=n;this.content={index:g,data:u}}validateBeforeSend(){var n,g;return typeof((n=this.content)===null||n===void 0?void 0:n.index)=="number"&&typeof((g=this.content)===null||g===void 0?void 0:g.data)=="string"?{isValid:!0}:{isValid:!1,error:{message:"content is invalid"}}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},u=g?this.payload:this.content,{index:E,data:m}=u;return{MsgType:this.type,MsgContent:{Index:E,Data:m}}}}class bc{static parseServerPushElement(n){const{MsgContent:g={}}=n,{Desc:u,Longitude:E,Latitude:m}=g;return new bc({description:u,longitude:E,latitude:m})}constructor(n){this.type=Vr.MSG_LOCATION;const{description:g,longitude:u,latitude:E}=n;this.content={description:g,longitude:u,latitude:E}}validateBeforeSend(){return{isValid:!0}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},u=g?this.payload:this.content,{description:E,longitude:m,latitude:D}=u;return{MsgType:this.type,MsgContent:{Desc:E,Longitude:m,Latitude:D}}}}class kE{static parseServerPushElement(n){const{MsgContent:g={}}=n,{StreamMsgID:u,CompatibleText:E,Markdown:m,BinaryData:D,ErrorCode:M,ErrorMsg:T}=g;return new kE({streamMessageID:u,compatibleText:E,markdown:m,binaryData:D,errorCode:M,errorMessage:T})}constructor(n){this.type=Vr.MSG_STREAM,this.content={streamMessageID:"",compatibleText:"",errorCode:0,errorMessage:"",isStreamEnded:!1},this._chunks=[],this._latestIndex=0;const{streamMessageID:g,compatibleText:u,markdown:E,binaryData:m,errorCode:D=0,errorMessage:M="",isStreamEnded:T=!1,chunks:P=[],latestIndex:W=0}=n;this.content.streamMessageID=g,this.content.compatibleText=u,this.content.markdown=E,this.content.binaryData=m,this.content.errorCode=D,this.content.errorMessage=M,this.content.isStreamEnded=T,this.content.chunks=P,this.content.latestIndex=W}updateChunks(n){if(!n||n.length===0)return;const g=n.sort((m,D)=>m.index-D.index),u=this._getMaxRevokedChunkIndex(g);u>=0&&(this._chunks=[],this._latestIndex=u,this._updateContent());const E=this._getValidChunks(g);if(E.length!==0&&(this._mergeAndSortChunks(E),this._chunks.length>0)){const m=this._chunks[this._chunks.length-1];this._latestIndex=m.index,this._updateContent(),this.content.isStreamEnded=m.isLast}}getLatestIndex(){return this._latestIndex}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},u=g?this.payload:this.content,{streamMessageID:E,chunks:m}=u,D=m?.map(M=>({EventType:M.eventType||"data",Index:M.index,Markdown:M.markdown,IsLast:M.isLast}));return{MsgType:this.type,MsgContent:{StreamMsgID:E,Chunks:D}}}validateBeforeSend(){var n,g;return((g=(n=this.content)===null||n===void 0?void 0:n.chunks)===null||g===void 0?void 0:g.length)>0?{isValid:!0}:{isValid:!1,error:{message:"content is invalid"}}}_filterContinuousChunks(n,g){if(n.length===0)return[];const u=[];let E=g;for(const m of n){if(m.index>E)break;m.index===E&&(u.push(m),E++)}return u}_mergeAndSortChunks(n){const g=new Map;this._chunks.forEach(u=>{g.set(u.index,u)}),n.forEach(u=>{g.set(u.index,u)}),this._chunks=Array.from(g.values()).sort((u,E)=>u.index-E.index)}_updateContent(){this.content.markdown=this._chunks.map(g=>g.markdown).join("");const n=this._chunks.map(g=>g.binaryData).filter(g=>g?.length>0);if(n.length===0)this.content.binaryData=new Uint8Array(0);else if(n.length===1)this.content.binaryData=n[0];else{const g=n.reduce((m,D)=>m+D.length,0),u=new Uint8Array(g);let E=0;for(const m of n)u.set(m,E),E+=m.length;this.content.binaryData=u}}_getMaxRevokedChunkIndex(n){let g=-1;for(let u=0;ug&&(g=E.index)}return g}_getValidChunks(n){const g=n.filter(u=>u.eventType===Nc.DATA&&u.index>this._latestIndex);return this._filterContinuousChunks(g,this._latestIndex+1)}}var kc=new class{init(s){this._core=s,s.message.messageFactory.registerElementClass(Vr.MSG_FACE,Ll),s.message.messageFactory.registerElementClass(Vr.MSG_LOCATION,bc),s.message.messageFactory.registerElementClass(Vr.MSG_STREAM,kE),s.helper.registerApi({apiName:"createFaceMessage",context:this}),s.helper.registerApi({apiName:"createTextAtMessage",context:this}),s.helper.registerApi({apiName:"createForwardMessage",context:this}),s.helper.registerApi({apiName:"createLocationMessage",context:this})}createFaceMessage(s){if(!s)return null;const{index:n,data:g}=s?.payload||{},u=new Ll({index:n,data:g}),E=this._core.common.getCurrentUserID(),m=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:E}));return m.setElement(u),m}createTextAtMessage(s){const{atUserList:n}=s?.payload||{},g=this._core.apiMap.createTextMessage(s),{OuterConstant:u}=this._core;if(!g)return null;if(Array.isArray(n)){const E=[],m=[];n.forEach(D=>{D!==u.MSG_AT_ALL?(E.push({GroupAtAllFlag:gh,GroupAt_Account:D}),m.push(D)):(E.push({GroupAtAllFlag:ro}),m.push(u.MSG_AT_ALL))}),g._groupAtInfoList=E,g.atUserList=m}return g}createForwardMessage(s){const{helper:n,OuterConstant:g}=this._core,{to:u,conversationType:E,priority:m,payload:D,needReadReceipt:M,receiverList:T,cloudCustomData:P="",isSupportExtension:W=!1}=s;if(!Array.isArray(D._elements))throw new n.ChatError({functionName:"createForwardMessage",code:2454});if(D.type===g.MSG_GRP_TIP)throw new n.ChatError({functionName:"createForwardMessage",code:2453});const iA=this._core.common.getCurrentUserID(),EA=this._core.message.messageFactory.createMessage({to:u,from:iA,conversationType:E,isPlaceMessage:0,priority:m,payload:D,needReadReceipt:M,isSupportExtension:W,cloudCustomData:P,receiverList:T});return EA.setRelayFlag(!0),EA.setElement(D._elements[0]),EA}createLocationMessage(s){if(!s)return null;const{description:n,longitude:g,latitude:u}=s?.payload||{},E=new bc({description:n,longitude:g,latitude:u}),m=this._core.common.getCurrentUserID(),D=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:m}));return D.setElement(E),D}};let Fu=class{init(s){this._messageHelper=new br(s),this._core=s;const{notificationCenter:n,InnerEvent:{MESSAGE_PUSH:g},InnerEventSubType:{C2C_REVOKED_MESSAGE:u},helper:{registerWorkflowStep:E},constants:{WORKFLOW_NAME:m,WORKFLOW_STEP:D}}=s;n.subscribeInnerEvent(g,u,this._handleC2CNotifyMessage,this),E(m.SYNC_SERVER_INFO_AFTER_RE_ONLINE,D.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,this._handleC2CRevokeMessagesFromUnreadMessageSync,this)}_handleC2CNotifyMessage(s){const{C2cNotifyMsgArray:n}=s;n?.forEach(g=>{Object.keys(g).includes("WithdrawC2cMsgNotify")&&this._handleC2CRevokeMessage(g)})}_handleC2CRevokeMessage(s){return pA(this,void 0,void 0,function*(){try{const{WithdrawC2cMsgNotify:{C2cWithdrawInfoArray:n}}=s;yield this._parseAndEmitC2CRevokedMessages(n)}catch(n){console.debug(n)}})}_parseAndEmitC2CRevokedMessages(s){return pA(this,void 0,void 0,function*(){const n=[],{notificationCenter:g,OuterEvent:u,common:{getCurrentUserID:E}}=this._core;s.forEach(m=>{var D;const{MsgRand:M,MsgSeq:T,To_Account:P,From_Account:W,RevokerInfo:{Revoker_Account:iA,Revoke_Reason:EA}}=m,RA=E()===W?`C2C${P}`:`C2C${W}`,kA=((D=m?.RevokerInfo)===null||D===void 0?void 0:D.Reason)||EA,xA=this._messageHelper.generateRevokeMessage({conversationID:RA,sequence:T,random:M,revoker:iA,revokeReason:kA});n.push(xA)}),n.length>0&&(yield this._messageHelper.updateRevokerInfo(n),g.emitOuterEvent(u.MESSAGE_REVOKED,{name:u.MESSAGE_REVOKED,data:n}))})}_handleC2CRevokeMessagesFromUnreadMessageSync(s){return pA(this,void 0,void 0,function*(){const{revokedMessageList:n}=s.result;yield this._parseAndEmitC2CRevokedMessages(n)})}dispose(){const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:n},InnerEventSubType:{C2C_REVOKED_MESSAGE:g}}=this._core;s.unSubscribeInnerEvent(n,g,this._handleC2CNotifyMessage,this)}},QC=class{init(s){this._messageHelper=new br(s),this._core=s;const{notificationCenter:n,InnerEvent:{MESSAGE_PUSH:g},InnerEventSubType:{GROUP_MESSAGE_REVOKED:u}}=s;n.subscribeInnerEvent(g,u,this._handleGroupNotifyMessage,this)}_handleGroupNotifyMessage(s){const{GroupTips:n}=s;n?.forEach(g=>{var u;Array.isArray((u=g?.MsgBody)===null||u===void 0?void 0:u.GroupWithdrawInfoArray)&&this._handleGroupRevokeMessage(g)})}_handleGroupRevokeMessage(s){return pA(this,void 0,void 0,function*(){try{const{RevokerInfo:n,MsgBody:{GroupWithdrawInfoArray:g},GroupInfo:u}=s,E=[],m=[],{notificationCenter:D,OuterEvent:M,utils:{isEmpty:T},common:{isCommunity:P}}=this._core;let W=!1;u&&(W=P({groupID:u.GroupId})||!T(u.TopicId)),g.forEach(iA=>{const{Random:EA,MsgSeq:RA,GroupId:kA,MsgClientTime:xA,TinyId:LA,TopicId:SA,RevokerInfo:{Revoker_Account:OA=n?.Revoker_Account||"",Reason:JA=n?.Reason||""}}=iA,ne=SA?`GROUP${SA}`:`GROUP${kA}`,se=this._messageHelper.generateRevokeMessage({conversationID:ne,sequence:RA,random:EA,tinyID:LA,clientTime:xA,revoker:OA,revokeReason:JA});W?(se.revokerInfo.nick=u.From_AccountNick,se.revokerInfo.avatar=u.From_AccountHeadurl,E.push(se)):m.push(se)}),m.length>0&&(yield this._messageHelper.updateRevokerInfo(m),E.push(...m)),E.length!==0&&D.emitOuterEvent(M.MESSAGE_REVOKED,{name:M.MESSAGE_REVOKED,data:E})}catch(n){console.debug(n)}})}dispose(){const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:n},InnerEventSubType:{GROUP_MESSAGE_REVOKED:g}}=this._core;s.unSubscribeInnerEvent(n,g,this._handleGroupNotifyMessage,this)}};var Au=new class{constructor(){this._c2cMessageReceiver=new Fu,this._groupMessageReceiver=new QC}init(s){this._c2cMessageReceiver.init(s),this._groupMessageReceiver.init(s)}dispose(){this._c2cMessageReceiver.dispose(),this._groupMessageReceiver.dispose()}},ch=new class{constructor(){this._core=null}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"translateText",context:this})}translateText(s){return pA(this,void 0,void 0,function*(){try{const{sourceLanguage:n,sourceTextList:g,targetLanguage:u}=s,E=yield function(m,D){return pA(this,void 0,void 0,function*(){var M,T;const{sourceTextList:P,sourceLanguage:W,targetLanguage:iA}=m,{store:EA,common:RA}=D,kA={SourceText:P,Source:W,Target:iA,FromAccount:(M=EA.get("login"))===null||M===void 0?void 0:M.tinyID,SDKAppID:(T=EA.get("instance"))===null||T===void 0?void 0:T.sdkAppId},xA=yield RA.buildAndSendPacket({servcmd:"im_open_translate.ws_batch_trans_text",data:kA});if(xA){const{CmdErrorCode:LA,TargetText:SA}=xA;return{cmdErrorCode:LA,translatedTextList:SA}}})}({sourceLanguage:n,sourceTextList:g,targetLanguage:u},this._core);if(E){const{cmdErrorCode:{ErrorCode:m,ErrorInfo:D},translatedTextList:M}=E;if(m===0)return{code:0,data:{translatedTextList:M}};throw{errorCode:m,errorInfo:D,message:D}}}catch(n){const{errorCode:g,errorInfo:u}=n||{};throw new this._core.helper.ChatError({functionName:"translateText",code:g,message:u})}})}},Ou=new class{init(s){this._core=s,s.helper.registerApi({apiName:"convertVoiceToText",context:this})}convertVoiceToText(s){return pA(this,void 0,void 0,function*(){var n;const{message:g,language:u=Tc.ZH_PY}=s;let{url:E}=g.payload||{};const m=this._core.common.getCurrentUserID();g.from===m&&g.flow==="out"&&(E=g.payload.remoteAudioUrl),this._validateVoiceFormat(E);const D=((n=BI.exec(E))===null||n===void 0?void 0:n[1])||"mp3",M=hI[u]||ZI;try{const T=yield function(P){var W;const{store:iA,common:EA}=Us.core,{url:RA,format:kA,serverLanguageType:xA}=P,LA={BytesUrl:RA,BytesEngServiceType:xA,BytesVoiceFormat:kA,Uint32Sdkappid:(W=iA.get("instance"))===null||W===void 0?void 0:W.sdkAppId,Uint64SourceType:0};return EA.buildAndSendPacket({servcmd:"im_open_speech.ws_sentence_recognition",data:LA})}({url:E,format:D,serverLanguageType:M});if(T){const{CmdErrorCode:P,BytesResult:W}=T;if(P.ErrorCode===0)return{code:0,data:{result:W}};throw{code:P.ErrorCode,message:P.ErrorInfo}}}catch(T){const{code:P,message:W}=T||{};throw new this._core.common.ChatError({functionName:"convertVoiceToText",code:P,message:W})}})}_validateVoiceFormat(s){if(!BI.test(s))throw new this._core.common.ChatError({code:2119})}};class pI{constructor(n){const{constants:g,common:u,utils:E}=Us.core,{CONV_C2C:m,CONV_GROUP:D}=g.OuterConstant,{ID:M,tinyID:T,from:P,to:W,clientTime:iA=u.timeManager.getServerTimeSeconds()||0,random:EA,sequence:RA,cloudCustomData:kA="",nick:xA="",avatar:LA="",clientSequence:SA,conversationType:OA,groupID:JA,_elements:ne,time:se}=n;this.ID=M||`${T}-${iA}-${EA}`,this.messageRandom=EA,this.from=P,this.messageSender=P,this.time=se,this.messageSequence=RA,this.clientSequence=SA||RA,this.clientTime=iA,this.cloudCustomData=kA,this.messageReceiver=W,this.avatar=LA,this.nick=xA;const _i=E.deepCopyWithMethods(ne);_i.forEach(Ti=>{Ti.payload=Ti.content,delete Ti.content}),this.messageBody=_i,M?OA.startsWith(m)?this.receiverUserID=W:OA.startsWith(D)&&(this.receiverGroupID=W):JA?(this.receiverGroupID=JA,this.messageReceiver=JA):W&&(this.receiverUserID=W,this.messageReceiver=W)}transformElementsToServerFormat(){return this.messageBody?Array.isArray(this.messageBody)?this.messageBody.map(n=>n.transformToServerFormat({isMergerMessage:!0})):this.messageBody.transformToServerFormat({isMergerMessage:!0}):null}}class rl{static parseServerPushElement(n){const{MsgContent:g}=n,{MsgList:u=[],CompatibleText:E,AbstractList:m,Title:D,PbMsgKey:M,JsonMsgKey:T}=g||{},P=u.map(W=>dr(W));return new rl({messageList:P,title:D,abstractList:m,compatibleText:E,pbDownloadKey:M,downloadKey:T})}constructor(n){this.type=Us.core.constants.OuterConstant.MSG_MERGER;const{messageList:g,title:u,abstractList:E,compatibleText:m,pbDownloadKey:D="",downloadKey:M="",version:T=0,layersOverLimit:P=!1}=n,W=[];g.forEach(iA=>{if(iA){const EA=new pI(iA);W.push(EA)}}),this.content={messageList:W,title:u,abstractList:E,compatibleText:m,version:T,downloadKey:M,pbDownloadKey:D,layersOverLimit:P}}validateBeforeSend(){const{isEmpty:n}=Us.core.helper;return n(this.content.messageList)?{isValid:!1,error:{message:"content is invalid"}}:{isValid:!0}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},u=g?this.payload:this.content,{abstractList:E,compatibleText:m,downloadKey:D,layersOverLimit:M,pbDownloadKey:T,title:P,version:W,messageList:iA}=u;return{MsgType:this.type,MsgContent:{AbstractList:E,CompatibleText:m,JsonMsgKey:D,LayersOverLimit:M,PbMsgKey:T,Title:P,Version:W,MsgList:Ac(iA)}}}}var pC=new class{init(s){this._core=s;const{message:n,helper:g,constants:{OuterConstant:u}}=s;n.messageFactory.registerElementClass(u.MSG_MERGER,rl),g.registerApi({apiName:"createMergerMessage",context:this}),g.registerApi({apiName:"sendMessage",context:this,matcher:E=>E[0].type===u.MSG_MERGER}),g.registerApi({apiName:"downloadMergerMessage",context:this})}createMergerMessage(s){const{common:n}=this._core;if(!s)return null;const g=new rl(s.payload),u=n.getCurrentUserID(),E=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:u}));return E.setRelayFlag(!0),E.setElement(g),E}sendMessage(s,n){return pA(this,void 0,void 0,function*(){var g,u,E;try{const m=function(P){let W="utf-8";Us.core.helper.IN_BROWSER&&document&&(W=document.charset.toLowerCase());let iA,EA=0,RA=0;if(RA=P.length,W==="utf-8"||W==="utf8")for(let kA=0;kA11264){D=this._core.utils.deepCopyWithMethods(s);try{const{JsonMsgKey:P,PbMsgKey:W}=yield function(EA){return pA(this,void 0,void 0,function*(){const{payload:{messageList:RA}}=EA,kA={MsgList:Ac(RA)};return Us.core.common.buildAndSendPacket({servcmd:"im_long_msg.save_relay_json_msg",data:kA})})}(D),{payload:iA}=D;M=new rl(Object.assign(Object.assign({},iA),{messageList:[],downloadKey:P,pbDownloadKey:W})),D.setElement(M)}catch(P){console.error(P)}}const{data:{message:T}}=yield(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageSender)===null||E===void 0?void 0:E.sendMessage(D,n);return M&&T.setElement(s._elements),{code:0,data:{message:T}}}catch(m){const{errorCode:D}=m;throw new this._core.helper.ChatError({code:D})}})}downloadMergerMessage(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n}=this._core,g=s.payload,{downloadKey:u,pbDownload:E,type:m,messageList:D}=g,M=Do(g,["downloadKey","pbDownload","type","messageList"]);try{const T=yield function(iA){return pA(this,void 0,void 0,function*(){return Us.core.common.buildAndSendPacket({servcmd:"im_long_msg.get_relay_json_msg",data:{JsonMsgKey:iA}})})}(u),{MsgList:P}=T||{},W=P?.map(iA=>{const EA=dr(iA);return new pI(EA)});return typeof s.isOnlineMessage=="function"?s.setElement({type:s.type,content:Object.assign({messageList:W},M)}):(s.payload.messageList=W,s.payload.downloadKey="",s.payload.pbDownloadKey=""),n.info("downloadMergerMessage",` success downloadKey:${u}`),s}catch(T){const{errorCode:P}=T;throw new this._core.helper.ChatError({functionName:"downloadMergerMessage",code:P,moreMessage:u})}})}},aa=new class{init(s){this._core=s,this._core.helper.registerExperimentalAPI("sendComboMessage",this)}sendComboMessage(s){return pA(this,void 0,void 0,function*(){const{appStore:n,message:g,common:{getCurrentUserID:u},utils:{isArray:E}}=this._core,{GroupId:m,To_Account:D}=s;s.From_Account=s.From_Account||u();let M=null;if(m){M=this._generateGroupMessage(Object.assign(Object.assign({},s),{ToGroupId:m}));const T=n.userStore.getUserProfile(u());M.level=T?.level||0,E(D)&&D.length>0&&(M._receiverList=D)}else D&&(M=this._generateC2CMessage(s));return g.messageSender.sendMessage(M,s)})}_generateC2CMessage(s){const{message:n,OuterConstant:{CONV_C2C:g}}=this._core,u=g,E=n.messageHelper.parseServerPushMessage(s),m=n.messageFactory.createMessage(Object.assign(Object.assign({},E),{conversationType:u,flow:ec.OUT})),{elements:D}=E;return m.setElement(D),m}_generateGroupMessage(s){const{message:n,OuterConstant:{CONV_GROUP:g}}=this._core,u=g,E=n.messageHelper.parseServerGroupMessage(s),m=n.messageFactory.createMessage(Object.assign(Object.assign({},E),{conversationType:u,flow:ec.OUT})),{elements:D}=E;return m.setElement(D),m}},tc=new class{init(s){this._core=s;const{helper:n,notificationCenter:g,InnerEvent:{MESSAGE_PUSH:u},InnerEventSubType:{GROUP_MESSAGE_PINNED:E}}=s;g.subscribeInnerEvent(u,E,this._handleGroupMessagePinned,this),n.registerApi({apiName:"pinGroupMessage",context:this}),n.registerApi({apiName:"getPinnedGroupMessageList",context:this})}pinGroupMessage(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n,common:{isTopic:g},OuterConstant:{GROUP_ID_PREFIX:u},helper:{ChatError:E}}=this._core;let{groupID:m,message:D,isPinned:M}=s;const{sequence:T}=D;try{return yield function(P){return pA(this,void 0,void 0,function*(){const{common:{buildAndSendPacket:W,getCurrentUserID:iA}}=Us.core,{groupID:EA,sequence:RA,isPinned:kA}=P,xA=iA(),LA=kA?"group_open_http_svc.pin_message":"group_open_http_svc.unpin_message",SA={GroupId:EA,MsgSeq:RA};return kA?SA.Pinner_Account=xA:SA.UnPinner_Account=xA,W({servcmd:LA,data:SA})})}({groupID:m,sequence:T,isPinned:M}),{code:0,data:{}}}catch(P){const{errorCode:W,errorInfo:iA}=P||{};throw new E({code:W,message:iA})}})}getPinnedGroupMessageList(s){return pA(this,void 0,void 0,function*(){let n=[];try{const g=yield function(u){return pA(this,void 0,void 0,function*(){const{groupID:E}=u,{common:{buildAndSendPacket:m}}=Us.core;return m({servcmd:"group_open_http_svc.get_pinned_messages",data:{GroupId:E}})})}({groupID:s});if(g){const{PinnedMsgList:u=[]}=g;n=yield this._updatePinnedMessageInfo({serverPinnedMessageList:u,groupID:s})}return{code:0,data:{messageList:n}}}catch(g){throw g}})}_handleGroupMessagePinned(s){const{message:{messageHelper:n,messageFactory:g},notificationCenter:u,OuterEvent:E,OuterConstant:m}=this._core;s.GroupTips.forEach(D=>{const{ToGroupId:M,MsgBody:{PinnedMsg:T,OpType:P,MsgOperatorMemberExtraInfo:W,SdkGroupMessageId:iA}}=D,{UserId:EA,NickName:RA="",ImageUrl:kA=""}=W;let xA=null,LA=!1;if(P===pd){LA=!0;const SA=n.parseServerGroupMessage(T);xA=g.createMessage(Object.assign(Object.assign({},SA),{conversationType:m.CONV_GROUP,flow:"in"})),xA.setElement(SA.elements),xA.pinnerInfo={userID:EA,nick:RA,avatar:kA}}else if(P===NE){const{ClientTime:SA,Random:OA,SenderTinyId:JA,ServerTime:ne,MsgSeq:se}=iA;xA={ID:`${JA}-${SA}-${OA}`,sequence:se,random:OA,time:ne,clientTime:SA}}xA&&u.emitOuterEvent(E.PINNED_GROUP_MESSAGE_UPDATED,{name:E.PINNED_GROUP_MESSAGE_UPDATED,data:{groupID:M,message:xA,isPinned:LA,operatorInfo:{userID:EA,nick:RA,avatar:kA}}})})}_findMessageBySequence(s,n){const{message:{messageDataHandler:g}}=this._core;return[...g.getLocalMessageList(s),...g.getSparseMessageList(s)].find(u=>u.sequence===n)}_updatePinnedMessageInfo(s){return pA(this,arguments,void 0,function*({serverPinnedMessageList:n,groupID:g}){const{OuterConstant:{CONV_GROUP:u},utils:{isEmpty:E}}=this._core,m=[],D=[],M=[],T=new Map,P=`${u}${g}`;for(let iA=0;iA{const{sequence:kA}=RA,xA=T.get(kA),LA=iA[xA]||{userID:xA,nick:"",avatar:""};RA.pinnerInfo=LA}),m.sort((RA,kA)=>RA.sequence-kA.sequence),m}return[]})}_fetchPinnedMessageInfo(s){return pA(this,void 0,void 0,function*(){var n,g;const{message:{messageHistory:u},user:{userProfile:E},utils:{isArray:m}}=this._core,{conversationID:D,messageSequenceList:M,pinnerIDList:T}=s,P=yield Promise.all([this._fetchMessageBySequence({conversationID:D,messageSequenceList:M}),E?.getUserProfile({userIDList:T})]);if(m(P)){const W={};return(((n=P[1])===null||n===void 0?void 0:n.data)||[]).forEach(iA=>{const{userID:EA,nick:RA="",avatar:kA=""}=iA;W[EA]={userID:EA,nick:RA,avatar:kA}}),{messageList:((g=P[0])===null||g===void 0?void 0:g.messageList)||[],pinnerInfoMap:W}}})}_fetchMessageBySequence(s){return pA(this,void 0,void 0,function*(){const{utils:{isEmpty:n},message:{messageHistory:g}}=this._core,{conversationID:u,messageSequenceList:E}=s;return n(E)?[]:g.getGroupRoamingMessagesByAnchor({conversationID:u,messageSequenceList:E,getType:3})})}};class lg{constructor(n){this.eventType=Nc.DATA,this.index=0,this.markdown="",this.isLast=!1,this.binaryData=null;const{EventType:g,Index:u,Markdown:E,IsLast:m,BinaryData:D}=n;this.eventType=g,this.index=u,this.markdown=E,this.isLast=m,this.binaryData=D}}var mI=new class{constructor(){this._messageMap=new Map,this._retryCountMap=new Map}init(s){this._core=s;const{notificationCenter:n,OuterEvent:{MESSAGE_RECEIVED:g},InnerEvent:{HISTORY_MESSAGE_FETCHED:u},common:{workflowManager:E},constants:{WORKFLOW_NAME:m,WORKFLOW_STEP:D}}=s;n.subscribeInnerEvent(co,this._handleStreamMessageChunkPush,this),n.subscribeOuterEvent(g,this._handleMessageReceived,this),n.subscribeInnerEvent(u,this.processHistoryMessage,this),E.registerWorkflowStep(m.SYNC_SERVER_INFO_AFTER_RE_ONLINE,D.STREAM_MESSAGE_RECOVER,this._recoverStreamMessage,this)}processHistoryMessage(s){const{utils:{isEmpty:n,safeStringify:g},ssoLog:u}=this._core;try{s?.forEach(E=>{var m;if(this._isValidStreamMessage(E)){const D=(m=E?._elements)===null||m===void 0?void 0:m[0],{streamMessageID:M,markdown:T,binaryData:P}=D?.content||{};n(T)&&n(P)?(this._messageMap.set(M,E),this._fetchStreamMessageChunks(E)):D.content.isStreamEnded=!0}})}catch(E){u.error("processHistoryMessage.error",g(E))}}_handleMessageReceived(s){const n=s.data;n?.forEach(g=>{var u,E;if(this._isValidStreamMessage(g)){const{streamMessageID:m}=((E=(u=g?._elements)===null||u===void 0?void 0:u[0])===null||E===void 0?void 0:E.content)||{};m&&(this._messageMap.set(m,g),this._fetchStreamMessageChunks(g))}})}_isValidStreamMessage(s){var n,g;const{utils:{isEmpty:u}}=this._core,{streamMessageID:E}=((g=(n=s?._elements)===null||n===void 0?void 0:n[0])===null||g===void 0?void 0:g.content)||{};return s.type===Vr.MSG_STREAM&&!u(E)}_fetchStreamMessageChunks(s){return pA(this,void 0,void 0,function*(){var n,g;const{constants:{ERROR_CODE:u},ssoLog:E,utils:{safeStringify:m}}=this._core,D=(n=s._elements)===null||n===void 0?void 0:n[0],M=(g=D?.content)===null||g===void 0?void 0:g.streamMessageID;try{const{from:T,to:P}=s,W=D.getLatestIndex();if(D.content.isStreamEnded)return;const iA=yield function(EA){return pA(this,void 0,void 0,function*(){const{from:RA,to:kA,streamMessageID:xA,index:LA}=EA,SA={From_Account:RA,To_Account:kA,StreamMsgID:xA,AckIndex:LA};return Us.core.common.buildAndSendPacket({servcmd:"StreamMsg.GetStreamHttp",data:SA,timeout:5e3})})}({from:T,to:P,streamMessageID:M,index:W});if(iA){const{ErrorCode:EA,ErrorInfo:RA}=iA;if(EA!==0)throw D.content.errorCode=EA,D.content.errorMessage=RA,{errorCode:EA,errorMessage:RA}}}catch(T){if(T.errorCode===u.NETWORK_TIMEOUT&&this._shouldRetryFetch(M)){const P=this._retryCountMap.get(M)||0;E.debug("_fetchStreamMessageChunks.timeout",`error: ${m(T)} retried: ${P}`),this._retryCountMap.set(M,P+1),this._fetchStreamMessageChunks(s)}else E.error("_fetchStreamMessageChunks.error",m(T))}})}_shouldRetryFetch(s){const{utils:{isNumber:n}}=this._core;if(!this._retryCountMap.has(s))return this._retryCountMap.set(s,1),!0;const g=this._retryCountMap.get(s);return!!(n(g)&&g<=3)}_onStreamEnded(s,n,g){const{ssoLog:u}=this._core;g.content.isStreamEnded=!0,g.stopReason=n,this._messageMap.delete(s),u.debug("_onStreamEnded",`streamMessage end, StopReason: ${n}`)}_handleStreamMessageChunkPush(s){var n;const{ssoLog:g}=this._core,{StopReason:u,Chunks:E,StreamID:m}=s?.body||{},D=this._messageMap.get(m);if(!D)return void g.warn(`_handleStreamMessageChunkPush, unfounded message: ${m}`);const M=(n=D._elements)===null||n===void 0?void 0:n[0];if(M&&this._validateExpectedChunk(M,E)){if(E.length>0){const T=E.map(P=>new lg(P));M.updateChunks(T)}this._emitMessageModify(D),function(T,P){pA(this,void 0,void 0,function*(){const{common:{generateProtocolData:W},utils:{safeStringify:iA},ssoLog:EA,channel:RA}=Us.core,kA={StreamMsgID:T,AckIndex:P};try{const xA=W({servcmd:"StreamMsg.AckHttp",data:kA});RA.sendPacket(xA)}catch(xA){EA.debug("sendStreamChunkAck",iA(xA))}})}(m,M.getLatestIndex()),M.content.isStreamEnded&&this._onStreamEnded(m,u,M)}}_emitMessageModify(s){const{notificationCenter:n,OuterEvent:{MESSAGE_MODIFIED:g}}=this._core;n.emitOuterEvent(g,{name:g,data:[s]})}_validateExpectedChunk(s,n){const g=s.getLatestIndex()+1;let u=!1;for(let E=0;Em.Index).join(", ")}]`),!1}return!0}_recoverStreamMessage(){this._retryCountMap.clear();const{ssoLog:s,utils:{safeStringify:n}}=this._core;try{const g=Array.from(this._messageMap.entries());for(let u=Math.max(0,g.length-300);u{const LA=this._getResponseBody(kA,E,iA&&EA),SA=this._buildResponse(kA,LA);if(kA.status===200)n(null,SA);else{if(EA&&!RA.includes(EA))return s.url=this._domainName2IP(RA,EA),s.uploadByIP=!0,this.request(s,n);n({code:kA.status,message:JSON.stringify(kA.responseText)},SA)}},kA.onerror=()=>{const LA=this._getResponseBody(kA,E,iA&&EA),SA=this._buildResponse(kA,LA),OA={code:kA.status,message:kA.status===0?"CORS blocked or network error":JSON.stringify(kA.responseText)};n(OA,SA)},s.onProgress&&kA.upload&&(kA.upload.onprogress=LA=>{const{total:SA,loaded:OA}=LA,JA=Math.min(Math.floor(100*OA/SA),100);s.onProgress({total:SA,loaded:OA,percent:JA/100})}),kA.send(P),kA})}_buildResponse(s,n){const g={};return s.getAllResponseHeaders().trim().split(`
-`).forEach(u=>{if(u){const[E,m]=u.split(":").map(D=>D.trim());g[E.toLowerCase()]=m}}),{statusCode:s.status,statusMessage:s.statusText,headers:g,data:n}}_getResponseBody(s,n,g){return s.status===200&&n?{location:n,uploadIP:g}:{response:s.responseText,uploadIP:g}}_queryString(s,n="&",g="="){var u;const{isEmpty:E,isPlainObject:m}=(u=this._core)===null||u===void 0?void 0:u.utils;return E(s)?"":m(s)?Object.keys(s).map(D=>{const M=encodeURIComponent(D)+g;return Array.isArray(s[D])?s[D].map(T=>M+encodeURIComponent(T)).join(n):M+encodeURIComponent(s[D])}).filter(Boolean).join(n):void 0}_domainName2IP(s,n){return s.replace(/^http(s)?:\/\/(.*?)\//,`https://${n}/`)}};const xu=["unknown","image","video","audio","log"];var fI=new class{init(s){this._core=s}request(s,n){var g;const{MINI_APP_NAMESPACE:u,IN_ALIPAY_MINI_APP:E,isUniIOSApp:m}=(g=this._core)===null||g===void 0?void 0:g.utils,{resources:D="",headers:M={},url:T,downloadUrl:P=""}=s;let W=T,iA=null;const EA=P?P.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/):null;if(!EA)return void console.warn("message Invalid download URL format");const RA=decodeURIComponent(EA[3]),kA=RA.includes("?")?RA.split("?")[0]:RA||"",xA={key:s.fileKey||kA,success_action_status:200,"Content-Type":""},LA={};if(m()){const[OA,JA]=T.split("?sign=");JA&&(W=`${OA}?sign=${encodeURIComponent(JA)}`,LA.sign=decodeURIComponent(JA),LA.signature=decodeURIComponent(JA))}let SA={url:W,header:M,name:"file",filePath:D,formData:Object.assign(Object.assign({},xA),LA),timeout:s.timeout||3e5};if(E){const{name:OA}=SA,JA=Do(SA,["name"]);SA=Object.assign(Object.assign({},JA),{fileName:"file",fileType:s.fileType?xu[s.fileType]:"image"})}return iA=u.uploadFile(Object.assign(Object.assign({},SA),{success:OA=>{this._handleResponse({response:OA,downloadUrl:P,callback:n})},fail:OA=>{this._handleResponse({response:OA,downloadUrl:P,callback:n})}})),iA.onProgressUpdate&&iA.onProgressUpdate(OA=>{s.onProgress&&s.onProgress({total:OA.totalBytesExpectedToSend||0,loaded:OA.totalBytesSent||0,percent:OA.progress?Math.floor(OA.progress)/100:0})}),iA}_handleResponse(s){const{downloadUrl:n,response:g,callback:u}=s,E={};if(g.header)for(const D in g.header)g.header.hasOwnProperty(D)&&(E[D.toLowerCase()]=g.header[D]);const m=+g.statusCode;m===200?u(null,{statusCode:m,headers:E,data:Object.assign(Object.assign({},g.data),{location:n})}):u({code:m,message:JSON.stringify(g.data)},{statusCode:m,headers:E,data:void 0})}};function al(s){return function(n){return Object.prototype.toString.call(n).match(/^\[object (.*)\]$/)[1].toLowerCase()}(s)==="file"}function kr(s){const n=s||99999999;return Math.round(Math.random()*n)}function Lr(s,n=!0,g=!0){const u=Date.now();return n?g?u-s+" ms":`${Math.round((u-s)/1e3)} s`:g?u-s:Math.round((u-s)/1e3)}function Ig(s){return`${Array.from({length:8},()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1)).join("")}-${s}`}function ar(s,n){return Math.round(Number(s)*10**n)/10**n}function Rr(s){return s<=1048576?`${ar(s/1024,1)}KB/s`:`${ar(s/1048576,1)}MB/s`}const ic="TIMImageElem",Fg="TIMSoundElem",Ya="TIMFileElem",Ul="TIMVideoFileElem",Ca="RichMediaMessagePlugin",yI=["rich.my-imcloud.com","imrich.qcloud.com"],eu=1,ha=2,gl=3,UE=255;var tu;(function(s){s.UNSENT="unSend",s.SUCCESS="success",s.FAIL="fail"})(tu||(tu={}));const FE={wechat:/^(wxfile:\/\/tmp_|http:\/\/temp\/|cloud:\/\/temp-)/,alipay:/^(https:\/\/resource\/|alipayfile:\/\/tmp\/)/,baidu:/^(http:\/\/tmp\/|swanfile:\/\/tmp_)/,bytedance:/^(ttfile:\/\/tmp_|\/(var|tmp)\/|tttemp:\/\/)/,qq:/^(qqfile:\/\/tmp_|http:\/\/qtemp\/)/},Jr=Symbol("isCustomUpload");var iu,Ft=new class{init(s){this._core=s}addAuthToUrl(s=""){if(this._isMiniProgramTempFile(s))return s;const n=function(g){return g?g.startsWith("https://")?g:g.startsWith("http://")?g.replace("http://","https://"):g:""}(s);return this.processResourceUrl(n)}removeAuthToUrl(s){return function(n,g){const[u,E]=n.split("?");if(!E)return u;const m=E.split("&").reduce((M,T)=>{const[P,W]=T.split("=");return P&&P!==g&&(M[P]=W||""),M},{}),D=Object.keys(m).map(M=>`${M}${m[M]?`=${m[M]}`:""}`).join("&");return D?`${u}?${D}`:u}(s,"authKey")}_isMiniProgramTempFile(s){return!!this.getPlatformFlags().IN_MINI_APP&&Object.values(FE).some(n=>n.test(s))}extractFileFromInput(s){const{utils:{isArray:n}}=this._core;return al(s)?s:function(g){if(typeof g!="object"||g===null)return!1;const u=Object.getPrototypeOf(g);if(u===null)return!0;let E=u;for(;Object.getPrototypeOf(E)!==null;)E=Object.getPrototypeOf(E);return u===E}(s)&&typeof uni<"u"?n(s.tempFiles)&&s.tempFiles.length>0?s.tempFiles[0]:n(s.files)?s.files[0]:s.tempFile?s.tempFile:null:s instanceof HTMLInputElement&&s.files&&s.files.length>0?s.files[0]:null}probeImageWidthHeight(s){return pA(this,void 0,void 0,function*(){var n;const{IN_MINI_APP:g,IN_BROWSER:u}=((n=this._core)===null||n===void 0?void 0:n.utils)||{};return this._shouldSkipProbing()?{width:0,height:0}:u?this._probeImageDimensionsWeb(s):g?this._probeImageDimensionsMiniApp(s):void 0})}isSimpleCos(){var s;const n=((s=this._core)===null||s===void 0?void 0:s.store.get("cloudConfig"))||{},{simple_cos:g}=n;return g!=="0"}getFileDNList(){var s;let n=yI;const g=((s=this._core)===null||s===void 0?void 0:s.store.get("cloudConfig"))||{},{file_dn_list:u}=g;if(u===void 0)return n;try{JSON.parse(u).forEach(E=>{n.includes(E)||n.push(E)})}catch(E){console.warn(E),n=yI}return n}getPlatform(){var s;return(s=this._core)===null||s===void 0?void 0:s.utils.platform}generateUUID(s,n){var g;let u=`${this.getSDKAppID()}-${this.getCurrentUserID()}-${(g=this._core)===null||g===void 0?void 0:g.utils.randomString()}`;if(n)return`${u}.${n}`;const E=s.name||s.value||s.url||s.tempFilePath,m=E&&E.slice(E.lastIndexOf(".")+1);return m&&(u=`${u}.${m}`),u}processResourceUrl(s){if(!s)return"";let n=s;const g=this.getFileDownloadProxy(),u=this.getAuthKey(),E=this.getFileDNList();return g&&(s.startsWith("http://")?n=s.replace(/^http:\/\/[^/]+/,g):s.startsWith("https://")&&(n=s.replace(/^https:\/\/[^/]+/,g))),u&&n.indexOf("authKey=")===-1&&function(D,M){let T=!1;if(D){const P=D.match(/:\/\/([0-9]?\.)?(.[^/:]+)/),W=P&&P[2]||"";if(W.includes("rich-dev"))return!0;for(let iA=0;iA-1?`${n}&authKey=${u}`:`${n}?authKey=${u}`),n}getCurrentUserID(){var s,n;return(n=(s=this._core)===null||s===void 0?void 0:s.store.get("login"))===null||n===void 0?void 0:n.userId}getSDKAppID(){var s,n;return(n=(s=this._core)===null||s===void 0?void 0:s.store.get("instance"))===null||n===void 0?void 0:n.sdkAppId}getFileDownloadProxy(){var s,n;return((n=(s=this._core)===null||s===void 0?void 0:s.store.get("instance"))===null||n===void 0?void 0:n.fileDownloadProxy)||""}getFileUploadProxy(){var s,n;return((n=(s=this._core)===null||s===void 0?void 0:s.store.get("instance"))===null||n===void 0?void 0:n.fileUploadProxy)||""}getAuthKey(){var s,n;return((n=(s=this._core)===null||s===void 0?void 0:s.store.get("login"))===null||n===void 0?void 0:n.authKey)||""}isPrivateNetWork(){var s,n;return(n=(s=this._core)===null||s===void 0?void 0:s.store.get("instance"))===null||n===void 0?void 0:n.proxyServer}getPlatformFlags(){var s;const{IN_BROWSER:n,IN_MINI_APP:g,IN_RN_APP:u,IN_UNI_NATIVE_APP:E}=(s=this._core)===null||s===void 0?void 0:s.utils;return{IN_BROWSER:n,IN_MINI_APP:g,IN_RN_APP:u,IN_UNI_NATIVE_APP:E}}isEmpty(s){var n;const{isEmpty:g}=(n=this._core)===null||n===void 0?void 0:n.utils;return g(s)}generateURL(s,n){const{needAddAuthToUrl:g=!0}=n||{};return g?this.addAuthToUrl(s):s}_probeImageDimensionsMiniApp(s){var n;const{MINI_APP_NAMESPACE:g}=((n=this._core)===null||n===void 0?void 0:n.utils)||{};return new Promise(u=>{g.getImageInfo({src:s,success:E=>u({width:E.width,height:E.height}),fail:()=>u({width:0,height:0})})})}_shouldSkipProbing(){var s;const{IN_RN_APP:n,IS_IE:g,IE_VERSION:u,IN_WX_MINI_GAME:E}=((s=this._core)===null||s===void 0?void 0:s.utils)||{};return n||g&&u===9||E}_probeImageDimensionsWeb(s){return new Promise(n=>{const g=new Image,u=()=>{g.onload=null,g.onerror=null,g.src=""};g.onload=()=>{n({width:g.width,height:g.height}),u()},g.onerror=()=>{n({width:0,height:0}),u()},g.src=s})}},Yu={exports:{}},Vu=(iu||(iu=1,function(s){s.exports=function(n){var g=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];function u(LA,SA){var OA=LA[0],JA=LA[1],ne=LA[2],se=LA[3];JA=((JA+=((ne=((ne+=((se=((se+=((OA=((OA+=(JA&ne|~JA&se)+SA[0]-680876936|0)<<7|OA>>>25)+JA|0)&JA|~OA&ne)+SA[1]-389564586|0)<<12|se>>>20)+OA|0)&OA|~se&JA)+SA[2]+606105819|0)<<17|ne>>>15)+se|0)&se|~ne&OA)+SA[3]-1044525330|0)<<22|JA>>>10)+ne|0,JA=((JA+=((ne=((ne+=((se=((se+=((OA=((OA+=(JA&ne|~JA&se)+SA[4]-176418897|0)<<7|OA>>>25)+JA|0)&JA|~OA&ne)+SA[5]+1200080426|0)<<12|se>>>20)+OA|0)&OA|~se&JA)+SA[6]-1473231341|0)<<17|ne>>>15)+se|0)&se|~ne&OA)+SA[7]-45705983|0)<<22|JA>>>10)+ne|0,JA=((JA+=((ne=((ne+=((se=((se+=((OA=((OA+=(JA&ne|~JA&se)+SA[8]+1770035416|0)<<7|OA>>>25)+JA|0)&JA|~OA&ne)+SA[9]-1958414417|0)<<12|se>>>20)+OA|0)&OA|~se&JA)+SA[10]-42063|0)<<17|ne>>>15)+se|0)&se|~ne&OA)+SA[11]-1990404162|0)<<22|JA>>>10)+ne|0,JA=((JA+=((ne=((ne+=((se=((se+=((OA=((OA+=(JA&ne|~JA&se)+SA[12]+1804603682|0)<<7|OA>>>25)+JA|0)&JA|~OA&ne)+SA[13]-40341101|0)<<12|se>>>20)+OA|0)&OA|~se&JA)+SA[14]-1502002290|0)<<17|ne>>>15)+se|0)&se|~ne&OA)+SA[15]+1236535329|0)<<22|JA>>>10)+ne|0,JA=((JA+=((ne=((ne+=((se=((se+=((OA=((OA+=(JA&se|ne&~se)+SA[1]-165796510|0)<<5|OA>>>27)+JA|0)&ne|JA&~ne)+SA[6]-1069501632|0)<<9|se>>>23)+OA|0)&JA|OA&~JA)+SA[11]+643717713|0)<<14|ne>>>18)+se|0)&OA|se&~OA)+SA[0]-373897302|0)<<20|JA>>>12)+ne|0,JA=((JA+=((ne=((ne+=((se=((se+=((OA=((OA+=(JA&se|ne&~se)+SA[5]-701558691|0)<<5|OA>>>27)+JA|0)&ne|JA&~ne)+SA[10]+38016083|0)<<9|se>>>23)+OA|0)&JA|OA&~JA)+SA[15]-660478335|0)<<14|ne>>>18)+se|0)&OA|se&~OA)+SA[4]-405537848|0)<<20|JA>>>12)+ne|0,JA=((JA+=((ne=((ne+=((se=((se+=((OA=((OA+=(JA&se|ne&~se)+SA[9]+568446438|0)<<5|OA>>>27)+JA|0)&ne|JA&~ne)+SA[14]-1019803690|0)<<9|se>>>23)+OA|0)&JA|OA&~JA)+SA[3]-187363961|0)<<14|ne>>>18)+se|0)&OA|se&~OA)+SA[8]+1163531501|0)<<20|JA>>>12)+ne|0,JA=((JA+=((ne=((ne+=((se=((se+=((OA=((OA+=(JA&se|ne&~se)+SA[13]-1444681467|0)<<5|OA>>>27)+JA|0)&ne|JA&~ne)+SA[2]-51403784|0)<<9|se>>>23)+OA|0)&JA|OA&~JA)+SA[7]+1735328473|0)<<14|ne>>>18)+se|0)&OA|se&~OA)+SA[12]-1926607734|0)<<20|JA>>>12)+ne|0,JA=((JA+=((ne=((ne+=((se=((se+=((OA=((OA+=(JA^ne^se)+SA[5]-378558|0)<<4|OA>>>28)+JA|0)^JA^ne)+SA[8]-2022574463|0)<<11|se>>>21)+OA|0)^OA^JA)+SA[11]+1839030562|0)<<16|ne>>>16)+se|0)^se^OA)+SA[14]-35309556|0)<<23|JA>>>9)+ne|0,JA=((JA+=((ne=((ne+=((se=((se+=((OA=((OA+=(JA^ne^se)+SA[1]-1530992060|0)<<4|OA>>>28)+JA|0)^JA^ne)+SA[4]+1272893353|0)<<11|se>>>21)+OA|0)^OA^JA)+SA[7]-155497632|0)<<16|ne>>>16)+se|0)^se^OA)+SA[10]-1094730640|0)<<23|JA>>>9)+ne|0,JA=((JA+=((ne=((ne+=((se=((se+=((OA=((OA+=(JA^ne^se)+SA[13]+681279174|0)<<4|OA>>>28)+JA|0)^JA^ne)+SA[0]-358537222|0)<<11|se>>>21)+OA|0)^OA^JA)+SA[3]-722521979|0)<<16|ne>>>16)+se|0)^se^OA)+SA[6]+76029189|0)<<23|JA>>>9)+ne|0,JA=((JA+=((ne=((ne+=((se=((se+=((OA=((OA+=(JA^ne^se)+SA[9]-640364487|0)<<4|OA>>>28)+JA|0)^JA^ne)+SA[12]-421815835|0)<<11|se>>>21)+OA|0)^OA^JA)+SA[15]+530742520|0)<<16|ne>>>16)+se|0)^se^OA)+SA[2]-995338651|0)<<23|JA>>>9)+ne|0,JA=((JA+=((se=((se+=(JA^((OA=((OA+=(ne^(JA|~se))+SA[0]-198630844|0)<<6|OA>>>26)+JA|0)|~ne))+SA[7]+1126891415|0)<<10|se>>>22)+OA|0)^((ne=((ne+=(OA^(se|~JA))+SA[14]-1416354905|0)<<15|ne>>>17)+se|0)|~OA))+SA[5]-57434055|0)<<21|JA>>>11)+ne|0,JA=((JA+=((se=((se+=(JA^((OA=((OA+=(ne^(JA|~se))+SA[12]+1700485571|0)<<6|OA>>>26)+JA|0)|~ne))+SA[3]-1894986606|0)<<10|se>>>22)+OA|0)^((ne=((ne+=(OA^(se|~JA))+SA[10]-1051523|0)<<15|ne>>>17)+se|0)|~OA))+SA[1]-2054922799|0)<<21|JA>>>11)+ne|0,JA=((JA+=((se=((se+=(JA^((OA=((OA+=(ne^(JA|~se))+SA[8]+1873313359|0)<<6|OA>>>26)+JA|0)|~ne))+SA[15]-30611744|0)<<10|se>>>22)+OA|0)^((ne=((ne+=(OA^(se|~JA))+SA[6]-1560198380|0)<<15|ne>>>17)+se|0)|~OA))+SA[13]+1309151649|0)<<21|JA>>>11)+ne|0,JA=((JA+=((se=((se+=(JA^((OA=((OA+=(ne^(JA|~se))+SA[4]-145523070|0)<<6|OA>>>26)+JA|0)|~ne))+SA[11]-1120210379|0)<<10|se>>>22)+OA|0)^((ne=((ne+=(OA^(se|~JA))+SA[2]+718787259|0)<<15|ne>>>17)+se|0)|~OA))+SA[9]-343485551|0)<<21|JA>>>11)+ne|0,LA[0]=OA+LA[0]|0,LA[1]=JA+LA[1]|0,LA[2]=ne+LA[2]|0,LA[3]=se+LA[3]|0}function E(LA){var SA,OA=[];for(SA=0;SA<64;SA+=4)OA[SA>>2]=LA.charCodeAt(SA)+(LA.charCodeAt(SA+1)<<8)+(LA.charCodeAt(SA+2)<<16)+(LA.charCodeAt(SA+3)<<24);return OA}function m(LA){var SA,OA=[];for(SA=0;SA<64;SA+=4)OA[SA>>2]=LA[SA]+(LA[SA+1]<<8)+(LA[SA+2]<<16)+(LA[SA+3]<<24);return OA}function D(LA){var SA,OA,JA,ne,se,_i,Ti=LA.length,Lt=[1732584193,-271733879,-1732584194,271733878];for(SA=64;SA<=Ti;SA+=64)u(Lt,E(LA.substring(SA-64,SA)));for(OA=(LA=LA.substring(SA-64)).length,JA=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],SA=0;SA>2]|=LA.charCodeAt(SA)<<(SA%4<<3);if(JA[SA>>2]|=128<<(SA%4<<3),SA>55)for(u(Lt,JA),SA=0;SA<16;SA+=1)JA[SA]=0;return ne=(ne=8*Ti).toString(16).match(/(.*?)(.{0,8})$/),se=parseInt(ne[2],16),_i=parseInt(ne[1],16)||0,JA[14]=se,JA[15]=_i,u(Lt,JA),Lt}function M(LA){var SA,OA,JA,ne,se,_i,Ti=LA.length,Lt=[1732584193,-271733879,-1732584194,271733878];for(SA=64;SA<=Ti;SA+=64)u(Lt,m(LA.subarray(SA-64,SA)));for(OA=(LA=SA-64>2]|=LA[SA]<<(SA%4<<3);if(JA[SA>>2]|=128<<(SA%4<<3),SA>55)for(u(Lt,JA),SA=0;SA<16;SA+=1)JA[SA]=0;return ne=(ne=8*Ti).toString(16).match(/(.*?)(.{0,8})$/),se=parseInt(ne[2],16),_i=parseInt(ne[1],16)||0,JA[14]=se,JA[15]=_i,u(Lt,JA),Lt}function T(LA){var SA,OA="";for(SA=0;SA<4;SA+=1)OA+=g[LA>>8*SA+4&15]+g[LA>>8*SA&15];return OA}function P(LA){var SA;for(SA=0;SA"u"||ArrayBuffer.prototype.slice||function(){function LA(SA,OA){return(SA=0|SA||0)<0?Math.max(SA+OA,0):Math.min(SA,OA)}ArrayBuffer.prototype.slice=function(SA,OA){var JA,ne,se,_i,Ti=this.byteLength,Lt=LA(SA,Ti),Ni=Ti;return OA!==n&&(Ni=LA(OA,Ti)),Lt>Ni?new ArrayBuffer(0):(JA=Ni-Lt,ne=new ArrayBuffer(JA),se=new Uint8Array(ne),_i=new Uint8Array(this,Lt,JA),se.set(_i),ne)}}(),xA.prototype.append=function(LA){return this.appendBinary(W(LA)),this},xA.prototype.appendBinary=function(LA){this._buff+=LA,this._length+=LA.length;var SA,OA=this._buff.length;for(SA=64;SA<=OA;SA+=64)u(this._hash,E(this._buff.substring(SA-64,SA)));return this._buff=this._buff.substring(SA-64),this},xA.prototype.end=function(LA){var SA,OA,JA=this._buff,ne=JA.length,se=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(SA=0;SA>2]|=JA.charCodeAt(SA)<<(SA%4<<3);return this._finish(se,ne),OA=P(this._hash),LA&&(OA=kA(OA)),this.reset(),OA},xA.prototype.reset=function(){return this._buff="",this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},xA.prototype.getState=function(){return{buff:this._buff,length:this._length,hash:this._hash.slice()}},xA.prototype.setState=function(LA){return this._buff=LA.buff,this._length=LA.length,this._hash=LA.hash,this},xA.prototype.destroy=function(){delete this._hash,delete this._buff,delete this._length},xA.prototype._finish=function(LA,SA){var OA,JA,ne,se=SA;if(LA[se>>2]|=128<<(se%4<<3),se>55)for(u(this._hash,LA),se=0;se<16;se+=1)LA[se]=0;OA=(OA=8*this._length).toString(16).match(/(.*?)(.{0,8})$/),JA=parseInt(OA[2],16),ne=parseInt(OA[1],16)||0,LA[14]=JA,LA[15]=ne,u(this._hash,LA)},xA.hash=function(LA,SA){return xA.hashBinary(W(LA),SA)},xA.hashBinary=function(LA,SA){var OA=P(D(LA));return SA?kA(OA):OA},xA.ArrayBuffer=function(){this.reset()},xA.ArrayBuffer.prototype.append=function(LA){var SA,OA=RA(this._buff.buffer,LA),JA=OA.length;for(this._length+=LA.byteLength,SA=64;SA<=JA;SA+=64)u(this._hash,m(OA.subarray(SA-64,SA)));return this._buff=SA-64>2]|=JA[SA]<<(SA%4<<3);return this._finish(se,ne),OA=P(this._hash),LA&&(OA=kA(OA)),this.reset(),OA},xA.ArrayBuffer.prototype.reset=function(){return this._buff=new Uint8Array(0),this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},xA.ArrayBuffer.prototype.getState=function(){var LA=xA.prototype.getState.call(this);return LA.buff=EA(LA.buff),LA},xA.ArrayBuffer.prototype.setState=function(LA){return LA.buff=iA(LA.buff,!0),xA.prototype.setState.call(this,LA)},xA.ArrayBuffer.prototype.destroy=xA.prototype.destroy,xA.ArrayBuffer.prototype._finish=xA.prototype._finish,xA.ArrayBuffer.hash=function(LA,SA){var OA=P(M(new Uint8Array(LA)));return SA?kA(OA):OA},xA}()}(Yu)),Yu.exports),mC=rI(Vu),q=new class{constructor(){this.uploadFileTryCount=0,this.maxRetries=1,this.systemClockOffset=0,this.httpRequest=null,this.uploadFileType="",this.duration=900,this.fetchCosTryCount=0}init(s){var n;this._core=s;const{IN_MINI_APP:g}=s.utils;this.httpRequest=g?fI:Pu,(n=this.httpRequest)===null||n===void 0||n.init(s)}uploadToCOS(s){return pA(this,void 0,void 0,function*(){const n=`${Ca} uploadToCOS`,{ssoLog:g,utils:{safeStringify:u}}=this._core,{file:E}=s;this.uploadFileType=s.uploadFileType,g.debug("uploadToCOS",`${n} options:${u(s)}`);try{const m=Date.now(),D=yield this._createCosOptions(s),M=D.fileExistsInCOS?{data:{location:D.downloadUrl}}:yield this._uploadFile(D);this._handleUploadError(M,s);const T=this._createUploadResult(E,M),P=Date.now()-m,W=function(EA){return EA<1024?`${EA}B`:EA<1048576?`${Math.floor(EA/1024)}KB`:`${Math.floor(EA/1048576)}MB`}(E.size),iA=`size:${W} time:${P}ms speed:${Rr(1e3*E.size/P)}`;return g.debug("uploadToCOS",`${n} ok. name:${E.name} ${iA}`),{uploadOptions:D,response:T}}catch(m){throw g.warn("uploadToCOS",`${n} failed, error:${u(m)}`),m}})}_handleUploadError(s,n){var g,u;const{ChatError:E}=(g=this._core)===null||g===void 0?void 0:g.helper;if(s.statusCode===403)throw n.url,!((u=s?.data)===null||u===void 0)&&u.uploadIP&&s.data.uploadIP,new E({message:"Upload failed with status 403"})}_createUploadResult(s,n){return{fileName:s.name,fileSize:s.size,fileType:s.type.slice(s.type.indexOf("/")+1).toLowerCase(),location:n.data.location||"",uploadTime:Lr(Date.now(),!1),uploadSpeed:Rr(1e3*s.size/Lr(Date.now(),!1))}}_createCosOptions(s){return pA(this,void 0,void 0,function*(){const{fileName:n,resources:g,uploadMethod:u}=yield this._prepareUploadParams(s),E=this._isC2CConversation(s.message.conversationID)?1:2;try{const m=yield this._fetchCosSignatureUrl({fileType:this.uploadFileType,fileName:n,uploadMethod:u,duration:this.duration,userID:s.message.from,conversationType:E}),{uploadUrl:D,downloadUrl:M,requestSnapshotUrl:T,thumbUrl:P,largeUrl:W,fileKey:iA,existFlag:EA}=m,RA=!Ft.isPrivateNetWork()&&m.uploadIP;return{url:this._getRawOrUploadProxyUrl(D),fileType:this.uploadFileType,fileName:n,resources:g,downloadUrl:M,requestSnapshotUrl:T,thumbUrl:P,largeUrl:W,fileKey:iA,uploadIP:RA||"",fileExistsInCOS:EA===1,onProgress:kA=>this._handleUploadProgress(kA,s)}}catch(m){throw console.error("Failed to create COS pre-signed URL options:",m),m}})}_prepareUploadParams(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g,isEmpty:u}}=this._core;n.debug("_prepareUploadParams",` prepareUploadParams:${g(s)}`);const{file:E}=s,{IN_MINI_APP:m,IN_RN_APP:D}=Ft.getPlatformFlags(),M=m||D,T=M&&s.message.type!==Ya,{name:P}=E,W=P.slice(P.lastIndexOf(".")),iA=`${kr(999999)}${W}`,EA=T?E.name:iA,RA=yield this._generateHashFileName(E);return{fileName:u(RA)?Ig(EA):`${RA}${W}`,resources:M?E.url:E,uploadMethod:M?1:0}})}_generateHashFileName(s){return pA(this,void 0,void 0,function*(){const{utils:{IN_MINI_APP:n,IN_BROWSER:g,IN_UNI_NATIVE_APP:u,isArray:E},ssoLog:m}=this._core,D=Date.now();let M="";return g&&(M=yield this._generateHashFileNameInWeb(s)),n&&(E(s.tempFiles)&&(s=s.tempFiles[0]),u||(M=yield this._generateFileNameInMiniProgram(s)),u&&(M=yield this._generateFileNameInUNINativeApp(s))),m.info("_generateHashFileName",`hashFileName:${M} costTime:${Date.now()-D}`),M})}_generateHashFileNameInWeb(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g}}=this._core;let u="";try{u=yield new Promise((E,m)=>{const D=File.prototype.slice||File.prototype.mozSlice||File.prototype.webkitSlice;D||(n.warn("_generateHashFileNameInWeb","Browser does not support file slicing"),E(""));const M=10485760,T=Math.ceil(s.size/M);let P=0;const W=new mC.ArrayBuffer,iA=new FileReader,EA=setTimeout(()=>{iA.abort(),n.warn("_generateHashFileNameInWeb","File hash generation timeout"),E("")},2e3);function RA(){const kA=P*M,xA=kA+M>=s.size?s.size:kA+M;iA.readAsArrayBuffer(D.call(s,kA,xA))}iA.onload=kA=>{n.debug("_generateHashFileNameInWeb",`read chunk nr ${P+1} of ${T}`),W.append(kA.target.result),P++,P{clearTimeout(EA),m(kA)},RA()})}catch(E){n.warn("_generateHashFileNameInWeb",g(E))}return u})}_generateFileNameInMiniProgram(s){return pA(this,void 0,void 0,function*(){const{utils:{MINI_APP_NAMESPACE:n,safeStringify:g,isEmpty:u},ssoLog:E}=this._core;let m="";if(u(s.url))return E.warn("_generateFileNameInMiniProgram","file.url is empty"),m;if(typeof n?.getFileSystemManager!="function")return E.warn("_generateFileNameInUNINativeApp","getFileSystemManager is not a function"),m;try{m=yield new Promise((D,M)=>{n.getFileSystemManager().getFileInfo({filePath:s.url,success:T=>{D(T.digest)},fail:T=>{M(T)}})})}catch(D){E.warn("_generateFileNameInMiniProgram",g(D))}return m})}_generateFileNameInUNINativeApp(s){return pA(this,void 0,void 0,function*(){var n;const{utils:{safeStringify:g,isEmpty:u},ssoLog:E}=this._core;let m="";if(u(s.url))return E.warn("_generateFileNameInUNINativeApp","file.url is empty"),m;if(typeof((n=plus==null?void 0:plus.io)===null||n===void 0?void 0:n.getFileInfo)!="function")return E.warn("_generateFileNameInUNINativeApp","plus.io.getFileInfo is not a function"),m;try{m=yield new Promise((D,M)=>{plus.io.getFileInfo({filePath:s.url,success:T=>{D(T.digest)},fail:T=>{M(T)}})})}catch(D){E.warn("_generateFileNameInMiniProgram",g(D))}return m})}_handleUploadProgress(s,n){if(typeof n.onProgress=="function")try{n.onProgress(s.percent)}catch(g){throw console.warn("Upload progress callback error:",g),g}}_fetchCosSignatureUrl(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g}}=this._core,u=Ft.isSimpleCos(),E=this._prepareCosRequestData(s),m=u?"im_cos_msg.simple_sig":"im_cos_msg.pre_sig";try{const D=yield function(T,P,W){return pA(this,void 0,void 0,function*(){try{const{helper:iA,channel:EA}=W,RA=iA.generateCosSpecifiedData({servcmd:T,data:P}),kA=`${RA.head.seq}${T}`;return yield EA.sendPacket(RA,{requestId:kA})}catch(iA){throw console.warn("getCosSig error:",iA),iA}})}(m,E,this._core);this.fetchCosTryCount=0;const M=this._processResponse(D);return n.debug("_fetchCosSignatureUrl",` ok. isSimpleCos:${u} data:${g(M)}`),M||{}}catch(D){if(this.fetchCosTryCount<1)return this.fetchCosTryCount++,this._fetchCosSignatureUrl(s);throw this.fetchCosTryCount=0,D}})}_processResponse(s){var n;const g=Ft.isSimpleCos(),u=g?(n=s?.rpt_pre_sig)===null||n===void 0?void 0:n[0]:s;if(!u)return{};if(g){const{str_final_ip:W,rpt_pre_sig:iA,uint32_file_id:EA,uint32_exist_flag:RA,str_download_url:kA,str_upload_url:xA,str_snapshot_url:LA,str_file_key:SA}=u;return{uploadIP:W,preSig:iA,fileID:EA,existFlag:RA,downloadUrl:kA,uploadUrl:xA,requestSnapshotUrl:LA,fileKey:SA}}const{upload_url:E,download_url:m,snapshot_url:D,thumb_url:M,large_url:T,file_key:P}=u;return{uploadUrl:E,downloadUrl:m,requestSnapshotUrl:D,thumbUrl:M,largeUrl:T,fileKey:P}}_prepareCosRequestData(s){return Ft.isSimpleCos()?{uint32_upload_method:s.uploadMethod,uint32_platform:Ft.getPlatform(),uint32_sdkappid:Ft.getSDKAppID(),str_user_id:s.userID,uint32_scene:s.conversationType,rpt_upload_object:[{uint32_file_id:1,uint32_file_type:s.fileType,str_file_name:s.fileName}]}:{file_type:s.fileType,file_name:s.fileName,upload_method:s.uploadMethod,Duration:s.duration}}_uploadFile(s){return pA(this,void 0,void 0,function*(){return new Promise((n,g)=>{this.httpRequest.request(s,(u,E)=>{u&&this.uploadFileTryCount=3e4}_syncSystemClock(s){var n,g,u;const E=((n=s.headers)===null||n===void 0?void 0:n.date)||((g=s.headers)===null||g===void 0?void 0:g.Date)||((u=s.error)===null||u===void 0?void 0:u.ServerTime);if(E){const m=Date.now(),D=Date.parse(E);this.systemClockOffset=D-m}}_getRawOrUploadProxyUrl(s){const n=Ft.getFileUploadProxy();let g=s;return n&&(g=s.replace(/^https:\/\/[^/]+/,n)),g}_isC2CConversation(s){return s.slice(0,3)==="C2C"}};const L=2108,oA=2251,G=2252,x=2253,tA=["jpg","jpeg","gif","png","bmp","image","webp"],uA={JPG:1,JPEG:1,GIF:2,PNG:3,BMP:4,UNKNOWN:255},wA=1,XA=2;class Qe{constructor(n,g){this.instanceID=kr(9999999),this.sizeType=n.type||0,this.type=0,this.size=n.size||0,this.width=n.width||0,this.height=n.height||0,this.imageUrl=Ft.addAuthToUrl(n.imageUrl||n.url||""),this.url=Ft.addAuthToUrl(n.url||g)}setSizeType(n){this.sizeType=n}setType(n){this.type=n}setImageUrl(n){n&&(this.imageUrl=Ft.addAuthToUrl(n))}getImageUrl(){return this.imageUrl}}function p(s){const{originUrl:n,originWidth:g,originHeight:u,min:E=198}=s,m=parseInt(g)||0,D=parseInt(u)||0,M={url:void 0,width:0,height:0};if((m<=D?m:D)<=E)M.url=n,M.width=m,M.height=D;else{D<=m?(M.width=Math.ceil(m*E/D),M.height=E):(M.width=E,M.height=Math.ceil(D*E/m));const T=n&&n.indexOf("?")>-1?`${n}&`:`${n}?`;M.url=E===198?`${T}imageView2/3/w/198/h/198`:`${T}imageView2/3/w/720/h/720`}if(n===void 0){const{url:T}=M;return Do(M,["url"])}return M}class B{constructor(n){this._imageMemoryURL="",this._percent=0,this.type=ic;const{uuid:g,file:u,imageFormat:E,imageInfoArray:m=[],isCustomUpload:D=!1}=n;this._imageMemoryURL=this.createImageDataAsURL(u),this.content={imageFormat:E,uuid:g,imageInfoArray:[]},this[Jr]=D,this.initImageInfoArray(m),this.autoFixUrl()}static parseServerPushElement(n){const{MsgContent:g}=n,{ImageFormat:u,ImageInfoArray:E,UUID:m}=g,D=function(M){return M.map(T=>({size:T.Size,type:T.Type,width:T.Width,height:T.Height,url:T.URL}))}(E);return new B({imageFormat:u,imageInfoArray:D,uuid:m})}createImageDataAsURL(n){let g="";const{IN_MINI_APP:u,IN_RN_APP:E,IN_BROWSER:m}=Ft.getPlatformFlags();return n&&((u||E)&&(g=n.url),m&&(g=window.URL.createObjectURL(n))),g}initImageInfoArray(n=[]){const g={type:0,size:0,width:0,height:0,url:""};for(let u=0;u<3;u++){const E=n[u]||Object.assign({},g),m=new Qe(E,this._imageMemoryURL);m.setSizeType(u+1),m.setType(u),this.addImageInfo(m)}this.updateAccessSideImageInfoArray()}autoFixUrl(){const n=["http","https"];this.content.imageInfoArray.forEach(g=>{if(!g.url||g.imageUrl==="")return;const[u,...E]=g.imageUrl.split("://"),m=E.join("://");n.includes(u)||g.setImageUrl(`https://${m}`)})}updatePercent(n){this._percent=Math.min(n,1)}updateImageFormat(n){this.content.imageFormat=uA[n.toUpperCase()]||uA.UNKNOWN}addImageInfo(n){this.content.imageInfoArray.length>=3||this.content.imageInfoArray.push(n)}updateImageInfoArray(n){const g=this.content.imageInfoArray.length;let u;for(let E=0;E({InstanceId:g.instanceID,Type:g.sizeType,MsgType:g.type,Size:g.size,Width:g.width,Height:g.height,URL:Ft.removeAuthToUrl(g.imageUrl)}))}}const v=new class{init(s){this.core=s}},N={[eu]:"i",[gl]:"a",[ha]:"v",[UE]:"f"};let O=null,z=null;function X(s){var n;const{store:g,utils:{isNumber:u,safeStringify:E},ssoLog:m}=v.core;try{const D=((n=g.get("cloudConfig"))===null||n===void 0?void 0:n.upload_size_limit)||"";D!==z&&(z=D,O=JSON.parse(D)||{});const M=O?.[N[s]];if(u(M))return 1024*M*1024}catch(D){m.debug("getCloudControlUploadSizeLimit",E(D))}return null}var nA=new class{constructor(){this._messageOptionsMap=new Map}init(s){var n;this._core=s;const{notificationCenter:g,helper:u,InnerEvent:E,message:m}=s;u.registerApi({apiName:"createImageMessage",context:this}),u.registerExperimentalAPI("createImageMessage",this,"createCustomUploadImageMessage"),(n=m?.messageFactory)===null||n===void 0||n.registerElementClass(ic,B),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createImageMessage(s){var n,g,u;try{const E=(n=this._core.store.get("login"))===null||n===void 0?void 0:n.userId,m=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:E})),D=this._processImage(s);s.payload.file=D;const M={imageFormat:uA.UNKNOWN,uuid:Ft.generateUUID(D),file:D,imageInfoArray:[]},T=new B(M);return m.setElement(T),this._messageOptionsMap.set(m.clientSequence,s),m}catch(E){throw E}}createCustomUploadImageMessage(s){var n,g,u,E;const{store:m,utils:{isEmpty:D}}=this._core,M=(n=m.get("login"))===null||n===void 0?void 0:n.userId,T=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:M})),{largeImageUuid:P,largeFileSize:W,largeImageWidth:iA,largeImageHeight:EA,largeImageUrl:RA,originImageUuid:kA,originFileSize:xA,originImageWidth:LA,originImageHeight:SA,originImageUrl:OA,thumbImageUuid:JA,thumbFileSize:ne,thumbImageWidth:se,thumbImageHeight:_i,thumbImageUrl:Ti}=((E=s?.payload)===null||E===void 0?void 0:E.file)||{};if(D(OA)||D(kA))throw new Error("createImageMessageExperimental originImageUrl or originImageUuid is empty");const Lt=new B({imageFormat:uA.UNKNOWN,uuid:kA,imageInfoArray:[{instanceID:kA,size:xA,width:LA,height:SA,imageUrl:OA,url:OA},{instanceID:P,size:W,width:iA,height:EA,imageUrl:RA,url:RA},{instanceID:JA,size:ne,width:se,height:_i,imageUrl:Ti,url:Ti}],isCustomUpload:!0});return T.setElement(Lt),this._messageOptionsMap.set(T.clientSequence,s),T._skipUpload=!0,T}upload(s){return pA(this,void 0,void 0,function*(){const n=s.getElements()[0],{file:g}=this._messageOptionsMap.get(s.clientSequence).payload;this._validateBeforeUploadImage(g);const u=yield this._performImageUpload(n,s,g),E=this._generateImageInfo(u);return n.updateImageFormat(u?.fileType),n.updateImageInfoArray(E),this._updateImageType(n.content.imageInfoArray),s})}_performImageUpload(s,n,g){return pA(this,void 0,void 0,function*(){const{to:u}=n,E={uploadFileType:eu,file:g,to:u,message:n,onProgress:M=>{var T,P;s.updatePercent(M),(P=(T=this._messageOptionsMap.get(n.clientSequence))===null||T===void 0?void 0:T.onProgress)===null||P===void 0||P.call(T,M)}},{uploadOptions:m,response:D}=yield q.uploadToCOS(E);return this._parseResponse(m,D)})}_generateImageInfo(s){const{location:n,fileSize:g,width:u,height:E,smallImageUrl:m,smallImageWidth:D,smallImageHeight:M,largeImageUrl:T,largeImageWidth:P,largeImageHeight:W,imageInfoArray:iA}=s,EA=Ft.addAuthToUrl(n),RA={size:g,url:EA,width:u,height:E};return iA?.length>0?this._processImageInfoArray(iA,g):m&&T?[Object.assign({},RA),{largeImageUrl:T,largeImageWidth:P,largeImageHeight:W},{smallImageUrl:m,smallImageWidth:D,smallImageHeight:M}]:[Object.assign({},RA),this._generateThumbInfo(EA,u,E,720),this._generateThumbInfo(EA,u,E,198)]}_generateThumbInfo(s,n,g,u){return p({originUrl:s,originWidth:n,originHeight:g,min:u})}_processImageInfoArray(s,n){let g,u,E;for(const m of s)m.type===1?(u=m,u.size=n):m.type===2?(E=m,E.size=n):(g=m,g.size=n);return[Object.assign({},g),Object.assign({},E),Object.assign({},u)]}_parseResponse(s,n){return pA(this,void 0,void 0,function*(){try{const{thumbUrl:g,largeUrl:u,downloadUrl:E}=s;if(g&&u&&(yield this._getImageInfoByUrl(g,n,"thumb"),yield this._getImageInfoByUrl(u,n,"large")),Ft.isSimpleCos()&&!Ft.isPrivateNetWork()&&(yield this._getImageInfoArray(E,n),n?.uploadIP)){const m=this._extractDomainFromUrl(E);m&&(yield this._getDownloadIP(m,n))}return n}catch(g){throw g}})}_extractDomainFromUrl(s){var n;try{const g=s.match(/:\/\/([^\/]+)/);return g?g[1]:null}catch(g){return(n=this._core)===null||n===void 0||n.ssoLog.warn("_extractDomainFromUrl",`Failed to extract domain from URL:${g.message}`),null}}_getImageInfoByUrl(s,n,g){return pA(this,void 0,void 0,function*(){var u;try{const E=Ft.addAuthToUrl(s),{width:m=0,height:D=0}=yield Ft.probeImageWidthHeight(E);n.width=m,n.height=D,g==="thumb"?(n.smallImageUrl=s,n.smallImageWidth=m,n.smallImageHeight=D):(n.largeImageUrl=s,n.largeImageWidth=m,n.largeImageHeight=D)}catch(E){(u=this._core)===null||u===void 0||u.ssoLog.warn("_getImageInfoByUrl",`Failed to get ${g} image info:${E.message}`)}})}_validateBeforeUploadImage(s){var n;const{ChatError:g}=(n=this._core)===null||n===void 0?void 0:n.helper;if(!s)throw new g({code:oA});this._checkImageType(s),this._checkImageSize(s)}_processImage(s){var n;try{const{IN_MINI_APP:g}=(n=this._core)===null||n===void 0?void 0:n.utils;let{file:u}=s.payload;return u=g?this._processMiniAppImageFile(u):this._processWebImageFile(u),u}catch(g){throw g}}_processMiniAppImageFile(s){al(s)&&console.warn("FileUnsupportedInMiniApp","createImageMessage");const n=s.tempFiles[0].path||s.tempFiles[0].tempFilePath;return{url:n,name:n.slice(n.lastIndexOf("/")+1),size:s.tempFiles&&s.tempFiles[0].size||1,type:n.slice(n.lastIndexOf(".")+1).toLowerCase()}}_processWebImageFile(s){var n;const{ChatError:g}=(n=this._core)===null||n===void 0?void 0:n.helper,u=Ft.extractFileFromInput(s);if(!u)throw new g({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return u}_getDownloadIP(s,n){return pA(this,void 0,void 0,function*(){const g=`${Ca} getDownloadIP domainName: ${s}`;try{const u=yield function(m,D){return pA(this,void 0,void 0,function*(){try{const{helper:M,channel:T}=D,P="im_cos_msg.get_final_ip",W={str_domain:m},iA=M.generateProtocolData({servcmd:P,data:W}),EA=`${iA.head.seq}${P}`;return yield T.sendPacket(iA,{requestId:EA})}catch(M){throw console.warn("getFinalIP error:",M),M}})}(s,this._core);if(!u||!u.str_final_ip)return;console.log(`${g} ok. downloadIP:${u}`);const E=n.location.split("/");E[0]=u.str_final_ip,n.location=E.join("/")}catch(u){console.warn(u)}})}_getImageInfoArray(s,n){return pA(this,void 0,void 0,function*(){try{const g=yield function(u,E){return pA(this,void 0,void 0,function*(){try{const{helper:m,channel:D}=E,M="im_cos_msg.get_imageinfo",T={str_image_url:u},P=m.generateProtocolData({servcmd:M,data:T}),W=`${P.head.seq}${M}`;return yield D.sendPacket(P,{requestId:W})}catch(m){throw console.warn("getImageInfo error:",m),m}})}(s,this._core);return n.imageInfoArray=this._processImageInfoResponse(g),n}catch(g){throw n.imageInfoArray=void 0,g}})}_processImageInfoResponse(s){if(!s)return[];const{rpt_msg_image_info:n}=s;return n.map(g=>({type:g.uint32_image_type,url:g.str_url,width:g.uint32_width,height:g.uint32_height,imageFormat:g.str_image_format}))}_checkImageType(s){const{utils:n,helper:g}=this._core;let u="";if(n.IN_MINI_APP&&(u=s.url.slice(s.url.lastIndexOf(".")+1)),n.IN_BROWSER&&(u=s.name.slice(s.name.lastIndexOf(".")+1)),tA.indexOf(u.toLowerCase())<0)throw new g.ChatError({code:G})}_checkImageSize(s){const{utils:n,helper:g,store:u}=this._core;let E=0;if(E=(n.IN_MINI_APP,s.size),E===0)throw new g.ChatError({code:L});if(E>=(X(eu)||20971520))throw new g.ChatError({code:x})}_updateImageType(s){s[1].type=XA,s[2].type=wA}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this)}};const DA=2108,GA=2401,VA=2402,ee="2.5.0",Ee="1.18.0";function Ke(s,n){const g=s.split("."),u=n.split("."),E=Math.max(g.length,u.length);for(;g.lengthM)return 1;if(D0;return{isValid:n,error:n?null:{message:"content can not be empty"}}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},u=g?this.payload:this.content,{uuid:E,downloadFlag:m,fileUrl:D,fileName:M,fileSize:T}=u;return{MsgType:this.type,MsgContent:{Download_Flag:m,Url:Ft.removeAuthToUrl(D),FileName:M,FileSize:T,UUID:E}}}_getFileInfo(n){const{utils:{IN_UNI_NATIVE_APP:g}}=v.core;if(n.fileName&&n.fileSize)return{size:n.fileSize,name:n.fileName};const{file:u}=n;return u?(g&&this._processNativeAppFile(u),{size:u.size,name:u.name}):{size:0,name:""}}_processNativeAppFile(n){if(n.path&&n.path.includes(".")){const g=n.path.slice(n.path.lastIndexOf(".")+1).toLowerCase();n.type=g,n.name||(n.name=`${kr(999999)}.${g}`)}n.name||(n.type="",n.name=n.path.slice(n.path.lastIndexOf("/")+1).toLowerCase()),n.suffix&&(n.type=n.suffix),n.url||(n.url=n.path)}}ot=Jr;var kt=new class{constructor(){this._messageOptionsMap=new Map}init(s){var n;this._core=s;const{notificationCenter:g,helper:u,InnerEvent:E,message:m}=s;u.registerApi({apiName:"createFileMessage",context:this}),u.registerExperimentalAPI("createFileMessage",this,"createCustomUploadFileMessage"),(n=m?.messageFactory)===null||n===void 0||n.registerElementClass(Ya,at),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createFileMessage(s){var n,g,u;try{this._checkVersion();const E=this._processFile(s.payload.file);s.payload.file=E;const m=(n=this._core.store.get("login"))===null||n===void 0?void 0:n.userId,D=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:m})),M={uuid:Ft.generateUUID(E),file:E},T=new at(M);return D.setElement(T),this._messageOptionsMap.set(D.clientSequence,s),D}catch(E){throw E}}createCustomUploadFileMessage(s){var n,g,u;try{const{store:E,message:m,utils:{isEmpty:D}}=this._core,M=(n=E.get("login"))===null||n===void 0?void 0:n.userId,{url:T,uuid:P,fileSize:W,fileName:iA=""}=((g=s?.payload)===null||g===void 0?void 0:g.file)||{};if(D(T))throw new Error("url is required");const EA=(u=m.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:M})),RA=new at({url:T,uuid:P,file:{size:W,name:iA},isCustomUpload:!0});return EA.setElement(RA),EA}catch(E){throw E}}upload(s){return pA(this,void 0,void 0,function*(){const{file:n}=this._messageOptionsMap.get(s.clientSequence).payload;this._validateBeforeUploadFile(n);const g=s.getElements()[0],u=yield this._performFileUpload(g,s,n),E=Ft.addAuthToUrl(u?.location);return g.updateFileUrl(E),s})}_validateBeforeUploadFile(s){const{helper:{ChatError:n}}=this._core;if(!s)throw new n({code:GA});const g=X(UE)||104857600;if(s.size>g)throw new n({code:VA});if(s.size===0)throw new n({code:DA})}_performFileUpload(s,n,g){return pA(this,void 0,void 0,function*(){const{to:u}=n,E={uploadFileType:UE,file:g,to:u,message:n,onProgress:D=>{var M,T;s.updatePercent(D),(T=(M=this._messageOptionsMap.get(n.clientSequence))===null||M===void 0?void 0:M.onProgress)===null||T===void 0||T.call(M,D)}},{response:m}=yield q.uploadToCOS(E);return m})}_processFile(s){var n,g;const{IN_BROWSER:u,IN_RN_APP:E,IN_WX_MINI_APP:m,IN_QQ_MINI_APP:D,IN_UNI_NATIVE_APP:M}=(n=this._core)===null||n===void 0?void 0:n.utils,{ChatError:T}=(g=this._core)===null||g===void 0?void 0:g.helper;if(u||M){const P=Ft.extractFileFromInput(s);if(!P)throw new T({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return P}if(m||D){const{tempFiles:P}=s;return Object.assign(Object.assign({},P[0]),{url:P[0].path})}return E?Object.assign(Object.assign({},s),{url:s.uri}):s}_checkVersion(){var s,n;const{MINI_APP_NAMESPACE:g,IN_MINI_APP:u,IN_WX_MINI_APP:E,IN_QQ_MINI_APP:m,IN_UNI_NATIVE_APP:D}=(s=this._core)===null||s===void 0?void 0:s.utils,{ChatError:M}=(n=this._core)===null||n===void 0?void 0:n.helper;if(u){if(!(E||m||D))throw new M({message:"Unsupported mini app environment"});const T=g.getSystemInfoSync().SDKVersion;if(E&&Ke(T,ee)<0)throw new M({message:`WXChooseMessageFile requires SDK version ${ee} or higher`});if(m&&Ke(T,Ee)<0)throw new M({message:`QQChooseMessageFile requires SDK version ${Ee} or higher`})}}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this)}};const Yt=2108,Ui=2351,ao=2352,zi=["mp4","quicktime","mov","video"];var ui;class Po{constructor(n){this.type=Ul,this.uploadProgress=0,this[ui]=!1;const g=typeof n?.videoSecond=="number"?n?.videoSecond:0;this[Jr]=n.isCustomUpload||!1,this.content={remoteVideoUrl:Ft.addAuthToUrl(n.remoteVideoUrl||n.videoUrl||""),videoFormat:n.videoFormat,videoSecond:parseInt(g?.toString(),10),videoSize:n.videoSize,videoUrl:Ft.addAuthToUrl(n.videoUrl),videoDownloadFlag:2,videoUUID:n.videoUUID,thumbUUID:n.thumbUUID,thumbFormat:n.thumbFormat,thumbWidth:n.thumbWidth,snapshotWidth:n.thumbWidth,thumbHeight:n.thumbHeight,snapshotHeight:n.thumbHeight,thumbSize:n.thumbSize,snapshotSize:n.thumbSize,thumbDownloadFlag:2,thumbUrl:Ft.addAuthToUrl(n.thumbUrl),snapshotUrl:Ft.addAuthToUrl(n.thumbUrl)}}static parseServerPushElement(n){const{MsgContent:g}=n,{VideoUrl:u,VideoFormat:E,VideoSecond:m,VideoSize:D,VideoDownloadFlag:M,VideoUUID:T,ThumbUUID:P,ThumbFormat:W,ThumbWidth:iA,SnapshotWidth:EA,ThumbHeight:RA,SnapshotHeight:kA,ThumbSize:xA,SnapshotSize:LA,ThumbDownloadFlag:SA,ThumbUrl:OA,SnapshotUrl:JA}=g;return new Po({videoUrl:u,videoFormat:E,videoSecond:m,videoSize:D,videoDownloadFlag:M,videoUUID:T,thumbUUID:P,thumbFormat:W,thumbWidth:iA,snapshotWidth:EA,thumbHeight:RA,snapshotHeight:kA,thumbSize:xA,snapshotSize:LA,thumbDownloadFlag:SA,thumbUrl:OA,snapshotUrl:JA})}updatePercent(n){this.uploadProgress=Math.min(n,1)}updateVideoUrl(n){n&&(this.content.remoteVideoUrl=n)}updateSnapshotInfo(n){const{snapshotUrl:g,snapshotWidth:u,snapshotHeight:E}=n;Ft.isEmpty(g)||(this.content.thumbUrl=this.content.snapshotUrl=g),Ft.isEmpty(u)||(this.content.thumbWidth=this.content.snapshotWidth=Number(u)),Ft.isEmpty(E)||(this.content.thumbHeight=this.content.snapshotHeight=Number(E))}validateBeforeSend(){if(this[Jr])return{isValid:!0};const n=this.content.remoteVideoUrl!=="";return{isValid:n,error:n?null:{message:"content can not be empty"}}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},u=g?this.payload:this.content,{remoteVideoUrl:E,videoFormat:m,videoSecond:D,videoSize:M,videoDownloadFlag:T,videoUUID:P,thumbUUID:W,thumbFormat:iA,thumbWidth:EA,snapshotWidth:RA,thumbHeight:kA,snapshotHeight:xA,thumbSize:LA,snapshotSize:SA,thumbDownloadFlag:OA,thumbUrl:JA,snapshotUrl:ne}=u;return{MsgType:this.type,MsgContent:{VideoUrl:Ft.removeAuthToUrl(E),VideoFormat:m,VideoSecond:D,VideoSize:M,VideoDownloadFlag:T,VideoUUID:P,ThumbUUID:W,ThumbFormat:iA,ThumbWidth:EA,SnapshotWidth:RA,ThumbHeight:kA,SnapshotHeight:xA,ThumbSize:LA,SnapshotSize:SA,ThumbDownloadFlag:OA,ThumbUrl:Ft.removeAuthToUrl(JA),SnapshotUrl:Ft.removeAuthToUrl(ne)}}}}ui=Jr;var As,pi=new class{constructor(){this._messageOptionsMap=new Map}init(s){var n;this._core=s;const{notificationCenter:g,helper:u,InnerEvent:E,message:m}=s;u.registerApi({apiName:"createVideoMessage",context:this}),u.registerExperimentalAPI("createVideoMessage",this,"createCustomUploadVideoMessage"),(n=m?.messageFactory)===null||n===void 0||n.registerElementClass(Ul,Po),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createVideoMessage(s){var n,g,u;try{const E=this._processVideo(s);s.payload.file=E;const m=(n=this._core.store.get("login"))===null||n===void 0?void 0:n.userId,D=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:m})),M={videoFormat:E.videoFile.type,videoSecond:ar(E.videoFile.second,0),videoSize:E.videoFile.size,remoteVideoUrl:"",videoUrl:E.videoFile.url,videoUUID:Ft.generateUUID(E.videoFile),thumbUUID:Ft.generateUUID(E.videoFile,"jpg"),thumbWidth:E.width||200,thumbHeight:E.height||200,thumbUrl:E.thumbUrl,thumbSize:E.thumbSize,thumbFormat:"jpg"},T=new Po(M);return D.setElement(T),this._messageOptionsMap.set(D.clientSequence,s),D}catch(E){throw E}}createCustomUploadVideoMessage(s){var n,g,u;try{const{store:E,message:m}=this._core;this._validateCustomUploadVideoMessage(s);const D=(n=E.get("login"))===null||n===void 0?void 0:n.userId,{videoUrl:M,videoUuid:T,duration:P,snapshotUrl:W,snapshotUuid:iA,videoFileSize:EA,videoType:RA,snapshotWidth:kA,snapshotHeight:xA,snapshotFileSize:LA,snapshotType:SA="jpg"}=((g=s?.payload)===null||g===void 0?void 0:g.file)||{},OA=(u=m.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:D})),JA=new Po({videoFormat:RA,videoSecond:P||0,videoSize:EA,remoteVideoUrl:M,videoUrl:M,videoUUID:T,thumbUUID:iA,thumbWidth:kA||200,thumbHeight:xA||200,thumbUrl:W,thumbSize:LA,thumbFormat:SA,isCustomUpload:!0});return OA.setElement(JA),this._messageOptionsMap.set(OA.clientSequence,s),OA}catch(E){throw E}}upload(s){return pA(this,void 0,void 0,function*(){const n=s.getElements()[0],{file:g}=this._messageOptionsMap.get(s.clientSequence).payload;this._validateBeforeUploadVideo(g);const u=yield this._performVideoUpload(n,s,g),{location:E,snapshotInfo:m}=u,D=Ft.addAuthToUrl(E);return n.updateVideoUrl(D),Ft.isEmpty(m)||n.updateSnapshotInfo(m),s})}_validateBeforeUploadVideo(s){const{helper:{ChatError:n}}=this._core,g=X(ha)||104857600;if(s.videoFile.size>g)throw new n({code:Ui});if(s.videoFile.size===0)throw new n({code:Yt});if(zi.indexOf(s.videoFile.type)===-1)throw new n({code:ao})}_validateCustomUploadVideoMessage(s){var n;const{utils:{isEmpty:g,isNumber:u}}=this._core,{videoUrl:E,videoUuid:m,duration:D,snapshotUrl:M,snapshotUuid:T}=((n=s?.payload)===null||n===void 0?void 0:n.file)||{};if(g(E)||g(m)||!u(D)||g(M)||g(T))throw new Error("Invalid video message options: missing required fields (videoUrl, videoUuid, duration, snapshotUrl, snapshotUuid)")}_performVideoUpload(s,n,g){return pA(this,void 0,void 0,function*(){const{to:u}=n,E={uploadFileType:ha,file:g,to:u,message:n,onProgress:M=>{var T,P;s.updatePercent(M),(P=(T=this._messageOptionsMap.get(n.clientSequence))===null||T===void 0?void 0:T.onProgress)===null||P===void 0||P.call(T,M)}},{response:m,uploadOptions:D}=yield q.uploadToCOS(E);return{snapshotInfo:yield this._getSnapshotInfoByUrl(D.requestSnapshotUrl),location:m.location}})}_processVideo(s){var n,g;try{const{ChatError:u}=(n=this._core)===null||n===void 0?void 0:n.helper,{IN_MINI_APP:E,IN_BROWSER:m}=(g=this._core)===null||g===void 0?void 0:g.utils;let{file:D}=s.payload,M={};if(E&&(M=this._processMiniVideoFile(D),D.name=M.name,D.url=M.url,D.type=M.type),m){const T=Ft.extractFileFromInput(D);if(!T)throw new u({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});D=T,M=this._processWebVideoFile(D)}return D.videoFile=M,D.thumbUrl="",D.thumbSize=0,D}catch(u){throw console.warn(`${Ca} _processFile error:`,u),u}}_processMiniVideoFile(s){const{utils:{IN_UNI_NATIVE_APP:n},helper:{ChatError:g}}=this._core;if(al(s))throw new g({message:"FileUnsupportedInMiniApp"});Array.isArray(s.tempFiles)&&(s=s.tempFiles[0]);let u=s.tempFilePath.slice(s.tempFilePath.lastIndexOf(".")+1).toLowerCase();return n&&(u=s.fileType||u),{url:s.tempFilePath,name:s.tempFilePath.slice(s.tempFilePath.lastIndexOf("/")+1),size:s.size||1,second:s.duration||0,type:u}}_processWebVideoFile(s){const{name:n,size:g=1,duration:u=0,type:E}=s,m=E.split("/")[1];return{url:window.URL.createObjectURL(s),name:n,size:g,second:u,type:m}}_getSnapshotInfoByUrl(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n}=this._core;try{n.debug("_getSnapshotInfoByUrl",`${Ca} _getSnapshotInfoByUrl url:${s}`);const g={version:1,platform:Ft.getPlatform(),cover_name:Ig(kr(99999)),snapshot_url:s},u=yield function(T,P){return pA(this,void 0,void 0,function*(){try{const W="im_cos_msg.video_cover",{helper:iA,channel:EA}=P,RA=iA.generateCosSpecifiedData({servcmd:W,data:T}),kA=`${RA.head.seq}${W}`;return yield EA.sendPacket(RA,{requestId:kA})}catch(W){throw console.warn("getSnapshotInfo error:",W),W}})}(g,this._core),{download_url:E}=u||{};if(n.debug("_getSnapshotInfoByUrl",`${Ca} _getSnapshotInfoByUrl OK snapshotUrl:${E}`),Ft.isEmpty(E))return{};const m=Ft.addAuthToUrl(E),{width:D=0,height:M=0}=yield Ft.probeImageWidthHeight(m);return{snapshotUrl:m,snapshotWidth:D,snapshotHeight:M}}catch(g){throw g}})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this)}};class Ki{constructor(n){this.uploadProgress=0,this.type=Fg,this[As]=!1,this[Jr]=n.isCustomUpload||!1,this.content={downloadFlag:2,second:n.second,size:n.size,url:Ft.generateURL(n.url,{needAddAuthToUrl:!this[Jr]}),remoteAudioUrl:Ft.addAuthToUrl(n.url||""),uuid:n.uuid}}static parseServerPushElement(n){const{MsgContent:g}=n,{Url:u,Download_Flag:E,Second:m,Size:D,UUID:M}=g;return new Ki({url:u,downloadFlag:E,second:m,size:D,uuid:M})}updatePercent(n){this.uploadProgress=Math.min(n,1)}updateAudioUrl(n){this.content.remoteAudioUrl=n}validateBeforeSend(){if(this[Jr])return{isValid:!0};const n=this.content.remoteAudioUrl!=="";return{isValid:n,error:n?null:{message:"content can not be empty"}}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},u=g?this.payload:this.content,{uuid:E,downloadFlag:m,remoteAudioUrl:D,size:M,second:T}=u;return{MsgType:this.type,MsgContent:{Url:Ft.removeAuthToUrl(D),Download_Flag:m,Second:T,Size:M,UUID:E}}}}As=Jr;const Ws=2108,we=2300,Rt=2301;var FA=new class{constructor(){this._messageOptionsMap=new Map}init(s){var n;this._core=s;const{notificationCenter:g,helper:u,InnerEvent:E,message:m}=s;u.registerApi({apiName:"createAudioMessage",context:this}),u.registerExperimentalAPI("createAudioMessage",this,"createCustomUploadAudioMessage"),(n=m?.messageFactory)===null||n===void 0||n.registerElementClass(Fg,Ki),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createAudioMessage(s){var n,g,u;try{let{file:E}=s.payload;E=this._processAudioFile(s.payload.file),s.payload.file=E;const m=(n=this._core.store.get("login"))===null||n===void 0?void 0:n.userId,D=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:m})),M={second:Math.max(1,Math.round((E.duration||E.second)/1e3)),size:E.fileSize||E.size||1,url:E.tempFilePath||E.uri||E.url,uuid:Ft.generateUUID(E)},T=new Ki(M);return D.setElement(T),this._messageOptionsMap.set(D.clientSequence,s),D}catch(E){throw E}}createCustomUploadAudioMessage(s){var n,g,u;try{this._validateCustomUploadOptions(s);const{store:E,message:m}=this._core,D=(n=E.get("login"))===null||n===void 0?void 0:n.userId,{url:M,uuid:T,duration:P,fileSize:W}=((g=s?.payload)===null||g===void 0?void 0:g.file)||{},iA=(u=m.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:D})),EA=new Ki({second:P,size:W||1,url:M,uuid:T,isCustomUpload:!0});return iA.setElement(EA),this._messageOptionsMap.set(iA.clientSequence,s),iA}catch(E){throw E}}upload(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g}}=this._core;n.debug("upload",`${Ca} uploadAudio message:${g(s)}`);const{file:u}=this._messageOptionsMap.get(s.clientSequence).payload;this._validateBeforeUploadAudio(u);const E=s.getElements()[0],m=yield this._performAudioUpload(E,s,u),D=Ft.addAuthToUrl(m?.location);return E.updateAudioUrl(D),s})}_validateBeforeUploadAudio(s){const{helper:{ChatError:n},store:g}=this._core;if(!s)throw new n({code:we});const u=X(gl)||20971520;if(s.size>u)throw new n({code:Rt});if(s.size===0)throw new n({code:Ws})}_performAudioUpload(s,n,g){return pA(this,void 0,void 0,function*(){const{to:u}=n,E={uploadFileType:gl,file:g,to:u,message:n,onProgress:D=>{var M,T;s.updatePercent(D),(T=(M=this._messageOptionsMap.get(n.clientSequence))===null||M===void 0?void 0:M.onProgress)===null||T===void 0||T.call(M,D)}},{response:m}=yield q.uploadToCOS(E);return m})}_processAudioFile(s){var n;const{IN_MINI_APP:g,IN_BROWSER:u}=(n=this._core)===null||n===void 0?void 0:n.utils;return g?this._processMiniFile(s):u?this._processWebFile(s):void 0}_processMiniFile(s){return{url:s.tempFilePath,name:s.tempFilePath.slice(s.tempFilePath.lastIndexOf("/")+1),size:s.fileSize,second:s.duration,type:s.tempFilePath.slice(s.tempFilePath.lastIndexOf(".")+1).toLowerCase()}}_processWebFile(s){if(s.tempFilePath||s.uri)return s;const n=URL.createObjectURL(s);return s.tempFilePath=n,s}_validateCustomUploadOptions(s){var n;const{utils:{isEmpty:g}}=this._core,{url:u,uuid:E,duration:m}=((n=s?.payload)===null||n===void 0?void 0:n.file)||{};if(g(u)||g(E)||g(m))throw new Error("Invalid audio message options")}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this)}};const Wt={to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1},cloudCustomData:{required:!1,rules:["string"],allowEmpty:!1},priority:{required:!1,rules:["string"],allowEmpty:!1},customModerationConfigurationID:{required:!1,rules:["string"],allowEmpty:!1},onProgress:{required:!1,rules:["function"],allowEmpty:!1}},En={createImageMessage:Wt,createAudioMessage:Wt,createVideoMessage:Wt,createFileMessage:Wt},Zt={createImageMessage:!0,createAudioMessage:!0,createVideoMessage:!0,createFileMessage:!0},us={[ic]:nA,[Ya]:kt,[Ul]:pi,[Fg]:FA};var vi=new class{constructor(){this.name="RichMediaMessage"}install(s){this._core=s;const{constants:{OuterConstant:{MSG_AUDIO:n,MSG_FILE:g,MSG_IMAGE:u,MSG_VIDEO:E}}}=s;v.init(s),nA.init(s),kt.init(s),pi.init(s),FA.init(s),q.init(s),Ft.init(s),s.helper.registerApi({apiName:"sendMessage",context:this,matcher:m=>[n,g,u,E].includes(m[0].type)}),s.helper.registerValidateConfig({auth:Zt,params:En})}sendMessage(s,n){return pA(this,void 0,void 0,function*(){var g,u,E;try{return this._isCustomUpload(s)||(yield this._upload(s)),yield(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageSender)===null||E===void 0?void 0:E.sendMessage(s,n)}catch(m){throw m}})}_upload(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g}}=this._core;if(n.debug("_upload",` uploadFile message:${g(s)}`),s._relayFlag!==!0)try{const u=us[s.type];u&&(yield u.upload(s),n.info("_upload",` type:${s.type}`))}catch(u){throw s.status=tu.FAIL,u instanceof Error&&(u.data={message:s}),this._core.message.messageDataHandler.storeConversationMessage(s),u}})}_isCustomUpload(s){var n,g;return((g=(n=s._elements)===null||n===void 0?void 0:n[0])===null||g===void 0?void 0:g[Jr])===!0}};const ho=new class{init(s){this.core=s}};class Ct{constructor(n){this.conversationID=n.conversationID||"",this.unreadCount=n.unreadCount||0,this.type=n.type||"",this.lastMessage=ho.core.common.buildLastMessage(n.lastMessage),this.peerReadTime=n.peerReadTime||0,this.groupAtInfoList=[],this.remark=n.remark||"",this.isPinned=n.isPinned||!1,this.messageRemindType=n.messageRemindType,this.markList=n.markList||[],this.customData=n.customData||"",this.conversationGroupList=n.conversationGroupList||[],this.draftText=n.draftText||"",this.userProfile=n.userProfile,this.groupProfile=n.groupProfile,this.subType=n.subType||"",this._isInfoCompleted=!1,this._init()}_init(){var n;const{core:{OuterConstant:g,utils:{isUndefined:u}}}=ho;u(this.userProfile)&&this.type===g.CONV_C2C?this.userProfile={userID:this.conversationID.replace(g.CONV_C2C,"")}:this.type===g.CONV_GROUP&&(!this.subType&&(!((n=this.groupProfile)===null||n===void 0)&&n.type)&&(this.subType=this.groupProfile.type),u(this.groupProfile)&&(this.groupProfile={groupID:this.conversationID.replace(g.CONV_GROUP,""),selfInfo:{},lastMessage:{},type:this.subType}))}updateUnreadCount(n){var g;const{core:{OuterConstant:u,utils:{isUndefined:E},store:m}}=ho,{nextUnreadCount:D,isFromGetConversations:M,isUnreadC2CMessage:T}=n;if(E(D))return;if(this.subType===u.GRP_AVCHATROOM)return void(this.unreadCount=0);if(M&&this.type===u.CONV_GROUP)return void(this.unreadCount=D);if(T&&this.type===u.CONV_C2C)return void(this.unreadCount=D);const P=((g=m.get("cloudConfig"))===null||g===void 0?void 0:g.support_unread_count_for_meeting)==="1";this.subType!==u.GRP_MEETING||P?this.unreadCount+=D:this.unreadCount=0}updateLastMessage(n){this.lastMessage=ho.core.common.buildLastMessage(n)}reduceUnreadCount(){return this.unreadCount>=1&&(this.unreadCount-=1,!0)}isLastMessageRevoked(n){const{core:{OuterConstant:g}}=ho,{sequence:u,time:E}=n;return this.type===g.CONV_C2C&&u===this.lastMessage.lastSequence&&E===this.lastMessage.lastTime||this.type===g.CONV_GROUP&&u===this.lastMessage.lastSequence}setLastMessageRevoked(n){this.lastMessage.isRevoked=n}setLastMessageRevoker(n){this.lastMessage.revoker=n}setDraftText(n){this.draftText=n}updateGroupAtInfoList(n){const{core:{common:{updateGroupAtInfo:g}}}=ho;g(n,this.groupAtInfoList)}clearGroupAtInfoList(){this.groupAtInfoList.length=0}getProfileCompleted(){return this._isInfoCompleted}setProfileCompleted(){this._isInfoCompleted=!0}}const Bt=s=>{const{core:{OuterConstant:n,utils:{isString:g}}}=ho;return g(s)&&s.slice(0,3)===n.CONV_C2C},ug=s=>{const{core:{OuterConstant:n,utils:{isString:g}}}=ho;return g(s)&&s.slice(0,5)===n.CONV_GROUP},ks=s=>{const{core:{OuterConstant:n,utils:{isString:g}}}=ho;return g(s)&&s===n.CONV_SYSTEM};function ji(s){const{OuterConstant:n}=ho.core;let g="";return s===0?g=n.MSG_REMIND_ACPT_AND_NOTE:s===1?g=n.MSG_REMIND_DISCARD:s===2?g=n.MSG_REMIND_ACPT_NOT_NOTE:s===3&&(g=n.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),g}function Hr(s){const{OuterConstant:n}=ho.core;let g;return s.startsWith(n.CONV_C2C)&&(g=s.replace(n.CONV_C2C,"")),g==="@TLS#ERROR"||g==="@TLS#NOT_FOUND"}function oc(s,n){const{helper:g}=ho.core,u=new g.ChatError({functionName:s,code:n?.errorCode||n?.code,message:n?.errorInfo||n?.message});throw console.error(`${s} fail:`,u),u}var is,ga;(function(s){s[s.OFF=0]="OFF",s[s.ON=1]="ON"})(is||(is={})),function(s){s[s.ONLY_CONVERSATIONID=1]="ONLY_CONVERSATIONID"}(ga||(ga={}));var Ba;(function(s){s[s.CONV_NOT_FOUND=2500]="CONV_NOT_FOUND",s[s.USER_OR_GRP_NOT_FOUND=2501]="USER_OR_GRP_NOT_FOUND",s[s.CONV_UN_RECORDED_TYPE=2502]="CONV_UN_RECORDED_TYPE"})(Ba||(Ba={}));const ea=0,H=1;var BA=new class{constructor(){this._name="GetC2CMessageRemindType"}init(s){this._core=s}get(s){return pA(this,void 0,void 0,function*(){try{const{common:n}=this._core,g=yield function(E,m){return pA(this,void 0,void 0,function*(){const{toAccount:D,userIDList:M}=E,T={To_Account:D,Peer_Account:M};return m.common.buildAndSendPacket({servcmd:"openim.get_c2c_peer_mute_notifications",data:T})})}({toAccount:n.getCurrentUserID(),userIDList:s},this._core),{MuteNotificationsList:u=[]}=g||{};u.forEach(E=>{const{Peer_Account:m,MuteNotifications:D}=E,M=`${this._core.OuterConstant.CONV_C2C}${m}`,T=ji(D);NA.patchMessageRemindType([M],T)})}catch(n){console.error(`${this._name}.get fail:`,n)}})}},yA=new class{constructor(){this._name="GetGroupMessageRemindType"}init(s){this._core=s}get(s){return pA(this,void 0,void 0,function*(){if(s.length!==0)try{const n=yield function(u,E){return pA(this,void 0,void 0,function*(){const{groupIDList:m,responseFilter:D}=u,M={GroupIdList:m,ResponseFilter:D};return E.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_self_member_info",data:M})})}({groupIDList:s,responseFilter:{MemberInfoFilter:["MsgFlag"]}},this._core),{GroupInfo:g=[]}=n||{};g.forEach(u=>{var E;const{GroupId:m,MemberList:D}=u,M=((E=D[0])===null||E===void 0?void 0:E.MsgFlag)||"",T=`${this._core.OuterConstant.CONV_GROUP}${m}`;NA.patchMessageRemindType([T],M)})}catch(n){console.error(`${this._name}.get fail:`,n)}})}},NA=new class{constructor(){this._name="ConversationDataHandler",this._totalUnreadCount=0,this._groupAtTipsList=[]}init(s){this._core=s;const{helper:n,notificationCenter:g,appStore:{conversationStore:u},constants:{WORKFLOW_NAME:E,WORKFLOW_STEP:m},InnerEvent:{SYNC_CONVERSATION_LIST:D,MESSAGE_PUSH:M,NEW_MESSAGE:T,MESSAGE_DELETED:P,MESSAGE_REVOKED:W,MESSAGE_MODIFIED:iA,CONVERSATION_UPDATED:EA,LOGOUT:RA,DESTROY:kA},InnerEventSubType:{C2C_MESSAGE_PEER_READ:xA}}=s;this._conversationStore=u,n.registerWorkflowStep(E.SYNC_SERVER_INFO_AFTER_LOGIN,m.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),n.registerWorkflowStep(E.SYNC_SERVER_INFO_AFTER_LOGIN,m.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,this._handleGroupListSyncFinished,this),n.registerWorkflowStep(E.RECEIVE_C2C_NEW_MESSAGE,m.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),n.registerWorkflowStep(E.RECEIVE_C2C_NEW_MESSAGE,m.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),n.registerWorkflowStep(E.RECEIVE_GROUP_NEW_MESSAGE,m.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),n.registerWorkflowStep(E.SYNC_SERVER_INFO_AFTER_RE_ONLINE,m.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),n.registerWorkflowStep(E.RECEIVE_GROUP_TIPS_NOTIFICATION,m.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this);const{InnerEventSubType:{GROUP_AT_TIPS:LA}}=g;g.subscribeInnerEvent(D,this._handleConversationSynced,this),g.subscribeInnerEvent(T,this._handleNewMessage,this),g.subscribeInnerEvent(M,LA,this._handleNewGroupAtTips,this),g.subscribeInnerEvent(P,this._handleMessageDeleted,this),g.subscribeInnerEvent(W,this._handleMessageRevoked,this),g.subscribeInnerEvent(iA,this._handleMessageModified,this),g.subscribeInnerEvent(EA,this._handleConversationUpdated,this),g.subscribeInnerEvent(M,xA,this._handleMessageRead,this),g.subscribeInnerEvent(RA,this._reset,this),g.subscribeInnerEvent(kA,this._dispose,this),s.ssoLog.debug(`${this._name}.init`)}_handleConversationSynced(s){this.updateLocalConversationList({conversationUpdateFieldList:s.conversationUpdateFieldList||[],isFromGetConversations:!0,updateUnreadCount:!0}),this.emitConversationListUpdate()}_handleUnreadSyncFinished(s){const{constants:{WORKFLOW_STEP:n}}=this._core,{conversationUpdateFieldList:g=[],groupTipList:u=[],isUnreadC2CMessage:E}=s.result[n.UNREAD_MESSAGE_SYNC]||{};let m=!1;g.forEach(D=>{const{conversationID:M,unreadCount:T}=D,P=this.getLocalConversation(M);P&&P.unreadCount!==T&&(P.updateUnreadCount({nextUnreadCount:T,isUnreadC2CMessage:E}),m=!0)}),m&&this.emitConversationListUpdate(),this._handleGroupAtTipsSynced(u)}_handleGroupAtTipsSynced(s){var n;for(let g=0;g0&&this._handleNewGroupAtTips({GroupTips:M._groupAtInfoList}),m=!0}m&&this.emitConversationListUpdate()}_handleNewMessage(s){const{conversationUpdateFieldList:n=[],isInstantMessage:g=!0,isUnreadC2CMessage:u=!1,updateUnreadCount:E=!0}=s.result||{};if(n.length===0)return;const{common:{isTopic:m}}=this._core;m(n[0].conversationID)||(this.updateLocalConversationList({conversationUpdateFieldList:n,isInstantMessage:g,isUnreadC2CMessage:u,isFromGetConversations:!1,updateUnreadCount:E}),n.filter(D=>this._isConversationNeedShow(D.conversationID)).length>0&&this.emitConversationListUpdate())}_handleNewGroupAtTips(s){const{GroupTips:n=[]}=s;n.forEach(g=>{const{GroupAtTips:u,MsgBody:E,MsgRandom:m,ClientSeq:D}=g;let M={};u?M=this._convertGroupAtTipsKey(u):E?M=Object.assign({},this._convertGroupAtTipsKey(E)):g.groupAtType&&(M=Object.assign({},g)),M.__random=m,M.__sequence=D,this._groupAtTipsList.push(M)}),console.log(`${this._name}._handleNewGroupAtTips groupAtTipsList: ${JSON.stringify(this._groupAtTipsList)}`),this._updateGroupAtInfoList()}_convertGroupAtTipsKey(s){const{From_Account:n,GroupId:g,MsgSeq:u,GroupAtType:E}=s;return{from:n,groupID:g,sequence:u,groupAtType:E}}_updateGroupAtInfoList(){if(this._groupAtTipsList.length===0)return;const{common:s,OuterConstant:n}=this._core,g=s.getCurrentUserID();let u=!1;this._groupAtTipsList.forEach(E=>{const{groupID:m,from:D}=E;if(D!==g){const M=this.getLocalConversation(`${n.CONV_GROUP}${m}`);M&&(M.updateGroupAtInfoList(E),u=!0)}}),u&&this.emitConversationListUpdate(),this._groupAtTipsList.length=0}_handleMessageDeleted(s){var n,g;console.log(`${this._name}._handleMessageDeleted, conversationID:`,s);const{message:{messageDataHandler:u},OuterConstant:E}=this._core,m=u?.getLocalMessageList(s)||[];let D={};for(let P=(m.length||0)-1;P>=0;P--)if(!m[P].isDeleted&&m[P]._isExcludedFromLastMessage!==!0){D=m[P];break}const M=this.getLocalConversation(s);if(!M)return;let T=!1;M.lastMessage.lastSequence===D.sequence&&M.lastMessage.lastTime===D.time||(!((g=(n=this._core)===null||n===void 0?void 0:n.helper)===null||g===void 0)&&g.isEmpty(D)&&(D=void 0),M.updateLastMessage(D),T=!0),s.startsWith(E.CONV_C2C)&&this.updateUnreadCount(s),T&&(this.emitConversationListUpdate(),console.log(`${this._name}._handleMessageDeleted. update conversationID:${s} with lastMessage:`,M.lastMessage))}_handleMessageRevoked(s){const{messageList:n=[],updateUnreadCount:g=!0}=s;if(console.log(`${this._name}._handleMessageRevoked messageList:${n.length}`),n.length===0)return;let u=null,E=!1;n.forEach(m=>{u=this.getLocalConversation(m.conversationID),u&&(g&&u.reduceUnreadCount()&&(E=!0),u.isLastMessageRevoked({sequence:m.sequence,time:m.time})&&(u.setLastMessageRevoked(!0),u.setLastMessageRevoker(m.revoker),E=!0))}),E&&this.emitConversationListUpdate()}_handleMessageModified(s){const{utils:{isEmpty:n},common:{getMessagePreviewText:g},ssoLog:u}=this._core;u.debug(`${this._name}._handleMessageModified`,JSON.stringify(s));const{conversationID:E,messageList:m}=s,D=this.getLocalConversation(E);if(n(D))return;const{lastMessage:M}=D;if(M){const T=m?.[0]||{};M.lastTime===T.time&&M.lastSequence===T.sequence&&M.version!==T.version&&(M.type=T.type,M.payload=T.payload,M.messageForShow=g(T.type,T.payload),M.cloudCustomData=T.cloudCustomData,M.version=T.version,this.emitConversationListUpdate(),console.log(`${this._name} conversationID:${E} lastMessage updated`))}}_handleConversationUpdated(s){this.emitConversationListUpdate(s?.needSort)}updateLocalConversationList(s){const{isFromGetConversations:n}=s,{newConversationList:g}=this._getTmpConversationListMapping(s);this._sortConversationList(),n||this._updateNewConversationProfile(g),this._core.ssoLog.debug("updateLocalConversationList",` newConversationList: ${g.length}`)}_getTmpConversationListMapping(s){const{OuterConstant:n}=this._core,{conversationUpdateFieldList:g,isFromGetConversations:u,isInstantMessage:E,isUnreadC2CMessage:m=!1,updateUnreadCount:D}=s,M=[],T=g?.length;for(let P=0;P{M[1].isPinned===!0?s(M[1].lastMessage.lastTime)?u.push(M):g.push(M):s(M[1].lastMessage.lastTime)?m.push(M):E.push(M)});const D=g.sort((M,T)=>T[1].lastMessage.lastTime-M[1].lastMessage.lastTime).concat(u).concat(E.sort((M,T)=>T[1].lastMessage.lastTime-M[1].lastMessage.lastTime)).concat(m);this._updateConversationMapFromList(D)}_updateNewConversationProfile(s){if(s.length===0)return;const n=[],g=[],{OuterConstant:{CONV_GROUP:u,CONV_C2C:E}}=this._core;s.forEach(m=>{const{conversationID:D,type:M}=m;if(M===E){const T=D.replace(E,"");n.push(T)}else if(M===u){const T=D.replace(u,"");g.push(T)}}),n.length>0&&this._updateC2CConversation(n),g.length>0&&this._updateGroupConversation(g)}_updateC2CConversation(s){var n;const{OuterConstant:{CONV_C2C:g},appStore:{userStore:u},user:E}=this._core;let m=!1;(n=E.userProfile)===null||n===void 0||n.getUserProfile({userIDList:s}).then(D=>{(D?.data||[]).forEach(M=>{var T;const{userID:P}=M,W=this.getLocalConversation(`${g}${P}`);if(W){const iA=((T=u.getFriend(P))===null||T===void 0?void 0:T.remark)||"";W.remark=iA,W.userProfile=M,m=!0}}),m&&this.emitConversationListUpdate()}).catch(D=>{}),BA.get(s)}_updateGroupConversation(s){return pA(this,void 0,void 0,function*(){const{OuterConstant:{CONV_GROUP:n},appStore:{groupStore:g},utils:{safeStringify:u},ssoLog:E,apiMap:{getGroupProfile:m}}=this._core;let D=!1;try{yield Promise.all(s.map(M=>pA(this,void 0,void 0,function*(){const T=g.getGroup(M),P=this.getLocalConversation(`${n}${M}`);T&&P&&(P.groupProfile=T,D=!0),P&&!P.getProfileCompleted()&&typeof m=="function"&&(yield m({groupID:M}))}))),yA.get(s),D&&this.emitConversationListUpdate()}catch(M){E.debug("_updateGroupConversation",u(M))}})}_handleMessageRead(s){const{OuterConstant:{CONV_C2C:n}}=this._core,{C2cNotifyMsgArray:g=[]}=s||{};g.forEach(u=>{const{To_Account:E,UinPairReadArray:m=[]}=u?.C2cReadedReceipt||{};m?.forEach(D=>{const{LastReadTime:M}=D,T=`${n}${E}`;this._updateConversationReadInfo({conversationID:T,peerReadTime:M}),this._updateMessageListPeerRead({conversationID:T,peerReadTime:M})})})}_updateConversationReadInfo(s){const{appStore:n,utils:{isEmpty:g},common:{getCurrentUserID:u}}=this._core,{conversationID:E,peerReadTime:m}=s,D=n.conversationStore.getConversationMap();if(D.has(E)){const M=D.get(E);M.peerReadTime=m;const T=M?.lastMessage;g(T)||T.fromAccount===u()&&T.lastTime<=m&&!T.isPeerRead&&(T.isPeerRead=!0,n.conversationStore.updateConversation(E,{lastMessage:T}))}}_updateMessageListPeerRead(s){const{notificationCenter:n,OuterEvent:g,message:u}=this._core,{conversationID:E,peerReadTime:m}=s,D=u.messageDataHandler.getLocalMessageList(E),M=u.messageDataHandler.getSparseMessageList(E),T=[];D.forEach(P=>{P.time<=m&&!P.isPeerRead&&P.flow==="out"&&(P.isPeerRead=!0,T.push(P))}),M.forEach(P=>{P.time<=m&&!P.isPeerRead&&P.flow==="out"&&(P.isPeerRead=!0,T.push(P))}),n.emitOuterEvent(g.MESSAGE_READ_BY_PEER,{name:g.MESSAGE_READ_BY_PEER,data:T})}_isConversationNeedShow(s){var n,g;const{OuterConstant:{CONV_GROUP:u,GRP_ROOM:E,GRP_LIVE:m},utils:{isUndefined:D}}=this._core,M=this.getLocalConversation(s);if(D(M))return!0;const T=M.type===u&&((n=M.groupProfile)===null||n===void 0?void 0:n.type)===E,P=M.type===u&&((g=M.groupProfile)===null||g===void 0?void 0:g.type)===m;return!(T||P)}updateUnreadCount(s,n=!0){var g,u;let E=!1;const m=this.getLocalConversation(s),D=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageDataHandler)===null||u===void 0?void 0:u.getLocalMessageList(s);if(!m)return E;const M=m.unreadCount,T=D?.filter(P=>!P.isRead&&!P._onlineOnlyFlag&&!P.isDeleted).length;return console.log(`${this._name}._updateUnreadCount conversationID:${s} currentUnreadCount:${M} newUnreadCount:${T}`),M!==T&&(m.unreadCount=T,E=!0,n===!0&&this.emitConversationListUpdate()),E}emitConversationListUpdate(s=!1){var n,g;s&&this._sortConversationList();const{OuterEvent:{CONVERSATION_LIST_UPDATED:u},conversation:E}=this._core,m=this.getLocalConversationList();this._emitEvent({name:u,data:m,isSyncCompleted:(g=(n=E?.syncConversationHandler)===null||n===void 0?void 0:n.isSyncCompleted)===null||g===void 0?void 0:g.call(n)}),this._emitTotalUnreadCountUpdate()}_emitTotalUnreadCountUpdate(){var s;const n=this.getTotalUnreadMessageCount();this._totalUnreadCount!==n&&(this._core.ssoLog.debug("_emitTotalUnreadCountUpdate",` from ${this._totalUnreadCount} to ${n}`),this._totalUnreadCount=n,this._emitEvent({name:(s=this._core)===null||s===void 0?void 0:s.OuterEvent.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED,data:n}))}_emitEvent(s){var n;(n=this._core)===null||n===void 0||n.notificationCenter.emitOuterEvent(s.name,s)}getTotalUnreadMessageCount(){const{OuterConstant:s,utils:{isEmpty:n}}=this._core,g=this.getLocalConversationList();let u=0;return g.forEach(E=>{E.type!==s.CONV_SYSTEM&&(n(E.messageRemindType)||E.messageRemindType===s.MSG_REMIND_ACPT_AND_NOTE)&&(u+=E.unreadCount)}),u}getLocalConversationList(){return[...this._conversationStore.getConversationMap().values()].filter(s=>this._isConversationNeedShow(s.conversationID))}hasLocalConversation(s){return this._conversationStore.getConversationMap().has(s)}getLocalConversation(s){return this._conversationStore.getConversationMap().get(s)}setLocalConversation(s,n){return this._conversationStore.getConversationMap().set(s,n)}deleteLocalConversation(s){this._conversationStore.getConversationMap().delete(s)}_updateConversationMapFromList(s){this._clearConversationMap();for(const[n,g]of s)this.setLocalConversation(n,g)}_clearConversationMap(){this._conversationStore.getConversationMap().clear()}patchMessageRemindType(s,n){let g=!1;s.forEach(u=>{const E=this.getLocalConversation(u);E?.messageRemindType!==n&&(E.messageRemindType=n,g=!0)}),console.log(`${this._name}.patchMessageRemindType conversationIDList:${s} messageRemindType:${n} hasUpdated:${g}`),g&&this.emitConversationListUpdate()}markMessageAsRead(s){const{message:{messageDataHandler:n}}=this._core,{conversationID:g,lastReadTime:u=0,lastReadSequence:E=0}=s,m=n?.getLocalMessageList(g);if(m.length===0)return;const{length:D}=m;for(let M=D-1;M>=0;M--){const T=m[M],P=u&&T.time>u,W=E&&T.sequence>E;if(!P&&!W){if(T.flow==="in"&&T.isRead)break;T.setIsRead(!0)}}}appendToPinnedConversation(s){const n=[...this._conversationStore.getConversationMap().entries()],g=n.findIndex(u=>u[1].isPinned===!1);n.splice(g,0,[s.conversationID,s]),this._updateConversationMapFromList(n),this.emitConversationListUpdate()}_reset(){this._clearConversationMap(),this._totalUnreadCount=0,this._groupAtTipsList=[]}_dispose(){const{notificationCenter:s,InnerEvent:{NEW_MESSAGE:n,MESSAGE_DELETED:g,MESSAGE_REVOKED:u,MESSAGE_MODIFIED:E,CONVERSATION_UPDATED:m,LOGOUT:D,DESTROY:M,SYNC_CONVERSATION_LIST:T}}=this._core,{InnerEventSubType:{GROUP_AT_TIPS:P}}=s;s.unSubscribeInnerEvent(n,this._handleNewMessage,this),s.unSubscribeInnerEvent(n,P,this._handleNewGroupAtTips,this),s.unSubscribeInnerEvent(g,this._handleMessageDeleted,this),s.unSubscribeInnerEvent(u,this._handleMessageRevoked,this),s.unSubscribeInnerEvent(E,this._handleMessageModified,this),s.unSubscribeInnerEvent(m,this._handleConversationUpdated,this),s.unSubscribeInnerEvent(T,this._handleConversationSynced,this),s.unSubscribeInnerEvent(D,this._reset,this),s.unSubscribeInnerEvent(M,this._dispose,this)}},zA=new class{constructor(){this._name="GetConversationList"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"getConversationList",context:this})}getConversationList(s){return pA(this,void 0,void 0,function*(){return{code:0,data:{conversationList:this._getConversationList(s),isSyncCompleted:this._core.conversation.syncConversationHandler.isSyncCompleted()}}})}_getConversationList(s){const{utils:{isUndefined:n,isArray:g,isPlainObject:u}}=this._core;if(n(s))return NA.getLocalConversationList();if(g(s))return s.length===0?[]:NA.getLocalConversationList().filter(E=>s.includes(E.conversationID));if(u(s)){const{type:E,markType:m,groupName:D,hasUnreadCount:M,hasGroupAtInfo:T}=s;return NA.getLocalConversationList().filter(P=>this._filterType(P,E)&&this._filterMarkType(P,m)&&this._filterGroupName(P,D)&&this._filterUnreadCount(P,M)&&this._filterGroupAtInfo(P,T))}return[]}_filterType(s,n){const{OuterConstant:g}=this._core;return n!==g.CONV_C2C&&n!==g.CONV_GROUP||s.type===n}_filterGroupName(s,n){const{utils:{isString:g}}=this._core;return!g(n)||(n===""?s.conversationGroupList.length===0:s.conversationGroupList.includes(n))}_filterMarkType(s,n){const{utils:{isNumber:g}}=this._core;return!g(n)||(n===0?s.markList.length===0:s.markList.includes(n))}_filterUnreadCount(s,n){let g=!0;return n===!0?g=s.unreadCount>=1:n===!1&&(g=s.unreadCount===0),g}_filterGroupAtInfo(s,n){let g=!0;return n===!0?g=s.groupAtInfoList.length>=1:n===!1&&(g=s.groupAtInfoList.length===0),g}},Re=new class{constructor(){this._name="GetConversationProfile"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"getConversationProfile",context:this})}getConversationProfile(s){return pA(this,void 0,void 0,function*(){const{OuterConstant:{CONV_C2C:n,CONV_GROUP:g,GRP_AVCHATROOM:u},appStore:{groupStore:E},utils:{isEmpty:m}}=this._core,D={code:0,data:{}};let M=NA.getLocalConversation(s);if(ks(s))return D.data.conversation=M,D;let T=!1;const P=Bt(s)?n:g;if(m(M)&&(T=!0,M=new Ct({conversationID:s,type:P})),console.log(`${this._name}.getConversationProfile conversationID:${s} isNewConversation:${T}`),D.data.conversation=M,M?.getProfileCompleted())return D;if(P===n){const W=s.replace(n,"");yield this._handleC2CConversation(M,W),T&&(yield BA.get([W]))}if(P===g){const W=s.replace(g,"");if(!E.getGroup(W))return D;yield this._handleGroupConversation(M,W),T&&M.groupProfile.type!==u&&(yield yA.get([W]))}return D})}_handleC2CConversation(s,n){return pA(this,void 0,void 0,function*(){var g,u;const{user:E,helper:m,utils:{isEmpty:D},appStore:{conversationStore:M,userStore:T}}=this._core,{conversationID:P}=s,W=yield(g=E.userProfile)===null||g===void 0?void 0:g.getUserProfile({userIDList:[n]});if(W?.data.length===0)throw new m.ChatError({code:Ba.USER_OR_GRP_NOT_FOUND});s.userProfile=W?.data[0];const iA=(u=T.getFriend(n))===null||u===void 0?void 0:u.remark;D(iA)||s.remark===iA||(s.remark=iA),s.setProfileCompleted();const EA=NA.hasLocalConversation(P);console.log(`${this._name}._handleC2CConversation conversationID:${P} hasLocalConversation: ${EA}`),EA?M.updateConversation(P,s):NA.appendToPinnedConversation(s)})}_handleGroupConversation(s,n){return pA(this,void 0,void 0,function*(){const{apiMap:{getGroupProfile:g},appStore:{conversationStore:u}}=this._core,{conversationID:E}=s,m=yield g({groupID:n});s.groupProfile=m?.data.group,s.setProfileCompleted();const D=NA.hasLocalConversation(E);console.log(`${this._name}._handleGroupConversation conversationID:${E} hasLocalConversation: ${D}`),D?u.updateConversation(E,s):NA.appendToPinnedConversation(s)})}},le=new class{init(s){const{helper:n}=s;n.registerApi({apiName:"getTotalUnreadMessageCount",context:this})}getTotalUnreadMessageCount(){return NA.getTotalUnreadMessageCount()}},Ne=new class{constructor(){this._serverGroupConversationLastReadSeqMap=new Map,this._name="SetMessageRead"}init(s){this._core=s;const{helper:n,common:{isTopic:g},notificationCenter:u,InnerEvent:{MESSAGE_PUSH:E},InnerEventSubType:{ALL_MESSAGE_READ:m}}=s;n.registerApi({apiName:"setMessageRead",context:this,matcher:D=>!g(D[0].conversationID)}),n.registerApi({apiName:"setAllMessageRead",context:this}),u.subscribeInnerEvent(E,m,this._handleAllMessageRead,this)}handleC2CMessageReadSync(s){const{helper:{isEmpty:n},OuterConstant:g}=this._core;s.forEach(u=>{const{ReadC2cMsgNotify:E}=u;if(!n(E)){const{UinPairReadArray:m=[]}=E;m.forEach(D=>{const{From_Account:M,LastReadTime:T}=D,P=`${g.CONV_C2C}${M}`;console.log(`${this._name}.handleC2CMessageReadSync conversationID:${P} lastReadTime:${T}`),NA.markMessageAsRead({conversationID:P,lastReadTime:T}),NA.updateUnreadCount(P)})}})}handleGroupMessageReadSync(s){const{OuterConstant:n,utils:{isUndefined:g}}=this._core;s.forEach(u=>{const{GroupReadInfoArray:E}=u.MsgBody;g(E)||E.forEach(m=>{const{GroupId:D,LastReadMsgSeq:M}=m,T=`${n.CONV_GROUP}${D}`;console.log(`${this._name}.handleGroupMessageReadSync conversationID:${T} lastReadSequence:${M}`),NA.markMessageAsRead({conversationID:T,lastReadSequence:M}),NA.updateUnreadCount(T),this._clearGroupAtInfoList(T)})})}setMessageRead(s){return pA(this,void 0,void 0,function*(){var n,g;const{OuterConstant:u}=this._core,{conversationID:E}=s,m={code:0,data:{}},D=NA.getLocalConversation(E);let M=`${this._name}.setMessageRead conversationID:${E} unreadCount:${D?.unreadCount||0}`;if(m.successLog={message:M},!D)return m;const T=!(!((g=(n=this._core)===null||n===void 0?void 0:n.helper)===null||g===void 0)&&g.isEmpty(D.groupAtInfoList));if(D.type===u.CONV_GROUP&&T&&this._deleteGroupAtTips(E),D.unreadCount===0)return m;const{helper:{ChatError:P}}=this._core;try{if(D.type===u.CONV_C2C){const W=this._getLocalMessageMaxTime(D);M+=`lastMessageTime:${W}`,yield this._setC2CMessageRead(E,W)}if(D.type===u.CONV_GROUP){const W=this._getLocalMessageMaxSequence(D);M+=`lastMessageSequence:${W}`,yield this._setGroupMessageRead(E,W)}}catch(W){const{errorCode:iA,errorInfo:EA}=W;throw new P({functionName:"setMessageRead",code:iA,message:EA,moreMessage:M})}return D.type===u.CONV_SYSTEM&&(D.unreadCount=0),NA.emitConversationListUpdate(),Object.assign(Object.assign({},m),{successLog:{message:M}})})}setAllMessageRead(){return pA(this,arguments,void 0,function*(s={}){const{OuterConstant:{READ_ALL_MSG:n},utils:{safeStringify:g}}=this._core;let u=`scope:${s.scope}`;s.scope||(s.scope=n);const{scope:E}=s,m=this._generateSetAllMessageReadRequestData(E);if(m.allC2CMessageReadStatus===ea&&m.groupMessageReadInfoList.length===0)return{code:0};try{const D=yield function(M){return pA(this,void 0,void 0,function*(){const{allC2CMessageReadStatus:T,groupMessageReadInfoList:P}=M,W={C2CReadAllMsg:T,GroupReadInfo:P};return ho.core.common.buildAndSendPacket({servcmd:"openim.read_all_unread_msg",data:W})})}(m);if(D){const{GroupReadInfoArray:M,C2CReadAllMsg:T}=D,P=this._parseGroupReadInfo(M);this._updateAllConversationReadStatus({allC2CMessageReadStatus:T})>0&&NA.emitConversationListUpdate(),u+=`failureGroupInfoList:${g(P)}`}return{code:0,successLog:{message:u}}}catch(D){const{errorCode:M}=D;throw new this._core.helper.ChatError({functionName:"setAllMessageRead",code:M,moreMessage:u})}})}_handleAllMessageRead(s){const{GroupReadInfoArray:n,C2CReadAllMsg:g}=s;this._parseGroupReadInfo(n),this._updateAllConversationReadStatus({allC2CMessageReadStatus:g})>0&&NA.emitConversationListUpdate()}_updateAllConversationReadStatus(s){const{OuterConstant:{CONV_C2C:n,CONV_GROUP:g},appStore:u}=this._core,E=u.conversationStore.getConversationMap(),{allC2CMessageReadStatus:m}=s;let D=0;for(const[M,T]of E)if(T.unreadCount>=1){if(m===H&&T.type===n){const P=this._getLocalMessageMaxTime(T);NA.markMessageAsRead({conversationID:M,lastReadTime:P})}else if(T.type===g){const P=M.replace(g,"");if(this._serverGroupConversationLastReadSeqMap.has(P)){const W=this._serverGroupConversationLastReadSeqMap.get(P);NA.markMessageAsRead({conversationID:M,lastReadSequence:W})}}NA.updateUnreadCount(M,!1)&&(D+=1)}return D}_generateSetAllMessageReadRequestData(s){const{OuterConstant:{CONV_C2C:n,CONV_GROUP:g,READ_ALL_C2C_MSG:u},appStore:E}=this._core,m={allC2CMessageReadStatus:ea,groupMessageReadInfoList:[]},D=E.conversationStore.getConversationMap();for(const[,M]of D){const{type:T,unreadCount:P}=M;if(this._shouldSetAllMessageRead({scope:s,type:T,unreadCount:P})){if(T===n&&m.allC2CMessageReadStatus===ea){if(m.allC2CMessageReadStatus=H,s===u)break}else if(T===g){const W=this._getLocalMessageMaxSequence(M),{groupID:iA}=M.groupProfile;m.groupMessageReadInfoList.push({GroupId:iA,MsgSeq:W})}}}return m}_parseGroupReadInfo(s){const{utils:{isUndefined:n}}=this._core,g=[];return s?.forEach(u=>{const{GroupId:E,MsgSeq:m,RetCode:D,LastReadMsgSeq:M}=u;n(D)?this._serverGroupConversationLastReadSeqMap.set(E,M):(this._serverGroupConversationLastReadSeqMap.set(E,m),D!==0&&g.push(`${E}-${m}-${D}`))}),g}_deleteGroupAtTips(s){return pA(this,void 0,void 0,function*(){console.log(`${this._name}._deleteGroupAtTips conversationID:${s}`);const n=NA.getLocalConversation(s);if(!n)return;const g=n?.groupAtInfoList||[];if(g.length!==0)try{const{common:{getCurrentUserID:u,isCommunity:E},OuterConstant:{CONV_GROUP:m,CONV_AT_ALL:D}}=this._core;let M=[...g];if(E({groupID:s.replace(m,"")})&&(M=g.filter(P=>!P.atTypeArray.includes(D)),M.length===0))return void this._clearGroupAtInfoList(s,!1);const T=M.map(P=>({From_Account:P.from,To_Account:u(),MsgSeq:P.__sequence,MsgRandom:P.__random,GroupId:P.groupID}));yield function(P,W){return pA(this,void 0,void 0,function*(){const{messageListToDelete:iA}=P,EA={DelMsgList:iA};return W.common.buildAndSendPacket({servcmd:"openim.deletemsg",data:EA})})}({messageListToDelete:T},this._core),console.log(`${this._name}._deleteGroupAtTips ok. count:${g.length}`),this._clearGroupAtInfoList(s)}catch(u){console.error(`${this._name}._deleteGroupAtTips fail:`,u)}})}_clearGroupAtInfoList(s,n=!0){const g=NA.getLocalConversation(s);g&&(g.groupAtInfoList.length>0&&(g.clearGroupAtInfoList(),console.log(`${this._name}._clearGroupAtInfoList conversationID:${s} needEmitConversationUpdate:${n}`)),n&&NA.emitConversationListUpdate())}_getLocalMessageMaxTime(s){var n;const{conversationID:g}=s,u=this._core.message.messageDataHandler.getLocalMessageList(g),E=Math.max(...u.map(D=>D.time));let m=((n=s?.lastMessage)===null||n===void 0?void 0:n.lastTime)||0;return E>m&&(console.log(`${this._name}._getLocalMessageMaxTime update lastMessageTime from ${m} to ${E}`),m=E),m}_getLocalMessageMaxSequence(s){var n;const{conversationID:g}=s,u=this._core.message.messageDataHandler.getLocalMessageList(g),E=Math.max(...u.map(D=>D.sequence));let m=((n=s?.lastMessage)===null||n===void 0?void 0:n.lastSequence)||0;return E>m&&(console.log(`${this._name}._getLocalMessageMaxSequence update lastMessageSequence from ${m} to ${E}`),m=E),m}_setC2CMessageRead(s,n){return pA(this,void 0,void 0,function*(){try{yield function(g,u){return pA(this,void 0,void 0,function*(){return u.common.buildAndSendPacket({servcmd:"openim.msgreaded",data:g})})}({C2CMsgReaded:{Cookie:"",C2CMsgReadedItem:[{To_Account:s.replace("C2C",""),LastedMsgTime:n,Receipt:1}]}},this._core),console.log(`${this._name}._setC2CMessageRead ok, lastReadTime:${n}`),NA.markMessageAsRead({conversationID:s,lastReadTime:n}),NA.updateUnreadCount(s)}catch(g){throw console.warn(`${this._name}._setC2CMessageRead fail:`,g),g}})}_setGroupMessageRead(s,n){return pA(this,void 0,void 0,function*(){try{yield function(g,u){return pA(this,void 0,void 0,function*(){const{groupID:E,lastMessageSequence:m}=g,D={GroupId:E,MsgReadedSeq:m};return u.common.buildAndSendPacket({servcmd:"group_open_http_svc.msg_read_report",data:D})})}({groupID:s.replace("GROUP",""),lastMessageSequence:n},this._core),console.log(`${this._name}._setGroupMessageRead ok, lastReadSequence:${n}`),NA.markMessageAsRead({conversationID:s,lastReadSequence:n}),NA.updateUnreadCount(s)}catch(g){throw console.warn(`${this._name}._setGroupMessageRead fail:`,g),g}})}_shouldSetAllMessageRead(s){const{OuterConstant:{CONV_C2C:n,CONV_GROUP:g,READ_ALL_MSG:u,READ_ALL_C2C_MSG:E,READ_ALL_GROUP_MSG:m}}=this._core,{type:D,scope:M,unreadCount:T}=s;return!(T<=0)&&(!(D!==n||![u,E].includes(M))||!(D!==g||![u,m].includes(M)))}},ae=new class{constructor(){this._name="PinConversation"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"pinConversation",context:this})}handleConversationPinned(s,n){const{utils:{isArray:g}}=this._core;if(!g(s))return;const{OuterConstant:u}=this._core;let E=!1;s.forEach(m=>{const{Type:D,Peer_Account:M,GroupId:T}=m;let P;D===1?P=NA.getLocalConversation(`${u.CONV_C2C}${M}`):D===2&&(P=NA.getLocalConversation(`${u.CONV_GROUP}${T}`)),P&&(console.log(`${this._name}.handleConversationPinned conversationID:${P.conversationID} localPinned:${P.isPinned} remotePinned:${n}`),n&&!P.isPinned&&(P.isPinned=!0,E=!0),!n&&P.isPinned&&(P.isPinned=!1,E=!0))}),E&&NA.emitConversationListUpdate(!0)}pinConversation(s){return pA(this,void 0,void 0,function*(){const{OuterConstant:n,common:g,helper:{ChatError:u}}=this._core,{conversationID:E,isPinned:m}=s,D={code:0,data:{conversationID:E}},M=NA.getLocalConversation(E);if(M&&M.isPinned===m)return D;if(ks(E))return M&&(M.isPinned=m),NA.emitConversationListUpdate(!0),D;const T=`conversationID:${E} isPinned:${m}`;try{let P=null;if(Bt(E)?P={Type:1,To_Account:E.replace(n.CONV_C2C,"")}:ug(E)&&(P={Type:2,GroupId:E.replace(n.CONV_GROUP,"")}),yield function(iA,EA){return pA(this,void 0,void 0,function*(){const{fromAccount:RA,operationType:kA,itemList:xA}=iA,LA={From_Account:RA,OperationType:kA,RecentContactItem:xA};return EA.common.buildAndSendPacket({servcmd:"recentcontact.top",data:LA})})}({fromAccount:g.getCurrentUserID(),operationType:m===!0?1:2,itemList:[P]},this._core)){if(M)M.isPinned!==m&&(M.isPinned=m);else{const iA=new Ct({conversationID:E,type:Bt(E)?n.CONV_C2C:n.CONV_GROUP,isPinned:m});NA.setLocalConversation(E,iA)}NA.emitConversationListUpdate(!0)}return Object.assign(Object.assign({},D),{successLog:{message:T}})}catch(P){const{errorCode:W,errorInfo:iA}=P;throw new u({functionName:"pinConversation",code:W,message:iA,moreMessage:T})}})}},Fe=new class{constructor(){this._name="DeleteConversation"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"deleteConversation",context:this})}handleConversationDeleted(s){const{utils:{isArray:n}}=this._core;if(!n(s))return;const{OuterConstant:g}=this._core,u=[];s.forEach(E=>{const{Type:m,Peer_Account:D,GroupId:M}=E;m===1&&u.push(`${g.CONV_C2C}${D}`),m===2&&u.push(`${g.CONV_GROUP}${M}`)}),console.log(`${this._name}.handleConversationDeleted conversationIDList:${u}`),this._deleteLocalConversationList(u)}deleteConversation(s){return pA(this,void 0,void 0,function*(){const{utils:{isString:n}}=this._core;if(n(s))return this._deleteConversation({conversationIDList:[s],flag:ga.ONLY_CONVERSATIONID});const g=Object.assign({},s);return g.conversationIDList.length>100&&(g.conversationIDList=g.conversationIDList.slice(0,100)),this._deleteConversation(g)})}_deleteConversation(s){return pA(this,void 0,void 0,function*(){const{conversationIDList:n,clearHistoryMessage:g=!0,flag:u=0}=s,{helper:{ChatError:E}}=this._core,m=`conversationIDList:${n} clearHistoryMessage:${g}`;try{const D=yield Promise.all([this._deleteConversationFromLocal(n),this._deleteConversationFromServer(n,g)]),M=[...D[0],...D[1]];if(M.length===0)throw new this._core.helper.ChatError({code:Ba.CONV_NOT_FOUND});return{code:0,data:u===ga.ONLY_CONVERSATIONID?{conversationID:M[0]}:{conversationIDList:M},successLog:{message:m}}}catch(D){const{errorCode:M,errorInfo:T}=D;throw new E({code:M,message:T,moreMessage:m})}})}_deleteConversationFromLocal(s){const{OuterConstant:n}=this._core;return s.filter(g=>{var u;if(!NA.hasLocalConversation(g))return!1;const E=(u=NA.getLocalConversation(g))===null||u===void 0?void 0:u.type;return E!==n.CONV_GROUP||this._hasLocalGroup(g)?E===n.CONV_SYSTEM&&(this._deleteLocalConversation(g),!0):(this._deleteLocalConversation(g),!0)})}_deleteConversationFromServer(s,n){return pA(this,void 0,void 0,function*(){const{OuterConstant:g,common:u}=this._core,E={fromAccount:u.getCurrentUserID(),conversationList:[],clearHistoryMessage:n?1:0};if(s.forEach(D=>{var M;if(NA.hasLocalConversation(D)){const T=((M=NA.getLocalConversation(D))===null||M===void 0?void 0:M.type)||"",P=D.replace(T,"");T===g.CONV_C2C?E.conversationList.push({To_Account:P,Type:1}):T===g.CONV_GROUP&&this._hasLocalGroup(D)&&E.conversationList.push({ToGroupid:P,Type:2})}}),E.conversationList.length===0)return[];const m=yield function(D,M){return pA(this,void 0,void 0,function*(){const{fromAccount:T,conversationList:P,clearHistoryMessage:W}=D,iA={From_Account:T,ContactItem:P,ClearRamble:W};return M.common.buildAndSendPacket({servcmd:"recentcontact.batch_delete",data:iA})})}(E,this._core);if(m){const{ResultItem:D=[]}=m,M=[];return D.length>0&&D.forEach(T=>{if(T.ResultCode===0){const P=T.Type===1?`${g.CONV_C2C}${T.To_Account}`:`${g.CONV_GROUP}${T.ToGroupid}`;M.push(P)}}),this._deleteLocalConversationList(M),M}return[]})}_deleteLocalConversationList(s){let n=!1;s.forEach(g=>{NA.hasLocalConversation(g)&&(this._deleteLocalConversation(g,!1),n=!0)}),console.log(`${this._name}._deleteLocalConversationList isUpdate:${n}`),n&&NA.emitConversationListUpdate()}_deleteLocalConversation(s,n=!0){const g=NA.hasLocalConversation(s);console.log(`${this._name}._deleteLocalConversation conversationID:${s} has:${g}`),g&&(NA.deleteLocalConversation(s),this._deleteConversationLocalMessage(s),n&&NA.emitConversationListUpdate())}_hasLocalGroup(s){const{OuterConstant:{CONV_GROUP:n},appStore:{groupStore:g}}=this._core,u=s.replace(n,"");return!!g.getGroup(u)}_deleteConversationLocalMessage(s){console.log(`${this._name}._deleteConversationLocalMessage conversationID:${s}`),this._core.message.messageDataHandler.deleteConversationMessageList(s),this._core.message.messageHistory.completedHistoryConversations.delete(s)}},St=new class{constructor(){this._name="SetConversationDraft"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"setConversationDraft",context:this})}setConversationDraft(s){return pA(this,void 0,void 0,function*(){const{conversationID:n,draftText:g}=s;if(console.log(`${this._name} conversationID:${n} draftText:${g}`),!NA.hasLocalConversation(n))throw new this._core.helper.ChatError({code:Ba.CONV_NOT_FOUND});const u=NA.getLocalConversation(n);return u?.setDraftText(g),NA.emitConversationListUpdate(),{code:0,data:{conversation:u}}})}},Kt=new class{constructor(){this._name="SetC2CMessageRemindType"}init(s){this._core=s}set(s,n){return pA(this,void 0,void 0,function*(){s.length>30&&(console.warn(`${this._name}.set userIDList length:${s.length} exceeds limit 30`),s.splice(30));const g=function(){const{MSG_REMIND_ACPT_AND_NOTE:P,MSG_REMIND_DISCARD:W,MSG_REMIND_ACPT_NOT_NOTE:iA}=ho.core.OuterConstant;return{[P]:0,[W]:1,[iA]:2}}()[n],u=yield function(P,W){return pA(this,void 0,void 0,function*(){const{userIDList:iA,receiveMessageOption:EA}=P,RA={Peer_Account:iA,Mute_Notifications:EA};return W.common.buildAndSendPacket({servcmd:"openim.set_c2c_peer_mute_notifications",data:RA})})}({userIDList:s,receiveMessageOption:g},this._core),{ErrorList:E=[]}=u||{},m=[];E.forEach(P=>{const{Peer_Account:W,ErrorCode:iA}=P;m.push({userID:W,code:iA});const EA=s.indexOf(W);EA>-1&&s.splice(EA,1)});const D=[],M=[],{OuterConstant:T}=this._core;return s.forEach(P=>{M.push(`${T.CONV_C2C}${P}`),D.push({userID:P})}),NA.patchMessageRemindType(M,n),{code:0,data:{successUserIDList:D,failureUserIDList:m}}})}},ai=new class{constructor(){this._name="SetGroupMessageRemindType"}init(s){this._core=s}set(s,n){return pA(this,void 0,void 0,function*(){const{common:{getCurrentUserID:g,isTopic:u},OuterConstant:E}=this._core;if(yield function(m,D){return pA(this,void 0,void 0,function*(){const{groupID:M,userID:T,receiveMessageOption:P}=m,W={GroupId:M,Member_Account:T,MsgFlag:P};return D.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:W})})}({groupID:s,userID:g(),receiveMessageOption:n},this._core),!u(s)){const m=`${E.CONV_GROUP}${s}`;NA.patchMessageRemindType([m],n)}return{code:0,data:{groupID:s,messageRemindType:n}}})}},ft=new class{constructor(){this._name="SetMessageRemindType"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"setMessageRemindType",context:this})}handleC2CMessageRemindTypeSync(s){const{helper:{isEmpty:n},OuterConstant:g,ssoLog:u}=this._core;s.forEach(E=>{const{MuteNotificationsSync:m}=E;if(!n(m)){const{To_Account:D,MuteNotifications:M}=m,T=D.map(W=>`${g.CONV_C2C}${W}`),P=ji(M);u.debug(`${this._name}.handleC2CMessageRemindTypeSync conversationIDList:${T} messageRemindType:${P}`),NA.patchMessageRemindType(T,P)}})}setMessageRemindType(s){return pA(this,void 0,void 0,function*(){const n="setMessageRemindType",{groupID:g,userIDList:u,messageRemindType:E}=s,{helper:m,utils:{isUndefined:D},ssoLog:M}=this._core;try{if(!D(g))return M.debug(`${this._name}.${n} groupID:${g} messageRemindType:${E}`),yield ai.set(g,E);if(!D(u))return M.debug(`${this._name}.${n} userIDList:${u} messageRemindType:${E}`),yield Kt.set(u,E);throw new m.ChatError({functionName:n,message:"userIDList or groupID is required"})}catch(T){throw new m.ChatError({functionName:n,code:T?.errorCode,message:T?.errorInfo,moreMessage:`groupID:${g} userIDList:${u} messageRemindType:${E}`})}})}},Bi=new class{init(s){s.ssoLog.debug("ConversationAction.init"),this._core=s,zA.init(s),Re.init(s),le.init(s),Ne.init(s),ae.init(s),Fe.init(s),St.init(s),ft.init(s);const{notificationCenter:n,InnerEvent:{MESSAGE_PUSH:g,DESTROY:u}}=this._core,{InnerEventSubType:{CONV_MODIFIED:E,C2C_MESSAGE_READ_SYNC:m,GROUP_MESSAGE_READ_SYNC:D,C2C_REMIND_TYPE_SYNC:M}}=n;n.subscribeInnerEvent(g,E,this._onConversationModified,this),n.subscribeInnerEvent(g,m,this._onC2CMessageReadSync,this),n.subscribeInnerEvent(g,M,this._onC2CMessageRemindTypeSync,this),n.subscribeInnerEvent(g,D,this._onGroupMessageReadSync,this),n.subscribeInnerEvent(u,this._dispose,this)}_onConversationModified(s){const{constants:{ConvModifyPushType:n}}=this._core,{RecentContactMod:g=[]}=s;g.forEach(u=>{const{PushType:E}=u;if(E===n.CONV_DELETED){const{RecentContactList:m}=u.RecentContactDeleteItem;Fe.handleConversationDeleted(m)}if(E===n.CONV_PINED){const{RecentContactList:m}=u.RecentContactTopItem;ae.handleConversationPinned(m,!0)}if(E===n.CONV_UNPINED){const{RecentContactList:m}=u.RecentContactTopItem;ae.handleConversationPinned(m,!1)}})}_onC2CMessageReadSync(s){const{C2cNotifyMsgArray:n=[]}=s;Ne.handleC2CMessageReadSync(n)}_onC2CMessageRemindTypeSync(s){const{C2cNotifyMsgArray:n=[]}=s;ft.handleC2CMessageRemindTypeSync(n)}_onGroupMessageReadSync(s){const{GroupTips:n=[]}=s;Ne.handleGroupMessageReadSync(n)}_dispose(){const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:n,DESTROY:g}}=this._core,{InnerEventSubType:{CONV_MODIFIED:u,C2C_MESSAGE_READ_SYNC:E,GROUP_MESSAGE_READ_SYNC:m,C2C_REMIND_TYPE_SYNC:D}}=s;s.unSubscribeInnerEvent(n,u,this._onConversationModified,this),s.unSubscribeInnerEvent(n,E,this._onC2CMessageReadSync,this),s.unSubscribeInnerEvent(n,D,this._onC2CMessageRemindTypeSync,this),s.unSubscribeInnerEvent(n,m,this._onGroupMessageReadSync,this),s.unSubscribeInnerEvent(g,this._dispose,this)}},Ao=new class{init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"setAllReceiveMessageOpt",context:this})}setAllReceiveMessageOpt(s){return pA(this,void 0,void 0,function*(){try{const{OuterConstant:{MSG_REMIND_ACPT_NOT_NOTE:n}}=this._core,{messageRemindType:g=n,isRepeated:u=!0}=s,{startTime:E=0,endTime:m=0}=this._calcStartAndEndTime(s),D=yield function(M){return pA(this,void 0,void 0,function*(){const{common:T}=ho.core,{startTime:P,endTime:W,isRepeated:iA,messageRemindType:EA}=M,RA={StartTime:P,EndTime:W,IsRepeated:iA,Level:EA};return T.buildAndSendPacket({servcmd:"im_msg_db_logic.ws_set_do_not_disturb",data:RA})})}({messageRemindType:this._getType(g),startTime:E,endTime:m,isRepeated:u?is.ON:is.OFF});return{code:0,data:{errorCode:D.ErrorCode,errorInfo:D.ErrorInfo}}}catch(n){oc("setAllReceiveMessageOpt",n)}})}_calcStartAndEndTime(s){const{startHour:n=0,startMinute:g=0,startSecond:u=0,duration:E=0,isRepeated:m=!0}=s,D=new Date,M=new Date(D.getFullYear(),D.getMonth(),D.getDate(),n,g,u),T=Math.round(M.getTime()/1e3);let P=T+E;return m&&E>=86400&&(P=T+86400),{startTime:T,endTime:P}}_getType(s){const{OuterConstant:n}=this._core;return{[n.MSG_REMIND_ACPT_AND_NOTE]:0,[n.MSG_REMIND_DISCARD]:1,[n.MSG_REMIND_ACPT_NOT_NOTE]:2}[s]}},Is=new class{init(s){this._core=s;const{helper:n,notificationCenter:g,InnerEvent:u}=s;n.registerApi({apiName:"getAllReceiveMessageOpt",context:this}),g.subscribeInnerEvent(u.MESSAGE_PUSH,g.InnerEventSubType.ALL_RECEIVE_MESSAGE_OPTION,this.onAllReceiveMsgOptionNotify,this)}onAllReceiveMsgOptionNotify(s){const n=this._handleResult(s),{notificationCenter:g,OuterEvent:{ALL_RECEIVE_MESSAGE_OPT_UPDATED:u}}=this._core;g.emitOuterEvent(u,{name:u,data:n})}getAllReceiveMessageOpt(){return pA(this,void 0,void 0,function*(){try{const s=yield function(){return pA(this,void 0,void 0,function*(){const{common:n}=ho.core,g={To_Account:n.getCurrentUserID()};return n.buildAndSendPacket({servcmd:"im_msg_db_logic.ws_get_do_not_disturb",data:g})})}();return{code:0,data:this._handleResult(s)}}catch(s){oc("getAllReceiveMessageOpt",s)}})}_handleResult(s){const{OuterConstant:n}=this._core,{MSG_REMIND_ACPT_AND_NOTE:g,MSG_REMIND_DISCARD:u,MSG_REMIND_ACPT_NOT_NOTE:E}=n,m={0:g,1:u,2:E},{Level:D,StartTime:M,EndTime:T,IsRepeated:P}=s;return{messageRemindType:m[D]||g,startTime:M,endTime:T,isRepeated:P===is.ON}}},Uo=new class{init(s){s.ssoLog.debug("ReceiveMessageOptions.init"),this._core=s,Kt.init(s),ai.init(s),BA.init(s),yA.init(s),Ao.init(s),Is.init(s)}};const ti=s=>!Bt(s)&&!ug(s)&&!ks(s),Ur={getConversationProfile:[{key:"conversationID",required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!ti(s)||"conversationID is invalid."}],setMessageRead:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!ti(s)||"conversationID is invalid."}},pinConversation:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!ti(s)||"conversationID is invalid."},isPinned:{required:!0,rules:["boolean"],allowEmpty:!1}},deleteConversation:[{key:"options",required:!0,rules:["string","object"],allowEmpty:!1,customValidator:s=>{const{core:{utils:{isArray:n,isObject:g,isString:u}}}=ho;if(!u(s)&&!g(s))return"options is String or Object.";if(u(s)&&ti(s))return"conversationID is invalid.";if(g(s)){if(!n(s.conversationIDList))return"conversationIDList is not Array.";if(s.conversationIDList.length===0)return"conversationIDList is empty.";if(s.conversationIDList.some(E=>{if(ti(E))return!0}))return"conversationIDList includes invalid conversationID.";if(s.clearHistoryMessage&&typeof s.clearHistoryMessage!="boolean")return"clearHistoryMessage is not Boolean."}return!0}}],setConversationDraft:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!(!Bt(s)&&!ug(s))||"conversationID is invalid."},draftText:{required:!0,rules:["string"],allowEmpty:!0}},setAllReceiveMessageOpt:{messageRemindType:{required:!1,rules:["string"],allowEmpty:!0},startHour:{required:!1,rules:["number"],allowEmpty:!0},startMinute:{required:!1,rules:["number"],allowEmpty:!0},startSecond:{required:!1,rules:["number"],allowEmpty:!0},duration:{required:!1,rules:["number"],allowEmpty:!0},isRepeated:{required:!1,rules:["boolean"],allowEmpty:!0}}},Zo={getConversationList:!0,getConversationProfile:!0,getTotalUnreadCount:!0,setMessageRead:!0,pinConversation:!0,deleteConversation:!0,setConversationDraft:!0,setMessageRemindType:!0,getAllReceiveMessageOpt:!0,setAllReceiveMessageOpt:!0};var jn=new class{constructor(){this.name="Conversation"}install(s){ho.init(s),Bi.init(s),Uo.init(s),NA.init(s),s.helper.registerValidateConfig({auth:Zo,params:Ur})}};const Wn=new class{init(s){this.core=s}},ta="AVChatRoom",qr="AV_HISTORY_MSG",sc="GRP_COUNTER",Ju="Set",pm="Increase",Ri="Decrease",ii=0,yo=1,on=2,os=["Type","Name","Introduction","Notification","FaceUrl","Owner_Account","CreateTime","InfoSeq","LastInfoTime","LastMsgTime","MemberNum","MaxMemberNum","ApplyJoinOption","NextMsgSeq","ShutUpAllMember","InviteJoinOption","LastRecallTime"],Eg=["Type","Name","Introduction","Notification","FaceUrl","CreateTime","Owner_Account","LastInfoTime","LastMsgTime","NextMsgSeq","MemberNum","MaxMemberNum","ApplyJoinOption","InviteJoinOption"],Fl=["Role","JoinTime","MsgFlag","MsgSeq"],md=["Role","JoinTime","MsgSeq","MsgFlag","NameCard"],Lc=0,Mr=1,DI="notStart",ou="resolved",Og="rejected",su=10018,SI=11e3,Uc=2,Hu=["Owner","Admin","Member"],mm=["Role","JoinTime","NameCard","ShutUpUntil","OnlineStatus"],fm=0,ym=1,Dm=2,sD=4,nD=1,bv=2,rD=3,aD=4,kv=5,ET=1,fd=0,dT=4,gD=6,CT=400,cD=300,hT={from:!0,groupID:!0,groupName:!0,to:!0},Lv={from:!0,groupID:!0,groupName:!0,to:!0,type:!0},BT=2,Uv=4,QT=5,pT=7,lD=8,ID=15,_Q=20,Sm=21,Mm=2600,yd=2602,mT=2603,fT=2620,vm=2621,uD=2623,lh=2660,yT=2661,DT=2681,Rm=2683,Fv=2684,ED=2685,wm=2687,Ov=3122,ST=10018,MT={0:"DisableInvite",1:"NeedPermission",2:"FreeAccess"},Pv=s=>s===Wn.core.OuterConstant.GRP_PUBLIC,Dd=s=>s===Wn.core.OuterConstant.GRP_AVCHATROOM,_m=(s,n)=>{const{isArray:g}=Wn.core.utils;if(!g(s)||!g(n))return!1;let u=!1;return n.forEach(({key:E,value:m})=>{const D=s.find(M=>M.key===E);D?D.value!==m&&(D.value=m,u=!0):(s.push({key:E,value:m}),u=!0)}),u},Sd=s=>{const n=[];if(!s)return n;for(let g=0,u=s.length;g{const n=[];for(let g=0,u=s.length;g0&&M.members.forEach(T=>{T.userID===this.selfInfo.userID&&D(this.selfInfo,T,["sequence"])})}updateSelfInfo(n){const{nameCard:g,joinTime:u,role:E,messageRemindType:m,readedSequence:D,excludedUnreadSequenceList:M}=n,{common:{deepMerge:T}}=Wn.core;T(this.selfInfo,{nameCard:g,joinTime:u,role:E,messageRemindType:m,readedSequence:D,excludedUnreadSequenceList:M},[],["",null,void 0,0,NaN])}setSelfNameCard(n){this.selfInfo.nameCard=n}}var Yi=new class{constructor(){this._name="GroupDataHandler"}init(s){this._core=s;const{appStore:{groupStore:n}}=s;this._groupMap=n.getGroupMap()}hasLocalGroup(s){return this._groupMap.has(s)}getLocalGroup(s){return this._groupMap.get(s)}updateLocalGroup(s){const{common:{getCurrentUserID:n}}=this._core;let g;s.forEach(E=>{var m;g=E.groupID,this.hasLocalGroup(g)?(m=this.getLocalGroup(g))===null||m===void 0||m.updateGroup(E):(this._groupMap.set(g,new qu(E)),this._clearGroupLocalMessage(g))});const u=n();for(const[,E]of this._groupMap)E.selfInfo.userID=u,E.selfInfo.role==="Owner"&&(E.ownerID=u)}deleteLocalGroup(s){this._groupMap.delete(s)}getLocalGroupList(){const{OuterConstant:{GRP_ROOM:s,GRP_LIVE:n}}=this._core;return[...this._groupMap.values()].filter(g=>{const{type:u}=g;return u!==s&&u!==n})}clearLocalGroup(){this._groupMap.clear()}emitGroupListUpdate(){const s=this.getLocalGroupList(),{OuterEvent:{GROUP_LIST_UPDATED:n},notificationCenter:g}=this._core;g.emitOuterEvent(n,{name:n,data:s})}updateConversationGroupProfile(s){const{appStore:{conversationStore:n},OuterConstant:{CONV_GROUP:g}}=this._core,u=`${g}${s}`,E=n.getConversation(u);if(E){const m=this.getLocalGroup(s);E.setProfileCompleted(),n.updateConversation(u,{groupProfile:m})}}reset(){this.clearLocalGroup()}_clearGroupLocalMessage(s){const{message:{messageHistory:n,messageDataHandler:g},OuterConstant:{CONV_GROUP:u},ssoLog:E}=this._core;E.debug("_clearGroupLocalMessage",`groupID:${s}`);const m=`${u}${s}`;n.completedHistoryConversations.delete(m),g.deleteConversationMessageList(m)}};function Nm(s,n){return pA(this,void 0,void 0,function*(){const{type:g,limit:u,offset:E,supportTopic:m=0,memberAccount:D,responseFilter:M}=s,T={Type:g,Limit:u,Offset:E,Member_Account:D,ResponseFilter:M,SupportTopic:m,NeedAppDefineData:1};return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_joined_group_list",data:T})})}const dn=function(s,n){return{code:0,data:s||{},successLog:n}};var xv=new class{constructor(){this._name="GetGroupList",this._pagingStatus=DI,this.PAGING_GRP_COUNT_LIMIT=200}init(s){this._core=s;const{helper:n,constants:{WORKFLOW_NAME:g,WORKFLOW_STEP:u}}=s;n.registerApi({apiName:"getGroupList",context:this}),n.registerWorkflowStep(g.SYNC_SERVER_INFO_AFTER_LOGIN,u.GROUP_LIST_SYNC,this._syncGroupList,this)}getGroupList(){return pA(this,arguments,void 0,function*(s=!1){if(s){const g=[];return yield this._pagingGetJoinedCommunityList({limit:this.PAGING_GRP_COUNT_LIMIT,offset:0,groupList:g}),Yi.updateLocalGroup(g),Yi.getLocalGroupList()}if(this._core.ssoLog.debug("getGroupList",`${this._name}.getGroupList pagingStatus:${this._pagingStatus}`),this._pagingStatus===Og||this._pagingStatus===DI)return this._syncGroupList().then(()=>{const g=Yi.getLocalGroupList();return dn({groupList:g,isSyncCompleted:this._isSyncCompleted()})}).catch(g=>{throw g});const n=Yi.getLocalGroupList();return dn({groupList:n,isSyncCompleted:this._isSyncCompleted()},{message:`return group count:${n.length}`})})}_syncGroupList(){return pA(this,void 0,void 0,function*(){this._pagingStatus===DI&&Yi.clearLocalGroup();const s=this.PAGING_GRP_COUNT_LIMIT,n=[];try{yield this._pagingGetGroupList({limit:s,offset:0,groupList:n}),this._pagingStatus=ou,this._groupListTreeShaking(n),Yi.updateLocalGroup(n);const g=Yi.getLocalGroupList();return this._core.ssoLog.debug("_syncGroupList",`${this._name}._syncGroupList ok, count:${g.length}`),Yi.emitGroupListUpdate(),g}catch(g){throw this._pagingStatus=Og,g}})}_pagingGetGroupList(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n}=this._core,{isCommunityRelay:g=!1,groupList:u}=s;let E,{limit:m,offset:D}=s;const M=[...os];g&&(E=this._core.OuterConstant.GRP_COMMUNITY,M.push("AtInfoList"));try{const T=yield Nm({type:E,limit:m,offset:D,memberAccount:this._core.store.get("login").userId,responseFilter:{GroupBaseInfoFilter:M,SelfInfoFilter:[...Fl]}},this._core),{GroupIdList:P=[],TotalCount:W=0}=T||{},iA=this._convertGroupKey(P);u.push(...iA);const EA=D+m,RA=!(W>EA),kA=`offset:${D} limit:${m} total:${W} isCompleted:${RA} current:${u.length} isCommunityRelay:${g}`;return n.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList ok. ${kA}`),g?RA?u:(D=EA,this._pagingGetGroupList({isCommunityRelay:!0,limit:m,offset:D,groupList:u})):RA?(n.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList start to get community list`),D=0,this._pagingGetGroupList({isCommunityRelay:!0,limit:m,offset:D,groupList:u})):(D=EA,this._pagingGetGroupList({limit:m,offset:D,groupList:u}))}catch(T){if(T.ErrorCode===su)return n.warn("_pagingGetGroupList",`${this._name}._pagingGetGroupList response size exceeds the limit, request count:${m}`),m=50,this._pagingGetGroupList({isCommunityRelay:g,limit:m,offset:D,groupList:u});if(g)return T.code===SI&&n.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList ok. community unavailable`),u;throw T}})}_pagingGetJoinedCommunityList(s){return pA(this,void 0,void 0,function*(){const{common:{getCurrentUserID:n},OuterConstant:g,ssoLog:u}=this._core,{groupList:E}=s;let{limit:m,offset:D}=s;try{const M=yield Nm({limit:m,offset:D,type:g.GRP_COMMUNITY,memberAccount:n(),supportTopic:1,responseFilter:{GroupBaseInfoFilter:[...os],SelfInfoFilter:[...Fl]}},this._core),{GroupIdList:T=[],TotalCount:P=0}=M||{},W=this._convertGroupKey(T);E.push(...W);const iA=D+m,EA=!(P>iA),RA=`offset:${D} limit:${m} total:${P} isCompleted:${EA} current:${E.length}`;return u.debug("_pagingGetJoinedCommunityList",`${this._name}._pagingGetJoinedCommunityList ok. ${RA}`),EA?E:(D=iA,this._pagingGetJoinedCommunityList({limit:m,offset:D,groupList:E}))}catch(M){if(M.code===ST)return u.warn("_pagingGetJoinedCommunityList",`${this._name}._pagingGetJoinedCommunityList response size exceeds the limit, request count:${m}`),m=50,this._pagingGetJoinedCommunityList({limit:m,offset:D,groupList:E});throw M}})}_groupListTreeShaking(s){const n=new Map([...Yi.getLocalGroupList()]);for(let u=0,E=s.length;u{const{AtFlagList:E,AtMsgSeq:m,From_Account:D}=u;g.push({groupID:s,groupAtType:E,sequence:m,from:D})}),g}},Ku=new class{constructor(){this._name="CreateGroup"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"createGroup",context:this})}createGroup(s){return pA(this,void 0,void 0,function*(){var n;this._preCheckParams(s);const{helper:{ChatError:g}}=this._core;try{const{utils:{isEmpty:u},common:{getCurrentUserID:E},OuterConstant:{GRP_AVCHATROOM:m}}=this._core,D=yield function(iA,EA){return pA(this,void 0,void 0,function*(){const{name:RA,type:kA,groupID:xA,introduction:LA,notification:SA,avatar:OA,maxMemberNum:JA,joinOption:ne,inviteOption:se,memberList:_i,groupCustomField:Ti,isSupportTopic:Lt}=iA;let Ni,cs;_i&&(Ni=_i.map(mt=>{const{userID:UA,memberCustomField:oi}=mt;return{Member_Account:UA,AppMemberDefinedData:oi?OE(oi):void 0}})),Ti&&(cs=OE(Ti));const Se={Name:RA,Type:kA,GroupId:xA,Introduction:LA,Notification:SA,FaceUrl:OA,MaxMemberCount:JA,ApplyJoinOption:ne,InviteJoinOption:se,MemberList:Ni,AppDefinedData:cs,SupportTopic:Lt,webPushFlag:1};return EA.common.buildAndSendPacket({servcmd:"group_open_http_svc.create_group",data:Se})})}(Object.assign(Object.assign({},s),{ownerID:E()}),this._core),{GroupId:M,OverJoinedGroupLimit_Account:T=[]}=D||{},P=`${this._name}.createGroup ok, type:${s.type} groupID:${M} overLimitUserIDList:${T}`;if(u(s.memberList)||u(T)||(s.memberList=(n=s.memberList)===null||n===void 0?void 0:n.filter(iA=>T.includes(iA.userID))),s.type===m)return dn({group:new qu(Object.assign(Object.assign({},s),{groupID:M}))},{message:P});Yi.updateLocalGroup([Object.assign(Object.assign({},s),{groupID:M})]);const W=Yi.getLocalGroup(M);return this._notNeedSendCustomMessage(s)||(this._sendCustomMessage(M,s.type),Yi.emitGroupListUpdate()),dn({group:W},{message:P})}catch(u){const{errorCode:E,errorInfo:m}=u;throw new g({functionName:"createGroup",code:E,message:m,moreMessage:` groupID:${s.groupID}`})}})}_preCheckParams(s){const{type:n,groupID:g}=s,{utils:{isEmpty:u,isUndefined:E},common:{isCommunity:m}}=this._core,D=!u(g);if(!(()=>{const{GRP_PUBLIC:M,GRP_WORK:T,GRP_MEETING:P,GRP_AVCHATROOM:W,GRP_COMMUNITY:iA}=Wn.core.OuterConstant;return[M,T,P,W,iA]})().includes(n))throw new this._core.helper.ChatError({code:Mm});if(!m({type:n})){if(D&&m({groupID:g}))throw new this._core.helper.ChatError({code:yd});E(s.isSupportTopic)||(s.isSupportTopic=void 0)}if(this._canIUseMemberList(n)||E(s.memberList)||(s.memberList=void 0),this._canIUseJoinOption(n)||E(s.joinOption)||(s.joinOption=void 0),m({type:n})){if(D&&!m({groupID:g}))throw new this._core.helper.ChatError({code:yd});s.isSupportTopic=this._canIUseTopic(s)?1:0}}_canIUseMemberList(s){return!Dd(s)}_canIUseJoinOption(s){return Pv(s)||this._core.common.isCommunity({type:s})}_canIUseTopic(s){const{isSupportTopic:n}=s;return n===!0}_notNeedSendCustomMessage(s){const{type:n,isSupportTopic:g}=s,{OuterConstant:{GRP_AVCHATROOM:u,GRP_COMMUNITY:E}}=this._core;return n===u||n===E&&g===1}_sendCustomMessage(s,n){var g,u,E,m,D,M;const{OuterConstant:T,common:{t:P}}=this._core;let W=P("CREATE_GROUP"),iA=Lc;n===T.GRP_COMMUNITY&&(W=P("CREATE_COMMUNITY"),iA=Mr);const EA={to:s,conversationType:"GROUP",payload:{data:JSON.stringify({businessID:"group_create",content:W,cmd:iA,opUser:this._core.store.get("login").userId,version:4})}},RA=(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageFactory)===null||E===void 0?void 0:E.createCustomMessage(EA);(M=(D=(m=this._core)===null||m===void 0?void 0:m.message)===null||D===void 0?void 0:D.messageSender)===null||M===void 0||M.sendMessage(RA,{})}},zs=new class{constructor(){this._name="AttributesDataHandler",this._groupAttributesCache=new Map,this._groupAttributesCacheValuesCopy={}}init(s){this._core=s;const{helper:n,constants:g}=s;n.registerWorkflowStep(g.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,g.WORKFLOW_STEP.GROUP_ATTRIBUTE_CACHE_CLEAR,this.clearLocalMainSequence,this)}clearLocalMainSequence(){this._groupAttributesCache.forEach(s=>{s.localMainSequence=0})}isGroupAttributesUpdated(s){const{elements:{newGroupProfile:n}}=s,{utils:{isEmpty:g,isUndefined:u}}=this._core;return!u(n)&&!g(n.groupAttributeOption)}handleGroupAttributesUpdated(s){const{groupID:n,groupAttributeOption:g}=s,{serverMainSequence:u,groupAttributeList:E=[],operation:m}=g;this._core.ssoLog.debug("handleGroupAttributesUpdated",`${this._name}.handleGroupAttributesUpdated groupID:${n} operation:${m}`);const{utils:{isUndefined:D}}=this._core;D(m)||(this.refreshGroupAttributesCache({groupID:n,serverMainSequence:u,groupAttributeList:E,operation:m}),this.emitGroupAttributesUpdated(n))}initGroupAttributesCache(s){const{groupID:n,avChatRoomKey:g}=s;this._groupAttributesCache.set(n,{lastUpdateTime:0,localMainSequence:0,serverMainSequence:0,avChatRoomKey:g,values:new Map}),this._core.ssoLog.debug("initGroupAttributesCache",`${this._name}.initGroupAttributesCache. groupID:${n} avChatRoomKey:${g}`)}hasGroupAttributesCache(s){return this._groupAttributesCache.has(s)}getGroupAttributesCache(s){return this.hasGroupAttributesCache(s)||this.initGroupAttributesCache({groupID:s}),this._groupAttributesCache.get(s)}deleteGroupAttributesCache(s){this.hasGroupAttributesCache(s)&&this._groupAttributesCache.delete(s)}refreshGroupAttributesCache(s){const{groupID:n,serverMainSequence:g,groupAttributeList:u,operation:E}=s;if(this.hasGroupAttributesCache(n)){const m=this.getGroupAttributesCache(n),{localMainSequence:D}=m;E!==kv&&g-D!==1||(m.serverMainSequence=g,m.localMainSequence=g,m.lastUpdateTime=Date.now(),this._updateGroupAttributesCacheValues({groupAttributes:m,groupAttributeList:u,operation:E})),g-D>1&&(m.serverMainSequence=g),this._groupAttributesCache.set(n,m),this._core.ssoLog.debug("refreshGroupAttributesCache",`${this._name}.refreshGroupAttributesCache. operation:${E} localMainSequence:${D} serverMainSequence:${g}`)}}_updateGroupAttributesCacheValues(s){const{groupAttributes:n,groupAttributeList:g=[],operation:u}=s;u!==rD?u!==aD?(u===nD&&n.values.clear(),g.forEach(E=>{const{key:m,value:D,sequence:M}=E;n.values.set(m,{value:D,sequence:M})})):g.forEach(E=>{n.values.delete(E.key)}):n.values.clear()}getGroupAttributesCacheValues(s){var n;const{groupID:g,keyList:u=[]}=s,E={};if(this.hasGroupAttributesCache(g)){const{values:m}=this.getGroupAttributesCache(g);if(u.length===0){for(const D of m.keys())E[D]=((n=m.get(D))===null||n===void 0?void 0:n.value)||"";return E}return u.forEach(D=>{var M;m.has(D)&&(E[D]=((M=m.get(D))===null||M===void 0?void 0:M.value)||"")}),E}return E}saveGroupAttributesCacheValuesCopy(s){this._groupAttributesCacheValuesCopy=this.getGroupAttributesCacheValues({groupID:s})}emitGroupAttributesUpdated(s){var n,g;const{OuterConstant:{GRP_ROOM:u,GRP_LIVE:E}}=this._core,m=this.getGroupAttributesCacheValues({groupID:s}),D=this._core.appStore.groupStore.getGroup(s),{updatedKeyList:M,deletedKeyList:T}=this._computeValuesChangedData(m);M.length===0&&T.length===0||([u,E].includes(D.type)?(this._core.ssoLog.debug("RICH_STATUS_CHANGED",`${this._name}.emitRichStatusChanged update count:${M.length}, delete count:${T.length}`),this._emitEvent({name:(n=this._core)===null||n===void 0?void 0:n.OuterEvent.RICH_STATUS_CHANGED,data:{groupID:s,richStatus:m,updatedKeyList:M,deletedKeyList:T}})):(this._core.ssoLog.debug("emitGroupAttributesUpdated",`${this._name}.emitGroupAttributesUpdated update count:${M.length}, delete count:${T.length}`),this._emitEvent({name:(g=this._core)===null||g===void 0?void 0:g.OuterEvent.GROUP_ATTRIBUTES_UPDATED,data:{groupID:s,groupAttributes:m,updatedKeyList:M,deletedKeyList:T}})))}_computeValuesChangedData(s){const{utils:{isUndefined:n}}=this._core,g=[],u=[];return Object.keys(s).forEach(E=>{s[E]!==this._groupAttributesCacheValuesCopy[E]&&g.push(E)}),Object.keys(this._groupAttributesCacheValuesCopy).forEach(E=>{n(s[E])&&u.push(E)}),this._groupAttributesCacheValuesCopy={},{updatedKeyList:g,deletedKeyList:u}}_emitEvent(s){var n;(n=this._core)===null||n===void 0||n.notificationCenter.emitOuterEvent(s.name,s)}convertKeyValueMapToList(s){const n=[];return Object.keys(s).forEach(g=>{n.push({key:g,value:s[g]})}),n}reset(){this._groupAttributesCache.clear(),this._groupAttributesCacheValuesCopy={}}},uh=new class{constructor(){this._name="DismissGroup"}init(s,n){this._core=s;const{helper:g}=s;g.registerApi({apiName:"dismissGroup",context:this,matcher:()=>!n.getInstalledSubPlugins().includes(ta)})}dismissGroup(s){return pA(this,void 0,void 0,function*(){const{helper:{ChatError:n}}=this._core;try{yield function(u,E){return pA(this,void 0,void 0,function*(){const m={GroupId:u};return E.common.buildAndSendPacket({servcmd:"group_open_http_svc.destroy_group",data:m})})}(s,this._core);const{type:g}=Yi.getLocalGroup(s);return Yi.deleteLocalGroup(s),Yi.emitGroupListUpdate(),zs.deleteGroupAttributesCache(s),dn({groupID:s,type:g},{message:s})}catch(g){const{errorCode:u,errorInfo:E}=g;throw new n({functionName:"dismissGroup",code:u,message:E})}})}},Ol=new class{constructor(){this._name="GetGroupProfile"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"getGroupProfile",context:this})}getGroupProfile(s){return pA(this,void 0,void 0,function*(){const{groupID:n,groupCustomFieldFilter:g}=s,u={groupIDList:[n],responseFilter:{GroupBaseInfoFilter:[...os],AppDefinedDataFilter_Group:g,MemberInfoFilter:[...md]}},{helper:{ChatError:E}}=this._core;try{const m=yield this.getGroupProfileAdvance(u),{successGroupList:D,failureGroupList:M}=m;if(M.length>0)throw M[0];let T;return!Yi.hasLocalGroup(n)&&Dd(D[0].type)?T=new qu(D[0]):(Yi.updateLocalGroup(D),T=Yi.getLocalGroup(n)),T.isSupportTopic||Yi.updateConversationGroupProfile(n),dn({group:T},{message:`groupID:${n}`})}catch(m){const{code:D,message:M}=m;throw new E({functionName:"getGroupProfile",code:D,message:M})}})}getGroupProfileAdvance(s){return pA(this,void 0,void 0,function*(){const{groupIDList:n}=s,{common:{isCommunity:g}}=this._core,u=n.filter(T=>!g({groupID:T})),E=n.filter(T=>g({groupID:T}));u.length>50&&(u.length=50),E.length>50&&(E.length=50);const m=yield Promise.all([this._getGroupProfileAdvance(Object.assign(Object.assign({},s),{groupIDList:u})),this._getGroupProfileAdvance(Object.assign(Object.assign({},s),{groupIDList:E,isCommunityProfile:!0}))]),D=[],M=[];return m.forEach(T=>{D.push(...T.successGroupList),M.push(...T.failureGroupList)}),{successGroupList:D,failureGroupList:M}})}_getGroupProfileAdvance(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{isUndefined:g}}=this._core,{isCommunityProfile:u=!1}=s,E=Do(s,["isCommunityProfile"]);if(E.groupIDList.length===0)return{successGroupList:[],failureGroupList:[]};try{const m=yield function(W,iA){return pA(this,void 0,void 0,function*(){const{groupIDList:EA,responseFilter:RA}=W,kA={GroupIdList:EA,ResponseFilter:RA};return iA.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_self_member_info",data:kA})})}(E,this._core),{GroupInfo:D=[]}=m||{},M=this._convertGroupProfileKey(D),T=M.filter(W=>g(W.errorCode)||W.errorCode===0),P=M.filter(W=>W.errorCode&&W.errorCode!==0).map(W=>({code:W.errorCode,message:W.errorInfo,data:{groupID:W.groupID}}));return n.debug("_getGroupProfileAdvance",`${this._name}._getGroupProfileAdvance ok, groupID:${E.groupIDList.join(",")}`),{successGroupList:T,failureGroupList:P}}catch(m){if(u)return{successGroupList:[],failureGroupList:[]};throw m}})}_convertGroupProfileKey(s){const n=[];for(let g=0,u=s.length;g0&&u{const{Key:T,Value:P=0}=M;E.set(T,P)}),this._groupCountersMap.set(n,{lastUpdateTime:Date.now(),groupCounterSeq:u,counters:E,avChatRoomKey:m})}}initGroupCountersCache(s){const{groupID:n,avChatRoomKey:g}=s;this._groupCountersMap.set(n,{lastUpdateTime:0,groupCounterSeq:0,counters:new Map,avChatRoomKey:g})}getLocalCounters(s,n){const g={};if(!this._hasLocalGroupCounters(s))return g;const{counters:u}=this.getLocalGroupCounters(s);if(n.length>0)n.forEach(E=>{u.has(E)&&(g[E]=u.get(E))});else for(const E of u.keys())g[E]=u.get(E);return g}deleteLocalGroupCounters(s){const{groupID:n,counterList:g=[],groupCounterSeq:u}=s;if(this._hasLocalGroupCounters(n)){const{counters:E,avChatRoomKey:m}=this.getLocalGroupCounters(n);g.forEach(D=>{E.delete(D.key)}),this._groupCountersMap.set(n,{lastUpdateTime:Date.now(),groupCounterSeq:u,counters:E,avChatRoomKey:m})}}setGroupCounters(s,n){if(!this._hasLocalGroupCounters(s))return;const g=this.getLocalGroupCounters(s),{counters:u}=g;let E=!1;Object.entries(n).forEach(([m,D])=>{u.has(m)&&u.get(m)!==D&&(u.set(m,D),E=!0)}),E&&this._groupCountersMap.set(s,Object.assign(Object.assign({},g),{lastUpdateTime:Date.now(),counters:u}))}_hasLocalGroupCounters(s){return this._groupCountersMap.has(s)}reset(){this._groupCountersMap.clear()}},PE=new class{constructor(){this._name="JoinGroup"}init(s,n){this._core=s;const{helper:g}=s;g.registerApi({apiName:"joinGroup",context:this,matcher:()=>!n.getInstalledSubPlugins().includes(ta)})}joinGroup(s){return pA(this,void 0,void 0,function*(){const{groupID:n}=s,{helper:{ChatError:g},OuterConstant:u,ssoLog:E}=this._core;try{if(Yi.hasLocalGroup(n))try{return yield Ol.getGroupProfile({groupID:n}),dn({status:u.JOIN_STATUS_ALREADY_IN_GROUP,group:Yi.getLocalGroup(n)},{message:`groupID:${n} joinedStatus:${u.JOIN_STATUS_ALREADY_IN_GROUP}`})}catch{return E.warn("joinGroup",`${this._name}.joinGroup ${n} was unjoined, start to join!`),Yi.deleteLocalGroup(n),yield this._applyJoinGroup(s)}return yield this._applyJoinGroup(s)}catch(m){const{errorCode:D,errorInfo:M}=m;throw new g({functionName:"joinGroup",code:D,message:M,moreMessage:`groupID:${n}`})}})}_applyJoinGroup(s){return pA(this,void 0,void 0,function*(){const{OuterConstant:n,helper:g,ssoLog:u}=this._core,{groupID:E}=s,m=Object.assign({},s),D=g.checkBusinessCapabilityBits(qr);D&&(m.historyMessageFlag=1);const M=yield function(SA,OA){return pA(this,void 0,void 0,function*(){const{groupID:JA,applyMessage:ne,historyMessageFlag:se}=SA,_i={GroupId:JA,ApplyMsg:ne,HugeGroupHistoryMsgFlag:se};return OA.common.buildAndSendPacket({servcmd:"group_open_http_svc.apply_join_group",data:_i})})}(m,this._core),{Type:T,JoinedStatus:P,LongPollingKey:W,StartSeq:iA,HugeGroupFlag:EA,AVChatRoomKey:RA,RspMsgList:kA=[]}=M||{},xA=`groupID:${E} joinedStatus:${P} longPollingKey:${W} startSeq:${iA} avChatRoomFlag:${EA} canGetAVChatRoomHistoryMsg:${D}, historyMessageCount:${kA.length}`;u.debug("_applyJoinGroup",`${this._name}._applyJoinGroup ok, ${xA}`);let LA=new qu({groupID:E,type:T});if(P===n.JOIN_STATUS_WAIT_APPROVAL)return dn({status:n.JOIN_STATUS_WAIT_APPROVAL,group:LA});if(P===n.JOIN_STATUS_SUCCESS){try{LA=(yield Ol.getGroupProfile({groupID:E})).data.group}catch(SA){u.warn("_applyJoinGroup",`${this._name}._applyJoinGroup getGroupProfile failed, groupID: ${E}, errorCode:${SA?.code}`)}return this._handleJoinResult({group:LA,avChatRoomFlag:EA,longPollingKey:W,startSequence:iA,avChatRoomKey:RA,historyMessageList:kA})}throw new this._core.helper.ChatError({code:lh})})}_handleJoinResult(s){const{group:n,avChatRoomFlag:g,avChatRoomKey:u}=s;return g===1?(zs.initGroupAttributesCache({groupID:n.groupID,avChatRoomKey:u}),nc.initGroupCountersCache({groupID:n.groupID,avChatRoomKey:u}),dn(s)):(Yi.updateLocalGroup([n]),Yi.emitGroupListUpdate(),dn({status:this._core.OuterConstant.JOIN_STATUS_SUCCESS,group:n},{message:`groupID:${n.groupID}`}))}},TQ=new class{constructor(){this._name="QuitGroup"}init(s,n){this._core=s;const{helper:g}=s;g.registerApi({apiName:"quitGroup",context:this,matcher:()=>!n.getInstalledSubPlugins().includes(ta)})}quitGroup(s){return pA(this,void 0,void 0,function*(){if(!Yi.hasLocalGroup(s))throw new this._core.helper.ChatError({code:uD});const{helper:{ChatError:n}}=this._core;try{yield function(u,E){return pA(this,void 0,void 0,function*(){const m={GroupId:u};return E.common.buildAndSendPacket({servcmd:"group_open_http_svc.quit_group",data:m})})}(s,this._core);const{type:g}=Yi.getLocalGroup(s);return Yi.deleteLocalGroup(s),Yi.emitGroupListUpdate(),zs.deleteGroupAttributesCache(s),dn({groupID:s,type:g},{message:`groupID:${s}`})}catch(g){const{errorCode:u,errorInfo:E}=g;throw new n({functionName:"quitGroup",code:u,message:E,moreMessage:`groupID:${s}`})}})}},gB=new class{constructor(){this._name="SearchGroup"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"searchGroupByID",context:this})}searchGroupByID(s){return pA(this,void 0,void 0,function*(){try{const n=yield function(OA,JA){return pA(this,void 0,void 0,function*(){const ne={GroupIdList:[OA],GroupBasePublicInfoFilter:[...Eg]};return JA.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_public_info",data:ne})})}(s,this._core),{GroupInfo:g=[]}=n||{},{AppDefinedData:u=[],ApplyJoinOption:E,CreateTime:m,FaceUrl:D,Introduction:M,InviteJoinOption:T,MaxMemberNum:P,MemberNum:W,Name:iA,Owner_Account:EA,Type:RA,ErrorCode:kA,ErrorInfo:xA}=g[0];if(kA!==0)throw new this._core.helper.ChatError({code:kA,message:xA});const LA=Sd(u),SA=new qu({groupID:s,name:iA,avatar:D,introduction:M,joinOption:E,inviteOption:T,maxMemberCount:P,memberCount:W,type:RA,ownerID:EA,createTime:m,groupCustomField:LA});return dn({group:SA})}catch(n){const{errorCode:g,errorInfo:u}=n;throw new this._core.helper.ChatError({functionName:"searchGroupByID",code:g,message:u})}})}},vT=new class{constructor(){this._name="UpdateGroupProfile"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"updateGroupProfile",context:this})}updateGroupProfile(s){return pA(this,void 0,void 0,function*(){const{groupID:n}=s,{utils:{isUndefined:g,safeStringify:u},ssoLog:E,helper:m}=this._core;let D=Yi.getLocalGroup(n);if(D){const{type:M}=D;this._canIUseJoinOption(M)||g(s.joinOption)||(E.warn("updateGroupProfile",`${this._name}.updateGroupProfile groupID:${n} joinOption is unavailable for Work/Meeting/AVChatRoom`),s.joinOption=void 0)}g(s.muteAllMembers)||(s.muteAllMembers=s.muteAllMembers===!0?"On":"Off");try{return yield function(M,T){return pA(this,void 0,void 0,function*(){const{groupID:P,name:W,avatar:iA,introduction:EA,notification:RA,muteAllMembers:kA,joinOption:xA,inviteOption:LA,groupCustomField:SA}=M,OA={GroupId:P,Name:W,FaceUrl:iA,Introduction:EA,Notification:RA,ShutUpAllMember:kA,ApplyJoinOption:xA,InviteJoinOption:LA,AppDefinedData:SA?OE(SA):void 0};return T.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_base_info",data:OA})})}(s,this._core),D?(D.updateGroup(s),Yi.emitGroupListUpdate()):D=new qu(s),dn({group:D},{message:`groupID:${n}`})}catch(M){const{errorCode:T,errorInfo:P}=M;throw new m.ChatError({code:T,message:P,moreMessage:`options:${u(s)}`})}})}_canIUseJoinOption(s){return Pv(s)||this._core.common.isCommunity({type:s})}},RT=new class{constructor(){this._name="ChangeGroupOwner"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"changeGroupOwner",context:this})}changeGroupOwner(s){return pA(this,void 0,void 0,function*(){const n="changeGroupOwner",{groupID:g,newOwnerID:u}=s,E=Yi.getLocalGroup(g),{helper:m,OuterConstant:D,common:{getCurrentUserID:M}}=this._core;if(E?.type===D.GRP_AVCHATROOM)throw new m.ChatError({functionName:n,code:fT});if(u===M())throw new m.ChatError({functionName:n,code:vm});try{return yield function(T,P){return pA(this,void 0,void 0,function*(){const{groupID:W,newOwnerID:iA}=T,EA={GroupId:W,NewOwner_Account:iA};return P.common.buildAndSendPacket({servcmd:"group_open_http_svc.change_group_owner",data:EA})})}(s,this._core),E.ownerID=u,Yi.emitGroupListUpdate(),dn({group:E})}catch(T){throw new m.ChatError({functionName:n,code:T?.errorCode,message:T?.errorInfo})}})}},NQ=new class{constructor(){this._name="GetGroupOnlineMemberCount",this._onlineMemberCountMap=new Map}init(s,n){this._core=s;const{helper:g}=s;g.registerApi({apiName:"getGroupOnlineMemberCount",context:this,matcher:()=>!n.getInstalledSubPlugins().includes(ta)})}getGroupOnlineMemberCount(s){return pA(this,void 0,void 0,function*(){const n="getGroupOnlineMemberCount";if(!Yi.hasLocalGroup(s))return dn({memberCount:0});const g=Date.now();if(this._onlineMemberCountMap.has(s)){const u=this._onlineMemberCountMap.get(s),{lastReqTime:E=0,memberCount:m=0}=u||{};if(g-E<=6e4)return dn({memberCount:m})}try{const u=yield function(D,M){return pA(this,void 0,void 0,function*(){const T={GroupId:D};return M.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_online_member_num",data:T})})}(s,this._core),{OnlineMemberNum:E=0}=u||{};this._onlineMemberCountMap.set(s,{lastReqTime:Date.now(),memberCount:E});const m=`${this._name}.${n} ok. groupID:${s} memberCount:${E}`;return dn({memberCount:E},{message:m})}catch(u){throw new this._core.helper.ChatError({functionName:n,code:u?.errorCode,message:u?.errorInfo})}})}},GQ=new class{init(s,n){s.ssoLog.debug("GroupAction.init"),xv.init(s),Ku.init(s),uh.init(s,n),PE.init(s,n),TQ.init(s,n),gB.init(s),Ol.init(s),vT.init(s),RT.init(s),NQ.init(s,n)}dismissGroup(s){return uh.dismissGroup(s)}joinGroup(s){return PE.joinGroup(s)}quitGroup(s){return TQ.quitGroup(s)}getGroupOnlineMemberCount(s){return NQ.getGroupOnlineMemberCount(s)}},Yv=new class{constructor(){this._name="GetGroupApplicationList"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"getGroupApplicationList",context:this})}getGroupApplicationList(){return pA(this,void 0,void 0,function*(){const s="getGroupApplicationList";try{const n=yield Promise.all([this._getGroupApplicationList(),this._getGroupApplicationList({type:this._core.OuterConstant.GRP_COMMUNITY})]);this._core.ssoLog.debug("getGroupApplicationList",`${this._name}.${s} ok.`);const g=this._handleGroupApplicationResult([...n[0],...n[1]]);return dn({applicationList:g})}catch(n){throw new this._core.helper.ChatError({functionName:s,code:n?.errorCode,message:n?.errorInfo})}})}_getGroupApplicationList(s){return pA(this,void 0,void 0,function*(){const{type:n,startTime:g=0,limit:u=20}=s||{},{common:E}=this._core;let m;try{m=yield function(P,W){return pA(this,void 0,void 0,function*(){const{type:iA,startTime:EA,limit:RA,handleAccount:kA}=P,xA={Type:iA,StartTime:EA,Limit:RA,Handle_Account:kA};return W.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_pendency",data:xA})})}({type:n,startTime:g,limit:u,handleAccount:E.getCurrentUserID()},this._core)}catch(P){if(P?.errorCode!==11e3)throw P;m={}}const{NextStartTime:D=0,PendencyList:M=[]}=m||{};if(D===0)return M;const T=yield this._getGroupApplicationList(Object.assign(Object.assign({},s),{startTime:D}));return[...M,...T]})}_handleGroupApplicationResult(s){const n=[];return s.forEach(g=>{const u=this._convertApplicationData(g),{handled:E}=u,m=Do(u,["handled"]);E===0&&n.push(m)}),n}_convertApplicationData(s){const{Handled:n,AddTime:g,ApplyInviteMsg:u,Authentication:E,FromUserNickName:m,From_Account:D,GroupId:M,GroupName:T,PendencyType:P,To_Account:W}=s;return{handled:n,messageKey:g,applicant:D,applicantNick:m,groupID:M,groupName:T,authentication:E,applicationType:P,userID:W,note:u,addTime:g}}},Vv=new class{constructor(){this._name="HandleGroupApplication"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"handleGroupApplication",context:this})}handleGroupApplication(s){return pA(this,void 0,void 0,function*(){const{application:n}=s,g=this._handleParams(s);try{n?.applicationType===Uc?yield function(E,m){return pA(this,void 0,void 0,function*(){const{groupID:D,handleAction:M,handleMessage:T,applicant:P,authentication:W,invitee:iA}=E,EA={GroupId:D,HandleMsg:M,ApprovalMsg:T,Applicant_Account:P,Authentication:W,Invited_Account:iA};return m.common.buildAndSendPacket({servcmd:"group_open_http_svc.handle_invite_join_permission_group",data:EA})})}(g,this._core):yield function(E,m){return pA(this,void 0,void 0,function*(){const{groupID:D,handleAction:M,handleMessage:T,applicant:P,authentication:W,messageKey:iA}=E,EA={GroupId:D,HandleMsg:M,ApprovalMsg:T,Applicant_Account:P,Authentication:W,MsgKey:iA};return m.common.buildAndSendPacket({servcmd:"group_open_http_svc.handle_apply_join_group",data:EA})})}(g,this._core);const u=Yi.getLocalGroup(g.groupID);return dn({group:u})}catch(u){throw new this._core.helper.ChatError({functionName:"handleGroupApplication",code:u?.errorCode,message:u?.errorInfo})}})}_handleParams(s){var n;const{handleAction:g,handleMessage:u,message:E,application:m}=s;let D,M,T,P,W;if(E){const{payload:iA}=E||{};D=iA.operatorID,M=(n=iA.groupProfile)===null||n===void 0?void 0:n.groupID,T=iA.authentication,P=iA.messageKey}else D=m?.applicant||"",M=m?.groupID||"",T=m?.authentication||"",P=m?.messageKey||0;return m?.applicationType===Uc&&(W=m.userID),{handleAction:g,handleMessage:u,applicant:D,invitee:W,groupID:M,authentication:T,messageKey:P}}},dD=new class{init(s){s.ssoLog.debug("GroupApplication.init"),Yv.init(s),Vv.init(s)}};let yC=class{constructor(s){this.userID="",this.avatar="",this.nick="",this.role="",this.joinTime="",this.nameCard="",this.muteUntil=0,this.memberCustomField=[],this.isOnline=!1,this.updateMember(s)}updateMember(s){const{core:{utils:{isUndefined:n},common:{deepMerge:g}}}=Wn;n(s.muteTime)||(this.muteUntil=Math.floor((Date.now()+1e3*s.muteTime)/1e3)),n(s.onlineStatus)||(this.isOnline=s.onlineStatus==="Online");const u=[null,void 0,"",0,NaN];s.memberCustomField&&_m(this.memberCustomField,s.memberCustomField),g(this,s,["memberCustomField","marks","onlineStatus","muteTime"],u)}};function cB(s,n){return pA(this,void 0,void 0,function*(){const{groupID:g,userID:u,muteTime:E,role:m,nameCard:D,memberCustomField:M}=s;let T;M&&(T=OE(M));const P={GroupId:g,Member_Account:u,ShutUpTime:E,Role:m,NameCard:D,AppMemberDefinedData:T};return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:P})})}var CD=new class{constructor(){this._name="GetGroupMemberList"}init(s,n){this._core=s;const{helper:g}=s;g.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>!n.getInstalledSubPlugins().includes(ta)})}getGroupMemberList(s){return pA(this,void 0,void 0,function*(){const n="getGroupMemberList",{groupID:g,offset:u=0,count:E=100,role:m="",filter:D=""}=s,M=Yi.getLocalGroup(g),T=E>100?100:E,P={groupID:g,offset:u,limit:T,memberRoleFilter:Hu.includes(m)?[m]:void 0,memberInfoFilter:mm};try{const W=yield function(se,_i){return pA(this,void 0,void 0,function*(){const{isCommunity:Ti}=_i.common,{groupID:Lt,offset:Ni,limit:cs,memberRoleFilter:Se,memberInfoFilter:mt}=se,UA={GroupId:Lt,Limit:cs,MemberRoleFilter:Se,MemberInfoFilter:mt};return Ti({groupID:Lt})?UA.Next=String(Ni):UA.Offset=Ni,_i.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_member_info",data:UA})})}(P,this._core),{MemberList:iA,MemberNum:EA,Next:RA}=W||{},kA=`${this._name}.${n} ok, totalMemberCount:${EA} next:${RA}`,{utils:{isArray:xA,isEmpty:LA},common:{isCommunity:SA}}=this._core;if(M&&(M.memberCount=EA),!xA(iA)||iA.length===0)return dn({memberList:[],offset:0},{message:kA});let OA=u+T;SA({groupID:g})&&(OA=LA(RA)?0:RA),iA.lengthD.userID),u=yield(n=this._core.user.userProfile)===null||n===void 0?void 0:n.getUserProfile({userIDList:g}),E=u?.data||[],m=new Map(E.map(D=>[D.userID,D]));return s.forEach(D=>{if(m.has(D.userID)){const{nick:M="",avatar:T=""}=m.get(D.userID);D.nick=M,D.avatar=T}}),s})}_generateGroupMember(s){const n=[];for(let g=0,u=s.length;g50&&(T.warn("getGroupMemberProfile",`${this._name}.${n} userIDList length:${u.length} exceeds limit 50`),u.splice(50));const P=`userIDList length:${u.length} groupID:${g}`;try{const W=yield function(kA,xA){return pA(this,void 0,void 0,function*(){const{groupID:LA,userIDList:SA,memberInfoFilter:OA,memberCustomFieldFilter:JA}=kA,ne={GroupId:LA,Member_List_Account:SA,MemberInfoFilter:OA,AppDefinedDataFilter_GroupMember:JA};return xA.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_specified_group_member_info",data:ne})})}({groupID:g,userIDList:u,memberCustomFieldFilter:E,memberInfoFilter:[...mm]},this._core),{MemberList:iA}=W||{};if(!M(iA)||iA.length===0)return dn({memberList:[]});let EA=this._convertMemberInfo(iA);EA=yield this._getMemberAvatarAndNick(EA);const RA=this._generateGroupMember(EA);return dn({memberList:RA},{message:P})}catch(W){throw new D.ChatError({functionName:n,code:W?.errorCode,message:W?.errorInfo,moreMessage:P})}})}_convertMemberInfo(s){const n=[];for(let g=0,u=s.length;gD.userID),u=yield(n=this._core.user.userProfile)===null||n===void 0?void 0:n.getUserProfile({userIDList:g}),E=u?.data||[],m=new Map(E.map(D=>[D.userID,D]));return s.forEach(D=>{if(m.has(D.userID)){const{nick:M="",avatar:T=""}=m.get(D.userID);D.nick=M,D.avatar=T}}),s})}_generateGroupMember(s){const n=[];for(let g=0,u=s.length;g({Member_Account:M}));try{const M=yield function(RA,kA){return pA(this,void 0,void 0,function*(){const{groupID:xA,userIDList:LA}=RA,SA={GroupId:xA,MemberList:LA};return kA.common.buildAndSendPacket({servcmd:"group_open_http_svc.add_group_member",data:SA})})}({groupID:g,userIDList:D},this._core),{MemberList:T=[]}=M||{},{failureUserIDList:P,successUserIDList:W,existedUserIDList:iA,overLimitUserIDList:EA}=this._handleResult(T);return dn({failureUserIDList:P,successUserIDList:W,existedUserIDList:iA,overLimitUserIDList:EA,group:E},{message:` groupID:${g} successUserIDList:${W} failureUserIDList:${P} existedUserIDList:${iA} overLimitUserIDList:${EA}`})}catch(M){throw new m.ChatError({functionName:n,code:M?.errorCode,message:M?.errorInfo})}})}_handleResult(s){const n=[],g=[],u=[],E=[];return s.forEach(m=>{const{Result:D,Member_Account:M}=m;D===fm?n.push(M):D===ym?g.push(M):D===Dm?u.push(M):D===sD&&E.push(M)}),{failureUserIDList:n,successUserIDList:g,existedUserIDList:u,overLimitUserIDList:E}}},vd=new class{constructor(){this._name="DeleteGroupMember"}init(s,n){this._core=s;const{helper:g}=s;g.registerApi({apiName:"deleteGroupMember",context:this,matcher:()=>!n.getInstalledSubPlugins().includes(ta)})}deleteGroupMember(s){return pA(this,void 0,void 0,function*(){const n="deleteGroupMember",{groupID:g,userIDList:u}=s,E=Yi.getLocalGroup(g),{helper:m,utils:{isUndefined:D},ssoLog:M}=this._core;if(D(E))throw new m.ChatError({functionName:n,code:mT});u.length>20&&(M.warn("deleteGroupMember",`${this._name}.${n} userIDList length:${u.length} exceeds limit 20`),u.splice(20));try{return yield function(T,P){return pA(this,void 0,void 0,function*(){const{groupID:W,userIDList:iA,reason:EA}=T,RA={GroupId:W,MemberToDel_Account:iA,Reason:EA};return P.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_member",data:RA})})}({groupID:g,userIDList:u},this._core),dn({group:E,userIDList:u},{message:`groupID:${g} userIDList length:${u.length}`})}catch(T){throw new m.ChatError({functionName:n,code:T?.errorCode,message:T?.errorInfo})}})}},Jv=new class{constructor(){this._name="SetGroupMemberMuteTime"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"setGroupMemberMuteTime",context:this})}setGroupMemberMuteTime(s){return pA(this,void 0,void 0,function*(){const{helper:n}=this._core,{groupID:g,userID:u,muteTime:E}=s,m=` groupID:${g} userID:${u} muteTime:${E}`;this._preCheckSettingMuteParams(s);try{yield cB(s,this._core);const D=Yi.getLocalGroup(g),M=new yC({userID:u,muteTime:E});return dn({group:D,member:M},{message:m})}catch(D){throw new n.ChatError({functionName:"setGroupMemberMuteTime",code:D?.errorCode,message:D?.errorInfo,moreMessage:m})}})}_preCheckSettingMuteParams(s){const{userID:n}=s,{store:g,helper:u}=this._core;if(n===g.get("login").userId)throw new u.ChatError({functionName:"setGroupMemberMuteTime",code:ED})}},kQ=new class{constructor(){this._name="SetGroupMemberRole"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"setGroupMemberRole",context:this})}setGroupMemberRole(s){return pA(this,void 0,void 0,function*(){const n="setGroupMemberRole",{helper:g}=this._core,{groupID:u,userID:E,role:m}=s,D=`${this._name}.${n} ok, groupID:${u} userID:${E} role:${m}`;this._preCheckSettingRoleParams(s);try{yield cB(s,this._core);const M=Yi.getLocalGroup(u),T=new yC({userID:E,role:m});return dn({group:M,member:T},{message:D})}catch(M){throw new g.ChatError({functionName:n,code:M?.errorCode,message:M?.errorInfo,moreMessage:D})}})}_preCheckSettingRoleParams(s){var n;const{groupID:g,userID:u,role:E}=s,{store:m,helper:D,OuterConstant:M,common:{isCommunity:T}}=this._core,P=Yi.getLocalGroup(g);if(((n=P?.selfInfo)===null||n===void 0?void 0:n.role)!==M.GRP_MBR_ROLE_OWNER)throw new D.ChatError({functionName:"setGroupMemberRole",code:DT});if(u===m.get("login").userId)throw new D.ChatError({functionName:"setGroupMemberRole",code:Fv});const W=[...Hu];if(T({groupID:g})&&W.push(M.GRP_MBR_ROLE_CUSTOM),!W.includes(E))throw new D.ChatError({functionName:"setGroupMemberRole",code:Rm})}},hD=new class{constructor(){this._name="SetGroupMemberNameCard"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"setGroupMemberNameCard",context:this})}setGroupMemberNameCard(s){return pA(this,void 0,void 0,function*(){var n;const g="setGroupMemberNameCard",{helper:u,common:{getCurrentUserID:E}}=this._core,{groupID:m,userID:D=E(),nameCard:M}=s,T=`${this._name}.${g} ok, groupID:${m} userID:${D} nameCard:${M}`;this._preCheckSettingNameCardParams(s);try{yield cB({groupID:m,userID:D,nameCard:M},this._core);const W=Yi.getLocalGroup(m);D===((n=W?.selfInfo)===null||n===void 0?void 0:n.userID)&&(W.updateSelfInfo({nameCard:M}),Yi.emitGroupListUpdate(),Yi.updateConversationGroupProfile(m));const iA=new yC({userID:D,nameCard:M});return dn({group:W,member:iA},{message:T})}catch(P){throw new u.ChatError({functionName:g,code:P?.errorCode,message:P?.errorInfo,moreMessage:T})}})}_preCheckSettingNameCardParams(s){const{groupID:n}=s,{helper:g}=this._core,u=Yi.getLocalGroup(n);if(Dd(u?.type))throw new g.ChatError({functionName:"setGroupMemberNameCard",code:wm})}},Gm=new class{constructor(){this._name="SetGroupMemberCustomField"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"setGroupMemberCustomField",context:this})}setGroupMemberCustomField(s){return pA(this,void 0,void 0,function*(){const n="setGroupMemberCustomField",{helper:g,common:{getCurrentUserID:u}}=this._core;this._preCheckSettingCustomFiledParams(s);const{groupID:E,userID:m=u(),memberCustomField:D}=s,M=`${this._name}.${n} ok, groupID:${E}userID:${m} memberCustomField:${JSON.stringify(D)}`;try{yield cB({groupID:E,userID:m,memberCustomField:D},this._core);const P=Yi.getLocalGroup(E),W=new yC({userID:m,memberCustomField:D});return dn({group:P,member:W},{message:M})}catch(T){throw new g.ChatError({functionName:n,code:T?.errorCode,message:T?.errorInfo,moreMessage:M})}})}_preCheckSettingCustomFiledParams(s){const{groupID:n}=s,{helper:g}=this._core,u=Yi.getLocalGroup(n);if(Dd(u?.type))throw new g.ChatError({functionName:"setGroupMemberCustomField",code:wm})}},Hv=new class{init(s,n){s.ssoLog.debug("GroupMember.init"),CD.init(s,n),bQ.init(s),Md.init(s),vd.init(s,n),Jv.init(s),kQ.init(s),hD.init(s),Gm.init(s)}getGroupMemberList(s){return CD.getGroupMemberList(s)}deleteGroupMember(s){return vd.deleteGroupMember(s)}},wT=new class{init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"getGroupCounters",context:this})}getGroupCounters(s){return pA(this,void 0,void 0,function*(){const n="getGroupCounters";try{Tm(n,sc);const{groupID:g,keyList:u=[]}=s,{avChatRoomKey:E,lastUpdateTime:m}=nc.getLocalGroupCounters(g);if(!(Date.now()-m>=this._getExpireTime()))return{code:0,data:{counters:nc.getLocalCounters(g,u)}};const D=yield function(P){return pA(this,void 0,void 0,function*(){const{groupID:W,GroupCounterKeys:iA,avChatRoomKey:EA}=P,{common:RA}=Wn.core,kA={GroupId:W,keyList:iA,BytesKey:EA};return RA.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_counter",data:kA})})}({groupID:g,keyList:u,avChatRoomKey:E}),{GroupCounter:M=[],GroupCounterSeq:T}=D;return nc.updateLocalGroupCounters({groupID:g,counterList:M,groupCounterSeq:T}),{code:0,data:{counters:nc.getLocalCounters(g,u)}}}catch(g){fC(n,g)}})}_getExpireTime(){const{store:s,utils:{isUndefined:n}}=this._core,g=s.get("cloudConfig")||{},{grp_counter_expire_time:u}=g;return n(u)?3e4:Number(u)}},bm=new class{init(s){const{helper:n}=s;n.registerApi({apiName:"setGroupCounters",context:this}),n.registerApi({apiName:"increaseGroupCounter",context:this}),n.registerApi({apiName:"decreaseGroupCounter",context:this})}setGroupCounters(s){return pA(this,void 0,void 0,function*(){return this._handleCounterOperation(Ju,s)})}increaseGroupCounter(s){return pA(this,void 0,void 0,function*(){return this._handleCounterOperation(pm,s)})}decreaseGroupCounter(s){return pA(this,void 0,void 0,function*(){return this._handleCounterOperation(Ri,s)})}_handleCounterOperation(s,n){return pA(this,void 0,void 0,function*(){const g=`${s}GroupCounter`;try{Tm(g,sc);const{groupID:u,key:E,value:m=0}=n,{avChatRoomKey:D}=nc.getLocalGroupCounters(u),M=s===Ju?this._convertObjectToList(n.counters):[{Key:E,Value:m}],T=yield this._updateGroupCounters({groupID:u,counterList:M,avChatRoomKey:D,mode:s});return nc.setGroupCounters(u,T),{code:0,data:{counters:T}}}catch(u){fC(g,u)}})}_updateGroupCounters(s){return pA(this,void 0,void 0,function*(){const n=yield function(E){const{groupID:m,counterList:D,mode:M,avChatRoomKey:T}=E,{common:P}=Wn.core,W={GroupId:m,GroupCounter:D,Mode:M,BytesKey:T};return P.buildAndSendPacket({servcmd:"group_open_http_svc.update_group_counter",data:W})}(s),{GroupCounter:g=[]}=n,u={};return g.forEach(E=>{const{Key:m,Value:D=0}=E;u[m]=D}),u})}_convertObjectToList(s){return Object.entries(s).map(([n,g])=>({Key:n,Value:g||0}))}},lB=new class{init(s){this._core=s,wT.init(s),bm.init(s)}isGroupCounterUpdated(s){const{elements:{groupCounterInfo:n}}=s,{utils:{isEmpty:g}}=this._core;return!g(n)}handleGroupCounterUpdated(s){const{to:n,elements:{groupCounterInfo:g}}=s;g.forEach(u=>{const{type:E,groupCounterSeq:m,counterList:D=[]}=u;E!==ii&&E!==on||this._processAndNotifyCounterUpdate(n,m,D),E===yo&&nc.deleteLocalGroupCounters({groupID:n,groupCounterSeq:m,counterList:D})})}_processAndNotifyCounterUpdate(s,n,g){const{OuterEvent:u,notificationCenter:E}=this._core;nc.updateLocalGroupCounters({groupID:s,groupCounterSeq:n,counterList:g}),g.forEach(({Key:m,Value:D=0})=>{E.emitOuterEvent(u.GROUP_COUNTER_UPDATED,{name:u.GROUP_COUNTER_UPDATED,data:{groupID:s,key:m,value:D}})})}reset(){nc.reset()}},km=new class{constructor(){this._name="InitGroupAttributes"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"initGroupAttributes",context:this})}initGroupAttributes(s){return pA(this,void 0,void 0,function*(){const{groupID:n,groupAttributes:g}=s,{serverMainSequence:u,avChatRoomKey:E}=zs.getGroupAttributesCache(n),m=zs.convertKeyValueMapToList(g);try{const D=yield function(W,iA){return pA(this,void 0,void 0,function*(){const{groupID:EA,mainSequence:RA,groupAttributeList:kA,avChatRoomKey:xA}=W,LA={GroupId:EA,AttrMainSeq:RA,GroupAttr:kA,BytesKey:xA,AttrControl:["RaceConflict"]};return iA.common.buildAndSendPacket({servcmd:"group_open_http_svc.set_group_attr",data:LA})})}({groupID:n,avChatRoomKey:E,groupAttributeList:m,mainSequence:u},this._core),{AttrMainSeq:M,GroupAttr:T}=D||{},P=T.map(W=>{const{Key:iA,seq:EA}=W;return{key:iA,value:g[iA],sequence:EA}});return zs.saveGroupAttributesCacheValuesCopy(n),zs.refreshGroupAttributesCache({groupID:n,serverMainSequence:M,groupAttributeList:P,operation:nD}),zs.emitGroupAttributesUpdated(n),dn({groupAttributes:g},{message:` groupID:${n} serverMainSequence:${M}`})}catch(D){throw new this._core.helper.ChatError({functionName:"initGroupAttributes",code:D?.errorCode,message:D?.errorInfo})}})}},_T=new class{constructor(){this._name="SetGroupAttributes"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"setGroupAttributes",context:this}),n.registerExperimentalAPI("setRichStatus",this)}setGroupAttributes(s){return pA(this,void 0,void 0,function*(){const{groupID:n,groupAttributes:g,richStatusMode:u}=s,{serverMainSequence:E,avChatRoomKey:m,values:D}=zs.getGroupAttributesCache(n),M=zs.convertKeyValueMapToList(g).map(T=>{var P;const{key:W,value:iA}=T;return{key:W,value:iA,seq:((P=D.get(T.key))===null||P===void 0?void 0:P.sequence)||0}});try{const T=yield function(EA,RA){return pA(this,void 0,void 0,function*(){const{groupID:kA,mainSequence:xA,groupAttributeList:LA,avChatRoomKey:SA,richStatusMode:OA}=EA,JA={GroupId:kA,AttrMainSeq:xA,GroupAttr:LA,BytesKey:SA,AttrControl:["RaceConflict"],AllowRoomEngineOpt:OA};return RA.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_attr",data:JA})})}({groupID:n,avChatRoomKey:m,groupAttributeList:M,mainSequence:E,richStatusMode:u},this._core),{AttrMainSeq:P,GroupAttr:W}=T||{},iA=W.map(EA=>{const{Key:RA,seq:kA}=EA;return{key:RA,value:g[RA],sequence:kA}});return zs.saveGroupAttributesCacheValuesCopy(n),zs.refreshGroupAttributesCache({groupID:n,serverMainSequence:P,groupAttributeList:iA,operation:bv}),zs.emitGroupAttributesUpdated(n),dn({groupAttributes:g},{message:` groupID:${n} serverMainSequence:${P}`})}catch(T){throw new this._core.helper.ChatError({functionName:"setGroupAttributes",code:T?.errorCode,message:T?.errorInfo})}})}setRichStatus(s){return pA(this,void 0,void 0,function*(){const{groupID:n,richStatus:g}=s;return this.setGroupAttributes({groupID:n,groupAttributes:g,richStatusMode:!0})})}},BD=new class{constructor(){this._name="DeleteGroupAttributes"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"deleteGroupAttributes",context:this}),n.registerExperimentalAPI("deleteRichStatus",this)}deleteGroupAttributes(s){return pA(this,void 0,void 0,function*(){const n="deleteGroupAttributes",{groupID:g,keyList:u=[],richStatusMode:E}=s;try{let m;m=u.length===0?yield this._clearGroupAttributes(g,{richStatusMode:E}):yield this._deleteGroupAttributes(g,{keyList:u,richStatusMode:E});const{resultList:D,serverMainSequence:M,operation:T,groupAttributeList:P}=m||{},W=`${this._name}.${n} ok. groupID:${g} operation: ${T}`;return zs.saveGroupAttributesCacheValuesCopy(g),zs.refreshGroupAttributesCache({groupID:g,serverMainSequence:M,groupAttributeList:P,operation:T}),zs.emitGroupAttributesUpdated(g),dn({keyList:D},{message:W})}catch(m){throw new this._core.helper.ChatError({functionName:n,code:m?.errorCode,message:m?.errorInfo})}})}deleteRichStatus(s){return pA(this,void 0,void 0,function*(){return this.deleteGroupAttributes(Object.assign(Object.assign({},s),{richStatusMode:!0}))})}_deleteGroupAttributes(s,n){return pA(this,void 0,void 0,function*(){const{serverMainSequence:g,avChatRoomKey:u,values:E}=zs.getGroupAttributesCache(s),{keyList:m,richStatusMode:D}=n,M=[],T=[];m.forEach(iA=>{if(E.has(iA)){const{sequence:EA=0}=E.get(iA)||{};T.push({key:iA,seq:EA}),M.push(iA)}});const P=yield function(iA,EA){return pA(this,void 0,void 0,function*(){const{groupID:RA,mainSequence:kA,groupAttributeList:xA,avChatRoomKey:LA,richStatusMode:SA}=iA,OA={GroupId:RA,AttrMainSeq:kA,GroupAttr:xA,BytesKey:LA,AttrControl:["RaceConflict"],AllowRoomEngineOpt:SA};return EA.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_attr",data:OA})})}({groupID:s,avChatRoomKey:u,groupAttributeList:T,mainSequence:g,richStatusMode:D},this._core),{AttrMainSeq:W}=P||{};return{resultList:M,serverMainSequence:W,groupAttributeList:T,operation:aD}})}_clearGroupAttributes(s,n){return pA(this,void 0,void 0,function*(){const{serverMainSequence:g,avChatRoomKey:u,values:E}=zs.getGroupAttributesCache(s),{richStatusMode:m}=n||{},D=[...E.keys()],M=yield function(P,W){return pA(this,void 0,void 0,function*(){const{groupID:iA,mainSequence:EA,avChatRoomKey:RA,richStatusMode:kA}=P,xA={GroupId:iA,AttrMainSeq:EA,BytesKey:RA,AttrControl:["RaceConflict"],AllowRoomEngineOpt:kA};return W.common.buildAndSendPacket({servcmd:"group_open_http_svc.clear_group_attr",data:xA})})}({groupID:s,avChatRoomKey:u,mainSequence:g,richStatusMode:m},this._core),{AttrMainSeq:T}=M||{};return{resultList:D,serverMainSequence:T,operation:rD}})}},QD=new class{constructor(){this._name="GetGroupAttributes"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"getGroupAttributes",context:this}),n.registerExperimentalAPI("getRichStatus",this,"getGroupAttributes")}getGroupAttributes(s){return pA(this,void 0,void 0,function*(){const{groupID:n}=s,{avChatRoomKey:g,lastUpdateTime:u,localMainSequence:E,serverMainSequence:m}=zs.getGroupAttributesCache(n),{helper:{ChatError:D}}=this._core,M=`groupID:${n} localMainSequence:${E} serverMainSequence:${m} keyList:${s.keyList}`;if(Date.now()-u>=3e4||E{const{key:iA,value:EA,seq:RA}=W;return{key:iA,value:EA,sequence:RA}});return zs.refreshGroupAttributesCache({groupID:u,serverMainSequence:M,groupAttributeList:P,operation:kv}),{serverGroupAttributeList:T}})}},LQ=new class{init(s){s.ssoLog.debug("GroupAttribute.init"),km.init(s),_T.init(s),BD.init(s),QD.init(s),zs.init(s)}isGroupAttributesUpdated(s){return zs.isGroupAttributesUpdated(s)}handleGroupAttributesUpdated(s){const{to:n,elements:{newGroupProfile:g}}=s,{groupAttributeOption:u}=g,{serverMainSequence:E,withChangedAttributeInfo:m}=u,{localMainSequence:D}=zs.getGroupAttributesCache(n),M=E-D;if(console.log(`GroupAttribute.handleGroupAttributesUpdated groupID:${n} withChangedAttributeInfo:${m} diffSequence:${M}`),M!==0)if(zs.saveGroupAttributesCacheValuesCopy(n),m!==1||M!==1){if(zs.hasGroupAttributesCache(n)){const{avChatRoomKey:T}=zs.getGroupAttributesCache(n);QD.getGroupAttributesFromServer({groupID:n,avChatRoomKey:T}).then(()=>{zs.emitGroupAttributesUpdated(n)}).catch(()=>{})}}else zs.handleGroupAttributesUpdated({groupID:n,groupAttributeOption:u})}reset(){zs.reset()}};function xE(s,n="tips"){const{ClientSeq:g,From_Account:u,MsgClientTime:E,MsgPriority:m,MsgRandom:D,MsgSeq:M,MsgTimeStamp:T,TinyId:P,ToGroupId:W,GroupInfo:iA,MsgBody:EA}=s,RA=function(kA){const{GroupCode:xA,GroupId:LA,GroupName:SA,GroupType:OA,MsgFrom_AccountExtraInfo:JA,From_Account:ne,To_Account:se}=kA;return{groupCode:xA,groupID:LA,groupName:SA,type:OA,messageFromAccountExtraInformation:JA,from:ne,to:se}}(iA);return{clientSequence:g,from:u,clientTime:E,priority:m,random:D,sequence:M,time:T,tinyID:P,to:W,groupProfile:RA,elements:n==="tips"?ju(EA):Eh(EA)}}function ju(s){const n={};return Object.keys(s).forEach(g=>{var u,E;switch(g){case"MemberNum":n.memberCount=s[g];break;case"OpType":n.operationType=s[g];break;case"Operator_Account":n.operatorID=s[g];break;case"List_Account":n.userIDList=s[g];break;case"MsgMemberExtraInfo":n.memberInfoList=(u=s[g])===null||u===void 0?void 0:u.map(m=>pD(m));break;case"MsgOperatorMemberExtraInfo":n.operatorInfo=pD(s[g]);break;case"MsgGroupNewInfo":n.newGroupProfile=function(m){const D={};return Object.keys(m).forEach(M=>{switch(M){case"GroupIntroduction":D.introduction=m[M];break;case"GroupName":D.groupName=m[M];break;case"GroupFaceUrl":D.avatar=m[M];break;case"GroupNotification":D.notification=m[M];break;case"ApplyJoinOption":D.joinOption=m[M];break;case"InviteJoinOption":D.inviteOption=m[M];break;case"ShutupAll":D.muteAllMembers=m[M];break;case"Owner_Account":D.ownerID=m[M];break;case"GroupAttrOption":D.groupAttributeOption=function(P){const{BytesChangedKeys:W,GroupAttrSeq:iA,OpType:EA,PushChangedAttrValFlag:RA,GroupAttrInfo:kA}=P,xA=kA.map(LA=>{const{Key:SA,Val:OA,SubKeySeq:JA}=LA;return{key:SA,value:OA,sequence:JA}});return{changedKeyList:W,groupAttributeList:xA,serverMainSequence:iA,operation:EA,withChangedAttributeInfo:RA}}(m[M]);break;case"MsgAppDefinedData":D.groupCustomField=(T=m[M])==null?void 0:T.map(P=>({key:P.Key,value:P.Value}));break;case"InviteOption":D.inviteOption=MT[m[M]]||m[M]}var T}),D}(s[g]);break;case"MsgMemberInfo":n.msgMemberInfo=(E=s[g])===null||E===void 0?void 0:E.map(m=>function(D){const{ShutupTime:M,User_Account:T}=D;return{muteTime:M,userID:T}}(m));break;case"OnlineMemberInfo":n.onlineMemberInfo=function(m){const{ExpireTime:D,OnlineMemberNum:M}=m;return{expireTime:D,onlineMemberNum:M}}(s[g]);break;case"GroupCounterInfo":n.groupCounterInfo=function(m){return m.map(D=>{const{GroupCounterSeq:M,GroupCounter:T,Type:P}=D;return{type:P,groupCounterSeq:M,counterList:T}})}(s[g])}}),n}function pD(s){const{ImageUrl:n,NickName:g,Role:u,UserId:E}=s;return{avatar:n,nick:g,role:u,userID:E}}function Eh(s){const n={};return Object.keys(s).forEach(g=>{switch(g){case"MsgKey":n.messageKey=s[g];break;case"Operator_Account":n.operatorID=s[g];break;case"ReportType":n.operationType=s[g];break;case"Authentication":n.authentication=s[g];break;case"MsgFlag":n.messageRemindType=s[g];break;case"UserDefinedField":n.userDefinedField=s[g];break;case"RemarkInfo":n.remarkInfo=s[g];break;case"BanDuration":n.duration=s[g];break;case"MuteTime":n.muteTime=s[g];break;case"MsgMemberExtraInfoList":n.inviteeInfoList=(u=s[g]||[])==null?void 0:u.map(E=>{const{UserId:m,ImageUrl:D,NickName:M}=E;return{userID:m,avatar:D,nick:M}});break;case"MemberList_Account":n.inviteeList=s[g]}var u}),n}class Lm{constructor(n){this.type=Wn.core.OuterConstant.MSG_GRP_TIP,this.content={},this._initContent(n)}static parseServerPushElement(n){const g=ju(n);return new Lm(g)}_initContent(n){Object.keys(n).forEach(g=>{switch(g){case"groupProfile":this._initGroupProfile(n[g]);break;case"operatorInfo":this._initOperatorInfo(n[g]);break;case"memberInfoList":case"msgMemberInfo":this._updateMemberList(n[g]);break;case"newGroupProfile":this._initNewGroupProfile(n[g]);break;case"memberExtraInfo":case"remarkInfo":case"onlineMemberInfo":break;default:this.content[g]=n[g]}}),this.content.userIDList||(this.content.userIDList=[this.content.operatorID])}_initGroupProfile(n){this.content.groupProfile={};const g=Object.keys(n);for(let u=0;u{n.forEach(u=>{g.userID===u.userID&&Object.assign(g,u)})}):this.content.memberList=n}_initNewGroupProfile(n){this.content.newGroupProfile={};const g=Object.keys(n);for(let u=0;u0&&this._handleGroupTipMessage(g),{conversationUpdateFieldList:u,messageList:g}}_emitGroupTipsEvent(s){var n;const{constants:{WORKFLOW_STEP:g}}=this._core,{messageList:u=[]}=((n=s?.result)===null||n===void 0?void 0:n[g.HANDLE_GROUP_TIPS_NOTIFICATION])||{};if(u.length>0){const{notificationCenter:E,OuterEvent:m}=this._core;E.emitOuterEvent(m.MESSAGE_RECEIVED,{name:m.MESSAGE_RECEIVED,data:u})}}_handleGroupTips(s,n=!0){const{Event:g,GroupTips:u}=s,E=new Map,m=[],D=[];for(let M=0,T=u.length;M{const{operationType:u}=g.payload;switch(u){case n.JOINED:this._handleNewMemberJoined(g);break;case n.QUITTED:this._handleMemberQuitted(g);break;case n.KICKED:this._handleMemberKicked(g);break;case n.GROUP_PROFILE_UPDATED:this._handleGroupProfileUpdated(g);break;case n.ADMIN_SET:this._handleMemberGrantAdmin(g);break;case n.ADMIN_CANCELED:this._handleMemberRevokeAdmin(g)}})}_handleNewMemberJoined(s){this._handleGroupMemberCountUpdated(s)}_handleMemberQuitted(s){this._handleGroupMemberCountUpdated(s)}_handleMemberKicked(s){this._handleGroupMemberCountUpdated(s)}_handleGroupProfileUpdated(s){var n;const{newGroupProfile:g,groupProfile:u,operatorInfo:E}=s.payload,{groupID:m}=u,D=Yi.getLocalGroup(m);Object.keys(g).forEach(T=>{switch(T){case"ownerID":this._handleGroupOwnerChanged(m,g);break;case"groupName":D.name=g[T];break;case"groupCustomField":Array.isArray(D[T])&&Array.isArray(g[T])?_m(D[T],g[T]):D[T]=g[T];break;default:D[T]=g[T]}});const{utils:{isUndefined:M}}=this._core;M(E)||((n=D?.selfInfo)===null||n===void 0?void 0:n.userID)!==E.userID||Object.keys(E).forEach(T=>{T==="nameCard"&&D.updateSelfInfo({nameCard:E[T]}),T==="role"&&this._updateSelfRole(D,E[T])}),Yi.emitGroupListUpdate(),Yi.updateConversationGroupProfile(m)}_handleGroupOwnerChanged(s,n){const{common:g,OuterConstant:u}=this._core,E=Yi.getLocalGroup(s),m=g.getCurrentUserID(),{ownerID:D}=n;m===D&&E.updateGroup({ownerID:D,selfInfo:{role:u.GRP_MBR_ROLE_OWNER}})}_updateSelfRole(s,n){const{OuterConstant:g}=this._core;let u=g.GRP_MBR_ROLE_MEMBER;n===CT?u=g.GRP_MBR_ROLE_OWNER:n===cD&&(u=g.GRP_MBR_ROLE_ADMIN),s.updateSelfInfo({role:u})}_handleGroupMemberCountUpdated(s){const{memberCount:n,groupProfile:{groupID:g}}=s.payload,u=Yi.getLocalGroup(g),{utils:{isNumber:E}}=this._core;u&&E(n)&&u.memberCount!==n&&(u.memberCount=n,Yi.emitGroupListUpdate(),Yi.updateConversationGroupProfile(g))}_handleGroupTipsRecover(s){const{utils:{isArray:n}}=this._core,{groupTipList:g}=s?.result||{};n(g)&&g.forEach(u=>{const{messageList:E}=this._handleGroupTips({Event:u.Event,GroupTips:[u]},!1);this._handleGroupTipMessage(E)})}_handleMemberGrantAdmin(s){const{OuterConstant:n}=this._core,{groupProfile:g,userIDList:u}=s.payload,E=this._core.common.getCurrentUserID(),{groupID:m}=g,D=Yi.getLocalGroup(m);D&&u.includes(E)&&(D.updateSelfInfo({role:n.GRP_MBR_ROLE_ADMIN}),Yi.emitGroupListUpdate(),Yi.updateConversationGroupProfile(m))}_handleMemberRevokeAdmin(s){const{OuterConstant:n}=this._core,{groupProfile:g,userIDList:u}=s.payload,E=this._core.common.getCurrentUserID(),{groupID:m}=g,D=Yi.getLocalGroup(m);D&&u.includes(E)&&(D.updateSelfInfo({role:n.GRP_MBR_ROLE_MEMBER}),Yi.emitGroupListUpdate(),Yi.updateConversationGroupProfile(m))}};class UQ{constructor(n){this.type=Wn.core.OuterConstant.MSG_GRP_SYS_NOTICE,this.content={},this._initContent(n)}static parseServerPushElement(n){const g=Eh(n);return new UQ(g)}_initContent(n){Object.keys(n).forEach(g=>{switch(g){case"remarkInfo":this.content.handleMessage=n[g];break;case"groupProfile":this._initGroupProfile(n[g]);break;case"memberInfoList":break;default:this.content[g]=n[g]}})}_initGroupProfile(n){this.content.groupProfile={};const g=Object.keys(n);for(let u=0;u0&&this._handleGroupSysTemMessage(g,E),g===!0&&E.length>0&&m.emitOuterEvent(D.MESSAGE_RECEIVED,{name:D.MESSAGE_RECEIVED,data:E})}_handleGroupSystemNotification(s,n){const g=[];let u={};for(let E=0;E0?[u]:[],messageList:g}}_assembleMessage(s){const{message:{messageFactory:n},OuterConstant:g,utils:{randomInt:u}}=this._core;s.flow="in",s.conversationType=g.CONV_SYSTEM,s.conversationSubType=s.groupProfile.type,s.conversationID=g.CONV_SYSTEM;const E=n.createMessage(s),m=new UQ(Object.assign(Object.assign({},s.elements),{groupProfile:Object.assign({},s.groupProfile)}));E.setElement(m),E.isSystemMessage=!0;const D=E.sequence===1&&E.random===1,M=E.sequence===2&&E.random===2;return(D||M)&&(E.sequence=u(),E.random=u(),E.generateMessageID()),E}_handleConversationOptions(s,n){const{OuterConstant:g}=this._core,u={conversationID:g.CONV_SYSTEM,unreadCount:0,type:g.CONV_SYSTEM,subType:s.conversationSubType,lastMessage:null};return n&&u.unreadCount++,u}_handleGroupSysTemMessage(s,n){s&&n.forEach(g=>{const{operationType:u}=g.payload;switch(u){case BT:this._handleGroupJoinResult(g);break;case Uv:this._handleMemberKicked(g);break;case QT:this._handleGroupDismissed(g);break;case pT:this._handleGroupInvitedResult(g);break;case lD:this._handleGroupQuitResult(g);break;case _Q:this._handleMessageRemindTypeSynced(g);break;case Sm:this._handleAVChatRoomMemberBanned(g)}})}_handleGroupJoinResult(s){const{groupProfile:n}=s.payload,{groupID:g,type:u}=n,E=Yi.hasLocalGroup(g);this._core.ssoLog.debug("_handleGroupJoinResult",` groupID:${g} type:${u} hasLocalGroup:${E}`),E||Dd(u)||(Yi.updateLocalGroup([Object.assign({},n)]),Yi.emitGroupListUpdate())}_handleMemberKicked(s){const{groupProfile:{groupID:n,type:g}}=s.payload;Yi.hasLocalGroup(n)&&this._deleteLocalGroup(n,g),this._updateConversationProfile(n,{unreadCount:0})}_handleGroupDismissed(s){const{groupProfile:{groupID:n,type:g}}=s.payload;Yi.hasLocalGroup(n)&&this._deleteLocalGroup(n,g),this._updateConversationProfile(n,{unreadCount:0})}_handleGroupInvitedResult(s){const{groupProfile:n}=s.payload,{groupID:g}=n,u=Yi.hasLocalGroup(g);this._core.ssoLog.debug("_handleGroupInvitedResult",` groupID:${g} hasLocalGroup:${u}`),u||Ol.getGroupProfile({groupID:g}).then(E=>{const{data:{group:m}}=E;Yi.updateLocalGroup([Object.assign({},m)]),Yi.emitGroupListUpdate()})}_handleGroupQuitResult(s){const{groupProfile:{groupID:n,type:g}}=s.payload,u=Yi.hasLocalGroup(n);this._core.ssoLog.debug("_handleGroupQuitResult",` groupID:${n} type:${g} hasLocalGroup:${u}`),u&&this._deleteLocalGroup(n,g),this._updateConversationProfile(n,{unreadCount:0})}_handleMessageRemindTypeSynced(s){const{groupProfile:{groupID:n},messageRemindType:g}=s.payload;this._updateConversationProfile(n,{messageRemindType:g})}_handleAVChatRoomMemberBanned(s){const{groupProfile:{groupID:n,type:g}}=s.payload;this._deleteLocalGroup(n,g)}_deleteLocalGroup(s,n){if(Dd(n)){const{appStore:{conversationStore:g},OuterConstant:{CONV_GROUP:u}}=this._core;g.deleteConversation(`${u}${s}`)}Yi.deleteLocalGroup(s),Yi.emitGroupListUpdate()}_updateConversationProfile(s,n){const{appStore:{conversationStore:g},OuterConstant:{CONV_GROUP:u}}=this._core,E=`${u}${s}`;g.getConversation(E)&&g.updateConversation(E,n)}},mD=new class{init(s){this._core=s,s.ssoLog.debug("GroupNotificationHandler.init"),qv.init(s),Kv.init(s);const{notificationCenter:n,InnerEvent:g}=s,{InnerEventSubType:u}=n;n.subscribeInnerEvent(g.MESSAGE_PUSH,u.GROUP_TIPS_NOTIFICATION,this._onNewGroupTipsNotification,this),n.subscribeInnerEvent(g.MESSAGE_PUSH,u.GROUP_SYSTEM_NOTIFICATION,this._onNewGroupSystemNotification,this),n.subscribeInnerEvent(g.DESTROY,this._dispose,this)}_onNewGroupTipsNotification(s){const{common:{workflowManager:n},constants:{WORKFLOW_NAME:g}}=this._core;n.executeWorkflow(g.RECEIVE_GROUP_TIPS_NOTIFICATION,s)}_onNewGroupSystemNotification(s){Kv.onNewGroupSystemNotification(s)}_dispose(){const{notificationCenter:s,InnerEvent:n}=this._core,{InnerEventSubType:g}=s;s.unSubscribeInnerEvent(n.MESSAGE_PUSH,g.GROUP_TIPS_NOTIFICATION,this._onNewGroupTipsNotification,this),s.unSubscribeInnerEvent(n.MESSAGE_PUSH,g.GROUP_SYSTEM_NOTIFICATION,this._onNewGroupSystemNotification,this)}};const vn={required:!0,rules:["string"],allowEmpty:!1},FQ={required:!0,rules:["number"],allowEmpty:!1},Rd={required:!0,rules:["array"],allowEmpty:!1},fD={required:!0,rules:["object"],allowEmpty:!1},TT={createGroup:{name:vn,type:vn},dismissGroup:[Object.assign({key:"groupID"},vn)],joinGroup:{groupID:vn,applyMessage:{required:!1,rules:["string"],allowEmpty:!0}},quitGroup:[Object.assign({key:"groupID"},vn)],searchGroupByID:[Object.assign({key:"groupID"},vn)],getGroupProfile:{groupID:vn,groupCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},updateGroupProfile:{groupID:vn,muteAllMembers:{required:!1,rules:["boolean"],allowEmpty:!1}},changeGroupOwner:{groupID:vn,newOwnerID:vn},getGroupOnlineMemberCount:[Object.assign({key:"groupID"},vn)],handleGroupApplication:{handleAction:vn},getGroupMemberList:{groupID:vn},getGroupMemberProfile:{groupID:vn,userIDList:Rd,memberCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},addGroupMember:{groupID:vn,userIDList:Rd},deleteGroupMember:{groupID:vn,userIDList:Rd},setGroupMemberMuteTime:{groupID:vn,userID:vn,muteTime:Object.assign(Object.assign({},FQ),{customValidator:s=>!(s<0)||"muteTime must be a non-negative number."})},setGroupMemberRole:{groupID:vn,userID:vn,role:vn},setGroupMemberNameCard:{groupID:vn,userID:{required:!1,rules:["string"],allowEmpty:!1},nameCard:vn},setGroupMemberCustomField:{groupID:vn,userID:{required:!1,rules:["string"],allowEmpty:!1},memberCustomField:Rd},markGroupMemberList:{groupID:vn,markType:Object.assign(Object.assign({},FQ),{customValidator:s=>!(s<1e3)||"markType must be greater than or equal to 1000."}),enableMark:{required:!0,rules:["boolean"],allowEmpty:!1},userIDList:Rd},initGroupAttributes:{groupID:vn,groupAttributes:fD},setGroupAttributes:{groupID:vn,groupAttributes:fD},deleteGroupAttributes:{groupID:vn,keyList:Object.assign(Object.assign({},Rd),{allowEmpty:!0})},getGroupAttributes:{groupID:vn,keyList:Object.assign(Object.assign({},Rd),{allowEmpty:!0})},getGroupCounters:{groupID:vn,keyList:{required:!1,rules:["array"],allowEmpty:!0}},setGroupCounters:{groupID:vn,counters:fD},increaseGroupCounter:{groupID:vn,key:vn,value:FQ},decreaseGroupCounter:{groupID:vn,key:vn,value:FQ}},NT={getGroupList:!0,createGroup:!0,dismissGroup:!0,joinGroup:!0,quitGroup:!0,searchGroupByID:!0,getGroupProfile:!0,updateGroupProfile:!0,changeGroupOwner:!0,getGroupOnlineMemberCount:!0,getGroupApplicationList:!0,handleGroupApplication:!0,getGroupMemberList:!0,getGroupMemberProfile:!0,addGroupMember:!0,deleteGroupMember:!0,setGroupMemberMuteTime:!0,setGroupMemberRole:!0,setGroupMemberNameCard:!0,setGroupMemberCustomField:!0,markGroupMemberList:!0,initGroupAttributes:!0,setGroupAttributes:!0,getGroupAttributes:!0,deleteGroupAttributes:!0,getGroupCounters:!0,setGroupCounters:!0,increaseGroupCounter:!0,decreaseGroupCounter:!0};var GT=new class{constructor(){this._installedSubPlugins=[],this.groupDataHandler=Yi,this.groupAction=GQ,this.groupAttribute=LQ,this.groupMember=Hv,this.groupCounter=lB,this.name="Group"}install(s,n=[]){this._core=s,Wn.init(s),Yi.init(s),GQ.init(s,this),Hv.init(s,this),dD.init(s),lB.init(s),LQ.init(s),mD.init(s),s.helper.registerValidateConfig({auth:NT,params:TT}),this._installSubPlugins(n);const{notificationCenter:g,InnerEvent:u}=s;g.subscribeInnerEvent(u.LOGOUT,this._reset,this),g.subscribeInnerEvent(u.DESTROY,this._dispose,this)}getInstalledSubPlugins(){return this._installedSubPlugins}_installSubPlugins(s){const{utils:{isArray:n}}=this._core;s&&n(s)&&s.forEach(g=>{var u;this._installedSubPlugins.includes(g.name)||((u=g.install)===null||u===void 0||u.call(g,this._core,this),this._installedSubPlugins.push(g.name))})}_reset(){Yi.reset(),LQ.reset(),lB.reset()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(n.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this)}};const IB=new class{init(s){this.core=s}},jv="AV_MBR_LIST",bT="AV_BAN_MBR",YE={NORMAL_MESSAGE:3,GROUP_TIPS_HAS_ROAMING:4,GROUP_SYSTEM_MESSAGE:5,GROUP_TIPS_HAS_NO_ROAMING:6,BROADCAST_MESSAGE:17,MESSAGE_REVOKED:20,MESSAGE_REACTION:21,LIVE_CUSTOM_DATA:100},dh={GROUP_DISMISSED:5,QUIT_GROUP:8,AVCHATROOM_MEMBER_BANNED:21},yD=60,DD=2603,kT=2686,LT=2688,OQ=3122;class Wv{constructor(n){const{core:g,manager:u,groupID:E,getRequestParams:m,onSuccess:D,onFail:M}=n;this._name="Polling",this._core=g,this._manager=u,this._timeoutID=-1,this._isRunning=!1,this._groupID=E,this._getRequestParams=m,this._onSuccess=D,this._onFail=M}start(){this._isRunning=!0,this._request(),console.log(`${this._name}.start pollingInterval:${this._manager.getCurrentPollingInterval(this._groupID)}`)}isRunning(){return this._isRunning}_request(){return pA(this,void 0,void 0,function*(){try{const n=this._getRequestParams(this._groupID),g=yield function(E,m){return pA(this,void 0,void 0,function*(){const{longPollingKey:D,startSequence:M,startBroadcastSeq:T,simplifiedMessage:P}=E,W={Key:D,StartSeq:M,StartBroadcastSeq:T,DownsizeFlag:P,USP:1,HoldTime:90};return m.common.buildAndSendPacket({servcmd:"group_open_long_polling_http_svc.get_msg",data:W})})}(n,this._core);this._onSuccess(this._groupID,g);const u=this._manager.getCurrentPollingInterval(this._groupID);this._runNextPolling(u)}catch(n){this._onFail(this._groupID,n),this._runNextPolling(2e3)}})}_runNextPolling(n){this.isRunning()&&(this._timeoutID>-1&&clearTimeout(this._timeoutID),this._timeoutID=setTimeout(this._request.bind(this),n))}stop(){console.log(`${this._name}.stop timerID:${this._timeoutID}`),this._timeoutID>-1&&(clearTimeout(this._timeoutID),this._timeoutID=-1),this._isRunning=!1}}class Ch{constructor(n){this._maxLength=n,this._map=new Map}set(n){var g;if(this._map.size>=this._maxLength){const u=((g=this._map.entries().next().value)===null||g===void 0?void 0:g[0])||"";this._map.delete(u)}this._map.set(n,1)}has(n){return this._map.has(n)}delete(n){this.has(n)&&this._map.delete(n)}clear(){this._map.clear()}}const Wu=s=>s===YE.GROUP_TIPS_HAS_NO_ROAMING||s===YE.GROUP_TIPS_HAS_ROAMING,PQ=s=>s===YE.GROUP_SYSTEM_MESSAGE;function Um(s){const n=function(g){const{E:u,MCT:E,MR:m,MP:D,MTS:M,GId:T,MS:P,CCD:W,F_Account:iA,IsSys:EA,GInf:RA,MsgBody:kA}=g,xA=Do(g,["E","MCT","MR","MP","MTS","GId","MS","CCD","F_Account","IsSys","GInf","MsgBody"]);return Object.assign({Event:u,MsgClientTime:E,MsgRandom:m,MsgPriority:D,MsgTimeStamp:M,ToGroupId:T,MsgSeq:P,CloudCustomData:W,From_Account:iA,IsSystemMsg:EA,GroupInfo:SD(RA),MsgBody:UT(kA)},xA)}(s);return function(g){const{Event:u}=g;(Wu(u)||PQ(u))&&(g.From_Account=g.From_Account||"@TIM#SYSTEM"),E=u,(E===YE.BROADCAST_MESSAGE||(m=>m===YE.NORMAL_MESSAGE)(u))&&function(m){const{core:{OuterConstant:D}}=IB;m.CloudCustomData=m.CloudCustomData||"",m.MsgBody=m.MsgBody.map(M=>{if(M.MsgType===D.MSG_CUSTOM){const{content:T={}}=M;M.content=Object.assign({Data:"",Desc:"",Ext:""},T)}return M})}(g);var E;Wu(u)&&function(m){const{GroupJoinType:D,MsgOperatorMemberExtraInfo:M={},MsgMemberExtraInfo:T,Operator_Account:P,List_Account:W,OpType:iA}=m.MsgBody||{};typeof D=="number"||iA!==1&&iA!==2||(m.MsgBody.GroupJoinType=iA===2?0:1),T||(m.MsgBody.MsgMemberExtraInfo=W?.map(EA=>({UserId:EA}))),iA!==1||T||(m.MsgBody.MsgMemberExtraInfo=[{UserId:M.UserId}]),m.MsgBody.MsgOperatorMemberExtraInfo=Object.assign({Operator_Account:P,ImageUrl:"",NickName:""},M)}(g),PQ(u)&&function(m){const{MsgOperatorMemberExtraInfo:D={},Operator_Account:M}=m.MsgBody||{};m.MsgBody.MsgMemberExtraInfo=Object.assign({UserId:M,ImageUrl:"",NickName:""},D),m.MsgBody=Object.assign({Authentication:"",RemarkInfo:"",MsgKey:1e3*m.MsgTimeStamp},m.MsgBody),m.MsgBody=Object.keys(m.MsgBody).filter(T=>T!=="MsgOperatorMemberExtraInfo").reduce((T,P)=>Object.assign(Object.assign({},T),{[P]:m.MsgBody[P]}),{})}(g)}(n),n}function SD(s){const n=s||{},{GN:g,GT:u,F_Hd:E,F_NN:m,F_Ll:D}=n,M=Do(n,["GN","GT","F_Hd","F_NN","F_Ll"]),T=Object.assign({GroupName:g,GroupType:u},M);return E&&(T.From_AccountHeadurl=E),m&&(T.From_AccountNick=m),D&&(T.From_AccountLevel=D),T}function UT(s){let n=s;Array.isArray(s)||(n=[s]);const g=n.map(u=>{const{O_Account:E,Opt:m,L_Account:D,RT:M,UDF:T,OpInf:P,OnlineInf:W,MsgMemberExtraInfo:iA}=u,EA=Do(u,["O_Account","Opt","L_Account","RT","UDF","OpInf","OnlineInf","MsgMemberExtraInfo"]),RA=Object.assign({Operator_Account:E,OpType:m,List_Account:D,ReportType:M,UserDefinedField:T},EA);return P&&(RA.MsgOperatorMemberExtraInfo=function(kA){const{Img:xA,NN:LA}=kA,SA=Do(kA,["Img","NN"]);return Object.assign({ImageUrl:xA,NickName:LA},SA)}(P)),iA&&(RA.MsgMemberExtraInfo=function(kA){return kA?.map(xA=>{const{Img:LA,NN:SA}=xA,OA=Do(xA,["Img","NN"]);return Object.assign({ImageUrl:LA,NickName:SA},OA)})}(iA)),W&&(RA.OnlineMemberInfo=function(kA){const{ET:xA,Num:LA}=kA;return{ExpireTime:xA,OnlineMemberNum:LA}}(W)),RA});return Array.isArray(s)?g:g[0]}var hh=new class{constructor(){this._name="MessageParser",this._sequenceList=new Ch(200),this._messageIDList=new Ch(100),this._broadcastMessageIDMap=new Map,this._reportMessageStackedCount=0}init(s,n){this._core=s,this._avChatRoomHandler=n}onMessageReceived(s,n,g=!1){this._sortServerMessageList({groupID:s,serverMessageList:n,isHistoryMessage:g});const u=this._handleMessageList(s,n);if(u.length===0)return;if(!g){const{appStore:{conversationStore:T},OuterConstant:{CONV_GROUP:P},common:{buildLastMessage:W}}=this._core,iA=W(u[u.length-1]);T.updateConversation(`${P}${s}`,{lastMessage:iA})}this._checkMessageStacked(u);const E=u.filter(T=>T.isModified===!0),m=u.filter(T=>T.isModified===!1),{OuterEvent:{MESSAGE_RECEIVED:D,MESSAGE_MODIFIED:M}}=this._core;E.length>0&&this._emitEvent({name:M,data:E}),m.length>0&&this._emitEvent({name:D,data:m})}_sortServerMessageList(s){const{groupID:n,serverMessageList:g,isHistoryMessage:u}=s;let E=[];this._avChatRoomHandler.isPollingSimplifiedMessage()&&!u?(g.sort((m,D)=>m.MS-D.MS),E=g.map(m=>m.MS)):(g.sort((m,D)=>m.MsgSeq-D.MsgSeq),E=g.map(m=>m.MsgSeq)),console.log(`${this._name}._sortServerMessageList groupID:${n} count:${E.length} sequenceList:${E}`),E.length=0}_handleMessageList(s,n){var g;const{message:{messageDataHandler:u,messageHelper:E}}=this._core,m=this._avChatRoomHandler.isPollingSimplifiedMessage(),D=[],M=n.length;for(let T=0;Tg===YE.MESSAGE_REVOKED)(n)?(this._handleMessageRevoked(s),null):(g=>g===YE.LIVE_CUSTOM_DATA)(n)?(this._onLiveCustomData(s),null):(g=>g===YE.MESSAGE_REACTION)(n)?null:s:(console.warn(`${this._name}.onMessageReceived unknown event:${n}`),null)}_createMessage(s){const{message:{messageFactory:n},OuterConstant:g}=this._core;let u=g.CONV_GROUP;s.elements.type===g.MSG_GRP_SYS_NOTICE&&(u=g.CONV_SYSTEM);const E=!!s.isSystemMessage,m=n.createMessage(Object.assign(Object.assign({},s),{conversationType:u,isSystemMessage:E,flow:"in"}));return m.setElement(s.elements),m}_filterDuplicateMessage(s){const{common:n}=this._core;if(!n.isUnlimitedAVChatRoom()){if(this._sequenceList.has(s.sequence))return null;this._sequenceList.set(s.sequence)}const g=this._messageIDList.has(s.ID);return g?(console.warn(`${this._name}_filterDuplicateMessageItem ID:${s.ID} has:${g}`),null):(this._messageIDList.set(s.ID),s)}_handleMessageRevoked(s){const{OuterConstant:n,OuterEvent:{MESSAGE_REVOKED:g}}=this._core,{ToGroupId:u,MsgBody:{RevokeMsgList:E},RevokerInfo:{Revoker_Account:m,Reason:D=""}}=s,M=[];E.forEach(T=>{const{TinyId:P,MsgClientTime:W,Random:iA,MsgSeq:EA}=T,RA={conversationID:`${n.CONV_GROUP}${u}`,ID:`${P}-${W}-${iA}`,revoker:m,revokeReason:D,revokerInfo:{userID:m,nick:"",avatar:""},sequence:EA};M.push(RA)}),M.length!==0&&this._emitEvent({name:g,data:M})}_onLiveCustomData(s){const{OuterEvent:{ROOM_CUSTOM_DATA_RECEIVED:n}}=this._core,{ToGroupId:g,MsgSeq:u,MsgTimeStamp:E,MsgBody:m}=s,D=m?.Content||m?.MsgContent||"";this._emitEvent({name:n,data:D}),console.log(`${this._name}._onLiveCustomData groupID:${g} sequence:${u} time:${E} data:${D}`)}_onGroupDismissed(s){this._avChatRoomHandler.reset(s)}_checkMessageStacked(s){const{length:n}=s;if(n>=100&&this._reportMessageStackedCount<5){const g=this._avChatRoomHandler.getJoinedGroups();this._core.ssoLog.info("MessageStacked",`count:${n} groupID:${g.join(",")}`),this._reportMessageStackedCount+=1}}_emitEvent(s){this._core.notificationCenter.emitOuterEvent(s.name,s)}onBroadcastMessageReceived(s){const{message:{messageHelper:n},OuterEvent:{MESSAGE_RECEIVED:g}}=this._core,u=this._avChatRoomHandler.isPollingSimplifiedMessage(),E=[],m=s.length;for(let D=0;D0&&this._emitEvent({name:g,data:E})}_updateLocalOnlineMemberCountFromTips(s){const{utils:{isEmpty:n}}=this._core,{ToGroupId:g,MsgBody:{OnlineMemberInfo:u}}=s;if(n(u))return;const{OnlineMemberNum:E=0,ExpireTime:m=yD}=u,D=Date.now();let M=this._avChatRoomHandler.getLocalOnlineMemberCount(g);n(M)?M={lastReqTime:0,lastSyncTime:0,latestUpdateTime:D,memberCount:E,expireTime:m}:(M.latestUpdateTime=D,M.memberCount=E),this._avChatRoomHandler.updateLocalOnlineMemberCount(g,M)}reset(){this._reportMessageStackedCount=0,this._sequenceList.clear(),this._messageIDList.clear(),this._broadcastMessageIDMap.clear()}};const uB=s=>{const{core:{store:n}}=IB;return(n.get("cloudConfig")||{})[s]},Bh=s=>{const{core:{utils:{isUndefined:n}}}=IB;return!n(s)},xQ=()=>{const s=uB("polling_interval");return Bh(s)?parseInt(s,10):300},EB=()=>{const s=uB("polling_simplified_msg");return Bh(s)?parseInt(s,10):0};var zv=new class{constructor(){this._name="GetAVChatRoomOnlineMemberCount"}init(s,n){this._core=s,this._parentPlugin=n;const{helper:g}=s;g.registerApi({apiName:"getGroupOnlineMemberCount",context:this,matcher:()=>n.getInstalledSubPlugins().length>0})}getGroupOnlineMemberCount(s){return pA(this,void 0,void 0,function*(){const{appStore:{groupStore:n},OuterConstant:g}=this._core,u=n.getGroup(s);return u?u.type===g.GRP_AVCHATROOM?this._getOnlineMemberCount(s):this._parentPlugin.groupAction.getGroupOnlineMemberCount(s):{code:0,data:{memberCount:0}}})}_getOnlineMemberCount(s){return pA(this,void 0,void 0,function*(){const n="_getOnlineMemberCount",{utils:{isEmpty:g}}=this._core,u=Pg.getLocalOnlineMemberCount(s);if(g(u)||this._isExpired(s)){const{memberCount:E=0}=yield this._getOnlineMemberCountFromServer(s);return console.log(`${this._name}.${n} ok, groupID:${s} memberCount:${E} from server.`),{code:0,data:{memberCount:E}}}return console.log(`${this._name}.${n} ok, groupID:${s} memberCount:${u.memberCount} from local.`),{code:0,data:{memberCount:u.memberCount}}})}_isExpired(s){const n=Pg.getLocalOnlineMemberCount(s),g=Date.now(),u=g-n.lastSyncTime>1e3*n.expireTime,E=g-n.latestUpdateTime>1e4,m=g-n.lastReqTime>3e3;return u&&E&&m}_getOnlineMemberCountFromServer(s){return pA(this,void 0,void 0,function*(){const n="_getOnlineMemberCountFromServer";try{const g=yield function(M,T){return pA(this,void 0,void 0,function*(){const P={GroupId:M};return T.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_online_member_num",data:P})})}(s,this._core),{OnlineMemberNum:u=0,ExpireTime:E=yD}=g||{},m=Date.now(),D={lastSyncTime:m,latestUpdateTime:m,lastReqTime:m,memberCount:u,expireTime:E};return Pg.updateLocalOnlineMemberCount(s,D),{memberCount:u}}catch(g){const u=new this._core.helper.ChatError({functionName:n,code:g?.errorCode,message:g?.errorInfo});throw console.error(`${this._name}.${n} fail:`,u),u}})}},Pg=new class{constructor(){this._name="AVChatRoomHandler",this._joinedGroupMap=new Map,this._pollingRequestInfoMap=new Map,this._pollingInstanceMap=new Map,this._onlineMemberCountMap=new Map,this._pollingIntervalMap=new Map,this._pollingNoMessageCountMap=new Map,this._membersReqInfoMap=new Map,this._startBroadcastSequence=1}init(s,n){this._core=s,this._parentPlugin=n,hh.init(s,this),s.ssoLog.debug("AVChatRoomHandler.init")}onAVChatRoomSystemNotification(s){const{OuterConstant:{GRP_AVCHATROOM:n}}=this._core,{GroupTips:g=[]}=s;for(let u=0;u0&&(n=[...this._joinedGroupMap.values()].filter(g=>g.type===s)),n}handleJoinGroupResult(s){return pA(this,void 0,void 0,function*(){const{utils:{isUndefined:n},OuterConstant:{CONV_GROUP:g},apiMap:{getConversationProfile:u},OuterConstant:E}=this._core,{longPollingKey:m,group:D,historyMessageList:M=[]}=s,{groupID:T}=D;return yield this._preCheck(D),this._joinedGroupMap.set(T,D),this._parentPlugin.groupDataHandler.updateLocalGroup([D]),this._parentPlugin.groupDataHandler.emitGroupListUpdate(),u(`${g}${T}`),zv.getGroupOnlineMemberCount(T),M.length>0&&hh.onMessageReceived(T,M,!0),n(m)?{code:0,data:{status:E.JOIN_STATUS_SUCCESS,group:D}}:{code:0,data:this.startMessageLongPolling(s)}})}isGroupCounterUpdated(s){return this._parentPlugin.groupCounter.isGroupCounterUpdated(s)}handleGroupCounterUpdated(s){this._parentPlugin.groupCounter.handleGroupCounterUpdated(s)}_preCheck(s){return pA(this,void 0,void 0,function*(){const{common:n,OuterConstant:g,helper:u,apiMap:{quitGroup:E},ssoLog:m}=this._core;if(n.isUnlimitedAVChatRoom()){if(this._pollingInstanceMap.size>(()=>{const T=uB("polling_count_limit");return Bh(T)&&T>0?parseInt(T,10):20})())throw new u.ChatError({code:LT,message:"the count of longPolling exceeds the max limit"});return}if(this._joinedAVChatRoomCount()===0||s.type===g.GRP_LIVE)return;const[D,M]=this._joinedGroupMap.entries().next().value;if(M.selfInfo.role===g.GRP_MBR_ROLE_OWNER)this._parentPlugin.groupDataHandler.deleteLocalGroup(D);else try{yield E(D)}catch(T){m.debug("quitGroup",`${this._name}._preCheck quitGroup failed, groupID:${D} info:`,T)}this.reset(D)})}startMessageLongPolling(s){const{OuterConstant:n}=this._core,{longPollingKey:g,startSequence:u=1,group:E}=s,{groupID:m}=E;return this._pollingRequestInfoMap.set(m,{longPollingKey:g,startSequence:u}),this._pollingIntervalMap.set(m,xQ()),this._startPolling(m),this._reportLongPollingCount(),{status:n.JOIN_STATUS_SUCCESS,group:E}}_startPolling(s){if(this._core.ssoLog.debug("_startPolling",`${this._name}._startPolling groupID:${s}`),this._pollingInstanceMap.has(s)){const g=this._pollingInstanceMap.get(s);return void(g?.isRunning()||g==null||g.start())}const n=new Wv({core:this._core,manager:this,groupID:s,getRequestParams:this._handleRequestParams.bind(this),onSuccess:this._handleSuccess.bind(this),onFail:this._handleFailure.bind(this)});n.start(),this._pollingInstanceMap.set(s,n)}_handleRequestParams(s){const{longPollingKey:n,startSequence:g}=this._pollingRequestInfoMap.get(s)||{};return s===[...this._pollingInstanceMap.keys()][0]?{longPollingKey:n,startSequence:g,startBroadcastSeq:this._startBroadcastSequence,simplifiedMessage:EB()}:{longPollingKey:n,startSequence:g,simplifiedMessage:EB()}}_handleSuccess(s,n){const{ErrorCode:g}=n;if(g!==0){const{longPollingKey:u,startSequence:E}=this._pollingRequestInfoMap.get(s)||{};return void console.warn(`${this._name}._handleSuccess groupID:${s} key:${u} startSeq:${E} errorCode:${g}`)}this._hasJoinedAVChatRoom(s)&&this._handleResponseData(s,n)}_handleResponseData(s,n){const{Key:g,NextSeq:u,NextBroadcastSeq:E,RspMsgList:m=[],RspBroadcastMsgList:D=[]}=n;if(g&&u&&this._pollingRequestInfoMap.set(s,{longPollingKey:g,startSequence:u}),E&&E>this._startBroadcastSequence&&(this._startBroadcastSequence=E),m.length>0)this._getPollingNoMessageCount(s)!==0&&(this._updatePollingNoMessageCount(s,0),this._pollingIntervalMap.set(s,xQ())),hh.onMessageReceived(s,m);else{let M=this._getPollingNoMessageCount(s);if(M+=1,this._updatePollingNoMessageCount(s,M),M===(()=>{const T=uB("polling_no_msg_count");return Bh(T)?parseInt(T,10):20})()){const T=xQ()+(()=>{const P=uB("polling_interval_plus");return Bh(P)?parseInt(P,10):2e3})();this._pollingIntervalMap.set(s,T)}}D.length>0&&hh.onBroadcastMessageReceived(D)}_handleFailure(s,n){const{ssoLog:g,utils:{safeStringify:u}}=this._core;g.warn("polling",`${this._name}._handleFailure groupID:${s} error: ${u(n)}`)}_joinedAVChatRoomCount(){const{OuterConstant:s}=this._core;let n=[];return this._joinedGroupMap.size>0&&(n=this.getJoinedGroups().filter(g=>g.type===s.GRP_AVCHATROOM)),n.length}_hasJoinedAVChatRoom(s){return this._joinedGroupMap.has(s)}getJoinedGroups(){return[...this._joinedGroupMap.values()]}updateLocalLiveGroup(s,n){this._joinedGroupMap.set(s,n),this._parentPlugin.groupDataHandler.updateLocalGroup([n])}handleLiveHistoryMessages(s,n){hh.onMessageReceived(s,n,!0)}isOverFrequencyLimit(s){if(!this._membersReqInfoMap.has(s))return this._membersReqInfoMap.set(s,{startTime:Date.now(),requestCount:1}),!1;let{startTime:n,requestCount:g}=this._membersReqInfoMap.get(s);const{interval:u,count:E}=(()=>{const m=uB("av_members_freq_limit");if(Bh(m)){const{interval:D,count:M}=JSON.parse(m);if(M>0&&D>0)return{interval:D,count:M}}return{interval:30,count:4}})();return Date.now()-n>1e3*u?(this._membersReqInfoMap.set(s,{startTime:Date.now(),requestCount:1}),!1):(g+=1,this._membersReqInfoMap.set(s,{startTime:n,requestCount:g}),g>E)}_stopPolling(s){if(this._core.ssoLog.debug("_stopPolling",`${this._name}._stopPolling groupID:${s}`),s){const{appStore:{conversationStore:n},OuterConstant:{CONV_GROUP:g}}=this._core;n.deleteConversation(`${g}${s}`);const u=this._pollingInstanceMap.get(s);return u?.stop(),this._parentPlugin.groupDataHandler.deleteLocalGroup(s),this._pollingInstanceMap.delete(s),this._pollingRequestInfoMap.delete(s),this._joinedGroupMap.delete(s),this._onlineMemberCountMap.delete(s),this._pollingIntervalMap.delete(s),this._pollingNoMessageCountMap.delete(s),void this._membersReqInfoMap.delete(s)}for(const n of this._pollingInstanceMap.values())n?.stop();this._pollingInstanceMap.clear(),this._pollingRequestInfoMap.clear(),this._joinedGroupMap.clear(),this._onlineMemberCountMap.clear(),this._pollingIntervalMap.clear(),this._pollingNoMessageCountMap.clear(),this._membersReqInfoMap.clear()}_updatePollingNoMessageCount(s,n){this._pollingNoMessageCountMap.set(s,n)}_getPollingNoMessageCount(s){return this._pollingNoMessageCountMap.get(s)||0}_reportLongPollingCount(){const s=this._joinedGroupMap.size;if(s>1){const{common:n,OuterConstant:g,ssoLog:u}=this._core,E=n.isUnlimitedAVChatRoom()?1:0,m=[],D=[];Array.from(this._joinedGroupMap.values()).forEach(({groupID:M,type:T})=>{T===g.GRP_LIVE?D.push(M):m.push(M)}),u.info("longPollingCount",String(s),{moreMessage:`av:${m.join(",")} live:${D.join(",")} code: ${E}`,eventType:29})}}reset(s){this._stopPolling(s),this._startBroadcastSequence=1,hh.reset()}},Zv=new class{init(s,n){this._core=s,this._parentPlugin=n;const{helper:g}=s;g.registerApi({apiName:"joinGroup",context:this,matcher:()=>n.getInstalledSubPlugins().length>0})}joinGroup(s){return pA(this,void 0,void 0,function*(){const{OuterConstant:n}=this._core,g=yield this._parentPlugin.groupAction.joinGroup(s),{data:{status:u,group:{type:E}}}=g;return E===n.GRP_AVCHATROOM?u===n.JOIN_STATUS_ALREADY_IN_GROUP?g:Pg.handleJoinGroupResult(g.data):g})}},FT=new class{init(s,n){this._core=s,this._parentPlugin=n;const{helper:g}=s;g.registerApi({apiName:"quitGroup",context:this,matcher:()=>n.getInstalledSubPlugins().length>0})}quitGroup(s){return pA(this,void 0,void 0,function*(){const{OuterConstant:n}=this._core,g=yield this._parentPlugin.groupAction.quitGroup(s),{data:{type:u}}=g;return u===n.GRP_AVCHATROOM&&Pg.reset(s),g})}},Xv=new class{init(s,n){this._core=s,this._parentPlugin=n;const{helper:g}=s;g.registerApi({apiName:"dismissGroup",context:this,matcher:()=>n.getInstalledSubPlugins().length>0})}dismissGroup(s){return pA(this,void 0,void 0,function*(){const{OuterConstant:n}=this._core,g=yield this._parentPlugin.groupAction.dismissGroup(s),{data:{type:u}}=g;return u===n.GRP_AVCHATROOM&&Pg.reset(s),g})}},Fm=new class{constructor(){this._name="GetAVChatRoomMemberList"}init(s,n){this._core=s,this._parentPlugin=n;const{helper:g}=s;g.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>n.getInstalledSubPlugins().length>0})}getGroupMemberList(s){return pA(this,void 0,void 0,function*(){const{appStore:{groupStore:n},helper:g,OuterConstant:u}=this._core,{groupID:E}=s,m=n.getGroup(E);if(m?.type===u.GRP_AVCHATROOM&&g.checkBusinessCapabilityBits(jv)){if(Pg.isOverFrequencyLimit(E))throw{code:2996,message:`Over frequency limit: get_members-${E}`};return this._getGroupMemberList(s)}return this._parentPlugin.groupMember.getGroupMemberList(s)})}_getGroupMemberList(s){return pA(this,void 0,void 0,function*(){const n="_getGroupMemberList",{helper:g}=this._core;try{const u=yield function(M,T){return pA(this,void 0,void 0,function*(){const{groupID:P,offset:W=0}=M,iA={GroupId:P,Timestamp:W};return T.common.buildAndSendPacket({servcmd:"group_open_avchatroom_http_svc.get_members",data:iA})})}(s,this._core),{MemberList:E=[],NextTimestamp:m=0}=u||{},D=this._handleMemberList(E);return console.log(`${this._name}.${n} ok, groupID:${s.groupID} count:${D.length} nextOffset:${m}`),{code:0,data:{memberList:D,offset:m}}}catch(u){const E=new g.ChatError({functionName:n,code:u?.errorCode,message:u?.errorInfo});throw console.error(`${this._name}.${n} fail:`,E),E}})}_handleMemberList(s){return s.map(n=>{const{Member_Account:g,NickName:u="",Avatar:E="",Remark:m="",JoinTime:D=0,Marks:M=[]}=n;return{userID:g,nick:u,avatar:E,remark:m,joinTime:D,marks:M,isOnline:!0}})}},Om=new class{constructor(){this._name="DeleteAVChatRoomMember"}init(s,n){this._core=s,this._parentPlugin=n;const{helper:g}=s;g.registerApi({apiName:"deleteGroupMember",context:this,matcher:()=>n.getInstalledSubPlugins().length>0})}deleteGroupMember(s){return pA(this,void 0,void 0,function*(){const n="deleteGroupMember",{appStore:{groupStore:g},utils:{isUndefined:u},helper:E,OuterConstant:m}=this._core,{groupID:D}=s,M=g.getGroup(D);if(u(M))throw new E.ChatError({functionName:n,code:DD});if(M.type===m.GRP_AVCHATROOM){if(E.checkBusinessCapabilityBits(bT))return this._deleteGroupMember(s);throw new E.ChatError({functionName:n,code:OQ})}return this._parentPlugin.groupMember.deleteGroupMember(s)})}_deleteGroupMember(s){return pA(this,void 0,void 0,function*(){const n="_deleteGroupMember",{appStore:{groupStore:g},helper:u,ssoLog:E}=this._core,{groupID:m,duration:D=0,userIDList:M}=s;if(D===0)throw new u.ChatError({functionName:n,code:kT});try{return yield function(T,P){return pA(this,void 0,void 0,function*(){const{groupID:W,userIDList:iA,duration:EA,reason:RA}=T,kA={GroupId:W,Members_Account:iA,Duration:EA,Description:RA};return P.common.buildAndSendPacket({servcmd:"group_open_http_svc.ban_group_member",data:kA})})}(s,this._core),E.debug(n,`${this._name}.${n} ok, groupID:${m}`),{code:0,data:{group:g.getGroup(m),userIDList:M}}}catch(T){throw new u.ChatError({functionName:n,code:T?.errorCode,message:T?.errorInfo})}})}},wd=new class{constructor(){this._name="MarkAVChatRoomMember"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"markGroupMemberList",context:this})}markGroupMemberList(s){return pA(this,void 0,void 0,function*(){const n="markGroupMemberList",{groupID:g,markType:u,enableMark:E,userIDList:m=[]}=s,D=this._generateRequestData(s);try{const M=yield function(iA,EA){return pA(this,void 0,void 0,function*(){const{groupID:RA,operationType:kA,memberList:xA}=iA,LA={GroupId:RA,CommandType:kA,MemberList:xA};return EA.common.buildAndSendPacket({servcmd:"group_open_avchatroom_http_svc.modify_user_info",data:LA})})}(D,this._core),{MemberList:T=[]}=M||{},{successUserIDList:P,failureUserIDList:W}=this._handleResult(T,m);return{code:0,data:{successUserIDList:P,failureUserIDList:W},successLog:{message:`${this._name}.${n} ok, groupID:${g} markType:${u} enableMark:${E} success:${P.length} fail:${W.length}`}}}catch(M){throw new this._core.helper.ChatError({functionName:n,code:M?.errorCode,message:M?.errorInfo})}})}_generateRequestData(s){const{groupID:n,markType:g,enableMark:u,userIDList:E=[]}=s,m=u===!0?1:2,D=[...E];return D.length>500&&console.warn(`${this._name}._generateRequestData, the length of userIDList cannot exceed 500`),{groupID:n,operationType:m,memberList:D.map(M=>({Member_Account:M,Marks:[g]}))}}_handleResult(s,n){const g=[],u=[];return s.length===n.length?(g.push(...n),{successUserIDList:g,failureUserIDList:u}):(n.forEach(E=>{s.find(m=>m.Member_Account===E)?g.push(E):u.push(E)}),{successUserIDList:g,failureUserIDList:u})}},$v=new class{init(s,n){s.ssoLog.debug("AVChatRoomAction.init"),Zv.init(s,n),FT.init(s,n),Xv.init(s,n),Fm.init(s,n),zv.init(s,n),Om.init(s,n),wd.init(s)}},AR=new class{constructor(){this._name="LiveHandler"}init(s){this._core=s;const{helper:n,ssoLog:g}=s;n.registerExperimentalAPI("startMessageLongPolling",this),n.registerExperimentalAPI("stopMessageLongPolling",this),g.debug("LiveHandler.init")}startMessageLongPolling(s){const{common:n,utils:{isEmpty:g},OuterConstant:u,ssoLog:E}=this._core,{groupID:m,longPollingKey:D,longPollingSequence:M=1}=s;if(g(D))return E.warn("startMessageLongPolling",`${this._name}.startMessageLongPolling longPollingKey is empty.`),Promise.resolve({});Pg.hasPollingInstance(m)&&this.stopMessageLongPolling({groupID:m});const T=Pg.getJoinedLiveList(),P=n.isUnlimitedAVChatRoom();!P&&T.length>0&&this.stopMessageLongPolling({groupID:T[0].groupID}),E.debug("startMessageLongPolling",`${this._name}.startMessageLongPolling isUnlimited:${P} groupID:${m} longPollingKey:${D} longPollingSequence:${M}`);const W={groupID:m,type:u.GRP_LIVE};return Pg.updateLocalLiveGroup(m,W),this._getLiveHistoryMessages({groupID:m,longPollingKey:D,startSequence:M}),Pg.startMessageLongPolling({group:W,longPollingKey:D,startSequence:M})}stopMessageLongPolling(s){const{groupID:n}=s;return Pg.reset(n),this._core.ssoLog.debug("stopMessageLongPolling",`${this._name}.stopMessageLongPolling ok, groupID:${n}`),Promise.resolve({groupID:n})}_getLiveHistoryMessages(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n}=this._core,{groupID:g}=s;try{const u=yield function(m,D){return pA(this,void 0,void 0,function*(){const{groupID:M,longPollingKey:T,startSequence:P}=m,W={GroupId:M,LongPollingKey:T,PullPreSeq:P};return D.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_huge_group_msg",data:W})})}(s,this._core),{RspMsgList:E=[]}=u||{};n.debug("_getLiveHistoryMessages",`${this._name}._getLiveHistoryMessages ok, groupID:${g} count:${E.length}`),E.length>0&&Pg.handleLiveHistoryMessages(g,E)}catch(u){n.debug("_getLiveHistoryMessages",`${this._name}._getLiveHistoryMessages failed, groupID:${g} info:${u.message}`)}})}},Pm=new class{constructor(){this.name="AVChatRoom"}install(s,n){this._core=s,IB.init(s),Pg.init(s,n),$v.init(s,n),AR.init(s);const{notificationCenter:g,InnerEvent:u}=s,{InnerEventSubType:E}=g;g.subscribeInnerEvent(u.MESSAGE_PUSH,E.GROUP_SYSTEM_NOTIFICATION,this._onAVChatRoomSystemNotification,this),g.subscribeInnerEvent(u.LOGOUT,this._reset,this),g.subscribeInnerEvent(u.DESTROY,this._dispose,this)}_onAVChatRoomSystemNotification(s){Pg.onAVChatRoomSystemNotification(s)}_reset(){Pg.reset()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:n}=this._core,{InnerEventSubType:g}=s;s.unSubscribeInnerEvent(n.MESSAGE_PUSH,g.GROUP_SYSTEM_NOTIFICATION,this._onAVChatRoomSystemNotification,this),s.unSubscribeInnerEvent(n.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this)}};const Ag=new class{init(s){this.core=s}},xm="message",dB="user",CB={OR:"or",AND:"and"},MI=20,OT=20,eR=20,Qh={required:!1,rules:["array"],allowEmpty:!0,customValidator:s=>!s||!!(Array.isArray(s)&&s.length<=5)||"keywordList should be an array and length <= 5"},Ym={required:!1,rules:["string"],allowEmpty:!0,customValidator:s=>!s||!![CB.OR,CB.AND].includes(s)||"keywordListMatchType should be OR or AND"},DC={required:!1,rules:["number"],allowEmpty:!0,customValidator:s=>typeof s=="number"&&s>=1&&s<=100||"count must be a number between 1 and 100"},YQ={required:!1,rules:["string"],allowEmpty:!0},tR={required:!1,rules:["array"],allowEmpty:!0,customValidator:s=>{const{OuterConstant:n}=Ag.core;if(!Array.isArray(s))return"groupTypeList should be an array";const g=[n.GRP_PUBLIC,n.GRP_COMMUNITY,n.GRP_WORK,n.GRP_MEETING];let u=!1;for(let E=0;E{const{OuterConstant:n}=Ag.core,g=[n.MSG_TEXT,n.MSG_IMAGE,n.MSG_AUDIO,n.MSG_FILE,n.MSG_VIDEO,n.MSG_LOCATION,n.MSG_CUSTOM,n.MSG_MERGER];let u=!1;for(let E=0;E{const{OuterConstant:n}=Ag.core;return!(!s?.startsWith(n.CONV_C2C)&&!s?.startsWith(n.CONV_GROUP)&&s!==n.CONV_SYSTEM)||"conversationID is invalid"}},Vm=s=>({required:!1,rules:["number"],allowEmpty:!0,customValidator:n=>typeof n=="number"&&n>=0||`${s} should be a number >= 0';`}),MD={required:!1,rules:["string"],allowEmpty:!0,customValidator:s=>{const{OuterConstant:n}=Ag.core;return!![n.GENDER_FEMALE,n.GENDER_MALE].includes(s)||"gender is invalid"}},Jm={searchCloudMessages:{keywordList:Qh,keywordListMatchType:Ym,cursor:YQ,senderUserIDList:{required:!1,rules:["array"],allowEmpty:!0,customValidator:s=>!!(Array.isArray(s)&&s.length<=5)||"senderUserIDList should be an array and length <= 5"},messageTypeList:iR,conversationID:oR,timePosition:Vm("timePosition"),timePeriod:Vm("timePeriod")},searchCloudUsers:{keywordList:Qh,keywordListMatchType:Ym,cursor:YQ,count:DC,miniBirthday:Vm("miniBirthday"),maxBirthday:Vm("maxBirthday"),gender:MD},searchCloudGroupMembers:{keywordList:Qh,keywordListMatchType:Ym,cursor:YQ,count:DC,groupTypeList:tR,groupIDList:{required:!1,rules:["array"],allowEmpty:!0}},searchCloudGroups:{keywordList:Qh,keywordListMatchType:Ym,cursor:YQ,count:DC,groupTypeList:tR}},vD={searchCloudMessages:!0,searchCloudUsers:!0,searchCloudGroupMembers:!0,searchCloudGroups:!0};var RD=new class{constructor(){this.name="CloudSearch"}install(s){this._core=s,Ag.init(s),s.helper.registerApi({apiName:"searchCloudMessages",context:this}),s.helper.registerApi({apiName:"searchCloudUsers",context:this}),s.helper.registerApi({apiName:"searchCloudGroupMembers",context:this}),s.helper.registerApi({apiName:"searchCloudGroups",context:this}),s.helper.registerValidateConfig({auth:vD,params:Jm})}searchCloudMessages(s){return pA(this,void 0,void 0,function*(){try{const{OuterConstant:n,helper:g}=this._core,{conversationID:u,timePeriod:E,timePosition:m}=s,D=Do(s,["conversationID","timePeriod","timePosition"]),M=Object.assign({count:100},D);u&&(u.startsWith(n.CONV_C2C)?M.account=u.replace(n.CONV_C2C,""):u.startsWith(n.CONV_GROUP)&&(M.groupID=u.replace(n.CONV_GROUP,""))),this._setTimeRangeParams(M,{timePeriod:E,timePosition:m});const T=yield function(LA){return pA(this,void 0,void 0,function*(){const{count:SA,keywordList:OA,keywordListMatchType:JA,senderUserIDList:ne,messageTypeList:se,endTime:_i,startTime:Ti,cursor:Lt,account:Ni,groupID:cs}=LA,Se={Count:SA,KeywordList:OA,MatchType:JA,SendUserIDList:ne,MsgTypeList:se,EndTime:_i,StartTime:Ti,Cursor:Lt,PeerAccount:Ni,GroupID:cs};return Ag.core.common.buildAndSendPacket({servcmd:"message_search.query",data:Se})})}(M);if(!T)return{code:0,data:{}};const{ErrorCode:P,ErrorInfo:W,TotalCount:iA,Cursor:EA="",ConversationMsgs:RA=[]}=T;if(P!==0)throw{errorCode:P,errorInfo:W};const kA=`keywordList:${s.keywordList} keywordListMatchType:${s.keywordListMatchType} cursor:${s.cursor} res: totalCount:${iA}`;return{code:0,data:{searchResultList:RA.map(LA=>{const{MsgList:SA,Count:OA,GroupID:JA,UserID:ne}=LA,se=JA?`${n.CONV_GROUP}${JA}`:`${n.CONV_C2C}${ne}`;if(this._isSearchingAllConversations(s)&&OA>1)return{conversationID:se,messageCount:OA,messageList:[]};const _i=SA.map(Ti=>g.isEmpty(JA)?function(Lt,Ni){const cs=Ni.OuterConstant.CONV_C2C,Se=Ni.message.messageHelper.parseServerPushMessage(Lt),mt=Ni.message.messageFactory.createMessage(Object.assign(Object.assign({},Se),{conversationType:cs,flow:"in"}));return mt.setElement(Se.elements),mt}(Ti,this._core):function(Lt,Ni){const cs=Ni.OuterConstant.CONV_GROUP,Se=Ni.message.messageHelper.parseServerGroupMessage(Lt),mt=Ni.message.messageFactory.createMessage(Object.assign(Object.assign({},Se),{conversationType:cs,flow:"in"}));return mt.setElement(Se.elements),mt}(Ti,this._core));return{conversationID:se,messageCount:OA,messageList:_i}}),cursor:EA,totalCount:iA},successLog:{message:kA}}}catch(n){const{errorCode:g,errorInfo:u}=n||{};this._handleError({errorCode:g,errorInfo:u,searchType:xm,functionName:"searchCloudMessages"})}})}searchCloudUsers(s){return pA(this,void 0,void 0,function*(){var n;try{const{keywordListMatchType:g,count:u=OT}=s,E=Do(s,["keywordListMatchType","count"]),m=Object.assign({count:u,keywordListMatchType:g===CB.AND?1:0},E);this._setBirthdayRangeParams(m,s);const D=yield function(kA){return pA(this,void 0,void 0,function*(){const{count:xA,keywordList:LA,keywordListMatchType:SA,miniBirthday:OA,maxBirthday:JA,cursor:ne,gender:se}=kA,_i={Count:xA,Keywords:LA,KeywordMatchType:SA,Cursor:ne,UserBirthStart:OA,UserBirthEnd:JA,Gender:se};return Ag.core.common.buildAndSendPacket({servcmd:"user_search.query",data:_i})})}(m);if(!D)return{error:0,data:{}};const{ErrorCode:M,ErrorInfo:T,TotalCount:P,Cursor:W="",Users:iA=[]}=D;if(M!==0)throw{errorCode:M,errorInfo:T};const EA=`keywordList:${s.keywordList} keywordListMatchType:${s.keywordListMatchType} cursor:${s.cursor} count:${s.count} res: totalCount:${P}`,RA=[];for(let kA=0,xA=iA.length;kA({tag:ne.Tag,value:ne.StrValue})),JA=(n=this._core.user.userProfile)===null||n===void 0?void 0:n.createProfile(LA,OA);RA.push(JA)}return{code:0,data:{searchResultList:RA,cursor:W,totalCount:P},successLog:{message:EA}}}catch(g){const{errorCode:u,errorInfo:E}=g||{};this._handleError({errorCode:u,errorInfo:E,searchType:dB,functionName:"searchCloudUsers"})}})}searchCloudGroupMembers(s){return pA(this,void 0,void 0,function*(){try{const{count:n=eR,keywordListMatchType:g}=s,u=Do(s,["count","keywordListMatchType"]),E=Object.assign({count:n,keywordListMatchType:g===CB.AND?1:0},u),m=yield function(RA){return pA(this,void 0,void 0,function*(){const{count:kA,keywordList:xA,keywordListMatchType:LA,groupTypeList:SA,cursor:OA,groupIDList:JA}=RA,ne={Count:kA,Keywords:xA,KeywordMatchType:LA,Cursor:OA,GroupType:SA,GroupIdList:JA};return Ag.core.common.buildAndSendPacket({servcmd:"group_member_search.query",data:ne})})}(E);if(!m)return{code:0,data:{}};const{ErrorCode:D,ErrorInfo:M,GroupMembers:T=[],Cursor:P,TotalCount:W}=m;if(D!==0)throw{errorCode:D,errorInfo:M};const iA=`keywordList:${s.keywordList} keywordListMatchType:${s.keywordListMatchType} cursor:${s.cursor} count:${s.count} res: totalCount:${W}`,EA=new Map;return T.forEach(RA=>{const{GroupID:kA,GroupName:xA,GroupType:LA,GroupFaceUrl:SA,GroupMemberUserName:OA,GroupMemberUserID:JA,GroupMemberNameCard:ne,GroupMemberAvatar:se=""}=RA,_i={groupID:kA,name:xA,type:LA,avatar:SA},Ti={userID:JA,nick:OA,nameCard:ne,avatar:se};if(EA.has(kA)){const Lt=EA.get(kA);Lt.memberList.push(Ti),EA.set(kA,Lt)}else EA.set(kA,{groupInfo:_i,memberList:[Ti]})}),{code:0,data:{searchResultList:[...EA.values()],cursor:P,totalCount:W},successLog:{message:iA}}}catch(n){const{errorCode:g,errorInfo:u}=n||{};this._handleError({errorCode:g,errorInfo:u,searchType:dB,functionName:"searchCloudGroupMembers"})}})}searchCloudGroups(s){return pA(this,void 0,void 0,function*(){try{const{count:n=MI,keywordListMatchType:g}=s,u=Do(s,["count","keywordListMatchType"]),E=Object.assign({count:n,keywordListMatchType:g===CB.AND?1:0},u),m=yield function(EA){return pA(this,void 0,void 0,function*(){const{count:RA,keywordList:kA,keywordListMatchType:xA,groupTypeList:LA,cursor:SA}=EA,OA={Count:RA,Keywords:kA,KeywordMatchType:xA,Cursor:SA,GroupType:LA};return Ag.core.common.buildAndSendPacket({servcmd:"group_search.query",data:OA})})}(E);if(!m)return{code:0,data:{}};const{ErrorCode:D,ErrorInfo:M,Groups:T,Cursor:P,TotalCount:W}=m;if(D!==0)throw{errorCode:D,errorInfo:M};const iA=`keywordList:${s.keywordList} keywordListMatchType:${s.keywordListMatchType} cursor:${s.cursor} count:${s.count} res: totalCount:${W}`;return{code:0,data:{searchResultList:T?.map(EA=>function(RA){const{GroupFaceUrl:kA,GroupID:xA,GroupIntroduction:LA,GroupMemberNum:SA,GroupName:OA,GroupOwnerTinyID:JA,GroupOwnerUserID:ne,GroupOwnerUserName:se,GroupType:_i,GroupAddOption:Ti,GroupInviteOption:Lt}=RA;return{avatar:kA,groupID:xA,introduction:LA,memberCount:SA,name:OA,ownerTinyID:JA,ownerID:ne,ownerNick:se,type:_i,joinOption:Ti,inviteOption:Lt}}(EA))||[],cursor:P,totalCount:W},successLog:{message:iA}}}catch(n){const{errorCode:g,errorInfo:u}=n||{};this._handleError({errorCode:g,errorInfo:u,searchType:dB,functionName:"searchCloudGroups"})}})}_setTimeRangeParams(s,{timePeriod:n,timePosition:g}){n&&n>0&&(s.startTime=g&&g>0?g-n:this._core.helper.timeManager.getServerTimeSeconds()-n),s.startTime&&s.startTime<0&&(s.startTime=void 0),g&&g>0&&(s.endTime=g)}_handleError({errorCode:s,errorMessage:n,searchType:g}){const{helper:u}=this._core;let E=s;throw s===60020?E="SearchUnable":g!==xm&&s===27003?E="SearchParamsError":g!==xm&&s===60018&&(E="SearchOverLimit"),new u.ChatError({code:E,message:n})}_isSearchingAllConversations(s){return this._core.helper.isEmpty(s.conversationID)}_setBirthdayRangeParams(s,n){const{miniBirthday:g,maxBirthday:u}=n;g!==void 0&&(s.miniBirthday=g,u===void 0&&(s.maxBirthday=4294967295)),u!==void 0&&(s.maxBirthday=u)}};function ph(s,n){return Math.round(Number(s)*Math.pow(10,n))/Math.pow(10,n)}const sR="qualityStat",wD="im-ssolog-quality-stat";var _D;(function(s){s[s.ONLINE=8]="ONLINE"})(_D||(_D={}));const Hm="networkRTT",mh="messageE2EDelay",hB="sendMessageC2C",fh="sendMessageGroup",yh="sendMessageGroupAV",BB="sendMessageRichMedia",QB="cosUpload",SC="messageReceivedGroup",VQ="messageReceivedGroupAVPush",JQ="messageReceivedGroupAVPull",PT={[Hm]:2,[mh]:3,[hB]:4,[fh]:5,[yh]:6,[BB]:7,[SC]:8,[VQ]:9,[JQ]:10,[QB]:11},nR=[hB,fh,yh,BB,QB],Dh=[SC,VQ,JQ],pB=[Hm,mh,hB,fh,yh,BB,QB,SC,VQ,JQ],TD={ERR_SVR_COMM_SENSITIVE_TEXT:80001,ERR_SVR_COMM_BODY_SIZE_LIMIT:80002,OPEN_SERVICE_OVERLOAD_ERROR:60022,ERR_SVR_MSG_PKG_PARSE_FAILED:20001,ERR_SVR_MSG_INTERNAL_AUTH_FAILED:20002,ERR_SVR_MSG_INVALID_ID:20003,ERR_SVR_MSG_PUSH_DENY:20006,ERR_SVR_MSG_IN_PEER_BLACKLIST:20007,ERR_SVR_MSG_BOTH_NOT_FRIEND:20009,ERR_SVR_MSG_NOT_PEER_FRIEND:20010,ERR_SVR_MSG_NOT_SELF_FRIEND:20011,ERR_SVR_MSG_SHUTUP_DENY:20012,ERR_SVR_GROUP_INVALID_PARAMETERS:10004,ERR_SVR_GROUP_PERMISSION_DENY:10007,ERR_SVR_GROUP_NOT_FOUND:10010,ERR_SVR_GROUP_INVALID_GROUPID:10015,ERR_SVR_GROUP_REJECT_FROM_THIRDPARTY:10016,ERR_SVR_GROUP_SHUTUP_DENY:10017,MSG_SEND_FAIL:2100,OVER_FREQUENCY_LIMIT:2996},qm="quality_stat";var HQ=new class{constructor(){this._messageStatsMap=new Map,this._userSideErrorCodes=new Set(Object.values(TD))}init(s){this._core=s,Object.values(nR).forEach(n=>{this._messageStatsMap.set(n,{totalCount:0,successCount:0,failedCountOfUserSide:0,costSum:0,costCount:0,fileSizeSum:0})})}dispatchSendStats(s){const{name:n,message:g,error:u,startTs:E}=s,{SEND_MESSAGE_STAT:m}=this._core.constants;switch(n){case m.TOTAL_COUNT:this._handleTotalCount(g);break;case m.SUCCESS_COUNT:this._handleSuccessCount(g);break;case m.FAILED_COUNT:this._handleFailedCount(g,u);break;case m.SEND_COST:this._handleSendCost(g,E)}}getStatResult(s){const n=this._messageStatsMap.get(s);if(!n||n.totalCount===0)return null;const{totalCount:g,successCount:u,failedCountOfUserSide:E}=n,m=ph(u/g*100,2),D=u+E,M=ph(D/g*100,2),T=this._calcAverageValue(n,s);return this._resetStat(s),{total_count:g,success_count_business:u,percent_business:m,success_count_platform:D,percent_platform:M,average_value:T}}_handleTotalCount(s){const n=this._getSendMessageSpecifiedKey(s),g=n&&this._messageStatsMap.get(n);g&&g.totalCount++}_handleSuccessCount(s){const n=this._getSendMessageSpecifiedKey(s),g=n&&this._messageStatsMap.get(n);g&&g.successCount++}_handleFailedCount(s,n){var g;const u=(g=n?.code)!==null&&g!==void 0?g:n?.errorCode;if(this._isUserSideError(u)){const E=this._getSendMessageSpecifiedKey(s),m=E&&this._messageStatsMap.get(E);m&&m.failedCountOfUserSide++}}_handleSendCost(s,n){const g=this._getSendMessageSpecifiedKey(s),u=g&&this._messageStatsMap.get(g);u&&(u.costSum+=Date.now()-n,u.costCount++)}_isUserSideError(s){return this._userSideErrorCodes.has(s)||s>=120001&&s<=13e4||s>=10100&&s<=10200}_getSendMessageSpecifiedKey(s){const{MSG_IMAGE:n,MSG_AUDIO:g,MSG_VIDEO:u,MSG_FILE:E,CONV_C2C:m,CONV_GROUP:D,GRP_AVCHATROOM:M}=this._core.OuterConstant;if([n,g,u,E].includes(s.type))return BB;if(s.conversationType===m)return hB;if(s.conversationType===D){const{groupStore:T}=this._core.appStore,P=T.getGroup(s.to);if(!P)return;const{type:W}=P;return W===M?yh:fh}}_calcAverageValue(s,n){return s.costCount===0?0:Math.round(n===QB?1e3*s.fileSizeSum/s.costSum:s.costSum/s.costCount)}_resetStat(s){const n=this._messageStatsMap.get(s);n&&(n.totalCount=0,n.successCount=0,n.failedCountOfUserSide=0,n.costSum=0,n.costCount=0,n.fileSizeSum=0)}},qQ=new class{constructor(){this._lastCycleStats=new Map,this._currentCycleStats=new Map}init(s){this._core=s;const{OuterEvent:n,notificationCenter:g}=s;this._initStatsMap(),g.subscribeOuterEvent(n.MESSAGE_RECEIVED,this._onMessageReceived,this)}addMessageSequence(s){const n=this._getReceivedMessageSpecifiedKey(s),{utils:{isUndefined:g},OuterConstant:{CONV_GROUP:u},ssoLog:E}=this._core;if(g(n)||!this._currentCycleStats.has(n))return void E.debug("addMessageSequence",`${sR}.addMessageSequence invalid key:${n}`);const{conversationID:m,sequence:D}=s,M=m.replace(u,""),T=this._lastCycleStats.get(n);if(T.size===0||!T.has(M))return void this._addToCurrentCycle(n,M,D);const P=T.get(M);D>P.minSeq&&D{const{sortedSequences:m,minSeq:D,maxSeq:M}=E;m.length>0&&(u+=m.length,g+=M-D+1)}),g===0?null:(this._transferCycleDataOptimized(s),{total_count:g,success_count_business:u,percent_business:ph(u/g*100,2)})}reset(){this._lastCycleStats.clear(),this._currentCycleStats.clear()}dispose(){const{notificationCenter:s,OuterEvent:{MESSAGE_RECEIVED:n}}=this._core;s.unSubscribeOuterEvent(n,this._onMessageReceived,this),this.reset()}_initStatsMap(){Object.values(Dh).forEach(s=>{this._lastCycleStats.set(s,new Map),this._currentCycleStats.set(s,new Map)})}_onMessageReceived(s){const{data:n=[]}=s;n.forEach(g=>{this.addMessageSequence(g)})}_transferCycleDataOptimized(s){const n=this._currentCycleStats.get(s);if(!n)return;const g=new Map;n.forEach((u,E)=>{const m=u.dirty?[...u.sortedSequences].sort((D,M)=>D-M):u.sortedSequences;g.set(E,{sortedSequences:m,minSeq:u.minSeq,maxSeq:u.maxSeq,dirty:!1})}),this._lastCycleStats.set(s,g),this._currentCycleStats.set(s,new Map)}_getReceivedMessageSpecifiedKey(s){const{OuterConstant:{CONV_GROUP:n,GRP_AVCHATROOM:g}}=this._core;if(s.conversationType===n&&s?._onlineOnlyFlag!==!0){const{groupStore:u}=this._core.appStore,E=u.getGroup(s.to);if(!E)return null;const{type:m}=E;return m===g?JQ:SC}}_insertToLastCycle(s,n){n.dirty&&(n.sortedSequences.sort((u,E)=>u-E),n.dirty=!1);const g=this._findInsertPos(n.sortedSequences,s);n.sortedSequences.splice(g,0,s),n.minSeq=Math.min(n.minSeq,s),n.maxSeq=Math.max(n.maxSeq,s)}_findInsertPos(s,n){let g=0,u=s.length-1;for(;g<=u;){const E=Math.floor((g+u)/2);if(s[E]===n)return E;s[E]0&&(this._totalDelay+=g,this._totalCount++,g<=1?this._countLessThan1s++:g<=3&&this._countLessThan3s++)}getStatResult(){if(this._totalCount===0)return null;const s={total_count:this._totalCount,success_count_business:this._countLessThan1s,success_count_platform:this._countLessThan3s,percent_business:this._calculatePercentage(this._countLessThan1s,this._totalCount),percent_platform:this._calculatePercentage(this._countLessThan3s,this._totalCount),average_value:this._calculateAverageDelay(this._totalCount)};return this.reset(),s}reset(){this._totalDelay=0,this._totalCount=0,this._countLessThan1s=0,this._countLessThan3s=0}dispose(){const{notificationCenter:s,OuterEvent:{MESSAGE_RECEIVED:n}}=this._core;s.unSubscribeOuterEvent(n,this._onMessageReceived,this),this.reset()}_onMessageReceived(s){const{data:n=[]}=s,{OuterConstant:{MSG_GRP_TIP:g,MSG_GRP_SYS_NOTICE:u}}=this._core,E=[g,u];n.forEach(m=>{!E.includes(m.type)&&m.clientTime>0&&this.addMessageDelay(m.clientTime)})}_calculateAverageDelay(s){return s===0?0:ph(this._totalDelay/s,1)}_calculatePercentage(s,n){return ph(s/n*100,2)}},rR=new class{init(s){this.core=s}},xT=new class{constructor(){this.name="MessageQualityStat",this._reportIndex=0,this._wholePeriod=!1,this._pendingReports=[],this._failedLogsCache=new Map}install(s){this._core=s;const{helper:n,notificationCenter:g,InnerEvent:{QUALITY_STAT:u,LOGOUT:E,DESTROY:m},constants:{WORKFLOW_NAME:D,WORKFLOW_STEP:M}}=s;rR.init(s),HQ.init(s),qQ.init(s),KQ.init(s),n.registerWorkflowStep(D.SYNC_SERVER_INFO_AFTER_LOGIN,M.QUALITY_REPORT,this.handleLoginSuccess,this),g.subscribeInnerEvent(u,this._handleQualityStat,this),g.subscribeInnerEvent(E,this._reset,this),g.subscribeInnerEvent(m,this._dispose,this)}handleLoginSuccess(){const{store:s,helper:n,utils:{isUndefined:g}}=this._core,u=s.get("cloudConfig")||{},{q_rpt_interval:E}=u,m=g(E)?12e4:Number(E);n.taskScheduler.addTask({id:qm,intervalMs:m,callback:this.report,context:this})}report(){this._wholePeriod=!0;const s=[...pB.map(n=>{const g=this._buildQualityReportItem(n);return g?Object.assign(Object.assign({},g),{report_index:this._reportIndex,whole_period:this._wholePeriod}):null}).filter(Boolean),...this._pendingReports];this._pendingReports=[],this._needSkipReport()||this._uploadQualityReports(s)}_handleQualityStat(s){const{constants:{QUALITY_METRICS:n}}=this._core,{label:g,data:u}=s;g===n.MESSAGE_SEND_SUCCESS_RATE&&HQ.dispatchSendStats(u)}_needSkipReport(){return this._isSDKAppIDInBlacklist()&&!this._isTinyIDInWhitelist()}_isSDKAppIDInBlacklist(){const{store:s,utils:n}=this._core,g=s.get("cloudConfig")||{},u=s.get("instance")||{},{sdkAppId:E}=u,{q_rpt_sdkappid_bl:m=[]}=g;if(!n.isEmpty(m))return m.split(",").map(D=>Number(D)).includes(E)}_isTinyIDInWhitelist(){const{store:s,utils:n}=this._core,g=s.get("cloudConfig")||{},u=s.get("login")||{},E=Number(u.tinyID),{q_rpt_tinyid_wl:m=[]}=g;if(!n.isEmpty(m))return m.split(",").includes(E)}_buildQualityReportItem(s){const n=this._getStatResultByKey(s);if(n===null)return null;const g={quality_type:PT[s],timestamp:Date.now(),network_type:_D.ONLINE,extension:""};return Object.assign(Object.assign({},g),n)}_getStatResultByKey(s){switch(s){case mh:return KQ.getStatResult();case hB:case fh:case yh:case BB:case QB:return HQ.getStatResult(s);case SC:case VQ:case JQ:return qQ.getStatResult(s);default:return null}}_uploadQualityReports(s){return pA(this,void 0,void 0,function*(){try{const n={header:this._core.common.getCommonHead(),quality:s};yield function(g){const{common:u,channel:E}=rR.core,m="imopenstat.tim_web_report_v2",D=u.generateSSOLogProtocolData({servcmd:m,data:g}),M=`${D.head.seq}${m}`;return E.sendPacket(D,{requestId:M})}(n),this._reportIndex++,this._wholePeriod=!1}catch(n){console.warn("doReport failed. error:",n),this._pendingReports=this._pendingReports.concat(s),this._cacheFailedLogs()}})}_cacheFailedLogs(){const s=this._pendingReports,n=`${sR}._cacheFailedLogs`;let g=[...this._failedLogsCache.get(wD)||[],...s];g.length>10&&(g=g.slice(g.length-10),console.log(`${n} logs overflow, keeping last 10 items`)),this._failedLogsCache.set(wD,g),console.log(`${n} count: ${g.length}`),this._pendingReports=[]}_reset(){const{helper:s}=this._core;s.taskScheduler.removeTask(qm)}_dispose(){const{notificationCenter:s,InnerEvent:{QUALITY_STAT:n,LOGOUT:g,DESTROY:u}}=this._core;s.unSubscribeInnerEvent(n,this._handleQualityStat,this),s.unSubscribeInnerEvent(g,this._reset,this),s.unSubscribeInnerEvent(u,this._dispose,this),this._reset(),KQ.dispose(),qQ.dispose()}};const cl=new class{init(s){this.core=s}};function aR(s){return pA(this,void 0,void 0,function*(){var n;const{message:g,user:u,appStore:E,constants:{OuterConstant:m}}=cl.core,D=E.conversationStore.getConversationMap();if(D.has(s)){const T=(n=D.get(s))===null||n===void 0?void 0:n.userProfile;if(T&&s.startsWith(m.CONV_C2C)){const{avatar:P,nick:W}=T;cl.core.message.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:s,latestAvatar:P,latestNick:W,isSentByMe:!1})}}const{data:M}=(yield u.userProfile.getMyProfile())||{};if(M){const{avatar:T,nick:P}=M;g.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:s,latestAvatar:T,latestNick:P,isSentByMe:!0})}})}function gR(s){return pA(this,void 0,void 0,function*(){const n=s.map(g=>g.revoker);try{const g=yield function(u){return pA(this,void 0,void 0,function*(){var E,m;const D=yield(E=cl.core.user.userProfile)===null||E===void 0?void 0:E.getUserProfile({userIDList:u});return D?.data?(m=D.data)===null||m===void 0?void 0:m.reduce((M,{userID:T,nick:P,avatar:W})=>(M[T]={nick:P||"",avatar:W||""},M),{}):null})}(n);g&&s.forEach(u=>{const{revoker:E}=u;g[E]&&(u.revokerInfo.nick=g[E].nick||"",u.revokerInfo.avatar=g[E].avatar||"",u.revokerInfo.userID=E)})}catch(g){console.debug(g)}})}const ND=1,cR=2,Sh=20,jQ=2500,lR=1,Mh=300;function WQ(s){return pA(this,void 0,void 0,function*(){var n,g;const{appStore:u,utils:{isEmpty:E},common:{getCurrentUserID:m},notificationCenter:D,OuterEvent:M,OuterConstant:{CONV_C2C:T}}=cl.core,{messageList:P,conversationID:W}=s,iA=u.conversationStore.getConversationMap();let EA=(n=iA.get(W))===null||n===void 0?void 0:n.peerReadTime;if(!EA){const kA=W.replace(T,""),xA=yield function(LA){return pA(this,void 0,void 0,function*(){const SA={To_Account:LA};return cl.core.common.buildAndSendPacket({servcmd:"openim.get_peer_read_time",data:SA})})}([kA]);if(xA){const{ReadTime:LA}=xA;EA=LA?.[0],iA.has(W)&&(iA.get(W).peerReadTime=EA)}}if(iA.has(W)){const kA=(g=iA.get(W))===null||g===void 0?void 0:g.lastMessage;E(kA)||kA.fromAccount===m()&&kA.lastTime<=EA&&!kA.isPeerRead&&(kA.isPeerRead=!0,u.conversationStore.updateConversation(W,{lastMessage:kA}))}const RA=[];P.forEach(kA=>{kA.time<=EA&&!kA.isPeerRead&&kA.flow==="out"&&(kA.isPeerRead=!0,RA.push(kA))}),RA.length>0&&D.emitOuterEvent(M.MESSAGE_READ_BY_PEER,{name:M.MESSAGE_READ_BY_PEER,data:RA})})}var IR=new class{init(s){this._core=s,s.helper.registerApi({apiName:"getMessageList",context:this}),s.helper.registerApi({apiName:"getMessageListHopping",context:this}),s.helper.registerApi({apiName:"clearHistoryMessage",context:this})}getMessageList(s){return pA(this,void 0,void 0,function*(){try{const{message:n,OuterConstant:{Direction:g,CONV_C2C:u,CONV_GROUP:E},InnerEvent:{HISTORY_MESSAGE_FETCHED:m},notificationCenter:D}=this._core,{conversationID:M,nextReqMessageID:T}=s,P=Sh;if(M==="@TIM#SYSTEM")return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}};const W=this._getAvailableLocalMessagesCount({conversationID:M,nextReqMessageID:T});if(this._needFetchHistoryMessageList({conversationID:M,availableLocalMessagesCount:W,targetCount:P})){let iA=null;if(M.startsWith(E)?iA=yield n.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:M,sequence:Number(T),count:P,direction:g.FORWARD,shouldMarkCompleted:!0}):M.startsWith(u)&&(iA=yield n.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:M,messageID:T,count:P,direction:g.FORWARD,shouldMarkCompleted:!0})),iA){const{nextReqMessageIDFromServer:EA,hasNoMoreHistoryMessage:RA,messageList:kA}=iA,xA=n.messageDataHandler.prependLocalMessageList({messageList:kA,conversationID:M});(function(ne){const{appStore:se,message:_i,OuterConstant:Ti}=cl.core,Lt=se.conversationStore.getConversation(ne),Ni=_i.messageDataHandler.getLocalMessageList(ne);if(!Lt||Ni.length===0||ne===Ti.CONV_SYSTEM)return;const cs=[];for(let mt=0;mtUA.isRevoked).length;Se=cs.length-Lt.unreadCount-mt}else Se=cs.length-Lt.unreadCount;for(let mt=0;mtne.isRevoked);yield gR(SA),D.emitInnerEvent(m,xA);const OA={nextReqMessageID:RA?"":String(EA),messageList:LA,isCompleted:RA},JA=LA.map(ne=>ne.sequence);return{code:0,data:OA,successLog:{message:`conversationID: ${M} nextReqMessageID: ${T} availableLocalMessagesCount: ${W} sequenceList: ${JSON.stringify(JA)}`}}}return{code:0,data:{messageList:[],isCompleted:!1,nextReqMessageID:""}}}return{code:0,data:yield this._getMessageListFromMemory({conversationID:M,nextReqMessageID:T,count:P}),successLog:{message:`conversationID: ${M} nextReqMessageID: ${T} availableLocalMessagesCount: ${W}}`}}}catch(n){const{code:g,message:u}=n||{};throw new this._core.helper.ChatError({code:g,message:u,moreMessage:`options: ${this._core.utils.safeStringify(s)}`})}})}getMessageListHopping(s){return pA(this,void 0,void 0,function*(){var n,g;const{OuterConstant:{Direction:u,CONV_C2C:E,CONV_GROUP:m},utils:{safeStringify:D}}=this._core,{conversationID:M,sequence:T,time:P,direction:W=u.FORWARD}=s,{utils:{isEmpty:iA},message:EA,notificationCenter:RA,InnerEvent:{HISTORY_MESSAGE_FETCHED:kA}}=this._core;if(![u.BACKWARD,u.FORWARD].includes(W))throw new this._core.helper.ChatError({message:"direction must be 0 or 1",moreMessage:`options: ${D(s)}`});let{count:xA=Sh}=s;xA=xA>Sh?Sh:xA;let LA=null;if(M.startsWith(m)){if(LA=yield EA.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:M,sequence:T,count:xA,direction:W}),LA){const{nextReqMessageIDFromServer:SA,hasNoMoreHistoryMessage:OA,messageList:JA,invisibleSequenceList:ne}=LA;if(this._core.message.messageDataHandler.storeSparseMessageList(JA),RA.emitInnerEvent(kA,JA),W===u.FORWARD){const se=OA&&SA<1;return{code:0,data:{messageList:JA,isCompleted:se,nextMessageSeq:se?"":SA}}}if(W===u.BACKWARD){if(iA(JA)&&iA(ne))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};const se=((n=JA?.[JA.length-1])===null||n===void 0?void 0:n.sequence)||0,_i=((g=ne?.[ne.length-1])===null||g===void 0?void 0:g.sequence)||0;return{code:0,data:{messageList:JA.filter(Ti=>Ti.sequence>=T),isCompleted:!OA,nextMessageSeq:OA?Math.max(se,_i)+1:""}}}return{code:0,data:LA}}}else if(M.startsWith(E)&&(LA=yield EA.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:M,count:xA+1,time:P,direction:W}),LA)){const{messageList:SA,lastMessageTime:OA,hasNoMoreHistoryMessage:JA}=LA;return RA.emitInnerEvent(kA,SA),JA||(W===u.FORWARD?SA.shift():SA.pop()),EA.messageDataHandler.storeSparseMessageList(SA),yield WQ({messageList:SA,conversationID:M}),{code:0,data:{messageList:SA,isCompleted:JA,nextMessageTime:JA?"":OA}}}})}clearHistoryMessage(s){return pA(this,void 0,void 0,function*(){var n;const{appStore:g,common:{ChatError:u,getCurrentUserID:E},OuterConstant:{CONV_C2C:m,CONV_GROUP:D},apiMap:M,message:T}=this._core,P=g.conversationStore.getConversation(s);if(!P)throw new u({code:jQ});const W={fromAccount:E()},{type:iA}=P;iA===m?(W.type=ND,W.toAccount=s.replace(m,"")):iA===D&&(W.type=cR,W.toGroupID=s.replace(D,""));try{return yield(n=M?.setMessageRead)===null||n===void 0?void 0:n.call(M,{conversationID:s}),(yield function(RA){return pA(this,void 0,void 0,function*(){const{fromAccount:kA,type:xA,toAccount:LA,toGroupID:SA}=RA,OA={From_Account:kA,Type:xA,To_Account:LA,ToGroupid:SA};return cl.core.common.buildAndSendPacket({servcmd:"recentcontact.clear_msg",data:OA})})}(W))&&(T.messageDataHandler.deleteConversationMessageList(s),T.messageHistory.completedHistoryConversations.delete(s),T.messageHistory.clearHistoryMessageListFetchAnchors(s),this._updateConversationLastMessage(s)),{code:0,data:{conversationID:s},successLog:{message:`convID:${s}`}}}catch(EA){const{errorCode:RA}=EA;throw new this._core.helper.ChatError({functionName:"clearHistoryMessage",code:RA,moreMessage:`convID:${s}`})}})}_updateConversationLastMessage(s){const{appStore:n}=this._core;n.conversationStore.updateConversation(s,{lastMessage:this._generateLastMessage()},{needSort:!0})}_getAvailableLocalMessagesCount({conversationID:s,nextReqMessageID:n}){const{OuterConstant:{CONV_C2C:g,CONV_GROUP:u}}=this._core,E=this._core.message.messageDataHandler.getLocalMessageList(s),{length:m}=E;if(!n)return m;let D=-1;return s?.startsWith(g)?D=E.findIndex(M=>M.ID===n):s?.startsWith(u)&&(D=E.findIndex(M=>n.includes("-")?M.ID===n:String(M.sequence)===n)),D===-1?0:D}_needFetchHistoryMessageList({conversationID:s,availableLocalMessagesCount:n,targetCount:g}){const{message:u}=this._core;return nn.startsWith(E)?EA.ID===g:String(EA.sequence)===g),W=iA>u?iA-u:0,T=iA):W=M>u?M-u:0,P.messageList=D.slice(W,iA),P.isCompleted=T<=u&&m.messageHistory.completedHistoryConversations.has(n),P.isCompleted?P.nextReqMessageID="":P.nextReqMessageID=this._generateNextReqMessageID({conversationID:n,targetIndex:W}),n.startsWith(E)&&(yield aR(n),yield WQ({messageList:P.messageList,conversationID:n})),P})}_generateNextReqMessageID({conversationID:s,targetIndex:n}){const g=this._core.message.messageDataHandler.getLocalMessageList(s);return s.startsWith("C2C")?g[n].ID:String(g[n].sequence)}_generateLastMessage(){return{lastTime:0,lastSequence:0,fromAccount:"",messageForShow:"",payload:null,type:"",isRevoked:!1,cloudCustomData:"",onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:!1,revoker:null}}},mB=new class{constructor(){this._lastMessageSequenceMapOnDisconnect=new Map,this._lastMessageTimeMapOnDisconnect=new Map}init(s){this._core=s;const{common:{workflowManager:n},constants:{WORKFLOW_NAME:g,WORKFLOW_STEP:u,InnerEvent:E}}=s;n.registerWorkflowStep(g.SYNC_SERVER_INFO_AFTER_RE_ONLINE,u.HISTORY_MESSAGE_RECOVER,this._syncGroupOfflineMessage,this),n.registerWorkflowStep(g.SYNC_SERVER_INFO_AFTER_RE_ONLINE,u.C2C_HISTORY_MESSAGE_RECOVER,this._syncC2COfflineMessage,this),s.notificationCenter.subscribeInnerEvent(E.SOCKET_DISCONNECTED,this._updateLastMessageSequenceMapOnDisconnect,this)}_syncGroupOfflineMessage(s){const{conversationList:n}=s?.result||{},{OuterConstant:g,utils:{isArray:u}}=this._core;if(u(n)){const E=n.filter(m=>m.type===g.CONV_GROUP&&m.groupProfile.type!==g.GRP_AVCHATROOM);return this._recoverGroupHistoryMessage(E)}}_recoverGroupHistoryMessage(s){return pA(this,void 0,void 0,function*(){const{OuterConstant:n}=this._core,g=[],u=[];return yield Promise.all(s?.map(E=>pA(this,void 0,void 0,function*(){const{groupProfile:{groupID:m}={},lastMessage:{lastSequence:D}={}}=E,M=`${n.CONV_GROUP}${m}`;let T=this._getLocalLastMessageSequence(M);this._shouldRecoverHistory({localLastMessageSequence:T,serverLastMessageSequence:D})&&(yield this._recoverGroupHistoryForConversation({conversationID:M,localLastMessageSequence:T,serverLastMessageSequence:D,groupTipList:u})),g.push(M.replace(n.CONV_GROUP,""))}))),{recoverRevokeNoticeGroupIDList:g,groupTipList:u}})}_recoverGroupHistoryForConversation(s){return pA(this,arguments,void 0,function*({conversationID:n,localLastMessageSequence:g,serverLastMessageSequence:u,groupTipList:E}){try{const{utils:{isArray:m,isObject:D,isEmpty:M},OuterEvent:T,OuterConstant:P,notificationCenter:W,message:iA,appStore:EA,common:{getMessagePreviewText:RA,buildLastMessage:kA}}=this._core,xA=u-g,LA=Math.min(20,xA),SA={},OA=yield iA.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:n,sequence:g+LA,direction:P.Direction.FORWARD,count:LA}),{nextReqMessageIDFromServer:JA,hasNoMoreHistoryMessage:ne,messageList:se,serverGroupTipList:_i}=OA;m(_i)&&E.push(..._i);const Ti=ne&&JA<0,Lt=[];if(m(se)&&(se.forEach(Ni=>{iA.messageReceiver.groupMessageReceiver.updateMessageProfile(Ni),Ni.from===P.CONV_SYSTEM&&(Ni.isSystemMessage=!1),iA.messageDataHandler.storeConversationMessage(Ni)&&!M(Ni.payload)&&(Lt.push(Ni),Ni._isExcludedFromLastMessage||(SA.lastMessage=kA(Ni)))}),Lt.length>0&&W.emitOuterEvent(T.MESSAGE_RECEIVED,{name:T.MESSAGE_RECEIVED,data:Lt})),!Ti&&se.length>0){const Ni=se[se.length-1].sequence;yield this._recoverGroupHistoryForConversation({conversationID:n,localLastMessageSequence:Ni,serverLastMessageSequence:u,groupTipList:E})}D(SA.lastMessage)&&(SA.lastMessage.messageForShow=RA(SA.lastMessage.type,SA.lastMessage.payload),EA.conversationStore.updateConversation(n,SA))}catch(m){this._core.ssoLog.error("_recoverGroupHistoryForConversation",`Recovery failed for conversation:${n}`,{error:m})}})}_updateLastMessageSequenceMapOnDisconnect(){const{message:s}=this._core,n=s.messageDataHandler.getContinuousMessagesByConversation();for(const[g,u]of n){const E=Array.from(u.values());if(E?.length>0){const m=E[E.length-1];g.startsWith("C2C")?this._lastMessageTimeMapOnDisconnect.set(g,m.time):g.startsWith("GROUP")&&this._lastMessageSequenceMapOnDisconnect.set(g,m.sequence)}}}_getLocalLastMessageSequence(s){const{message:n}=this._core;if(this._lastMessageSequenceMapOnDisconnect.has(s))return this._lastMessageSequenceMapOnDisconnect.get(s);const g=n.messageDataHandler.getLocalMessageList(s),u=g[g.length-1];return u?.sequence}_shouldRecoverHistory(s){const{localLastMessageSequence:n,serverLastMessageSequence:g}=s;if(typeof n!="number"||typeof g!="number")return!1;const u=g-n;return g!==0&&n>0&&u>=lR&&u{m.type===g.CONV_C2C&&E.push(m)}),this._recoverC2CHistoryMessage(E)}}_recoverC2CHistoryMessage(s){return pA(this,void 0,void 0,function*(){yield Promise.all(s?.map(n=>pA(this,void 0,void 0,function*(){const{conversationID:g,lastMessage:{lastTime:u}={}}=n,E=this._getLocalLastMessageTime(g);this._shouldRecoverC2CHistory({localLastMessageTime:E,serverLastMessageTime:u})&&(yield this._recoverHistoryForC2CConversation({conversationID:g,localLastMessageTime:E,serverLastMessageTime:u}))})))})}_shouldRecoverC2CHistory(s){const{localLastMessageTime:n,serverLastMessageTime:g}=s,u=g-n;return n>0&&u>=1&&u<=600}_recoverHistoryForC2CConversation(s){return pA(this,void 0,void 0,function*(){var n;const{conversationID:g,localLastMessageTime:u,serverLastMessageTime:E}=s,{utils:{isArray:m,isObject:D,isEmpty:M,safeStringify:T},OuterEvent:P,OuterConstant:W,notificationCenter:iA,message:EA,appStore:RA,common:{getMessagePreviewText:kA,buildLastMessage:xA}}=this._core;try{const LA={},SA=yield EA.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:g,direction:W.Direction.BACKWARD,time:u,count:20});if(M(SA))return;const{hasNoMoreHistoryMessage:OA,messageList:JA}=SA,ne=[];m(JA)&&(JA.forEach(_i=>{EA.messageDataHandler.storeConversationMessage(_i)&&!M(_i.payload)&&(ne.push(_i),_i._isExcludedFromLastMessage||(LA.lastMessage=xA(_i)))}),ne.length>0&&iA.emitOuterEvent(P.MESSAGE_RECEIVED,{name:P.MESSAGE_RECEIVED,data:ne}));const se=(n=JA[JA.length-1])===null||n===void 0?void 0:n.time;!OA&&se>E&&(yield this._recoverHistoryForC2CConversation({conversationID:g,localLastMessageTime:se,serverLastMessageTime:E})),D(LA.lastMessage)&&(LA.lastMessage.messageForShow=kA(LA.lastMessage.type,LA.lastMessage.payload),RA.conversationStore.updateConversation(g,LA))}catch(LA){this._core.ssoLog.error("_recoverHistoryForC2CConversation",`Recovery failed for conversation:${g} error: ${T(LA)}`)}})}_getLocalLastMessageTime(s){const{message:n}=this._core;if(this._lastMessageTimeMapOnDisconnect.has(s))return this._lastMessageTimeMapOnDisconnect.get(s);const g=n.messageDataHandler.getLocalMessageList(s),u=g[g.length-1];return u?.time}reset(){this._lastMessageSequenceMapOnDisconnect.clear(),this._lastMessageTimeMapOnDisconnect.clear()}dispose(){this.reset()}},fB=new class{constructor(){this.name="HistoryMessage"}install(s){this._core=s,cl.init(s),IR.init(s),mB.init(s),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.LOGOUT,this._reset,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this.dispose,this)}dispose(){const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(n.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(n.DESTROY,this.dispose,this),mB.dispose()}_reset(){mB.reset()}},GD=new class{init(s){this.core=s}},MC=new class{constructor(){this._reportedAtomicStoreIDs=new Set}init(s){const{helper:{registerExperimentalAPI:n}}=s;this._core=s,n("reportModalView",this),n("reportTUIFeatureUsage",this),n("reportRoomEngineEvent",this)}reportModalView(s){const{ssoLog:n,utils:{safeStringify:g,isString:u}}=this._core;try{if(!u(s))throw new Error("reportModalView data is not a string");n.createSSOLogData({method:"reportModalView",message:s,eventType:30}).end(!0)}catch(E){n.debug(`reportModalView Report failed: ${g(E)}`)}}reportTUIFeatureUsage(s){const{ssoLog:n,utils:{safeStringify:g,isEmpty:u}}=this._core,{atomicStoreID:E}=s;try{u(E)||this._reportedAtomicStoreIDs.has(E)||(this._core.ssoLog.info("reportTUIFeatureUsage",`atomicStoreID: ${s.atomicStoreID}`,{method:"reportTUIFeatureUsage",eventType:31,code:E}),this._reportedAtomicStoreIDs.add(E))}catch(m){n.debug(`reportTUIFeatureUsage Report failed: ${g(m)}`)}}reportRoomEngineEvent(s){const{utils:{safeStringify:n},ssoLog:g}=this._core;try{g.debug(`reportRoomEngineEvent Report: ${n(s)}`);const{eventId:u,eventCode:E,eventResult:m,eventMessage:D,moreMessage:M,extensionMessage:T}=s;g.createSSOLogData({method:T,code:u,message:D,eventType:30,costTime:E,uiPlatform:m,moreMessage:M}).end(!0)}catch(u){g.debug(`reportRoomEngineEvent Report failed: ${n(u)}`)}}reset(){this._reportedAtomicStoreIDs.clear()}dispose(){this.reset()}},zQ=new class{constructor(){this.name="DataReport"}install(s){this._core=s;const{notificationCenter:n,InnerEvent:{LOGOUT:g,DESTROY:u}}=s;GD.init(s),MC.init(s),n.subscribeInnerEvent(g,this._reset,this),n.subscribeInnerEvent(u,this._dispose,this)}_reset(){MC.reset()}_dispose(){const{notificationCenter:s,InnerEvent:{LOGOUT:n,DESTROY:g}}=this._core;s.unSubscribeInnerEvent(n,this._reset,this),s.unSubscribeInnerEvent(g,this._dispose,this),MC.dispose()}};let Km=nr.STANDARD,yB=[];Km=nr.STANDARD,yB=[rh,lC,IC,uC,Rc,xT,fB,zQ,LE,vi,jn,GT,Pm,RD,zI];function DB(s,n){const{operationType:g,memberInfoList:u,operatorInfo:E}=s||{};let m={};if(Rs(u)?Rs(E)||(m=E):g!==Tg.JOINED&&g!==Tg.KICKED&&g!==Tg.ADMIN_SET&&g!==Tg.ADMIN_CANCELED||(m=Object.assign({},u[0])),!Rs(m)){const{nick:D="",avatar:M=""}=m;n.nick=D,n.avatar=M}}const ZQ=s=>({lastTime:s?.time||s?.lastTime||0,lastSequence:s?.sequence||s?.lastSequence||0,fromAccount:s?.from||s?.fromAccount||"",messageForShow:zc(s?.type,s?.payload),payload:s?.payload||null,type:s?.type||"",isRevoked:s?.isRevoked||!1,cloudCustomData:s?.cloudCustomData||"",onlineOnlyFlag:s?._onlineOnlyFlag||!1,nick:s?.nick||"",nameCard:s?.nameCard||"",version:s?.version||0,isPeerRead:s?.isPeerRead||!1,revoker:s?.revoker||null});var XQ=Object.freeze({__proto__:null,ChatError:gs,WorkflowManager:ws,buildAndSendPacket:gg,buildLastMessage:ZQ,get builtInPlugins(){return yB},checkBusinessCapabilityBits:tn,deepMerge:dd,getCurrentUserID:Ar,getErrorMessage:rs,getMessagePreviewText:zc,isC2CConv:s=>l(s)&&s.slice(0,3)===ka.CONV_C2C,isCommunity:Xr,isGroupConv:s=>l(s)&&s.slice(0,5)===ka.CONV_GROUP,isInternational:Rl,isTopic:Wc,isUnlimitedAVChatRoom:function(){var s;return!!(!((s=fe.store.get("instance"))===null||s===void 0)&&s.unlimitedAVChatRoom)},liteChatInstanceMap:da,registerInterceptor:Mc,registerValidateConfig:jc,requireAuth:Id,get sdkEdition(){return Km},setGroupTipsUserInfo:DB,t:Nu,updateGroupAtInfo:(s,n)=>{const{CONV_AT_ME:g,CONV_AT_ALL:u,CONV_AT_ALL_AT_ME:E}=Lo;if(function(M,T){const{CONV_AT_ME:P,CONV_AT_ALL:W,CONV_AT_ALL_AT_ME:iA}=Lo,{groupID:EA,sequence:RA}=M;let kA=!1;return Xr({groupID:EA})&&T.forEach(xA=>{xA.messageSequence===RA&&(xA.atTypeArray.includes(P)&&M.groupAtType.includes(W)&&(xA.atTypeArray=[iA]),xA.atTypeArray.includes(W)&&M.groupAtType.includes(P)&&(xA.atTypeArray=[iA],xA.__random=M.__random,xA.__sequence=M.__sequence),kA=!0)}),kA}(s,n))return;let m=[...s.groupAtType];m.includes(g)&&m.includes(u)&&(m=[E]);const D={from:s.from,groupID:s.groupID,topicID:s.topicID,messageSequence:s.sequence,atTypeArray:m,__random:s.__random,__sequence:s.__sequence};n.push(D)},validateAndExecute:Sr,validateParameters:lI});class nu{constructor(){this._builtInPlugins=new Set,this._externalPlugins=new Set}static getInstance(){return nu._instance||(nu._instance=new nu),nu._instance}static setInstance(n){nu._instance=n}installBuiltInPlugin(n){n&&this._installPlugin(n,this._builtInPlugins)}installExternalPlugin(n){n&&this._installPlugin(n,this._externalPlugins)}clear(){this._builtInPlugins=new Set,this._externalPlugins=new Set}_installPlugin(n,g){let u=[];u=h(n)?n:[n];const E=u.findIndex(D=>D?.name==="AVChatRoom"),m=E>-1?u.splice(E,1):[];u.forEach(D=>{this._isPluginInstalled(D.name)||(D&&vg(D.install)?(g.add(D.name),vg(D.getInstalledSubPlugins)?(m?.forEach(M=>g.add(M?.name)),D.install(Cr.getInstance().exposeApiForPlugin(),m)):D.install(Cr.getInstance().exposeApiForPlugin()),vg(D.handleLoginSuccess)&&this._isLoggedIn()&&D.handleLoginSuccess()):vg(D)?(g.add(D.name),D(Cr.getInstance().exposeApiForPlugin()),vg(D.handleLoginSuccess)&&this._isLoggedIn()&&D.handleLoginSuccess()):console.warn('A plugin must either be a function or an object with an "install" function.'))})}_isPluginInstalled(n){return this._builtInPlugins.has(n)||this._externalPlugins.has(n)}_isLoggedIn(){var n;return((n=fe.store.get("login"))===null||n===void 0?void 0:n.isLoggedIn)===!0}}var SB=new class{constructor(){this._conversationMap=new Map}getConversationMap(){return this._conversationMap}getConversation(s){return this._conversationMap.get(s)}updateConversation(s,n,g){const{emit:u=!0,needSort:E=!1}=g||{},m=this._conversationMap.get(s);m&&!Rs(n)&&(Object.keys(n).forEach(D=>{m[D]=n[D]}),u&&fe.notificationCenter.emitInnerEvent(so.CONVERSATION_UPDATED,{needSort:E}))}deleteConversation(s){this._conversationMap.has(s)&&(this._conversationMap.delete(s),fe.notificationCenter.emitInnerEvent(so.CONVERSATION_UPDATED))}},$Q=new class{constructor(){this._groupMap=new Map}getGroupMap(){return this._groupMap}getGroup(s){return this._groupMap.get(s)}updateGroup(s,n){const g=this._groupMap.get(s);g&&!Rs(n)&&Object.keys(n).forEach(u=>{g[u]=n[u]})}},Ap=new class{constructor(){this._messagesByConversation=new Map}updateMessage(s,n,g){var u;const{operation:E,updateUnreadCount:m=!0}=g,D=Do(g,["operation","updateUnreadCount"]),M=[];for(const T of n){const P=(u=this._messagesByConversation.get(s))===null||u===void 0?void 0:u.get(T);if(!P)return!1;Object.keys(D).forEach(W=>{P[W]=D[W]}),M.push(P)}return this._emitMessageStoreOperationEvent(E,{conversationID:s,messageList:M,updateUnreadCount:m}),M}getMessagesByConversation(s){var n;return[...((n=this._messagesByConversation.get(s))===null||n===void 0?void 0:n.values())||[]]}getMessages(){return this._messagesByConversation}_emitMessageStoreOperationEvent(s,n){const{conversationID:g}=n;Wc(g)?fe.notificationCenter.emitInnerEvent(vu[s],n):fe.notificationCenter.emitInnerEvent(s,n)}},rc=new class{constructor(){this.userProfileMap=new Map,this.friendMap=new Map}getUserProfileMap(){return this.userProfileMap}getFriendMap(){return this.friendMap}getUserProfile(s){return this.userProfileMap.get(s)}getFriend(s){return this.friendMap.get(s)}},bD=Object.freeze({__proto__:null,conversationStore:SB,groupStore:$Q,messageStore:Ap,userStore:rc});class Cr{static getInstance(){return Cr._instance||(Cr._instance=new Cr),Cr._instance}static setInstance(n){Cr._instance=n}constructor(){this._experimentalApiMap={statTUIKeyFeatures:this.statKeyFeatureUsage.bind(this),setApplicationID:this.setApplicationID.bind(this)},this._apiHandlersMap={},this._apiMap={on:fe.notificationCenter.subscribeOuterEvent.bind(fe.notificationCenter),off:fe.notificationCenter.unSubscribeOuterEvent.bind(fe.notificationCenter),destroy:this.destroy.bind(this),callExperimentalAPI:this.callExperimentalAPI.bind(this),use:nu.getInstance().installExternalPlugin.bind(nu.getInstance()),registerPlugin:this.registerPlugin.bind(this),setLogLevel:this.setLogLevel.bind(this)}}registerPlugin(n){fe.ssoLog.debug("registerPlugin",n)}statKeyFeatureUsage(n){fe.ssoLog.debug("statTUIKeyFeatures",n)}setLogLevel(n){fe.ssoLog.debug("setLogLevel",n),fe.ssoLog.setLogLevel(n)}setApplicationID(n){fe.store.set("instance",{applicationID:n})}getApiMap(){return this._apiMap}setApiMap(n){this._apiMap=n}registerApi(n){const{common:{timeManager:g},utils:{safeStringify:u}}=fe,{apiName:E,context:m,methodName:D=E,matcher:M}=n;this._apiHandlersMap[E]||(this._apiHandlersMap[E]=[]),this._apiHandlersMap[E].push({context:m,methodName:D,matcher:M}),this._apiMap[E]&&this._apiHandlersMap[E].length!==1||(this._apiMap[E]=(...T)=>{const P=g.getServerTimeMs();let W=0;E==="login"&&(W=4),JI.includes(E)&&fe.ssoLog.debug(E,`${E} start params: ${u(T)}`),Sr(D,T);const iA=this._apiHandlersMap[E];for(const EA of iA)if(!EA.matcher||EA.matcher(T))try{const RA=EA.context[EA.methodName].bind(EA.context)(...T);return this._isPromiseLike(RA)?this._handleAsyncResult(RA,E,W,P):(this._reportApiSuccessLog({result:RA,apiName:E,eventType:W,startTime:P}),RA)}catch(RA){throw fe.ssoLog.error(E,`${E} fail ${RA?.message||RA?.errorMessage})`,{error:RA,costTime:g.getServerTimeMs()-P,eventType:W,method:E}),RA}})}registerExperimentalAPI(n,g,u){const E=u||n;this._experimentalApiMap[n]=g[E].bind(g)}destroy(){return pA(this,void 0,void 0,function*(){var n,g;try{!((n=fe.store.get("login"))===null||n===void 0)&&n.isLogin&&(yield this._apiMap.logout()),fe.notificationCenter.emitInnerEvent(so.DESTROY)}catch(u){console.debug("destroy error: ",u)}finally{fe.notificationCenter.emitOuterEvent(Dr.SDK_DESTROY,{SDKAppID:(g=fe.store.get("instance"))===null||g===void 0?void 0:g.sdkAppId}),da.clear(),nu.getInstance().clear(),ws.getInstance().destroy(),fe.destroy()}})}exposeApiForClient(){return this._apiMap}exposeApiForPlugin(){return Object.assign(Object.assign({InnerEvent:so,InnerEventSubType:fe.notificationCenter.InnerEventSubType,OuterEvent:Dr,OuterConstant:Lo,SignalingEvent:Hc,helper:Object.assign(Object.assign(Object.assign({},fe.utils),fe.common),{registerApi:this.registerApi.bind(this),registerExperimentalAPI:this.registerExperimentalAPI.bind(this),registerInterceptor:Mc,registerValidateConfig:jc,checkBusinessCapabilityBits:tn,registerWorkflowStep:ws.getInstance().registerWorkflowStep.bind(ws.getInstance()),ChatError:gs}),apiMap:this._apiMap},fe),{constants:Object.assign(Object.assign({},za),fe.constants),common:Object.assign(Object.assign(Object.assign({},XQ),fe.common),{workflowManager:ws.getInstance()}),utils:fe.utils,appStore:bD})}callExperimentalAPI(n,g){return fe.ssoLog.debug(`callExperimentalAPI.${n} start params: ${fe.utils.safeStringify(g)}`),this._experimentalApiMap[n]?this._experimentalApiMap[n](g):(fe.ssoLog.error("callExperimentalAPI",`callExperimentalAPI.${n} not found, params: ${fe.utils.safeStringify(g)}`),Promise.reject(new gs({code:Ea.INVALID_OPERATION})))}_isPromiseLike(n){return n!==null&&typeof n=="object"&&typeof n.then=="function"}_handleAsyncResult(n,g,u,E){return n.then(m=>(this._reportApiSuccessLog({result:m,apiName:g,eventType:u,startTime:E}),m)).catch(m=>{throw fe.ssoLog.error(g,`${g} fail ${m?.message||m?.errorMessage})`,{error:m,costTime:fe.common.timeManager.getServerTimeMs()-E,eventType:u,method:g,startTime:E}),m})}_reportApiSuccessLog(n){let{result:g,apiName:u,startTime:E,eventType:m}=n;const{timeManager:D}=fe.common,{successLog:{message:M,moreMessage:T}={message:"",moreMessage:""}}=g||{},P=D.getServerTimeMs();u==="login"&&(E+=D.getTimeOffsetWithServer()),JI.includes(u)&&fe.ssoLog.info(u,`${u} success ${M} ${T}`,{costTime:P-E,eventType:m,message:M,moreMessage:T,startTime:E}),g?.successLog&&delete g.successLog}}class uR{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120,this._customLoginInfo=""}init(){const{notificationCenter:n,store:g}=fe;g.set("login",{isReady:!1}),Cr.getInstance().registerApi({apiName:"login",context:this}),Cr.getInstance().registerApi({apiName:"logout",context:this}),Cr.getInstance().registerApi({apiName:"getLoginUser",context:this}),Cr.getInstance().registerApi({apiName:"isReady",context:this}),Cr.getInstance().registerApi({apiName:"getServerTime",context:this}),Cr.getInstance().registerExperimentalAPI("setCustomLoginInfo",this),n.subscribeInnerEvent(so.RECONNECTED,this._reLogin,this),fe.notificationCenter.subscribeInnerEvent(so.DESTROY,this._dispose,this)}login(n){return pA(this,void 0,void 0,function*(){var g;const{sdkEdition:u}=fe.store.get("instance")||{};try{if(this._isLoginIn())return this._createRepeatLoginResponse();if(this._isLoginFrequencyExceeded())throw new gs({functionName:"login",code:Ea.REPEAT_LOGIN});const E=yield this._performLogin(n);this._validateAfterLogin(E),this._handleLoginSuccess(E),yield this._ensureAsyncComplete(),this._updateAndEmitSDKReady(),this._latestLoginAt=0;const m=(g=fe.channel.getSocketAdapter())===null||g===void 0?void 0:g.getId(),{appId:D,href:M}=fe.store.get("instance")||{},{instanceID:T,customStatus:P}=E||{};return{code:0,data:E,successLog:{message:u,moreMessage:`socketID:${m} instanceID:${T} customStatus:${P} href: ${M} appId: ${D}`}}}catch(E){const{errorCode:m}=E;m!==Ea.REPEAT_LOGIN&&(this._latestLoginAt=0);const D=new gs({functionName:"login",code:m});throw console.error(D),D}})}_reLogin(){return pA(this,void 0,void 0,function*(){var n;try{if(!this._isLoginIn())return;const g=yield Tu(this._customLoginInfo);if(g){const{instanceID:u,customStatus:E}=g;fe.store.set("login",{statusInstanceId:u}),ws.getInstance().executeWorkflow(xt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,{customStatus:E,statusType:mE.USER_STATUS_ONLINE});const m=(n=fe.channel.getSocketAdapter())===null||n===void 0?void 0:n.getId();fe.ssoLog.info("reLogin",`socketId:${m} instanceId:${u}`)}}catch(g){console.warn(g)}})}logout(){return pA(this,arguments,void 0,function*(n=na.USER_INITIATED){const{ssoLog:g}=fe;g.debug("logout",`logout start logoutReason: ${n}`);try{yield this._performLogout(n),g.info("logout","logout success"),fe.ssoLog.uploadSSOLogData()}catch(u){const{errorCode:E}=u;throw new gs({functionName:"logout",code:E})}finally{this.handleLogoutCompleted()}return{code:0,data:{}}})}getLoginUser(){return this._isLoginIn()?Ar():""}isReady(){var n;return(n=fe.store.get("login"))===null||n===void 0?void 0:n.isReady}setCustomLoginInfo(n=""){this._customLoginInfo=n}handleLogoutCompleted(){this._updateAndEmitSDKNotReady(),this._reset(),ws.getInstance().reset(),fe.notificationCenter.emitInnerEvent("logout")}getServerTime(){const{timeManager:n}=fe.common;return n.getServerTimeMs()}_updateAndEmitSDKReady(){fe.store.set("login",{isReady:!0}),setTimeout(()=>{fe.notificationCenter.emitOuterEvent(Dr.SDK_READY,{name:Dr.SDK_READY})},1)}_updateAndEmitSDKNotReady(){fe.store.set("login",{isReady:!1}),fe.notificationCenter.emitOuterEvent(Dr.SDK_NOT_READY,{name:Dr.SDK_NOT_READY})}_validateAfterLogin(n){const g="login";if(!n)throw new gs({functionName:g,message:"login response is empty"});const{tinyID:u,a2Key:E}=n||{};if(!u)throw new gs({functionName:g,code:Ea.NO_TINYID});if(!E)throw new gs({functionName:g,code:Ea.NO_A2KEY})}_createRepeatLoginResponse(){var n;return{code:0,data:{actionStatus:"OK",errorCode:0,errorInfo:rs({code:"RepeatLogin",replacement1:(n=fe.store.get("login"))===null||n===void 0?void 0:n.userId}),repeatLogin:!0}}}_performLogin(n){return pA(this,void 0,void 0,function*(){const{userID:g,userSig:u}=n;return fe.store.set("login",{userId:g,userSig:u}),this._latestLoginAt=Date.now(),Tu(this._customLoginInfo)})}_ensureAsyncComplete(){return pA(this,void 0,void 0,function*(){yield new Promise(n=>{setTimeout(()=>n(null),1)})})}_handleLoginSuccess(n){const{timeManager:g}=fe.common,{helloInterval:u,timeStamp:E,customStatus:m,purchaseBits:D}=n,M=1e3*E;g.calculateTimeOffsetWithServer(this._latestLoginAt,M),this._helloInterval=u||120,this._updateLoginStore(n),fe.user.userStatus.setCustomStatus(m),ws.getInstance().executeWorkflow(xt.SYNC_SERVER_INFO_AFTER_LOGIN,{purchaseBits:D}),fe.common.taskScheduler.addTask({id:Gg,intervalMs:1e3*this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this})}_performLogout(n){return function(g){return pA(this,void 0,void 0,function*(){const{logoutReason:u}=g,E="im_open_status.wslogout",m=fe.common.generateProtocolData({servcmd:E,data:{wslogout_type:u,isWebUniapp:0}}),D=`${m.head.seq}${E}`;return yield fe.channel.sendPacket(m,{requestId:D})})}({logoutReason:n})}_updateLoginStore(n){const{a2Key:g,tinyID:u,instanceID:E,authKey:m}=n;fe.store.set("login",{a2Key:g,tinyID:u,statusInstanceId:E,authKey:m,isLoggedIn:!0})}_sendOnlinePresenceRequest(){return pA(this,void 0,void 0,function*(){this._latestSendOnlinePresenceRequestTime=Date.now();try{yield function(){const n="im_open_status.wshello",g=fe.common.generateProtocolData({servcmd:n,data:{isWebUniapp:0}}),u=`${g.head.seq}${n}`;return fe.channel.sendPacket(g,{requestId:u})}()}catch(n){fe.ssoLog.warn("_sendOnlinePresenceRequest",` error:${n.message}`)}})}_isLoginIn(){var n;return((n=fe.store.get("login"))===null||n===void 0?void 0:n.isLoggedIn)===!0}_isLoginFrequencyExceeded(){return Date.now()-this._latestLoginAt<=15e3}_reset(){fe.common.taskScheduler.removeTask(Gg),this._helloInterval=120,this._latestSendOnlinePresenceRequestTime=0,this._latestLoginAt=0,this._customLoginInfo="",fe.store.clear("login"),fe.store.set("login",{isReady:!1}),fe.store.set("instance",{applicationID:0})}_dispose(){this._reset();const{notificationCenter:n}=fe;n.unSubscribeInnerEvent(so.RECONNECTED,this._reLogin,this),n.unSubscribeInnerEvent(so.DESTROY,this._dispose,this)}}const ER={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}},YT={logout:!0};class vh{constructor(){this.loginAction=new uR,this.kickedOutHandler=new _u,this.loginAction.init(),this.kickedOutHandler.init(),jc({auth:YT,params:ER})}}var Kr,zu,VE;(function(s){s.CONV_C2C="C2C",s.CONV_GROUP="GROUP",s.CONV_TOPIC="TOPIC",s.CONV_SYSTEM="@TIM#SYSTEM"})(Kr||(Kr={})),function(s){s.MSG_PRIORITY_HIGH="High",s.MSG_PRIORITY_NORMAL="Normal",s.MSG_PRIORITY_LOW="Low",s.MSG_PRIORITY_LOWEST="Lowest"}(zu||(zu={})),function(s){s.MSG_TEXT="TIMTextElem",s.MSG_CUSTOM="TIMCustomElem",s.MSG_LOCATION="TIMLocationElem",s.MSG_FACE="TIMFaceElem",s.MSG_IMAGE="TIMImageElem",s.MSG_AUDIO="TIMSoundElem",s.MSG_FILE="TIMFileElem",s.MSG_VIDEO="TIMVideoFileElem",s.MSG_GRP_TIP="TIMGroupTipElem",s.MSG_GRP_SYS_NOTICE="TIMGroupSystemNoticeElem",s.MSG_MERGER="TIMRelayElem"}(VE||(VE={}));const kD={1:zu.MSG_PRIORITY_HIGH,2:zu.MSG_PRIORITY_NORMAL,3:zu.MSG_PRIORITY_LOW,4:zu.MSG_PRIORITY_LOWEST},LD=0,dR=1;var Zu;(function(s){s.IN="in",s.OUT="out"})(Zu||(Zu={}));const CR=2,ep={};function ru(s){if(!s)return 0;if(ep[s]===void 0){const n=new Date,g=`3${n.getHours()}`.slice(-2),u=`0${n.getMinutes()}`.slice(-2),E=`0${n.getSeconds()}`.slice(-2);ep[s]=parseInt([g,u,E,"0001"].join(""),10),console.log(`autoIncrementIndex start index:${ep[s]}`)}else ep[s]+=1;return ep[s]}class JE{constructor(n){this.ID="",this.random=0,this.sequence=0,this.nameCard="",this.isRead=!1,this.isPeerRead=!1,this.isDeleted=!1,this.isResend=!1,this.hasRiskContent=!1,this._onlineOnlyFlag=!1,this.atUserList=[],this._groupAtInfoList=[],this.isBroadcastMessage=!1,this.priority=zu.MSG_PRIORITY_NORMAL,this._relayFlag=!1;const{clientTime:g=fe.common.timeManager.getServerTimeSeconds()||0,senderTinyID:u,currentUser:E,needReadReceipt:m,isSupportExtension:D,customModerationConfigurationId:M,to:T,from:P,nick:W="",avatar:iA="",time:EA,messageControlInfo:RA,tinyID:kA,cloudCustomData:xA="",messageLifeTime:LA,messageVersion:SA=0,conversationType:OA,sequence:JA,checkResult:ne=0,isPlaceMessage:se=0,messageFlagBits:_i,receiverList:Ti,isSystemMessage:Lt=!1,status:Ni=Yr.SUCCESS,revokeReason:cs="",conversationSubType:Se,clientSequence:mt,protocol:UA="JSON",revokerInfo:oi={userID:"",nick:"",avatar:""},readReceiptInfo:_s={readCount:void 0,unreadCount:void 0,isPeerRead:void 0,timestamp:0},random:Gi,groupProfile:Fr,atUserList:xi,flow:gr,isRead:_t=!1,priority:Tt=zu.MSG_PRIORITY_NORMAL,onlineOnlyFlag:$u=!1,nameCard:ln="",quoteInfo:Bo}=n;var ll;this.clientTime=g,this.senderTinyID=u||kA,this.needReadReceipt=m===!0||m===1,this.isSupportExtension=D===!0||D===1,this._cmConfigID=M,this.to=T,this.nick=W,this.avatar=iA,this.protocol=UA,this.random=Gi===void 0?(ll=ll||99999999,Math.round(Math.random()*ll)):Gi,this.time=EA||Math.ceil(Date.now()/1e3),this._isExcludedFromLastMessage=!!RA?.excludedFromLastMessage,this._isExcludedFromUnreadCount=!!RA?.excludedFromUnreadCount,this.isModified=!!SA,this.cloudCustomData=xA,this.messageLifeTime=LA,this.from=P||null,this.sequence=JA||0,this.conversationType=OA||Kr.CONV_C2C,this.hasRiskContent=ne>1,this.version=SA,this.isPlaceMessage=se,this.isRevoked=se===2||_i===8,this.isSystemMessage=Lt,this.readReceiptInfo=_s,this.revokeReason=cs,this.revokerInfo=oi,this._receiverList=Ti,this.conversationSubType=Se,this.revoker=oi?.revoker||"",this.clientSequence=mt||JA||0,this.status=Ni,this.atUserList=xi||[],this.flow=gr,this.isRead=_t,this.priority=Tt,this._onlineOnlyFlag=$u,this.nameCard=ln,this.quoteInfo=Bo,this.reInitialize(E),this._initC2CReadReceiptInfo(n),this._extractGroupInfo(Fr)}getElements(){return this._elements}isOnlineMessage(){return this.messageLifeTime===0}setElement(n){Array.isArray(n)?this._elements=n:this._elements=[n],this._updatePayloadAndType()}transformElementsToServerFormat(){return this._elements?Array.isArray(this._elements)?this._elements.map(n=>n.transformToServerFormat()):this._elements.transformToServerFormat():null}setRelayFlag(n){this._relayFlag=n}validateBeforeSend(){var n,g,u;return this._relayFlag?{isValid:!0}:((n=this._elements)===null||n===void 0?void 0:n.length)>0?(u=(g=this._elements[0])===null||g===void 0?void 0:g.validateBeforeSend)===null||u===void 0?void 0:u.call(g):{isValid:!1}}_updatePayloadAndType(){this._elements[0]&&(this.payload=this._elements[0].content,this.type=this._elements[0].type)}_initC2CReadReceiptInfo(n){const{readReceiptSentByPeer:g,timestamp:u=0}=n;this.conversationType===Kr.CONV_C2C&&this.needReadReceipt===!0&&(this.readReceiptInfo.isPeerRead=g===1,this.readReceiptInfo.timestamp=u)}_extractGroupInfo(n){if(!n)return;const{From_AccountNick:g,From_AccountHeadurl:u,MsgFrom_AccountExtraInfo:E,GroupType:m}=n,{NameCard:D}=E||{};typeof g=="string"&&(this.nick=g),typeof u=="string"&&(this.avatar=u),typeof D=="string"&&(this.nameCard=D),this.conversationSubType=m}reInitialize(n){n===this.from&&(this.isRead=!0),this._initSequence(n),this._concatConversationID(n),this.generateMessageID()}_concatConversationID(n){let g="";const u=this.conversationType;u!==Kr.CONV_SYSTEM?(g=u===Kr.CONV_C2C?n===this.from?this.to:this.from:this.to,this.conversationID=g?`${u}${g}`:null):this.conversationID=Kr.CONV_SYSTEM}_initSequence(n){this.clientSequence===0&&n&&(this.clientSequence=ru(n)),this.sequence===0&&this.conversationType===Kr.CONV_C2C&&(this.sequence=this.clientSequence)}generateMessageID(){this.from===Kr.CONV_SYSTEM&&(this.senderTinyID="144115198244471703"),this.ID=`${this.senderTinyID}-${this.clientTime}-${this.random}`}setIsRead(n){this.isRead=n}}class _d{static parseServerPushElement(n){const{MsgContent:g={}}=n,{Data:u,Ext:E,Desc:m}=g;return new _d({data:u,description:m,extension:E})}constructor(n){this.type=VE.MSG_CUSTOM;const{data:g="",description:u="",extension:E=""}=n;this.content={data:g,description:u,extension:E}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},u=g?this.payload:this.content,{data:E,description:m,extension:D}=u;return{MsgType:this.type,MsgContent:{Data:E,Ext:D,Desc:m}}}validateBeforeSend(){const{isEmpty:n}=fe.utils,g=[this.content.data,this.content.description,this.content.extension].some(u=>!n(u));return{isValid:g,error:g?null:{message:"content can not be empty"}}}}class Td{static parseServerPushElement(n){const{MsgContent:g={Text:""}}=n,{Text:u}=g;return new Td({text:u})}constructor(n){this.type=wg.MSG_TEXT,this.content={text:n.text||""}}validateBeforeSend(){var n,g;return((g=(n=this.content)===null||n===void 0?void 0:n.text)===null||g===void 0?void 0:g.length)>0?{isValid:!0}:{isValid:!1,error:{message:"content can not be empty"}}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},u=g?this.payload:this.content,{text:E}=u;return{MsgType:this.type,MsgContent:{Text:E}}}}var jm=new class{constructor(){this._elementClassMap={[VE.MSG_CUSTOM]:_d,[VE.MSG_TEXT]:Td}}init(){Cr.getInstance().registerApi({apiName:"createCustomMessage",context:this}),Cr.getInstance().registerApi({apiName:"createTextMessage",context:this})}registerElementClass(s,n){var g;(g=n).prototype!==void 0&&"constructor"in g.prototype&&(this._elementClassMap[s]=n)}getElementClass(s){return this._elementClassMap[s]}createMessage(s){const{from:n,flow:g=Zu.OUT}=s,{userId:u}=fe.store.get("login")||{};this._isSendByCurrentInstance({from:n,flow:g,currentUser:u})?this._updateWithSenderInfo(s):this._isMultiEndpointSyncMessage({from:n,flow:g,currentUser:u})&&(s.flow=Zu.OUT);const E=Object.assign(Object.assign({},s),{currentUser:u});return new JE(E)}createCustomMessage(s){const n=Ar(),g=this.createMessage(Object.assign(Object.assign({},s),{from:n})),u=this._elementClassMap[VE.MSG_CUSTOM];if(!g)return null;if(u){const E=new u(s.payload);g.setElement(E)}return g}createTextMessage(s){var n;if(!s)return null;const g=typeof s.payload=="string"?s.payload:((n=s?.payload)===null||n===void 0?void 0:n.text)||"",u=new Td({text:g}),E=Ar(),m=fe.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:E}));return m.setElement(u),m}_updateWithSenderInfo(s){var n,g;const{nick:u,avatar:E,conversationType:m,to:D}=s,{userId:M,tinyID:T}=fe.store.get("login")||{},P=rc.getUserProfile(M);return s.nick=u||P?.nick||"",s.avatar=E||P?.avatar||"",s.tinyID=s.tinyID||T||"",s.from=M,s.status=Yr.UNSENT,s.flow=Zu.OUT,m===ka.CONV_GROUP&&(s.nameCard=(g=(n=$Q.getGroup(D))===null||n===void 0?void 0:n.selfInfo)===null||g===void 0?void 0:g.nameCard),s}_isMultiEndpointSyncMessage(s){const{from:n,flow:g,currentUser:u}=s;return n===u&&g===Zu.IN}_isSendByCurrentInstance(s){const{from:n,flow:g,currentUser:u}=s;return n===u&&g===Zu.OUT}};const hR={PushFlag:0,Title:"",Desc:"",Ext:"",ApnsInfo:{Sound:"",BadgeMode:0,IsVoipPush:void 0,Image:"",InterruptionLevel:"active",ContentAvailable:0},AndroidInfo:{Sound:"",XiaoMiChannelID:"",OPPOChannelID:"",GoogleChannelID:"",VIVOClassification:1,VIVOCategory:"",HuaWeiCategory:"",OPPOCategory:"",HuaWeiImage:"",HonorImage:"",GoogleImage:"",HonorImportance:"",MeizuNotifyType:void 0}},Nd={HonorImportance:{range:["LOW","NORMAL"],defaultValue:void 0},MeizuNotifyType:{range:[0,1],defaultValue:void 0}},UD={enableIOSBackgroundNotification:{range:[!0,!1],defaultValue:!1},interruptionLevel:{range:["passive","active","time-sensitive","critical"],defaultValue:"active"}};function BR(s,n){return Object.keys(n).forEach(g=>{const{range:u,defaultValue:E}=n[g];s[g]=u.includes(s[g])?s[g]:E}),s}function tp(s){const n=s.lastIndexOf(".");return n===-1?s:s.slice(0,n)}function QR(s){const{androidInfo:n={},androidOPPOChannelID:g=""}=s,u=n.OPPOChannelID||g,E=BR(n,Nd),{sound:m="",FCMChannelID:D=""}=E,M=Do(E,["sound","FCMChannelID"]);return Object.assign(Object.assign({},M),{Sound:tp(m),OPPOChannelID:u,GoogleChannelID:D})}function pR(s){const{apnsInfo:n={},ignoreIOSBadge:g=!1,disableVoipPush:u}=s,E=BR(n,UD),{ignoreIOSBadge:m,disableVoipPush:D,enableIOSBackgroundNotification:M}=E,T=Do(E,["ignoreIOSBadge","disableVoipPush","enableIOSBackgroundNotification"]),P=m===!0||g===!0?1:0;let W;return r(u)||(W=u===!1?1:0),r(D)||(W=D===!1?1:0),Object.assign(Object.assign({},T),{BadgeMode:P,IsVoipPush:W,ContentAvailable:M?1:0})}function FD(s){return fe.utils.isPlainObject(s)?{PushFlag:s.disablePush===!0?1:0,Title:s.title||"",Desc:s.description||"",Ext:s.extension||"",ApnsInfo:pR(s),AndroidInfo:QR(s)}:hR}function Wm(s){const{From_AccountHeadurl:n,From_AccountNick:g,IsNeedReadReceipt:u,IsPeerRead:E,IsSyncMsg:m,MsgBody:D,MsgClientTime:M,MsgLifeTime:T,MsgRandom:P,MsgSeq:W,MsgTimeStamp:iA,SendMsgControl:EA,SupportMessageExtension:RA,TinyId:kA,MsgCheckResult:xA,CloudCustomData:LA,MsgVersion:SA,MsgFlagBits:OA,RevokerInfo:JA,InnerSdkCustomData:ne}=s;let se,{From_Account:_i,To_Account:Ti}=s;if(m===1){const Lt=Ti;Ti=_i,_i=Lt}if(JA){const{Reason:Lt,Revoker_Account:Ni,Revoker_FromUin:cs}=JA;se={reason:Lt,revoker:Ni,revokerFromUin:cs,userID:Ni}}return{from:_i,avatar:n,nick:g,needReadReceipt:u===1,isSyncMessage:m,clientTime:M,messageLifeTime:T,random:P,sequence:W,time:iA,messageControlInfo:{excludedFromLastMessage:EA?.NoLastMsg===1,excludedFromUnreadCount:EA?.NoUnread===1},isSupportExtension:RA,to:Ti,tinyID:kA,checkResult:xA,cloudCustomData:LA,revokerInfo:se,messageVersion:SA,messageFlagBits:OA,readReceiptSentByPeer:E,elements:vC(D),onlineOnlyFlag:T===0,quoteInfo:ip(ne)}}function zm(s){const{From_Account:n,MsgBody:g,MsgClientTime:u,MsgRandom:E,MsgSeq:m,MsgTimeStamp:D,To_Account:M,MsgVersion:T,CloudCustomData:P,MsgCheckResult:W}=s;return{from:n,clientTime:u,random:E,sequence:m,time:D,to:M,elements:vC(g),messageVersion:T,cloudCustomData:P,checkResult:W}}function OD(s){const{ClientSeq:n,From_Account:g,GroupInfo:u,MsgBody:E,MsgClientTime:m,MsgRandom:D,MsgSeq:M,MsgTimeStamp:T,SendMsgControl:P,SupportMessageExtension:W,TinyId:iA,CloudCustomData:EA,MsgVersion:RA,MsgCheckResult:kA,NeedReadReceipt:xA,IsPlaceMsg:LA,RevokerInfo:SA,GroupAtInfo:OA,OnlineOnlyFlag:JA,InnerSdkCustomData:ne}=s;let se,_i=zu.MSG_PRIORITY_NORMAL;if(Object.keys(kD).includes(String(s.MsgPriority))&&(_i=kD[s.MsgPriority]),SA){const{Reason:Lt,Revoker_Account:Ni,Revoker_FromUin:cs}=SA;se={reason:Lt,revoker:Ni,revokerFromUin:cs,userID:Ni}}const Ti=function(Lt){const Ni=[];return Array.isArray(Lt)&&Lt.forEach(cs=>{cs.GroupAtAllFlag===LD?Ni.push(cs.GroupAt_Account):cs.GroupAtAllFlag===dR&&Ni.push(Lo.MSG_AT_ALL)}),Ni}(OA);return{clientSequence:n,from:g,groupProfile:u,clientTime:m,priority:_i,random:D,sequence:M,time:T,messageControlInfo:{excludedFromLastMessage:P?.NoLastMsg===1,excludedFromUnreadCount:P?.NoUnread===1},isSupportExtension:W,tinyID:iA,cloudCustomData:EA,messageVersion:RA,checkResult:kA,needReadReceipt:xA,isPlaceMessage:LA,revokerInfo:se,atUserList:Ti,elements:vC(E),to:VT(s),onlineOnlyFlag:JA===1,quoteInfo:ip(ne)}}function VT(s){const{utils:{isEmpty:n},constants:{IS_TOPIC_MESSAGE:g}}=fe,{ToGroupId:u,GroupInfo:{MillionGroupFlag:E=0,TopicId:m}={}}=s;return E!==g||n(m)?u:m}function vC(s){if(!s)return null;if(Array.isArray(s))return s.map(g=>{const u=fe.message.messageFactory.getElementClass(g.MsgType);return u?.parseServerPushElement(g)});const n=fe.message.messageFactory.getElementClass(s.MsgType);return n?.parseServerPushElement(s)}function PD(s){const{From_Account:n,MsgBody:g,MsgClientTime:u,MsgRandom:E,MsgSeq:m,MsgTimeStamp:D,GroupId:M,TopicId:T,MsgVersion:P,CloudCustomData:W,MsgCheckResult:iA}=s;return{from:n,clientTime:u,random:E,sequence:m,time:D,groupID:M,topicID:T,elements:vC(g),messageVersion:P,cloudCustomData:W,checkResult:iA}}function ip(s){const{utils:{isString:n,safeStringify:g},ssoLog:u}=fe;if(!n(s))return null;try{const{messageID:E,messageTime:m,messageSequence:D}=JSON.parse(s).businessQuote;return{msgID:E,messageTime:m,messageSequence:D}}catch(E){return u.debug("_parseServerQuoteInfo",g(E)),null}}function op({conversationUpdateFields:s,message:n}){const{conversationID:g,conversationType:u,conversationSubType:E,flow:m,_isExcludedFromUnreadCount:D,_isExcludedFromLastMessage:M}=n,T=M?"":ZQ(n),P=!D&&m===Zu.IN;s.has(g)?(s.get(g).lastMessage=T,P&&s.get(g).unreadCount++):s.set(g,{conversationID:g,type:u,subType:E,unreadCount:P?1:0,lastMessage:T})}function MB(s){return s.filter(n=>{const g=!Rs(n?._elements),u=n?.isPlaceMessage===1;return g||fe.ssoLog.error("emptyMessageBody",`from:${n.from} to:${n.to} sequence:${n.sequence}`),g&&!u})}function vB(s){const{messageDataHandler:n}=fe.message;return!n.isInMessageList(s)&&!n.isMessageSentByCurrentInstance(s)}var mR=Object.freeze({__proto__:null,autoIncrementIndex:ru,createAndroidPushInfo:QR,createApnsPushInfo:pR,createOfflinePushInfo:FD,filterValidMessages:MB,getAndroidSoundName:tp,parseServerGroupMessage:OD,parseServerPushC2CModifyMessage:zm,parseServerPushGroupModifyMessage:PD,parseServerPushMessage:Wm,parseServerPushMessageElement:vC,shouldStoreMessage:vB,updateConversationFields:op});const{isPlainObject:fR}=fe.utils;function sp(s,n={}){const{onlineUserOnly:g,messageControlInfo:u}=n;let{offlinePushInfo:E}=n;s.conversationType===Kr.CONV_C2C&&g===!0&&(E?E.disablePush=!0:E={disablePush:!0});let m="";typeof s.cloudCustomData=="string"&&s.cloudCustomData.length>0&&(m=s.cloudCustomData);const D=[];if(u&&fR(u)){const{excludedFromUnreadCount:M,excludedFromLastMessage:T,excludedFromContentModeration:P}=u;M===!0&&D.push("NoUnread"),T===!0&&D.push("NoLastMsg"),P===!0&&D.push("NoMsgCheck")}return{onlineUserOnly:g,cloudCustomData:m,messageControlInfo:D,offlinePushInfo:E}}function xD(s){const{webhookInfo:{disableCloudMessagePreHook:n=!1,disableCloudMessagePostHook:g=!1}={}}=s||{};if(!n&&!g)return;const u=[];return n&&u.push("ForbidBeforeSendMsgCallback"),g&&u.push("ForbidAfterSendMsgCallback"),u}function Rh(s,n){return pA(this,void 0,void 0,function*(){const g=s.conversationType===Kr.CONV_GROUP?function(E,m){var D;const M=sp(E,m),{onlineUserOnly:T,cloudCustomData:P,messageControlInfo:W,offlinePushInfo:iA}=M,EA=JSON.parse(JSON.stringify(E.transformElementsToServerFormat()));let RA;return h(E._receiverList)&&E._receiverList.length>0&&(RA=E._receiverList,E._receiverList.length>50&&(RA=E._receiverList.slice(0,50),console.warn("ReceiverListLimit"))),{servcmd:"group_open_http_svc.send_group_msg",data:{From_Account:(D=fe.store.get("login"))===null||D===void 0?void 0:D.userId,GroupId:E.to,MsgBody:EA,CloudCustomData:P,Random:E.random,MsgPriority:E.priority,ClientSeq:E.clientSequence,GroupAtInfo:E._groupAtInfoList,OnlineOnlyFlag:T?1:0,MsgClientTime:E.clientTime,OfflinePushInfo:FD(iA),SendMsgControl:T?void 0:W,NeedReadReceipt:E.needReadReceipt===!0?1:0,To_Account:RA,SupportMessageExtension:E.isSupportExtension===!0?1:0,IsRelayMsg:E._relayFlag===!0?1:0,CustomModerationConfigID:E._cmConfigID,ForbidCallbackControl:xD(m),InnerSdkCustomData:wB(E)}}}(s,n):function(E,m){var D;const M=sp(E,m),{onlineUserOnly:T,cloudCustomData:P,messageControlInfo:W,offlinePushInfo:iA}=M,EA=T===!0?0:void 0,RA=JSON.parse(JSON.stringify(E.transformElementsToServerFormat()));return{servcmd:"openim.sendmsg",data:{From_Account:(D=fe.store.get("login"))===null||D===void 0?void 0:D.userId,To_Account:E.to,MsgBody:RA,CloudCustomData:P,MsgSeq:E.sequence,MsgRandom:E.random,MsgLifeTime:EA,From_AccountNick:E.nick,From_AccountHeadurl:E.avatar,SendMsgControl:EA!==0?W:void 0,MsgClientTime:E.clientTime,IsNeedReadReceipt:E.needReadReceipt===!0?1:0,SupportMessageExtension:E.isSupportExtension===!0?1:0,IsRelayMsg:E._relayFlag===!0?1:0,CustomModerationConfigID:E._cmConfigID,OfflinePushInfo:FD(iA),ForbidCallbackControl:xD(m),InnerSdkCustomData:wB(E)}}}(s,n),u=yield gg(g);return u?{time:u.MsgTime,messageDropReason:u.MsgDropReason,sequence:u.MsgSeq}:null})}function wh(s){return pA(this,void 0,void 0,function*(){const{from:n,to:g,version:u=0,sequence:E,random:m,time:D,type:M,cloudCustomData:T}=s,P={From_Account:n,To_Account:g,MsgVersion:u,MsgSeq:E,MsgRandom:m,MsgTime:D,MsgType:M,MsgBody:s.transformElementsToServerFormat(),CloudCustomData:T},W=yield gg({servcmd:"openim.modify_c2c_msg",data:P});if(W){const{MsgBody:iA,MsgVersion:EA,CloudCustomData:RA}=W;return{elements:vC(iA),messageVersion:EA,cloudCustomData:RA}}})}function RB(s){return pA(this,void 0,void 0,function*(){const{to:n,version:g=0,sequence:u,cloudCustomData:E}=s,m={GroupId:n,MsgVersion:g,MsgSeq:u,MsgBody:s.transformElementsToServerFormat(),CloudCustomData:E},D=yield gg({servcmd:"openim.modify_group_msg",data:m});if(D){const{MsgBody:M,MsgVersion:T,CloudCustomData:P}=D;return{elements:vC(M),messageVersion:T,cloudCustomData:P}}})}function _h(s){return pA(this,void 0,void 0,function*(){const{groupID:n,count:g,messageSequence:u,messageSequenceList:E,getType:m}=s,D={GroupId:n,ReqMsgNumber:g,WithRecalledMsg:1,Version:1,GetType:m};return u&&(D.ReqMsgSeq=u),h(E)&&E.length>0&&(D.ReqMsgSeqList=E),yield gg({servcmd:"group_open_http_svc.group_msg_get",data:D})})}function Zm(s){return pA(this,void 0,void 0,function*(){const{peerAccount:n,count:g,lastMessageTime:u,messageKey:E,direction:m}=s;return gg({servcmd:"openim.getroammsg",data:{Peer_Account:n,MaxCnt:g,WithRecalledMsg:1,LastMsgTime:u,MsgKey:E,GetDirection:m}})})}function wB(s){if(fe.utils.isObject(s.quoteInfo)){const{msgID:n,messageSequence:g,messageTime:u}=s.quoteInfo;return JSON.stringify({businessQuote:{messageID:n,messageSequence:g,messageTime:u}})}}var YD=Object.freeze({__proto__:null,createMessagePackOptions:sp,generateForbidCallbackControl:xD,getC2CRoamingMessagesByAnchor:Zm,getGroupRoamingMessagesByAnchor:_h,getRoamingMessages:function(s){return pA(this,void 0,void 0,function*(){const{peerAccount:n,count:g,lastMessageTime:u,messageKey:E}=s;return(yield gg({servcmd:"openim.getroammsg",data:{Peer_Account:n,MaxCnt:g||15,LastMsgTime:u||0,MsgKey:E,GetDirection:0,WithRecalledMsg:1}}))||[]})},modifyC2CMessage:wh,modifyGroupMessage:RB,sendMessage:Rh});const{isPlainObject:JT}=fe.utils,{MSG_AUDIO:VD,MSG_FILE:JD,MSG_IMAGE:yR,MSG_VIDEO:DR,MSG_MERGER:SR}=Lo;class Xm{constructor(){this._sendProtocolMap=new Map}init(){Cr.getInstance().registerApi({apiName:"sendMessage",context:this,matcher:n=>![VD,JD,yR,DR,SR].includes(n[0].type)})}registerSendProtocol(n,g,u){this._sendProtocolMap.set(n,g.bind(u))}sendMessage(n,g){return pA(this,void 0,void 0,function*(){const{TOTAL_COUNT:u,SEND_COST:E,SUCCESS_COUNT:m,FAILED_COUNT:D}=rr;if(!(n instanceof JE))throw new gs({code:Ea.MSG_INSTANCE_REQUIRED});const M=n.validateBeforeSend();if(!M.isValid){const{code:W,message:iA=""}=M.error||{};throw new gs({code:W,message:iA})}this._reportMessageSendQuality({name:u,message:n});let T=!1;const{messageDataHandler:P}=fe.message||{};try{const{messageControlInfo:W}=g||{};let iA=null;P.addRandomOfSentMessage(n.random);const EA=Date.now(),RA=this._getSendProtocol(n);if(n.conversationType===Kr.CONV_C2C?(T=g?.onlineUserOnly===!0,iA=yield RA(n,g)):n.conversationType===Kr.CONV_GROUP&&(yield this._validateBeforeSendGroupMessage(n),iA=yield RA(n,g)),iA){const{messageDropReason:kA,sequence:xA,time:LA}=iA;if(this._updateNickAndAvatarOfSentMessageByMe(n),kA&&this._logRateLimitInfo(n,xA,kA),this._reportMessageSendQuality({name:m,message:n}),this._reportMessageSendQuality({name:E,message:n,startTs:EA}),n.isResend===!0){const SA=P.findMessage(n.ID);SA&&(fe.ssoLog.debug("sendMessage",`sendMessage resend ok. ID:${SA.ID}`),P.deleteConversationMessage(SA))}return n.status=Yr.SUCCESS,n.time=LA,n.conversationType===Kr.CONV_GROUP&&(n.sequence=xA),T?n._onlineOnlyFlag=!0:(P.storeConversationMessage(n),this._applySentMessageControlInfo(n,W),this._emitOnlineMessageSent(n)),n.type===wg.MSG_STREAM?{code:0,data:{message:n,streamMessageID:iA.streamMessageID}}:{code:0,data:{message:n}}}}catch(W){n.status=Yr.FAIL,P.removeRandomOfSentMessage(n.random);let{errorCode:iA}=W||{},EA=W?.errorInfo||W?.message||"";throw this._hasRiskContent(iA)&&(n.hasRiskContent=!0),T||this._isRejectedByRestApi(iA)||P.storeConversationMessage(n),this._reportMessageSendQuality({name:D,message:n,error:W}),new gs({code:iA,message:EA,data:{message:n},moreMessage:`type:${n.type} from:${n.from} to:${n.to}`})}})}_hasRiskContent(n){return n===80001||n===80004}_isRejectedByRestApi(n){return n>=10100&&n<=10200||n>=120001&&n<=13e4}_emitOnlineMessageSent(n){const g=n._isExcludedFromLastMessage?"":n,{conversationID:u,conversationType:E}=n,m=Wc(u)?so.TOPIC_NEW_MESSAGE:so.NEW_MESSAGE;fe.notificationCenter.emitInnerEvent(m,{result:{conversationUpdateFieldList:[{conversationID:u,type:E,message:n,lastMessage:g,unreadCount:0}]}})}_applySentMessageControlInfo(n,g){g&&JT(g)&&(g.excludedFromLastMessage===!0&&(n._isExcludedFromLastMessage=!0),g.excludedFromUnreadCount===!0&&(n._isExcludedFromUnreadCount=!0))}_logRateLimitInfo(n,g,u){const E=`from:${n.from} to:${n.to} sequence:${g} messageDropReason:${u}`;fe.ssoLog.warn("messageDropReason",E)}_updateNickAndAvatarOfSentMessageByMe(n){const{messageDataHandler:g}=fe.message||{};let u=!1;const{conversationID:E}=n,m=g.getLatestMsgSentByMe(E);if(m){const{nick:D,avatar:M}=m;D===n.nick&&M===n.avatar||(u=!0),u&&g.updateNickAndAvatarOfSentMessage({conversationID:E,latestNick:n.nick,latestAvatar:n.avatar,isSentByMe:!0})}}_validateBeforeSendGroupMessage(n){return pA(this,void 0,void 0,function*(){var g,u,E;const{to:m,from:D}=n;let M=m,T=$Q.getGroup(M);if(Xr({groupID:M})&&T?.isSupportTopic)throw new gs({code:Ea.MSG_SEND_GRP_WITH_TOPIC_FAIL});if(Wc(m)&&([M]=m.split(sa.TOPIC),T=$Q.getGroup(M)),!T&&typeof((g=Cr.getInstance().getApiMap())===null||g===void 0?void 0:g.getGroupProfile)=="function"){const P=yield Cr.getInstance().getApiMap().getGroupProfile({groupID:M});if(((E=(u=P?.data)===null||u===void 0?void 0:u.group)===null||E===void 0?void 0:E.type)===Lo.GRP_AVCHATROOM){const W=rs({code:Ea.MSG_SEND_FAIL_NOT_IN_AV,replacement1:D,replacement2:M});throw new gs({code:Ea.MSG_SEND_FAIL_NOT_IN_AV,message:W})}}return!0})}_reportMessageSendQuality(n){fe.notificationCenter.emitInnerEvent(so.QUALITY_STAT,{label:gI.MESSAGE_SEND_SUCCESS_RATE,data:n})}_getSendProtocol(n){return this._sendProtocolMap.get(n.type)||Rh}}var HT=new class{constructor(){this._sparseMessagesByConversation=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new Set}init(){fe.notificationCenter.subscribeInnerEvent(so.LOGOUT,this._reset,this),fe.notificationCenter.subscribeInnerEvent(so.DESTROY,this._dispose,this)}get _messagesByConversation(){return Ap.getMessages()}storeConversationMessage(s,n=!1){if(an)return!0;const{conversationID:g}=s;if(!g||(this._messagesByConversation.has(g)||this._messagesByConversation.set(g,new Map),this._shouldSkipStoreMessage(s,n)))return!1;const u=this._getUniqueIdOfMessage(s);return this._messagesByConversation.get(g).set(u,s),this._updateLatestMessageMap(s),!0}_updateLatestMessageMap(s){const{conversationID:n}=s;s.flow==="out"?this._setLatestMsgSentByMe(n,s):n.startsWith("C2C")&&this._setLatestMsgSentByPeer(n,s)}_shouldSkipStoreMessage(s,n){const g=this._getUniqueIdOfMessage(s),u=this._messagesByConversation.get(s.conversationID);if(u?.has(g)){const E=u?.get(g);if(!n||E?.isModified===!0)return!0}return!1}deleteConversationMessage(s){var n;const{conversationID:g=""}=s,u=this._getUniqueIdOfMessage(s);this._messagesByConversation.has(g)&&((n=this._messagesByConversation.get(g))===null||n===void 0||n.delete(u))}modifyConversationMessage(s,n){var g;if(!this._messagesByConversation.has(s)&&!this._sparseMessagesByConversation.has(s))return{isUpdated:!1,message:null};const u=this._getUniqueIdOfMessage(n),E=this._getMessageFromLocalMessage(s,u);if(E){const{messageVersion:m,elements:D,cloudCustomData:M,checkResult:T=0}=n,P=T>1;if(fe.ssoLog.debug("modifyConversationMessage",`conversationToMessageMap modifyConversationMessage localVersion:${E.version} remoteVersion:${m}`),E.versionE.ID===s)||null,n)break;if(!n){const u=Array.from(this._sparseMessagesByConversation.values());for(const E of u)if(n=E.get(s)||null,n)break}return n}deleteConversationMessageList(s){this._messagesByConversation.has(s)&&(this._messagesByConversation.delete(s),this._latestMessageSentByMeMap.delete(s),this._latestMessageSentByPeerMap.delete(s)),this._sparseMessagesByConversation.has(s)&&this._sparseMessagesByConversation.delete(s)}revokeMessage({conversationID:s,sequence:n,random:g,revoker:u}){const E=this._messagesByConversation.get(s);let m=null;if(E){const D=Array.from(E.values());if(m=this._findMessageBySequenceAndRandom({messageList:D,random:g,sequence:n}),m){const M=this._getUniqueIdOfMessage(m);return Ap.updateMessage(s,[M],{isRevoked:!0,revoker:u,operation:yc.revoke}),m}}if(this._sparseMessagesByConversation.has(s)){const D=Array.from(this._sparseMessagesByConversation.get(s).values());if(m=this._findMessageBySequenceAndRandom({messageList:D,random:g,sequence:n}),m)return m.isRevoked=!0,m.revoker=u,m}}_findMessageBySequenceAndRandom({messageList:s,sequence:n,random:g}){for(let u=0;u0){const D=new Map([...E,...m.entries()]);this._messagesByConversation.set(g,D),this._updateLatestMessageSentByMe(g),this._updateLatestMessageSentByPeer(g)}return u}storeSparseMessageList(s){if(s.length===0)return;const{conversationID:n}=s[0],g=s.length;this._sparseMessagesByConversation.has(n)||this._sparseMessagesByConversation.set(n,new Map);const u=this._sparseMessagesByConversation.get(n);for(let E=0;E=0;u--)if(g[u].flow==="out"){this._setLatestMsgSentByMe(s,g[u]);break}}}_updateLatestMessageSentByPeer(s){var n;const g=Array.from(((n=this._messagesByConversation.get(s))===null||n===void 0?void 0:n.values())||[]);if(g.length!==0&&s.startsWith("C2C")){for(let u=g.length-1;u>=0;u--)if(g[u].flow==="in"){this._setLatestMsgSentByPeer(s,g[u]);break}}}_getUniqueIdOfMessage(s){const{from:n,to:g,random:u,sequence:E,time:m}=s;return`${n}-${g}-${u}-${E}-${m}`}_setLatestMsgSentByPeer(s,n){this._latestMessageSentByPeerMap.set(s,n)}_setLatestMsgSentByMe(s,n){this._latestMessageSentByMeMap.set(s,n)}getLatestMsgSentByPeer(s){return this._latestMessageSentByPeerMap.get(s)}getLatestMsgSentByMe(s){return this._latestMessageSentByMeMap.get(s)}addRandomOfSentMessage(s){this._randomOfSentMessageList.add(s)}removeRandomOfSentMessage(s){this._randomOfSentMessageList.delete(s)}updateNickAndAvatarOfSentMessage(s){const{conversationID:n="",latestAvatar:g,latestNick:u,isSentByMe:E=!0}=s,m=this._messagesByConversation.get(n);if(!m)return;const D=Array.from(m.values()),M=E?"out":"in";D.forEach(T=>{const{nick:P,avatar:W,flow:iA}=T;iA===M&&(P!==u&&(T.nick=u),W!==g&&(T.avatar=g))})}isInMessageList(s){var n;const{conversationID:g}=s;if(!g||!this._messagesByConversation.has(g))return!1;const u=this._getUniqueIdOfMessage(s);return(n=this._messagesByConversation.get(g))===null||n===void 0?void 0:n.has(u)}isMessageSentByCurrentInstance(s){const{random:n}=s;return this._randomOfSentMessageList.has(n)}getContinuousMessagesByConversation(){return this._messagesByConversation}getLocalMessageList(s){const n=this._messagesByConversation.get(s);return n?[...n.values()]:[]}getSparseMessageList(s){const n=this._sparseMessagesByConversation.get(s);return n?[...n.values()]:[]}_reset(){this._messagesByConversation.clear(),this._latestMessageSentByPeerMap.clear(),this._latestMessageSentByMeMap.clear(),this._randomOfSentMessageList.clear()}_dispose(){this._reset(),fe.notificationCenter.unSubscribeInnerEvent(so.LOGOUT,this._reset,this),fe.notificationCenter.unSubscribeInnerEvent(so.DESTROY,this._dispose,this)}};function $m(s,n){const g=SB.getConversation(s);if(g?.lastMessage){const{lastMessage:u}=g,{lastTime:E,lastSequence:m,version:D}=u,{time:M,sequence:T,messageVersion:P,elements:W,cloudCustomData:iA}=n;E===M&&m===T&&D!==P&&(u.type=W[0].type,u.payload=W[0].content,u.messageForShow=zc(u.type,u.payload),u.cloudCustomData=iA,u.version=P,SB.updateConversation(s,{lastMessage:u}))}}class MR{init(){Cr.getInstance().registerApi({apiName:"modifyMessage",context:this})}modifyMessage(n){return pA(this,void 0,void 0,function*(){const{to:g,payload:u,sequence:E,conversationType:m,random:D,time:M,from:T,type:P}=n;if(this._canModifyMessageElement(P)){const W=n?._elements||[];W.length>=1&&(W[0].type=P,W[0].content=u)}try{let W=null,iA=null;if(m===Kr.CONV_C2C?W=yield wh(n):m===Kr.CONV_GROUP&&(W=yield RB(n)),W){let EA=`${m}${g}`;return g===Ar()&&m===Kr.CONV_C2C&&(EA=`${m}${T}`),iA={conversationType:m,from:T,to:g,time:M,random:D,sequence:E,elements:W?.elements,cloudCustomData:W?.cloudCustomData,messageVersion:W?.messageVersion,conversationID:EA},this._handleModifyMessageSuccess(iA),{code:0,data:{message:n},successLog:{message:`to:${g}`}}}}catch(W){const{errorCode:iA}=W||{};throw new gs({functionName:"modifyMessage",code:iA,moreMessage:`to:${g}`})}})}_handleModifyMessageSuccess(n){const{conversationID:g}=n,{isUpdated:u,message:E}=fe.message.messageDataHandler.modifyConversationMessage(g,n);u===!0&&fe.notificationCenter.emitOuterEvent(Dr.MESSAGE_MODIFIED,{name:Dr.MESSAGE_MODIFIED,data:[E]}),fe.notificationCenter.emitInnerEvent(so.MESSAGE_MODIFIED,{conversationID:g,message:E}),$m(g,n)}_canModifyMessageElement(n){return[VE.MSG_TEXT,VE.MSG_CUSTOM,VE.MSG_LOCATION,VE.MSG_FACE].includes(n)}}class Th{init(){const{notificationCenter:n}=fe,{InnerEventSubType:g}=n;ws.getInstance().registerWorkflowStep(xt.RECEIVE_C2C_NEW_MESSAGE,qt.HANDLE_C2C_NEW_MESSAGE,this._handleC2CMessagePush,this),ws.getInstance().registerWorkflowStep(xt.RECEIVE_C2C_NEW_MESSAGE,qt.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterReceiveNewMessage,this),ws.getInstance().registerWorkflowStep(xt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,qt.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterSyncUnreadMessage,this),n.subscribeInnerEvent(so.MESSAGE_PUSH,g.C2C_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),n.subscribeInnerEvent(so.MESSAGE_PUSH,g.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),n.subscribeInnerEvent(so.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(n){ws.getInstance().executeWorkflow(xt.RECEIVE_C2C_NEW_MESSAGE,n)}_handleC2CMessagePush(n){const g=n.data||{},{messageDataHandler:u}=fe.message||{},E=[],m=new Map;return g.C2cMsgArray.forEach(D=>{const M=this._generateC2CMessage(D);this._updateMessageProfile(M);let T=M.isModified===1;u.isMessageSentByCurrentInstance(M)?M.isModified=T:T=!1,M._onlineOnlyFlag?u.isMessageSentByCurrentInstance(M)||E.push(M):vB(M)&&(u.storeConversationMessage(M)&&op({conversationUpdateFields:m,message:M}),u.isMessageSentByCurrentInstance(M)&&!T||E.push(M))}),{conversationUpdateFieldList:[...m.values()],messages:E}}_emitMessageEventsAfterReceiveNewMessage(n){var g;const{messages:u=[]}=((g=n.result)===null||g===void 0?void 0:g[qt.HANDLE_C2C_NEW_MESSAGE])||{};this._emitMessageEvents(u)}_emitMessageEventsAfterSyncUnreadMessage(n){var g;const{messages:u=[]}=((g=n.result)===null||g===void 0?void 0:g[qt.UNREAD_MESSAGE_SYNC])||{};this._emitMessageEvents(u)}_emitMessageEvents(n){const g=n?.filter(E=>E?.isModified===!0)||[];g.length>0&&fe.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:g});const u=n?.filter(E=>!E?.isModified);u.length>0&&fe.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:u})}_generateC2CMessage(n){const g=Kr.CONV_C2C,u=Wm(n),E=fe.message.messageFactory.createMessage(Object.assign(Object.assign({},u),{conversationType:g,flow:Zu.IN})),{elements:m}=u;return E.setElement(m),E}_updateMessageProfile(n){var g;const{messageDataHandler:u}=fe.message||{},E=(g=fe.store.get("login"))===null||g===void 0?void 0:g.userId,{from:m,nick:D,avatar:M,conversationID:T=""}=n;if(m!==E){const P=u.getLatestMsgSentByPeer(T);if(P){const{nick:W,avatar:iA}=P;r(D)||r(M)?(n.nick=l(W)?W:n.nick,n.avatar=l(iA)?iA:n.avatar):D===W&&M===iA||(u.updateNickAndAvatarOfSentMessage({conversationID:T,latestNick:D,latestAvatar:M,isSentByMe:!1}),this._updateConversationUserProfile({conversationID:T,nick:D,avatar:M}))}}else{const P=u.getLatestMsgSentByMe(T);!P||D===P.nick&&M===P.avatar||u.updateNickAndAvatarOfSentMessage({conversationID:T,latestNick:D,latestAvatar:M,isSentByMe:!0})}}_updateConversationUserProfile(n){const{conversationID:g,nick:u,avatar:E}=n,m=SB.getConversation(g),{userProfile:D={}}=m||{};D.avatar===E&&D.nick===u||SB.updateConversation(g,{userProfile:Object.assign(Object.assign({},D),{nick:u,avatar:E})})}_updateMessageListDueToModify(n){const{conversationID:g}=n,{isUpdated:u,message:E}=fe.message.messageDataHandler.modifyConversationMessage(g,n);u===!0&&fe.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[E]}),fe.notificationCenter.emitInnerEvent("ModifyMessageSuccess",n),$m(g,n)}_handleC2CMessageModify(n){n.C2cMsgModNotifys.forEach(g=>{var u;const E=Kr.CONV_C2C;let m=zm(g);const{to:D,from:M}=m;let T=`${E}${D}`;D===((u=fe.store.get("login"))===null||u===void 0?void 0:u.userId)&&(T=`${E}${M}`),m=Object.assign({conversationType:E,conversationID:T},m),this._updateMessageListDueToModify(m)})}_dispose(){const{notificationCenter:n}=fe,{InnerEventSubType:g}=n;fe.notificationCenter.unSubscribeInnerEvent(so.MESSAGE_PUSH,g.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),fe.notificationCenter.unSubscribeInnerEvent(so.MESSAGE_PUSH,g.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),fe.notificationCenter.unSubscribeInnerEvent(so.DESTROY,this._dispose,this)}}class Nh{init(){const{notificationCenter:n}=fe,{InnerEventSubType:g}=n;ws.getInstance().registerWorkflowStep(xt.RECEIVE_GROUP_NEW_MESSAGE,qt.HANDLE_GROUP_NEW_MESSAGE,this._handleGroupMessagePush,this),ws.getInstance().registerWorkflowStep(xt.RECEIVE_GROUP_NEW_MESSAGE,qt.EMIT_GROUP_MESSAGE_EVENT,this._emitMessageEvents,this),n.subscribeInnerEvent(so.MESSAGE_PUSH,g.GROUP_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),n.subscribeInnerEvent(so.MESSAGE_PUSH,g.GROUP_MESSAGE_MODIFIED,this._handleGroupMessageModify,this),n.subscribeInnerEvent(so.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(n){this._canExecuteReceiverNewMessageWorkFlow(n)&&ws.getInstance().executeWorkflow(xt.RECEIVE_GROUP_NEW_MESSAGE,n)}_handleGroupMessagePush(n){const g=n.data||{},{messageDataHandler:u}=fe.message,E=[],m=new Map,D=g?.GroupMsgArray;return D?.forEach(M=>{if(M.GroupInfo.NotVisible===1)return;const T=this._generateGroupMessage(M);this.updateMessageProfile(T);let P=T.isModified===1;u.isMessageSentByCurrentInstance(T)?T.isModified=P:P=!1,T._onlineOnlyFlag?u.isMessageSentByCurrentInstance(T)||E.push(T):vB(T)&&u.storeConversationMessage(T)&&(E.push(T),op({conversationUpdateFields:m,message:T}))}),{conversationUpdateFieldList:[...m.values()],messages:E}}_emitMessageEvents(n){var g;const{messages:u}=((g=n.result)===null||g===void 0?void 0:g[qt.HANDLE_GROUP_NEW_MESSAGE])||{},E=u?.filter(D=>D?.isModified===!0)||[];E.length>0&&fe.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:E});const m=u?.filter(D=>!D?.isModified)||[];m.length>0&&fe.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:m})}_generateGroupMessage(n){const g=Kr.CONV_GROUP,u=OD(n),E=fe.message.messageFactory.createMessage(Object.assign(Object.assign({},u),{conversationType:g,flow:Zu.IN})),{elements:m}=u;return E.setElement(m),E}updateMessageProfile(n){var g;const{messageDataHandler:u}=fe.message||{},E=(g=fe.store.get("login"))===null||g===void 0?void 0:g.userId,{from:m,nick:D,avatar:M,conversationID:T="",_elements:P}=n;if(m===E){const W=u.getLatestMsgSentByMe(T);!W||D===W.nick&&M===W.avatar||u.updateNickAndAvatarOfSentMessage({conversationID:T,latestNick:D,latestAvatar:M,isSentByMe:!0})}else if(m===Lo.CONV_SYSTEM){const{operationType:W,memberInfoList:iA,operatorInfo:EA}=P;let RA={};if(Rs(iA)?Rs(EA)||(RA=EA):[Tg.JOINED,Tg.KICKED,Tg.ADMIN_SET,Tg.ADMIN_CANCELED].includes(W)&&(RA=Object.assign({},iA[0])),!Rs(RA)){const{nick:kA="",avatar:xA=""}=RA;n.nick=kA,n.avatar=xA}}}_updateMessageListDueToModify(n){const{conversationID:g}=n,{isUpdated:u,message:E}=fe.message.messageDataHandler.modifyConversationMessage(g,n);u===!0&&fe.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[E]}),$m(g,n)}_handleGroupMessageModify(n){n.GroupMsgModNotifys.forEach(g=>{const u=Kr.CONV_GROUP;let E=PD(g);const{topicID:m,groupID:D}=E,M=m||D,T=`${u}${M}`;E=Object.assign({conversationType:u,conversationID:T,to:M},E),this._updateMessageListDueToModify(E)})}_dispose(){const{notificationCenter:n}=fe,{InnerEventSubType:{GROUP_REALTIME_MESSAGE:g,GROUP_MESSAGE_MODIFIED:u}}=n;n.unSubscribeInnerEvent(so.MESSAGE_PUSH,g,this._handleGroupMessagePush,this),n.unSubscribeInnerEvent(so.MESSAGE_PUSH,u,this._handleGroupMessageModify,this),n.unSubscribeInnerEvent(so.DESTROY,this._dispose,this)}_canExecuteReceiverNewMessageWorkFlow(n){var g,u;const{GroupId:E,GroupType:m}=((u=(g=n?.GroupMsgArray)===null||g===void 0?void 0:g[0])===null||u===void 0?void 0:u.GroupInfo)||{},D=m===La.GRP_AVCHATROOM;return!(!$Q.getGroup(E)&&D)}}var HD=new class{constructor(){this.c2cMessageReceiver=new Th,this.groupMessageReceiver=new Nh}init(){this.c2cMessageReceiver.init(),this.groupMessageReceiver.init()}};const vR={createCustomMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1},cloudCustomData:{required:!1,rules:["string"],allowEmpty:!1},priority:{required:!1,rules:["string"],allowEmpty:!1},customModerationConfigurationID:{required:!1,rules:["string"],allowEmpty:!1}},sendMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"options",required:!1,rules:["object"],allowEmpty:!1}],createTextMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!(!s.startsWith("C2C")&&!s.startsWith("GROUP"))||"conversationType is invalid."},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>function(n){var g;return typeof n?.text!="string"||typeof n.text=="string"&&((g=n?.text)===null||g===void 0?void 0:g.length)===0?"payload.text must be a string":!0}(s)}}},qT={createCustomMessage:!0,sendMessage:!0,modifyMessage:!0};var KT=new class{constructor(){this._historyMessageListFetchAnchors=new Map,this.completedHistoryConversations=new Set}getGroupRoamingMessagesByAnchor(s){return pA(this,void 0,void 0,function*(){try{const{conversationID:n,count:g,direction:u,sequence:E,messageSequenceList:m,shouldMarkCompleted:D=!1,getType:M}=s,T=n.replace(ka.CONV_GROUP,""),P=[];let W=E;if(u===qc.BACKWARD){if(typeof E!="number")return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};W=E+g-1}const iA=yield _h({groupID:T,count:g,messageSequence:W,messageSequenceList:m,getType:M});if(iA){const{RspMsgList:EA=[],NextReqMsgSeq:RA=0,IsFinished:kA,InvisibleMsgSeq:xA}=iA,LA=`groupID:${T} sequence:${E} reqSeq:${W} direction:${u} complete:${kA} nextSequence:${RA} remoteMsgCount:${EA.length} invisibleSequenceList:${xA}`,SA=[];for(let ne=0;ne=E),OA&&D&&this.completedHistoryConversations.add(n);const JA=MB(SA);return fe.ssoLog.info("getGroupRoamingMessagesByAnchor",LA),{messageList:JA,invisibleSequenceList:xA,nextReqMessageIDFromServer:RA,hasNoMoreHistoryMessage:OA,serverGroupTipList:P}}}catch(n){const{errorCode:g,errorInfo:u}=n||{};throw new gs({code:g,message:u})}})}clearHistoryMessageListFetchAnchors(s){this._historyMessageListFetchAnchors.delete(s)}isHistoryMessageFetchCompleted(s){return this.completedHistoryConversations.has(s)}_parseMessage(s){var n;const g=ka.CONV_GROUP;s.Event===4&&(s.MsgBody.MsgType=Lo.MSG_GRP_TIP);const u=OD(s),E=jm.createMessage(Object.assign(Object.assign({},u),{conversationType:g,flow:"in"}));return DB(((n=u.elements)===null||n===void 0?void 0:n.content)||{},E),E.setElement(u.elements),E}getC2CRoamingMessagesByAnchor(s){return pA(this,void 0,void 0,function*(){var n;try{const{conversationID:g,count:u,messageID:E,time:m,direction:D,shouldMarkCompleted:M=!1}=s;let T=m,P="";if(!m){const EA=E?fe.message.messageDataHandler.findMessage(E):null;if(T=EA?.time||0,E&&this._historyMessageListFetchAnchors.has(g)){const RA=this._historyMessageListFetchAnchors.get(g);T=RA.lastMessageTime,P=RA.messageKey}}const W=g.replace(ka.CONV_C2C,""),iA=yield Zm({count:u,lastMessageTime:T,messageKey:P,peerAccount:W,direction:D});if(iA){const{MsgList:EA=[],Complete:RA,MsgKey:kA,LastMsgTime:xA}=iA;this._historyMessageListFetchAnchors.set(g,{messageKey:kA,lastMessageTime:xA});const LA=[];for(let ne=0;ne{const{tag:E,value:m}=u;E&&E.indexOf(KD)>-1?g.profileCustomField.push({key:E,value:m}):Gd.has(E)&&(g[Gd.get(E)]=m)}),Object.assign(Object.assign({},Af),g)}parseProfileItem(s=[]){const n=[];return s.forEach(g=>{n.push({tag:g.Tag,value:g.Value})}),n}parseProfileList(s=[]){const n=[];return s.forEach(g=>{n.push({tag:g.Tag,value:g.ValueBytes})}),n}convertParamsToProfile(s){const n=[];return Object.keys(s).forEach(g=>{g!==jD&&n.push({tag:Pl[g.toUpperCase()],value:s[g]})}),s.profileCustomField&&h(s.profileCustomField)&&s.profileCustomField.forEach(g=>{n.push({tag:g.key,value:g.value})}),n}normalizeProfileFields(s){const n={},g=[];return s.forEach(u=>{const{tag:E,value:m}=u;if(E&&E.indexOf(KD)>-1&&g.push({key:E,value:m}),Gd.has(E)&&m!==void 0){const D=Gd.get(E);n[D]=m}}),g.length>0&&(n.profileCustomField=g),n}};const{generateProtocolData:wR}=fe.common;function _R(s){return pA(this,void 0,void 0,function*(){const n="profile.portrait_get_all",g={From_Account:Ar(),UserItem:[]};s.forEach(D=>{g.UserItem.push({CustomSequence:0,StandardSequence:0,To_Account:D})});const u=wR({servcmd:n,data:g}),E=`${u.head.seq}${n}`,m=yield fe.channel.sendPacket(u,{requestId:E});if(m)return function(D){const{ActionStatus:M,ErrorCode:T,ErrorDisplay:P,ErrorInfo:W,UserProfileItem:iA}=D,EA=[];return iA.map(RA=>{const{To_Account:kA,CustomSequence:xA,ResultCode:LA,ResultInfo:SA,StandardSequence:OA,ProfileItem:JA}=RA,ne=Xu.parseProfileItem(JA);EA.push({userId:kA,customSequence:xA,resultCode:LA,resultInfo:SA,standardSequence:OA,profileItem:ne})}),{actionStatus:M,errorCode:T,errorDisplay:P,errorInfo:W,userProfile:EA}}(m)})}function HE(s){return rc.getFriendMap().has(s)}const{isEmpty:WD}=fe.utils;class ef{constructor(){this._strangerProfileMap=new Map}init(){Cr.getInstance().registerApi({apiName:"getMyProfile",context:this}),Cr.getInstance().registerApi({apiName:"getUserProfile",context:this}),Cr.getInstance().registerApi({apiName:"updateMyProfile",context:this}),this.createProfile=Xu.createProfile.bind(Xu);const{notificationCenter:n}=fe;ws.getInstance().registerWorkflowStep(xt.SYNC_SERVER_INFO_AFTER_LOGIN,qt.USER_PROFILE_SYNC,this.getMyProfileCacheThenServer,this),n.subscribeInnerEvent(so.MESSAGE_PUSH,n.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),n.subscribeInnerEvent(so.LOGOUT,this._reset,this),n.subscribeInnerEvent(so.DESTROY,this._dispose,this)}getMyProfile(){return pA(this,void 0,void 0,function*(){try{const n=Ar(),g=yield _R([n]);if(g){const u=this._handleProfileFormResponse(g)[0];return rc.getUserProfileMap().set(n,u),{code:0,data:u}}}catch(n){const{errorCode:g,errorInfo:u}=n;throw new gs({functionName:"getMyProfile",code:g,message:u})}})}getUserProfile(n){return pA(this,void 0,void 0,function*(){try{let{userIDList:g}=n;const{userIdListToRequest:u,profileFromCache:E}=this._filterRequestAndCacheUsers(g);if(u.length===0)return{code:0,data:E,successLog:{message:`userIDList.length:${g.length}`}};u.length>RR&&(fe.ssoLog.warn("getUserProfile","userIdListToRequest.length > 1000"),u.length=RR);const{data:m,error:D}=yield this._batchFetchUserProfiles(u),M=u.length,T=m.length,P=M-T;if(E.length===0&&M===P&&!WD(D))throw D;if(h(m))return m.forEach(iA=>{HE(iA.userID)?rc.getUserProfileMap().set(iA.userID,iA):this._strangerProfileMap.set(iA.userID,iA)}),{code:0,data:m.concat(E),successLog:{message:`getUserProfile query:${M} success:${T} fail:${P} from cache:${E.length}`}}}catch(g){throw new gs(g)}})}getMyProfileCacheThenServer(){return pA(this,void 0,void 0,function*(){const n=Ar(),g=rc.getUserProfileMap().has(n);return g?{code:0,data:g}:this.getMyProfile()})}updateMyProfile(n){return pA(this,void 0,void 0,function*(){const g=Ar(),u={};for(const m in n)n[m]!==void 0&&(u[m]=n[m]);const E=Xu.convertParamsToProfile(u);try{yield function(P){return pA(this,void 0,void 0,function*(){const W="profile.portrait_set",iA=wR({servcmd:W,data:P}),EA=`${iA.head.seq}${W}`,RA=yield fe.channel.sendPacket(iA,{requestId:EA});if(RA){const{ActionStatus:kA,ErrorCode:xA,ErrorDisplay:LA,ErrorInfo:SA}=RA;return{actionStatus:kA,errorCode:xA,errorDisplay:LA,errorInfo:SA}}})}({From_Account:g,ProfileItem:E});const D=rc.getUserProfile(g);let M;M=D?Object.assign(Object.assign({},D),u):Xu.createProfile(g,E);const T=!rg(D,M,["lastUpdatedTime"]);return M.lastUpdatedTime=Date.now(),rc.getUserProfileMap().set(g,M),T&&this._emitProfileUpdated(M),{code:0,data:M,successLog:{message:`profileArray: ${fe.utils.safeStringify(E)}`}}}catch(m){const{errorCode:D,errorInfo:M}=m;throw new gs({functionName:"updateMyProfile",code:D,message:M,moreMessage:`params: ${fe.utils.safeStringify(n)}`})}})}updateMyNickAndAvatar(n){return pA(this,void 0,void 0,function*(){const g=Ar(),u=Date.now(),E=rc.getUserProfile(g);let m={};m=E?Object.assign(E,n):Xu.createProfile(g,n),m.lastUpdatedTime=u,rc.getUserProfileMap().set(g,m)})}_onProfileDataModify(n){const g=function(m){const{Profile_Account:D,PushType:M,ProfileList:T}=m;return{userId:D,pushType:M,profileList:Xu.parseProfileList(T)}}(n.ProfileDataMod[0]);if(WD(g))return;const{isProfileUpdated:u,profile:E}=this._handleProfileModified(g);u&&this._emitProfileUpdated(E)}_emitProfileUpdated(n){fe.notificationCenter.emitInnerEvent(so.PROFILE_UPDATE,{name:so.PROFILE_UPDATE,data:[n]}),fe.notificationCenter.emitOuterEvent(Dr.PROFILE_UPDATED,{name:Dr.PROFILE_UPDATED,data:[n]}),SB.updateConversation(`C2C${n?.userID}`,{userProfile:n})}_dispose(){const{notificationCenter:n}=fe;n.unSubscribeInnerEvent(so.LOGOUT,this._reset,this),n.unSubscribeInnerEvent(so.MESSAGE_PUSH,n.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),n.unSubscribeInnerEvent(so.DESTROY,this._dispose,this),this._reset()}_handleProfileModified(n){const{userId:g,profileList:u}=n,E=rc.getUserProfile(g);if(!(Ar()===g||HE(g)&&E))return{isProfileUpdated:!1,profile:null};const m=Xu.normalizeProfileFields(u),D=Object.keys(m).some(W=>W===jD?this._isCustomFieldChanged(E.profileCustomField,m.profileCustomField):E[W]!==m[W]);if(!D)return{isProfileUpdated:!1,profile:E};const M=Date.now(),T=Object.prototype.hasOwnProperty.call(m,jD)?this._mergeProfileCustomField(E.profileCustomField,m.profileCustomField):E.profileCustomField,P=Object.assign(Object.assign(Object.assign({},E),m),{profileCustomField:T,lastUpdatedTime:M});return rc.getUserProfileMap().set(g,P),{isProfileUpdated:D,profile:P}}_filterRequestAndCacheUsers(n){const g=[],u=[];return n.forEach(E=>{const m=rc.getUserProfileMap().has(E);HE(E)&&m?u.push(rc.getUserProfile(E)):this._isStrangerAndProfileValid(E)?u.push(this._strangerProfileMap.get(E)):g.push(E)}),{userIdListToRequest:g,profileFromCache:u}}_handleProfileFormResponse(n){const{userProfile:g}=n;if(!Array.isArray(g))return[];const u=g.filter(m=>m.userId!=="@TLS#NOT_FOUND"&&m.userId!==""&&!WD(m.profileItem)),E=Date.now();return u.map(m=>{const D=Xu.createProfile(m.userId,m.profileItem);return D.lastUpdatedTime=E,D})}_isStrangerAndProfileValid(n){var g;if(!HE(n)){const{lastUpdatedTime:u=0}=this._strangerProfileMap.get(n)||{},E=((g=fe.store.get("cloudConfig"))===null||g===void 0?void 0:g.stranger_profile_expiration_time)||6e5;return Date.now()-u<=E}return!1}_chunkUserIDList(n,g){return Array.from({length:Math.ceil(n.length/g)},(u,E)=>n.slice(E*g,(E+1)*g))}_batchFetchUserProfiles(n){return pA(this,void 0,void 0,function*(){const g=[],u=[];let E={};return this._chunkUserIDList(n,100).forEach(m=>{g.push(_R(m))}),(yield Promise.allSettled(g)).forEach(m=>{if(m.status==="fulfilled"){const D=m.value,M=this._handleProfileFormResponse(D);h(M)&&u.push(...M)}else if(m.status==="rejected"){const{code:D,message:M}=m.reason||{};E={errorCode:D,message:M}}}),{data:u,error:E}})}_isCustomFieldChanged(n=[],g=[]){if(!h(g)||g.length===0)return!1;if(!h(n)||n.length===0)return!0;const u=new Map(n.map(E=>[E.key,E.value]));return g.some(E=>u.get(E.key)!==E.value)}_mergeProfileCustomField(n=[],g=[]){const u=h(n)?n.map(E=>Object.assign({},E)):[];return h(g)&&g.length!==0&&g.forEach(({key:E,value:m})=>{const D=u.find(M=>M.key===E);D?D.value=m:u.push({key:E,value:m})}),u}_reset(){rc.getUserProfileMap().clear(),this._strangerProfileMap.clear()}}const tf=new Map,zD=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let s=0,n=zD.length;s>(-2*m&6)):0)E="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(E);try{return decodeURIComponent(escape(g))}catch(u){return console.warn(u),""}}const{isEmpty:WT}=fe.utils,{generateProtocolData:of}=fe.common;function TR(s){return pA(this,void 0,void 0,function*(){const n="im_open_status.ws_get_user_status",g=of({servcmd:n,data:{To_Account:s}}),u=`${g.head.seq}${n}`,E=yield fe.channel.sendPacket(g,{requestId:u});if(E)return function(m){const{ErrorCode:D,ErrorInfo:M,ErrorList:T=[],UserStatusList:P=[]}=m,W=P.map(EA=>{const{To_Account:RA,Status:kA,CustomStatus:xA,Detail:LA=[]}=EA;return{userID:RA,statusType:kA,customStatus:np(xA),onlineDevices:zT(LA)}}),iA=T.map(EA=>{const{To_Account:RA,Invalid_Account:kA,ErrorCode:xA,ErrorInfo:LA}=EA;return{userID:WT(kA)?RA:kA,code:xA,message:LA}});return{errorCode:D,errorInfo:M,successUserList:W,failureUserList:iA}}(E)})}function zT(s){const n=[];return s?.forEach(g=>{const{Platform:u,Status:E}=g;E==="Online"&&n.push(u)}),n}class ZT{constructor(){this._customStatus=""}init(){const{notificationCenter:n}=fe;Cr.getInstance().registerApi({apiName:"getUserStatus",context:this}),Cr.getInstance().registerApi({apiName:"setSelfStatus",context:this}),Cr.getInstance().registerApi({apiName:"subscribeUserStatus",context:this}),Cr.getInstance().registerApi({apiName:"unsubscribeUserStatus",context:this}),ws.getInstance().registerWorkflowStep(xt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,qt.USER_STATUS_UPDATE,this._onReOnline,this),n.subscribeInnerEvent(so.MESSAGE_PUSH,n.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),n.subscribeInnerEvent(so.LOGOUT,this._reset,this),n.subscribeInnerEvent(so.DESTROY,this._dispose,this)}setSelfStatus(n){return pA(this,void 0,void 0,function*(){const g=Ar(),{customStatus:u}=n;try{return yield function(E){return pA(this,void 0,void 0,function*(){const m="im_open_status.ws_set_custom_status",D=of({servcmd:m,data:{CustomStatus:E}}),M=`${D.head.seq}${m}`,T=yield fe.channel.sendPacket(D,{requestId:M});if(T){const{ErrorCode:P,ErrorInfo:W}=T;return{errorCode:P,errorInfo:W}}})}(u),this._customStatus=u,{code:0,data:{userID:g,statusType:Gh,customStatus:u},successLog:{message:`customStatus: ${u}`}}}catch(E){const{errorCode:m,errorInfo:D}=E;throw new gs({functionName:"setSelfStatus",code:m,message:D})}})}getUserStatus(n){return pA(this,void 0,void 0,function*(){const{userIDList:g=[]}=n;if(this._isOnlyMeInArray(g))return this._getMyStatus();const u=yield this._getUserStatus(g);return Object.assign(Object.assign({},u),{successLog:{message:`userIDList length: ${g.length}`}})})}setCustomStatus(n){const g=np(n);this._customStatus=g}subscribeUserStatus(n){return pA(this,void 0,void 0,function*(){try{const{userIDList:g=[]}=n;this._checkBusinessCapabilityBits("subscribeUserStatus");const u=this._getMaxUserCount("subscribe"),E=this._sliceUserIDList(g,u),m=yield function(M){return pA(this,void 0,void 0,function*(){const{channel:T}=fe,P="im_open_status.ws_status_subscribe",W=of({servcmd:P,data:{To_Account:M}}),iA=`${W.head.seq}${P}`;return yield T.sendPacket(W,{requestId:iA})})}(E),D=this._parseResponse(m);return{code:0,data:{failureUserList:D},successLog:{message:`userID length:${g.length} failCount: ${D.length}`}}}catch(g){const{errorCode:u}=g;throw new gs({functionName:"subscribeUserStatus",code:u})}})}unsubscribeUserStatus(n){return pA(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("unsubscribeUserStatus");const{userIDList:g=[]}=n,u=this._getMaxUserCount("unsubscribe"),E=this._sliceUserIDList(g,u),m=yield function(M){return pA(this,void 0,void 0,function*(){const{channel:T}=fe,P="im_open_status.ws_status_unsubscribe";let W={};W=M.length===0?{UnsubscribeAll:1}:{To_Account:M};const iA=of({servcmd:P,data:W}),EA=`${iA.head.seq}${P}`;return yield T.sendPacket(iA,{requestId:EA})})}(E),D=this._parseResponse(m);return{code:0,data:{failureUserList:D},successLog:{message:`userID length:${g.length} failCount: ${D.length}`}}}catch(g){const{errorCode:u}=g;throw new gs({functionName:"unsubscribeUserStatus",code:u})}})}_onUserStatusUpdate(n){const{UserStatusList:g=[]}=n||{},u=g.map(E=>{const{To_Account:m,Status:D,CustomStatus:M,Platform:T}=E,P={userID:m,statusType:D,customStatus:np(M)};return T&&(P.onlineDevices=T),P});this._emitUserStatusUpdatedEvent(u)}_onReOnline(n){const g=np(n.data.customStatus);if(this._customStatus===g)return;this._customStatus=g;const u={userID:Ar(),statusType:Gh,customStatus:g};this._emitUserStatusUpdatedEvent(u)}_emitUserStatusUpdatedEvent(n){fe.notificationCenter.emitOuterEvent(Dr.USER_STATUS_UPDATED,{name:Dr.USER_STATUS_UPDATED,data:n})}_sliceUserIDList(n,g){return n.slice(0,g)}_parseResponse(n){const{ErrorList:g=[]}=n;return g.map(u=>{const{To_Account:E,Invalid_Account:m,ErrorCode:D,ErrorInfo:M}=u;return{userID:fe.utils.isEmpty(m)?E:m,code:D,message:M}})}_checkBusinessCapabilityBits(n){if(!fe.store.get("commercialConfig").get(jT))throw new gs({functionName:n,code:Ea.NO_USE,replacement1:n})}_getMaxUserCount(n){const g=fe.store.get("cloudConfig")||{},u={query:{key:"status_query_count",default:500},subscribe:{key:"status_sub_count",default:100},unsubscribe:{key:"status_unsub_count",default:100}},{key:E,default:m}=u[n],D=g[E]||m;return parseInt(D,10)}_getMyStatus(){return{code:0,data:{successUserList:[{userID:Ar(),statusType:Gh,customStatus:this._customStatus}],failureUserList:[]}}}_getUserStatus(n){return pA(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("getUserStatus");const g=this._getMaxUserCount("query"),u=this._sliceUserIDList(n,g),E=yield TR(u),{successUserList:m,failureUserList:D}=E||{};return{code:0,data:{successUserList:m,failureUserList:D}}}catch(g){const{errorCode:u}=g;throw new gs({functionName:"getUserStatus",code:u})}})}_isOnlyMeInArray(n){const g=Ar();return n.length===1&&n.indexOf(g)>-1}_dispose(){const{notificationCenter:n}=fe;n.unSubscribeInnerEvent(so.MESSAGE_PUSH,n.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),n.unSubscribeInnerEvent(so.DESTROY,this._dispose,this),n.unSubscribeInnerEvent(so.LOGOUT,this._reset,this),this._reset()}_reset(){this._customStatus=""}}const ZD={getUserProfile:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},updateMyProfile:{nick:{required:!1,rules:["string"],allowEmpty:!0},avatar:{required:!1,rules:["string"],allowEmpty:!0},gender:{required:!1,rules:["string"],allowEmpty:!0},selfSignature:{required:!1,rules:["string"],allowEmpty:!0},allowType:{required:!1,rules:["string"],allowEmpty:!0},birthday:{required:!1,rules:["number"],allowEmpty:!1},language:{required:!1,rules:["string"],allowEmpty:!0},messageSettings:{required:!1,rules:["string"],allowEmpty:!0},adminForbidType:{required:!1,rules:["string"],allowEmpty:!0},level:{required:!1,rules:["number"],allowEmpty:!1},role:{required:!1,rules:["number"],allowEmpty:!0},profileCustomField:{required:!1,rules:["array"],allowEmpty:!0,customValidator:function(s){for(const n of s){if(typeof n!="object")return"Each item in profileCustomField must be an object";if(typeof n?.key!="string")return"Each item.key in profileCustomField must be a string";if(!n?.key.startsWith(KD))return'Each item.key in profileCustomField must start with "Tag_Profile_Custom"'}return!0}}},setSelfStatus:{customStatus:{required:!0,rules:["string"],allowEmpty:!0}},getUserStatus:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},subscribeUserStatus:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},unsubscribeUserStatus:{userIDList:{required:!1,rules:["array"],allowEmpty:!0}}},XT={getMyProfile:!0,getUserProfile:!0,updateMyProfile:!0,setSelfStatus:!0,getUserStatus:!0,subscribeUserStatus:!0,unsubscribeUserStatus:!0};class $T{constructor(){this.userProfile=new ef,this.userStatus=new ZT,this.userProfile.init(),this.userStatus.init(),jc({auth:XT,params:ZD})}}function XD(s){const n=[];if(!l(s))return n;const g=s.length;if(g===0)return n;for(let u=g-1;u>=0;u--)s[u]==="1"&&n.push(2**(g-u-1));return n}var bd,RC,kd;(function(s){s.NOT_START="notStart",s.PENDING="pending",s.RESOLVED="resolved",s.REJECTED="rejected"})(bd||(bd={})),function(s){s[s.C2C=1]="C2C",s[s.GROUP=2]="GROUP"}(RC||(RC={})),function(s){s[s.C2C=8]="C2C",s[s.GROUP=2]="GROUP"}(kd||(kd={}));class $D{constructor(){this._name="SyncConversationHandler",this._pagingStatus=bd.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}init(){const{notificationCenter:n}=fe;ws.getInstance().registerWorkflowStep(xt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,qt.CONVERSATION_RECOVER,this._syncConversationList,this),ws.getInstance().registerWorkflowStep(xt.SYNC_SERVER_INFO_AFTER_LOGIN,qt.CONVERSATION_LIST_SYNC,this._syncConversationListAfterLogin,this),n.subscribeInnerEvent(so.LOGOUT,this._reset,this),n.subscribeInnerEvent(so.DESTROY,this._dispose,this),fe.ssoLog.debug(`${this._name}.init`)}isSyncCompleted(){return this._pagingStatus===bd.RESOLVED}_syncConversationListAfterLogin(){return pA(this,void 0,void 0,function*(){return this._pagingStatus=bd.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0,this._syncConversationList()})}_syncConversationList(){return pA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g}}=fe;n.debug("_syncConversationList","start");try{const u=yield this._pagingGetConversationList(!0);this._pagingStatus=bd.RESOLVED;const{conversationList:E=[]}=u||{};return n.info("_syncConversationList",`success count:${E.length}`),u}catch(u){const E=new gs(u);n.error("_syncConversationList",`fail ${g(u)}`,{error:E})}})}_pagingGetConversationList(n){return pA(this,void 0,void 0,function*(){try{const g=[];this._pagingStatus=bd.PENDING;const u=yield function(iA){return pA(this,void 0,void 0,function*(){const{fromAccount:EA,pagingTimeStamp:RA,pagingStartIndex:kA,pagingPinnedTimeStamp:xA,pagingPinnedStartIndex:LA}=iA;return gg({servcmd:"recentcontact.page_get",data:{AssistFlags:31,MsgAssistFlags:15,OrderType:1,From_Account:EA,StartIndex:kA,TimeStamp:RA,TopStartIndex:LA,TopTimeStamp:xA}})})}({fromAccount:Ar(),pagingTimeStamp:n?this._pagingTimeStamp:0,pagingStartIndex:n?this._pagingStartIndex:0,pagingPinnedTimeStamp:n?this._pagingPinnedTimeStamp:0,pagingPinnedStartIndex:n?this._pagingPinnedStartIndex:0}),{CompleteFlag:E,SessionItem:m=[],TimeStamp:D,StartIndex:M,TopTimeStamp:T,TopStartIndex:P}=u||{};let W=[];if(E===1&&(this._pagingStatus=bd.RESOLVED),m.length>0&&(W=this._getConversationOptions(m),g.push(...W)),fe.notificationCenter.emitInnerEvent(so.SYNC_CONVERSATION_LIST,{conversationUpdateFieldList:W}),this._pagingTimeStamp=D,this._pagingStartIndex=M,this._pagingPinnedTimeStamp=T,this._pagingPinnedStartIndex=P,E!==1){const{conversationList:iA}=yield this._pagingGetConversationList(n);g.push(...iA)}return{conversationList:g}}catch(g){throw g}})}_getConversationOptions(n){const{utils:{isUndefined:g}}=fe,u=this._convertConversationKey(n);return this._filterValidConversations(u).map(E=>(g(E.lastMsg)&&(E.lastMsg={elements:[]}),E.type===RC.C2C?this._assembleC2COption(E):this._assembleGroupOption(E)))}_filterValidConversations(n){return n.filter(({type:g,userID:u})=>g===RC.C2C&&!function(E){let m;return E.startsWith(Lo.CONV_C2C)&&(m=E.replace(Lo.CONV_C2C,"")),m==="@TLS#ERROR"||m==="@TLS#NOT_FOUND"}(u)||g===2)}_assembleC2COption(n){var g,u,E,m,D,M,T,P;const W=this._createUserprofile(n);return{conversationID:`${Lo.CONV_C2C}${n.userID}`,type:Lo.CONV_C2C,lastMessage:{lastTime:n.time,lastSequence:n.sequence,fromAccount:n.lastC2CMsgFromAccount,type:!((g=n.lastMsg)===null||g===void 0)&&g.elements[0]?(u=n.lastMsg)===null||u===void 0?void 0:u.elements[0].type:null,payload:!((E=n.lastMsg)===null||E===void 0)&&E.elements[0]?this._amendLayersOverLimitProp(n.lastMsg.elements[0].content):null,cloudCustomData:((M=(D=(m=n.lastMsg)===null||m===void 0?void 0:m.elements)===null||D===void 0?void 0:D[0])===null||M===void 0?void 0:M.cloudCustomData)||"",isRevoked:n.lastMessageFlag===kd.C2C,onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:this._computeIsPeerRead(n),revoker:((P=(T=n.lastMsg)===null||T===void 0?void 0:T.revokerInfo)===null||P===void 0?void 0:P.revoker)||null},unreadCount:0,userProfile:W,peerReadTime:n.peerReadTime,isPinned:n.isPinned===1,customData:n.customMark||"",markList:XD(n.standardMark),conversationGroupList:[],remark:n.friendRemark||"",messageRemindType:this._transMsgRemindType(n.messageRemindType)}}_createUserprofile(n){var g;const{userID:u,nick:E,peerAvatar:m}=n,D=[{tag:"Tag_Profile_IM_Nick",value:E},{tag:"Tag_Profile_IM_Image",value:m}];return(g=fe.user.userProfile)===null||g===void 0?void 0:g.createProfile(u,D)}_computeIsPeerRead(n){const g=Ar(),{lastC2CMsgFromAccount:u,time:E,c2cPeerReadTime:m}=n;return u===g&&E<=m}_assembleGroupOption(n){var g,u,E,m,D;return{conversationID:`${Lo.CONV_GROUP}${n.groupID}`,type:Lo.CONV_GROUP,lastMessage:Object.assign(Object.assign({lastTime:n.time,lastSequence:n.sequence,fromAccount:n.msgGroupFromAccount},this._patchTypeAndPayload(n)),{cloudCustomData:((E=(u=(g=n.lastMsg)===null||g===void 0?void 0:g.elements)===null||u===void 0?void 0:u[0])===null||E===void 0?void 0:E.cloudCustomData)||"",isRevoked:n.lastMessageFlag===kd.GROUP,onlineOnlyFlag:!1,nick:n.msgGroupFromNickName||"",nameCard:n.msgGroupFromCardName||"",revoker:((D=(m=n.lastMsg)===null||m===void 0?void 0:m.revokerInfo)===null||D===void 0?void 0:D.revoker)||null}),groupProfile:{groupID:n.groupID,name:n.groupNick,avatar:n.groupImage,type:n.groupType,nextMessageSeq:n.nextMessageSeq},unreadCount:this._computeGroupUnreadCount(n),peerReadTime:0,isPinned:n.isPinned===1,version:0,customData:n.customMark||"",markList:XD(n.standardMark),conversationGroupList:[],messageRemindType:this._transMsgRemindType(n.messageRemindType),subType:n.groupType}}_convertConversationKey(n){return n.map(g=>({type:g.Type,userID:g.To_Account,nick:g.C2cNick,peerAvatar:g.C2cImage,time:g.MsgTimeStamp,sequence:g.MsgSeq,lastC2CMsgFromAccount:g.LastC2cMsgFrom_Account,lastMsg:this._convertLastMsgKey(g.LastMsg),lastMessageFlag:g.LastMsgFlags,c2cPeerReadTime:g.C2cPeerReadTime,peerReadTime:g.C2cPeerReadTime,friendRemark:g.C2cRemark,isPinned:g.TopFlags,standardMark:g.StandardMark,customMark:g.CustomMark,messageRemindType:g.MsgRecvOption,groupID:g.ToAccount,groupNick:g.GroupNick,groupImage:g.GroupImage,groupType:g.GroupType,nextMessageSeq:g.GroupNextMsgSeq,msgGroupFromAccount:g.MsgGroupFrom_Account,msgGroupFromNickName:g.MsgGroupFromNickName,msgGroupFromCardName:g.MsgGroupFromCardName,unreadCount:g.UnreadMsgCount,noUnreadCount:g.GroupIgnoredUnreadSeqCount}))}_convertLastMsgKey(n){var g,u,E;const{utils:{isEmpty:m}}=fe;if(m(n))return null;let D="",M=null;if(!m(n.GroupTips)){const{From_Account:T,GroupName:P}=((g=n.GroupTips)===null||g===void 0?void 0:g.GroupInfo)||{};D=Lo.MSG_GRP_TIP,M=Object.assign(Object.assign({},this._parseContent(D,n.GroupTips.MsgBody)),{groupProfile:{from:T,groupName:P}})}return n.MsgBody&&(D=(u=n.MsgBody[0])===null||u===void 0?void 0:u.MsgType,M=this._parseContent(D,n.MsgBody[0])),{event:n.Event,elements:[{type:D,content:M,cloudCustomData:n.CloudCustomData}],revokerInfo:{revoker:(E=n.RevokerInfo)===null||E===void 0?void 0:E.Revoker_Account}}}_parseContent(n,g){var u;if(!g)return g;const E=fe.message.messageFactory.getElementClass(n);return E?(u=E.parseServerPushElement(g))===null||u===void 0?void 0:u.content:g}_amendLayersOverLimitProp(n){const{LayersOverLimit:g}=n;return Do(n,["LayersOverLimit"]).layersOverLimit=g===1,n}_transMsgRemindType(n){let g="";return n===0?g=Lo.MSG_REMIND_ACPT_AND_NOTE:n===1?g=Lo.MSG_REMIND_DISCARD:n===2?g=Lo.MSG_REMIND_ACPT_NOT_NOTE:n===3&&(g=Lo.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),g}_patchTypeAndPayload(n){var g;const{utils:{isUndefined:u}}=fe,{event:E,elements:m=[]}=n.lastMsg||{};return u(E)?{type:m[0]?m[0].type:null,payload:m[0]?this._amendLayersOverLimitProp(m[0].content):null}:{type:Lo.MSG_GRP_TIP,payload:((g=m?.[0])===null||g===void 0?void 0:g.content)||{}}}_computeGroupUnreadCount(n){const{unreadCount:g=0,noUnreadCount:u=0}=n,E=g-u;return E>0?E:0}_reset(){this._pagingStatus=bd.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}_dispose(){this._reset();const{notificationCenter:n}=fe;n.unSubscribeInnerEvent(so.LOGOUT,this._reset,this),n.unSubscribeInnerEvent(so.DESTROY,this._dispose,this)}}class AS{constructor(){this.syncConversationHandler=new $D,this.syncConversationHandler.init()}}console.log(`TencentCloudLiteChat.VERSION:${Zr}`);var eS={create:function(s){var n,g;const{SDKAppID:u,testEnv:E=!1,devMode:m=!1,unlimitedAVChatRoom:D=!1,scene:M="",oversea:T=!1,instance:P,disableIndependentDomain:W=!1,proxyServer:iA=""}=s;let EA=u;if(!function(kA){if(typeof kA=="number")return!0;const xA=Number(kA);return!Number.isNaN(xA)}(EA))return console.error("Create SDK instance failed. Failed to parse the SDKAppID, please check the arguments"),null;if(EA=Number(EA),da.has(EA))return da.get(EA);let RA=null;if(P)RA=P,RA._workflowManager&&ws.setInstance(RA._workflowManager),RA._pluginManager&&RA._pluginManager.installBuiltInPlugin(yB),P.isReady()&&((g=(n=ws.getInstance()).executeWorkflow)===null||g===void 0||g.call(n,xt.SYNC_SERVER_INFO_AFTER_LOGIN));else{const kA=function(){function ne(){return(65536*(1+Math.random())|0).toString(16).substring(1)}return`${ne()+ne()}${ne()}${ne()}${ne()}${ne()}${ne()}${ne()}`}();fe.init({sdkAppId:EA,instanceId:kA,testEnv:E,devMode:m,unlimitedAVChatRoom:D,disableIndependentDomain:W,scene:M,oversea:T,sdkEdition:Km,version:Zr,proxyServer:iA}),ws.getInstance().init(),fe.message=new qD,fe.user=new $T,fe.login=new vh,fe.conversation=new AS,nu.getInstance().installBuiltInPlugin(yB),RA=Cr.getInstance().exposeApiForClient(),RA._workflowManager=ws.getInstance(),RA._pluginManager=nu.getInstance();const{utils:{IS_WORKER_AVAILABLE:xA,USER_AGENT:LA,getPlatformType:SA,isIOSWebView:OA}}=fe,JA=`instanceID:${kA} SDKAppID:${u} platform:${HA} host:${SA()} isIOSWebView:${OA} workerAvailable:${xA} UserAgent:${LA}`;fe.ssoLog.info("sdkConstruct",JA)}return da.set(EA,RA),RA},TSignaling:Hc,EVENT:Dr,VERSION:Zr,TYPES:Lo};return eS})}(W1)),W1.exports}var FoA=UoA();const ig=BW(FoA);var z1={exports:{}},OoA=z1.exports,t8;function PoA(){return t8||(t8=1,function(t,i){(function(r,l){t.exports=l()})(OoA,function(){function r(oe,je){if(!(oe instanceof je))throw new TypeError("Cannot call a class as a function")}function l(oe,je){for(var Dt=0;Dt"u"&&typeof uni.requireNativePlugin=="function",WA=TA&&uni.getDeviceInfo().platform.toLocaleLowerCase()==="ios",ge=(TA&&uni.getDeviceInfo().platform.toLocaleLowerCase(),lA||rA||mA||IA||cA||TA),ue=U!==void 0&&(U.nativeModuleProxy!==void 0||U.ReactNative!==void 0),xe=rA?qq:mA?tt:IA?swan:cA?my:lA?wx:TA?uni:{},Be=function(oe){if(k(oe)!=="object"||oe===null)return!1;var je=Object.getPrototypeOf(oe);if(je===null)return!0;for(var Dt=je;Object.getPrototypeOf(Dt)!==null;)Dt=Object.getPrototypeOf(Dt);return je===Dt};function ut(oe){if(oe==null)return!0;if(typeof oe=="boolean")return!1;if(typeof oe=="number")return oe===0;if(typeof oe=="string"||typeof oe=="function"||Array.isArray(oe))return oe.length===0;if(oe instanceof Error)return oe.message==="";if(Be(oe)){for(var je in oe)if(Object.prototype.hasOwnProperty.call(oe,je))return!1;return!0}return!1}var pt=function(){return I(function oe(){r(this,oe),this._n="WebRequest"},[{key:"request",value:function(oe,je){var Dt=this,ni="".concat(this._n,".request"),Jt=oe.downloadUrl||"",gi=(oe.method||"PUT").toUpperCase(),Fi=oe.url;if(console.log("%c tim-upload-plugin %c","background:#0abf5b; padding:1px; border-radius:3px; color: #fff","background:transparent","".concat(ni," URL:").concat(Fi)),oe.qs){var To=function(ki){var ns=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"&",jo=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"=";return ut(ki)?"":Be(ki)?Object.keys(ki).map(function($i){var jt=encodeURIComponent($i)+jo;return Array.isArray(ki[$i])?ki[$i].map(function(io){return jt+encodeURIComponent(io)}).join(ns):jt+encodeURIComponent(ki[$i])}).filter(Boolean).join(ns):void 0}(oe.qs);To&&(Fi+="".concat(Fi.indexOf("?")===-1?"?":"&").concat(To))}var to=new XMLHttpRequest;to.open(gi,Fi,!0),to.responseType=oe.dataType||"text";var uo=oe.headers||{};if(oe.uploadByIP&&(uo=w(w({},uo),{},{host:oe.uploadIP})),!ut(uo))for(var Vs in uo)uo.hasOwnProperty(Vs)&&Vs.toLowerCase()!=="content-length"&&Vs.toLowerCase()!=="user-agent"&&Vs.toLowerCase()!=="origin"&&Vs.toLowerCase()!=="host"&&to.setRequestHeader(Vs,uo[Vs]);return to.onload=function(){if(to.status===200)je(null,Dt._xhrRes(to,Dt._xhrBody(to,Jt,oe.uploadByIP&&oe.uploadIP),uo));else{if(oe.uploadIP&&oe.url.indexOf(oe.uploadIP)===-1)return oe.url=function(ns,jo){return ns.replace(/^http(s)?:\/\/(.*?)\//,"https://".concat(jo,"/"))}(oe.url,oe.uploadIP),oe.uploadByIP=!0,Dt.request(oe,je);var ki={code:to.status,message:JSON.stringify(to.responseText)};je(ki,Dt._xhrRes(to,Dt._xhrBody(to,Jt,oe.uploadByIP&&oe.uploadIP),uo))}},to.onerror=function(ki){var ns=Dt._xhrBody(to,Jt,oe.uploadByIP&&oe.uploadIP),jo={code:to.status,message:JSON.stringify(to.responseText)};ns||to.statusText||to.status!==0||(ki.message="CORS blocked or network error"),je(jo,Dt._xhrRes(to,ns)),jo=null},oe.onProgress&&to.upload&&(to.upload.onprogress=function(ki){var ns=ki.total,jo=ki.loaded,$i=Math.floor(100*jo/ns);oe.onProgress({total:ns,loaded:jo,percent:($i>=100?100:$i)/100})}),to.send(oe.resources),to}},{key:"_xhrRes",value:function(oe,je){var Dt={};return oe.getAllResponseHeaders().trim().split(`
-`).forEach(function(ni){if(ni){var Jt=ni.indexOf(":"),gi=ni.substr(0,Jt).trim().toLowerCase(),Fi=ni.substr(Jt+1).trim();Dt[gi]=Fi}}),{statusCode:oe.status,statusMessage:oe.statusText,headers:Dt,data:je}}},{key:"_xhrBody",value:function(oe,je,Dt){return oe.status===200&&je?{location:je,uploadIP:Dt}:{response:oe.responseText,uploadIP:Dt}}}])}(),ze=["unknown","image","video","audio","log"],_e=["name"],We=function(){return I(function oe(){r(this,oe)},[{key:"request",value:function(oe,je){var Dt=this,ni=oe.resources,Jt=ni===void 0?"":ni,gi=oe.headers,Fi=gi===void 0?{}:gi,To=oe.url,to=oe.downloadUrl,uo=to===void 0?"":to,Vs=To,ki=null,ns=uo.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/),jo=decodeURIComponent(ns[3]),$i=jo.indexOf("?")>-1?jo.split("?")[0]:jo,jt={key:oe.fileKey?oe.fileKey:$i,success_action_status:200,"Content-Type":""},io={};if(WA){var bi=To.split("?sign=");if(bi.length>1){var vs=bi[1];Vs="".concat(bi[0],"?sign=").concat(encodeURIComponent("".concat(vs))),io.sign=decodeURIComponent(vs),io.signature=decodeURIComponent(vs)}}var HA={url:Vs,header:Fi,name:"file",filePath:Jt,formData:w(w({},jt),io),timeout:oe.timeout||3e5};if(cA){var ce=HA;ce.name,HA=w(w({},function(Ve,Ut){if(Ve==null)return{};var nt,It,Xt=function(be,Xe){if(be==null)return{};var vt={};for(var wt in be)if({}.hasOwnProperty.call(be,wt)){if(Xe.includes(wt))continue;vt[wt]=be[wt]}return vt}(Ve,Ut);if(Object.getOwnPropertySymbols){var $t=Object.getOwnPropertySymbols(Ve);for(It=0;It<$t.length;It++)nt=$t[It],Ut.includes(nt)||{}.propertyIsEnumerable.call(Ve,nt)&&(Xt[nt]=Ve[nt])}return Xt}(ce,_e)),{},{fileName:"file",fileType:ze[oe.fileType]})}return(ki=xe.uploadFile(w(w({},HA),{},{success:function(Ve){Dt._handleResponse({response:Ve,downloadUrl:uo,callback:je})},fail:function(Ve){Dt._handleResponse({response:Ve,downloadUrl:uo,callback:je})}}))).onProgressUpdate&&ki.onProgressUpdate(function(Ve){oe.onProgress&&oe.onProgress({total:Ve.totalBytesExpectedToSend,loaded:Ve.totalBytesSent,percent:Math.floor(Ve.progress)/100})}),ki}},{key:"_handleResponse",value:function(oe){var je=oe.downloadUrl,Dt=oe.response,ni=oe.callback,Jt=Dt.header,gi={};if(Jt)for(var Fi in Jt)Jt.hasOwnProperty(Fi)&&(gi[Fi.toLowerCase()]=Jt[Fi]);var To=+Dt.statusCode;To===200?ni(null,{statusCode:To,headers:gi,data:w(w({},Dt.data),{},{location:je})}):ni({code:To,message:JSON.stringify(Dt.data)},{statusCode:To,headers:gi,data:void 0})}}])}(),Le=function(){return I(function oe(){r(this,oe)},[{key:"request",value:function(oe,je){var Dt=this,ni=oe.resources,Jt=ni===void 0?"":ni,gi=oe.fileKey,Fi=gi===void 0?"":gi,To=oe.url,to=oe.downloadUrl,uo=to===void 0?"":to,Vs=new FormData;Vs.append("key",Fi),Vs.append("success_action_status",200),Vs.append("file",{uri:Jt,type:"application/octet-stream",name:"uploaded_file"}),fetch(To,{method:"POST",headers:{"Content-Type":"multipart/form-data"},body:Vs}).then(function(ki){Dt._handleResponse({response:ki,downloadUrl:uo,callback:je})}).catch(function(ki){Dt._handleResponse({response:ki,downloadUrl:uo,callback:je})})}},{key:"_handleResponse",value:function(oe){var je=oe.downloadUrl,Dt=oe.response,ni=oe.callback,Jt=Dt.headers,gi=Dt.status,Fi=Jt&&Jt.map||{};gi===200?ni(null,{statusCode:200,headers:Fi,data:{location:je}}):ni({code:gi,message:JSON.stringify(Dt)},{statusCode:gi,headers:Fi,data:void 0})}}])}();return function(){return I(function oe(){r(this,oe),this.retry=1,this.tryCount=0,this.systemClockOffset=0,this.httpRequest=ge?new We:ue?new Le:new pt,console.log("TIMUploadPlugin.VERSION: ".concat("1.4.3"))},[{key:"uploadFile",value:function(oe,je){var Dt=this;return this.httpRequest.request(oe,function(ni,Jt){ni&&Dt.tryCount=3e4&&(this.systemClockOffset=To-Fi,je=!0)}else Math.floor(oe.statusCode/100)===5&&(je=!0)}return je}}],[{key:"getVersion",value:function(){return"1.4.3"}}])}()})}(z1)),z1.exports}var xoA=PoA();const YoA=BW(xoA);/**
+`],{type:"application/javascript"});this._worker=new Worker(URL.createObjectURL(g)),this._worker.postMessage({type:fr,url:n})}send(n){var g,u;try{(g=this._worker)===null||g===void 0||g.postMessage({type:Ls,data:n})}catch(E){(u=this._onSendFail)===null||u===void 0||u.call(this,E)}}bindSocketHandlers(n){const{onOpen:g,onMessage:u,onClose:E,onError:m,onSendFail:D}=n;if(this._worker){const M={[ms]:g,[as]:u,[Mu]:E,[Wa]:m,[Cs]:D};this._onSendFail=D,this._worker.onmessage=T=>{var P;const{type:W}=T?.data||{};typeof M[W]=="function"&&((P=M[W])===null||P===void 0||P.call(M,T?.data))}}}unbindSocketHandlers(){this._worker&&(this._worker.onmessage=null)}disconnect(){this._worker&&(this._worker.postMessage({type:Jc}),this._worker.terminate(),this._worker=null),this._blobUrl&&(URL.revokeObjectURL(this._blobUrl),this._blobUrl=null)}}class JI{}var $o,Xi=new class{constructor(){this._store=new Map}get(s){return this._store.get(s)}getStorage(s){return ki?gi?my.getStorageSync({key:s}).data:io.getStorageSync(s):this._canUseLocalStorage()?localStorage.getItem(s):{}}set(s,n){const g=this._store.get(s)||{};n instanceof Map?this._store.set(s,n):this._store.set(s,Object.assign(Object.assign({},g),n))}setStorage(s,n){ki?gi?my.setStorageSync({key:s,data:JSON.stringify(n)}):io.setStorageSync(s,JSON.stringify(n)):this._canUseLocalStorage()&&localStorage.setItem(s,JSON.stringify(n))}clear(s){typeof s=="string"?this._store.set(s,{}):this._store.clear()}clearLocalStorage(s){this._canUseLocalStorage()&&(typeof s=="string"?localStorage.setItem(s,""):localStorage.clear())}reset(){this.clear()}_canUseLocalStorage(){return typeof window<"u"&&navigator&&navigator.cookieEnabled&&localStorage}};class pc{connectSocket(n){return this._socket=io.connectSocket({url:n,header:{"content-type":"application/json"},multiple:!0,complete:()=>{}}),this._socket}send(n){var g;(g=this._socket)===null||g===void 0||g.send({data:n,fail:this._onSendFail})}bindSocketHandlers(n){const{onOpen:g,onMessage:u,onClose:E,onError:m,onSendFail:D}=n;this._socket&&(this._socket.onClose(E),this._socket.onOpen(g),this._socket.onMessage(M=>u(M?.data)),this._socket.onError(()=>m),this._onSendFail=D)}unbindSocketHandlers(){this._socket&&(this._socket.onClose(()=>{}),this._socket.onOpen(()=>{}),this._socket.onMessage(()=>{}),this._socket.onError(()=>{}))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}(function(s){s[s.CONNECTED=0]="CONNECTED",s[s.CONNECTING=1]="CONNECTING",s[s.DISCONNECTED=2]="DISCONNECTED"})($o||($o={}));class ng{constructor(n){this._url="",this._readyState=$o.DISCONNECTED,this._url=n,this._id=U(),this._emitter=new On,gi?this._socket=new pc:ut||To||_e||XA||Fi||Ut?this._socket=new cn({onError:this._onError.bind(this)}):an?this._socket=new JI:this._canUseWebWorker()?this._socket=new sg:this._socket=new Sl,this.connect()}connect(){this.doOpen(),this._bindSocketHandlers()}doOpen(){[$o.CONNECTED,$o.CONNECTING].includes(this._readyState)||(this._readyState=$o.CONNECTING,this._ws=this._socket.connectSocket(this._url))}send(n){this._readyState!==$o.CONNECTED?this.reconnect():this._socket.send(n)}reconnect(){[$o.CONNECTED,$o.CONNECTING].includes(this._readyState)||(this.disconnect(),this.doOpen())}getId(){return this._id}on(n,g,u){this._emitter.on(n,g,u)}off(n,g,u){this._emitter.off(n,g,u)}isConnected(){return this._readyState===$o.CONNECTED}disconnect(){this._readyState=$o.DISCONNECTED,this._unbindSocketHandlers(),this._socket.disconnect()}_onOpen(n){this._readyState===$o.CONNECTING&&(this._readyState=$o.CONNECTED,this._emitter.emit("connect",{socketId:this._id,event:n}))}_onMessage(n){this._emitter.emit("message",n)}_onClose(n){this._readyState=$o.DISCONNECTED,this._emitter.emit("close",{socketId:this._id,event:n})}_onError(n){this._readyState=$o.DISCONNECTED,this._emitter.emit("error",{socketId:this._id,error:n})}_onSendFail(n){this._readyState=$o.DISCONNECTED,this._emitter.emit("sendFail",{socketId:this._id,error:n})}_bindSocketHandlers(){this._socket.bindSocketHandlers({onOpen:this._onOpen.bind(this),onMessage:this._onMessage.bind(this),onClose:this._onClose.bind(this),onError:this._onError.bind(this),onSendFail:this._onSendFail.bind(this)})}_unbindSocketHandlers(){this._socket.unbindSocketHandlers()}_canUseWebWorker(){const n=Xi.get("cloudConfig")||{};return(r(n.isWorkerEnabled)||n.isWorkerEnabled==="1")&&Go}}const Dg={[gt.SINGAPORE]:[[2e7,3e7],[172e7,173e7]],[gt.KOREA]:[[3e7,4e7],[173e7,174e7]],[gt.GERMANY]:[[4e7,5e7],[174e7,175e7]],[gt.IND]:[[5e7,6e7],[175e7,176e7]],[gt.JPN]:[[6e7,7e7],[176e7,177e7]],[gt.USA]:[[7e7,8e7],[177e7,178e7]],[gt.INDONESIA]:[[8e7,9e7],[178e7,179e7]],[gt.KSA]:[[9e7,1e8],[179e7,18e8]]};function ua(s){var n;if(!((n=Xi.get("instance"))===null||n===void 0)&&n.oversea)return gt.OVERSEA;for(const g of Object.keys(Dg))for(const[u,E]of Dg[g])if(s>=u&&s`${iA}=${W[iA]}`).join("&"));var W;return g?`${s}/binfo?${P}&compress=gzip`:`${s}/info?${P}`}function Hs(s){const n=Xi.get("instance"),{sdkAppId:g,testEnv:u,proxyServer:E}=n,m=ua(g);if(u)return Hn(pt.TEST[m].DEFAULT,{isBinary:s});if(!Rs(E))return Hn(E,{isBinary:s});const D=pt.PRODUCTION[m],M=Wt&&D.ANYCAST,T=Wt,P=!!D.BACKUP_CN;return Hn({[bo.INITIAL]:()=>(_o=bo.DEFAULT,D.DEFAULT),[bo.DEFAULT]:()=>(_o=bo.IPV6,D.IPV6),[bo.IPV6]:()=>(_o=bo.BACKUP,D.BACKUP),[bo.BACKUP]:()=>T?(_o=bo.BACKUP_WEB_ONLY,function(W){const iA=Math.floor(10001*Math.random())+1e4;return W.replace("*",String(iA))}(D.BACKUP_WEB_ONLY)):P?(_o=bo.BACKUP_CN,D.BACKUP_CN):M?(_o=bo.ANYCAST,D.ANYCAST):D.DEFAULT,[bo.BACKUP_WEB_ONLY]:()=>P?(_o=bo.BACKUP_CN,D.BACKUP_CN):M?(_o=bo.ANYCAST,D.ANYCAST):D.DEFAULT,[bo.BACKUP_CN]:()=>(_o=M?bo.ANYCAST:bo.DEFAULT,D[_o]),[bo.ANYCAST]:()=>(_o=bo.DEFAULT,D.ANYCAST="",D.DEFAULT)}[_o](),{isBinary:s})}var Sg=new class{constructor(){this._timeOffsetWithServer=0}getServerTimeMs(){return Date.now()+this._timeOffsetWithServer}getServerTimeSeconds(){return Math.floor(this.getServerTimeMs()/1e3)}getTimeOffsetWithServer(){return this._timeOffsetWithServer}calculateTimeOffsetWithServer(s,n){const g=Date.now(),u=g-s;this._timeOffsetWithServer=n+u-g}};const mc=16;var fn=new class{constructor(){this._tasks=[],this._timer=null,this._taskMap=new Map}_addTaskToScheduler(s){const{id:n}=s;this.removeTask(n),this._tasks.push(s),this._taskMap.set(n,s),this._sort(),this._scheduleNextTask()}_createTask(s){const{id:n,callback:g,context:u,isOnce:E=!1,intervalMs:m=mc}=s,D=Math.max(m,mc);return{id:n,nextExecuteTime:Date.now()+D,intervalMs:m,callback:g,context:u,isOnce:E}}addTask(s){const n=this._createTask(s);this._addTaskToScheduler(n)}addOnceTask(s){const n=this._createTask(Object.assign(Object.assign({},s),{isOnce:!0}));this._addTaskToScheduler(n)}removeTask(s){const n=this._tasks.findIndex(g=>g.id===s);n>-1&&(this._tasks.splice(n,1),this._taskMap.delete(s),this._scheduleNextTask())}updateTaskInterval(s,n){const g=this._taskMap.get(s);g&&(g.intervalMs=n,g.nextExecuteTime=Date.now()+n,this._sort(),this._scheduleNextTask())}clearAllTasks(){this._tasks=[],this._taskMap.clear(),this._timer&&(clearTimeout(this._timer),this._timer=null)}dispose(){this.clearAllTasks()}_sort(){this._tasks.sort((s,n)=>s.nextExecuteTime-n.nextExecuteTime)}_scheduleNextTask(){this._timer&&(clearTimeout(this._timer),this._timer=null);const s=this._tasks[0];if(s){const n=Math.max(0,s.nextExecuteTime-Date.now());this._timer=setTimeout(()=>this._execute(),n)}}_execute(){const s=Date.now();for(;this._tasks.length&&this._tasks[0].nextExecuteTime<=s;){const n=this._tasks[0];try{n.context?n.callback.call(n.context):n.callback(),n.isOnce?this.removeTask(n.id):(n.nextExecuteTime=s+n.intervalMs,this._sort())}catch(g){console.warn(`Task ${n.id} execution failed:`,g),n.isOnce&&this.removeTask(n.id)}}this._scheduleNextTask()}};function Ga(s){const n=[];for(let g=0;g=55296&&u<=56319){const E=s.charCodeAt(++g)-56320+(u-55296<<10)+65536;n.push(240|E>>18,128|E>>12&63,128|E>>6&63,128|63&E)}else u<=127?n.push(u):u<=2047?n.push(192|u>>6,128|63&u):n.push(224|u>>12,128|u>>6&63,128|63&u)}return new Uint8Array(n)}function In(s){const n=Array.isArray(s)?[]:Object.create(null);for(const g in s)Object.prototype.hasOwnProperty.call(s,g)&&_(g)&&s[g]!=null&&(s[g]===null||typeof s[g]!="object"?n[g]=s[g]:n[g]=In(s[g]));return n}function fs(s,n){if(mA.includes(s))return 0;const g=Ga(JSON.stringify(n));let u=4294967295;const{length:E}=g;for(let m=0;m>>=1:u=u>>>1^3988292384}return(4294967295^u)>>>0}function Ea(s){const{servcmd:n,data:g}=s,u=function(m){const D=Xi.get("login")||{},M=Xi.get("instance")||{};return{servcmd:m,ver:"v4",platform:HA,websdkappid:537048168,websdkversion:"1.7.3",a2:D.a2Key||void 0,tinyid:D.tinyID||void 0,status_instid:D.statusInstanceId||0,sdkappid:M.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:D.a2Key?void 0:D.userId,usersig:D.a2Key?void 0:D.userSig,sdkability:478343027,sdkability_ext:IA(""),cappid:M.applicationID||0,tjgID:"",seq:Sa(),cs:0}}(n),E=In(g);return u.cs=fs(n,E),{head:u,body:E}}function yn(s){const{servcmd:n,data:g}=s,u=function(m){const D=Xi.get("login")||{},M=Xi.get("instance")||{};return{servcmd:m,ver:"v4",platform:HA,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:M.sdkAppId,contenttype:"",reqtime:Math.floor(Date.now()/1e3),identifier:"",usersig:"",status_instid:D.statusInstanceId||0,sdkability:478343027,sdkability_ext:IA(""),cappid:M.applicationID||0,seq:Sa(),cs:0}}(n),E=In(g);return u.cs=fs(n,E),{head:u,body:E}}let ba=U();function Sa(){return ba=ba<2415919103?ba+1:U(),ba}function $(){var s;const n=Xi.get("login")||{},g=Xi.get("instance")||{};return{sdk_type:30,sdk_app_id:g.sdkAppId,sdk_version:"1.6.18",tiny_id:Number(n.tinyID),user_id:n.userId||((s=Xi.get("webPush"))===null||s===void 0?void 0:s.userId),platform:HA,instance_id:g.instanceId,trace_id:new Date().getTime()}}var K,vA=Object.freeze({__proto__:null,calcBodyCRC:fs,filterProtocolDataInvalidFields:In,generateCosSpecifiedData:function(s){const{servcmd:n,data:g}=s,u=function(m){const D=Xi.get("login")||{},M=Xi.get("instance")||{};return{servcmd:m,ver:"v4",platform:HA,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:M.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:D.userId,usersig:D.userSig,status_instid:D.statusInstanceId||0,sdkability:478343027,sdkability_ext:IA(""),cappid:M.applicationID||0,seq:Sa(),cs:0}}(n),E=In(g);return u.cs=fs(n,E),{head:u,body:E}},generateProtocolData:Ea,generateSSOLogProtocolData:yn,generateSequence:Sa,getCommonHead:$,getHostSite:ua,taskScheduler:fn,timeManager:Sg});(function(s){s[s.info=4]="info",s[s.warning=5]="warning",s[s.error=6]="error"})(K||(K={}));const qA={method:"extension",networkType:"network_type",eventType:"event_type",code:"error_code",message:"error_message",moreMessage:"more_message",duplicate:"duplicate",costTime:"cost_time",level:"level",uiPlatform:"ui_platform",timestamp:"timestamp"};class ee{constructor(n){this.level=K.info,this._canSendLog=!0,this._logCreatedAt=Sg.getServerTimeMs(),this.timestamp=0,this.networkType=8,this.code=0,this.moreMessage="",this.method="",this.message="",this.costTime=0,this.duplicate=!1,this.eventType=0,this.uiPlatform=this._getUiPlatform(),this._sdkEdition=this._getSDKEdition();const{method:g,eventType:u=0,message:E="",costTime:m=0,error:D,uiPlatform:M,moreMessage:T="",code:P=0,startTime:W=0}=n||{};this.eventType=u,this.method=g,this.message=E,this.costTime=m,this.moreMessage=`${T} startTime:${W}`,this.code=P,D&&this.setError(D),Rs(M)||(this.uiPlatform=M)}setMoreMessage(n){this.moreMessage=`${this.moreMessage} ${n}`}updateLogCreatedAtByTimeOffset(){this._logCreatedAt+=Sg.getTimeOffsetWithServer()}end(n=!1){this._canSendLog&&(this._canSendLog=!1,this.timestamp=Sg.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe()),n&&this._ssoLogModule.uploadSSOLogData())}setError(n){var g;return n instanceof Error?this._canSendLog?(!((g=Xi.get("netWorkMonitor"))===null||g===void 0)&&g.isNetworkOnline&&(n.errorCode&&(this.code=n.errorCode),n.errorMessage&&this.setMoreMessage(n.errorMessage)),this.level=K.error,this):this:(console.warn("SSOLogData.setError value not instanceof Error, please check!"),this)}setLogInfo(n){return Object.keys(n).forEach(g=>{Object.keys(qA).includes(g)&&(this[g]=n[g])}),this}setSSOLogModule(n){this._ssoLogModule=n}_convertSSOLogDataKeyToServe(){const n={};return Object.keys(this).forEach(g=>{const u=g;qA[u]&&(n[qA[u]]=this[u])}),n}_getUiPlatform(){var n;const g=(n=Xi.get("instance"))===null||n===void 0?void 0:n.scene;if(typeof g=="string"){const u=Number(g);return isNaN(u)?void 0:u}}_getSDKEdition(){var n;return(n=Xi.get("instance"))===null||n===void 0?void 0:n.sdkEdition}}var fe;(function(s){s.RECONNECTED="reconnected",s.CLOUD_CONFIG_UPDATE="cloud_config_update",s.SOCKET_DISCONNECTED="socket_disconnected"})(fe||(fe={}));var xe=fe;const Oe=20,rt=6e4,dt=[4,5,6],Mt="report-logger";var xt=new class{constructor(){this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._reportLevel=[4,5,6],this._minThreshold=Oe,this._maxThreshold=100,this._waitingTime=rt,this._lastReportAt=Date.now(),this._ssoLogMap=new Map,this._logLevel=lA.DEBUG,this._throttleConfig={global:{throttleTime:Pe,maxCount:pe},single:{throttleTime:Ee,maxCount:de}},this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap=new Map,gn.subscribeInnerEvent(xe.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),fn.addTask({id:Mt,intervalMs:1e3,callback:this._checkAndReportIfDue,context:this}),this._logQueue=[],this._savePlatFormInfo()}_handleCloudConfigUpdate(s){const{evt_rpt_threshold:n=Oe,evt_rpt_waiting:g=rt,evt_rpt_level:u=dt,evt_rpt_sdkappid_bl:E="",evt_rpt_tinyid_wl:m="",evt_rpt_global_throttle_time:D=Pe,evt_rpt_global_throttle_count:M=pe,evt_rpt_single_throttle_time:T=Ee,evt_rpt_single_throttle_count:P=de}=s||{};this._sdkAppIdBlackList=E.split(",").map(W=>Number(W)),this._waitingTime=Number(g),this._minThreshold=n,this._reportLevel=u,this._tinyIdWhiteList=m.split(","),this._throttleConfig={global:{throttleTime:D,maxCount:M},single:{throttleTime:T,maxCount:P}}}createSSOLogData(s){const n=new ee(s);return n.setSSOLogModule(this),this._ssoLogMap.set(s.method,n),n}getSSOLogData(s){return this._ssoLogMap.get(s)||{}}pushToLogQueue(s){s&&(this._logQueue.push(s),this._shouldUploadImmediately()&&this.uploadSSOLogData())}setLogLevel(s){[lA.DEBUG,lA.ERROR,lA.INFO,lA.NONE,lA.WARN].includes(s)&&(this._logLevel=s)}debug(s,n="",g){this._log(lA.DEBUG,s,n,g)}info(s,n="",g){this._log(lA.INFO,s,n,g)}warn(s,n="",g){this._log(lA.WARN,s,n,g)}error(s,n="",g){this._log(lA.ERROR,s,n,g)}_shouldUploadImmediately(){return this._logQueue.length>=this._minThreshold}_isReportDue(){return Date.now()>=this._lastReportAt+this._waitingTime}_checkAndReportIfDue(){this._isReportDue()&&this._logQueue.length>0&&this.uploadSSOLogData()}uploadSSOLogData(){return pA(this,void 0,void 0,function*(){if(this._logQueue.length===0)return;const s=this._logQueue.slice();this._logQueue=[];try{const n=this._filterLogs(s);if(n.length===0)return void(this._lastReportAt=Date.now());const g={Header:$(),Event:n};Rs(g.Header.user_id)||(yield function(u){const E="imopenstat.tim_web_report_v2",m=yn({servcmd:E,data:u}),D=`${m.head.seq}${E}`;return De.sendPacket(m,{requestId:D})}(g))}catch(n){this._requeueFailedLogs(s),this.debug("uploadSSOLogData",en(n))}finally{this._lastReportAt=Date.now()}})}_requeueFailedLogs(s){this._logQueue=s.concat(this._logQueue);const n=this._logQueue.length-200;n>0&&(this._logQueue.splice(0,n),this.debug("uploadSSOLogData",`log queue overflow, dropped ${n} oldest logs`))}_savePlatFormInfo(){var s,n;if(ut){const g=(n=(s=wx.getAccountInfoSync)===null||s===void 0?void 0:s.call(wx))===null||n===void 0?void 0:n.miniProgram;if(g){const{appId:u,envVersion:E}=g;Xi.set("instance",{appId:u,envVersion:E})}}else Wt&&Xi.set("instance",{href:window.location.href})}_filterLogs(s){const{tinyID:n}=Xi.get("login")||{},{sdkAppId:g}=Xi.get("instance")||{};return this._sdkAppIdBlackList.includes(g)&&!this._tinyIdWhiteList.includes(n)?[]:s.filter(u=>this._reportLevel.includes(u.level))}_checkThrottle(s){return!!this._checkGlobalThrottle()||this._checkSingleThrottle(s)}_checkGlobalThrottle(){const s=Date.now();if(s-this._globalThrottle.startTime>=this._throttleConfig.global.throttleTime)this._globalThrottle.count=1,this._globalThrottle.startTime=s;else if(this._globalThrottle.count++,this._globalThrottle.count>this._throttleConfig.global.maxCount)return!0;return!1}_checkSingleThrottle(s){const n=Date.now(),g=this._singleThrottleMap.get(s);return g?n-g.startTime>=this._throttleConfig.single.throttleTime?(g.count=1,g.startTime=n,!1):g.count>=this._throttleConfig.single.maxCount||(g.count++,!1):(this._singleThrottleMap.set(s,{count:1,startTime:n}),!1)}_shouldLog(s){return s>=this._logLevel&&this._logLevel!==lA.NONE}_shouldReport(s){return this._reportLevel.includes(WA[s])}_formatLog(s,n,g,u){const E=new Date,m=`${E.getHours()}:${E.getMinutes()}:${E.getSeconds()}:${E.getMilliseconds()}`,D=`<${lA[s]}>`;return _t||ki?[`${cA} [${m}] ${D} [${n}] ${g}`]:["%c%s%c%s","background:#0abf5b; padding:1px; border-radius:3px; color: #fff",cA,"",`[${m}] ${D} [${n}] ${g} params: ${en(u)}`]}_log(s,n,g,u){if(this._shouldLog(s)){const E=this._formatLog(s,n,g,u);TA[s].apply(console,E)}if(this._shouldReport(s)){const E=this._getThrottleKey(n,g,u);this._checkThrottle(E)||this.createSSOLogData(Object.assign(Object.assign({message:g},u),{method:n})).end()}}_getThrottleKey(s,n,g){const u=`${s}${n}${en(Object.assign(Object.assign({},g),{costTime:""}))}`,E=Ga(JSON.stringify(u));let m=4294967295;const{length:D}=E;for(let M=0;M>>=1:m=m>>>1^3988292384}return`${(4294967295^m)>>>0}`}reset(){console.log("SSO_LOG_MODULE.reset"),fn.removeTask(Mt),gn.unSubscribeInnerEvent(xe.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),this._lastReportAt=0,this.uploadSSOLogData(),this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._minThreshold=Oe,this._maxThreshold=100,this._waitingTime=rt,this._logQueue=[],this._logLevel=lA.DEBUG,this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap.clear()}};const Ii=15e3,ct="Channel",Pt="channel_schedule_task",Ji="channel_reconnect_task",Ki="connected",qs="connecting",Mi="disconnected",zo=1e3,Mg="network_status_change",sr="activity_status_change",yr="send_fail",xn="reconnect_failed",Ml="socket_error",Ks="socket_close";function aI(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function Wg(s){return Wg=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(n){return typeof n}:function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},Wg(s)}function fc(s){throw new Error('Could not dynamically require "'+s+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var vu,Ma={exports:{}},vl=(vu||(vu=1,function(s){s.exports=function n(g,u,E){function m(T,P){if(!u[T]){if(!g[T]){if(!P&&fc)return fc(T);if(D)return D(T,!0);var W=new Error("Cannot find module '"+T+"'");throw W.code="MODULE_NOT_FOUND",W}var iA=u[T]={exports:{}};g[T][0].call(iA.exports,function(EA){return m(g[T][1][EA]||EA)},iA,iA.exports,n,g,u,E)}return u[T].exports}for(var D=fc,M=0;M>>6:(EA<65536?iA[xA++]=224|EA>>>12:(iA[xA++]=240|EA>>>18,iA[xA++]=128|EA>>>12&63),iA[xA++]=128|EA>>>6&63),iA[xA++]=128|63&EA);return iA},u.buf2binstring=function(W){return P(W,W.length)},u.binstring2buf=function(W){for(var iA=new E.Buf8(W.length),EA=0,RA=iA.length;EA>10&1023,SA[RA++]=56320|1023&kA)}return P(SA,RA)},u.utf8border=function(W,iA){var EA;for((iA=iA||W.length)>W.length&&(iA=W.length),EA=iA-1;0<=EA&&(192&W[EA])==128;)EA--;return EA<0||EA===0?iA:EA+M[W[EA]]>iA?EA:iA}},{"./common":1}],3:[function(n,g,u){g.exports=function(E,m,D,M){for(var T=65535&E,P=E>>>16&65535,W=0;D!==0;){for(D-=W=2e3>>1:m>>>1;D[M]=m}return D}();g.exports=function(m,D,M,T){var P=E,W=T+M;m^=-1;for(var iA=T;iA>>8^P[255&(m^D[iA])];return-1^m}},{}],6:[function(n,g,u){g.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],7:[function(n,g,u){g.exports=function(E,m){var D,M,T,P,W,iA,EA,RA,kA,xA,LA,SA,OA,JA,ae,re,_i,Ti,Lt,Ni,cs,Me,mt,UA,si;D=E.state,M=E.next_in,UA=E.input,T=M+(E.avail_in-5),P=E.next_out,si=E.output,W=P-(m-E.avail_out),iA=P+(E.avail_out-257),EA=D.dmax,RA=D.wsize,kA=D.whave,xA=D.wnext,LA=D.window,SA=D.hold,OA=D.bits,JA=D.lencode,ae=D.distcode,re=(1<>>=Lt=Ti>>>24,OA-=Lt,(Lt=Ti>>>16&255)==0)si[P++]=65535&Ti;else{if(!(16&Lt)){if(!(64&Lt)){Ti=JA[(65535&Ti)+(SA&(1<>>=Lt,OA-=Lt),OA<15&&(SA+=UA[M++]<>>=Lt=Ti>>>24,OA-=Lt,!(16&(Lt=Ti>>>16&255))){if(!(64&Lt)){Ti=ae[(65535&Ti)+(SA&(1<>>=Lt,OA-=Lt,(Lt=P-W)>3,SA&=(1<<(OA-=Ni<<3))-1,E.next_in=M,E.next_out=P,E.avail_in=M>>24&255)+(Me>>>8&65280)+((65280&Me)<<8)+((255&Me)<<24)}function SA(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new E.Buf16(320),this.work=new E.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function OA(Me){var mt;return Me&&Me.state?(mt=Me.state,Me.total_in=Me.total_out=mt.total=0,Me.msg="",mt.wrap&&(Me.adler=1&mt.wrap),mt.mode=RA,mt.last=0,mt.havedict=0,mt.dmax=32768,mt.head=null,mt.hold=0,mt.bits=0,mt.lencode=mt.lendyn=new E.Buf32(kA),mt.distcode=mt.distdyn=new E.Buf32(xA),mt.sane=1,mt.back=-1,iA):EA}function JA(Me){var mt;return Me&&Me.state?((mt=Me.state).wsize=0,mt.whave=0,mt.wnext=0,OA(Me)):EA}function ae(Me,mt){var UA,si;return Me&&Me.state?(si=Me.state,mt<0?(UA=0,mt=-mt):(UA=1+(mt>>4),mt<48&&(mt&=15)),mt&&(mt<8||15=Gi.wsize?(E.arraySet(Gi.window,mt,UA-Gi.wsize,Gi.wsize,0),Gi.wnext=0,Gi.whave=Gi.wsize):(si<(_s=Gi.wsize-Gi.wnext)&&(_s=si),E.arraySet(Gi.window,mt,UA-si,_s,Gi.wnext),(si-=_s)?(E.arraySet(Gi.window,mt,UA-si,si,0),Gi.wnext=si,Gi.whave=Gi.wsize):(Gi.wnext+=_s,Gi.wnext===Gi.wsize&&(Gi.wnext=0),Gi.whave>>8&255,UA.check=D(UA.check,dg,2,0),Nt=Tt=0,UA.mode=2;break}if(UA.flags=0,UA.head&&(UA.head.done=!1),!(1&UA.wrap)||(((255&Tt)<<8)+(Tt>>8))%31){Me.msg="incorrect header check",UA.mode=30;break}if((15&Tt)!=8){Me.msg="unknown compression method",UA.mode=30;break}if(Nt-=4,Va=8+(15&(Tt>>>=4)),UA.wbits===0)UA.wbits=Va;else if(Va>UA.wbits){Me.msg="invalid window size",UA.mode=30;break}UA.dmax=1<>8&1),512&UA.flags&&(dg[0]=255&Tt,dg[1]=Tt>>>8&255,UA.check=D(UA.check,dg,2,0)),Nt=Tt=0,UA.mode=3;case 3:for(;Nt<32;){if(xi===0)break A;xi--,Tt+=si[Gi++]<>>8&255,dg[2]=Tt>>>16&255,dg[3]=Tt>>>24&255,UA.check=D(UA.check,dg,4,0)),Nt=Tt=0,UA.mode=4;case 4:for(;Nt<16;){if(xi===0)break A;xi--,Tt+=si[Gi++]<>8),512&UA.flags&&(dg[0]=255&Tt,dg[1]=Tt>>>8&255,UA.check=D(UA.check,dg,2,0)),Nt=Tt=0,UA.mode=5;case 5:if(1024&UA.flags){for(;Nt<16;){if(xi===0)break A;xi--,Tt+=si[Gi++]<>>8&255,UA.check=D(UA.check,dg,2,0)),Nt=Tt=0}else UA.head&&(UA.head.extra=null);UA.mode=6;case 6:if(1024&UA.flags&&(xi<(Bo=UA.length)&&(Bo=xi),Bo&&(UA.head&&(Va=UA.head.extra_len-UA.length,UA.head.extra||(UA.head.extra=new Array(UA.head.extra_len)),E.arraySet(UA.head.extra,si,Gi,Bo,Va)),512&UA.flags&&(UA.check=D(UA.check,si,Bo,Gi)),xi-=Bo,Gi+=Bo,UA.length-=Bo),UA.length))break A;UA.length=0,UA.mode=7;case 7:if(2048&UA.flags){if(xi===0)break A;for(Bo=0;Va=si[Gi+Bo++],UA.head&&Va&&UA.length<65536&&(UA.head.name+=String.fromCharCode(Va)),Va&&Bo>9&1,UA.head.done=!0),Me.adler=UA.check=0,UA.mode=12;break;case 10:for(;Nt<32;){if(xi===0)break A;xi--,Tt+=si[Gi++]<>>=7&Nt,Nt-=7&Nt,UA.mode=27;break}for(;Nt<3;){if(xi===0)break A;xi--,Tt+=si[Gi++]<>>=1)){case 0:UA.mode=14;break;case 1:if(Ni(UA),UA.mode=20,mt!==6)break;Tt>>>=2,Nt-=2;break A;case 2:UA.mode=17;break;case 3:Me.msg="invalid block type",UA.mode=30}Tt>>>=2,Nt-=2;break;case 14:for(Tt>>>=7&Nt,Nt-=7&Nt;Nt<32;){if(xi===0)break A;xi--,Tt+=si[Gi++]<>>16^65535)){Me.msg="invalid stored block lengths",UA.mode=30;break}if(UA.length=65535&Tt,Nt=Tt=0,UA.mode=15,mt===6)break A;case 15:UA.mode=16;case 16:if(Bo=UA.length){if(xi>>=5,Nt-=5,UA.ndist=1+(31&Tt),Tt>>>=5,Nt-=5,UA.ncode=4+(15&Tt),Tt>>>=4,Nt-=4,286>>=3,Nt-=3}for(;UA.have<19;)UA.lens[nS[UA.have++]]=0;if(UA.lencode=UA.lendyn,UA.lenbits=7,_I={bits:UA.lenbits},Yl=T(0,UA.lens,0,19,UA.lencode,0,UA.work,_I),UA.lenbits=_I.bits,Yl){Me.msg="invalid code lengths set",UA.mode=30;break}UA.have=0,UA.mode=19;case 19:for(;UA.have>>16&255,wI=65535&Yg,!((_r=Yg>>>24)<=Nt);){if(xi===0)break A;xi--,Tt+=si[Gi++]<>>=_r,Nt-=_r,UA.lens[UA.have++]=wI;else{if(wI===16){for(eE=_r+2;Nt>>=_r,Nt-=_r,UA.have===0){Me.msg="invalid bit length repeat",UA.mode=30;break}Va=UA.lens[UA.have-1],Bo=3+(3&Tt),Tt>>>=2,Nt-=2}else if(wI===17){for(eE=_r+3;Nt>>=_r)),Tt>>>=3,Nt-=3}else{for(eE=_r+7;Nt>>=_r)),Tt>>>=7,Nt-=7}if(UA.have+Bo>UA.nlen+UA.ndist){Me.msg="invalid bit length repeat",UA.mode=30;break}for(;Bo--;)UA.lens[UA.have++]=Va}}if(UA.mode===30)break;if(UA.lens[256]===0){Me.msg="invalid code -- missing end-of-block",UA.mode=30;break}if(UA.lenbits=9,_I={bits:UA.lenbits},Yl=T(P,UA.lens,0,UA.nlen,UA.lencode,0,UA.work,_I),UA.lenbits=_I.bits,Yl){Me.msg="invalid literal/lengths set",UA.mode=30;break}if(UA.distbits=6,UA.distcode=UA.distdyn,_I={bits:UA.distbits},Yl=T(W,UA.lens,UA.nlen,UA.ndist,UA.distcode,0,UA.work,_I),UA.distbits=_I.bits,Yl){Me.msg="invalid distances set",UA.mode=30;break}if(UA.mode=20,mt===6)break A;case 20:UA.mode=21;case 21:if(6<=xi&&258<=gr){Me.next_out=Or,Me.avail_out=gr,Me.next_in=Gi,Me.avail_in=xi,UA.hold=Tt,UA.bits=Nt,M(Me,ln),Or=Me.next_out,_s=Me.output,gr=Me.avail_out,Gi=Me.next_in,si=Me.input,xi=Me.avail_in,Tt=UA.hold,Nt=UA.bits,UA.mode===12&&(UA.back=-1);break}for(UA.back=0;xg=(Yg=UA.lencode[Tt&(1<>>16&255,wI=65535&Yg,!((_r=Yg>>>24)<=Nt);){if(xi===0)break A;xi--,Tt+=si[Gi++]<>ac)])>>>16&255,wI=65535&Yg,!(ac+(_r=Yg>>>24)<=Nt);){if(xi===0)break A;xi--,Tt+=si[Gi++]<>>=ac,Nt-=ac,UA.back+=ac}if(Tt>>>=_r,Nt-=_r,UA.back+=_r,UA.length=wI,xg===0){UA.mode=26;break}if(32&xg){UA.back=-1,UA.mode=12;break}if(64&xg){Me.msg="invalid literal/length code",UA.mode=30;break}UA.extra=15&xg,UA.mode=22;case 22:if(UA.extra){for(eE=UA.extra;Nt>>=UA.extra,Nt-=UA.extra,UA.back+=UA.extra}UA.was=UA.length,UA.mode=23;case 23:for(;xg=(Yg=UA.distcode[Tt&(1<>>16&255,wI=65535&Yg,!((_r=Yg>>>24)<=Nt);){if(xi===0)break A;xi--,Tt+=si[Gi++]<>ac)])>>>16&255,wI=65535&Yg,!(ac+(_r=Yg>>>24)<=Nt);){if(xi===0)break A;xi--,Tt+=si[Gi++]<>>=ac,Nt-=ac,UA.back+=ac}if(Tt>>>=_r,Nt-=_r,UA.back+=_r,64&xg){Me.msg="invalid distance code",UA.mode=30;break}UA.offset=wI,UA.extra=15&xg,UA.mode=24;case 24:if(UA.extra){for(eE=UA.extra;Nt>>=UA.extra,Nt-=UA.extra,UA.back+=UA.extra}if(UA.offset>UA.dmax){Me.msg="invalid distance too far back",UA.mode=30;break}UA.mode=25;case 25:if(gr===0)break A;if(Bo=ln-gr,UA.offset>Bo){if((Bo=UA.offset-Bo)>UA.whave&&UA.sane){Me.msg="invalid distance too far back",UA.mode=30;break}Bo>UA.wnext?(Bo-=UA.wnext,Il=UA.wsize-Bo):Il=UA.wnext-Bo,Bo>UA.length&&(Bo=UA.length),_C=UA.window}else _C=_s,Il=Or-UA.offset,Bo=UA.length;for(gr_i?(Lt=Il[_C+xA[mt]],Ni=Nt[AE+xA[mt]]):(Lt=96,Ni=0),SA=1<>Or)+(OA-=SA)]=Ti<<24|Lt<<16|Ni,OA!==0;);for(SA=1<>=1;if(SA!==0?(Tt&=SA-1,Tt+=SA):Tt=0,mt++,--ln[Me]==0){if(Me===si)break;Me=W[iA+xA[mt]]}if(_s{const M=new Uint8Array(D).slice(4);let T;try{T=vl.inflate(M,{to:"string"})}catch(P){console.error("inflate error",P)}return T})(s.data):function(D){const M=new Uint8Array(D);let T="",P=0;const{length:W}=M;for(;P0)for(let kA=0;kA{var u;const{uplinkData:E,canResend:m,resolve:D,reject:M,timeout:T}=n;if(m){this._pendingRequests.set(g,{resolve:D,reject:M,timestamp:Date.now(),uplinkData:E,timeout:T,canResend:m});const P=this._isBinarySupported?Ga(E).buffer:E;(u=this._socketAdapter)===null||u===void 0||u.send(P)}else this._pendingRequests.delete(g)})}_onConnect(s){const{socketId:n,event:g={}}=s||{};this._connectionId=n,this._connectionEstablishedTime=Date.now();const u=Date.now()-this._connectionStartTime,E=`${ct}.onConnect cost:${u} ms. socketID:${n} res:${JSON.stringify(g)}`;if(this._ssoLog({method:"onConnect",message:E}),this._checkPendingRequestsAndResend(),this._sendHeartbeatIfReady(),this._isReconnecting){const m=`${ct}.reconnect success`;this._ssoLog({method:"reconnectSuccess",message:m}),gn.emitInnerEvent(xe.RECONNECTED),this._isReconnecting=!1}this._resetReconnectDelay(),this._handleConnectStateChange({state:Ki,shouldEmitEvent:!0,shouldAttemptReconnect:!1})}_sendAck(s){const n=Ea({servcmd:"openim.ws_msg_push_ack",data:{SessionData:s}});this.sendPacket(n)}_executeScheduledTaskIfReady(){return pA(this,void 0,void 0,function*(){this._clearTimeoutRequest(),this._sendHeartbeatIfReady()})}_canSendHeartbeat(){var s;return((s=this._socketAdapter)===null||s===void 0?void 0:s.isConnected())&&Date.now()>=this._nextHeartbeatAt&&!this._isHeartbeatInProgress}_sendHeartbeat(){return pA(this,void 0,void 0,function*(){var s;const n=Ea({servcmd:"heartbeat.alive",data:{}});try{const g=`${n.head.seq}${n.head.servcmd}`;yield this.sendPacket(n,{requestId:g,timeout:3e3})}catch(g){const u=(s=Xi.get("netWorkMonitor"))===null||s===void 0?void 0:s.isNetworkOnline,E=`${ct}.sendHeartbeat failed. isNetWorkOnline:${u} error: ${en(g)}`;this._ssoLog({method:"sendHeartbeatError",message:E}),this._handleConnectStateChange({state:Mi,shouldEmitEvent:!0,shouldAttemptReconnect:!0})}})}_sendHeartbeatIfReady(){return pA(this,void 0,void 0,function*(){this._canSendHeartbeat()&&(this._isHeartbeatInProgress=!0,yield this._sendHeartbeat(),this._isHeartbeatInProgress=!1)})}_updateHeartbeatTime(){this._nextHeartbeatAt=To?Date.now()+5e3:Date.now()+1e4}_handleNetworkStatusChange(s){const n=`${ct}.networkStatusChange ${JSON.stringify(s)}`;this._ssoLog({method:"networkStatusChange",message:n});const{isNetworkOnline:g,networkType:u}=s;g&&u!=="none"?this._handleConnectStateChange({state:Ki,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Mg}):this._handleConnectStateChange({state:Mi,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Mg})}isPrivateNetWork(){const s=Xi.get("instance")||{};return s.proxyServer&&!s.fileDownloadProxy}_handleConnectStateChange(s){const{state:n,shouldAttemptReconnect:g,shouldEmitEvent:u,reason:E}=s,m=`${ct}._handleConnectStateChange currentConnectState: ${this._currentConnectState} shouldAttemptReconnect: ${g} shouldEmitEvent: ${u} reason: ${E}`;this._currentConnectState!==n&&(this._ssoLog({method:"handleConnectStateChange",message:m}),u&&(xt.info("_handleConnectStateChange",` from ${this._currentConnectState} to ${n}`),gn.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:n}}),this._currentConnectState=n,n===Mi&&gn.emitInnerEvent(xe.SOCKET_DISCONNECTED)),g&&(this._resetReconnectDelay(),fn.addTask({id:Ji,intervalMs:this._intendedDelay,callback:this._scheduleReconnectWithBackoff,context:this})))}_handleActivityStatusChange(s){var n,g;const u=(g=(n=this._socketAdapter)===null||n===void 0?void 0:n._ws)===null||g===void 0?void 0:g.readyState,E=`${ct}.activityStatusChange ${JSON.stringify(s)} readyState: ${u}`;xt.debug("activityStatusChange",E),u===3&&this._handleConnectStateChange({state:Mi,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:sr})}_resetReconnectDelay(){var s;xt.debug(`${ct}._resetReconnectDelay`),fn.removeTask(Ji);const n=(s=Xi.get("activityMonitor"))===null||s===void 0?void 0:s.isActive;this._intendedDelay=n?zo:1e3}_scheduleReconnectWithBackoff(){var s;const n=(s=Xi.get("activityMonitor"))===null||s===void 0?void 0:s.isActive;this._intendedDelay=n?Math.min(5e3,Math.max(zo,1.5*this._intendedDelay)):Math.min(3e5,Math.max(1e3,1.5*this._intendedDelay));const g=new Date().toTimeString().slice(0,8),u=`${ct}.scheduleReconnectWithBackoff timeStr: ${g} intendedDelay: ${this._intendedDelay}`;xt.debug(u),this.reconnect(),fn.updateTaskInterval(Ji,this._intendedDelay)}_ssoLog(s){const{method:n,message:g}=s;xt.info(n,g)}_diagnose(){this.isPrivateNetWork()||(this._lastDiagnoseAt=Date.now(),function(s){pA(this,void 0,void 0,function*(){const n=s.split("/")[2];if(!n.startsWith("ws"))return;const g=`https://${n}/v3/netcheck/getconninfo?${s.slice(s.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield Pi({method:"GET",url:g,data:{}})}catch(u){xt.warn("diagnoseBySSO",`diagnoseBySSO failed. error:${u.message}`)}})}(this._url),function(s){pA(this,void 0,void 0,function*(){const n=`https://boce-cdn.my-imcloud.com/v3/netcheck/getconninfo?${s.slice(s.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield Pi({method:"GET",url:n,data:{}})}catch(g){xt.warn(`diagnoseByCDN', 'diagnoseByCDN failed. error:${g.message}`)}})}(this._url),this._beforeSendInterceptors=[])}_clearTimeoutRequest(){for(const[s,n]of this._pendingRequests.entries()){const{reject:g,timestamp:u,timeout:E}=n;Date.now()-u>=E&&(this._pendingRequests.delete(s),Date.now()-this._lastDiagnoseAt>=3e4&&this._diagnose(),g({errorCode:Qr,errorInfo:"NETWORK_TIMEOUT",data:{requestId:s}}))}}_updateIsBinarySupported(){var s;if(!((s=Xi.get("instance"))===null||s===void 0)&&s.devMode)return void(this._isBinarySupported=!1);const n=Es();if((gi||ut&&n==="windows"||Vs)&&(this._isBinarySupported=!1),To){const{uniRuntimeVersion:g=""}=io.getSystemInfoSync();(function(u){const E=u.split(".").map(Number),[m=0,D=0,M=0]=E;return m>2||!(m<2)&&(D>2||!(D<2)&&M>=6)})(g)||(this._isBinarySupported=!1)}}_isCompressedData(s){const n=new Uint8Array(s);return n[0]===67&&n[1]===79&&n[2]===77&&n[3]===80}};const ye={init:function(s){Xi.set("instance",s),De.init()},destroy:function(){De.dispose(),Xi.clear(),fn.dispose()},notificationCenter:gn,channel:De,store:Xi,ssoLog:xt,utils:yg,common:vA,constants:Dt},vg=s=>typeof s=="function";function rg(s,n,g){const u=g||[];if(!s||!n)return!1;const E=Object.keys(s).filter(D=>!u.includes(D)),m=Object.keys(n).filter(D=>!u.includes(D));return E.length===m.length&&E.every(D=>!!n.hasOwnProperty(D)&&(typeof s[D]=="object"&&s[D]!==null?rg(s[D],n[D],g):s[D]===n[D]))}var Rg;(function(s){s.SDK_READY="sdkStateReady",s.SDK_NOT_READY="sdkStateNotReady",s.SDK_DESTROY="sdkDestroy",s.MESSAGE_RECEIVED="onMessageReceived",s.ROOM_CUSTOM_DATA_RECEIVED="onRoomCustomDataReceived",s.MESSAGE_MODIFIED="onMessageModified",s.MESSAGE_REVOKED="onMessageRevoked",s.MESSAGE_READ_BY_PEER="onMessageReadByPeer",s.MESSAGE_READ_RECEIPT_RECEIVED="onMessageReadReceiptReceived",s.MESSAGE_EXTENSIONS_UPDATED="onMessageExtensionsUpdated",s.MESSAGE_EXTENSIONS_DELETED="onMessageExtensionsDeleted",s.MESSAGE_REACTIONS_UPDATED="onMessageReactionsUpdated",s.CONVERSATION_LIST_UPDATED="onConversationListUpdated",s.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED="onTotalUnreadMessageCountUpdated",s.CONVERSATION_GROUP_LIST_UPDATED="onConversationGroupListUpdated",s.CONVERSATION_IN_GROUP_UPDATED="onConversationInGroupUpdated",s.GROUP_LIST_UPDATED="onGroupListUpdated",s.GROUP_ATTRIBUTES_UPDATED="groupAttributesUpdated",s.GROUP_COUNTER_UPDATED="onGroupCounterUpdated",s.TOPIC_CREATED="onTopicCreated",s.TOPIC_DELETED="onTopicDeleted",s.TOPIC_UPDATED="onTopicUpdated",s.PROFILE_UPDATED="onProfileUpdated",s.USER_STATUS_UPDATED="onUserStatusUpdated",s.BLACKLIST_UPDATED="blacklistUpdated",s.FRIEND_LIST_UPDATED="onFriendListUpdated",s.FRIEND_GROUP_LIST_UPDATED="onFriendGroupListUpdated",s.FRIEND_APPLICATION_LIST_UPDATED="onFriendApplicationListUpdated",s.MY_FOLLOWERS_LIST_UPDATED="onMyFollowersListUpdated",s.MY_FOLLOWING_LIST_UPDATED="onMyFollowingListUpdated",s.MUTUAL_FOLLOWERS_LIST_UPDATED="onMutualFollowersListUpdated",s.KICKED_OUT="kickedOut",s.ERROR="error",s.NET_STATE_CHANGE="netStateChange",s.ALL_RECEIVE_MESSAGE_OPT_UPDATED="onAllReceiveMessageOptUpdated",s.SERVER_CONFIG_UPDATED="onServerConfigUpdated",s.PINNED_GROUP_MESSAGE_UPDATED="onPinnedGroupMessageUpdated",s.WEB_PUSH_MESSAGE_RECEIVED="onWebPushMessageReceived",s.GROUP_ONLINE_MEMBER_COUNT_CHANGED="onGroupOnlineMemberCountChanged",s.RICH_STATUS_CHANGED="onRichStatusChanged"})(Rg||(Rg={}));var Dn,Dr=Rg;(function(s){s.LOGOUT="logout",s.DESTROY="destroy",s.CLOUD_CONFIG_UPDATE="cloud_config_update",s.PROFILE_UPDATE="profile_updated",s.ERROR="error",s.RECONNECTED="reconnected",s.FORCE_OFFLINE="im_open_status.stat_forceoffline",s.COMMERCIAL_CONFIG_PUSH="im_sdk_config_mgr.push_imsdk_purchase_bitsv2",s.OVERLOAD_PUSH="OverLoadPush.notify2",s.NEW_MESSAGE="new_message",s.MESSAGE_PUSH="im_open_push.msg_push",s.MESSAGE_DELETED="message_deleted",s.MESSAGE_REVOKED="message_revoked",s.MESSAGE_MODIFIED="message_modified",s.SOCKET_DISCONNECTED="socket_disconnected",s.CONVERSATION_UPDATED="conversation_updated",s.TOPIC_MESSAGE_DELETED="topic_message_deleted",s.TOPIC_MESSAGE_REVOKED="topic_message_revoked",s.TOPIC_MESSAGE_MODIFIED="topic_message_modified",s.TOPIC_NEW_MESSAGE="topic_new_message",s.QUALITY_STAT="quality_stat",s.SYNC_CONVERSATION_LIST="sync_conversation_list",s.HISTORY_MESSAGE_FETCHED="history_message_fetched"})(Dn||(Dn={}));var ui,so=Dn;(function(s){s.NEW_INVITATION_RECEIVED="newInvitationReceived",s.INVITEE_ACCEPTED="ts_invitee_accepted",s.INVITEE_REJECTED="ts_invitee_rejected",s.INVITATION_CANCELLED="ts_invitation_cancelled",s.INVITATION_TIMEOUT="ts_invitation_timeout",s.INVITATION_MODIFIED="ts_invitation_modified"})(ui||(ui={}));var qc=ui;const zg=Object.assign({},{KICKED_OUT_MULT_ACCOUNT:"multipleAccount",KICKED_OUT_MULT_DEVICE:"multipleDevice",KICKED_OUT_USERSIG_EXPIRED:"userSigExpired",KICKED_OUT_REST_API:"REST_API_Kick"}),wg={MSG_TEXT:"TIMTextElem",MSG_IMAGE:"TIMImageElem",MSG_AUDIO:"TIMSoundElem",MSG_FILE:"TIMFileElem",MSG_FACE:"TIMFaceElem",MSG_VIDEO:"TIMVideoFileElem",MSG_LOCATION:"TIMLocationElem",MSG_GRP_TIP:"TIMGroupTipElem",MSG_GRP_SYS_NOTICE:"TIMGroupSystemNoticeElem",MSG_CUSTOM:"TIMCustomElem",MSG_MERGER:"TIMRelayElem",MSG_STREAM:"TIMStreamElem"};var Yr;(function(s){s.UNSENT="unSend",s.SUCCESS="success",s.FAIL="fail"})(Yr||(Yr={}));const yc={modify:so.MESSAGE_MODIFIED,delete:so.MESSAGE_DELETED,revoke:so.MESSAGE_REVOKED};var Kc;(function(s){s[s.FORWARD=0]="FORWARD",s[s.BACKWARD=1]="BACKWARD"})(Kc||(Kc={}));const ag=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},wg),{MSG_PRIORITY_HIGH:"High",MSG_PRIORITY_NORMAL:"Normal",MSG_PRIORITY_LOW:"Low",MSG_PRIORITY_LOWEST:"Lowest"}),{RECEIVE_WITH_OFFLINE_PUSH_EXCEPT_AT:"AcceptNotNotifyExceptAt",NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT:"AcceptNotNotifyExceptAt",NOT_RECEIVE_MSG_EXCEPT_AT:"NotReceiveMsgExceptAt",MSG_AT_ALL:"__kImSDK_MesssageAtALL__"}),{MSG_REMIND_ACPT_AND_NOTE:"AcceptAndNotify",MSG_REMIND_ACPT_NOT_NOTE:"AcceptNotNotify",MSG_REMIND_DISCARD:"Discard"}),{MessageStatus:Yr,Direction:Kc}),Ru={[yc.modify]:so.TOPIC_MESSAGE_MODIFIED,[yc.delete]:so.TOPIC_MESSAGE_DELETED,[yc.revoke]:so.TOPIC_MESSAGE_REVOKED},SE={GENDER_UNKNOWN:"Gender_Type_Unknown",GENDER_FEMALE:"Gender_Type_Female",GENDER_MALE:"Gender_Type_Male",USER_STATUS_UNKNOWN:0,USER_STATUS_ONLINE:1,USER_STATUS_OFFLINE:2,USER_STATUS_UNLOGINED:3,USER_NOT_FOUND:"@TLS#NOT_FOUND"},_g=Object.assign({},SE),ka={CONV_C2C:"C2C",CONV_GROUP:"GROUP",CONV_TOPIC:"TOPIC",CONV_SYSTEM:"@TIM#SYSTEM"},Dc=Object.assign(Object.assign(Object.assign(Object.assign({},ka),{CONV_AT_ME:1,CONV_AT_ALL:2,CONV_AT_ALL_AT_ME:3}),{CONV_MARK_TYPE_STAR:1,CONV_MARK_TYPE_UNREAD:2,CONV_MARK_TYPE_FOLD:4,CONV_MARK_TYPE_HIDE:8}),{READ_ALL_C2C_MSG:"readAllC2CMessage",READ_ALL_GROUP_MSG:"readAllGroupMessage",READ_ALL_MSG:"readAllMessage"}),ME=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},{SNS_TYPE_NO_RELATION:"CheckResult_Type_NoRelation",SNS_TYPE_A_WITH_B:"CheckResult_Type_AWithB",SNS_TYPE_B_WITH_A:"CheckResult_Type_BWithA",SNS_TYPE_BOTH_WAY:"CheckResult_Type_BothWay"}),{ALLOW_TYPE_ALLOW_ANY:"AllowType_Type_AllowAny",ALLOW_TYPE_NEED_CONFIRM:"AllowType_Type_NeedConfirm",ALLOW_TYPE_DENY_ANY:"AllowType_Type_DenyAny"}),{SNS_ADD_TYPE_SINGLE:"Add_Type_Single",SNS_ADD_TYPE_BOTH:"Add_Type_Both"}),{SNS_DELETE_TYPE_SINGLE:"Delete_Type_Single",SNS_DELETE_TYPE_BOTH:"Delete_Type_Both"}),{SNS_APPLICATION_TYPE_BOTH:"Pendency_Type_Both",SNS_APPLICATION_SENT_TO_ME:"Pendency_Type_ComeIn",SNS_APPLICATION_SENT_BY_ME:"Pendency_Type_SendOut",SNS_APPLICATION_AGREE:"Response_Action_Agree",SNS_APPLICATION_AGREE_AND_ADD:"Response_Action_AgreeAndAdd"}),{SNS_CHECK_TYPE_BOTH:"CheckResult_Type_Both",SNS_CHECK_TYPE_SINGLE:"CheckResult_Type_Single"}),{FORBID_TYPE_NONE:"AdminForbid_Type_None",FORBID_TYPE_SEND_OUT:"AdminForbid_Type_SendOut"}),La={GRP_WORK:"Private",GRP_PUBLIC:"Public",GRP_MEETING:"ChatRoom",GRP_AVCHATROOM:"AVChatRoom",GRP_COMMUNITY:"Community",GRP_ROOM:"Room",GRP_LIVE:"Live"},sa={COMMUNITY:"@TGS#_",TOPIC:"@TOPIC#_"},Tg={JOINED:1,QUITTED:2,KICKED:3,ADMIN_SET:4,ADMIN_CANCELED:5,GROUP_PROFILE_UPDATED:6,GROUP_MEMBER_PROFILE_UPDATED:7,TOPIC_PROFILE_UPDATED:8},gI=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},La),{GRP_MBR_ROLE_OWNER:"Owner",GRP_MBR_ROLE_ADMIN:"Admin",GRP_MBR_ROLE_MEMBER:"Member",GRP_MBR_ROLE_CUSTOM:"Custom"}),{GRP_TIP_MBR_JOIN:1,GRP_TIP_MBR_QUIT:2,GRP_TIP_MBR_KICKED_OUT:3,GRP_TIP_MBR_SET_ADMIN:4,GRP_TIP_MBR_CANCELED_ADMIN:5,GRP_TIP_GRP_PROFILE_UPDATED:6,GRP_TIP_MBR_PROFILE_UPDATED:7,GRP_TIP_BAN_AVCHATROOM_MEMBER:10,GRP_TIP_UNBAN_AVCHATROOM_MEMBER:11}),{JOIN_OPTIONS_FREE_ACCESS:"FreeAccess",JOIN_OPTIONS_NEED_PERMISSION:"NeedPermission",JOIN_OPTIONS_DISABLE_APPLY:"DisableApply",JOIN_STATUS_SUCCESS:"JoinedSuccess",JOIN_STATUS_ALREADY_IN_GROUP:"AlreadyInGroup",JOIN_STATUS_WAIT_APPROVAL:"WaitAdminApproval"}),{INVITE_OPTIONS_DISABLE_INVITE:"DisableInvite",INVITE_OPTIONS_NEED_PERMISSION:"NeedPermission",INVITE_OPTIONS_FREE_ACCESS:"FreeAccess"}),{GRP_PROFILE_OWNER_ID:"ownerID",GRP_PROFILE_CREATE_TIME:"createTime",GRP_PROFILE_LAST_INFO_TIME:"lastInfoTime",GRP_PROFILE_MEMBER_NUM:"memberNum",GRP_PROFILE_MAX_MEMBER_NUM:"maxMemberNum",GRP_PROFILE_JOIN_OPTION:"joinOption",GRP_PROFILE_INVITE_OPTION:"inviteOption",GRP_PROFILE_INTRODUCTION:"introduction",GRP_PROFILE_NOTIFICATION:"notification",GRP_PROFILE_MUTE_ALL_MBRS:"muteAllMembers"}),{GROUP_ID_PREFIX:sa,GROUP_TIPS_OPERATION_TYPE:Tg}),hs={IOS_OFFLINE_PUSH_NO_SOUND:"push.no_sound",IOS_OFFLINE_PUSH_DEFAULT_SOUND:"default"},Lo=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},zg),ag),_g),Dc),ME),gI),hs),{NET_STATE_CONNECTING:"connecting",NET_STATE_DISCONNECTED:"disconnected",NET_STATE_CONNECTED:"connected"}),da={NO_SDKAPPID:2e3,NO_TINYID:2022,NO_A2KEY:2023,USER_NOT_LOGGED_IN:2024,REPEAT_LOGIN:2025,MSG_SEND_FAIL:2100,MSG_SEND_FAIL_NOT_IN_AV:2101,MSG_SEND_GRP_WITH_TOPIC_FAIL:2115,MSG_INSTANCE_REQUIRED:2105,MSG_INVALID_CONV_TYPE:2106,MSG_REVOKE_FAIL:2110,MSG_DELETE_FAIL:2111,MSG_UNREAD_ALL_FAIL:2112,READ_RECEIPT_MSG_LIST_EMPTY:2114,CANNOT_DELETE_GRP_SYSTEM_NOTICE:2116,NOT_MY_FRIEND:2700,NETWORK_ERROR:2800,NETWORK_TIMEOUT:2801,NO_NETWORK:2805,UNCAUGHT_ERROR:2903,INVALID_OPERATION:2905,SDK_IS_NOT_READY:2999,LOGGING_IN:3e3,LOGIN_FAILED:3001,KICKED_OUT_MULT_DEVICE:3002,KICKED_OUT_MULT_ACCOUNT:3003,KICKED_OUT_USERSIG_EXPIRED:3004,LOGGED_OUT:3005,KICKED_OUT_REST_API:3006,NO_USE:3122,OPTIONS_IS_EMPTY:3153,MSG_A2KEY_EXPIRED:20002,ACCOUNT_A2KEY_EXPIRED:70001,HELLO_ANSWER_KICKED_OUT:1002,OPEN_SERVICE_OVERLOAD_ERROR:60022},nr={BASIC:"1",STANDARD:"2",PROFESSIONAL:"3",NODE:"4"},Yt={SYNC_SERVER_INFO_AFTER_RE_ONLINE:"sync-server-info-after-re-online",SYNC_SERVER_INFO_AFTER_LOGIN:"sync-server-info-after-login",RECEIVE_C2C_NEW_MESSAGE:"receive-c2c-new-message",RECEIVE_GROUP_NEW_MESSAGE:"receive-group-new-message",RECEIVE_GROUP_TIPS_NOTIFICATION:"receive-group-tips-notification"},qt={USER_STATUS_UPDATE:"user-status-update",CONVERSATION_RECOVER:"conversation-recover",HISTORY_MESSAGE_RECOVER:"history-message-recover",BLACKLIST_RECOVER:"blacklist-recover",FRIEND_RECOVER:"friend-recover",GROUP_ATTRIBUTE_CACHE_CLEAR:"group-attribute-cache-clear",UNREAD_MESSAGE_RECOVER:"unread-message-recover",HANDLE_NEW_MESSAGE:"handle-new-message",HANDLE_CONVERSATION_PROFILE_UPDATED:"handle-conversation-profile-updated",COMMERCIAL_CONFIG_UPDATE:"commercial-config-update",UNREAD_MESSAGE_SYNC:"unread-message-sync",FRIEND_AND_BLACKLIST_SYNC:"friend-and-blacklist-sync",SIGNALING_MESSAGE_RECOVER:"signaling-message-recover",GROUP_LIST_SYNC:"group-list-sync",CONVERSATION_LIST_SYNC:"conversation-list-sync",USER_PROFILE_SYNC:"user-profile-sync",CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED:"conversation-update-after-unread-sync-finished",CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED:"conversation-update-after-group-list-sync-finished",HANDLE_C2C_NEW_MESSAGE:"handle-c2c-new-message",HANDLE_GROUP_NEW_MESSAGE:"handle-group-new-message",CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE:"create-or-update-conversation-by-receive-new-message",HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD:"handle-group-tips-from-sync-unread",HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD:"handle-c2c-revoked-message-from-sync-unread",GROUP_REVOKED_NOTICE_RECOVER:"group-revoked-notice-recover",CLOUD_CONFIG_SYNC:"cloud-config-sync",UPDATE_GROUP_NEXT_SEQUENCE:"update-group-next-sequence",EMIT_C2C_MESSAGE_EVENT:"emit-c2c-message-event",EMIT_GROUP_MESSAGE_EVENT:"emit-group-message-event",CONVERSATION_GROUP_LIST_SYNC:"conversation-group-list-sync",CONVERSATION_GROUP_UPDATE:"conversation-group-update",UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED:"update-topic-after-unread-sync-finished",UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE:"update-topic-by-received-new-message",TOPIC_REQUEST_INFO_RESET:"topic-request-info-reset",QUALITY_REPORT:"quality-report",GROUP_TIPS_RECOVER:"group-tips-recover",HANDLE_GROUP_TIPS_NOTIFICATION:"handle-group-tips-notification",C2C_HISTORY_MESSAGE_RECOVER:"c2c-history-message-recover",FRIEND_APPLICATION_LIST_RECOVER:"friend-application-list-recover",EMIT_GROUP_TIPS_EVENT:"emit-group-tips-event",STREAM_MESSAGE_RECOVER:"stream-message-recover"},Ng={[Yt.SYNC_SERVER_INFO_AFTER_RE_ONLINE]:[{stepId:qt.USER_STATUS_UPDATE},{stepId:qt.GROUP_ATTRIBUTE_CACHE_CLEAR},{stepId:qt.UNREAD_MESSAGE_SYNC,dependency:qt.C2C_HISTORY_MESSAGE_RECOVER},{stepId:qt.CONVERSATION_RECOVER},{stepId:qt.HISTORY_MESSAGE_RECOVER,dependency:qt.CONVERSATION_RECOVER},{stepId:qt.BLACKLIST_RECOVER},{stepId:qt.FRIEND_RECOVER},{stepId:qt.FRIEND_APPLICATION_LIST_RECOVER},{stepId:qt.GROUP_REVOKED_NOTICE_RECOVER,dependency:qt.HISTORY_MESSAGE_RECOVER},{stepId:qt.GROUP_TIPS_RECOVER,dependency:qt.HISTORY_MESSAGE_RECOVER},{stepId:qt.TOPIC_REQUEST_INFO_RESET},{stepId:qt.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,dependency:qt.UNREAD_MESSAGE_SYNC},{stepId:qt.HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD,dependency:qt.UNREAD_MESSAGE_SYNC},{stepId:qt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[qt.UNREAD_MESSAGE_SYNC,qt.CONVERSATION_RECOVER]},{stepId:qt.EMIT_C2C_MESSAGE_EVENT,dependency:[qt.UNREAD_MESSAGE_SYNC,qt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED],skipIfDependencyMissing:!1},{stepId:qt.C2C_HISTORY_MESSAGE_RECOVER,dependency:qt.CONVERSATION_RECOVER},{stepId:qt.STREAM_MESSAGE_RECOVER}],[Yt.SYNC_SERVER_INFO_AFTER_LOGIN]:[{stepId:qt.COMMERCIAL_CONFIG_UPDATE},{stepId:qt.CLOUD_CONFIG_SYNC},{stepId:qt.USER_PROFILE_SYNC},{stepId:qt.UNREAD_MESSAGE_SYNC},{stepId:qt.FRIEND_AND_BLACKLIST_SYNC},{stepId:qt.GROUP_LIST_SYNC},{stepId:qt.CONVERSATION_LIST_SYNC},{stepId:qt.SIGNALING_MESSAGE_RECOVER,dependency:qt.UNREAD_MESSAGE_SYNC},{stepId:qt.UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED,dependency:[qt.UNREAD_MESSAGE_SYNC]},{stepId:qt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[qt.UNREAD_MESSAGE_SYNC,qt.CONVERSATION_LIST_SYNC]},{stepId:qt.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,dependency:[qt.GROUP_LIST_SYNC,qt.CONVERSATION_LIST_SYNC]},{stepId:qt.CONVERSATION_GROUP_LIST_SYNC},{stepId:qt.CONVERSATION_GROUP_UPDATE,dependency:[qt.CONVERSATION_LIST_SYNC,qt.CONVERSATION_GROUP_LIST_SYNC]},{stepId:qt.QUALITY_REPORT}],[Yt.RECEIVE_C2C_NEW_MESSAGE]:[{stepId:qt.HANDLE_C2C_NEW_MESSAGE},{stepId:qt.UNREAD_MESSAGE_SYNC},{stepId:qt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:qt.HANDLE_C2C_NEW_MESSAGE},{stepId:qt.EMIT_C2C_MESSAGE_EVENT,dependency:[qt.HANDLE_C2C_NEW_MESSAGE,qt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1},{stepId:qt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[qt.UNREAD_MESSAGE_SYNC]}],[Yt.RECEIVE_GROUP_NEW_MESSAGE]:[{stepId:qt.HANDLE_GROUP_NEW_MESSAGE},{stepId:qt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:qt.HANDLE_GROUP_NEW_MESSAGE},{stepId:qt.UPDATE_GROUP_NEXT_SEQUENCE,dependency:qt.HANDLE_GROUP_NEW_MESSAGE},{stepId:qt.UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE,dependency:qt.HANDLE_GROUP_NEW_MESSAGE},{stepId:qt.EMIT_GROUP_MESSAGE_EVENT,dependency:[qt.HANDLE_GROUP_NEW_MESSAGE,qt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1}],[Yt.RECEIVE_GROUP_TIPS_NOTIFICATION]:[{stepId:qt.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:qt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:qt.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:qt.EMIT_GROUP_TIPS_EVENT,dependency:[qt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,qt.HANDLE_GROUP_TIPS_NOTIFICATION],skipIfDependencyMissing:!1}]},cI={MESSAGE_SEND_SUCCESS_RATE:"messageSendSuccessRate"},rr={TOTAL_COUNT:"sendMessageTotalCount",SUCCESS_COUNT:"sendMessageSuccessCount",FAILED_COUNT:"sendMessageFailedCount",SEND_COST:"sendMessageCost"},HI=["login","getMyProfile","getUserProfile","updateMyProfile","setSelfStatus","getUserStatus","subscribeUserStatus","unsubscribeUserStatus","modifyMessage","deleteGroupMember","dismissGroup","getGroupMemberList","getGroupOnlineMemberCount","joinGroup","markGroupMemberList","quitGroup","searchCloudMessages","searchCloudGroups","searchCloudGroupMembers","searchCloudUsers","getMyFollowingList","getMyFollowersList","getMutualFollowersList","followUser","unfollowUser","getUserFollowInfo","checkFollowType","getFriendProfile","addFriend","deleteFriend","updateFriend","checkFriend","setFriendApplicationRead","createFriendGroup","deleteFriendGroup","addToFriendGroup","removeFromFriendGroup","renameFriendGroup","changeGroupOwner","createGroup","dismissGroup","getGroupList","getGroupOnlineMemberCount","getGroupProfile","searchGroupByID","updateGroupProfile","handleGroupApplication","deleteGroupAttributes","getGroupAttributes","initGroupAttributes","setGroupAttributes","addGroupMember","deleteGroupMember","getGroupMemberList","getGroupMemberProfile","setGroupMemberMuteTime","setGroupMemberNameCard","setGroupMemberRole","deleteMessage","revokeMessage","setMessageExtensions","getMessageExtensions","deleteMessageExtensions","getMessageList","addMessageReaction","removeMessageReaction","clearHistoryMessage","sendMessageReadReceipt","getMessageReadReceiptList","getGroupMessageReadMemberList","createMergerMessage","invite","accept","cancel","reject","modifyInvitation","deleteConversation","pinConversation","setMessageRead","setAllMessageRead","getConversationList","getTotalUnreadMessageCount","renameConversationGroup","deleteConversationGroup","markConversation","setConversationCustomData","deleteConversationsFromGroup","addConversationsToGroup","createConversationGroup"];var za=Object.freeze({__proto__:null,ERROR_CODE:da,InnerEvent:so,NEED_LOG_API:HI,OuterConstant:Lo,OuterEvent:Dr,PUSH:hs,QUALITY_METRICS:cI,SDK_EDITION:nr,SDK_INFO:{VERSION:"1.7.3",APPID:537048168},SEND_MESSAGE_STAT:rr,SignalingEvent:qc,WEB_PUSH_ACCOUNT_TYPE:1,WORKFLOW_DEFINITIONS:Ng,WORKFLOW_NAME:Yt,WORKFLOW_STEP:qt}),na,un,Sn;(function(s){s[s.USER_INITIATED=0]="USER_INITIATED",s[s.KICKED_OUT=1]="KICKED_OUT"})(na||(na={})),function(s){s[s.multipleAccount=1]="multipleAccount",s[s.multipleDevice=2]="multipleDevice",s[s.restApi=3]="restApi"}(un||(un={})),function(s){s[s.multipleDevice=3002]="multipleDevice",s[s.multipleAccount=3003]="multipleAccount",s[s.usersigExpired=70001]="usersigExpired",s[s.restApi=20002]="restApi"}(Sn||(Sn={}));const wu={[un.multipleAccount]:"multipleAccount",[un.multipleDevice]:"multipleDevice",[un.restApi]:"REST_API_Kick",[Sn.multipleAccount]:"multipleAccount",[Sn.multipleDevice]:"multipleDevice",[Sn.restApi]:"REST_API_Kick",[Sn.usersigExpired]:"userSigExpired"},Gg="login_online_presence_task",{ERROR:Ua,DESTROY:jc,FORCE_OFFLINE:qI}=so,{KICKED_OUT_MULT_ACCOUNT:vE,KICKED_OUT_MULT_DEVICE:lI,KICKED_OUT_REST_API:_u,ACCOUNT_A2KEY_EXPIRED:Rl,MSG_A2KEY_EXPIRED:Sc}=da;class Tu{init(){const{notificationCenter:n}=ye;n.subscribeInnerEvent(qI,this._handleForceOfflineFromServerPush,this),n.subscribeInnerEvent(Ua,Sc,this._handleForceOfflineFromResponse,this,this._isChatLoginEvent),n.subscribeInnerEvent(Ua,Rl,this._handleForceOfflineFromResponse,this,this._isChatLoginEvent),n.subscribeInnerEvent(Ua,vE,this._handleForceOfflineFromResponse,this),n.subscribeInnerEvent(Ua,lI,this._handleForceOfflineFromResponse,this),n.subscribeInnerEvent(Ua,_u,this._handleForceOfflineFromResponse,this),n.subscribeInnerEvent(jc,this._dispose,this)}_handleForceOfflineFromServerPush(n){var g;if(((g=ye.store.get("login"))===null||g===void 0?void 0:g.isLoggedIn)===!0){const{EventArray:u=[]}=n?.body||{};this._extractKickedOutMessages(u).forEach(E=>{const{KickoutMsgNotify:{KickType:m,NewInstInfo:D,Instid:M}}=E;this._isCurrentInstanceKickedOut(M)&&this._processKickedOutReasonInfo({kickedOutReasonCode:m,newInstanceInfo:D})})}}_extractKickedOutMessages(n){return n.reduce((g,u)=>[...g,...u.C2cNotifyMsgArray||[]],[]).filter(g=>{var u;return this._isKickedOut((u=g?.KickoutMsgNotify)===null||u===void 0?void 0:u.KickType)})}_handleForceOfflineFromResponse(n){const{errorCode:g}=n;this._processKickedOutReasonInfo({kickedOutReasonCode:g})}_processKickedOutReasonInfo(n){return pA(this,void 0,void 0,function*(){const{kickedOutReasonCode:g}=n,{ssoLog:u,utils:{safeStringify:E}}=ye;try{this._logKickedOutEvent(n),this._shouldLogoutAfterKickedOut(g)?yield ye.login.loginAction.logout(na.KICKED_OUT):ye.login.loginAction.handleLogoutCompleted()}catch(m){u.debug("_processKickedOutReasonInfo",` fail ${E(m)}`)}finally{ye.notificationCenter.emitOuterEvent(Dr.KICKED_OUT,{data:{type:wu[g]},name:Dr.KICKED_OUT})}})}_logKickedOutEvent(n){const{kickedOutReasonCode:g,newInstanceInfo:u={}}=n,E=`type:${wu[g]} newInstanceInfo: ${JSON.stringify(u)}`;ye.ssoLog.warn("kickedOut",E)}_isKickedOut(n){return[un.multipleAccount,un.multipleDevice,un.restApi].includes(n)}_isChatLoginEvent(n){const{requestHead:g}=n||{};return g?.idtype!==1}_shouldLogoutAfterKickedOut(n){return![Sn.usersigExpired,un.restApi].includes(n)}_isCurrentInstanceKickedOut(n){const{isLoggedIn:g,statusInstanceId:u}=ye.store.get("login")||{};return g===!0&&n===u}_dispose(){const{notificationCenter:n}=ye;n.unSubscribeInnerEvent(qI,this._handleForceOfflineFromServerPush,this),n.unSubscribeInnerEvent(Ua,Rl,this._handleForceOfflineFromResponse,this),n.unSubscribeInnerEvent(Ua,Sc,this._handleForceOfflineFromResponse,this),n.unSubscribeInnerEvent(Ua,vE,this._handleForceOfflineFromResponse,this),n.unSubscribeInnerEvent(Ua,lI,this._handleForceOfflineFromResponse,this),n.unSubscribeInnerEvent(Ua,_u,this._handleForceOfflineFromResponse,this),n.unSubscribeInnerEvent(jc,this._dispose,this)}}function Nu(s){return pA(this,void 0,void 0,function*(){const n="im_open_status.wslogin",g=ye.common.generateProtocolData({servcmd:n,data:{State:"Online",is_web_uniapp:0,InstType:0,CustomInfo:s}}),u=`${g.head.seq}${n}`,E=yield ye.channel.sendPacket(g,{timeout:9e4,requestId:u});if(E){const{HelloInterval:m,InstId:D,TinyId:M,TimeStamp:T,CustomStatus:P,PurchaseBits:W,A2Key:iA,RichMsgAuthKey:EA,ErrorCode:RA,ErrorInfo:kA,ActionStatus:xA}=E;return{helloInterval:m,instanceID:D,tinyID:M,timeStamp:T,customStatus:P,purchaseBits:W,a2Key:iA,authKey:EA,errorCode:RA,errorInfo:kA,actionStatus:xA}}})}function wl(){const{store:s}=ye;return ua(s.get("instance").sdkAppId)!==gt.CHINA}function rs(s){var n;try{const g=Xi.getStorage("errorMessage");if(!s||!g)return"";const u=((n=JSON.parse(g))===null||n===void 0?void 0:n.errorMessage)||{},{code:E,replacement1:m="",replacement2:D=""}=s;if(!E)return"";const M=wl()?`${E}_en`:`${E}_cn`;let T=u[u[M]?M:E]||"";return T&&(m&&(T=T.replace("$replacement1",m)),D&&(T=T.replace("$replacement2",D))),T}catch(g){return console.warn("Error parsing stored error messages:",g),""}}class gs extends Error{constructor(n={}){n.code=n.code||n.errorCode;let{functionName:g="Unknown",code:u,message:E="",data:m="",moreMessage:D="",errorMessage:M=""}=n;M=(u?rs(n):"")||M||E;let T=u?`${g} failed. error: {"message": ${M}, "code": ${u}}`:`${g} failed. error: {"message": ${M}}`;T=`${T} ${D}`,super(),this.code=u,this.errorCode=u,this.errorMessage=M,this.message=T,this.data=m}}function ud(s,n){var g;if(s&&((g=ye.store.get("login"))===null||g===void 0?void 0:g.isLoggedIn)!==!0)throw new gs({code:da.USER_NOT_LOGGED_IN,functionName:n})}function II(s,n,g){if(Array.isArray(s))for(let u=0;u{return P===(W=u,Object.prototype.toString.call(W).match(/^\[object (.*)\]$/)[1].toLowerCase());var W})){for(let W=0;W{const{interceptor:E,context:m}=u;E.apply(m,[g])})}(s)}function Mc(s,n){RE.push({interceptor:s,context:n})}function Wc(s){const{params:n,auth:g}=s;n&&typeof n=="object"&&Object.assign(_l,n),g&&typeof g=="object"&&Object.assign(Ed,g)}function tn(s){return ye.store.get("commercialConfig").get(s)}class ws{constructor(){this._handlers=new Map,this._activeWorkflows=new Map,this._stepStartTimes=new Map,this._logHandlers={start:(n,g)=>{const u=Date.now();g?(this._stepStartTimes.set(`${n}-${g}`,u),ye.ssoLog.debug("_executeWorkflowStep",`[Workflow ${n}] Step ${g} started at ${new Date(u).toISOString()}`)):(this._workflowStartTimes.set(n,u),ye.ssoLog.debug("_executeWorkflowStep",`[Workflow ${n}] started at ${new Date(u).toISOString()}`))},success:(n,g)=>{const u=Date.now();if(g){const E=this._stepStartTimes.get(`${n}-${g}`),m=E?u-E:0;this._stepStartTimes.delete(`${n}-${g}`),ye.ssoLog.debug("_executeWorkflowStep",`[Workflow ${n}] Step ${g} completed successfully at ${new Date(u).toISOString()} (${m}ms)`)}else{const E=this._workflowStartTimes.get(n),m=E?u-E:0;this._workflowStartTimes.delete(n),ye.ssoLog.debug("_executeWorkflowStep",`[Workflow ${n}] completed successfully at ${new Date(u).toISOString()} (${m}ms)`)}},error:(n,g,u)=>{const{ssoLog:E,utils:{safeStringify:m}}=ye,D=Date.now();if(g){const M=this._stepStartTimes.get(`${n}-${g}`),T=M?D-M:0;this._stepStartTimes.delete(`${n}-${g}`),E.error("_executeWorkflowStep",`[Workflow ${n}] Step ${g} failed at ${new Date(D).toISOString()} (${T}ms) ${m(u)}`,{error:u})}else{const M=this._workflowStartTimes.get(n),T=M?D-M:0;this._workflowStartTimes.delete(n),E.error("_executeWorkflowStep",`[Workflow ${n}] failed at ${new Date(D).toISOString()} (${T}ms) ${m(u)}`,{error:u})}}}}static getInstance(){return ws._instance||(ws._instance=new ws),ws._instance}static setInstance(n){ws._instance=n}init(){this._initializeWorkflows()}registerWorkflowStep(n,g,u,E){if(!this._handlers.has(n))return void ye.ssoLog.debug("registerWorkflowStep",`Workflow '${n}' not defined in core`);if(!Ng[n].find(D=>D.stepId===g))return void ye.ssoLog.debug("registerWorkflowStep",`Step '${g}' not defined in workflow '${n}'`);const m=this._handlers.get(n);m.has(g)||m.set(g,E?u.bind(E):u)}executeWorkflow(n,g){return pA(this,void 0,void 0,function*(){if(!this._validateWorkflow(n))return;ye.ssoLog.debug("executeWorkflow",`[Workflow ${n}] Started execution at ${new Date().toISOString()}`);const u=Ng[n],E={},m={cancelled:!1};this._activeWorkflows.set(n,{cancelToken:m});try{const D=new Map;u.forEach(T=>{D.set(T.stepId,T)});const M={workflowName:n,pendingSteps:new Set(u.map(T=>T.stepId)),completedSteps:new Set,runningSteps:new Set,stepMap:D,stepResults:E,data:g,cancelToken:m};yield new Promise((T,P)=>{const W=()=>{if(m.cancelled)return void T();this._getExecutableSteps({pendingSteps:M.pendingSteps,completedSteps:M.completedSteps,stepMap:M.stepMap,workflowName:n}).filter(iA=>!M.runningSteps.has(iA)).forEach(iA=>{M.completedSteps.has(iA)||M.runningSteps.has(iA)||this._executeWorkflowStep(iA,M,{onComplete:()=>{if(M.pendingSteps.size===0)return void T();this._getExecutableSteps({pendingSteps:M.pendingSteps,completedSteps:M.completedSteps,stepMap:M.stepMap,workflowName:n}).filter(EA=>!M.runningSteps.has(EA)).length===0&&M.runningSteps.size===0&&(ye.ssoLog.debug("executeWorkflow",`Workflow ${n} completed with some steps skipped due to dependency failures`),T())},onError:P,onStepComplete:W})})};W()}),ye.ssoLog.debug("executeWorkflow",`[Workflow ${n}] Completed execution at ${new Date().toISOString()}`)}catch(D){ye.ssoLog.error("executeWorkflow",`[Workflow ${n}] Failed execution at ${new Date().toISOString()}`,{error:D})}finally{this._activeWorkflows.delete(n)}})}_executeWorkflowStep(n,g,u){return pA(this,void 0,void 0,function*(){const{workflowName:E,runningSteps:m,stepMap:D,stepResults:M,data:T}=g;m.add(n),this._logWorkflowExecution(E,n,"start");try{const P=D.get(n);let W=null;P?.dependency&&(l(P.dependency)?W=M[P.dependency]:Array.isArray(P.dependency)&&(W={},P.dependency.forEach(EA=>{W[EA]=M[EA]})));const iA=this._handlers.get(E).get(n);if(iA){const EA=yield Promise.resolve(iA({data:T,result:W}));M[n]=EA,this._logWorkflowExecution(E,n,"success")}g.completedSteps.add(n)}catch(P){const W=`[Workflow].${E}.${n}`,{errorCode:iA,errorInfo:EA=`${W} failed`}=P||{},RA=new gs({functionName:W,code:iA,message:EA});ye.ssoLog.error(W,EA,{error:RA}),this._logWorkflowExecution(E,n,"error",P),u.onError(P)}finally{m.delete(n),g.pendingSteps.delete(n),u.onStepComplete(),u.onComplete()}})}reset(){this._cancelAllWorkflows()}destroy(){this.reset(),this._handlers.clear()}_initializeWorkflows(){Object.keys(Ng).forEach(n=>{this._handlers.has(n)||this._handlers.set(n,new Map)})}_cancelWorkFlow(n){const g=this._activeWorkflows.get(n);if(!g)return;const{cancelToken:u}=g;u.cancelled=!0,this._activeWorkflows.delete(n)}_cancelAllWorkflows(){Object.keys(Ng).forEach(n=>{this._cancelWorkFlow(n)})}_validateWorkflow(n){return Ng[n]?!!this._handlers.get(n):!1}_getExecutableSteps(n){const{pendingSteps:g,completedSteps:u,stepMap:E,workflowName:m}=n;return Array.from(g).filter(D=>{const M=E.get(D)||{},{dependency:T,skipIfDependencyMissing:P=!0}=M;if(!T)return!0;if(l(T))return this._isStepRegistered({workflowName:m,stepId:T})?u.has(T):!P;if(h(T)){if(T.filter(W=>!this._isStepRegistered({workflowName:m,stepId:W})).length>0&&P)return!1;for(const W of T)if(!u.has(W))return!1;return!0}return!1})}_isStepRegistered(n){var g;const{workflowName:u,stepId:E}=n;return(g=this._handlers.get(u))===null||g===void 0?void 0:g.has(E)}_logWorkflowExecution(n,g,u,E){this._logHandlers[u](n,g)}}const Ca=new Map,Xr=({type:s,groupID:n})=>s===Lo.GRP_COMMUNITY||`${n}`.startsWith(sa.COMMUNITY)&&!`${n}`.includes(sa.TOPIC),zc=(s="")=>{const n=s.startsWith("GROUP")?s.replace("GROUP",""):s;return n.startsWith(sa.COMMUNITY)&&`${n}`.includes(sa.TOPIC)},dd="openim",Zg="million_group_open_http_svc";function gg(s){return pA(this,void 0,void 0,function*(){const{servcmd:n,data:g}=function(m){const{data:D}=m;return wE(D)||Xg(D)}(s)?function(m){let{servcmd:D,data:M}=m;return Xg(M)?function(T){const{servcmd:P,data:W}=T;let{GroupId:iA=""}=W;const EA=iA;return[iA]=EA.split(sa.TOPIC),{servcmd:qn(P),data:Object.assign(Object.assign({},W),{GroupId:iA,TopicId:EA})}}(m):(wE(M)&&(D=qn(D)),{servcmd:D,data:M})}(s):s,u=ye.common.generateProtocolData({servcmd:n,data:g}),E=`${u.head.seq}${n}`;return ye.channel.sendPacket(u,{requestId:E,timeout:s.timeout})})}function wE(s){const{Type:n,GroupId:g,GroupIdList:u=[]}=s,E=g||u[0]||"";return Xr({type:n,groupID:E})}function Xg(s){const{GroupId:n=""}=s;return zc(n)}function qn(s){if(s.includes(dd))return s;const n=s.split(".")[1];return`${Zg}.${n}`}function Ar(){var s;return(s=ye.store.get("login"))===null||s===void 0?void 0:s.userId}const Fa=s=>h(s)||f(s),Cd=(s,n,g,u)=>{if(!Fa(s)||!Fa(n))return 0;let E=0;const m=Object.keys(n);let D;for(let M=0,T=m.length;M{if(r(n))return"";if(s===Lo.MSG_TEXT)return n.text||"";const g=KI[s];return g?Gu(g):""},Xc=[{cmd:"ws_get_user_status",interval:5,count:20},{cmd:"ws_status_subscribe",interval:5,count:20},{cmd:"ws_status_unsubscribe",interval:5,count:20},{cmd:"get_group_self_member_info",interval:5,count:20},{cmd:"modify_group_base_info",interval:1,count:8},{cmd:"get_pendency",interval:1,count:15},{cmd:"set_group_attr",interval:5,count:10},{cmd:"modify_group_attr",interval:5,count:10},{cmd:"delete_group_attr",interval:5,count:10},{cmd:"clear_group_attr",interval:5,count:10},{cmd:"get_group_attr",interval:5,count:20},{cmd:"update_group_counter",interval:5,count:20},{cmd:"get_group_counter",interval:5,count:20},{cmd:"get_topic",interval:1,count:10},{cmd:"read_all_unread_msg",interval:1,count:1},{cmd:"query",interval:5,count:20}],jI="im_sdk_config_mgr.fetch_config",EI="im_sdk_config_mgr.push_configv2",$c="cloud-config",Al=2996,va=new class{init(s){this.core=s}};function bg(s){return pA(this,void 0,void 0,function*(){const{sdkAppId:n}=va.core.store.get("instance")||{},g=va.core.helper.generateProtocolData({servcmd:jI,data:{uint32_sdkappid:n,uint64_version:s}}),u=`${g.head.seq}${jI}`;return va.core.channel.sendPacket(g,{requestId:u})})}var ys=new class{constructor(){this._core=null,this._expirationTime=0,this._version=0,this._isFetching=!1,this._cmdFrequencyLimitMap=new Map,this._methodCallFrequencyMap=new Map}install(s){this._core=s;const{notificationCenter:n,InnerEvent:g,helper:u,constants:{WORKFLOW_NAME:E,WORKFLOW_STEP:m},channel:D}=s;n.subscribeInnerEvent(EI,this._handlePushedConfig,this),u.registerWorkflowStep(E.SYNC_SERVER_INFO_AFTER_LOGIN,m.CLOUD_CONFIG_SYNC,this._handleLoginSuccess,this),n.subscribeInnerEvent(g.LOGOUT,this._reset,this),n.subscribeInnerEvent(g.DESTROY,this._dispose,this),u.registerExperimentalAPI("getServerConfig",this),this._updateCmdFreqLimitMap(Xc),D.registerBeforeSendInterceptor(this.checkMethodCallOverLimit,this)}getServerConfig(s){return pA(this,void 0,void 0,function*(){var n;const g={code:0,data:""};return s&&(g.data=((n=this._core.store.get("cloudConfig"))===null||n===void 0?void 0:n[s])||""),g})}checkMethodCallOverLimit(s){if(!this._cmdFrequencyLimitMap.has(s))return;if(!this._methodCallFrequencyMap.has(s))return void this._methodCallFrequencyMap.set(s,{startTime:Date.now(),methodCallCounter:1});const{count:n,interval:g}=this._cmdFrequencyLimitMap.get(s);let{startTime:u,methodCallCounter:E}=this._methodCallFrequencyMap.get(s);if(Date.now()-u>1e3*g)this._methodCallFrequencyMap.set(s,{startTime:Date.now(),methodCallCounter:1});else if(E+=1,this._methodCallFrequencyMap.set(s,{startTime:u,methodCallCounter:E}),E>n)throw new this._core.helper.ChatError({code:Al,replacement1:s})}_handlePushedConfig(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g}}=this._core;n.info("_handlePushedConfig",g(s)),yield this._updateCloudConfig(s)})}_handleLoginSuccess(){return pA(this,void 0,void 0,function*(){const{ssoLog:s,utils:{safeStringify:n}}=this._core;try{if(this._canFetch()){const g=yield bg(this._version);s.info("_fetchCloudConfigIfLogin",n(g)),yield this._updateCloudConfig(g)}this._core.helper.taskScheduler.addTask({id:$c,intervalMs:1e3,callback:this._fetchCloudConfigIfReady,context:this})}catch(g){s.debug("_fetchCloudConfigIfLogin",n(g))}})}_fetchCloudConfigIfReady(){return pA(this,void 0,void 0,function*(){const{ssoLog:s,utils:{safeStringify:n}}=this._core;if(this._canFetch())try{const g=yield bg(this._version);s.info("_fetchCloudConfigIfReady",n(g)),yield this._updateCloudConfig(g)}catch(g){s.error("_fetchCloudConfigIfReady",n(g))}})}_updateCloudConfig(s){return pA(this,void 0,void 0,function*(){const n=this._parseCloudConfig(s);n&&(this._core.store.set("cloudConfig",n),yield this._parseCmdFreqLimit(),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.CLOUD_CONFIG_UPDATE,n),this._core.notificationCenter.emitOuterEvent(this._core.OuterEvent.SERVER_CONFIG_UPDATED,{name:this._core.OuterEvent.SERVER_CONFIG_UPDATED,data:{config:n}}))})}_canFetch(){const{isLoggedIn:s}=this._core.store.get("login")||{};return s&&!this._isFetching&&Date.now()>=this._expirationTime}_parseCloudConfig(s){const{int32_error_code:n,str_error_message:g,str_json_config:u,uint32_expired_time:E,uint32_sdkappid:m,uint64_version:D}=s;let M=null;if(n===0){if(this._version!==D)try{M=JSON.parse(u),this._version=D}catch{}this._expirationTime=Date.now()+1e3*E}else this._expirationTime=n===void 0?Date.now()+36e5:Date.now()+12e4;return M}_parseCmdFreqLimit(){return pA(this,void 0,void 0,function*(){var s;let n=(s=yield this.getServerConfig("cmd_frequency_limit"))===null||s===void 0?void 0:s.data;const{isEmpty:g}=this._core.utils;if(!g(n))try{n=JSON.parse(n),this._updateCmdFreqLimitMap(n)}catch(u){console.warn(u)}})}_updateCmdFreqLimitMap(s){s.forEach(n=>{this._cmdFrequencyLimitMap.set(n.cmd,{interval:n.interval,count:n.count})})}_reset(){this._core.helper.taskScheduler.removeTask($c),this._core.store.clear("cloudConfig"),this._updateCmdFreqLimitMap(Xc),this._methodCallFrequencyMap.clear(),this._expirationTime=0,this._version=0,this._isFetching=!1}_dispose(){const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(EI,this._handlePushedConfig,this),s.unSubscribeInnerEvent(n.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this),this._reset()}};class Kn{constructor(n=0,g=0){this.high=n,this.low=g}equal(n){return n!==null&&this.low===n.low&&this.high===n.high}toString(){const n=Number(this.high).toString(16);let g=Number(this.low).toString(16);if(g.length<8){let u=8-g.length;for(;u;)g=`0${g}`,u--}return n+g}}const vc={SEARCH_GRP_SNS:new Kn(0,Math.pow(2,1)).toString(),AV_HISTORY_MSG:new Kn(0,Math.pow(2,2)).toString(),GRP_COMMUNITY:new Kn(0,Math.pow(2,3)).toString(),MSG_TO_SPECIFIED_GRP_MBR:new Kn(0,Math.pow(2,4)).toString(),AV_MBR_LIST:new Kn(0,Math.pow(2,6)).toString(),USER_STATUS:new Kn(0,Math.pow(2,7)).toString(),CONV_MARK:new Kn(0,Math.pow(2,9)).toString(),CONV_GROUP:new Kn(0,Math.pow(2,10)).toString(),AV_BAN_MBR:new Kn(0,Math.pow(2,11)).toString(),MSG_EXT:new Kn(0,Math.pow(2,13)).toString(),GRP_COUNTER:new Kn(0,Math.pow(2,15)).toString(),PLUGIN_TRANSLATE:new Kn(Math.pow(2,6)).toString(),PLUGIN_VOICE_TO_TEXT:new Kn(Math.pow(2,7)).toString(),PLUGIN_CS:new Kn(Math.pow(2,8)).toString(),PLUGIN_PUSH:new Kn(Math.pow(2,9)).toString(),PLUGIN_BOT:new Kn(Math.pow(2,10)).toString(),MSG_REACTION:new Kn(Math.pow(2,16)).toString(),FOLLOW:new Kn(Math.pow(2,20)).toString()},WI="CommercialConfig",zI="commercial-config";var _E=new class{constructor(){this._core=null,this._expirationTime=0,this._isFetching=!1,this._featureMap=new Map,this._methodKeyMap=new Map,this._purchaseBits="0"}install(s){this._core=s;const{helper:n,notificationCenter:g,constants:{WORKFLOW_NAME:u,WORKFLOW_STEP:E,InnerEvent:m}}=s;g.subscribeInnerEvent(m.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),g.subscribeInnerEvent(m.LOGOUT,this._handleLogout,this),g.subscribeInnerEvent(m.DESTROY,this._dispose,this),n.registerWorkflowStep(u.SYNC_SERVER_INFO_AFTER_LOGIN,E.COMMERCIAL_CONFIG_UPDATE,this._syncCommercialConfig,this),s.helper.registerExperimentalAPI("isCommercialAbilityEnabled",this),s.helper.registerExperimentalAPI("queryCommercialAbility",this)}isCommercialAbilityEnabled(s){return pA(this,void 0,void 0,function*(){const n=parseInt(s,10).toString(2),{length:g}=n;let u,E=!0;for(let m=g-1,D=0;m>=0;m--,D++)if(n.charAt(m)==="1"&&(u=D<32?new Kn(0,2**D).toString():new Kn(2**(D-32),0).toString(),!this._featureMap.get(u))){E=!1;break}return this._core.ssoLog.debug("isFeatureEnabled",`${WI}.isFeatureEnabled decimalNumber:${s} key:${u} ret:${E}`),{code:0,data:{enabled:E}}})}queryCommercialAbility(){return this._purchaseBits}_fetchAndParseCommercialConfig(){return pA(this,void 0,void 0,function*(){var s;const{ssoLog:n,utils:{safeStringify:g},common:{buildAndSendPacket:u}}=this._core;try{this._isFetching=!0;const E=yield u({servcmd:"im_sdk_config_mgr.fetch_imsdk_purchase_bitsv2",data:{uint32_sdkappid:(s=this._core.store.get("instance"))===null||s===void 0?void 0:s.sdkAppId}});E&&(this._parseCommercialConfig(E),this._core.store.set("commercialConfig",this._methodKeyMap))}catch(E){n.error("_fetchAndParseCommercialConfig",g(E))}finally{this._isFetching=!1}})}_syncCommercialConfig(s){return pA(this,void 0,void 0,function*(){const{purchaseBits:n}=s?.data||{};n&&(this._parsePurchaseBits(n),this._core.store.set("commercialConfig",this._methodKeyMap)),this._canFetch()&&(yield this._fetchAndParseCommercialConfig()),this._core.helper.taskScheduler.addTask({id:zI,intervalMs:1e3,callback:this._fetchCommercialConfigIfReady,context:this})})}_canFetch(){var s;const n=(s=this._core.store.get("login"))===null||s===void 0?void 0:s.isLoggedIn,g=Date.now()>=this._expirationTime;return n&&!this._isFetching&&g}_handlePushedConfig(s){s?.body&&(this._parseCommercialConfig(s.body),this._core.store.set("commercialConfig",this._methodKeyMap))}_fetchCommercialConfigIfReady(){return pA(this,void 0,void 0,function*(){this._canFetch()&&(yield this._fetchAndParseCommercialConfig())})}_parseCommercialConfig(s){const{ssoLog:n}=this._core;if(typeof s!="object")return;const{int32_error_code:g,str_error_message:u,str_purchase_bits:E,uint32_expired_time:m}=s;g===0?(this._parsePurchaseBits(E),this._expirationTime=Date.now()+1e3*m):g===void 0?(n.warn("_parseCommercialConfig",`${WI}._parseCommercialConfig failed. Invalid message format:`,s),this._expirationTime=Date.now()+36e5):(n.warn("_parseCommercialConfig",`${WI}._parseCommercialConfig errorCode:${g} errorMessage:${u}`),this._expirationTime=Date.now()+12e4)}_isValidPurchaseBits(s){return s&&typeof s=="string"&&s.length>=1&&s.length<=64&&/[01]{1,64}/.test(s)}_parsePurchaseBits(s){const{ssoLog:n,utils:{safeStringify:g}}=this._core;if(this._isValidPurchaseBits(s)){this._purchaseBits=s,this._featureMap.clear(),this._methodKeyMap.clear();let u=null;for(let E=s.length-1,m=0;E>=0;E--,m++)if(u=m<32?new Kn(0,2**m).toString():new Kn(2**(m-32),0).toString(),s[E]==="1"){this._featureMap.set(u,!0);const D=this._getKeyByValue(vc,u);D&&this._methodKeyMap.set(D,!0)}else{this._featureMap.set(u,!1);const D=this._getKeyByValue(vc,u);D&&this._methodKeyMap.set(D,!1)}}else n.warn("_parsePurchaseBits",`${WI}.parsePurchaseBits invalid purchases:${g(s)}`)}_getKeyByValue(s,n){const g=Object.entries(s).find(([u,E])=>E===n);return g?g[0]:void 0}_handleLogout(){this._reset()}_dispose(){this._reset(),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._core.helper.taskScheduler.removeTask(zI),this._core.store.set("commercialConfig",{}),this._expirationTime=0,this._isFetching=!1,this._featureMap.clear(),this._purchaseBits="0"}},rh=new class{constructor(){this._core=null,this._serverOverloadInfoMap=new Map}install(s){this._core=s;const{notificationCenter:n,InnerEvent:g,channel:u}=this._core;n.subscribeInnerEvent(g.OVERLOAD_PUSH,this._handleOverLoadPush,this),n.subscribeInnerEvent(g.LOGOUT,this._reset,this),n.subscribeInnerEvent(g.DESTROY,this._dispose,this),u.registerBeforeSendInterceptor(this.checkServerOverload,this)}checkServerOverload(s){if(!this._serverOverloadInfoMap.has(s))return;const{overloadStartTimestamp:n,delaySeconds:g}=this._serverOverloadInfoMap.get(s);if(Date.now()-n<=1e3*g)throw new this._core.helper.ChatError({functionName:s,message:"service is busy, please try again later"});this._serverOverloadInfoMap.delete(s)}_handleOverLoadPush(s){const{OverLoadServCmd:n,DelaySecs:g}=s;this._serverOverloadInfoMap.set(n,{overloadStartTimestamp:Date.now(),delaySeconds:g})}_reset(){this._serverOverloadInfoMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(n.OVERLOAD_PUSH,this._handleOverLoadPush,this),s.unSubscribeInnerEvent(n.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this)}},IC=new class{constructor(){this.name="ConfigCenter"}install(s){va.init(s),ys.install(s),_E.install(s),rh.install(s)}},ah=new class{constructor(){this.name="ErrorMessage",this._core=null}install(s){return pA(this,void 0,void 0,function*(){if(this._core=s,this._canFetch()){const n=yield this._fetchErrorMessage();if(!n)return;const g=this._parseResponse(n);this._saveErrorMessage(g)}})}_canFetch(){const s=this._core.store.getStorage("errorMessage");return!s||this._isExpired(s)}_saveErrorMessage(s){this._core.store.setStorage("errorMessage",{errorMessage:s,errorMessageSavedTime:new Date().getTime()})}_fetchErrorMessage(){return pA(this,void 0,void 0,function*(){try{return yield this._core.helper.httpRequest({method:"GET",url:"https://web.sdk.qcloud.com/im/download/error-message/v3/0.0.6/tim-error-message.txt"})}catch(s){console.error(s)}})}_isExpired(s){if(!s)return!0;const{errorMessageSavedTime:n}=s;return n&&new Date().getTime()-n>=6048e5}_parseResponse(s){if(typeof s=="string"){const n=s.split(`;
+`),g={},u=new RegExp(/'/g);for(let E=0;E{var JA,ae,re;const _i=function(Ti,Lt){const{From_Account:Ni,From_AccountHeadurl:cs,From_AccountNick:Me,IsNeedReadReceipt:mt,MsgBody:UA,MsgClientTime:si,MsgRandom:_s,MsgSeq:Gi,MsgTimeStamp:Or,SendMsgControl:xi,SupportMessageExtension:gr,To_Account:Tt,TinyId:Nt,MsgCheckResult:AE,CloudCustomData:ln,IsPeerRead:Bo,MsgFlagBits:Il,MsgVersion:_C,EventArray:_r}=Ti;return{from:Ni,avatar:cs,nick:Me,needReadReceipt:mt===1,readReceiptSentByPeer:Bo,clientTime:si,messageFlagBits:Il,random:_s,sequence:Gi,time:Or,messageControlInfo:xi,isSupportExtension:gr,to:Tt,tinyID:Nt,checkResult:AE,cloudCustomData:ln,messageVersion:_C,eventArray:_r,elements:Lt.message.messageHelper.parseServerPushMessageElement(UA)}}(OA,xA);if(!((re=(ae=(JA=OA?.EventArray)===null||JA===void 0?void 0:JA[0])===null||ae===void 0?void 0:ae.hasOwnProperty)===null||re===void 0)&&re.call(ae,"C2cNotifyMsgArray"))SA.push(...function(Ti){var Lt;const Ni=[];return(Lt=Ti.EventArray)===null||Lt===void 0||Lt.forEach(cs=>{var Me,mt;const{C2cNotifyMsgArray:UA}=cs,si=(mt=(Me=UA?.[0])===null||Me===void 0?void 0:Me.WithdrawC2cMsgNotify)===null||mt===void 0?void 0:mt.C2cWithdrawInfoArray;Array.isArray(si)&&Ni.push(...si)}),Ni}(OA));else{const Ti=xA.message.messageFactory.createMessage(Object.assign(Object.assign({},_i),{conversationType:"C2C",flow:"in"})),{elements:Lt}=_i;Ti.setElement(Lt),LA.push(Ti)}}),{unreadMessageList:LA,revokedMessageList:SA}}(T.MsgList,n);return{syncFlag:T?.SyncFlag,unreadMessageList:EA,revokedMessageList:RA,unreadCountList:P,overflowUnreadCountList:W,cookie:T?.Cookie,groupTipList:iA}}catch(T){console.warn(T)}})}var kg,no;(function(s){s[s.START_SYNC=0]="START_SYNC",s[s.SYNCING=1]="SYNCING",s[s.SYNC_COMPLETE=2]="SYNC_COMPLETE"})(kg||(kg={})),function(s){s[s.LOGIN_SUCCESS=0]="LOGIN_SUCCESS",s[s.NEW_MESSAGE_RECEIVED=1]="NEW_MESSAGE_RECEIVED"}(no||(no={}));var uC=new class{constructor(){this.name="UnreadMessageSynchronizer",this._unreadDBMessageMap=new Map,this._cookie="",this._localConversationIDListBeforeDisconnect=[]}install(s){this._core=s;const{constants:n}=s;s.helper.registerWorkflowStep(n.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,n.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterReOnline,this),s.helper.registerWorkflowStep(n.WORKFLOW_NAME.RECEIVE_C2C_NEW_MESSAGE,n.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterNewMessageReceived,this),s.helper.registerWorkflowStep(n.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_LOGIN,n.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterLogin,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.SOCKET_DISCONNECTED,this._handleDisconnect,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.LOGOUT,this._reset,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this)}_syncUnreadMessage(s){return pA(this,void 0,void 0,function*(){const{isAfterReOnline:n=!1,isAfterNewMessageReceived:g=!1,isAfterLogin:u=!1}=s||{};let E=kg.START_SYNC;const m=[],D=[],M=[],T=[];for(;this._canContinueSync({cookie:this._cookie,syncFlag:E});){const P=yield this._fetchUnreadDBMessage({cookie:this._cookie,syncFlag:E,syncTriggerEvent:g?no.NEW_MESSAGE_RECEIVED:no.LOGIN_SUCCESS});if(!P)break;const{unreadMessageList:W=[],revokedMessageList:iA=[],overflowUnreadCountList:EA,unreadCountList:RA,groupTipList:kA}=P;if(this._cookie=P?.cookie||"",E=P?.syncFlag,this._parseAndSaveUnreadMessageList(W),M.push(...iA),this._updateConversationUnreadOptions({unreadCountList:RA,overflowUnreadCountList:EA,conversationUpdateFieldList:m}),Array.isArray(kA)&&D.push(...kA),n){const{messages:xA}=this._handleNewMessageList(W);T.push(...xA)}}return n?{conversationUpdateFieldList:m,revokedMessageList:M,unreadMessageMap:this._unreadDBMessageMap,groupTipList:D,messages:T,isUnreadC2CMessage:!0}:{conversationUpdateFieldList:m,isInstantMessage:!u,isUnreadC2CMessage:!0,revokedMessageList:M,unreadMessageMap:this._unreadDBMessageMap,groupTipList:D}})}_syncUnreadDBMessageAfterLogin(){return pA(this,void 0,void 0,function*(){return this._cookie="",this._syncUnreadMessage({isAfterLogin:!0})})}_syncUnreadDBMessageAfterNewMessageReceived(s){return pA(this,void 0,void 0,function*(){if(s.data.Flag===1)return this._syncUnreadMessage({isAfterNewMessageReceived:!0})})}_updateConversationUnreadOptions(s){const{unreadCountList:n,overflowUnreadCountList:g,conversationUpdateFieldList:u}=s,{constants:{OuterConstant:{CONV_C2C:E,CONV_SYSTEM:m}}}=this._core;n?.forEach(D=>{const{From_Account:M,UnreadCount:T}=D;if(M!==m){const P=u.find(({conversationID:W})=>W===`${E}${M}`);P?P.unreadCount=T:u.push({conversationID:`${E}${M}`,unreadCount:T,type:E})}}),g?.forEach(D=>{const{From_Account:M,LastMsgTime:T}=D;M!==m&&(u.find(({conversationID:P})=>P===`${E}${M}`)||u.push({conversationID:`${E}${M}`,type:E,lastMsgTime:T}))})}_syncUnreadDBMessageAfterReOnline(){return pA(this,void 0,void 0,function*(){return this._syncUnreadMessage({isAfterReOnline:!0})})}_updateMessageProfile(s){var n;const{messageDataHandler:g}=this._core.message||{},u=(n=this._core.store.get("login"))===null||n===void 0?void 0:n.userId,{from:E,nick:m,avatar:D,conversationID:M=""}=s;if(E!==u){const T=g.getLatestMsgSentByPeer(M);if(T){const{nick:P,avatar:W}=T;m&&D?m===P&&D===W||g.updateNickAndAvatarOfSentMessage({conversationID:M,latestNick:m,latestAvatar:D,isSentByMe:!1}):(s.nick=P,s.avatar=W)}}else{const T=g.getLatestMsgSentByMe(M);!T||m===T.nick&&D===T.avatar||g.updateNickAndAvatarOfSentMessage({conversationID:M,latestNick:m,latestAvatar:D,isSentByMe:!0})}}_handleNewMessageList(s){const{messageDataHandler:n}=this._core.message||{},g=new Map,u=[];return s.forEach(E=>{this._updateMessageProfile(E);let m=E.isModified===1;if(n.isMessageSentByCurrentInstance(E)?E.isModified=m:m=!1,E.isOnlineMessage())E._onlineOnlyFlag=!0,n.isMessageSentByCurrentInstance(E)||u.push(E);else if(this._shouldStoreUnreadMessage(E)){if(n.storeConversationMessage(E)){const{conversationID:D,conversationType:M,conversationSubType:T,flow:P,_isExcludedFromUnreadCount:W,_isExcludedFromLastMessage:iA}=E,EA=iA?"":E;g.has(D)?(g.get(D).lastMessage=EA,P==="in"&&(W||g.get(D).unreadCount++)):g.set(D,{conversationID:D,type:M,subType:T,unreadCount:W||P!=="in"?0:1,lastMessage:EA})}n.isMessageSentByCurrentInstance(E)&&!m||u.push(E)}}),{messages:u,conversationOptions:g}}_shouldStoreUnreadMessage(s){var n;const{conversationID:g}=s,{message:u,appStore:E,utils:{isEmpty:m}}=this._core||{},D=Array.from(((n=E.conversationStore.getConversationMap())===null||n===void 0?void 0:n.keys())||[]),M=this._getLocalLastMessageTime(g);return!u.messageDataHandler.isInMessageList(s)&&D.includes(g)&&this._localConversationIDListBeforeDisconnect.includes(g)&&!m(M)}_fetchUnreadDBMessage(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g}}=this._core;try{n.debug("_fetchUnreadDBMessage",`unread-message-synchronizer._fetchUnreadDBMessage options:${g(s)}`);const E=yield el(s,this._core);if(!E)return null;const{syncFlag:m,unreadMessageList:D,revokedMessageList:M,cookie:T,unreadCountList:P,overflowUnreadCountList:W,groupTipList:iA}=E;return this._parseAndSaveUnreadMessageList(D),{syncFlag:m,cookie:T,unreadMessageList:D,revokedMessageList:M,unreadCountList:P,overflowUnreadCountList:W,groupTipList:iA}}catch(u){console.log(u)}})}_canContinueSync({cookie:s,syncFlag:n}){var g;return n===kg.START_SYNC||n===kg.SYNCING&&!(!((g=this._core)===null||g===void 0)&&g.helper.isEmpty(s))}_parseAndSaveUnreadMessageList(s){s.forEach(n=>{const{ID:g}=n;this._unreadDBMessageMap.set(g,n)})}_handleDisconnect(){var s;const{appStore:n}=this._core;this._localConversationIDListBeforeDisconnect=Array.from(((s=n.conversationStore.getConversationMap())===null||s===void 0?void 0:s.keys())||[])}_getLocalLastMessageTime(s){const{message:n}=this._core,g=n.messageDataHandler.getLocalMessageList(s),u=g[g.length-1];return u?.time}_reset(){this._cookie="",this._unreadDBMessageMap.clear()}_dispose(){var s,n;(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),(n=this._core)===null||n===void 0||n.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),this._reset()}},TE=new class{init(s){var n;this._core=s,this._visibilityChangeHandler=this._handleVisibilityChange.bind(this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this),document?.addEventListener("visibilitychange",this._visibilityChangeHandler),(n=this._core)===null||n===void 0||n.store.set("activityMonitor",{isActive:!0})}_handleVisibilityChange(){var s,n;const g=document?.visibilityState==="visible";(s=this._core)===null||s===void 0||s.store.set("activityMonitor",{isActive:g}),(n=this._core)===null||n===void 0||n.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:g})}_reset(){var s;(s=this._core)===null||s===void 0||s.store.clear("activityMonitor")}_dispose(){document?.removeEventListener("visibilitychange",this._visibilityChangeHandler);const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this),this._reset()}},NE=new class{init(s){var n;this._core=s,this._bindAppActivityEvent(),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this),(n=this._core)===null||n===void 0||n.store.set("activityMonitor",{isActive:!0})}_bindAppActivityEvent(){var s,n,g,u,E;const{MINI_APP_NAMESPACE:m,IN_TT_MINI_GAME:D,IN_WX_MINI_GAME:M}=((s=this._core)===null||s===void 0?void 0:s.utils)||{};D||M?((n=m?.onShow)===null||n===void 0||n.call(m,()=>{var T,P;(T=this._core)===null||T===void 0||T.store.set("activityMonitor",{isActive:!0}),(P=this._core)===null||P===void 0||P.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})}),(g=m?.onHide)===null||g===void 0||g.call(m,()=>{var T,P;(T=this._core)===null||T===void 0||T.store.set("activityMonitor",{isActive:!1}),(P=this._core)===null||P===void 0||P.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})})):((u=m?.onAppShow)===null||u===void 0||u.call(m,()=>{var T,P;(T=this._core)===null||T===void 0||T.store.set("activityMonitor",{isActive:!0}),(P=this._core)===null||P===void 0||P.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})}),(E=m?.onAppHide)===null||E===void 0||E.call(m,()=>{var T,P;(T=this._core)===null||T===void 0||T.store.set("activityMonitor",{isActive:!1}),(P=this._core)===null||P===void 0||P.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})}))}_reset(){var s;(s=this._core)===null||s===void 0||s.store.clear("activityMonitor")}_dispose(){const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this),this._reset()}},hd=new class{init(s){const{IN_MINI_APP:n,IN_WX_MINI_PLUGIN:g}=s.helper;g||(n?NE.init(s):TE.init(s))}};const GE="none",tl="online";var dI=new class{init(s){this._core=s,this._activateNetworkMonitoring(),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return pA(this,void 0,void 0,function*(){navigator.onLine?this._onOnline():this._onOffline(),this._onOnlineCallback=this._onOnline.bind(this),this._onOfflineCallback=this._onOffline.bind(this),window.addEventListener("online",this._onOnlineCallback),window.addEventListener("offline",this._onOfflineCallback)})}_deactivateNetworkMonitoring(){this._onOnlineCallback!==null&&(window.removeEventListener("online",this._onOnlineCallback),this._onOnlineCallback=null),this._onOfflineCallback!==null&&(window.removeEventListener("offline",this._onOfflineCallback),this._onOfflineCallback=null)}_onNetworkStatusChange(s){var n,g;const{isConnected:u,networkType:E}=s;(n=this._core)===null||n===void 0||n.store.set("netWorkMonitor",{isNetworkOnline:u,networkType:E}),(g=this._core)===null||g===void 0||g.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:u,networkType:E})}_onOnline(){this._onNetworkStatusChange({isConnected:!0,networkType:tl})}_onOffline(){this._onNetworkStatusChange({isConnected:!1,networkType:GE})}_reset(){var s;this._deactivateNetworkMonitoring(),(s=this._core)===null||s===void 0||s.store.clear("netWorkMonitor")}_dispose(){var s,n;(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent((n=this._core)===null||n===void 0?void 0:n.InnerEvent.DESTROY,this._dispose,this),this._reset()}},bu=new class{init(s){this._core=s,this._activateNetworkMonitoring(),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return pA(this,void 0,void 0,function*(){try{const{utils:{MINI_APP_NAMESPACE:s}}=this._core;this._mpNetworkStatusCallback=this._onNetworkStatusChange.bind(this),s.onNetworkStatusChange(this._onNetworkStatusChange.bind(this))}catch(s){console.error(s)}})}_deactivateNetworkMonitoring(){if(this._mpNetworkStatusCallback!==null){const{utils:{MINI_APP_NAMESPACE:s}}=this._core;s.offNetworkStatusChange&&s.offNetworkStatusChange(this._mpNetworkStatusCallback),this._mpNetworkStatusCallback=null}}_onNetworkStatusChange(s){var n,g;const{isConnected:u,networkType:E}=s;(n=this._core)===null||n===void 0||n.store.set("netWorkMonitor",{isNetworkOnline:u,networkType:E}),(g=this._core)===null||g===void 0||g.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:u,networkType:E})}_reset(){var s;this._deactivateNetworkMonitoring(),(s=this._core)===null||s===void 0||s.store.clear("netWorkMonitor")}_dispose(){var s,n;(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent((n=this._core)===null||n===void 0?void 0:n.InnerEvent.DESTROY,this._dispose,this),this._reset()}},ku=new class{init(s){const{IN_MINI_APP:n}=s.utils;n?bu.init(s):dI.init(s)}},EC=new class{constructor(){this.name="SystemStateMonitor"}install(s){hd.init(s),ku.init(s)}};const Rr=new Set(["tui_room_svr.*","callkit_records_svr.*","room_engine_srv.*","room_engine_http_srv.*","room_engine_mic.*","live_engine_srv.*","live_engine_http_srv.*","live_engine_pk.*","trtc_ai_service.*","call_engine_srv.*"]),cg="tui_room_svr.*";var Rc=new class{constructor(){this.name="BusinessCommandTransfer",this._transferredCommands=Rr}install(s){this._core=s;const{notificationCenter:n,InnerEvent:g,helper:u}=s;n.subscribeInnerEvent(g.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),n.subscribeInnerEvent(g.LOGOUT,this._reset,this),n.subscribeInnerEvent(g.DESTROY,this._dispose,this),n.subscribeInnerEvent("im_open_push.msg_push",n.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this),u.registerExperimentalAPI("sendTRTCCustomData",this,"transferBusinessCommand"),u.registerExperimentalAPI("sendRoomCustomData",this,"transferBusinessCommand")}transferBusinessCommand(s){return pA(this,void 0,void 0,function*(){const n="transferBusinessCommand";try{const{serviceCommand:g=cg}=s||{};if(!this._isValidTransferredCommand(g))throw new this._core.helper.ChatError({code:2995,functionName:n});return{code:0,data:(yield function(E,m){return pA(this,void 0,void 0,function*(){const{helper:D,channel:M}=m,{serviceCommand:T=cg,data:P}=E||{};let W={};try{W=typeof P=="string"?JSON.parse(P):P}catch(RA){console.warn(RA)}const iA=D.generateProtocolData({servcmd:T,data:W}),EA=`${iA.head.seq}${T}`;return M.sendPacket(iA,{requestId:EA,shouldRejectOnError:!1})})}(s,this._core))||{}}}catch(g){throw console.warn(g),new this._core.helper.ChatError({code:g?.errorCode,message:g?.errorInfo,data:{},functionName:n})}})}_onCloudConfigUpdate(s={}){try{if(typeof s.rtc_cmd!="string")return;const n=JSON.parse(s.rtc_cmd);Array.isArray(n)&&(this._transferredCommands=new Set([...this._transferredCommands,...n]))}catch(n){console.log(n)}}_isValidTransferredCommand(s=""){const n=`${s?.split(".")[0]}.*`;return this._transferredCommands.has(n)}_onServerPushBusinessCommand(s){const{OuterEvent:n,notificationCenter:g}=this._core,{MsgContent:u}=s||{},{ROOM_CUSTOM_DATA_RECEIVED:E}=n;g.emitOuterEvent(E,{name:E,data:u})}_reset(){this._transferredCommands=Rr}_dispose(){const{notificationCenter:s,InnerEvent:n}=this._core;this._reset(),s.unSubscribeInnerEvent(n.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),s.unSubscribeInnerEvent(n.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this),s.unSubscribeInnerEvent("im_open_push.msg_push",s.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this)}};const Lu=1,Tl=2,Bd=3,$r=4,CI=5,_n="TIMCustomElem",dC="C2C",il="GROUP",Qd="invite",hI="accept",Oa="cancel",CC="reject",Pa="modifyInvitation",ur="signaling",pd=8010,Uu="signaling-timeout";function Er(s){return s.filter(n=>{if(n.type===_n){const{cloudCustomData:g="",payload:{data:u=""}={}}=n,E=g.match(/"type":"tsignaling"/),m=u.match(/inviteID/),D=u.match(/actionType/);return E||m&&D}return!1})}function wc(s){const{data:n}=s.payload;try{return JSON.parse(n)}catch(g){return console.error(g),null}}function ol(s,n){return s.toString(16).padStart(n,"0")}function Lg(s){if(s<0||s>53)throw new Error("Number of digits must be between 0 and 53");if(s<=30)return Math.floor(Math.random()*(1<0;const M=this._core.common.getCurrentUserID();return D.includes(M)}return!0}updateSignaling(s){const n=`${ur}.updateSignaling`,{inviteID:g,inviter:u,inviteeList:E,groupID:m}=s;if(console.log(`${n} inviteID:${g} inviter:${u} groupID:${m}`),m&&this.hasSignaling(g)){const D=E[0],{inviteeList:M}=this._onlineSignalingMap.get(g);M.includes(D)&&(M.splice(M.indexOf(D),1),console.log(`${n} remove ${D}. localInviteeList.length:${M.length}`)),M.length===0&&this.removeSignaling(g)}else this.removeSignaling(g)}setSignalingListenStatus(s){this._isSignalingListening=s}getSignalingListenStatus(){return this._isSignalingListening}_dispose(){var s,n;this._reset(),(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),(n=this._core)===null||n===void 0||n.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._isSignalingListening=!1}_reset(){this._onlineSignalingMap.clear()}},$g=new class{init(s){this._core=s}createInviteSignaling(s){const n=this._generateInviteID(),g=this._createInviteSignalingData(Object.assign(Object.assign({},s),{inviteID:n})),{groupID:u,inviteeList:E}=g,m=u||E[0];return{signaling:this._createSignaling(g,m),signalingData:g,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createAcceptSignaling(s){const n=this._createAcceptSignalingData(s),{groupID:g,inviter:u}=n,E=g||u;return{signaling:this._createSignaling(n,E),signalingData:n,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createCancelSignaling(s){const n=this._createCancelSignalingData(s),{groupID:g,inviteeList:u}=n,E=g||u[0];return{signaling:this._createSignaling(n,E),signalingData:n,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createRejectSignaling(s){const n=this._createRejectSignalingData(s),{groupID:g,inviter:u}=n,E=g||u;return{signaling:this._createSignaling(n,E),signalingData:n,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createTimeoutSignaling(s){const{isInviter:n=!1}=s,g=this._createTimeoutSignalingData(s),{groupID:u,inviteeList:E,inviter:m}=g,D=u||(n?E[0]:m);return{signaling:this._createSignaling(g,D),signalingData:g,signalingExtensionOptions:this._createSignalingExtensionOptions(g)}}_createSignalingExtensionOptions(s){var n,g;const{data:u="",onlineUserOnly:E,inviteID:m="",offlinePushInfo:D,actionType:M}=s,T=((g=(n=Oo.getSignaling(m))===null||n===void 0?void 0:n.signaling)===null||g===void 0?void 0:g._onlineOnlyFlag)||!1;return{onlineUserOnly:E||T,offlinePushInfo:D,messageControlInfo:this._createMessageControlInfo(u,M)}}_createMessageControlInfo(s,n){const g=n===CI&&!!s.match(/excludeTimeoutSignalingFromHistoryMessage/),u=!!s.match(/excludeFromHistoryMessage/)||!!s.match(/excludeOriginalSignalingFromHistoryMessage/);return{excludedFromContentModeration:!0,excludedFromUnreadCount:g||u,excludedFromLastMessage:g||u}}_createInviteSignalingData(s){const n=`${ur}._createInviteSignalingData`,{userID:g,timeout:u=0,groupID:E="",inviteeList:m=[]}=s,D=this._core.common.getCurrentUserID(),M=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:Lu,inviter:D,inviteeList:E?m:[g],timeout:u});return console.log(`${n} signalingData:`,M),M}_createAcceptSignalingData(s){const n=`${ur}._createAcceptSignalingData`,{inviteID:g}=s,u=this._core.common.getCurrentUserID(),{inviter:E,groupID:m}=Oo.getSignaling(g),D=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:Bd,groupID:m,inviter:E,inviteeList:[u]});return console.log(`${n} signalingData:`,D),D}_createCancelSignalingData(s){const n=`${ur}._createCancelSignalingData`,{inviteID:g}=s,u=this._core.common.getCurrentUserID(),{inviteeList:E,groupID:m}=Oo.getSignaling(g),D=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:Tl,groupID:m,inviter:u,inviteeList:E});return console.log(`${n} signalingData:`,D),D}_createRejectSignalingData(s){const n=`${ur}._createRejectSignalingData`,{inviteID:g}=s,u=this._core.common.getCurrentUserID(),{inviter:E,groupID:m}=Oo.getSignaling(g),D=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:$r,groupID:m,inviter:E,inviteeList:[u]});return console.log(`${n} signalingData:`,D),D}_createTimeoutSignalingData(s){const n=`${ur}._createTimeoutSignalingData`,{isInviter:g=!1,inviteID:u}=s,{inviteeList:E,inviter:m}=Oo.getSignaling(u),D=this._core.common.getCurrentUserID(),M=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:CI,inviter:m,inviteeList:g?E:[D]});return console.log(`${n} signalingData:`,M),M}_createSignaling(s,n){var g,u,E;const{groupID:m=""}=s,D={to:n,conversationType:m?il:dC,priority:"High",payload:{data:JSON.stringify(s)}};return(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageFactory)===null||E===void 0?void 0:E.createCustomMessage(D)}_generateInviteID(){return[ol(Lg(32),8),ol(Lg(16),4),ol(16384|Lg(12),4),ol(32768|Lg(14),4),ol(Lg(48),12)].join("-")}_generateBaseSignalData(s){const{data:n="",inviteID:g="",groupID:u=""}=s;return{businessID:1,timeout:0,data:n,inviteID:g,groupID:u}}},Za=new class{constructor(){this._isProcessingSignaling=!1}init(s){this._core=s,s.helper.registerApi({apiName:"invite",context:this}),s.helper.registerApi({apiName:"accept",context:this}),s.helper.registerApi({apiName:"cancel",context:this}),s.helper.registerApi({apiName:"reject",context:this}),s.helper.registerApi({apiName:"modifyInvitation",context:this}),s.helper.registerApi({apiName:"getSignalingInfo",context:this}),s.helper.registerApi({apiName:"addSignalingListener",context:this}),s.helper.registerApi({apiName:"removeSignalingListener",context:this}),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.LOGOUT,this._reset,this)}invite(s){return pA(this,void 0,void 0,function*(){var n;try{this._validateBeforeInvite(s);const{signaling:g,signalingData:u,signalingExtensionOptions:E}=$g.createInviteSignaling(s),m=yield this._sendSignaling(g,E);if(m?.code===0){const{inviteID:D,timeout:M}=u;return Oo.saveSignaling(D,Object.assign(Object.assign({},u),{signaling:g})),M>0&&((n=this._core)===null||n===void 0||n.helper.taskScheduler.addOnceTask({id:`${Uu}-${D}`,intervalMs:1e3*(M+5),callback:this.handleInvitationExpiryTimer.bind(this,D)})),Object.assign(Object.assign({},m),{inviteID:D})}return m}catch(g){throw g}})}accept(s){return pA(this,void 0,void 0,function*(){try{const{inviteID:n}=s;this._validateBeforeAccept(n),this._isProcessingSignaling=!0;const{signaling:g,signalingData:u,signalingExtensionOptions:E}=$g.createAcceptSignaling(s),m=yield this._sendSignaling(g,E);return m?.code===0?(Oo.updateSignaling(u),Object.assign(Object.assign({},m),{inviteID:n})):m}catch(n){throw n}finally{this._isProcessingSignaling=!1}})}cancel(s){return pA(this,void 0,void 0,function*(){try{const{inviteID:n}=s;this._validateBeforeCancel(n),this._isProcessingSignaling=!0;const{signaling:g,signalingExtensionOptions:u}=$g.createCancelSignaling(s),E=yield this._sendSignaling(g,u);return E?.code===0?(Oo.removeSignaling(n),Object.assign(Object.assign({},E),{inviteID:n})):E}catch(n){throw n}finally{this._isProcessingSignaling=!1}})}reject(s){return pA(this,void 0,void 0,function*(){try{const{inviteID:n}=s;this._validateBeforeReject(n),this._isProcessingSignaling=!0;const{signaling:g,signalingExtensionOptions:u}=$g.createRejectSignaling(s),E=yield this._sendSignaling(g,u);return E?.code===0?(Oo.removeSignaling(n),Object.assign(Object.assign({},E),{inviteID:n})):E}catch(n){throw n}finally{this._isProcessingSignaling=!1}})}modifyInvitation(s){return pA(this,void 0,void 0,function*(){var n,g;const{inviteID:u,data:E}=s;let m="";try{this._validateBeforeModifyInvitation(u);const D=Oo.getSignaling(u),{signaling:M}=D,T=Do(D,["signaling"]);m=M.payload.data,T.data=E,M.payload.data=JSON.stringify(T);const P=yield(g=(n=this._core)===null||n===void 0?void 0:n.message.messageAction)===null||g===void 0?void 0:g.modifyMessage(M);return Oo.hasSignaling(u)&&Oo.saveSignaling(u,Object.assign(Object.assign({},T),{signaling:M})),P}catch(D){if(m){const{signaling:M}=Oo.getSignaling(u);M.payload.data=m}throw D}})}getSignalingInfo(s){const{ssoLog:n,utils:{safeStringify:g}}=this._core;if(Er([s]).length===0)return;const u=wc(s),E={businessID:u.businessID||1,inviteID:u.inviteID,groupID:u.groupID||"",inviter:u.inviter||"",inviteeList:u.inviteeList||[],data:u.data||"",actionType:u.actionType||Lu,timeout:u.timeout||0};return n.debug(`${ur} getSignalingInfo ${g(E)}`),E}addSignalingListener(s,n,g){var u,E;s===((u=this._core)===null||u===void 0?void 0:u.SignalingEvent.NEW_INVITATION_RECEIVED)&&Oo.setSignalingListenStatus(!0),(E=this._core)===null||E===void 0||E.notificationCenter.subscribeOuterEvent(s,n,g)}removeSignalingListener(s,n,g){var u,E;s===((u=this._core)===null||u===void 0?void 0:u.SignalingEvent.NEW_INVITATION_RECEIVED)&&Oo.setSignalingListenStatus(!1),(E=this._core)===null||E===void 0||E.notificationCenter.unSubscribeOuterEvent(s,n,g)}handleInvitationExpiryTimer(s){const n=Oo.getOnlineSignalingMap(),g=this._core.common.getCurrentUserID();if(!n.has(s))return;const u=n.get(s).inviter===g;this._sendTimeoutNotice({inviteID:s,isInviter:u})}_sendSignaling(s,n){return pA(this,void 0,void 0,function*(){var g,u,E;return(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageSender)===null||E===void 0?void 0:E.sendMessage(s,n)})}_sendTimeoutNotice(s){return pA(this,void 0,void 0,function*(){var n,g,u;this._core.ssoLog.debug("_sendTimeoutNotice",`${ur}._sendTimeoutNotice params:${JSON.stringify(s)}`);const{isInviter:E,inviteID:m}=s,{signaling:D,signalingData:M,signalingExtensionOptions:T}=$g.createTimeoutSignaling(s),P=yield this._sendSignaling(D,T);if(P?.code===0){const{data:W,groupID:iA,inviteeList:EA,inviter:RA}=M;(n=this._core)===null||n===void 0||n.notificationCenter.emitOuterEvent((g=this._core)===null||g===void 0?void 0:g.SignalingEvent.INVITATION_TIMEOUT,{name:(u=this._core)===null||u===void 0?void 0:u.SignalingEvent.INVITATION_TIMEOUT,data:{data:W,groupID:iA,inviteID:m,inviteeList:EA,inviter:RA,isSelfTimeout:!0,message:D}}),E?Oo.removeSignaling(m):Oo.updateSignaling(M)}})}_validateInviteId(s,n){if(!Oo.hasSignaling(n))throw new this._core.helper.ChatError({functionName:s,code:pd})}_validateProcessStatus(s){if(this._isProcessingSignaling)throw new this._core.helper.ChatError({functionName:s,message:"processing other signaling operations"})}_validateBeforeInvite(s){const n=Qd,{userID:g}=s,u=this._core.common.getCurrentUserID();if(g===u)throw new this._core.helper.ChatError({functionName:n,message:`cannot invite yourself, currentUserId:${u}, inviteeId:${g}`})}_validateBeforeAccept(s){const n=hI;this._validateInviteId(n,s),this._validateProcessStatus(n);const g=this._core.common.getCurrentUserID(),{inviteeList:u}=Oo.getSignaling(s);if(!u.includes(g)){const E=`userID:${g} not in inviteeList. inviteID:${s}`;throw new this._core.helper.ChatError({functionName:n,message:E})}}_validateBeforeCancel(s){const n=Oa;this._validateInviteId(n,s),this._validateProcessStatus(n);const g=this._core.common.getCurrentUserID(),{inviter:u}=Oo.getSignaling(s);if(u!==g){const E=`unmatched inviter:${u} and my userID:${g}`;throw new this._core.helper.ChatError({functionName:n,message:E})}}_validateBeforeReject(s){const n=CC;this._validateInviteId(n,s),this._validateProcessStatus(n);const g=this._core.common.getCurrentUserID(),{inviteeList:u}=Oo.getSignaling(s);if(!u.includes(g)){const E=`userID:${g} not in inviteeList. inviteID:${s}`;throw new this._core.helper.ChatError({functionName:n,message:E})}}_validateBeforeModifyInvitation(s){const n=Pa;this._validateInviteId(n,s)}_dispose(){var s,n;this._reset(),(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),(n=this._core)===null||n===void 0||n.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this)}_reset(){this._isProcessingSignaling=!1}},Nl=new class{constructor(){this._actionProcessor=new Map([[Lu,this._onNewInvitationReceived.bind(this)],[$r,this._onInviteeRejected.bind(this)],[Bd,this._onInviteeAccepted.bind(this)],[Tl,this._onInvitationCancelled.bind(this)],[CI,this._onInvitationTimeout.bind(this)]])}init(s){this._core=s,s.notificationCenter.subscribeOuterEvent(s.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),s.notificationCenter.subscribeOuterEvent(s.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this)}handleActionSignaling(s){s.forEach(n=>{const g=wc(n);if(g){const u=this._actionProcessor.get(g.actionType);u?.(g,n)}})}_handleMessageReceived(s){if(!Oo.getSignalingListenStatus())return;const n=Er(s.data);n.length!==0&&this.handleActionSignaling(n)}_handleMessageModified(s){if(!Oo.getSignalingListenStatus())return;const n=Er(s.data);n.length>0&&n.forEach(g=>{const u=wc(g);u&&this._onInvitationModified(u,g)})}_onNewInvitationReceived(s,n){var g,u;const E=`${ur}._onNewInvitationReceived`,{inviteID:m,inviteeList:D,groupID:M}=s,T=this._core.common.getCurrentUserID();if(this._core.ssoLog.debug("_onNewInvitationReceived",`${E} signalingData:${JSON.stringify(s)}}`),M&&!D.includes(T))return;let{timeout:P}=s;const W=Date.now()/1e3-n.time;P>0&&W>0&&P>W&&(P-=W);const iA=Oo.getSignaling(m);iA!==s&&(iA||Oo.saveSignaling(m,Object.assign(Object.assign({},s),{signaling:n})),P>0&&((g=this._core)===null||g===void 0||g.helper.taskScheduler.addOnceTask({id:`${Uu}-${m}`,intervalMs:1e3*P,callback:Za.handleInvitationExpiryTimer.bind(Za,m)})),this._emitEvent({name:(u=this._core)===null||u===void 0?void 0:u.SignalingEvent.NEW_INVITATION_RECEIVED,data:Object.assign(Object.assign({},this._generateBaseEmitData(s)),{inviteeList:D})}))}_onInviteeRejected(s){var n;const g=`${ur}._onInviteeRejected`,{inviteID:u,inviter:E,groupID:m,inviteeList:D}=s,M=Oo.hasSignaling(u);this._core.ssoLog.debug("_onInviteeRejected",`${g} inviteID:${u} hasInviteID:${M} inviter:${E} groupID:${m}`),M&&(Oo.updateSignaling(s),this._emitEvent({name:(n=this._core)===null||n===void 0?void 0:n.SignalingEvent.INVITEE_REJECTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(s)),{invitee:D[0]})}))}_onInviteeAccepted(s){var n;const g=`${ur}._onInviteeAccepted`,{inviteID:u,inviter:E,groupID:m,inviteeList:D}=s,M=Oo.hasSignaling(u);this._core.ssoLog.debug("_onInviteeAccepted",`${g} inviteID:${u} hasInviteID:${M} inviter:${E} groupID:${m}`),M&&(Oo.updateSignaling(s),this._emitEvent({name:(n=this._core)===null||n===void 0?void 0:n.SignalingEvent.INVITEE_ACCEPTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(s)),{invitee:D[0]})}))}_onInvitationCancelled(s){var n;const g=`${ur}._onInvitationCancelled`,{inviteID:u,inviter:E,groupID:m}=s,D=Oo.hasSignaling(u);this._core.ssoLog.debug("_onInvitationCancelled",`${g} inviteID:${u} hasInviteID:${D} inviter:${E} groupID:${m}`),D&&(Oo.removeSignaling(u),this._emitEvent({name:(n=this._core)===null||n===void 0?void 0:n.SignalingEvent.INVITATION_CANCELLED,data:this._generateBaseEmitData(s)}))}_onInvitationTimeout(s){var n;const g=`${ur}._onInvitationTimeout`,{inviteID:u,inviteeList:E}=s,m=Oo.hasSignaling(u);this._core.ssoLog.debug("_onInvitationTimeout",`${g} inviteID:${u} hasInviteID:${m} data:${s.data}`),m&&(Oo.updateSignaling(s),this._emitEvent({name:(n=this._core)===null||n===void 0?void 0:n.SignalingEvent.INVITATION_TIMEOUT,data:Object.assign(Object.assign({},this._generateBaseEmitData(s)),{inviteeList:E,isSelfTimeout:!1})}))}_onInvitationModified(s,n){var g;const u=`${ur}._onInvitationModified`,{inviteID:E,data:m}=s,D=Oo.hasSignaling(E);this._core.ssoLog.debug("_onInvitationModified",`${u} inviteID:${E} data:${m}`),D&&(Oo.saveSignaling(E,Object.assign(Object.assign({},s),{signaling:n})),this._emitEvent({name:(g=this._core)===null||g===void 0?void 0:g.SignalingEvent.INVITATION_MODIFIED,data:{inviteID:E,data:m}}))}_emitEvent(s){var n;(n=this._core)===null||n===void 0||n.notificationCenter.emitOuterEvent(s.name,s)}_generateBaseEmitData(s){const{inviteID:n,inviter:g,groupID:u,data:E}=s;return{inviteID:n,inviter:g,groupID:u,data:E||""}}_dispose(){var s,n,g;(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),(n=this._core)===null||n===void 0||n.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),(g=this._core)===null||g===void 0||g.notificationCenter.unSubscribeOuterEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}},Aa=new class{constructor(){this._offlineSignalingMap=new Map}init(s){this._core=s;const{notificationCenter:n,helper:g,constants:{InnerEvent:u,WORKFLOW_STEP:E,WORKFLOW_NAME:m}}=s;n.subscribeInnerEvent(u.DESTROY,this._dispose,this),n.subscribeInnerEvent(u.LOGOUT,this._reset,this),g.registerWorkflowStep(m.SYNC_SERVER_INFO_AFTER_LOGIN,E.SIGNALING_MESSAGE_RECOVER,this._handleC2COfflineMessage,this)}_handleC2COfflineMessage(s){const{result:{unreadMessageMap:n}={}}=s||{};if(!(n?.size!==0&&Oo.getSignalingListenStatus()))return;const g=Er([...n.values()]);if(g.length!==0&&(g.forEach(u=>{this._handleC2CActionType(u)}),this._offlineSignalingMap.size>0)){const u=this._sortOfflineSignalingByTime();Nl.handleActionSignaling(u)}}_handleC2CActionType(s){const n=wc(s);if(!n)return;const{actionType:g}=n;g===Lu?this._saveValidOfflineInvite(n,s):this._removeOfflineInvite(n)}_saveValidOfflineInvite(s,n){const{inviteID:g,inviteeList:u=[],timeout:E=0}=s,m=this._core.common.getCurrentUserID();if(!u.includes(m))return;const D=Date.now()/1e3-n.time;E>0&&D>E&&E!==0||this._offlineSignalingMap.set(g,Object.assign(Object.assign({},s),{signalingList:[n]}))}_removeOfflineInvite(s){const{inviteID:n=""}=s;this._offlineSignalingMap.has(n)&&this._offlineSignalingMap.delete(n)}_sortOfflineSignalingByTime(){let s=[];return this._offlineSignalingMap.forEach(n=>{s=[...s,...n.signalingList]}),s.sort((n,g)=>n.time-g.time)}_dispose(){var s,n;this._reset(),(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),(n=this._core)===null||n===void 0||n.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._offlineSignalingMap.clear()}};const gh={invite:{userID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0},timeout:{required:!1,rules:["number"],allowEmpty:!1},onlineUserOnly:{required:!1,rules:["boolean"],allowEmpty:!1},offlinePushInfo:{required:!1,rules:["object"],allowEmpty:!1}},cancel:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},accept:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},reject:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},modifyInvitation:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}}},js={invite:!0,cancel:!0,accept:!0,reject:!0,modifyInvitation:!0};var ZI=new class{constructor(){this.name="Signaling"}install(s){Za.init(s),Nl.init(s),$g.init(s),Oo.init(s),Aa.init(s),s.helper.registerValidateConfig({auth:js,params:gh})}};const Us=new class{init(s){this.core=s}};function _c(s){let n;const{message:g}=Us.core,{conversationID:u,messageID:E}=s;return n=g.messageDataHandler.getLocalMessageList(u).find(m=>m.ID===E),!n&&(n=g.messageDataHandler.getSparseMessageList(u).find(m=>m.ID===E)),n}function Ac(s){return s.map(n=>{const{from:g,to:u,cloudCustomData:E,avatar:m,nick:D,ID:M,clientSequence:T,clientTime:P,messageRandom:W,messageSequence:iA,time:EA}=n;return{ClientSeq:T,CloudCustomData:E,From_Account:g,From_AccountHeadurl:m,From_AccountNick:D,Id:M,MsgBody:JSON.parse(JSON.stringify(n.transformElementsToServerFormat())),MsgClientTime:P,MsgRandom:W,Random:W,MsgSeq:iA,MsgTimeStamp:EA,ReceiverId:u,SenderId:g,To_Account:u}})}function dr(s){var n;const{From_Account:g,From_AccountHeadurl:u,From_AccountNick:E,GroupId:m,MsgClientTime:D,ClientSeq:M,To_Account:T,MsgTimeStamp:P,TinyId:W,MsgRandom:iA,MsgSeq:EA}=s;return{from:g,avatar:u,nick:E,clientTime:D,time:P,tinyID:W,random:iA,sequence:EA,to:T,groupID:m,clientSequence:M,_elements:(n=s.MsgBody)===null||n===void 0?void 0:n.map(RA=>{const{MsgType:kA}=RA;return Us.core.message.messageFactory.getElementClass(kA).parseServerPushElement(RA)})}}var Vr,Xa;(function(s){s.MSG_TEXT="TIMTextElem",s.MSG_CUSTOM="TIMCustomElem",s.MSG_LOCATION="TIMLocationElem",s.MSG_FACE="TIMFaceElem",s.MSG_STREAM="TIMStreamElem"})(Vr||(Vr={})),function(s){s[s.FORWARD=0]="FORWARD",s[s.BACKWARD=1]="BACKWARD"}(Xa||(Xa={}));const bE="MSG_REACTION",hC="MSG_EXT",ch=0,ro=1,Tc={ZH_CN:"zh (cmn-Hans-CN)",EN_US:"en-US",YUE_HK:"yue-Hant-HK",JA_JP:"ja-JP",ZH_PY:"zh-PY"},Gl="16k_zh",BC="16k_en",QC="16k_yue",bl="16k_ja",XI="16k_zh-PY",BI={[Tc.ZH_CN]:Gl,[Tc.EN_US]:BC,[Tc.YUE_HK]:QC,[Tc.JA_JP]:bl,[Tc.ZH_PY]:XI},QI=/\.(wav|pcm|ogg-opus|speex|silk|mp3|m4a|aac|amr)/,kE={READ:0,UNREAD:1},kl=1,Ll=2,Ug=3;var ec;(function(s){s.IN="in",s.OUT="out"})(ec||(ec={}));const md=16,LE=17;var Nc;(function(s){s[s.DATA=0]="DATA",s[s.REVOKED=1]="REVOKED"})(Nc||(Nc={}));var $I;(function(s){s[s.NORMAL=0]="NORMAL",s[s.TIMEOUT=1]="TIMEOUT"})($I||($I={}));const lo="StreamMsg.PushStreamHttp";var UE=new class{constructor(){this._reactionsMap=new Map}init(s){this._core=s;const{helper:n,notificationCenter:g,InnerEvent:{MESSAGE_PUSH:u},InnerEventSubType:{MESSAGE_REACTION_UPDATED:E,MESSAGE_REACTION_UPDATED_SYNC:m}}=s;n.registerApi({apiName:"addMessageReaction",context:this}),n.registerApi({apiName:"removeMessageReaction",context:this}),n.registerApi({apiName:"getMessageReactions",context:this}),n.registerApi({apiName:"getAllUserListOfMessageReaction",context:this}),g.subscribeInnerEvent(u,E,this._handleReactionUpdated,this),g.subscribeInnerEvent(u,m,this._handleReactionSync,this)}addMessageReaction(s,n){return pA(this,void 0,void 0,function*(){const{OuterConstant:g,ssoLog:u,helper:E}=this._core;this._validateMessageReactionBusinessCapability();const{conversationID:m,ID:D,conversationType:M,from:T,to:P,clientSequence:W,random:iA,time:EA,sequence:RA}=s,kA=`conversationID:${m} messageID:${D} reactionID:${n}`;try{return this._recordMessageReactedByMe(D,n),M===g.CONV_C2C?yield function(xA,LA){return pA(this,void 0,void 0,function*(){var SA;const{from:OA,to:JA,clientSequence:ae,random:re,time:_i,reactionID:Ti}=xA,Lt={From_Account:OA,To_Account:JA,MsgKey:`${ae}_${re}_${_i}`,Reaction:Ti,Add_Account:[(SA=LA.store.get("login"))===null||SA===void 0?void 0:SA.userId]};return Us.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_add",data:Lt})})}({from:T,to:P,clientSequence:W,random:iA,time:EA,reactionID:n},this._core):M===g.CONV_GROUP&&(yield function(xA,LA){return pA(this,void 0,void 0,function*(){var SA;const{to:OA,reactionID:JA,sequence:ae}=xA,re={GroupId:OA,MsgSeq:ae,Reaction:JA,Add_Account:[(SA=LA.store.get("login"))===null||SA===void 0?void 0:SA.userId]};return Us.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_add",data:re})})}({to:P,reactionID:n,sequence:RA},this._core)),{code:0,successLog:{message:kA}}}catch(xA){this._removeMyReactionRecord(D,n);const{errorCode:LA}=xA||{};throw new E.ChatError({functionName:"addMessageReaction",code:LA,moreMessage:kA})}})}removeMessageReaction(s,n){return pA(this,void 0,void 0,function*(){const{OuterConstant:g,helper:u}=this._core;this._validateMessageReactionBusinessCapability();const{conversationID:E,ID:m,conversationType:D,from:M,to:T,clientSequence:P,random:W,time:iA,sequence:EA}=s,RA=`conversationID:${E} messageID:${m} reactionID:${n}`;try{return this._removeMyReactionRecord(m,n),D===g.CONV_C2C?yield function(kA,xA){return pA(this,void 0,void 0,function*(){var LA;const{from:SA,to:OA,clientSequence:JA,random:ae,time:re,reactionID:_i}=kA,Ti={From_Account:SA,To_Account:OA,MsgKey:`${JA}_${ae}_${re}`,Reaction:_i,Del_Account:[(LA=xA.store.get("login"))===null||LA===void 0?void 0:LA.userId]};return Us.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_del",data:Ti})})}({from:M,to:T,clientSequence:P,random:W,time:iA,reactionID:n},this._core):D===g.CONV_GROUP&&(yield function(kA,xA){return pA(this,void 0,void 0,function*(){var LA;const{to:SA,reactionID:OA,sequence:JA}=kA,ae={GroupId:SA,MsgSeq:JA,Reaction:OA,Del_Account:[(LA=xA.store.get("login"))===null||LA===void 0?void 0:LA.userId]};return Us.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_del",data:ae},xA)})}({to:T,reactionID:n,sequence:EA},this._core)),{code:0,successLog:{message:RA}}}catch(kA){const{errorCode:xA}=kA||{};throw new u.ChatError({functionName:"removeMessageReaction",code:xA,moreMessage:RA})}})}getAllUserListOfMessageReaction(s){return pA(this,void 0,void 0,function*(){this._validateMessageReactionBusinessCapability();const{message:n,reactionID:g,nextSeq:u=0}=s,E=s.count>100?100:s.count,{conversationID:m}=n,{ssoLog:D,helper:M,constants:T}=this._core;try{let P=null;if(P=m.startsWith(T.OuterConstant.CONV_C2C)?yield function(W){return pA(this,void 0,void 0,function*(){const{message:iA,nextSeq:EA,reactionID:RA,count:kA}=W,{from:xA,to:LA,clientSequence:SA,random:OA,time:JA}=iA,ae={Reaction:RA,NextSeq:EA,Count:kA,From_Account:xA,To_Account:LA,MsgKey:`${SA}_${OA}_${JA}`};return Us.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_iterate",data:ae})})}({message:n,reactionID:g,nextSeq:u,count:E}):yield function(W){return pA(this,void 0,void 0,function*(){const{message:iA,nextSeq:EA,reactionID:RA,count:kA}=W,{sequence:xA,to:LA}=iA,SA={Reaction:RA,NextSeq:EA,GroupId:LA,Count:kA,MsgSeq:xA};return Us.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_iterate",data:SA})})}({message:n,reactionID:g,nextSeq:u,count:E}),P){const{Reaction_Account:W,NextSeq:iA}=P,EA=yield this._getUserProfileList(W);return{code:0,data:{nextSeq:iA,isCompleted:u===0,userList:EA}}}}catch(P){const{errorCode:W}=P||{};throw new M.ChatError({functionName:"getAllUserListOfMessageReaction",code:W})}})}getMessageReactions(s){return pA(this,void 0,void 0,function*(){const{constants:n}=this._core;this._validateMessageReactionBusinessCapability();const{messageList:g,maxUserCountPerReaction:u=10}=s,E=g[0];let m=null;const D=new Map,{from:M,to:T,conversationType:P}=E,W=this._generateMessageKeyList(g,D);P===n.OuterConstant.CONV_C2C?m=yield function(kA){return pA(this,void 0,void 0,function*(){const{from:xA,to:LA,messageKeyList:SA,maxUserCountPerReaction:OA}=kA,JA={From_Account:xA,To_Account:LA,MsgKeyList:SA,Count:OA};return Us.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_multi_stat",data:JA})})}({from:M,to:T,messageKeyList:W,maxUserCountPerReaction:u}):P===n.OuterConstant.CONV_GROUP&&(m=yield function(kA){return pA(this,void 0,void 0,function*(){const{groupId:xA,messageSequenceList:LA,maxUserCountPerReaction:SA}=kA,OA={GroupId:xA,MsgSeqList:LA,Count:SA};return Us.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_multi_stat",data:OA})})}({groupId:T,messageSequenceList:W,maxUserCountPerReaction:u}));const{Results:iA=[]}=m||{},EA=this._extractUserIDsFromReactionResults(iA),RA=yield this._getUserProfileMap(EA);return{code:0,data:{resultList:iA.map(kA=>{const{ReactionList:xA,MsgSeq:LA,MsgKey:SA}=kA;return{messageID:this._generateMessageID({messageSequence:LA,messageKey:SA,messageIDMap:D}),reactionList:xA.map(OA=>{const{Reaction:JA,Count:ae,Reaction_Account:re,ReactedByMe:_i}=OA;return{reactionID:JA,totalUserCount:ae,partialUserList:this._generatePartialUserInfo({userIDList:re,userProfileMap:RA}),reactedByMyself:_i===1}})}})}}})}dispose(){this._reactionsMap.clear()}_extractUserIDsFromReactionResults(s){const n=[];return s?.forEach(g=>{const{ReactionList:u=[]}=g;u.forEach(E=>{E.Reaction_Account&&n.push(...E.Reaction_Account)})}),n}_getUserProfileList(s){return pA(this,void 0,void 0,function*(){var n;try{const g=yield(n=this._core.user.userProfile)===null||n===void 0?void 0:n.getUserProfile({userIDList:s});return g?g.data:[]}catch{return[]}})}_getUserProfileMap(s){return pA(this,void 0,void 0,function*(){const n=new Map;return(yield this._getUserProfileList(s)).forEach(g=>{const{nick:u,avatar:E,userID:m}=g;n.set(m,{nick:u,avatar:E,userID:m})}),n})}_recordMessageReactedByMe(s,n){const g=`${s}-${n}`;this._reactionsMap.has(g)?this._reactionsMap.get(g).reactedByMe=!0:this._reactionsMap.set(g,{reactedByMe:!0})}_removeMyReactionRecord(s,n){const g=`${s}-${n}`;this._reactionsMap.has(g)&&(this._reactionsMap.get(g).reactedByMe=!1)}_recordMessageReactionInfo(s){const{messageID:n,reactionID:g,reactionInfo:u}=s,E=`${n}-${g}`,m=this._reactionsMap.get(E)||{};this._reactionsMap.set(E,Object.assign(Object.assign({},m),u))}_validateMessageReactionBusinessCapability(){const{helper:s,constants:n}=this._core;if(!s.checkBusinessCapabilityBits(bE))throw new s.ChatError({functionName:"addMessageReaction",code:n.ERROR_CODE.NO_USE,replacement1:"addMessageReaction"})}_handleReactionUpdated(s){const{MsgReactionNotifyList:n}=s,{notificationCenter:g,constants:u}=this._core;n.forEach(E=>pA(this,void 0,void 0,function*(){const{C2CMsgInfo:m,GroupMsgInfo:D,MsgReactionSummary:M}=E,{TinyId:T,MsgClientTime:P,MsgRandom:W}=Object.assign(Object.assign({},m),D),iA=`${T}-${P}-${W}`,EA=this._extractUserIDsFromReactionResults([{ReactionList:M}]),RA=yield this._getUserProfileMap(EA),kA=M.map(xA=>{var LA;const{Reaction:SA,Reaction_Account:OA}=xA,JA=this._generatePartialUserInfo({userIDList:OA,userProfileMap:RA}),ae=OA?xA.Count:0,re=((LA=this._reactionsMap.get(`${iA}-${SA}`))===null||LA===void 0?void 0:LA.reactedByMe)||!1;return this._recordMessageReactionInfo({messageID:iA,reactionID:SA,reactionInfo:{reactionID:SA,totalUserCount:ae,partialUserList:JA}}),{reactionID:SA,totalUserCount:ae,partialUserList:JA,reactedByMyself:re}});g.emitOuterEvent(u.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:u.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:iA,reactionList:kA}})}))}_handleReactionSync(s){var n;const{notificationCenter:g,constants:u}=this._core,{C2CMsgInfo:E={},GroupMsgInfo:m={},Reaction:D,OperateType:M}=s.MsgReactionNotify,{TinyId:T="",MsgClientTime:P=0,MsgRandom:W=0}=Object.assign(Object.assign({},E),m),iA=`${T}-${P}-${W}`,EA=`${iA}-${D}`;if(M===1?this._recordMessageReactedByMe(iA,D):this._removeMyReactionRecord(iA,D),(n=this._reactionsMap.get(EA))===null||n===void 0?void 0:n.reactionID){const RA=this._reactionsMap.get(EA);RA.reactedByMyself=M===1,g.emitOuterEvent(u.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:u.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:iA,reactionList:[RA]}})}}_generatePartialUserInfo({userIDList:s,userProfileMap:n}){const g=[];return s?.forEach(u=>{n.has(u)&&g.push(n.get(u))}),g}_generateMessageID(s){const{messageSequence:n,messageKey:g,messageIDMap:u}=s;return g?u.get(g):u.get(n)}_generateMessageKeyList(s,n){const{constants:g}=this._core,u=s[0],{conversationType:E}=u;let m=[];return E===g.OuterConstant.CONV_C2C?m=s.map(D=>{const{clientSequence:M,random:T,time:P,ID:W}=D,iA=`${M}_${T}_${P}`;return n.set(iA,W),iA}):E===g.OuterConstant.CONV_GROUP&&(m=s.map(D=>{const{ID:M,sequence:T}=D;return n.set(T,M),T})),m}},$a=new class{init(s){this._core=s;const{helper:n,InnerEvent:{MESSAGE_PUSH:g},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:u,GROUP_MESSAGE_READ_RECEIPT:E},notificationCenter:m}=s;n.registerApi({apiName:"sendMessageReadReceipt",context:this}),n.registerApi({apiName:"getMessageReadReceiptList",context:this}),n.registerApi({apiName:"getGroupMessageReadMemberList",context:this}),m.subscribeInnerEvent(g,u,this._handleC2CMessageReadReceipt,this),m.subscribeInnerEvent(g,E,this._handleGroupMessageReadReceipt,this)}sendMessageReadReceipt(s){return pA(this,void 0,void 0,function*(){var n;const{common:g,constants:u}=this._core,E=this._filterValidMessageSendByOther(s);if(E.length===0)throw new g.ChatError({code:u.ERROR_CODE.READ_RECEIPT_MSG_LIST_EMPTY});try{const{conversationType:m}=E[0];return m===u.OuterConstant.CONV_C2C?yield function(D){return pA(this,void 0,void 0,function*(){const{common:M,constants:T}=Us.core,P=D[0].conversationID.replace(T.OuterConstant.CONV_C2C,""),W=D.map(EA=>{const{from:RA,to:kA,sequence:xA,random:LA,time:SA,clientTime:OA}=EA;return{From_Account:RA,To_Account:kA,MsgSeq:xA,MsgRandom:LA,MsgTime:SA,MsgClientTime:OA}}),iA={Peer_Account:P,C2CMsgInfo:W};return M.buildAndSendPacket({servcmd:"openim.c2c_msg_read_receipt",data:iA})})}(E):yield function(D){return pA(this,void 0,void 0,function*(){const{common:M,constants:T}=Us.core,P={GroupId:D[0].conversationID.replace(T.OuterConstant.CONV_GROUP,""),MsgSeqList:D.map(W=>({MsgSeq:W.sequence}))};return M.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_receipt",data:P})})}(E),{code:0,data:{}}}catch(m){const{errorCode:D,errorInfo:M}=m;throw new g.ChatError({code:D,message:M,moreMessage:`peerAccount:${(n=E?.[0])===null||n===void 0?void 0:n.conversationID}`})}})}getMessageReadReceiptList(s){return pA(this,void 0,void 0,function*(){const{common:n,constants:g}=this._core;try{const{conversationType:u}=s[0];if(u===g.OuterConstant.CONV_GROUP){const E=this._filterValidMessageSendByMe(s);if(E?.length>0){const m=yield function(M){return pA(this,void 0,void 0,function*(){const{common:T,constants:P}=Us.core,W={GroupId:M[0].conversationID.replace(P.OuterConstant.CONV_GROUP,""),MsgSeqList:M.map(iA=>({MsgSeq:iA.sequence}))};return T.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt",data:W})})}(E),{GroupMsgReceiptList:D}=m||{};this._updateGroupMessagesReadReceiptInfo({messageList:s,readReceiptList:D})}}return{code:0,data:{messageList:s}}}catch(u){const{errorCode:E,errorInfo:m}=u;throw new n.ChatError({code:E,message:m})}})}getGroupMessageReadMemberList(s){return pA(this,void 0,void 0,function*(){const{constants:n,common:g}=this._core,{message:u,filter:E=kE.READ,cursor:m=""}=s,{conversationID:D,sequence:M,ID:T}=u,P=D.replace(n.OuterConstant.CONV_GROUP,""),W=s.count>=100?100:s.count;try{const iA=yield function(EA){return pA(this,void 0,void 0,function*(){const{sequence:RA,groupID:kA,filter:xA,cursor:LA,count:SA}=EA,OA={MsgSeq:RA,GroupId:kA,Filter:xA,Cursor:LA,Num:SA};return Us.core.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt_detail",data:OA})})}({groupID:P,sequence:M,filter:E,cursor:m,count:W});if(iA){const{Cursor:EA,IsFinish:RA,UnreadList:kA,ReadList:xA}=iA,LA={cursor:EA,isCompleted:RA===1,messageID:T,unreadUserIDList:[],readUserIDList:[]};return E===kE.READ?LA.readUserIDList=xA.map(SA=>SA.Read_Account):E===kE.UNREAD&&(LA.unreadUserIDList=kA.map(SA=>SA.Unread_Account)),{code:0,data:LA}}}catch(iA){const{errorCode:EA,errorInfo:RA}=iA;throw new g.ChatError({code:EA,message:RA})}})}_handleC2CMessageReadReceipt(s){const n=[],{constants:g,helper:u}=this._core,{C2cMsgInfo:E,PeerReadTime:m,Peer_Account:D}=s;if(u.isEmpty(E))return;const M=`${g.OuterConstant.CONV_C2C}${D}`;E?.forEach(T=>{const{TinyId:P,MsgClientTime:W,MsgRandom:iA}=T,EA=`${P}-${W}-${iA}`,RA=_c({conversationID:M,messageID:EA});RA&&!RA.readReceiptInfo.isPeerRead&&(RA.readReceiptInfo.isPeerRead=!0,RA.readReceiptInfo.timestamp=m,n.push({userID:D,messageID:EA,isPeerRead:!0,timestamp:m}))}),this._emitReadReceiptEventIfNeed(n)}_updateGroupMessagesReadReceiptInfo(s){const{messageList:n,readReceiptList:g}=s,u=new Map;n.forEach(E=>{u.set(E.sequence,E)}),g?.forEach(E=>{if(E.Code===0){const{MsgSeq:m,ReadNum:D,UnreadNum:M}=E,T=u.get(m);T&&(T.readReceiptInfo.readCount=D,T.readReceiptInfo.unreadCount=M)}})}_handleGroupMessageReadReceipt(s){const n=[],{constants:g}=this._core,{GroupTips:u}=s;u.forEach(E=>{const{MsgBody:{GroupMsgReceiptList:m},GroupInfo:{GroupId:D}}=E,M=`${g.OuterConstant.CONV_GROUP}${D}`;m?.forEach(T=>{const{TinyId:P,MsgClientTime:W,MsgRandom:iA,ReadNum:EA,UnreadNum:RA}=T,kA=`${P}-${W}-${iA}`,xA=_c({conversationID:M,messageID:kA}),LA={groupID:D,messageID:kA,readCount:0,unreadCount:0};xA&&(typeof EA=="number"&&(xA.readReceiptInfo.readCount=EA,LA.readCount=EA),typeof RA=="number"&&(xA.readReceiptInfo.unreadCount=RA,LA.unreadCount=RA),n.push(LA))})}),this._emitReadReceiptEventIfNeed(n)}_emitReadReceiptEventIfNeed(s){const{notificationCenter:n,OuterEvent:g}=this._core;s.length>0&&n.emitOuterEvent(g.MESSAGE_READ_RECEIPT_RECEIVED,{name:g.MESSAGE_READ_RECEIPT_RECEIVED,data:s})}_filterValidMessageSendByOther(s){return this._filterNeedReadReceiptMessages(s).filter(n=>{const{from:g}=n;return g!==this._core.common.getCurrentUserID()})}_filterValidMessageSendByMe(s){const{OuterConstant:n}=this._core.constants;return this._filterNeedReadReceiptMessages(s).filter(g=>{const{from:u,status:E}=g;return u===this._core.common.getCurrentUserID()&&E===n.MessageStatus.SUCCESS})}_filterNeedReadReceiptMessages(s){return s.filter(n=>n.needReadReceipt===!0)}dispose(){const{InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:n,GROUP_MESSAGE_READ_RECEIPT:g},notificationCenter:u}=this._core;u.unSubscribeInnerEvent(s,n,this._handleC2CMessageReadReceipt,this),u.unSubscribeInnerEvent(s,g,this._handleGroupMessageReadReceipt,this)}};function Au(s,n,g){return pA(this,void 0,void 0,function*(){const{common:{buildAndSendPacket:u}}=Us.core,{from:E,to:m,clientSequence:D,random:M,time:T}=s;return u({servcmd:"openim_msg_ext_http_svc.set_key_values",data:{From_Account:E,To_Account:m,MsgKey:`${D}_${M}_${T}`,OperateType:g,ExtensionList:n}})})}function Fu(s,n,g){return pA(this,void 0,void 0,function*(){const{common:{buildAndSendPacket:u}}=Us.core,{to:E,sequence:m}=s;return u({servcmd:"openim_msg_ext_http_svc.group_set_key_values",data:{GroupId:E,MsgSeq:m,OperateType:g,ExtensionList:n}})})}var Gc=new class{constructor(){this._messageExtensionsMap=new Map,this._extensionsLatestSequenceMap=new Map,this._completedFetchExtensions=new Set}init(s){this._core=s;const{notificationCenter:n,helper:{registerApi:g},InnerEvent:{MESSAGE_PUSH:u,LOGOUT:E},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:m}}=s;g({apiName:"setMessageExtensions",context:this}),g({apiName:"getMessageExtensions",context:this}),g({apiName:"deleteMessageExtensions",context:this}),n.subscribeInnerEvent(u,m,this._handleMessageExtensionsNotify,this),n.subscribeInnerEvent(E,this.reset,this)}setMessageExtensions(s,n){return pA(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("setMessageExtensions");const{constants:{OuterConstant:g},ssoLog:u}=this._core,{ID:E,conversationID:m,sequence:D,time:M,conversationType:T}=s;let P=n;n.length>20&&(P=n.slice(0,20),u.warn("setMessageExtensions","the length of extensions cannot exceed 20"));const W=this._generateServerExtensions(s,P),iA=`convID:${m} messageID:${E} sequence:${D} time:${M} count:${P.length}`;try{let EA;if(T===g.CONV_C2C?EA=yield Au(s,W,kl):T===g.CONV_GROUP&&(EA=yield Fu(s,W,kl)),EA){const{resultList:RA,successCount:kA,failureCount:xA}=this._handleModifyMessageExtensions(s,EA);return{code:0,data:{extensions:RA},successLog:{message:`${iA} successCount:${kA} failCount:${xA}`}}}return{code:0,data:{extensions:[]}}}catch(EA){const{errorCode:RA}=EA;throw new this._core.helper.ChatError({functionName:"setMessageExtensions",code:RA,moreMessage:iA})}})}getMessageExtensions(s){return pA(this,void 0,void 0,function*(){const{utils:{isUndefined:n}}=this._core;this._validateMessageExtensionBusinessCapability("getMessageExtensions");const{conversationID:g,ID:u,sequence:E,time:m}=s,D=`convID:${g} messageID:${u} sequence:${E} time:${m}`;try{let M;this._completedFetchExtensions.has(u)&&(M=this._extensionsLatestSequenceMap.get(u));const T=yield this._fetchMessageExtensions(s,M);return n(M)&&T.length>1&&this._completedFetchExtensions.add(u),{code:0,data:{extensions:T},successLog:{message:D}}}catch(M){const{errorCode:T,errorInfo:P=""}=M||{};throw new this._core.common.ChatError({code:T,message:P,moreMessage:D})}})}deleteMessageExtensions(s,n){return pA(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("deleteMessageExtensions");const{utils:{isEmpty:g},constants:{OuterConstant:u}}=this._core,{conversationType:E,conversationID:m,sequence:D,ID:M,time:T}=s;let P=Ug;const W=[];g(n)||(P=Ll,n?.forEach(RA=>{W.push({key:RA,value:"",seq:0})}));const iA=`convID:${m} messageID:${M} sequence:${D} time:${T} operateType:${P}`,EA=this._generateServerExtensions(s,W);try{let RA;if(E===u.CONV_C2C?RA=yield Au(s,EA,P):E===u.CONV_GROUP&&(RA=yield Fu(s,EA,P)),RA){const{resultList:kA,successCount:xA,failureCount:LA}=this._handleModifyMessageExtensions(s,RA);return{code:0,data:{extensions:kA},successLog:{message:`${iA}successCount:${xA} failCount:${LA}`}}}return{code:0,data:{extensions:[]}}}catch(RA){const{errorCode:kA}=RA;throw new this._core.helper.ChatError({functionName:"deleteMessageExtensions",code:kA,moreMessage:iA})}})}reset(){this._messageExtensionsMap.clear(),this._extensionsLatestSequenceMap.clear(),this._completedFetchExtensions.clear()}dispose(){this.reset();const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:n,LOGOUT:g},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:u}}=this._core;s.unSubscribeInnerEvent(n,u,this._handleMessageExtensionsNotify,this),s.subscribeInnerEvent(g,this.reset,this)}_handleModifyMessageExtensions(s,n){const{ID:g}=s,{Seq:u}=n,E=n.ExtensionList||[],m=[];let D=0,M=0,T=[];return E.forEach(P=>{const{ErrorCode:W,Extension:iA}=P,{Key:EA,Value:RA,Seq:kA}=iA;m.push({code:W,key:EA,value:RA}),W===0?D++:M++,T.push({key:EA,value:RA,seq:kA})}),this._extensionsLatestSequenceMap.set(g,u),T.length>0&&this._updateLocalExtensions(s.ID,T),{resultList:m,successCount:D,failureCount:M}}_updateLocalExtensions(s,n){this._messageExtensionsMap.has(s)||this._messageExtensionsMap.set(s,new Map);const g=this._messageExtensionsMap.get(s);n?.forEach(u=>{const{key:E,seq:m,value:D=""}=u;g?.set(E,{value:D,seq:m})})}_fetchMessageExtensions(s,n){return pA(this,void 0,void 0,function*(){const{constants:{OuterConstant:g},utils:{isEmpty:u}}=this._core;try{let E;const{conversationType:m,ID:D}=s;if(m===g.CONV_C2C?E=yield function(M,T){const{common:{buildAndSendPacket:P}}=Us.core,{from:W,to:iA,clientSequence:EA,random:RA,time:kA}=M;return P({servcmd:"openim_msg_ext_http_svc.get_key_values",data:{From_Account:W,To_Account:iA,MsgKey:`${EA}_${RA}_${kA}`,StartSeq:T}})}(s,n):m===g.CONV_GROUP&&(E=yield function(M,T){const{common:{buildAndSendPacket:P}}=Us.core,{to:W,sequence:iA}=M;return P({servcmd:"openim_msg_ext_http_svc.group_get_key_values",data:{GroupId:W,MsgSeq:iA,StartSeq:T}})}(s,n)),E){const{LatestSeq:M,ClearSeq:T,CompleteFlag:P}=E,W=(E.ExtensionList||[]).map(EA=>({key:EA.Key,value:EA.Value,seq:EA.Seq}));if(this._updateLocalExtensions(D,W),this._clearLocationExtensions(D,T),this._extensionsLatestSequenceMap.set(D,M),P!==1){const EA=W[W.length-1].seq+1;return this._fetchMessageExtensions(s,EA)}const iA=[];if(this._messageExtensionsMap.has(D)){const EA=this._messageExtensionsMap.get(D);EA?.forEach((RA,kA)=>{const{value:xA}=RA;u(xA)||iA.push({key:kA,value:xA})})}return iA}}catch(E){throw E}})}_clearLocationExtensions(s,n){if(!(n<=0)&&this._messageExtensionsMap.has(s)){const g=this._messageExtensionsMap.get(s);g?.forEach((u,E)=>{u.seq<=n&&g.delete(E)})}}_generateServerExtensions(s,n){const{ID:g}=s;if(this._messageExtensionsMap.has(g)){const u=this._messageExtensionsMap.get(g);return n.map(E=>{var m;const{key:D,value:M}=E;let T=0;return u?.has(D)&&(T=(m=u.get(D))===null||m===void 0?void 0:m.seq),{Key:D,Value:M,Seq:T}})}return n.map(u=>({Key:u.key,Value:u.value,Seq:0}))}_validateMessageExtensionBusinessCapability(s){const{helper:n,constants:g}=this._core;if(!n.checkBusinessCapabilityBits(hC))throw new n.ChatError({functionName:s,code:g.ERROR_CODE.NO_USE,replacement1:s})}_handleMessageExtensionsNotify(s){const{SetKVInfo:n,DeleteKVInfo:g,ClearKVInfo:u,MsgOptType:E,TinyId:m,MsgLastSeq:D,ExtensionC2cMsgInfo:M,ExtensionGroupMsgInfo:T}=s?.MsgExtensionNotify||{},P=M||T||{},{MsgClientTime:W,MsgRandom:iA}=P,EA=`${m}-${W}-${iA}`;this._extensionsLatestSequenceMap.set(EA,D),E===kl?this._handleMessageExtensionsUpdated({messageID:EA,updateMessageExtensionsInfo:n}):E===Ll?this._handleMessageExtensionsDeleted({messageID:EA,deleteMessageExtensionsInfo:g}):E===Ug&&this._handleMessageExtensionsCleared({messageID:EA,clearMessageExtensionsInfo:u})}_handleMessageExtensionsUpdated(s){const{notificationCenter:n,OuterEvent:g}=this._core,{messageID:u,updateMessageExtensionsInfo:E=[]}=s,m=[];E.forEach(D=>{const{MsgKeyValue:M=[]}=D,T=M.map(P=>(m.push({key:P.Key,value:P.Value}),{key:P.Key,value:P.Value,seq:P.Seq}));this._updateLocalExtensions(u,T)}),n.emitOuterEvent(g.MESSAGE_EXTENSIONS_UPDATED,{name:g.MESSAGE_EXTENSIONS_UPDATED,data:{messageID:u,extensions:m}})}_handleMessageExtensionsDeleted(s){const{notificationCenter:n,OuterEvent:g}=this._core,{messageID:u,deleteMessageExtensionsInfo:E=[]}=s,m=[];E.forEach(D=>{const{MsgKeyValue:M=[]}=D,T=M.map(P=>(m.push(P.Key),{key:P.Key,seq:P.Seq}));this._updateLocalExtensions(u,T)}),n.emitOuterEvent(g.MESSAGE_EXTENSIONS_DELETED,{name:g.MESSAGE_EXTENSIONS_DELETED,data:{messageID:u,keyList:m}})}_handleMessageExtensionsCleared(s){const{notificationCenter:n,OuterEvent:{MESSAGE_EXTENSIONS_DELETED:g},utils:{isEmpty:u}}=this._core,{messageID:E,clearMessageExtensionsInfo:m=[]}=s,D=[];m.forEach(M=>{const{ClearMsgSeq:T}=M;this._messageExtensionsMap.has(E)&&(this._messageExtensionsMap.get(E)||[]).forEach((P,W)=>{P.seq<=T&&!u(P.value)&&D.push(W)}),this._clearLocationExtensions(E,T)}),n.emitOuterEvent(g,{name:g,data:{messageID:E,keyList:D}})}};const pI={key:"message",required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>{const{constants:{OuterConstant:n}}=Us.core;return s.status!==n.MessageStatus.SUCCESS?"message is not success":s.isSupportExtension===!0||"message is not support extension"}},sl={setMessageExtensions:[pI,{key:"extensions",required:!0,rules:["array"],allowEmpty:!1}],getMessageExtensions:[pI],deleteMessageExtensions:[pI]},nl=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({deleteMessage:[{required:!0,rules:["array"],allowEmpty:!1}],revokeMessage:[{required:!0,rules:["object"],allowEmpty:!1}],resendMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"options",required:!1,rules:["object"],allowEmpty:!1}],getMessageList:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},nextReqMessageID:{required:!1,rules:["string"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}},getMessageListHopping:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},sequence:{required:!1,rules:["number"],allowEmpty:!0},direction:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}},createTextAtMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>{const n=function(g){var u;return typeof g?.text!="string"||typeof g.text=="string"&&((u=g?.text)===null||u===void 0?void 0:u.length)===0?"payload.text is invalid.":!0}(s);return n!==!0?n:!(s?.atUserList&&!Array.isArray(s.atUserList))||"atUserList should be an array or undefind."}}},findMessage:[{required:!0,rules:["string"],allowEmpty:!1}],translateText:{sourceTextList:{required:!0,rules:["array"],allowEmpty:!1},sourceLanguage:{required:!0,rules:["string"],allowEmpty:!1},targetLanguage:{required:!0,rules:["string"],allowEmpty:!1}},createForwardMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!(!s.startsWith("C2C")&&!s.startsWith("GROUP"))||"conversationType is invalid."},payload:{required:!0,rules:["object"],allowEmpty:!1}},createLocationMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>{const{utils:{isString:n,isNumber:g}}=Us.core;return n(s?.description)?g(s?.longitude)?!!g(s?.latitude)||"payload.latitude must be a number.":"payload.longitude must be a number.":"payload.description must be a string."}}}},{addMessageReaction:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"reactionID",required:!0,rules:["string"],allowEmpty:!1}],removeMessageReaction:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"reactionID",required:!0,rules:["string"],allowEmpty:!1}],getMessageReactions:{messageList:{required:!0,rules:["array"],allowEmpty:!1},maxUserCountPerReaction:{required:!1,rules:["number"],allowEmpty:!0,customValidator:s=>typeof s!="number"?"maxUserCountPerReaction is invalid.":!(s<0||s>10)||"maxUserCountPerReaction should between [0, 10]."}},getAllUserListOfMessageReaction:{message:{required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>s.status==="success"||"message is invalid."},reactionID:{required:!0,rules:["string"],allowEmpty:!1},nextSeq:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}}}),{sendMessageReadReceipt:[{required:!0,rules:["array"],allowEmpty:!1}],getMessageReadReceiptList:[{required:!0,rules:["array"],allowEmpty:!1}],getGroupMessageReadMemberList:{message:{required:!0,rules:["object"],allowEmpty:!1},filter:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0},cursor:{required:!1,rules:["string"],allowEmpty:!0}}}),sl),{pinGroupMessage:{groupID:{required:!0,rules:["string"],allowEmpty:!1},message:{required:!0,rules:["object"],allowEmpty:!1},isPinned:{required:!0,rules:["boolean"],allowEmpty:!1}},getPinnedGroupMessageList:[{key:"groupID",required:!0,rules:["string"],allowEmpty:!1}]}),{createQuoteMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"quotedMessage",required:!0,rules:["object"],allowEmpty:!1}]}),xa=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({deleteMessage:!0,revokeMessage:!0,resendMessage:!0,getMessageList:!0,getMessageListHopping:!0,createTextAtMessage:!0,findMessage:!0,translateText:!0,createForwardMessage:!0,createLocationMessage:!0},{addMessageReaction:!0,removeMessageReaction:!0,getMessageReactions:!0,getAllUserListOfMessageReaction:!0}),{sendMessageReadReceipt:!0,getMessageReadReceiptList:!0,getGroupMessageReadMemberList:!0}),{setMessageExtensions:!0,getMessageExtensions:!0,deleteMessageExtensions:!0}),{pinGroupMessage:!0,getPinnedGroupMessageList:!0}),{createQuoteMessage:!0});class FE{constructor(n){this._core=n}deleteMessage(n){return pA(this,void 0,void 0,function*(){const{to:g,messageIdentifiers:u}=n,E={From_Account:this._core.common.getCurrentUserID(),To_Account:g,MsgKeyList:u};return this._core.common.buildAndSendPacket({servcmd:"openim.delete_c2c_msg_ramble",data:E})})}revokeMessage(n){return pA(this,void 0,void 0,function*(){const{to:g,from:u,sequence:E,time:m,random:D}=n,M={MsgInfo:{From_Account:u,To_Account:g,MsgSeq:E,MsgRandom:D,MsgTimeStamp:m}};return this._core.common.buildAndSendPacket({servcmd:"openim.msgwithdraw",data:M})})}}class ra{constructor(n){this._core=n}deleteMessage(n){return pA(this,void 0,void 0,function*(){const{to:g,messageIdentifiers:u}=n,E={GroupId:g,Deleter_Account:this._core.common.getCurrentUserID(),Seqs:u};return this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_ramble_msg_by_seq",data:E})})}revokeMessage(n){return pA(this,void 0,void 0,function*(){const{to:g,sequence:u}=n,E={GroupId:g,MsgSeqList:[{MsgSeq:u}]};return this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_recall",data:E})})}}const Mn=2116;class kr{constructor(n){this._core=n}generateRevokeMessage(n){const{conversationID:g,sequence:u,random:E,tinyID:m,clientTime:D,revokeReason:M,revoker:T}=n;let P={};const{messageDataHandler:W}=this._core.message;return P=W.revokeMessage({conversationID:g,sequence:u,random:E,revoker:T}),P||(P={conversationID:g,sequence:u},m&&D&&E&&(P.ID=`${m}-${D}-${E}`)),P.revoker=T,P.revokeReason=M,P.revokerInfo={userID:T,nick:"",avatar:""},P}updateRevokerInfo(n){return pA(this,void 0,void 0,function*(){const g=n.map(u=>u.revoker);try{const u=yield this._fetchUserInfos(g);u&&n.forEach(E=>{const{revoker:m}=E;u[m]&&(E.revokerInfo.nick=u[m].nick||"",E.revokerInfo.avatar=u[m].avatar||"",E.revokerInfo.userID=m)})}catch(u){console.debug(u)}})}_fetchUserInfos(n){return pA(this,void 0,void 0,function*(){var g,u;const E=yield(g=this._core.user.userProfile)===null||g===void 0?void 0:g.getUserProfile({userIDList:n});return E?.data?(u=E.data)===null||u===void 0?void 0:u.reduce((m,{userID:D,nick:M,avatar:T})=>(m[D]={nick:M||"",avatar:T||""},m),{}):null})}}var rl=new class{constructor(){this._core=null,this._c2cMessageAction=null,this._groupMessageAction=null}init(s){this._core=s,this._groupMessageAction=new ra(s),this._c2cMessageAction=new FE(s),this._messageHelper=new kr(s);const{helper:n}=s;n.registerApi({apiName:"deleteMessage",context:this}),n.registerApi({apiName:"revokeMessage",context:this}),n.registerApi({apiName:"resendMessage",context:this}),n.registerApi({apiName:"findMessage",context:this}),n.registerApi({apiName:"createQuoteMessage",context:this})}deleteMessage(s){return pA(this,void 0,void 0,function*(){let n=[],g=[];const{conversationID:u,conversationType:E}=s[0],m=u.replace(E,"");if(E==="@TIM#SYSTEM")throw new this._core.helper.ChatError({code:Mn});if(s.forEach(D=>{const{conversationID:M,conversationType:T,status:P,_onlineOnlyFlag:W,sequence:iA,random:EA,time:RA}=D||{};if(P==="success"&&M===u&&T===E){if(!W){const kA=T==="C2C"?`${iA}_${EA}_${RA}`:String(iA);n.push(kA)}g.push(D)}}),n.length===0)return this._handleDeleteMessageSuccess(g),{code:0,data:{messageList:g}};n.length>30&&(n=n.slice(0,30),g=g.slice(0,30));try{return E==="C2C"?yield this._c2cMessageAction.deleteMessage({to:m,messageIdentifiers:n}):yield this._groupMessageAction.deleteMessage({to:m,messageIdentifiers:n}),this._handleDeleteMessageSuccess(g),{code:0,data:{messageList:g}}}catch(D){const{utils:{safeStringify:M}}=this._core,{errorCode:T,errorInfo:P}=D;throw new this._core.helper.ChatError({functionName:"deleteMessage",code:T,message:P,moreMessage:`messageIdentifiers: ${M(n)}`})}})}revokeMessage(s){return pA(this,void 0,void 0,function*(){var n;const{conversationType:g,isRevoked:u,ID:E,type:m,from:D,to:M}=s;let T=null;const P=`type:${m} from:${D} to:${M} ID:${E}`;if(g==="@TIM#SYSTEM")throw new this._core.helper.ChatError({message:"system message cannot be revoked"});if(u)throw new this._core.helper.ChatError({message:"message has been revoked",moreMessage:P});try{if(T=g==="C2C"?yield this._c2cMessageAction.revokeMessage(s):yield this._groupMessageAction.revokeMessage(s),T){const{RecallRetList:W}=T,iA=((n=W?.[0])===null||n===void 0?void 0:n.RetCode)||0;if(iA!==0)throw new this._core.helper.ChatError({code:iA,moreMessage:P});return s.isRevoked=!0,yield this._handleRevokeMessageSuccess(s),{code:0,data:{message:s},successLog:{message:P}}}}catch(W){const{errorCode:iA}=W;throw new this._core.helper.ChatError({functionName:"revokeMessage",code:iA,moreMessage:P})}})}resendMessage(s,n){return pA(this,void 0,void 0,function*(){var g,u;return s.isResend=!0,s.status="unSend",(u=(g=this._core)===null||g===void 0?void 0:g.apiMap)===null||u===void 0?void 0:u.sendMessage(s,n)})}findMessage(s){return this._core.message.messageDataHandler.findMessage(s)}createQuoteMessage(s,n){const{ID:g,time:u,sequence:E}=n;return s.quoteInfo={msgID:g,messageTime:u,messageSequence:E},s}_handleDeleteMessageSuccess(s){if(s.length===0)return;const{message:{messageDataHandler:n},common:{isTopic:g},notificationCenter:u,InnerEvent:E}=this._core;s.forEach(D=>{D.isDeleted=!0;const M=n.getLocalMessageList(D.conversationID);M?.forEach(T=>{T.ID===D.ID&&(T.isDeleted=!0)})});const{conversationID:m=""}=s[0];g(m)?u.emitInnerEvent(E.TOPIC_MESSAGE_DELETED,m):u.emitInnerEvent(E.MESSAGE_DELETED,m)}_handleRevokeMessageSuccess(s){return pA(this,void 0,void 0,function*(){var n;const g=(n=this._core.store.get("login"))===null||n===void 0?void 0:n.userId,{conversationID:u,sequence:E,random:m}=s;this._core.message.messageDataHandler.revokeMessage({conversationID:u,sequence:E,random:m,revoker:g}),yield this._messageHelper.updateRevokerInfo([s])})}};class Ul{static parseServerPushElement(n){const{MsgContent:g={}}=n,{Index:u,Data:E}=g;return new Ul({index:u,data:E})}constructor(n){this.type=Vr.MSG_FACE;const{index:g,data:u}=n;this.content={index:g,data:u}}validateBeforeSend(){var n,g;return typeof((n=this.content)===null||n===void 0?void 0:n.index)=="number"&&typeof((g=this.content)===null||g===void 0?void 0:g.data)=="string"?{isValid:!0}:{isValid:!1,error:{message:"content is invalid"}}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},u=g?this.payload:this.content,{index:E,data:m}=u;return{MsgType:this.type,MsgContent:{Index:E,Data:m}}}}class bc{static parseServerPushElement(n){const{MsgContent:g={}}=n,{Desc:u,Longitude:E,Latitude:m}=g;return new bc({description:u,longitude:E,latitude:m})}constructor(n){this.type=Vr.MSG_LOCATION;const{description:g,longitude:u,latitude:E}=n;this.content={description:g,longitude:u,latitude:E}}validateBeforeSend(){return{isValid:!0}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},u=g?this.payload:this.content,{description:E,longitude:m,latitude:D}=u;return{MsgType:this.type,MsgContent:{Desc:E,Longitude:m,Latitude:D}}}}class OE{static parseServerPushElement(n){const{MsgContent:g={}}=n,{StreamMsgID:u,CompatibleText:E,Markdown:m,BinaryData:D,ErrorCode:M,ErrorMsg:T}=g;return new OE({streamMessageID:u,compatibleText:E,markdown:m,binaryData:D,errorCode:M,errorMessage:T})}constructor(n){this.type=Vr.MSG_STREAM,this.content={streamMessageID:"",compatibleText:"",errorCode:0,errorMessage:"",isStreamEnded:!1},this._chunks=[],this._latestIndex=0;const{streamMessageID:g,compatibleText:u,markdown:E,binaryData:m,errorCode:D=0,errorMessage:M="",isStreamEnded:T=!1,chunks:P=[],latestIndex:W=0}=n;this.content.streamMessageID=g,this.content.compatibleText=u,this.content.markdown=E,this.content.binaryData=m,this.content.errorCode=D,this.content.errorMessage=M,this.content.isStreamEnded=T,this.content.chunks=P,this.content.latestIndex=W}updateChunks(n){if(!n||n.length===0)return;const g=n.sort((m,D)=>m.index-D.index),u=this._getMaxRevokedChunkIndex(g);u>=0&&(this._chunks=[],this._latestIndex=u,this._updateContent());const E=this._getValidChunks(g);if(E.length!==0&&(this._mergeAndSortChunks(E),this._chunks.length>0)){const m=this._chunks[this._chunks.length-1];this._latestIndex=m.index,this._updateContent(),this.content.isStreamEnded=m.isLast}}getLatestIndex(){return this._latestIndex}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},u=g?this.payload:this.content,{streamMessageID:E,chunks:m}=u,D=m?.map(M=>({EventType:M.eventType||"data",Index:M.index,Markdown:M.markdown,IsLast:M.isLast}));return{MsgType:this.type,MsgContent:{StreamMsgID:E,Chunks:D}}}validateBeforeSend(){var n,g;return((g=(n=this.content)===null||n===void 0?void 0:n.chunks)===null||g===void 0?void 0:g.length)>0?{isValid:!0}:{isValid:!1,error:{message:"content is invalid"}}}_filterContinuousChunks(n,g){if(n.length===0)return[];const u=[];let E=g;for(const m of n){if(m.index>E)break;m.index===E&&(u.push(m),E++)}return u}_mergeAndSortChunks(n){const g=new Map;this._chunks.forEach(u=>{g.set(u.index,u)}),n.forEach(u=>{g.set(u.index,u)}),this._chunks=Array.from(g.values()).sort((u,E)=>u.index-E.index)}_updateContent(){this.content.markdown=this._chunks.map(g=>g.markdown).join("");const n=this._chunks.map(g=>g.binaryData).filter(g=>g?.length>0);if(n.length===0)this.content.binaryData=new Uint8Array(0);else if(n.length===1)this.content.binaryData=n[0];else{const g=n.reduce((m,D)=>m+D.length,0),u=new Uint8Array(g);let E=0;for(const m of n)u.set(m,E),E+=m.length;this.content.binaryData=u}}_getMaxRevokedChunkIndex(n){let g=-1;for(let u=0;ug&&(g=E.index)}return g}_getValidChunks(n){const g=n.filter(u=>u.eventType===Nc.DATA&&u.index>this._latestIndex);return this._filterContinuousChunks(g,this._latestIndex+1)}}var kc=new class{init(s){this._core=s,s.message.messageFactory.registerElementClass(Vr.MSG_FACE,Ul),s.message.messageFactory.registerElementClass(Vr.MSG_LOCATION,bc),s.message.messageFactory.registerElementClass(Vr.MSG_STREAM,OE),s.helper.registerApi({apiName:"createFaceMessage",context:this}),s.helper.registerApi({apiName:"createTextAtMessage",context:this}),s.helper.registerApi({apiName:"createForwardMessage",context:this}),s.helper.registerApi({apiName:"createLocationMessage",context:this})}createFaceMessage(s){if(!s)return null;const{index:n,data:g}=s?.payload||{},u=new Ul({index:n,data:g}),E=this._core.common.getCurrentUserID(),m=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:E}));return m.setElement(u),m}createTextAtMessage(s){const{atUserList:n}=s?.payload||{},g=this._core.apiMap.createTextMessage(s),{OuterConstant:u}=this._core;if(!g)return null;if(Array.isArray(n)){const E=[],m=[];n.forEach(D=>{D!==u.MSG_AT_ALL?(E.push({GroupAtAllFlag:ch,GroupAt_Account:D}),m.push(D)):(E.push({GroupAtAllFlag:ro}),m.push(u.MSG_AT_ALL))}),g._groupAtInfoList=E,g.atUserList=m}return g}createForwardMessage(s){const{helper:n,OuterConstant:g}=this._core,{to:u,conversationType:E,priority:m,payload:D,needReadReceipt:M,receiverList:T,cloudCustomData:P="",isSupportExtension:W=!1}=s;if(!Array.isArray(D._elements))throw new n.ChatError({functionName:"createForwardMessage",code:2454});if(D.type===g.MSG_GRP_TIP)throw new n.ChatError({functionName:"createForwardMessage",code:2453});const iA=this._core.common.getCurrentUserID(),EA=this._core.message.messageFactory.createMessage({to:u,from:iA,conversationType:E,isPlaceMessage:0,priority:m,payload:D,needReadReceipt:M,isSupportExtension:W,cloudCustomData:P,receiverList:T});return EA.setRelayFlag(!0),EA.setElement(D._elements[0]),EA}createLocationMessage(s){if(!s)return null;const{description:n,longitude:g,latitude:u}=s?.payload||{},E=new bc({description:n,longitude:g,latitude:u}),m=this._core.common.getCurrentUserID(),D=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:m}));return D.setElement(E),D}};let Ou=class{init(s){this._messageHelper=new kr(s),this._core=s;const{notificationCenter:n,InnerEvent:{MESSAGE_PUSH:g},InnerEventSubType:{C2C_REVOKED_MESSAGE:u},helper:{registerWorkflowStep:E},constants:{WORKFLOW_NAME:m,WORKFLOW_STEP:D}}=s;n.subscribeInnerEvent(g,u,this._handleC2CNotifyMessage,this),E(m.SYNC_SERVER_INFO_AFTER_RE_ONLINE,D.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,this._handleC2CRevokeMessagesFromUnreadMessageSync,this)}_handleC2CNotifyMessage(s){const{C2cNotifyMsgArray:n}=s;n?.forEach(g=>{Object.keys(g).includes("WithdrawC2cMsgNotify")&&this._handleC2CRevokeMessage(g)})}_handleC2CRevokeMessage(s){return pA(this,void 0,void 0,function*(){try{const{WithdrawC2cMsgNotify:{C2cWithdrawInfoArray:n}}=s;yield this._parseAndEmitC2CRevokedMessages(n)}catch(n){console.debug(n)}})}_parseAndEmitC2CRevokedMessages(s){return pA(this,void 0,void 0,function*(){const n=[],{notificationCenter:g,OuterEvent:u,common:{getCurrentUserID:E}}=this._core;s.forEach(m=>{var D;const{MsgRand:M,MsgSeq:T,To_Account:P,From_Account:W,RevokerInfo:{Revoker_Account:iA,Revoke_Reason:EA}}=m,RA=E()===W?`C2C${P}`:`C2C${W}`,kA=((D=m?.RevokerInfo)===null||D===void 0?void 0:D.Reason)||EA,xA=this._messageHelper.generateRevokeMessage({conversationID:RA,sequence:T,random:M,revoker:iA,revokeReason:kA});n.push(xA)}),n.length>0&&(yield this._messageHelper.updateRevokerInfo(n),g.emitOuterEvent(u.MESSAGE_REVOKED,{name:u.MESSAGE_REVOKED,data:n}))})}_handleC2CRevokeMessagesFromUnreadMessageSync(s){return pA(this,void 0,void 0,function*(){const{revokedMessageList:n}=s.result;yield this._parseAndEmitC2CRevokedMessages(n)})}dispose(){const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:n},InnerEventSubType:{C2C_REVOKED_MESSAGE:g}}=this._core;s.unSubscribeInnerEvent(n,g,this._handleC2CNotifyMessage,this)}},pC=class{init(s){this._messageHelper=new kr(s),this._core=s;const{notificationCenter:n,InnerEvent:{MESSAGE_PUSH:g},InnerEventSubType:{GROUP_MESSAGE_REVOKED:u}}=s;n.subscribeInnerEvent(g,u,this._handleGroupNotifyMessage,this)}_handleGroupNotifyMessage(s){const{GroupTips:n}=s;n?.forEach(g=>{var u;Array.isArray((u=g?.MsgBody)===null||u===void 0?void 0:u.GroupWithdrawInfoArray)&&this._handleGroupRevokeMessage(g)})}_handleGroupRevokeMessage(s){return pA(this,void 0,void 0,function*(){try{const{RevokerInfo:n,MsgBody:{GroupWithdrawInfoArray:g},GroupInfo:u}=s,E=[],m=[],{notificationCenter:D,OuterEvent:M,utils:{isEmpty:T},common:{isCommunity:P}}=this._core;let W=!1;u&&(W=P({groupID:u.GroupId})||!T(u.TopicId)),g.forEach(iA=>{const{Random:EA,MsgSeq:RA,GroupId:kA,MsgClientTime:xA,TinyId:LA,TopicId:SA,RevokerInfo:{Revoker_Account:OA=n?.Revoker_Account||"",Reason:JA=n?.Reason||""}}=iA,ae=SA?`GROUP${SA}`:`GROUP${kA}`,re=this._messageHelper.generateRevokeMessage({conversationID:ae,sequence:RA,random:EA,tinyID:LA,clientTime:xA,revoker:OA,revokeReason:JA});W?(re.revokerInfo.nick=u.From_AccountNick,re.revokerInfo.avatar=u.From_AccountHeadurl,E.push(re)):m.push(re)}),m.length>0&&(yield this._messageHelper.updateRevokerInfo(m),E.push(...m)),E.length!==0&&D.emitOuterEvent(M.MESSAGE_REVOKED,{name:M.MESSAGE_REVOKED,data:E})}catch(n){console.debug(n)}})}dispose(){const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:n},InnerEventSubType:{GROUP_MESSAGE_REVOKED:g}}=this._core;s.unSubscribeInnerEvent(n,g,this._handleGroupNotifyMessage,this)}};var eu=new class{constructor(){this._c2cMessageReceiver=new Ou,this._groupMessageReceiver=new pC}init(s){this._c2cMessageReceiver.init(s),this._groupMessageReceiver.init(s)}dispose(){this._c2cMessageReceiver.dispose(),this._groupMessageReceiver.dispose()}},lh=new class{constructor(){this._core=null}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"translateText",context:this})}translateText(s){return pA(this,void 0,void 0,function*(){try{const{sourceLanguage:n,sourceTextList:g,targetLanguage:u}=s,E=yield function(m,D){return pA(this,void 0,void 0,function*(){var M,T;const{sourceTextList:P,sourceLanguage:W,targetLanguage:iA}=m,{store:EA,common:RA}=D,kA={SourceText:P,Source:W,Target:iA,FromAccount:(M=EA.get("login"))===null||M===void 0?void 0:M.tinyID,SDKAppID:(T=EA.get("instance"))===null||T===void 0?void 0:T.sdkAppId},xA=yield RA.buildAndSendPacket({servcmd:"im_open_translate.ws_batch_trans_text",data:kA});if(xA){const{CmdErrorCode:LA,TargetText:SA}=xA;return{cmdErrorCode:LA,translatedTextList:SA}}})}({sourceLanguage:n,sourceTextList:g,targetLanguage:u},this._core);if(E){const{cmdErrorCode:{ErrorCode:m,ErrorInfo:D},translatedTextList:M}=E;if(m===0)return{code:0,data:{translatedTextList:M}};throw{errorCode:m,errorInfo:D,message:D}}}catch(n){const{errorCode:g,errorInfo:u}=n||{};throw new this._core.helper.ChatError({functionName:"translateText",code:g,message:u})}})}},Pu=new class{init(s){this._core=s,s.helper.registerApi({apiName:"convertVoiceToText",context:this})}convertVoiceToText(s){return pA(this,void 0,void 0,function*(){var n;const{message:g,language:u=Tc.ZH_PY}=s;let{url:E}=g.payload||{};const m=this._core.common.getCurrentUserID();g.from===m&&g.flow==="out"&&(E=g.payload.remoteAudioUrl),this._validateVoiceFormat(E);const D=((n=QI.exec(E))===null||n===void 0?void 0:n[1])||"mp3",M=BI[u]||XI;try{const T=yield function(P){var W;const{store:iA,common:EA}=Us.core,{url:RA,format:kA,serverLanguageType:xA}=P,LA={BytesUrl:RA,BytesEngServiceType:xA,BytesVoiceFormat:kA,Uint32Sdkappid:(W=iA.get("instance"))===null||W===void 0?void 0:W.sdkAppId,Uint64SourceType:0};return EA.buildAndSendPacket({servcmd:"im_open_speech.ws_sentence_recognition",data:LA})}({url:E,format:D,serverLanguageType:M});if(T){const{CmdErrorCode:P,BytesResult:W}=T;if(P.ErrorCode===0)return{code:0,data:{result:W}};throw{code:P.ErrorCode,message:P.ErrorInfo}}}catch(T){const{code:P,message:W}=T||{};throw new this._core.common.ChatError({functionName:"convertVoiceToText",code:P,message:W})}})}_validateVoiceFormat(s){if(!QI.test(s))throw new this._core.common.ChatError({code:2119})}};class mI{constructor(n){const{constants:g,common:u,utils:E}=Us.core,{CONV_C2C:m,CONV_GROUP:D}=g.OuterConstant,{ID:M,tinyID:T,from:P,to:W,clientTime:iA=u.timeManager.getServerTimeSeconds()||0,random:EA,sequence:RA,cloudCustomData:kA="",nick:xA="",avatar:LA="",clientSequence:SA,conversationType:OA,groupID:JA,_elements:ae,time:re}=n;this.ID=M||`${T}-${iA}-${EA}`,this.messageRandom=EA,this.from=P,this.messageSender=P,this.time=re,this.messageSequence=RA,this.clientSequence=SA||RA,this.clientTime=iA,this.cloudCustomData=kA,this.messageReceiver=W,this.avatar=LA,this.nick=xA;const _i=E.deepCopyWithMethods(ae);_i.forEach(Ti=>{Ti.payload=Ti.content,delete Ti.content}),this.messageBody=_i,M?OA.startsWith(m)?this.receiverUserID=W:OA.startsWith(D)&&(this.receiverGroupID=W):JA?(this.receiverGroupID=JA,this.messageReceiver=JA):W&&(this.receiverUserID=W,this.messageReceiver=W)}transformElementsToServerFormat(){return this.messageBody?Array.isArray(this.messageBody)?this.messageBody.map(n=>n.transformToServerFormat({isMergerMessage:!0})):this.messageBody.transformToServerFormat({isMergerMessage:!0}):null}}class al{static parseServerPushElement(n){const{MsgContent:g}=n,{MsgList:u=[],CompatibleText:E,AbstractList:m,Title:D,PbMsgKey:M,JsonMsgKey:T}=g||{},P=u.map(W=>dr(W));return new al({messageList:P,title:D,abstractList:m,compatibleText:E,pbDownloadKey:M,downloadKey:T})}constructor(n){this.type=Us.core.constants.OuterConstant.MSG_MERGER;const{messageList:g,title:u,abstractList:E,compatibleText:m,pbDownloadKey:D="",downloadKey:M="",version:T=0,layersOverLimit:P=!1}=n,W=[];g.forEach(iA=>{if(iA){const EA=new mI(iA);W.push(EA)}}),this.content={messageList:W,title:u,abstractList:E,compatibleText:m,version:T,downloadKey:M,pbDownloadKey:D,layersOverLimit:P}}validateBeforeSend(){const{isEmpty:n}=Us.core.helper;return n(this.content.messageList)?{isValid:!1,error:{message:"content is invalid"}}:{isValid:!0}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},u=g?this.payload:this.content,{abstractList:E,compatibleText:m,downloadKey:D,layersOverLimit:M,pbDownloadKey:T,title:P,version:W,messageList:iA}=u;return{MsgType:this.type,MsgContent:{AbstractList:E,CompatibleText:m,JsonMsgKey:D,LayersOverLimit:M,PbMsgKey:T,Title:P,Version:W,MsgList:Ac(iA)}}}}var mC=new class{init(s){this._core=s;const{message:n,helper:g,constants:{OuterConstant:u}}=s;n.messageFactory.registerElementClass(u.MSG_MERGER,al),g.registerApi({apiName:"createMergerMessage",context:this}),g.registerApi({apiName:"sendMessage",context:this,matcher:E=>E[0].type===u.MSG_MERGER}),g.registerApi({apiName:"downloadMergerMessage",context:this})}createMergerMessage(s){const{common:n}=this._core;if(!s)return null;const g=new al(s.payload),u=n.getCurrentUserID(),E=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:u}));return E.setRelayFlag(!0),E.setElement(g),E}sendMessage(s,n){return pA(this,void 0,void 0,function*(){var g,u,E;try{const m=function(P){let W="utf-8";Us.core.helper.IN_BROWSER&&document&&(W=document.charset.toLowerCase());let iA,EA=0,RA=0;if(RA=P.length,W==="utf-8"||W==="utf8")for(let kA=0;kA11264){D=this._core.utils.deepCopyWithMethods(s);try{const{JsonMsgKey:P,PbMsgKey:W}=yield function(EA){return pA(this,void 0,void 0,function*(){const{payload:{messageList:RA}}=EA,kA={MsgList:Ac(RA)};return Us.core.common.buildAndSendPacket({servcmd:"im_long_msg.save_relay_json_msg",data:kA})})}(D),{payload:iA}=D;M=new al(Object.assign(Object.assign({},iA),{messageList:[],downloadKey:P,pbDownloadKey:W})),D.setElement(M)}catch(P){console.error(P)}}const{data:{message:T}}=yield(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageSender)===null||E===void 0?void 0:E.sendMessage(D,n);return M&&T.setElement(s._elements),{code:0,data:{message:T}}}catch(m){const{errorCode:D}=m;throw new this._core.helper.ChatError({code:D})}})}downloadMergerMessage(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n}=this._core,g=s.payload,{downloadKey:u,pbDownload:E,type:m,messageList:D}=g,M=Do(g,["downloadKey","pbDownload","type","messageList"]);try{const T=yield function(iA){return pA(this,void 0,void 0,function*(){return Us.core.common.buildAndSendPacket({servcmd:"im_long_msg.get_relay_json_msg",data:{JsonMsgKey:iA}})})}(u),{MsgList:P}=T||{},W=P?.map(iA=>{const EA=dr(iA);return new mI(EA)});return typeof s.isOnlineMessage=="function"?s.setElement({type:s.type,content:Object.assign({messageList:W},M)}):(s.payload.messageList=W,s.payload.downloadKey="",s.payload.pbDownloadKey=""),n.info("downloadMergerMessage",` success downloadKey:${u}`),s}catch(T){const{errorCode:P}=T;throw new this._core.helper.ChatError({functionName:"downloadMergerMessage",code:P,moreMessage:u})}})}},aa=new class{init(s){this._core=s,this._core.helper.registerExperimentalAPI("sendComboMessage",this)}sendComboMessage(s){return pA(this,void 0,void 0,function*(){const{appStore:n,message:g,common:{getCurrentUserID:u},utils:{isArray:E}}=this._core,{GroupId:m,To_Account:D}=s;s.From_Account=s.From_Account||u();let M=null;if(m){M=this._generateGroupMessage(Object.assign(Object.assign({},s),{ToGroupId:m}));const T=n.userStore.getUserProfile(u());M.level=T?.level||0,E(D)&&D.length>0&&(M._receiverList=D)}else D&&(M=this._generateC2CMessage(s));return g.messageSender.sendMessage(M,s)})}_generateC2CMessage(s){const{message:n,OuterConstant:{CONV_C2C:g}}=this._core,u=g,E=n.messageHelper.parseServerPushMessage(s),m=n.messageFactory.createMessage(Object.assign(Object.assign({},E),{conversationType:u,flow:ec.OUT})),{elements:D}=E;return m.setElement(D),m}_generateGroupMessage(s){const{message:n,OuterConstant:{CONV_GROUP:g}}=this._core,u=g,E=n.messageHelper.parseServerGroupMessage(s),m=n.messageFactory.createMessage(Object.assign(Object.assign({},E),{conversationType:u,flow:ec.OUT})),{elements:D}=E;return m.setElement(D),m}},tc=new class{init(s){this._core=s;const{helper:n,notificationCenter:g,InnerEvent:{MESSAGE_PUSH:u},InnerEventSubType:{GROUP_MESSAGE_PINNED:E}}=s;g.subscribeInnerEvent(u,E,this._handleGroupMessagePinned,this),n.registerApi({apiName:"pinGroupMessage",context:this}),n.registerApi({apiName:"getPinnedGroupMessageList",context:this})}pinGroupMessage(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n,common:{isTopic:g},OuterConstant:{GROUP_ID_PREFIX:u},helper:{ChatError:E}}=this._core;let{groupID:m,message:D,isPinned:M}=s;const{sequence:T}=D;try{return yield function(P){return pA(this,void 0,void 0,function*(){const{common:{buildAndSendPacket:W,getCurrentUserID:iA}}=Us.core,{groupID:EA,sequence:RA,isPinned:kA}=P,xA=iA(),LA=kA?"group_open_http_svc.pin_message":"group_open_http_svc.unpin_message",SA={GroupId:EA,MsgSeq:RA};return kA?SA.Pinner_Account=xA:SA.UnPinner_Account=xA,W({servcmd:LA,data:SA})})}({groupID:m,sequence:T,isPinned:M}),{code:0,data:{}}}catch(P){const{errorCode:W,errorInfo:iA}=P||{};throw new E({code:W,message:iA})}})}getPinnedGroupMessageList(s){return pA(this,void 0,void 0,function*(){let n=[];try{const g=yield function(u){return pA(this,void 0,void 0,function*(){const{groupID:E}=u,{common:{buildAndSendPacket:m}}=Us.core;return m({servcmd:"group_open_http_svc.get_pinned_messages",data:{GroupId:E}})})}({groupID:s});if(g){const{PinnedMsgList:u=[]}=g;n=yield this._updatePinnedMessageInfo({serverPinnedMessageList:u,groupID:s})}return{code:0,data:{messageList:n}}}catch(g){throw g}})}_handleGroupMessagePinned(s){const{message:{messageHelper:n,messageFactory:g},notificationCenter:u,OuterEvent:E,OuterConstant:m}=this._core;s.GroupTips.forEach(D=>{const{ToGroupId:M,MsgBody:{PinnedMsg:T,OpType:P,MsgOperatorMemberExtraInfo:W,SdkGroupMessageId:iA}}=D,{UserId:EA,NickName:RA="",ImageUrl:kA=""}=W;let xA=null,LA=!1;if(P===md){LA=!0;const SA=n.parseServerGroupMessage(T);xA=g.createMessage(Object.assign(Object.assign({},SA),{conversationType:m.CONV_GROUP,flow:"in"})),xA.setElement(SA.elements),xA.pinnerInfo={userID:EA,nick:RA,avatar:kA}}else if(P===LE){const{ClientTime:SA,Random:OA,SenderTinyId:JA,ServerTime:ae,MsgSeq:re}=iA;xA={ID:`${JA}-${SA}-${OA}`,sequence:re,random:OA,time:ae,clientTime:SA}}xA&&u.emitOuterEvent(E.PINNED_GROUP_MESSAGE_UPDATED,{name:E.PINNED_GROUP_MESSAGE_UPDATED,data:{groupID:M,message:xA,isPinned:LA,operatorInfo:{userID:EA,nick:RA,avatar:kA}}})})}_findMessageBySequence(s,n){const{message:{messageDataHandler:g}}=this._core;return[...g.getLocalMessageList(s),...g.getSparseMessageList(s)].find(u=>u.sequence===n)}_updatePinnedMessageInfo(s){return pA(this,arguments,void 0,function*({serverPinnedMessageList:n,groupID:g}){const{OuterConstant:{CONV_GROUP:u},utils:{isEmpty:E}}=this._core,m=[],D=[],M=[],T=new Map,P=`${u}${g}`;for(let iA=0;iA{const{sequence:kA}=RA,xA=T.get(kA),LA=iA[xA]||{userID:xA,nick:"",avatar:""};RA.pinnerInfo=LA}),m.sort((RA,kA)=>RA.sequence-kA.sequence),m}return[]})}_fetchPinnedMessageInfo(s){return pA(this,void 0,void 0,function*(){var n,g;const{message:{messageHistory:u},user:{userProfile:E},utils:{isArray:m}}=this._core,{conversationID:D,messageSequenceList:M,pinnerIDList:T}=s,P=yield Promise.all([this._fetchMessageBySequence({conversationID:D,messageSequenceList:M}),E?.getUserProfile({userIDList:T})]);if(m(P)){const W={};return(((n=P[1])===null||n===void 0?void 0:n.data)||[]).forEach(iA=>{const{userID:EA,nick:RA="",avatar:kA=""}=iA;W[EA]={userID:EA,nick:RA,avatar:kA}}),{messageList:((g=P[0])===null||g===void 0?void 0:g.messageList)||[],pinnerInfoMap:W}}})}_fetchMessageBySequence(s){return pA(this,void 0,void 0,function*(){const{utils:{isEmpty:n},message:{messageHistory:g}}=this._core,{conversationID:u,messageSequenceList:E}=s;return n(E)?[]:g.getGroupRoamingMessagesByAnchor({conversationID:u,messageSequenceList:E,getType:3})})}};class lg{constructor(n){this.eventType=Nc.DATA,this.index=0,this.markdown="",this.isLast=!1,this.binaryData=null;const{EventType:g,Index:u,Markdown:E,IsLast:m,BinaryData:D}=n;this.eventType=g,this.index=u,this.markdown=E,this.isLast=m,this.binaryData=D}}var fI=new class{constructor(){this._messageMap=new Map,this._retryCountMap=new Map}init(s){this._core=s;const{notificationCenter:n,OuterEvent:{MESSAGE_RECEIVED:g},InnerEvent:{HISTORY_MESSAGE_FETCHED:u},common:{workflowManager:E},constants:{WORKFLOW_NAME:m,WORKFLOW_STEP:D}}=s;n.subscribeInnerEvent(lo,this._handleStreamMessageChunkPush,this),n.subscribeOuterEvent(g,this._handleMessageReceived,this),n.subscribeInnerEvent(u,this.processHistoryMessage,this),E.registerWorkflowStep(m.SYNC_SERVER_INFO_AFTER_RE_ONLINE,D.STREAM_MESSAGE_RECOVER,this._recoverStreamMessage,this)}processHistoryMessage(s){const{utils:{isEmpty:n,safeStringify:g},ssoLog:u}=this._core;try{s?.forEach(E=>{var m;if(this._isValidStreamMessage(E)){const D=(m=E?._elements)===null||m===void 0?void 0:m[0],{streamMessageID:M,markdown:T,binaryData:P}=D?.content||{};n(T)&&n(P)?(this._messageMap.set(M,E),this._fetchStreamMessageChunks(E)):D.content.isStreamEnded=!0}})}catch(E){u.error("processHistoryMessage.error",g(E))}}_handleMessageReceived(s){const n=s.data;n?.forEach(g=>{var u,E;if(this._isValidStreamMessage(g)){const{streamMessageID:m}=((E=(u=g?._elements)===null||u===void 0?void 0:u[0])===null||E===void 0?void 0:E.content)||{};m&&(this._messageMap.set(m,g),this._fetchStreamMessageChunks(g))}})}_isValidStreamMessage(s){var n,g;const{utils:{isEmpty:u}}=this._core,{streamMessageID:E}=((g=(n=s?._elements)===null||n===void 0?void 0:n[0])===null||g===void 0?void 0:g.content)||{};return s.type===Vr.MSG_STREAM&&!u(E)}_fetchStreamMessageChunks(s){return pA(this,void 0,void 0,function*(){var n,g;const{constants:{ERROR_CODE:u},ssoLog:E,utils:{safeStringify:m}}=this._core,D=(n=s._elements)===null||n===void 0?void 0:n[0],M=(g=D?.content)===null||g===void 0?void 0:g.streamMessageID;try{const{from:T,to:P}=s,W=D.getLatestIndex();if(D.content.isStreamEnded)return;const iA=yield function(EA){return pA(this,void 0,void 0,function*(){const{from:RA,to:kA,streamMessageID:xA,index:LA}=EA,SA={From_Account:RA,To_Account:kA,StreamMsgID:xA,AckIndex:LA};return Us.core.common.buildAndSendPacket({servcmd:"StreamMsg.GetStreamHttp",data:SA,timeout:5e3})})}({from:T,to:P,streamMessageID:M,index:W});if(iA){const{ErrorCode:EA,ErrorInfo:RA}=iA;if(EA!==0)throw D.content.errorCode=EA,D.content.errorMessage=RA,{errorCode:EA,errorMessage:RA}}}catch(T){if(T.errorCode===u.NETWORK_TIMEOUT&&this._shouldRetryFetch(M)){const P=this._retryCountMap.get(M)||0;E.debug("_fetchStreamMessageChunks.timeout",`error: ${m(T)} retried: ${P}`),this._retryCountMap.set(M,P+1),this._fetchStreamMessageChunks(s)}else E.error("_fetchStreamMessageChunks.error",m(T))}})}_shouldRetryFetch(s){const{utils:{isNumber:n}}=this._core;if(!this._retryCountMap.has(s))return this._retryCountMap.set(s,1),!0;const g=this._retryCountMap.get(s);return!!(n(g)&&g<=3)}_onStreamEnded(s,n,g){const{ssoLog:u}=this._core;g.content.isStreamEnded=!0,g.stopReason=n,this._messageMap.delete(s),u.debug("_onStreamEnded",`streamMessage end, StopReason: ${n}`)}_handleStreamMessageChunkPush(s){var n;const{ssoLog:g}=this._core,{StopReason:u,Chunks:E,StreamID:m}=s?.body||{},D=this._messageMap.get(m);if(!D)return void g.warn(`_handleStreamMessageChunkPush, unfounded message: ${m}`);const M=(n=D._elements)===null||n===void 0?void 0:n[0];if(M&&this._validateExpectedChunk(M,E)){if(E.length>0){const T=E.map(P=>new lg(P));M.updateChunks(T)}this._emitMessageModify(D),function(T,P){pA(this,void 0,void 0,function*(){const{common:{generateProtocolData:W},utils:{safeStringify:iA},ssoLog:EA,channel:RA}=Us.core,kA={StreamMsgID:T,AckIndex:P};try{const xA=W({servcmd:"StreamMsg.AckHttp",data:kA});RA.sendPacket(xA)}catch(xA){EA.debug("sendStreamChunkAck",iA(xA))}})}(m,M.getLatestIndex()),M.content.isStreamEnded&&this._onStreamEnded(m,u,M)}}_emitMessageModify(s){const{notificationCenter:n,OuterEvent:{MESSAGE_MODIFIED:g}}=this._core;n.emitOuterEvent(g,{name:g,data:[s]})}_validateExpectedChunk(s,n){const g=s.getLatestIndex()+1;let u=!1;for(let E=0;Em.Index).join(", ")}]`),!1}return!0}_recoverStreamMessage(){this._retryCountMap.clear();const{ssoLog:s,utils:{safeStringify:n}}=this._core;try{const g=Array.from(this._messageMap.entries());for(let u=Math.max(0,g.length-300);u{const LA=this._getResponseBody(kA,E,iA&&EA),SA=this._buildResponse(kA,LA);if(kA.status===200)n(null,SA);else{if(EA&&!RA.includes(EA))return s.url=this._domainName2IP(RA,EA),s.uploadByIP=!0,this.request(s,n);n({code:kA.status,message:JSON.stringify(kA.responseText)},SA)}},kA.onerror=()=>{const LA=this._getResponseBody(kA,E,iA&&EA),SA=this._buildResponse(kA,LA),OA={code:kA.status,message:kA.status===0?"CORS blocked or network error":JSON.stringify(kA.responseText)};n(OA,SA)},s.onProgress&&kA.upload&&(kA.upload.onprogress=LA=>{const{total:SA,loaded:OA}=LA,JA=Math.min(Math.floor(100*OA/SA),100);s.onProgress({total:SA,loaded:OA,percent:JA/100})}),kA.send(P),kA})}_buildResponse(s,n){const g={};return s.getAllResponseHeaders().trim().split(`
+`).forEach(u=>{if(u){const[E,m]=u.split(":").map(D=>D.trim());g[E.toLowerCase()]=m}}),{statusCode:s.status,statusMessage:s.statusText,headers:g,data:n}}_getResponseBody(s,n,g){return s.status===200&&n?{location:n,uploadIP:g}:{response:s.responseText,uploadIP:g}}_queryString(s,n="&",g="="){var u;const{isEmpty:E,isPlainObject:m}=(u=this._core)===null||u===void 0?void 0:u.utils;return E(s)?"":m(s)?Object.keys(s).map(D=>{const M=encodeURIComponent(D)+g;return Array.isArray(s[D])?s[D].map(T=>M+encodeURIComponent(T)).join(n):M+encodeURIComponent(s[D])}).filter(Boolean).join(n):void 0}_domainName2IP(s,n){return s.replace(/^http(s)?:\/\/(.*?)\//,`https://${n}/`)}};const Yu=["unknown","image","video","audio","log"];var yI=new class{init(s){this._core=s}request(s,n){var g;const{MINI_APP_NAMESPACE:u,IN_ALIPAY_MINI_APP:E,isUniIOSApp:m}=(g=this._core)===null||g===void 0?void 0:g.utils,{resources:D="",headers:M={},url:T,downloadUrl:P=""}=s;let W=T,iA=null;const EA=P?P.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/):null;if(!EA)return void console.warn("message Invalid download URL format");const RA=decodeURIComponent(EA[3]),kA=RA.includes("?")?RA.split("?")[0]:RA||"",xA={key:s.fileKey||kA,success_action_status:200,"Content-Type":""},LA={};if(m()){const[OA,JA]=T.split("?sign=");JA&&(W=`${OA}?sign=${encodeURIComponent(JA)}`,LA.sign=decodeURIComponent(JA),LA.signature=decodeURIComponent(JA))}let SA={url:W,header:M,name:"file",filePath:D,formData:Object.assign(Object.assign({},xA),LA),timeout:s.timeout||3e5};if(E){const{name:OA}=SA,JA=Do(SA,["name"]);SA=Object.assign(Object.assign({},JA),{fileName:"file",fileType:s.fileType?Yu[s.fileType]:"image"})}return iA=u.uploadFile(Object.assign(Object.assign({},SA),{success:OA=>{this._handleResponse({response:OA,downloadUrl:P,callback:n})},fail:OA=>{this._handleResponse({response:OA,downloadUrl:P,callback:n})}})),iA.onProgressUpdate&&iA.onProgressUpdate(OA=>{s.onProgress&&s.onProgress({total:OA.totalBytesExpectedToSend||0,loaded:OA.totalBytesSent||0,percent:OA.progress?Math.floor(OA.progress)/100:0})}),iA}_handleResponse(s){const{downloadUrl:n,response:g,callback:u}=s,E={};if(g.header)for(const D in g.header)g.header.hasOwnProperty(D)&&(E[D.toLowerCase()]=g.header[D]);const m=+g.statusCode;m===200?u(null,{statusCode:m,headers:E,data:Object.assign(Object.assign({},g.data),{location:n})}):u({code:m,message:JSON.stringify(g.data)},{statusCode:m,headers:E,data:void 0})}};function gl(s){return function(n){return Object.prototype.toString.call(n).match(/^\[object (.*)\]$/)[1].toLowerCase()}(s)==="file"}function Lr(s){const n=s||99999999;return Math.round(Math.random()*n)}function Ur(s,n=!0,g=!0){const u=Date.now();return n?g?u-s+" ms":`${Math.round((u-s)/1e3)} s`:g?u-s:Math.round((u-s)/1e3)}function Ig(s){return`${Array.from({length:8},()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1)).join("")}-${s}`}function ar(s,n){return Math.round(Number(s)*10**n)/10**n}function wr(s){return s<=1048576?`${ar(s/1024,1)}KB/s`:`${ar(s/1048576,1)}MB/s`}const ic="TIMImageElem",Fg="TIMSoundElem",Ya="TIMFileElem",Fl="TIMVideoFileElem",ha="RichMediaMessagePlugin",DI=["rich.my-imcloud.com","imrich.qcloud.com"],tu=1,Ba=2,cl=3,xE=255;var iu;(function(s){s.UNSENT="unSend",s.SUCCESS="success",s.FAIL="fail"})(iu||(iu={}));const YE={wechat:/^(wxfile:\/\/tmp_|http:\/\/temp\/|cloud:\/\/temp-)/,alipay:/^(https:\/\/resource\/|alipayfile:\/\/tmp\/)/,baidu:/^(http:\/\/tmp\/|swanfile:\/\/tmp_)/,bytedance:/^(ttfile:\/\/tmp_|\/(var|tmp)\/|tttemp:\/\/)/,qq:/^(qqfile:\/\/tmp_|http:\/\/qtemp\/)/},Jr=Symbol("isCustomUpload");var ou,Ot=new class{init(s){this._core=s}addAuthToUrl(s=""){if(this._isMiniProgramTempFile(s))return s;const n=function(g){return g?g.startsWith("https://")?g:g.startsWith("http://")?g.replace("http://","https://"):g:""}(s);return this.processResourceUrl(n)}removeAuthToUrl(s){return function(n,g){const[u,E]=n.split("?");if(!E)return u;const m=E.split("&").reduce((M,T)=>{const[P,W]=T.split("=");return P&&P!==g&&(M[P]=W||""),M},{}),D=Object.keys(m).map(M=>`${M}${m[M]?`=${m[M]}`:""}`).join("&");return D?`${u}?${D}`:u}(s,"authKey")}_isMiniProgramTempFile(s){return!!this.getPlatformFlags().IN_MINI_APP&&Object.values(YE).some(n=>n.test(s))}extractFileFromInput(s){const{utils:{isArray:n}}=this._core;return gl(s)?s:function(g){if(typeof g!="object"||g===null)return!1;const u=Object.getPrototypeOf(g);if(u===null)return!0;let E=u;for(;Object.getPrototypeOf(E)!==null;)E=Object.getPrototypeOf(E);return u===E}(s)&&typeof uni<"u"?n(s.tempFiles)&&s.tempFiles.length>0?s.tempFiles[0]:n(s.files)?s.files[0]:s.tempFile?s.tempFile:null:s instanceof HTMLInputElement&&s.files&&s.files.length>0?s.files[0]:null}probeImageWidthHeight(s){return pA(this,void 0,void 0,function*(){var n;const{IN_MINI_APP:g,IN_BROWSER:u}=((n=this._core)===null||n===void 0?void 0:n.utils)||{};return this._shouldSkipProbing()?{width:0,height:0}:u?this._probeImageDimensionsWeb(s):g?this._probeImageDimensionsMiniApp(s):void 0})}isSimpleCos(){var s;const n=((s=this._core)===null||s===void 0?void 0:s.store.get("cloudConfig"))||{},{simple_cos:g}=n;return g!=="0"}getFileDNList(){var s;let n=DI;const g=((s=this._core)===null||s===void 0?void 0:s.store.get("cloudConfig"))||{},{file_dn_list:u}=g;if(u===void 0)return n;try{JSON.parse(u).forEach(E=>{n.includes(E)||n.push(E)})}catch(E){console.warn(E),n=DI}return n}getPlatform(){var s;return(s=this._core)===null||s===void 0?void 0:s.utils.platform}generateUUID(s,n){var g;let u=`${this.getSDKAppID()}-${this.getCurrentUserID()}-${(g=this._core)===null||g===void 0?void 0:g.utils.randomString()}`;if(n)return`${u}.${n}`;const E=s.name||s.value||s.url||s.tempFilePath,m=E&&E.slice(E.lastIndexOf(".")+1);return m&&(u=`${u}.${m}`),u}processResourceUrl(s){if(!s)return"";let n=s;const g=this.getFileDownloadProxy(),u=this.getAuthKey(),E=this.getFileDNList();return g&&(s.startsWith("http://")?n=s.replace(/^http:\/\/[^/]+/,g):s.startsWith("https://")&&(n=s.replace(/^https:\/\/[^/]+/,g))),u&&n.indexOf("authKey=")===-1&&function(D,M){let T=!1;if(D){const P=D.match(/:\/\/([0-9]?\.)?(.[^/:]+)/),W=P&&P[2]||"";if(W.includes("rich-dev"))return!0;for(let iA=0;iA-1?`${n}&authKey=${u}`:`${n}?authKey=${u}`),n}getCurrentUserID(){var s,n;return(n=(s=this._core)===null||s===void 0?void 0:s.store.get("login"))===null||n===void 0?void 0:n.userId}getSDKAppID(){var s,n;return(n=(s=this._core)===null||s===void 0?void 0:s.store.get("instance"))===null||n===void 0?void 0:n.sdkAppId}getFileDownloadProxy(){var s,n;return((n=(s=this._core)===null||s===void 0?void 0:s.store.get("instance"))===null||n===void 0?void 0:n.fileDownloadProxy)||""}getFileUploadProxy(){var s,n;return((n=(s=this._core)===null||s===void 0?void 0:s.store.get("instance"))===null||n===void 0?void 0:n.fileUploadProxy)||""}getAuthKey(){var s,n;return((n=(s=this._core)===null||s===void 0?void 0:s.store.get("login"))===null||n===void 0?void 0:n.authKey)||""}isPrivateNetWork(){var s,n;return(n=(s=this._core)===null||s===void 0?void 0:s.store.get("instance"))===null||n===void 0?void 0:n.proxyServer}getPlatformFlags(){var s;const{IN_BROWSER:n,IN_MINI_APP:g,IN_RN_APP:u,IN_UNI_NATIVE_APP:E}=(s=this._core)===null||s===void 0?void 0:s.utils;return{IN_BROWSER:n,IN_MINI_APP:g,IN_RN_APP:u,IN_UNI_NATIVE_APP:E}}isEmpty(s){var n;const{isEmpty:g}=(n=this._core)===null||n===void 0?void 0:n.utils;return g(s)}generateURL(s,n){const{needAddAuthToUrl:g=!0}=n||{};return g?this.addAuthToUrl(s):s}_probeImageDimensionsMiniApp(s){var n;const{MINI_APP_NAMESPACE:g}=((n=this._core)===null||n===void 0?void 0:n.utils)||{};return new Promise(u=>{g.getImageInfo({src:s,success:E=>u({width:E.width,height:E.height}),fail:()=>u({width:0,height:0})})})}_shouldSkipProbing(){var s;const{IN_RN_APP:n,IS_IE:g,IE_VERSION:u,IN_WX_MINI_GAME:E}=((s=this._core)===null||s===void 0?void 0:s.utils)||{};return n||g&&u===9||E}_probeImageDimensionsWeb(s){return new Promise(n=>{const g=new Image,u=()=>{g.onload=null,g.onerror=null,g.src=""};g.onload=()=>{n({width:g.width,height:g.height}),u()},g.onerror=()=>{n({width:0,height:0}),u()},g.src=s})}},Vu={exports:{}},Ju=(ou||(ou=1,function(s){s.exports=function(n){var g=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];function u(LA,SA){var OA=LA[0],JA=LA[1],ae=LA[2],re=LA[3];JA=((JA+=((ae=((ae+=((re=((re+=((OA=((OA+=(JA&ae|~JA&re)+SA[0]-680876936|0)<<7|OA>>>25)+JA|0)&JA|~OA&ae)+SA[1]-389564586|0)<<12|re>>>20)+OA|0)&OA|~re&JA)+SA[2]+606105819|0)<<17|ae>>>15)+re|0)&re|~ae&OA)+SA[3]-1044525330|0)<<22|JA>>>10)+ae|0,JA=((JA+=((ae=((ae+=((re=((re+=((OA=((OA+=(JA&ae|~JA&re)+SA[4]-176418897|0)<<7|OA>>>25)+JA|0)&JA|~OA&ae)+SA[5]+1200080426|0)<<12|re>>>20)+OA|0)&OA|~re&JA)+SA[6]-1473231341|0)<<17|ae>>>15)+re|0)&re|~ae&OA)+SA[7]-45705983|0)<<22|JA>>>10)+ae|0,JA=((JA+=((ae=((ae+=((re=((re+=((OA=((OA+=(JA&ae|~JA&re)+SA[8]+1770035416|0)<<7|OA>>>25)+JA|0)&JA|~OA&ae)+SA[9]-1958414417|0)<<12|re>>>20)+OA|0)&OA|~re&JA)+SA[10]-42063|0)<<17|ae>>>15)+re|0)&re|~ae&OA)+SA[11]-1990404162|0)<<22|JA>>>10)+ae|0,JA=((JA+=((ae=((ae+=((re=((re+=((OA=((OA+=(JA&ae|~JA&re)+SA[12]+1804603682|0)<<7|OA>>>25)+JA|0)&JA|~OA&ae)+SA[13]-40341101|0)<<12|re>>>20)+OA|0)&OA|~re&JA)+SA[14]-1502002290|0)<<17|ae>>>15)+re|0)&re|~ae&OA)+SA[15]+1236535329|0)<<22|JA>>>10)+ae|0,JA=((JA+=((ae=((ae+=((re=((re+=((OA=((OA+=(JA&re|ae&~re)+SA[1]-165796510|0)<<5|OA>>>27)+JA|0)&ae|JA&~ae)+SA[6]-1069501632|0)<<9|re>>>23)+OA|0)&JA|OA&~JA)+SA[11]+643717713|0)<<14|ae>>>18)+re|0)&OA|re&~OA)+SA[0]-373897302|0)<<20|JA>>>12)+ae|0,JA=((JA+=((ae=((ae+=((re=((re+=((OA=((OA+=(JA&re|ae&~re)+SA[5]-701558691|0)<<5|OA>>>27)+JA|0)&ae|JA&~ae)+SA[10]+38016083|0)<<9|re>>>23)+OA|0)&JA|OA&~JA)+SA[15]-660478335|0)<<14|ae>>>18)+re|0)&OA|re&~OA)+SA[4]-405537848|0)<<20|JA>>>12)+ae|0,JA=((JA+=((ae=((ae+=((re=((re+=((OA=((OA+=(JA&re|ae&~re)+SA[9]+568446438|0)<<5|OA>>>27)+JA|0)&ae|JA&~ae)+SA[14]-1019803690|0)<<9|re>>>23)+OA|0)&JA|OA&~JA)+SA[3]-187363961|0)<<14|ae>>>18)+re|0)&OA|re&~OA)+SA[8]+1163531501|0)<<20|JA>>>12)+ae|0,JA=((JA+=((ae=((ae+=((re=((re+=((OA=((OA+=(JA&re|ae&~re)+SA[13]-1444681467|0)<<5|OA>>>27)+JA|0)&ae|JA&~ae)+SA[2]-51403784|0)<<9|re>>>23)+OA|0)&JA|OA&~JA)+SA[7]+1735328473|0)<<14|ae>>>18)+re|0)&OA|re&~OA)+SA[12]-1926607734|0)<<20|JA>>>12)+ae|0,JA=((JA+=((ae=((ae+=((re=((re+=((OA=((OA+=(JA^ae^re)+SA[5]-378558|0)<<4|OA>>>28)+JA|0)^JA^ae)+SA[8]-2022574463|0)<<11|re>>>21)+OA|0)^OA^JA)+SA[11]+1839030562|0)<<16|ae>>>16)+re|0)^re^OA)+SA[14]-35309556|0)<<23|JA>>>9)+ae|0,JA=((JA+=((ae=((ae+=((re=((re+=((OA=((OA+=(JA^ae^re)+SA[1]-1530992060|0)<<4|OA>>>28)+JA|0)^JA^ae)+SA[4]+1272893353|0)<<11|re>>>21)+OA|0)^OA^JA)+SA[7]-155497632|0)<<16|ae>>>16)+re|0)^re^OA)+SA[10]-1094730640|0)<<23|JA>>>9)+ae|0,JA=((JA+=((ae=((ae+=((re=((re+=((OA=((OA+=(JA^ae^re)+SA[13]+681279174|0)<<4|OA>>>28)+JA|0)^JA^ae)+SA[0]-358537222|0)<<11|re>>>21)+OA|0)^OA^JA)+SA[3]-722521979|0)<<16|ae>>>16)+re|0)^re^OA)+SA[6]+76029189|0)<<23|JA>>>9)+ae|0,JA=((JA+=((ae=((ae+=((re=((re+=((OA=((OA+=(JA^ae^re)+SA[9]-640364487|0)<<4|OA>>>28)+JA|0)^JA^ae)+SA[12]-421815835|0)<<11|re>>>21)+OA|0)^OA^JA)+SA[15]+530742520|0)<<16|ae>>>16)+re|0)^re^OA)+SA[2]-995338651|0)<<23|JA>>>9)+ae|0,JA=((JA+=((re=((re+=(JA^((OA=((OA+=(ae^(JA|~re))+SA[0]-198630844|0)<<6|OA>>>26)+JA|0)|~ae))+SA[7]+1126891415|0)<<10|re>>>22)+OA|0)^((ae=((ae+=(OA^(re|~JA))+SA[14]-1416354905|0)<<15|ae>>>17)+re|0)|~OA))+SA[5]-57434055|0)<<21|JA>>>11)+ae|0,JA=((JA+=((re=((re+=(JA^((OA=((OA+=(ae^(JA|~re))+SA[12]+1700485571|0)<<6|OA>>>26)+JA|0)|~ae))+SA[3]-1894986606|0)<<10|re>>>22)+OA|0)^((ae=((ae+=(OA^(re|~JA))+SA[10]-1051523|0)<<15|ae>>>17)+re|0)|~OA))+SA[1]-2054922799|0)<<21|JA>>>11)+ae|0,JA=((JA+=((re=((re+=(JA^((OA=((OA+=(ae^(JA|~re))+SA[8]+1873313359|0)<<6|OA>>>26)+JA|0)|~ae))+SA[15]-30611744|0)<<10|re>>>22)+OA|0)^((ae=((ae+=(OA^(re|~JA))+SA[6]-1560198380|0)<<15|ae>>>17)+re|0)|~OA))+SA[13]+1309151649|0)<<21|JA>>>11)+ae|0,JA=((JA+=((re=((re+=(JA^((OA=((OA+=(ae^(JA|~re))+SA[4]-145523070|0)<<6|OA>>>26)+JA|0)|~ae))+SA[11]-1120210379|0)<<10|re>>>22)+OA|0)^((ae=((ae+=(OA^(re|~JA))+SA[2]+718787259|0)<<15|ae>>>17)+re|0)|~OA))+SA[9]-343485551|0)<<21|JA>>>11)+ae|0,LA[0]=OA+LA[0]|0,LA[1]=JA+LA[1]|0,LA[2]=ae+LA[2]|0,LA[3]=re+LA[3]|0}function E(LA){var SA,OA=[];for(SA=0;SA<64;SA+=4)OA[SA>>2]=LA.charCodeAt(SA)+(LA.charCodeAt(SA+1)<<8)+(LA.charCodeAt(SA+2)<<16)+(LA.charCodeAt(SA+3)<<24);return OA}function m(LA){var SA,OA=[];for(SA=0;SA<64;SA+=4)OA[SA>>2]=LA[SA]+(LA[SA+1]<<8)+(LA[SA+2]<<16)+(LA[SA+3]<<24);return OA}function D(LA){var SA,OA,JA,ae,re,_i,Ti=LA.length,Lt=[1732584193,-271733879,-1732584194,271733878];for(SA=64;SA<=Ti;SA+=64)u(Lt,E(LA.substring(SA-64,SA)));for(OA=(LA=LA.substring(SA-64)).length,JA=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],SA=0;SA>2]|=LA.charCodeAt(SA)<<(SA%4<<3);if(JA[SA>>2]|=128<<(SA%4<<3),SA>55)for(u(Lt,JA),SA=0;SA<16;SA+=1)JA[SA]=0;return ae=(ae=8*Ti).toString(16).match(/(.*?)(.{0,8})$/),re=parseInt(ae[2],16),_i=parseInt(ae[1],16)||0,JA[14]=re,JA[15]=_i,u(Lt,JA),Lt}function M(LA){var SA,OA,JA,ae,re,_i,Ti=LA.length,Lt=[1732584193,-271733879,-1732584194,271733878];for(SA=64;SA<=Ti;SA+=64)u(Lt,m(LA.subarray(SA-64,SA)));for(OA=(LA=SA-64>2]|=LA[SA]<<(SA%4<<3);if(JA[SA>>2]|=128<<(SA%4<<3),SA>55)for(u(Lt,JA),SA=0;SA<16;SA+=1)JA[SA]=0;return ae=(ae=8*Ti).toString(16).match(/(.*?)(.{0,8})$/),re=parseInt(ae[2],16),_i=parseInt(ae[1],16)||0,JA[14]=re,JA[15]=_i,u(Lt,JA),Lt}function T(LA){var SA,OA="";for(SA=0;SA<4;SA+=1)OA+=g[LA>>8*SA+4&15]+g[LA>>8*SA&15];return OA}function P(LA){var SA;for(SA=0;SA"u"||ArrayBuffer.prototype.slice||function(){function LA(SA,OA){return(SA=0|SA||0)<0?Math.max(SA+OA,0):Math.min(SA,OA)}ArrayBuffer.prototype.slice=function(SA,OA){var JA,ae,re,_i,Ti=this.byteLength,Lt=LA(SA,Ti),Ni=Ti;return OA!==n&&(Ni=LA(OA,Ti)),Lt>Ni?new ArrayBuffer(0):(JA=Ni-Lt,ae=new ArrayBuffer(JA),re=new Uint8Array(ae),_i=new Uint8Array(this,Lt,JA),re.set(_i),ae)}}(),xA.prototype.append=function(LA){return this.appendBinary(W(LA)),this},xA.prototype.appendBinary=function(LA){this._buff+=LA,this._length+=LA.length;var SA,OA=this._buff.length;for(SA=64;SA<=OA;SA+=64)u(this._hash,E(this._buff.substring(SA-64,SA)));return this._buff=this._buff.substring(SA-64),this},xA.prototype.end=function(LA){var SA,OA,JA=this._buff,ae=JA.length,re=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(SA=0;SA>2]|=JA.charCodeAt(SA)<<(SA%4<<3);return this._finish(re,ae),OA=P(this._hash),LA&&(OA=kA(OA)),this.reset(),OA},xA.prototype.reset=function(){return this._buff="",this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},xA.prototype.getState=function(){return{buff:this._buff,length:this._length,hash:this._hash.slice()}},xA.prototype.setState=function(LA){return this._buff=LA.buff,this._length=LA.length,this._hash=LA.hash,this},xA.prototype.destroy=function(){delete this._hash,delete this._buff,delete this._length},xA.prototype._finish=function(LA,SA){var OA,JA,ae,re=SA;if(LA[re>>2]|=128<<(re%4<<3),re>55)for(u(this._hash,LA),re=0;re<16;re+=1)LA[re]=0;OA=(OA=8*this._length).toString(16).match(/(.*?)(.{0,8})$/),JA=parseInt(OA[2],16),ae=parseInt(OA[1],16)||0,LA[14]=JA,LA[15]=ae,u(this._hash,LA)},xA.hash=function(LA,SA){return xA.hashBinary(W(LA),SA)},xA.hashBinary=function(LA,SA){var OA=P(D(LA));return SA?kA(OA):OA},xA.ArrayBuffer=function(){this.reset()},xA.ArrayBuffer.prototype.append=function(LA){var SA,OA=RA(this._buff.buffer,LA),JA=OA.length;for(this._length+=LA.byteLength,SA=64;SA<=JA;SA+=64)u(this._hash,m(OA.subarray(SA-64,SA)));return this._buff=SA-64>2]|=JA[SA]<<(SA%4<<3);return this._finish(re,ae),OA=P(this._hash),LA&&(OA=kA(OA)),this.reset(),OA},xA.ArrayBuffer.prototype.reset=function(){return this._buff=new Uint8Array(0),this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},xA.ArrayBuffer.prototype.getState=function(){var LA=xA.prototype.getState.call(this);return LA.buff=EA(LA.buff),LA},xA.ArrayBuffer.prototype.setState=function(LA){return LA.buff=iA(LA.buff,!0),xA.prototype.setState.call(this,LA)},xA.ArrayBuffer.prototype.destroy=xA.prototype.destroy,xA.ArrayBuffer.prototype._finish=xA.prototype._finish,xA.ArrayBuffer.hash=function(LA,SA){var OA=P(M(new Uint8Array(LA)));return SA?kA(OA):OA},xA}()}(Vu)),Vu.exports),fC=aI(Ju),q=new class{constructor(){this.uploadFileTryCount=0,this.maxRetries=1,this.systemClockOffset=0,this.httpRequest=null,this.uploadFileType="",this.duration=900,this.fetchCosTryCount=0}init(s){var n;this._core=s;const{IN_MINI_APP:g}=s.utils;this.httpRequest=g?yI:xu,(n=this.httpRequest)===null||n===void 0||n.init(s)}uploadToCOS(s){return pA(this,void 0,void 0,function*(){const n=`${ha} uploadToCOS`,{ssoLog:g,utils:{safeStringify:u}}=this._core,{file:E}=s;this.uploadFileType=s.uploadFileType,g.debug("uploadToCOS",`${n} options:${u(s)}`);try{const m=Date.now(),D=yield this._createCosOptions(s),M=D.fileExistsInCOS?{data:{location:D.downloadUrl}}:yield this._uploadFile(D);this._handleUploadError(M,s);const T=this._createUploadResult(E,M),P=Date.now()-m,W=function(EA){return EA<1024?`${EA}B`:EA<1048576?`${Math.floor(EA/1024)}KB`:`${Math.floor(EA/1048576)}MB`}(E.size),iA=`size:${W} time:${P}ms speed:${wr(1e3*E.size/P)}`;return g.debug("uploadToCOS",`${n} ok. name:${E.name} ${iA}`),{uploadOptions:D,response:T}}catch(m){throw g.warn("uploadToCOS",`${n} failed, error:${u(m)}`),m}})}_handleUploadError(s,n){var g,u;const{ChatError:E}=(g=this._core)===null||g===void 0?void 0:g.helper;if(s.statusCode===403)throw n.url,!((u=s?.data)===null||u===void 0)&&u.uploadIP&&s.data.uploadIP,new E({message:"Upload failed with status 403"})}_createUploadResult(s,n){return{fileName:s.name,fileSize:s.size,fileType:s.type.slice(s.type.indexOf("/")+1).toLowerCase(),location:n.data.location||"",uploadTime:Ur(Date.now(),!1),uploadSpeed:wr(1e3*s.size/Ur(Date.now(),!1))}}_createCosOptions(s){return pA(this,void 0,void 0,function*(){const{fileName:n,resources:g,uploadMethod:u}=yield this._prepareUploadParams(s),E=this._isC2CConversation(s.message.conversationID)?1:2;try{const m=yield this._fetchCosSignatureUrl({fileType:this.uploadFileType,fileName:n,uploadMethod:u,duration:this.duration,userID:s.message.from,conversationType:E}),{uploadUrl:D,downloadUrl:M,requestSnapshotUrl:T,thumbUrl:P,largeUrl:W,fileKey:iA,existFlag:EA}=m,RA=!Ot.isPrivateNetWork()&&m.uploadIP;return{url:this._getRawOrUploadProxyUrl(D),fileType:this.uploadFileType,fileName:n,resources:g,downloadUrl:M,requestSnapshotUrl:T,thumbUrl:P,largeUrl:W,fileKey:iA,uploadIP:RA||"",fileExistsInCOS:EA===1,onProgress:kA=>this._handleUploadProgress(kA,s)}}catch(m){throw console.error("Failed to create COS pre-signed URL options:",m),m}})}_prepareUploadParams(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g,isEmpty:u}}=this._core;n.debug("_prepareUploadParams",` prepareUploadParams:${g(s)}`);const{file:E}=s,{IN_MINI_APP:m,IN_RN_APP:D}=Ot.getPlatformFlags(),M=m||D,T=M&&s.message.type!==Ya,{name:P}=E,W=P.slice(P.lastIndexOf(".")),iA=`${Lr(999999)}${W}`,EA=T?E.name:iA,RA=yield this._generateHashFileName(E);return{fileName:u(RA)?Ig(EA):`${RA}${W}`,resources:M?E.url:E,uploadMethod:M?1:0}})}_generateHashFileName(s){return pA(this,void 0,void 0,function*(){const{utils:{IN_MINI_APP:n,IN_BROWSER:g,IN_UNI_NATIVE_APP:u,isArray:E},ssoLog:m}=this._core,D=Date.now();let M="";return g&&(M=yield this._generateHashFileNameInWeb(s)),n&&(E(s.tempFiles)&&(s=s.tempFiles[0]),u||(M=yield this._generateFileNameInMiniProgram(s)),u&&(M=yield this._generateFileNameInUNINativeApp(s))),m.info("_generateHashFileName",`hashFileName:${M} costTime:${Date.now()-D}`),M})}_generateHashFileNameInWeb(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g}}=this._core;let u="";try{u=yield new Promise((E,m)=>{const D=File.prototype.slice||File.prototype.mozSlice||File.prototype.webkitSlice;D||(n.warn("_generateHashFileNameInWeb","Browser does not support file slicing"),E(""));const M=10485760,T=Math.ceil(s.size/M);let P=0;const W=new fC.ArrayBuffer,iA=new FileReader,EA=setTimeout(()=>{iA.abort(),n.warn("_generateHashFileNameInWeb","File hash generation timeout"),E("")},2e3);function RA(){const kA=P*M,xA=kA+M>=s.size?s.size:kA+M;iA.readAsArrayBuffer(D.call(s,kA,xA))}iA.onload=kA=>{n.debug("_generateHashFileNameInWeb",`read chunk nr ${P+1} of ${T}`),W.append(kA.target.result),P++,P{clearTimeout(EA),m(kA)},RA()})}catch(E){n.warn("_generateHashFileNameInWeb",g(E))}return u})}_generateFileNameInMiniProgram(s){return pA(this,void 0,void 0,function*(){const{utils:{MINI_APP_NAMESPACE:n,safeStringify:g,isEmpty:u},ssoLog:E}=this._core;let m="";if(u(s.url))return E.warn("_generateFileNameInMiniProgram","file.url is empty"),m;if(typeof n?.getFileSystemManager!="function")return E.warn("_generateFileNameInUNINativeApp","getFileSystemManager is not a function"),m;try{m=yield new Promise((D,M)=>{n.getFileSystemManager().getFileInfo({filePath:s.url,success:T=>{D(T.digest)},fail:T=>{M(T)}})})}catch(D){E.warn("_generateFileNameInMiniProgram",g(D))}return m})}_generateFileNameInUNINativeApp(s){return pA(this,void 0,void 0,function*(){var n;const{utils:{safeStringify:g,isEmpty:u},ssoLog:E}=this._core;let m="";if(u(s.url))return E.warn("_generateFileNameInUNINativeApp","file.url is empty"),m;if(typeof((n=plus==null?void 0:plus.io)===null||n===void 0?void 0:n.getFileInfo)!="function")return E.warn("_generateFileNameInUNINativeApp","plus.io.getFileInfo is not a function"),m;try{m=yield new Promise((D,M)=>{plus.io.getFileInfo({filePath:s.url,success:T=>{D(T.digest)},fail:T=>{M(T)}})})}catch(D){E.warn("_generateFileNameInMiniProgram",g(D))}return m})}_handleUploadProgress(s,n){if(typeof n.onProgress=="function")try{n.onProgress(s.percent)}catch(g){throw console.warn("Upload progress callback error:",g),g}}_fetchCosSignatureUrl(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g}}=this._core,u=Ot.isSimpleCos(),E=this._prepareCosRequestData(s),m=u?"im_cos_msg.simple_sig":"im_cos_msg.pre_sig";try{const D=yield function(T,P,W){return pA(this,void 0,void 0,function*(){try{const{helper:iA,channel:EA}=W,RA=iA.generateCosSpecifiedData({servcmd:T,data:P}),kA=`${RA.head.seq}${T}`;return yield EA.sendPacket(RA,{requestId:kA})}catch(iA){throw console.warn("getCosSig error:",iA),iA}})}(m,E,this._core);this.fetchCosTryCount=0;const M=this._processResponse(D);return n.debug("_fetchCosSignatureUrl",` ok. isSimpleCos:${u} data:${g(M)}`),M||{}}catch(D){if(this.fetchCosTryCount<1)return this.fetchCosTryCount++,this._fetchCosSignatureUrl(s);throw this.fetchCosTryCount=0,D}})}_processResponse(s){var n;const g=Ot.isSimpleCos(),u=g?(n=s?.rpt_pre_sig)===null||n===void 0?void 0:n[0]:s;if(!u)return{};if(g){const{str_final_ip:W,rpt_pre_sig:iA,uint32_file_id:EA,uint32_exist_flag:RA,str_download_url:kA,str_upload_url:xA,str_snapshot_url:LA,str_file_key:SA}=u;return{uploadIP:W,preSig:iA,fileID:EA,existFlag:RA,downloadUrl:kA,uploadUrl:xA,requestSnapshotUrl:LA,fileKey:SA}}const{upload_url:E,download_url:m,snapshot_url:D,thumb_url:M,large_url:T,file_key:P}=u;return{uploadUrl:E,downloadUrl:m,requestSnapshotUrl:D,thumbUrl:M,largeUrl:T,fileKey:P}}_prepareCosRequestData(s){return Ot.isSimpleCos()?{uint32_upload_method:s.uploadMethod,uint32_platform:Ot.getPlatform(),uint32_sdkappid:Ot.getSDKAppID(),str_user_id:s.userID,uint32_scene:s.conversationType,rpt_upload_object:[{uint32_file_id:1,uint32_file_type:s.fileType,str_file_name:s.fileName}]}:{file_type:s.fileType,file_name:s.fileName,upload_method:s.uploadMethod,Duration:s.duration}}_uploadFile(s){return pA(this,void 0,void 0,function*(){return new Promise((n,g)=>{this.httpRequest.request(s,(u,E)=>{u&&this.uploadFileTryCount=3e4}_syncSystemClock(s){var n,g,u;const E=((n=s.headers)===null||n===void 0?void 0:n.date)||((g=s.headers)===null||g===void 0?void 0:g.Date)||((u=s.error)===null||u===void 0?void 0:u.ServerTime);if(E){const m=Date.now(),D=Date.parse(E);this.systemClockOffset=D-m}}_getRawOrUploadProxyUrl(s){const n=Ot.getFileUploadProxy();let g=s;return n&&(g=s.replace(/^https:\/\/[^/]+/,n)),g}_isC2CConversation(s){return s.slice(0,3)==="C2C"}};const L=2108,oA=2251,G=2252,x=2253,tA=["jpg","jpeg","gif","png","bmp","image","webp"],uA={JPG:1,JPEG:1,GIF:2,PNG:3,BMP:4,UNKNOWN:255},wA=1,$A=2;class me{constructor(n,g){this.instanceID=Lr(9999999),this.sizeType=n.type||0,this.type=0,this.size=n.size||0,this.width=n.width||0,this.height=n.height||0,this.imageUrl=Ot.addAuthToUrl(n.imageUrl||n.url||""),this.url=Ot.addAuthToUrl(n.url||g)}setSizeType(n){this.sizeType=n}setType(n){this.type=n}setImageUrl(n){n&&(this.imageUrl=Ot.addAuthToUrl(n))}getImageUrl(){return this.imageUrl}}function p(s){const{originUrl:n,originWidth:g,originHeight:u,min:E=198}=s,m=parseInt(g)||0,D=parseInt(u)||0,M={url:void 0,width:0,height:0};if((m<=D?m:D)<=E)M.url=n,M.width=m,M.height=D;else{D<=m?(M.width=Math.ceil(m*E/D),M.height=E):(M.width=E,M.height=Math.ceil(D*E/m));const T=n&&n.indexOf("?")>-1?`${n}&`:`${n}?`;M.url=E===198?`${T}imageView2/3/w/198/h/198`:`${T}imageView2/3/w/720/h/720`}if(n===void 0){const{url:T}=M;return Do(M,["url"])}return M}class B{constructor(n){this._imageMemoryURL="",this._percent=0,this.type=ic;const{uuid:g,file:u,imageFormat:E,imageInfoArray:m=[],isCustomUpload:D=!1}=n;this._imageMemoryURL=this.createImageDataAsURL(u),this.content={imageFormat:E,uuid:g,imageInfoArray:[]},this[Jr]=D,this.initImageInfoArray(m),this.autoFixUrl()}static parseServerPushElement(n){const{MsgContent:g}=n,{ImageFormat:u,ImageInfoArray:E,UUID:m}=g,D=function(M){return M.map(T=>({size:T.Size,type:T.Type,width:T.Width,height:T.Height,url:T.URL}))}(E);return new B({imageFormat:u,imageInfoArray:D,uuid:m})}createImageDataAsURL(n){let g="";const{IN_MINI_APP:u,IN_RN_APP:E,IN_BROWSER:m}=Ot.getPlatformFlags();return n&&((u||E)&&(g=n.url),m&&(g=window.URL.createObjectURL(n))),g}initImageInfoArray(n=[]){const g={type:0,size:0,width:0,height:0,url:""};for(let u=0;u<3;u++){const E=n[u]||Object.assign({},g),m=new me(E,this._imageMemoryURL);m.setSizeType(u+1),m.setType(u),this.addImageInfo(m)}this.updateAccessSideImageInfoArray()}autoFixUrl(){const n=["http","https"];this.content.imageInfoArray.forEach(g=>{if(!g.url||g.imageUrl==="")return;const[u,...E]=g.imageUrl.split("://"),m=E.join("://");n.includes(u)||g.setImageUrl(`https://${m}`)})}updatePercent(n){this._percent=Math.min(n,1)}updateImageFormat(n){this.content.imageFormat=uA[n.toUpperCase()]||uA.UNKNOWN}addImageInfo(n){this.content.imageInfoArray.length>=3||this.content.imageInfoArray.push(n)}updateImageInfoArray(n){const g=this.content.imageInfoArray.length;let u;for(let E=0;E({InstanceId:g.instanceID,Type:g.sizeType,MsgType:g.type,Size:g.size,Width:g.width,Height:g.height,URL:Ot.removeAuthToUrl(g.imageUrl)}))}}const v=new class{init(s){this.core=s}},N={[tu]:"i",[cl]:"a",[Ba]:"v",[xE]:"f"};let O=null,z=null;function X(s){var n;const{store:g,utils:{isNumber:u,safeStringify:E},ssoLog:m}=v.core;try{const D=((n=g.get("cloudConfig"))===null||n===void 0?void 0:n.upload_size_limit)||"";D!==z&&(z=D,O=JSON.parse(D)||{});const M=O?.[N[s]];if(u(M))return 1024*M*1024}catch(D){m.debug("getCloudControlUploadSizeLimit",E(D))}return null}var rA=new class{constructor(){this._messageOptionsMap=new Map}init(s){var n;this._core=s;const{notificationCenter:g,helper:u,InnerEvent:E,message:m}=s;u.registerApi({apiName:"createImageMessage",context:this}),u.registerExperimentalAPI("createImageMessage",this,"createCustomUploadImageMessage"),(n=m?.messageFactory)===null||n===void 0||n.registerElementClass(ic,B),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createImageMessage(s){var n,g,u;try{const E=(n=this._core.store.get("login"))===null||n===void 0?void 0:n.userId,m=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:E})),D=this._processImage(s);s.payload.file=D;const M={imageFormat:uA.UNKNOWN,uuid:Ot.generateUUID(D),file:D,imageInfoArray:[]},T=new B(M);return m.setElement(T),this._messageOptionsMap.set(m.clientSequence,s),m}catch(E){throw E}}createCustomUploadImageMessage(s){var n,g,u,E;const{store:m,utils:{isEmpty:D}}=this._core,M=(n=m.get("login"))===null||n===void 0?void 0:n.userId,T=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:M})),{largeImageUuid:P,largeFileSize:W,largeImageWidth:iA,largeImageHeight:EA,largeImageUrl:RA,originImageUuid:kA,originFileSize:xA,originImageWidth:LA,originImageHeight:SA,originImageUrl:OA,thumbImageUuid:JA,thumbFileSize:ae,thumbImageWidth:re,thumbImageHeight:_i,thumbImageUrl:Ti}=((E=s?.payload)===null||E===void 0?void 0:E.file)||{};if(D(OA)||D(kA))throw new Error("createImageMessageExperimental originImageUrl or originImageUuid is empty");const Lt=new B({imageFormat:uA.UNKNOWN,uuid:kA,imageInfoArray:[{instanceID:kA,size:xA,width:LA,height:SA,imageUrl:OA,url:OA},{instanceID:P,size:W,width:iA,height:EA,imageUrl:RA,url:RA},{instanceID:JA,size:ae,width:re,height:_i,imageUrl:Ti,url:Ti}],isCustomUpload:!0});return T.setElement(Lt),this._messageOptionsMap.set(T.clientSequence,s),T._skipUpload=!0,T}upload(s){return pA(this,void 0,void 0,function*(){const n=s.getElements()[0],{file:g}=this._messageOptionsMap.get(s.clientSequence).payload;this._validateBeforeUploadImage(g);const u=yield this._performImageUpload(n,s,g),E=this._generateImageInfo(u);return n.updateImageFormat(u?.fileType),n.updateImageInfoArray(E),this._updateImageType(n.content.imageInfoArray),s})}_performImageUpload(s,n,g){return pA(this,void 0,void 0,function*(){const{to:u}=n,E={uploadFileType:tu,file:g,to:u,message:n,onProgress:M=>{var T,P;s.updatePercent(M),(P=(T=this._messageOptionsMap.get(n.clientSequence))===null||T===void 0?void 0:T.onProgress)===null||P===void 0||P.call(T,M)}},{uploadOptions:m,response:D}=yield q.uploadToCOS(E);return this._parseResponse(m,D)})}_generateImageInfo(s){const{location:n,fileSize:g,width:u,height:E,smallImageUrl:m,smallImageWidth:D,smallImageHeight:M,largeImageUrl:T,largeImageWidth:P,largeImageHeight:W,imageInfoArray:iA}=s,EA=Ot.addAuthToUrl(n),RA={size:g,url:EA,width:u,height:E};return iA?.length>0?this._processImageInfoArray(iA,g):m&&T?[Object.assign({},RA),{largeImageUrl:T,largeImageWidth:P,largeImageHeight:W},{smallImageUrl:m,smallImageWidth:D,smallImageHeight:M}]:[Object.assign({},RA),this._generateThumbInfo(EA,u,E,720),this._generateThumbInfo(EA,u,E,198)]}_generateThumbInfo(s,n,g,u){return p({originUrl:s,originWidth:n,originHeight:g,min:u})}_processImageInfoArray(s,n){let g,u,E;for(const m of s)m.type===1?(u=m,u.size=n):m.type===2?(E=m,E.size=n):(g=m,g.size=n);return[Object.assign({},g),Object.assign({},E),Object.assign({},u)]}_parseResponse(s,n){return pA(this,void 0,void 0,function*(){try{const{thumbUrl:g,largeUrl:u,downloadUrl:E}=s;if(g&&u&&(yield this._getImageInfoByUrl(g,n,"thumb"),yield this._getImageInfoByUrl(u,n,"large")),Ot.isSimpleCos()&&!Ot.isPrivateNetWork()&&(yield this._getImageInfoArray(E,n),n?.uploadIP)){const m=this._extractDomainFromUrl(E);m&&(yield this._getDownloadIP(m,n))}return n}catch(g){throw g}})}_extractDomainFromUrl(s){var n;try{const g=s.match(/:\/\/([^\/]+)/);return g?g[1]:null}catch(g){return(n=this._core)===null||n===void 0||n.ssoLog.warn("_extractDomainFromUrl",`Failed to extract domain from URL:${g.message}`),null}}_getImageInfoByUrl(s,n,g){return pA(this,void 0,void 0,function*(){var u;try{const E=Ot.addAuthToUrl(s),{width:m=0,height:D=0}=yield Ot.probeImageWidthHeight(E);n.width=m,n.height=D,g==="thumb"?(n.smallImageUrl=s,n.smallImageWidth=m,n.smallImageHeight=D):(n.largeImageUrl=s,n.largeImageWidth=m,n.largeImageHeight=D)}catch(E){(u=this._core)===null||u===void 0||u.ssoLog.warn("_getImageInfoByUrl",`Failed to get ${g} image info:${E.message}`)}})}_validateBeforeUploadImage(s){var n;const{ChatError:g}=(n=this._core)===null||n===void 0?void 0:n.helper;if(!s)throw new g({code:oA});this._checkImageType(s),this._checkImageSize(s)}_processImage(s){var n;try{const{IN_MINI_APP:g}=(n=this._core)===null||n===void 0?void 0:n.utils;let{file:u}=s.payload;return u=g?this._processMiniAppImageFile(u):this._processWebImageFile(u),u}catch(g){throw g}}_processMiniAppImageFile(s){gl(s)&&console.warn("FileUnsupportedInMiniApp","createImageMessage");const n=s.tempFiles[0].path||s.tempFiles[0].tempFilePath;return{url:n,name:n.slice(n.lastIndexOf("/")+1),size:s.tempFiles&&s.tempFiles[0].size||1,type:n.slice(n.lastIndexOf(".")+1).toLowerCase()}}_processWebImageFile(s){var n;const{ChatError:g}=(n=this._core)===null||n===void 0?void 0:n.helper,u=Ot.extractFileFromInput(s);if(!u)throw new g({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return u}_getDownloadIP(s,n){return pA(this,void 0,void 0,function*(){const g=`${ha} getDownloadIP domainName: ${s}`;try{const u=yield function(m,D){return pA(this,void 0,void 0,function*(){try{const{helper:M,channel:T}=D,P="im_cos_msg.get_final_ip",W={str_domain:m},iA=M.generateProtocolData({servcmd:P,data:W}),EA=`${iA.head.seq}${P}`;return yield T.sendPacket(iA,{requestId:EA})}catch(M){throw console.warn("getFinalIP error:",M),M}})}(s,this._core);if(!u||!u.str_final_ip)return;console.log(`${g} ok. downloadIP:${u}`);const E=n.location.split("/");E[0]=u.str_final_ip,n.location=E.join("/")}catch(u){console.warn(u)}})}_getImageInfoArray(s,n){return pA(this,void 0,void 0,function*(){try{const g=yield function(u,E){return pA(this,void 0,void 0,function*(){try{const{helper:m,channel:D}=E,M="im_cos_msg.get_imageinfo",T={str_image_url:u},P=m.generateProtocolData({servcmd:M,data:T}),W=`${P.head.seq}${M}`;return yield D.sendPacket(P,{requestId:W})}catch(m){throw console.warn("getImageInfo error:",m),m}})}(s,this._core);return n.imageInfoArray=this._processImageInfoResponse(g),n}catch(g){throw n.imageInfoArray=void 0,g}})}_processImageInfoResponse(s){if(!s)return[];const{rpt_msg_image_info:n}=s;return n.map(g=>({type:g.uint32_image_type,url:g.str_url,width:g.uint32_width,height:g.uint32_height,imageFormat:g.str_image_format}))}_checkImageType(s){const{utils:n,helper:g}=this._core;let u="";if(n.IN_MINI_APP&&(u=s.url.slice(s.url.lastIndexOf(".")+1)),n.IN_BROWSER&&(u=s.name.slice(s.name.lastIndexOf(".")+1)),tA.indexOf(u.toLowerCase())<0)throw new g.ChatError({code:G})}_checkImageSize(s){const{utils:n,helper:g,store:u}=this._core;let E=0;if(E=(n.IN_MINI_APP,s.size),E===0)throw new g.ChatError({code:L});if(E>=(X(tu)||20971520))throw new g.ChatError({code:x})}_updateImageType(s){s[1].type=$A,s[2].type=wA}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this)}};const DA=2108,GA=2401,VA=2402,te="2.5.0",Ce="1.18.0";function Ke(s,n){const g=s.split("."),u=n.split("."),E=Math.max(g.length,u.length);for(;g.lengthM)return 1;if(D0;return{isValid:n,error:n?null:{message:"content can not be empty"}}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},u=g?this.payload:this.content,{uuid:E,downloadFlag:m,fileUrl:D,fileName:M,fileSize:T}=u;return{MsgType:this.type,MsgContent:{Download_Flag:m,Url:Ot.removeAuthToUrl(D),FileName:M,FileSize:T,UUID:E}}}_getFileInfo(n){const{utils:{IN_UNI_NATIVE_APP:g}}=v.core;if(n.fileName&&n.fileSize)return{size:n.fileSize,name:n.fileName};const{file:u}=n;return u?(g&&this._processNativeAppFile(u),{size:u.size,name:u.name}):{size:0,name:""}}_processNativeAppFile(n){if(n.path&&n.path.includes(".")){const g=n.path.slice(n.path.lastIndexOf(".")+1).toLowerCase();n.type=g,n.name||(n.name=`${Lr(999999)}.${g}`)}n.name||(n.type="",n.name=n.path.slice(n.path.lastIndexOf("/")+1).toLowerCase()),n.suffix&&(n.type=n.suffix),n.url||(n.url=n.path)}}ot=Jr;var kt=new class{constructor(){this._messageOptionsMap=new Map}init(s){var n;this._core=s;const{notificationCenter:g,helper:u,InnerEvent:E,message:m}=s;u.registerApi({apiName:"createFileMessage",context:this}),u.registerExperimentalAPI("createFileMessage",this,"createCustomUploadFileMessage"),(n=m?.messageFactory)===null||n===void 0||n.registerElementClass(Ya,at),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createFileMessage(s){var n,g,u;try{this._checkVersion();const E=this._processFile(s.payload.file);s.payload.file=E;const m=(n=this._core.store.get("login"))===null||n===void 0?void 0:n.userId,D=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:m})),M={uuid:Ot.generateUUID(E),file:E},T=new at(M);return D.setElement(T),this._messageOptionsMap.set(D.clientSequence,s),D}catch(E){throw E}}createCustomUploadFileMessage(s){var n,g,u;try{const{store:E,message:m,utils:{isEmpty:D}}=this._core,M=(n=E.get("login"))===null||n===void 0?void 0:n.userId,{url:T,uuid:P,fileSize:W,fileName:iA=""}=((g=s?.payload)===null||g===void 0?void 0:g.file)||{};if(D(T))throw new Error("url is required");const EA=(u=m.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:M})),RA=new at({url:T,uuid:P,file:{size:W,name:iA},isCustomUpload:!0});return EA.setElement(RA),EA}catch(E){throw E}}upload(s){return pA(this,void 0,void 0,function*(){const{file:n}=this._messageOptionsMap.get(s.clientSequence).payload;this._validateBeforeUploadFile(n);const g=s.getElements()[0],u=yield this._performFileUpload(g,s,n),E=Ot.addAuthToUrl(u?.location);return g.updateFileUrl(E),s})}_validateBeforeUploadFile(s){const{helper:{ChatError:n}}=this._core;if(!s)throw new n({code:GA});const g=X(xE)||104857600;if(s.size>g)throw new n({code:VA});if(s.size===0)throw new n({code:DA})}_performFileUpload(s,n,g){return pA(this,void 0,void 0,function*(){const{to:u}=n,E={uploadFileType:xE,file:g,to:u,message:n,onProgress:D=>{var M,T;s.updatePercent(D),(T=(M=this._messageOptionsMap.get(n.clientSequence))===null||M===void 0?void 0:M.onProgress)===null||T===void 0||T.call(M,D)}},{response:m}=yield q.uploadToCOS(E);return m})}_processFile(s){var n,g;const{IN_BROWSER:u,IN_RN_APP:E,IN_WX_MINI_APP:m,IN_QQ_MINI_APP:D,IN_UNI_NATIVE_APP:M}=(n=this._core)===null||n===void 0?void 0:n.utils,{ChatError:T}=(g=this._core)===null||g===void 0?void 0:g.helper;if(u||M){const P=Ot.extractFileFromInput(s);if(!P)throw new T({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return P}if(m||D){const{tempFiles:P}=s;return Object.assign(Object.assign({},P[0]),{url:P[0].path})}return E?Object.assign(Object.assign({},s),{url:s.uri}):s}_checkVersion(){var s,n;const{MINI_APP_NAMESPACE:g,IN_MINI_APP:u,IN_WX_MINI_APP:E,IN_QQ_MINI_APP:m,IN_UNI_NATIVE_APP:D}=(s=this._core)===null||s===void 0?void 0:s.utils,{ChatError:M}=(n=this._core)===null||n===void 0?void 0:n.helper;if(u){if(!(E||m||D))throw new M({message:"Unsupported mini app environment"});const T=g.getSystemInfoSync().SDKVersion;if(E&&Ke(T,te)<0)throw new M({message:`WXChooseMessageFile requires SDK version ${te} or higher`});if(m&&Ke(T,Ce)<0)throw new M({message:`QQChooseMessageFile requires SDK version ${Ce} or higher`})}}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this)}};const Vt=2108,Ui=2351,ao=2352,Zi=["mp4","quicktime","mov","video"];var Ei;class Po{constructor(n){this.type=Fl,this.uploadProgress=0,this[Ei]=!1;const g=typeof n?.videoSecond=="number"?n?.videoSecond:0;this[Jr]=n.isCustomUpload||!1,this.content={remoteVideoUrl:Ot.addAuthToUrl(n.remoteVideoUrl||n.videoUrl||""),videoFormat:n.videoFormat,videoSecond:parseInt(g?.toString(),10),videoSize:n.videoSize,videoUrl:Ot.addAuthToUrl(n.videoUrl),videoDownloadFlag:2,videoUUID:n.videoUUID,thumbUUID:n.thumbUUID,thumbFormat:n.thumbFormat,thumbWidth:n.thumbWidth,snapshotWidth:n.thumbWidth,thumbHeight:n.thumbHeight,snapshotHeight:n.thumbHeight,thumbSize:n.thumbSize,snapshotSize:n.thumbSize,thumbDownloadFlag:2,thumbUrl:Ot.addAuthToUrl(n.thumbUrl),snapshotUrl:Ot.addAuthToUrl(n.thumbUrl)}}static parseServerPushElement(n){const{MsgContent:g}=n,{VideoUrl:u,VideoFormat:E,VideoSecond:m,VideoSize:D,VideoDownloadFlag:M,VideoUUID:T,ThumbUUID:P,ThumbFormat:W,ThumbWidth:iA,SnapshotWidth:EA,ThumbHeight:RA,SnapshotHeight:kA,ThumbSize:xA,SnapshotSize:LA,ThumbDownloadFlag:SA,ThumbUrl:OA,SnapshotUrl:JA}=g;return new Po({videoUrl:u,videoFormat:E,videoSecond:m,videoSize:D,videoDownloadFlag:M,videoUUID:T,thumbUUID:P,thumbFormat:W,thumbWidth:iA,snapshotWidth:EA,thumbHeight:RA,snapshotHeight:kA,thumbSize:xA,snapshotSize:LA,thumbDownloadFlag:SA,thumbUrl:OA,snapshotUrl:JA})}updatePercent(n){this.uploadProgress=Math.min(n,1)}updateVideoUrl(n){n&&(this.content.remoteVideoUrl=n)}updateSnapshotInfo(n){const{snapshotUrl:g,snapshotWidth:u,snapshotHeight:E}=n;Ot.isEmpty(g)||(this.content.thumbUrl=this.content.snapshotUrl=g),Ot.isEmpty(u)||(this.content.thumbWidth=this.content.snapshotWidth=Number(u)),Ot.isEmpty(E)||(this.content.thumbHeight=this.content.snapshotHeight=Number(E))}validateBeforeSend(){if(this[Jr])return{isValid:!0};const n=this.content.remoteVideoUrl!=="";return{isValid:n,error:n?null:{message:"content can not be empty"}}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},u=g?this.payload:this.content,{remoteVideoUrl:E,videoFormat:m,videoSecond:D,videoSize:M,videoDownloadFlag:T,videoUUID:P,thumbUUID:W,thumbFormat:iA,thumbWidth:EA,snapshotWidth:RA,thumbHeight:kA,snapshotHeight:xA,thumbSize:LA,snapshotSize:SA,thumbDownloadFlag:OA,thumbUrl:JA,snapshotUrl:ae}=u;return{MsgType:this.type,MsgContent:{VideoUrl:Ot.removeAuthToUrl(E),VideoFormat:m,VideoSecond:D,VideoSize:M,VideoDownloadFlag:T,VideoUUID:P,ThumbUUID:W,ThumbFormat:iA,ThumbWidth:EA,SnapshotWidth:RA,ThumbHeight:kA,SnapshotHeight:xA,ThumbSize:LA,SnapshotSize:SA,ThumbDownloadFlag:OA,ThumbUrl:Ot.removeAuthToUrl(JA),SnapshotUrl:Ot.removeAuthToUrl(ae)}}}}Ei=Jr;var As,pi=new class{constructor(){this._messageOptionsMap=new Map}init(s){var n;this._core=s;const{notificationCenter:g,helper:u,InnerEvent:E,message:m}=s;u.registerApi({apiName:"createVideoMessage",context:this}),u.registerExperimentalAPI("createVideoMessage",this,"createCustomUploadVideoMessage"),(n=m?.messageFactory)===null||n===void 0||n.registerElementClass(Fl,Po),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createVideoMessage(s){var n,g,u;try{const E=this._processVideo(s);s.payload.file=E;const m=(n=this._core.store.get("login"))===null||n===void 0?void 0:n.userId,D=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:m})),M={videoFormat:E.videoFile.type,videoSecond:ar(E.videoFile.second,0),videoSize:E.videoFile.size,remoteVideoUrl:"",videoUrl:E.videoFile.url,videoUUID:Ot.generateUUID(E.videoFile),thumbUUID:Ot.generateUUID(E.videoFile,"jpg"),thumbWidth:E.width||200,thumbHeight:E.height||200,thumbUrl:E.thumbUrl,thumbSize:E.thumbSize,thumbFormat:"jpg"},T=new Po(M);return D.setElement(T),this._messageOptionsMap.set(D.clientSequence,s),D}catch(E){throw E}}createCustomUploadVideoMessage(s){var n,g,u;try{const{store:E,message:m}=this._core;this._validateCustomUploadVideoMessage(s);const D=(n=E.get("login"))===null||n===void 0?void 0:n.userId,{videoUrl:M,videoUuid:T,duration:P,snapshotUrl:W,snapshotUuid:iA,videoFileSize:EA,videoType:RA,snapshotWidth:kA,snapshotHeight:xA,snapshotFileSize:LA,snapshotType:SA="jpg"}=((g=s?.payload)===null||g===void 0?void 0:g.file)||{},OA=(u=m.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:D})),JA=new Po({videoFormat:RA,videoSecond:P||0,videoSize:EA,remoteVideoUrl:M,videoUrl:M,videoUUID:T,thumbUUID:iA,thumbWidth:kA||200,thumbHeight:xA||200,thumbUrl:W,thumbSize:LA,thumbFormat:SA,isCustomUpload:!0});return OA.setElement(JA),this._messageOptionsMap.set(OA.clientSequence,s),OA}catch(E){throw E}}upload(s){return pA(this,void 0,void 0,function*(){const n=s.getElements()[0],{file:g}=this._messageOptionsMap.get(s.clientSequence).payload;this._validateBeforeUploadVideo(g);const u=yield this._performVideoUpload(n,s,g),{location:E,snapshotInfo:m}=u,D=Ot.addAuthToUrl(E);return n.updateVideoUrl(D),Ot.isEmpty(m)||n.updateSnapshotInfo(m),s})}_validateBeforeUploadVideo(s){const{helper:{ChatError:n}}=this._core,g=X(Ba)||104857600;if(s.videoFile.size>g)throw new n({code:Ui});if(s.videoFile.size===0)throw new n({code:Vt});if(Zi.indexOf(s.videoFile.type)===-1)throw new n({code:ao})}_validateCustomUploadVideoMessage(s){var n;const{utils:{isEmpty:g,isNumber:u}}=this._core,{videoUrl:E,videoUuid:m,duration:D,snapshotUrl:M,snapshotUuid:T}=((n=s?.payload)===null||n===void 0?void 0:n.file)||{};if(g(E)||g(m)||!u(D)||g(M)||g(T))throw new Error("Invalid video message options: missing required fields (videoUrl, videoUuid, duration, snapshotUrl, snapshotUuid)")}_performVideoUpload(s,n,g){return pA(this,void 0,void 0,function*(){const{to:u}=n,E={uploadFileType:Ba,file:g,to:u,message:n,onProgress:M=>{var T,P;s.updatePercent(M),(P=(T=this._messageOptionsMap.get(n.clientSequence))===null||T===void 0?void 0:T.onProgress)===null||P===void 0||P.call(T,M)}},{response:m,uploadOptions:D}=yield q.uploadToCOS(E);return{snapshotInfo:yield this._getSnapshotInfoByUrl(D.requestSnapshotUrl),location:m.location}})}_processVideo(s){var n,g;try{const{ChatError:u}=(n=this._core)===null||n===void 0?void 0:n.helper,{IN_MINI_APP:E,IN_BROWSER:m}=(g=this._core)===null||g===void 0?void 0:g.utils;let{file:D}=s.payload,M={};if(E&&(M=this._processMiniVideoFile(D),D.name=M.name,D.url=M.url,D.type=M.type),m){const T=Ot.extractFileFromInput(D);if(!T)throw new u({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});D=T,M=this._processWebVideoFile(D)}return D.videoFile=M,D.thumbUrl="",D.thumbSize=0,D}catch(u){throw console.warn(`${ha} _processFile error:`,u),u}}_processMiniVideoFile(s){const{utils:{IN_UNI_NATIVE_APP:n},helper:{ChatError:g}}=this._core;if(gl(s))throw new g({message:"FileUnsupportedInMiniApp"});Array.isArray(s.tempFiles)&&(s=s.tempFiles[0]);let u=s.tempFilePath.slice(s.tempFilePath.lastIndexOf(".")+1).toLowerCase();return n&&(u=s.fileType||u),{url:s.tempFilePath,name:s.tempFilePath.slice(s.tempFilePath.lastIndexOf("/")+1),size:s.size||1,second:s.duration||0,type:u}}_processWebVideoFile(s){const{name:n,size:g=1,duration:u=0,type:E}=s,m=E.split("/")[1];return{url:window.URL.createObjectURL(s),name:n,size:g,second:u,type:m}}_getSnapshotInfoByUrl(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n}=this._core;try{n.debug("_getSnapshotInfoByUrl",`${ha} _getSnapshotInfoByUrl url:${s}`);const g={version:1,platform:Ot.getPlatform(),cover_name:Ig(Lr(99999)),snapshot_url:s},u=yield function(T,P){return pA(this,void 0,void 0,function*(){try{const W="im_cos_msg.video_cover",{helper:iA,channel:EA}=P,RA=iA.generateCosSpecifiedData({servcmd:W,data:T}),kA=`${RA.head.seq}${W}`;return yield EA.sendPacket(RA,{requestId:kA})}catch(W){throw console.warn("getSnapshotInfo error:",W),W}})}(g,this._core),{download_url:E}=u||{};if(n.debug("_getSnapshotInfoByUrl",`${ha} _getSnapshotInfoByUrl OK snapshotUrl:${E}`),Ot.isEmpty(E))return{};const m=Ot.addAuthToUrl(E),{width:D=0,height:M=0}=yield Ot.probeImageWidthHeight(m);return{snapshotUrl:m,snapshotWidth:D,snapshotHeight:M}}catch(g){throw g}})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this)}};class ji{constructor(n){this.uploadProgress=0,this.type=Fg,this[As]=!1,this[Jr]=n.isCustomUpload||!1,this.content={downloadFlag:2,second:n.second,size:n.size,url:Ot.generateURL(n.url,{needAddAuthToUrl:!this[Jr]}),remoteAudioUrl:Ot.addAuthToUrl(n.url||""),uuid:n.uuid}}static parseServerPushElement(n){const{MsgContent:g}=n,{Url:u,Download_Flag:E,Second:m,Size:D,UUID:M}=g;return new ji({url:u,downloadFlag:E,second:m,size:D,uuid:M})}updatePercent(n){this.uploadProgress=Math.min(n,1)}updateAudioUrl(n){this.content.remoteAudioUrl=n}validateBeforeSend(){if(this[Jr])return{isValid:!0};const n=this.content.remoteAudioUrl!=="";return{isValid:n,error:n?null:{message:"content can not be empty"}}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},u=g?this.payload:this.content,{uuid:E,downloadFlag:m,remoteAudioUrl:D,size:M,second:T}=u;return{MsgType:this.type,MsgContent:{Url:Ot.removeAuthToUrl(D),Download_Flag:m,Second:T,Size:M,UUID:E}}}}As=Jr;const Ws=2108,Te=2300,Rt=2301;var FA=new class{constructor(){this._messageOptionsMap=new Map}init(s){var n;this._core=s;const{notificationCenter:g,helper:u,InnerEvent:E,message:m}=s;u.registerApi({apiName:"createAudioMessage",context:this}),u.registerExperimentalAPI("createAudioMessage",this,"createCustomUploadAudioMessage"),(n=m?.messageFactory)===null||n===void 0||n.registerElementClass(Fg,ji),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createAudioMessage(s){var n,g,u;try{let{file:E}=s.payload;E=this._processAudioFile(s.payload.file),s.payload.file=E;const m=(n=this._core.store.get("login"))===null||n===void 0?void 0:n.userId,D=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:m})),M={second:Math.max(1,Math.round((E.duration||E.second)/1e3)),size:E.fileSize||E.size||1,url:E.tempFilePath||E.uri||E.url,uuid:Ot.generateUUID(E)},T=new ji(M);return D.setElement(T),this._messageOptionsMap.set(D.clientSequence,s),D}catch(E){throw E}}createCustomUploadAudioMessage(s){var n,g,u;try{this._validateCustomUploadOptions(s);const{store:E,message:m}=this._core,D=(n=E.get("login"))===null||n===void 0?void 0:n.userId,{url:M,uuid:T,duration:P,fileSize:W}=((g=s?.payload)===null||g===void 0?void 0:g.file)||{},iA=(u=m.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:D})),EA=new ji({second:P,size:W||1,url:M,uuid:T,isCustomUpload:!0});return iA.setElement(EA),this._messageOptionsMap.set(iA.clientSequence,s),iA}catch(E){throw E}}upload(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g}}=this._core;n.debug("upload",`${ha} uploadAudio message:${g(s)}`);const{file:u}=this._messageOptionsMap.get(s.clientSequence).payload;this._validateBeforeUploadAudio(u);const E=s.getElements()[0],m=yield this._performAudioUpload(E,s,u),D=Ot.addAuthToUrl(m?.location);return E.updateAudioUrl(D),s})}_validateBeforeUploadAudio(s){const{helper:{ChatError:n},store:g}=this._core;if(!s)throw new n({code:Te});const u=X(cl)||20971520;if(s.size>u)throw new n({code:Rt});if(s.size===0)throw new n({code:Ws})}_performAudioUpload(s,n,g){return pA(this,void 0,void 0,function*(){const{to:u}=n,E={uploadFileType:cl,file:g,to:u,message:n,onProgress:D=>{var M,T;s.updatePercent(D),(T=(M=this._messageOptionsMap.get(n.clientSequence))===null||M===void 0?void 0:M.onProgress)===null||T===void 0||T.call(M,D)}},{response:m}=yield q.uploadToCOS(E);return m})}_processAudioFile(s){var n;const{IN_MINI_APP:g,IN_BROWSER:u}=(n=this._core)===null||n===void 0?void 0:n.utils;return g?this._processMiniFile(s):u?this._processWebFile(s):void 0}_processMiniFile(s){return{url:s.tempFilePath,name:s.tempFilePath.slice(s.tempFilePath.lastIndexOf("/")+1),size:s.fileSize,second:s.duration,type:s.tempFilePath.slice(s.tempFilePath.lastIndexOf(".")+1).toLowerCase()}}_processWebFile(s){if(s.tempFilePath||s.uri)return s;const n=URL.createObjectURL(s);return s.tempFilePath=n,s}_validateCustomUploadOptions(s){var n;const{utils:{isEmpty:g}}=this._core,{url:u,uuid:E,duration:m}=((n=s?.payload)===null||n===void 0?void 0:n.file)||{};if(g(u)||g(E)||g(m))throw new Error("Invalid audio message options")}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this)}};const zt={to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1},cloudCustomData:{required:!1,rules:["string"],allowEmpty:!1},priority:{required:!1,rules:["string"],allowEmpty:!1},customModerationConfigurationID:{required:!1,rules:["string"],allowEmpty:!1},onProgress:{required:!1,rules:["function"],allowEmpty:!1}},En={createImageMessage:zt,createAudioMessage:zt,createVideoMessage:zt,createFileMessage:zt},Xt={createImageMessage:!0,createAudioMessage:!0,createVideoMessage:!0,createFileMessage:!0},us={[ic]:rA,[Ya]:kt,[Fl]:pi,[Fg]:FA};var vi=new class{constructor(){this.name="RichMediaMessage"}install(s){this._core=s;const{constants:{OuterConstant:{MSG_AUDIO:n,MSG_FILE:g,MSG_IMAGE:u,MSG_VIDEO:E}}}=s;v.init(s),rA.init(s),kt.init(s),pi.init(s),FA.init(s),q.init(s),Ot.init(s),s.helper.registerApi({apiName:"sendMessage",context:this,matcher:m=>[n,g,u,E].includes(m[0].type)}),s.helper.registerValidateConfig({auth:Xt,params:En})}sendMessage(s,n){return pA(this,void 0,void 0,function*(){var g,u,E;try{return this._isCustomUpload(s)||(yield this._upload(s)),yield(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageSender)===null||E===void 0?void 0:E.sendMessage(s,n)}catch(m){throw m}})}_upload(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g}}=this._core;if(n.debug("_upload",` uploadFile message:${g(s)}`),s._relayFlag!==!0)try{const u=us[s.type];u&&(yield u.upload(s),n.info("_upload",` type:${s.type}`))}catch(u){throw s.status=iu.FAIL,u instanceof Error&&(u.data={message:s}),this._core.message.messageDataHandler.storeConversationMessage(s),u}})}_isCustomUpload(s){var n,g;return((g=(n=s._elements)===null||n===void 0?void 0:n[0])===null||g===void 0?void 0:g[Jr])===!0}};const ho=new class{init(s){this.core=s}};class Ct{constructor(n){this.conversationID=n.conversationID||"",this.unreadCount=n.unreadCount||0,this.type=n.type||"",this.lastMessage=ho.core.common.buildLastMessage(n.lastMessage),this.peerReadTime=n.peerReadTime||0,this.groupAtInfoList=[],this.remark=n.remark||"",this.isPinned=n.isPinned||!1,this.messageRemindType=n.messageRemindType,this.markList=n.markList||[],this.customData=n.customData||"",this.conversationGroupList=n.conversationGroupList||[],this.draftText=n.draftText||"",this.userProfile=n.userProfile,this.groupProfile=n.groupProfile,this.subType=n.subType||"",this._isInfoCompleted=!1,this._init()}_init(){var n;const{core:{OuterConstant:g,utils:{isUndefined:u}}}=ho;u(this.userProfile)&&this.type===g.CONV_C2C?this.userProfile={userID:this.conversationID.replace(g.CONV_C2C,"")}:this.type===g.CONV_GROUP&&(!this.subType&&(!((n=this.groupProfile)===null||n===void 0)&&n.type)&&(this.subType=this.groupProfile.type),u(this.groupProfile)&&(this.groupProfile={groupID:this.conversationID.replace(g.CONV_GROUP,""),selfInfo:{},lastMessage:{},type:this.subType}))}updateUnreadCount(n){var g;const{core:{OuterConstant:u,utils:{isUndefined:E},store:m}}=ho,{nextUnreadCount:D,isFromGetConversations:M,isUnreadC2CMessage:T}=n;if(E(D))return;if(this.subType===u.GRP_AVCHATROOM)return void(this.unreadCount=0);if(M&&this.type===u.CONV_GROUP)return void(this.unreadCount=D);if(T&&this.type===u.CONV_C2C)return void(this.unreadCount=D);const P=((g=m.get("cloudConfig"))===null||g===void 0?void 0:g.support_unread_count_for_meeting)==="1";this.subType!==u.GRP_MEETING||P?this.unreadCount+=D:this.unreadCount=0}updateLastMessage(n){this.lastMessage=ho.core.common.buildLastMessage(n)}reduceUnreadCount(){return this.unreadCount>=1&&(this.unreadCount-=1,!0)}isLastMessageRevoked(n){const{core:{OuterConstant:g}}=ho,{sequence:u,time:E}=n;return this.type===g.CONV_C2C&&u===this.lastMessage.lastSequence&&E===this.lastMessage.lastTime||this.type===g.CONV_GROUP&&u===this.lastMessage.lastSequence}setLastMessageRevoked(n){this.lastMessage.isRevoked=n}setLastMessageRevoker(n){this.lastMessage.revoker=n}setDraftText(n){this.draftText=n}updateGroupAtInfoList(n){const{core:{common:{updateGroupAtInfo:g}}}=ho;g(n,this.groupAtInfoList)}clearGroupAtInfoList(){this.groupAtInfoList.length=0}getProfileCompleted(){return this._isInfoCompleted}setProfileCompleted(){this._isInfoCompleted=!0}}const Bt=s=>{const{core:{OuterConstant:n,utils:{isString:g}}}=ho;return g(s)&&s.slice(0,3)===n.CONV_C2C},ug=s=>{const{core:{OuterConstant:n,utils:{isString:g}}}=ho;return g(s)&&s.slice(0,5)===n.CONV_GROUP},ks=s=>{const{core:{OuterConstant:n,utils:{isString:g}}}=ho;return g(s)&&s===n.CONV_SYSTEM};function Wi(s){const{OuterConstant:n}=ho.core;let g="";return s===0?g=n.MSG_REMIND_ACPT_AND_NOTE:s===1?g=n.MSG_REMIND_DISCARD:s===2?g=n.MSG_REMIND_ACPT_NOT_NOTE:s===3&&(g=n.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),g}function Hr(s){const{OuterConstant:n}=ho.core;let g;return s.startsWith(n.CONV_C2C)&&(g=s.replace(n.CONV_C2C,"")),g==="@TLS#ERROR"||g==="@TLS#NOT_FOUND"}function oc(s,n){const{helper:g}=ho.core,u=new g.ChatError({functionName:s,code:n?.errorCode||n?.code,message:n?.errorInfo||n?.message});throw console.error(`${s} fail:`,u),u}var is,ga;(function(s){s[s.OFF=0]="OFF",s[s.ON=1]="ON"})(is||(is={})),function(s){s[s.ONLY_CONVERSATIONID=1]="ONLY_CONVERSATIONID"}(ga||(ga={}));var Qa;(function(s){s[s.CONV_NOT_FOUND=2500]="CONV_NOT_FOUND",s[s.USER_OR_GRP_NOT_FOUND=2501]="USER_OR_GRP_NOT_FOUND",s[s.CONV_UN_RECORDED_TYPE=2502]="CONV_UN_RECORDED_TYPE"})(Qa||(Qa={}));const ea=0,H=1;var BA=new class{constructor(){this._name="GetC2CMessageRemindType"}init(s){this._core=s}get(s){return pA(this,void 0,void 0,function*(){try{const{common:n}=this._core,g=yield function(E,m){return pA(this,void 0,void 0,function*(){const{toAccount:D,userIDList:M}=E,T={To_Account:D,Peer_Account:M};return m.common.buildAndSendPacket({servcmd:"openim.get_c2c_peer_mute_notifications",data:T})})}({toAccount:n.getCurrentUserID(),userIDList:s},this._core),{MuteNotificationsList:u=[]}=g||{};u.forEach(E=>{const{Peer_Account:m,MuteNotifications:D}=E,M=`${this._core.OuterConstant.CONV_C2C}${m}`,T=Wi(D);NA.patchMessageRemindType([M],T)})}catch(n){console.error(`${this._name}.get fail:`,n)}})}},yA=new class{constructor(){this._name="GetGroupMessageRemindType"}init(s){this._core=s}get(s){return pA(this,void 0,void 0,function*(){if(s.length!==0)try{const n=yield function(u,E){return pA(this,void 0,void 0,function*(){const{groupIDList:m,responseFilter:D}=u,M={GroupIdList:m,ResponseFilter:D};return E.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_self_member_info",data:M})})}({groupIDList:s,responseFilter:{MemberInfoFilter:["MsgFlag"]}},this._core),{GroupInfo:g=[]}=n||{};g.forEach(u=>{var E;const{GroupId:m,MemberList:D}=u,M=((E=D[0])===null||E===void 0?void 0:E.MsgFlag)||"",T=`${this._core.OuterConstant.CONV_GROUP}${m}`;NA.patchMessageRemindType([T],M)})}catch(n){console.error(`${this._name}.get fail:`,n)}})}},NA=new class{constructor(){this._name="ConversationDataHandler",this._totalUnreadCount=0,this._groupAtTipsList=[]}init(s){this._core=s;const{helper:n,notificationCenter:g,appStore:{conversationStore:u},constants:{WORKFLOW_NAME:E,WORKFLOW_STEP:m},InnerEvent:{SYNC_CONVERSATION_LIST:D,MESSAGE_PUSH:M,NEW_MESSAGE:T,MESSAGE_DELETED:P,MESSAGE_REVOKED:W,MESSAGE_MODIFIED:iA,CONVERSATION_UPDATED:EA,LOGOUT:RA,DESTROY:kA},InnerEventSubType:{C2C_MESSAGE_PEER_READ:xA}}=s;this._conversationStore=u,n.registerWorkflowStep(E.SYNC_SERVER_INFO_AFTER_LOGIN,m.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),n.registerWorkflowStep(E.SYNC_SERVER_INFO_AFTER_LOGIN,m.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,this._handleGroupListSyncFinished,this),n.registerWorkflowStep(E.RECEIVE_C2C_NEW_MESSAGE,m.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),n.registerWorkflowStep(E.RECEIVE_C2C_NEW_MESSAGE,m.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),n.registerWorkflowStep(E.RECEIVE_GROUP_NEW_MESSAGE,m.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),n.registerWorkflowStep(E.SYNC_SERVER_INFO_AFTER_RE_ONLINE,m.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),n.registerWorkflowStep(E.RECEIVE_GROUP_TIPS_NOTIFICATION,m.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this);const{InnerEventSubType:{GROUP_AT_TIPS:LA}}=g;g.subscribeInnerEvent(D,this._handleConversationSynced,this),g.subscribeInnerEvent(T,this._handleNewMessage,this),g.subscribeInnerEvent(M,LA,this._handleNewGroupAtTips,this),g.subscribeInnerEvent(P,this._handleMessageDeleted,this),g.subscribeInnerEvent(W,this._handleMessageRevoked,this),g.subscribeInnerEvent(iA,this._handleMessageModified,this),g.subscribeInnerEvent(EA,this._handleConversationUpdated,this),g.subscribeInnerEvent(M,xA,this._handleMessageRead,this),g.subscribeInnerEvent(RA,this._reset,this),g.subscribeInnerEvent(kA,this._dispose,this),s.ssoLog.debug(`${this._name}.init`)}_handleConversationSynced(s){this.updateLocalConversationList({conversationUpdateFieldList:s.conversationUpdateFieldList||[],isFromGetConversations:!0,updateUnreadCount:!0}),this.emitConversationListUpdate()}_handleUnreadSyncFinished(s){const{constants:{WORKFLOW_STEP:n}}=this._core,{conversationUpdateFieldList:g=[],groupTipList:u=[],isUnreadC2CMessage:E}=s.result[n.UNREAD_MESSAGE_SYNC]||{};let m=!1;g.forEach(D=>{const{conversationID:M,unreadCount:T}=D,P=this.getLocalConversation(M);P&&P.unreadCount!==T&&(P.updateUnreadCount({nextUnreadCount:T,isUnreadC2CMessage:E}),m=!0)}),m&&this.emitConversationListUpdate(),this._handleGroupAtTipsSynced(u)}_handleGroupAtTipsSynced(s){var n;for(let g=0;g0&&this._handleNewGroupAtTips({GroupTips:M._groupAtInfoList}),m=!0}m&&this.emitConversationListUpdate()}_handleNewMessage(s){const{conversationUpdateFieldList:n=[],isInstantMessage:g=!0,isUnreadC2CMessage:u=!1,updateUnreadCount:E=!0}=s.result||{};if(n.length===0)return;const{common:{isTopic:m}}=this._core;m(n[0].conversationID)||(this.updateLocalConversationList({conversationUpdateFieldList:n,isInstantMessage:g,isUnreadC2CMessage:u,isFromGetConversations:!1,updateUnreadCount:E}),n.filter(D=>this._isConversationNeedShow(D.conversationID)).length>0&&this.emitConversationListUpdate())}_handleNewGroupAtTips(s){const{GroupTips:n=[]}=s;n.forEach(g=>{const{GroupAtTips:u,MsgBody:E,MsgRandom:m,ClientSeq:D}=g;let M={};u?M=this._convertGroupAtTipsKey(u):E?M=Object.assign({},this._convertGroupAtTipsKey(E)):g.groupAtType&&(M=Object.assign({},g)),M.__random=m,M.__sequence=D,this._groupAtTipsList.push(M)}),console.log(`${this._name}._handleNewGroupAtTips groupAtTipsList: ${JSON.stringify(this._groupAtTipsList)}`),this._updateGroupAtInfoList()}_convertGroupAtTipsKey(s){const{From_Account:n,GroupId:g,MsgSeq:u,GroupAtType:E}=s;return{from:n,groupID:g,sequence:u,groupAtType:E}}_updateGroupAtInfoList(){if(this._groupAtTipsList.length===0)return;const{common:s,OuterConstant:n}=this._core,g=s.getCurrentUserID();let u=!1;this._groupAtTipsList.forEach(E=>{const{groupID:m,from:D}=E;if(D!==g){const M=this.getLocalConversation(`${n.CONV_GROUP}${m}`);M&&(M.updateGroupAtInfoList(E),u=!0)}}),u&&this.emitConversationListUpdate(),this._groupAtTipsList.length=0}_handleMessageDeleted(s){var n,g;console.log(`${this._name}._handleMessageDeleted, conversationID:`,s);const{message:{messageDataHandler:u},OuterConstant:E}=this._core,m=u?.getLocalMessageList(s)||[];let D={};for(let P=(m.length||0)-1;P>=0;P--)if(!m[P].isDeleted&&m[P]._isExcludedFromLastMessage!==!0){D=m[P];break}const M=this.getLocalConversation(s);if(!M)return;let T=!1;M.lastMessage.lastSequence===D.sequence&&M.lastMessage.lastTime===D.time||(!((g=(n=this._core)===null||n===void 0?void 0:n.helper)===null||g===void 0)&&g.isEmpty(D)&&(D=void 0),M.updateLastMessage(D),T=!0),s.startsWith(E.CONV_C2C)&&this.updateUnreadCount(s),T&&(this.emitConversationListUpdate(),console.log(`${this._name}._handleMessageDeleted. update conversationID:${s} with lastMessage:`,M.lastMessage))}_handleMessageRevoked(s){const{messageList:n=[],updateUnreadCount:g=!0}=s;if(console.log(`${this._name}._handleMessageRevoked messageList:${n.length}`),n.length===0)return;let u=null,E=!1;n.forEach(m=>{u=this.getLocalConversation(m.conversationID),u&&(g&&u.reduceUnreadCount()&&(E=!0),u.isLastMessageRevoked({sequence:m.sequence,time:m.time})&&(u.setLastMessageRevoked(!0),u.setLastMessageRevoker(m.revoker),E=!0))}),E&&this.emitConversationListUpdate()}_handleMessageModified(s){const{utils:{isEmpty:n},common:{getMessagePreviewText:g},ssoLog:u}=this._core;u.debug(`${this._name}._handleMessageModified`,JSON.stringify(s));const{conversationID:E,messageList:m}=s,D=this.getLocalConversation(E);if(n(D))return;const{lastMessage:M}=D;if(M){const T=m?.[0]||{};M.lastTime===T.time&&M.lastSequence===T.sequence&&M.version!==T.version&&(M.type=T.type,M.payload=T.payload,M.messageForShow=g(T.type,T.payload),M.cloudCustomData=T.cloudCustomData,M.version=T.version,this.emitConversationListUpdate(),console.log(`${this._name} conversationID:${E} lastMessage updated`))}}_handleConversationUpdated(s){this.emitConversationListUpdate(s?.needSort)}updateLocalConversationList(s){const{isFromGetConversations:n}=s,{newConversationList:g}=this._getTmpConversationListMapping(s);this._sortConversationList(),n||this._updateNewConversationProfile(g),this._core.ssoLog.debug("updateLocalConversationList",` newConversationList: ${g.length}`)}_getTmpConversationListMapping(s){const{OuterConstant:n}=this._core,{conversationUpdateFieldList:g,isFromGetConversations:u,isInstantMessage:E,isUnreadC2CMessage:m=!1,updateUnreadCount:D}=s,M=[],T=g?.length;for(let P=0;P{M[1].isPinned===!0?s(M[1].lastMessage.lastTime)?u.push(M):g.push(M):s(M[1].lastMessage.lastTime)?m.push(M):E.push(M)});const D=g.sort((M,T)=>T[1].lastMessage.lastTime-M[1].lastMessage.lastTime).concat(u).concat(E.sort((M,T)=>T[1].lastMessage.lastTime-M[1].lastMessage.lastTime)).concat(m);this._updateConversationMapFromList(D)}_updateNewConversationProfile(s){if(s.length===0)return;const n=[],g=[],{OuterConstant:{CONV_GROUP:u,CONV_C2C:E}}=this._core;s.forEach(m=>{const{conversationID:D,type:M}=m;if(M===E){const T=D.replace(E,"");n.push(T)}else if(M===u){const T=D.replace(u,"");g.push(T)}}),n.length>0&&this._updateC2CConversation(n),g.length>0&&this._updateGroupConversation(g)}_updateC2CConversation(s){var n;const{OuterConstant:{CONV_C2C:g},appStore:{userStore:u},user:E}=this._core;let m=!1;(n=E.userProfile)===null||n===void 0||n.getUserProfile({userIDList:s}).then(D=>{(D?.data||[]).forEach(M=>{var T;const{userID:P}=M,W=this.getLocalConversation(`${g}${P}`);if(W){const iA=((T=u.getFriend(P))===null||T===void 0?void 0:T.remark)||"";W.remark=iA,W.userProfile=M,m=!0}}),m&&this.emitConversationListUpdate()}).catch(D=>{}),BA.get(s)}_updateGroupConversation(s){return pA(this,void 0,void 0,function*(){const{OuterConstant:{CONV_GROUP:n},appStore:{groupStore:g},utils:{safeStringify:u},ssoLog:E,apiMap:{getGroupProfile:m}}=this._core;let D=!1;try{yield Promise.all(s.map(M=>pA(this,void 0,void 0,function*(){const T=g.getGroup(M),P=this.getLocalConversation(`${n}${M}`);T&&P&&(P.groupProfile=T,D=!0),P&&!P.getProfileCompleted()&&typeof m=="function"&&(yield m({groupID:M}))}))),yA.get(s),D&&this.emitConversationListUpdate()}catch(M){E.debug("_updateGroupConversation",u(M))}})}_handleMessageRead(s){const{OuterConstant:{CONV_C2C:n}}=this._core,{C2cNotifyMsgArray:g=[]}=s||{};g.forEach(u=>{const{To_Account:E,UinPairReadArray:m=[]}=u?.C2cReadedReceipt||{};m?.forEach(D=>{const{LastReadTime:M}=D,T=`${n}${E}`;this._updateConversationReadInfo({conversationID:T,peerReadTime:M}),this._updateMessageListPeerRead({conversationID:T,peerReadTime:M})})})}_updateConversationReadInfo(s){const{appStore:n,utils:{isEmpty:g},common:{getCurrentUserID:u}}=this._core,{conversationID:E,peerReadTime:m}=s,D=n.conversationStore.getConversationMap();if(D.has(E)){const M=D.get(E);M.peerReadTime=m;const T=M?.lastMessage;g(T)||T.fromAccount===u()&&T.lastTime<=m&&!T.isPeerRead&&(T.isPeerRead=!0,n.conversationStore.updateConversation(E,{lastMessage:T}))}}_updateMessageListPeerRead(s){const{notificationCenter:n,OuterEvent:g,message:u}=this._core,{conversationID:E,peerReadTime:m}=s,D=u.messageDataHandler.getLocalMessageList(E),M=u.messageDataHandler.getSparseMessageList(E),T=[];D.forEach(P=>{P.time<=m&&!P.isPeerRead&&P.flow==="out"&&(P.isPeerRead=!0,T.push(P))}),M.forEach(P=>{P.time<=m&&!P.isPeerRead&&P.flow==="out"&&(P.isPeerRead=!0,T.push(P))}),n.emitOuterEvent(g.MESSAGE_READ_BY_PEER,{name:g.MESSAGE_READ_BY_PEER,data:T})}_isConversationNeedShow(s){var n,g;const{OuterConstant:{CONV_GROUP:u,GRP_ROOM:E,GRP_LIVE:m},utils:{isUndefined:D}}=this._core,M=this.getLocalConversation(s);if(D(M))return!0;const T=M.type===u&&((n=M.groupProfile)===null||n===void 0?void 0:n.type)===E,P=M.type===u&&((g=M.groupProfile)===null||g===void 0?void 0:g.type)===m;return!(T||P)}updateUnreadCount(s,n=!0){var g,u;let E=!1;const m=this.getLocalConversation(s),D=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageDataHandler)===null||u===void 0?void 0:u.getLocalMessageList(s);if(!m)return E;const M=m.unreadCount,T=D?.filter(P=>!P.isRead&&!P._onlineOnlyFlag&&!P.isDeleted).length;return console.log(`${this._name}._updateUnreadCount conversationID:${s} currentUnreadCount:${M} newUnreadCount:${T}`),M!==T&&(m.unreadCount=T,E=!0,n===!0&&this.emitConversationListUpdate()),E}emitConversationListUpdate(s=!1){var n,g;s&&this._sortConversationList();const{OuterEvent:{CONVERSATION_LIST_UPDATED:u},conversation:E}=this._core,m=this.getLocalConversationList();this._emitEvent({name:u,data:m,isSyncCompleted:(g=(n=E?.syncConversationHandler)===null||n===void 0?void 0:n.isSyncCompleted)===null||g===void 0?void 0:g.call(n)}),this._emitTotalUnreadCountUpdate()}_emitTotalUnreadCountUpdate(){var s;const n=this.getTotalUnreadMessageCount();this._totalUnreadCount!==n&&(this._core.ssoLog.debug("_emitTotalUnreadCountUpdate",` from ${this._totalUnreadCount} to ${n}`),this._totalUnreadCount=n,this._emitEvent({name:(s=this._core)===null||s===void 0?void 0:s.OuterEvent.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED,data:n}))}_emitEvent(s){var n;(n=this._core)===null||n===void 0||n.notificationCenter.emitOuterEvent(s.name,s)}getTotalUnreadMessageCount(){const{OuterConstant:s,utils:{isEmpty:n}}=this._core,g=this.getLocalConversationList();let u=0;return g.forEach(E=>{E.type!==s.CONV_SYSTEM&&(n(E.messageRemindType)||E.messageRemindType===s.MSG_REMIND_ACPT_AND_NOTE)&&(u+=E.unreadCount)}),u}getLocalConversationList(){return[...this._conversationStore.getConversationMap().values()].filter(s=>this._isConversationNeedShow(s.conversationID))}hasLocalConversation(s){return this._conversationStore.getConversationMap().has(s)}getLocalConversation(s){return this._conversationStore.getConversationMap().get(s)}setLocalConversation(s,n){return this._conversationStore.getConversationMap().set(s,n)}deleteLocalConversation(s){this._conversationStore.getConversationMap().delete(s)}_updateConversationMapFromList(s){this._clearConversationMap();for(const[n,g]of s)this.setLocalConversation(n,g)}_clearConversationMap(){this._conversationStore.getConversationMap().clear()}patchMessageRemindType(s,n){let g=!1;s.forEach(u=>{const E=this.getLocalConversation(u);E?.messageRemindType!==n&&(E.messageRemindType=n,g=!0)}),console.log(`${this._name}.patchMessageRemindType conversationIDList:${s} messageRemindType:${n} hasUpdated:${g}`),g&&this.emitConversationListUpdate()}markMessageAsRead(s){const{message:{messageDataHandler:n}}=this._core,{conversationID:g,lastReadTime:u=0,lastReadSequence:E=0}=s,m=n?.getLocalMessageList(g);if(m.length===0)return;const{length:D}=m;for(let M=D-1;M>=0;M--){const T=m[M],P=u&&T.time>u,W=E&&T.sequence>E;if(!P&&!W){if(T.flow==="in"&&T.isRead)break;T.setIsRead(!0)}}}appendToPinnedConversation(s){const n=[...this._conversationStore.getConversationMap().entries()],g=n.findIndex(u=>u[1].isPinned===!1);n.splice(g,0,[s.conversationID,s]),this._updateConversationMapFromList(n),this.emitConversationListUpdate()}_reset(){this._clearConversationMap(),this._totalUnreadCount=0,this._groupAtTipsList=[]}_dispose(){const{notificationCenter:s,InnerEvent:{NEW_MESSAGE:n,MESSAGE_DELETED:g,MESSAGE_REVOKED:u,MESSAGE_MODIFIED:E,CONVERSATION_UPDATED:m,LOGOUT:D,DESTROY:M,SYNC_CONVERSATION_LIST:T}}=this._core,{InnerEventSubType:{GROUP_AT_TIPS:P}}=s;s.unSubscribeInnerEvent(n,this._handleNewMessage,this),s.unSubscribeInnerEvent(n,P,this._handleNewGroupAtTips,this),s.unSubscribeInnerEvent(g,this._handleMessageDeleted,this),s.unSubscribeInnerEvent(u,this._handleMessageRevoked,this),s.unSubscribeInnerEvent(E,this._handleMessageModified,this),s.unSubscribeInnerEvent(m,this._handleConversationUpdated,this),s.unSubscribeInnerEvent(T,this._handleConversationSynced,this),s.unSubscribeInnerEvent(D,this._reset,this),s.unSubscribeInnerEvent(M,this._dispose,this)}},zA=new class{constructor(){this._name="GetConversationList"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"getConversationList",context:this})}getConversationList(s){return pA(this,void 0,void 0,function*(){return{code:0,data:{conversationList:this._getConversationList(s),isSyncCompleted:this._core.conversation.syncConversationHandler.isSyncCompleted()}}})}_getConversationList(s){const{utils:{isUndefined:n,isArray:g,isPlainObject:u}}=this._core;if(n(s))return NA.getLocalConversationList();if(g(s))return s.length===0?[]:NA.getLocalConversationList().filter(E=>s.includes(E.conversationID));if(u(s)){const{type:E,markType:m,groupName:D,hasUnreadCount:M,hasGroupAtInfo:T}=s;return NA.getLocalConversationList().filter(P=>this._filterType(P,E)&&this._filterMarkType(P,m)&&this._filterGroupName(P,D)&&this._filterUnreadCount(P,M)&&this._filterGroupAtInfo(P,T))}return[]}_filterType(s,n){const{OuterConstant:g}=this._core;return n!==g.CONV_C2C&&n!==g.CONV_GROUP||s.type===n}_filterGroupName(s,n){const{utils:{isString:g}}=this._core;return!g(n)||(n===""?s.conversationGroupList.length===0:s.conversationGroupList.includes(n))}_filterMarkType(s,n){const{utils:{isNumber:g}}=this._core;return!g(n)||(n===0?s.markList.length===0:s.markList.includes(n))}_filterUnreadCount(s,n){let g=!0;return n===!0?g=s.unreadCount>=1:n===!1&&(g=s.unreadCount===0),g}_filterGroupAtInfo(s,n){let g=!0;return n===!0?g=s.groupAtInfoList.length>=1:n===!1&&(g=s.groupAtInfoList.length===0),g}},we=new class{constructor(){this._name="GetConversationProfile"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"getConversationProfile",context:this})}getConversationProfile(s){return pA(this,void 0,void 0,function*(){const{OuterConstant:{CONV_C2C:n,CONV_GROUP:g,GRP_AVCHATROOM:u},appStore:{groupStore:E},utils:{isEmpty:m}}=this._core,D={code:0,data:{}};let M=NA.getLocalConversation(s);if(ks(s))return D.data.conversation=M,D;let T=!1;const P=Bt(s)?n:g;if(m(M)&&(T=!0,M=new Ct({conversationID:s,type:P})),console.log(`${this._name}.getConversationProfile conversationID:${s} isNewConversation:${T}`),D.data.conversation=M,M?.getProfileCompleted())return D;if(P===n){const W=s.replace(n,"");yield this._handleC2CConversation(M,W),T&&(yield BA.get([W]))}if(P===g){const W=s.replace(g,"");if(!E.getGroup(W))return D;yield this._handleGroupConversation(M,W),T&&M.groupProfile.type!==u&&(yield yA.get([W]))}return D})}_handleC2CConversation(s,n){return pA(this,void 0,void 0,function*(){var g,u;const{user:E,helper:m,utils:{isEmpty:D},appStore:{conversationStore:M,userStore:T}}=this._core,{conversationID:P}=s,W=yield(g=E.userProfile)===null||g===void 0?void 0:g.getUserProfile({userIDList:[n]});if(W?.data.length===0)throw new m.ChatError({code:Qa.USER_OR_GRP_NOT_FOUND});s.userProfile=W?.data[0];const iA=(u=T.getFriend(n))===null||u===void 0?void 0:u.remark;D(iA)||s.remark===iA||(s.remark=iA),s.setProfileCompleted();const EA=NA.hasLocalConversation(P);console.log(`${this._name}._handleC2CConversation conversationID:${P} hasLocalConversation: ${EA}`),EA?M.updateConversation(P,s):NA.appendToPinnedConversation(s)})}_handleGroupConversation(s,n){return pA(this,void 0,void 0,function*(){const{apiMap:{getGroupProfile:g},appStore:{conversationStore:u}}=this._core,{conversationID:E}=s,m=yield g({groupID:n});s.groupProfile=m?.data.group,s.setProfileCompleted();const D=NA.hasLocalConversation(E);console.log(`${this._name}._handleGroupConversation conversationID:${E} hasLocalConversation: ${D}`),D?u.updateConversation(E,s):NA.appendToPinnedConversation(s)})}},Ie=new class{init(s){const{helper:n}=s;n.registerApi({apiName:"getTotalUnreadMessageCount",context:this})}getTotalUnreadMessageCount(){return NA.getTotalUnreadMessageCount()}},Ge=new class{constructor(){this._serverGroupConversationLastReadSeqMap=new Map,this._name="SetMessageRead"}init(s){this._core=s;const{helper:n,common:{isTopic:g},notificationCenter:u,InnerEvent:{MESSAGE_PUSH:E},InnerEventSubType:{ALL_MESSAGE_READ:m}}=s;n.registerApi({apiName:"setMessageRead",context:this,matcher:D=>!g(D[0].conversationID)}),n.registerApi({apiName:"setAllMessageRead",context:this}),u.subscribeInnerEvent(E,m,this._handleAllMessageRead,this)}handleC2CMessageReadSync(s){const{helper:{isEmpty:n},OuterConstant:g}=this._core;s.forEach(u=>{const{ReadC2cMsgNotify:E}=u;if(!n(E)){const{UinPairReadArray:m=[]}=E;m.forEach(D=>{const{From_Account:M,LastReadTime:T}=D,P=`${g.CONV_C2C}${M}`;console.log(`${this._name}.handleC2CMessageReadSync conversationID:${P} lastReadTime:${T}`),NA.markMessageAsRead({conversationID:P,lastReadTime:T}),NA.updateUnreadCount(P)})}})}handleGroupMessageReadSync(s){const{OuterConstant:n,utils:{isUndefined:g}}=this._core;s.forEach(u=>{const{GroupReadInfoArray:E}=u.MsgBody;g(E)||E.forEach(m=>{const{GroupId:D,LastReadMsgSeq:M}=m,T=`${n.CONV_GROUP}${D}`;console.log(`${this._name}.handleGroupMessageReadSync conversationID:${T} lastReadSequence:${M}`),NA.markMessageAsRead({conversationID:T,lastReadSequence:M}),NA.updateUnreadCount(T),this._clearGroupAtInfoList(T)})})}setMessageRead(s){return pA(this,void 0,void 0,function*(){var n,g;const{OuterConstant:u}=this._core,{conversationID:E}=s,m={code:0,data:{}},D=NA.getLocalConversation(E);let M=`${this._name}.setMessageRead conversationID:${E} unreadCount:${D?.unreadCount||0}`;if(m.successLog={message:M},!D)return m;const T=!(!((g=(n=this._core)===null||n===void 0?void 0:n.helper)===null||g===void 0)&&g.isEmpty(D.groupAtInfoList));if(D.type===u.CONV_GROUP&&T&&this._deleteGroupAtTips(E),D.unreadCount===0)return m;const{helper:{ChatError:P}}=this._core;try{if(D.type===u.CONV_C2C){const W=this._getLocalMessageMaxTime(D);M+=`lastMessageTime:${W}`,yield this._setC2CMessageRead(E,W)}if(D.type===u.CONV_GROUP){const W=this._getLocalMessageMaxSequence(D);M+=`lastMessageSequence:${W}`,yield this._setGroupMessageRead(E,W)}}catch(W){const{errorCode:iA,errorInfo:EA}=W;throw new P({functionName:"setMessageRead",code:iA,message:EA,moreMessage:M})}return D.type===u.CONV_SYSTEM&&(D.unreadCount=0),NA.emitConversationListUpdate(),Object.assign(Object.assign({},m),{successLog:{message:M}})})}setAllMessageRead(){return pA(this,arguments,void 0,function*(s={}){const{OuterConstant:{READ_ALL_MSG:n},utils:{safeStringify:g}}=this._core;let u=`scope:${s.scope}`;s.scope||(s.scope=n);const{scope:E}=s,m=this._generateSetAllMessageReadRequestData(E);if(m.allC2CMessageReadStatus===ea&&m.groupMessageReadInfoList.length===0)return{code:0};try{const D=yield function(M){return pA(this,void 0,void 0,function*(){const{allC2CMessageReadStatus:T,groupMessageReadInfoList:P}=M,W={C2CReadAllMsg:T,GroupReadInfo:P};return ho.core.common.buildAndSendPacket({servcmd:"openim.read_all_unread_msg",data:W})})}(m);if(D){const{GroupReadInfoArray:M,C2CReadAllMsg:T}=D,P=this._parseGroupReadInfo(M);this._updateAllConversationReadStatus({allC2CMessageReadStatus:T})>0&&NA.emitConversationListUpdate(),u+=`failureGroupInfoList:${g(P)}`}return{code:0,successLog:{message:u}}}catch(D){const{errorCode:M}=D;throw new this._core.helper.ChatError({functionName:"setAllMessageRead",code:M,moreMessage:u})}})}_handleAllMessageRead(s){const{GroupReadInfoArray:n,C2CReadAllMsg:g}=s;this._parseGroupReadInfo(n),this._updateAllConversationReadStatus({allC2CMessageReadStatus:g})>0&&NA.emitConversationListUpdate()}_updateAllConversationReadStatus(s){const{OuterConstant:{CONV_C2C:n,CONV_GROUP:g},appStore:u}=this._core,E=u.conversationStore.getConversationMap(),{allC2CMessageReadStatus:m}=s;let D=0;for(const[M,T]of E)if(T.unreadCount>=1){if(m===H&&T.type===n){const P=this._getLocalMessageMaxTime(T);NA.markMessageAsRead({conversationID:M,lastReadTime:P})}else if(T.type===g){const P=M.replace(g,"");if(this._serverGroupConversationLastReadSeqMap.has(P)){const W=this._serverGroupConversationLastReadSeqMap.get(P);NA.markMessageAsRead({conversationID:M,lastReadSequence:W})}}NA.updateUnreadCount(M,!1)&&(D+=1)}return D}_generateSetAllMessageReadRequestData(s){const{OuterConstant:{CONV_C2C:n,CONV_GROUP:g,READ_ALL_C2C_MSG:u},appStore:E}=this._core,m={allC2CMessageReadStatus:ea,groupMessageReadInfoList:[]},D=E.conversationStore.getConversationMap();for(const[,M]of D){const{type:T,unreadCount:P}=M;if(this._shouldSetAllMessageRead({scope:s,type:T,unreadCount:P})){if(T===n&&m.allC2CMessageReadStatus===ea){if(m.allC2CMessageReadStatus=H,s===u)break}else if(T===g){const W=this._getLocalMessageMaxSequence(M),{groupID:iA}=M.groupProfile;m.groupMessageReadInfoList.push({GroupId:iA,MsgSeq:W})}}}return m}_parseGroupReadInfo(s){const{utils:{isUndefined:n}}=this._core,g=[];return s?.forEach(u=>{const{GroupId:E,MsgSeq:m,RetCode:D,LastReadMsgSeq:M}=u;n(D)?this._serverGroupConversationLastReadSeqMap.set(E,M):(this._serverGroupConversationLastReadSeqMap.set(E,m),D!==0&&g.push(`${E}-${m}-${D}`))}),g}_deleteGroupAtTips(s){return pA(this,void 0,void 0,function*(){console.log(`${this._name}._deleteGroupAtTips conversationID:${s}`);const n=NA.getLocalConversation(s);if(!n)return;const g=n?.groupAtInfoList||[];if(g.length!==0)try{const{common:{getCurrentUserID:u,isCommunity:E},OuterConstant:{CONV_GROUP:m,CONV_AT_ALL:D}}=this._core;let M=[...g];if(E({groupID:s.replace(m,"")})&&(M=g.filter(P=>!P.atTypeArray.includes(D)),M.length===0))return void this._clearGroupAtInfoList(s,!1);const T=M.map(P=>({From_Account:P.from,To_Account:u(),MsgSeq:P.__sequence,MsgRandom:P.__random,GroupId:P.groupID}));yield function(P,W){return pA(this,void 0,void 0,function*(){const{messageListToDelete:iA}=P,EA={DelMsgList:iA};return W.common.buildAndSendPacket({servcmd:"openim.deletemsg",data:EA})})}({messageListToDelete:T},this._core),console.log(`${this._name}._deleteGroupAtTips ok. count:${g.length}`),this._clearGroupAtInfoList(s)}catch(u){console.error(`${this._name}._deleteGroupAtTips fail:`,u)}})}_clearGroupAtInfoList(s,n=!0){const g=NA.getLocalConversation(s);g&&(g.groupAtInfoList.length>0&&(g.clearGroupAtInfoList(),console.log(`${this._name}._clearGroupAtInfoList conversationID:${s} needEmitConversationUpdate:${n}`)),n&&NA.emitConversationListUpdate())}_getLocalMessageMaxTime(s){var n;const{conversationID:g}=s,u=this._core.message.messageDataHandler.getLocalMessageList(g),E=Math.max(...u.map(D=>D.time));let m=((n=s?.lastMessage)===null||n===void 0?void 0:n.lastTime)||0;return E>m&&(console.log(`${this._name}._getLocalMessageMaxTime update lastMessageTime from ${m} to ${E}`),m=E),m}_getLocalMessageMaxSequence(s){var n;const{conversationID:g}=s,u=this._core.message.messageDataHandler.getLocalMessageList(g),E=Math.max(...u.map(D=>D.sequence));let m=((n=s?.lastMessage)===null||n===void 0?void 0:n.lastSequence)||0;return E>m&&(console.log(`${this._name}._getLocalMessageMaxSequence update lastMessageSequence from ${m} to ${E}`),m=E),m}_setC2CMessageRead(s,n){return pA(this,void 0,void 0,function*(){try{yield function(g,u){return pA(this,void 0,void 0,function*(){return u.common.buildAndSendPacket({servcmd:"openim.msgreaded",data:g})})}({C2CMsgReaded:{Cookie:"",C2CMsgReadedItem:[{To_Account:s.replace("C2C",""),LastedMsgTime:n,Receipt:1}]}},this._core),console.log(`${this._name}._setC2CMessageRead ok, lastReadTime:${n}`),NA.markMessageAsRead({conversationID:s,lastReadTime:n}),NA.updateUnreadCount(s)}catch(g){throw console.warn(`${this._name}._setC2CMessageRead fail:`,g),g}})}_setGroupMessageRead(s,n){return pA(this,void 0,void 0,function*(){try{yield function(g,u){return pA(this,void 0,void 0,function*(){const{groupID:E,lastMessageSequence:m}=g,D={GroupId:E,MsgReadedSeq:m};return u.common.buildAndSendPacket({servcmd:"group_open_http_svc.msg_read_report",data:D})})}({groupID:s.replace("GROUP",""),lastMessageSequence:n},this._core),console.log(`${this._name}._setGroupMessageRead ok, lastReadSequence:${n}`),NA.markMessageAsRead({conversationID:s,lastReadSequence:n}),NA.updateUnreadCount(s)}catch(g){throw console.warn(`${this._name}._setGroupMessageRead fail:`,g),g}})}_shouldSetAllMessageRead(s){const{OuterConstant:{CONV_C2C:n,CONV_GROUP:g,READ_ALL_MSG:u,READ_ALL_C2C_MSG:E,READ_ALL_GROUP_MSG:m}}=this._core,{type:D,scope:M,unreadCount:T}=s;return!(T<=0)&&(!(D!==n||![u,E].includes(M))||!(D!==g||![u,m].includes(M)))}},ce=new class{constructor(){this._name="PinConversation"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"pinConversation",context:this})}handleConversationPinned(s,n){const{utils:{isArray:g}}=this._core;if(!g(s))return;const{OuterConstant:u}=this._core;let E=!1;s.forEach(m=>{const{Type:D,Peer_Account:M,GroupId:T}=m;let P;D===1?P=NA.getLocalConversation(`${u.CONV_C2C}${M}`):D===2&&(P=NA.getLocalConversation(`${u.CONV_GROUP}${T}`)),P&&(console.log(`${this._name}.handleConversationPinned conversationID:${P.conversationID} localPinned:${P.isPinned} remotePinned:${n}`),n&&!P.isPinned&&(P.isPinned=!0,E=!0),!n&&P.isPinned&&(P.isPinned=!1,E=!0))}),E&&NA.emitConversationListUpdate(!0)}pinConversation(s){return pA(this,void 0,void 0,function*(){const{OuterConstant:n,common:g,helper:{ChatError:u}}=this._core,{conversationID:E,isPinned:m}=s,D={code:0,data:{conversationID:E}},M=NA.getLocalConversation(E);if(M&&M.isPinned===m)return D;if(ks(E))return M&&(M.isPinned=m),NA.emitConversationListUpdate(!0),D;const T=`conversationID:${E} isPinned:${m}`;try{let P=null;if(Bt(E)?P={Type:1,To_Account:E.replace(n.CONV_C2C,"")}:ug(E)&&(P={Type:2,GroupId:E.replace(n.CONV_GROUP,"")}),yield function(iA,EA){return pA(this,void 0,void 0,function*(){const{fromAccount:RA,operationType:kA,itemList:xA}=iA,LA={From_Account:RA,OperationType:kA,RecentContactItem:xA};return EA.common.buildAndSendPacket({servcmd:"recentcontact.top",data:LA})})}({fromAccount:g.getCurrentUserID(),operationType:m===!0?1:2,itemList:[P]},this._core)){if(M)M.isPinned!==m&&(M.isPinned=m);else{const iA=new Ct({conversationID:E,type:Bt(E)?n.CONV_C2C:n.CONV_GROUP,isPinned:m});NA.setLocalConversation(E,iA)}NA.emitConversationListUpdate(!0)}return Object.assign(Object.assign({},D),{successLog:{message:T}})}catch(P){const{errorCode:W,errorInfo:iA}=P;throw new u({functionName:"pinConversation",code:W,message:iA,moreMessage:T})}})}},Fe=new class{constructor(){this._name="DeleteConversation"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"deleteConversation",context:this})}handleConversationDeleted(s){const{utils:{isArray:n}}=this._core;if(!n(s))return;const{OuterConstant:g}=this._core,u=[];s.forEach(E=>{const{Type:m,Peer_Account:D,GroupId:M}=E;m===1&&u.push(`${g.CONV_C2C}${D}`),m===2&&u.push(`${g.CONV_GROUP}${M}`)}),console.log(`${this._name}.handleConversationDeleted conversationIDList:${u}`),this._deleteLocalConversationList(u)}deleteConversation(s){return pA(this,void 0,void 0,function*(){const{utils:{isString:n}}=this._core;if(n(s))return this._deleteConversation({conversationIDList:[s],flag:ga.ONLY_CONVERSATIONID});const g=Object.assign({},s);return g.conversationIDList.length>100&&(g.conversationIDList=g.conversationIDList.slice(0,100)),this._deleteConversation(g)})}_deleteConversation(s){return pA(this,void 0,void 0,function*(){const{conversationIDList:n,clearHistoryMessage:g=!0,flag:u=0}=s,{helper:{ChatError:E}}=this._core,m=`conversationIDList:${n} clearHistoryMessage:${g}`;try{const D=yield Promise.all([this._deleteConversationFromLocal(n),this._deleteConversationFromServer(n,g)]),M=[...D[0],...D[1]];if(M.length===0)throw new this._core.helper.ChatError({code:Qa.CONV_NOT_FOUND});return{code:0,data:u===ga.ONLY_CONVERSATIONID?{conversationID:M[0]}:{conversationIDList:M},successLog:{message:m}}}catch(D){const{errorCode:M,errorInfo:T}=D;throw new E({code:M,message:T,moreMessage:m})}})}_deleteConversationFromLocal(s){const{OuterConstant:n}=this._core;return s.filter(g=>{var u;if(!NA.hasLocalConversation(g))return!1;const E=(u=NA.getLocalConversation(g))===null||u===void 0?void 0:u.type;return E!==n.CONV_GROUP||this._hasLocalGroup(g)?E===n.CONV_SYSTEM&&(this._deleteLocalConversation(g),!0):(this._deleteLocalConversation(g),!0)})}_deleteConversationFromServer(s,n){return pA(this,void 0,void 0,function*(){const{OuterConstant:g,common:u}=this._core,E={fromAccount:u.getCurrentUserID(),conversationList:[],clearHistoryMessage:n?1:0};if(s.forEach(D=>{var M;if(NA.hasLocalConversation(D)){const T=((M=NA.getLocalConversation(D))===null||M===void 0?void 0:M.type)||"",P=D.replace(T,"");T===g.CONV_C2C?E.conversationList.push({To_Account:P,Type:1}):T===g.CONV_GROUP&&this._hasLocalGroup(D)&&E.conversationList.push({ToGroupid:P,Type:2})}}),E.conversationList.length===0)return[];const m=yield function(D,M){return pA(this,void 0,void 0,function*(){const{fromAccount:T,conversationList:P,clearHistoryMessage:W}=D,iA={From_Account:T,ContactItem:P,ClearRamble:W};return M.common.buildAndSendPacket({servcmd:"recentcontact.batch_delete",data:iA})})}(E,this._core);if(m){const{ResultItem:D=[]}=m,M=[];return D.length>0&&D.forEach(T=>{if(T.ResultCode===0){const P=T.Type===1?`${g.CONV_C2C}${T.To_Account}`:`${g.CONV_GROUP}${T.ToGroupid}`;M.push(P)}}),this._deleteLocalConversationList(M),M}return[]})}_deleteLocalConversationList(s){let n=!1;s.forEach(g=>{NA.hasLocalConversation(g)&&(this._deleteLocalConversation(g,!1),n=!0)}),console.log(`${this._name}._deleteLocalConversationList isUpdate:${n}`),n&&NA.emitConversationListUpdate()}_deleteLocalConversation(s,n=!0){const g=NA.hasLocalConversation(s);console.log(`${this._name}._deleteLocalConversation conversationID:${s} has:${g}`),g&&(NA.deleteLocalConversation(s),this._deleteConversationLocalMessage(s),n&&NA.emitConversationListUpdate())}_hasLocalGroup(s){const{OuterConstant:{CONV_GROUP:n},appStore:{groupStore:g}}=this._core,u=s.replace(n,"");return!!g.getGroup(u)}_deleteConversationLocalMessage(s){console.log(`${this._name}._deleteConversationLocalMessage conversationID:${s}`),this._core.message.messageDataHandler.deleteConversationMessageList(s),this._core.message.messageHistory.completedHistoryConversations.delete(s)}},St=new class{constructor(){this._name="SetConversationDraft"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"setConversationDraft",context:this})}setConversationDraft(s){return pA(this,void 0,void 0,function*(){const{conversationID:n,draftText:g}=s;if(console.log(`${this._name} conversationID:${n} draftText:${g}`),!NA.hasLocalConversation(n))throw new this._core.helper.ChatError({code:Qa.CONV_NOT_FOUND});const u=NA.getLocalConversation(n);return u?.setDraftText(g),NA.emitConversationListUpdate(),{code:0,data:{conversation:u}}})}},jt=new class{constructor(){this._name="SetC2CMessageRemindType"}init(s){this._core=s}set(s,n){return pA(this,void 0,void 0,function*(){s.length>30&&(console.warn(`${this._name}.set userIDList length:${s.length} exceeds limit 30`),s.splice(30));const g=function(){const{MSG_REMIND_ACPT_AND_NOTE:P,MSG_REMIND_DISCARD:W,MSG_REMIND_ACPT_NOT_NOTE:iA}=ho.core.OuterConstant;return{[P]:0,[W]:1,[iA]:2}}()[n],u=yield function(P,W){return pA(this,void 0,void 0,function*(){const{userIDList:iA,receiveMessageOption:EA}=P,RA={Peer_Account:iA,Mute_Notifications:EA};return W.common.buildAndSendPacket({servcmd:"openim.set_c2c_peer_mute_notifications",data:RA})})}({userIDList:s,receiveMessageOption:g},this._core),{ErrorList:E=[]}=u||{},m=[];E.forEach(P=>{const{Peer_Account:W,ErrorCode:iA}=P;m.push({userID:W,code:iA});const EA=s.indexOf(W);EA>-1&&s.splice(EA,1)});const D=[],M=[],{OuterConstant:T}=this._core;return s.forEach(P=>{M.push(`${T.CONV_C2C}${P}`),D.push({userID:P})}),NA.patchMessageRemindType(M,n),{code:0,data:{successUserIDList:D,failureUserIDList:m}}})}},ci=new class{constructor(){this._name="SetGroupMessageRemindType"}init(s){this._core=s}set(s,n){return pA(this,void 0,void 0,function*(){const{common:{getCurrentUserID:g,isTopic:u},OuterConstant:E}=this._core;if(yield function(m,D){return pA(this,void 0,void 0,function*(){const{groupID:M,userID:T,receiveMessageOption:P}=m,W={GroupId:M,Member_Account:T,MsgFlag:P};return D.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:W})})}({groupID:s,userID:g(),receiveMessageOption:n},this._core),!u(s)){const m=`${E.CONV_GROUP}${s}`;NA.patchMessageRemindType([m],n)}return{code:0,data:{groupID:s,messageRemindType:n}}})}},ft=new class{constructor(){this._name="SetMessageRemindType"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"setMessageRemindType",context:this})}handleC2CMessageRemindTypeSync(s){const{helper:{isEmpty:n},OuterConstant:g,ssoLog:u}=this._core;s.forEach(E=>{const{MuteNotificationsSync:m}=E;if(!n(m)){const{To_Account:D,MuteNotifications:M}=m,T=D.map(W=>`${g.CONV_C2C}${W}`),P=Wi(M);u.debug(`${this._name}.handleC2CMessageRemindTypeSync conversationIDList:${T} messageRemindType:${P}`),NA.patchMessageRemindType(T,P)}})}setMessageRemindType(s){return pA(this,void 0,void 0,function*(){const n="setMessageRemindType",{groupID:g,userIDList:u,messageRemindType:E}=s,{helper:m,utils:{isUndefined:D},ssoLog:M}=this._core;try{if(!D(g))return M.debug(`${this._name}.${n} groupID:${g} messageRemindType:${E}`),yield ci.set(g,E);if(!D(u))return M.debug(`${this._name}.${n} userIDList:${u} messageRemindType:${E}`),yield jt.set(u,E);throw new m.ChatError({functionName:n,message:"userIDList or groupID is required"})}catch(T){throw new m.ChatError({functionName:n,code:T?.errorCode,message:T?.errorInfo,moreMessage:`groupID:${g} userIDList:${u} messageRemindType:${E}`})}})}},Bi=new class{init(s){s.ssoLog.debug("ConversationAction.init"),this._core=s,zA.init(s),we.init(s),Ie.init(s),Ge.init(s),ce.init(s),Fe.init(s),St.init(s),ft.init(s);const{notificationCenter:n,InnerEvent:{MESSAGE_PUSH:g,DESTROY:u}}=this._core,{InnerEventSubType:{CONV_MODIFIED:E,C2C_MESSAGE_READ_SYNC:m,GROUP_MESSAGE_READ_SYNC:D,C2C_REMIND_TYPE_SYNC:M}}=n;n.subscribeInnerEvent(g,E,this._onConversationModified,this),n.subscribeInnerEvent(g,m,this._onC2CMessageReadSync,this),n.subscribeInnerEvent(g,M,this._onC2CMessageRemindTypeSync,this),n.subscribeInnerEvent(g,D,this._onGroupMessageReadSync,this),n.subscribeInnerEvent(u,this._dispose,this)}_onConversationModified(s){const{constants:{ConvModifyPushType:n}}=this._core,{RecentContactMod:g=[]}=s;g.forEach(u=>{const{PushType:E}=u;if(E===n.CONV_DELETED){const{RecentContactList:m}=u.RecentContactDeleteItem;Fe.handleConversationDeleted(m)}if(E===n.CONV_PINED){const{RecentContactList:m}=u.RecentContactTopItem;ce.handleConversationPinned(m,!0)}if(E===n.CONV_UNPINED){const{RecentContactList:m}=u.RecentContactTopItem;ce.handleConversationPinned(m,!1)}})}_onC2CMessageReadSync(s){const{C2cNotifyMsgArray:n=[]}=s;Ge.handleC2CMessageReadSync(n)}_onC2CMessageRemindTypeSync(s){const{C2cNotifyMsgArray:n=[]}=s;ft.handleC2CMessageRemindTypeSync(n)}_onGroupMessageReadSync(s){const{GroupTips:n=[]}=s;Ge.handleGroupMessageReadSync(n)}_dispose(){const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:n,DESTROY:g}}=this._core,{InnerEventSubType:{CONV_MODIFIED:u,C2C_MESSAGE_READ_SYNC:E,GROUP_MESSAGE_READ_SYNC:m,C2C_REMIND_TYPE_SYNC:D}}=s;s.unSubscribeInnerEvent(n,u,this._onConversationModified,this),s.unSubscribeInnerEvent(n,E,this._onC2CMessageReadSync,this),s.unSubscribeInnerEvent(n,D,this._onC2CMessageRemindTypeSync,this),s.unSubscribeInnerEvent(n,m,this._onGroupMessageReadSync,this),s.unSubscribeInnerEvent(g,this._dispose,this)}},Ao=new class{init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"setAllReceiveMessageOpt",context:this})}setAllReceiveMessageOpt(s){return pA(this,void 0,void 0,function*(){try{const{OuterConstant:{MSG_REMIND_ACPT_NOT_NOTE:n}}=this._core,{messageRemindType:g=n,isRepeated:u=!0}=s,{startTime:E=0,endTime:m=0}=this._calcStartAndEndTime(s),D=yield function(M){return pA(this,void 0,void 0,function*(){const{common:T}=ho.core,{startTime:P,endTime:W,isRepeated:iA,messageRemindType:EA}=M,RA={StartTime:P,EndTime:W,IsRepeated:iA,Level:EA};return T.buildAndSendPacket({servcmd:"im_msg_db_logic.ws_set_do_not_disturb",data:RA})})}({messageRemindType:this._getType(g),startTime:E,endTime:m,isRepeated:u?is.ON:is.OFF});return{code:0,data:{errorCode:D.ErrorCode,errorInfo:D.ErrorInfo}}}catch(n){oc("setAllReceiveMessageOpt",n)}})}_calcStartAndEndTime(s){const{startHour:n=0,startMinute:g=0,startSecond:u=0,duration:E=0,isRepeated:m=!0}=s,D=new Date,M=new Date(D.getFullYear(),D.getMonth(),D.getDate(),n,g,u),T=Math.round(M.getTime()/1e3);let P=T+E;return m&&E>=86400&&(P=T+86400),{startTime:T,endTime:P}}_getType(s){const{OuterConstant:n}=this._core;return{[n.MSG_REMIND_ACPT_AND_NOTE]:0,[n.MSG_REMIND_DISCARD]:1,[n.MSG_REMIND_ACPT_NOT_NOTE]:2}[s]}},Is=new class{init(s){this._core=s;const{helper:n,notificationCenter:g,InnerEvent:u}=s;n.registerApi({apiName:"getAllReceiveMessageOpt",context:this}),g.subscribeInnerEvent(u.MESSAGE_PUSH,g.InnerEventSubType.ALL_RECEIVE_MESSAGE_OPTION,this.onAllReceiveMsgOptionNotify,this)}onAllReceiveMsgOptionNotify(s){const n=this._handleResult(s),{notificationCenter:g,OuterEvent:{ALL_RECEIVE_MESSAGE_OPT_UPDATED:u}}=this._core;g.emitOuterEvent(u,{name:u,data:n})}getAllReceiveMessageOpt(){return pA(this,void 0,void 0,function*(){try{const s=yield function(){return pA(this,void 0,void 0,function*(){const{common:n}=ho.core,g={To_Account:n.getCurrentUserID()};return n.buildAndSendPacket({servcmd:"im_msg_db_logic.ws_get_do_not_disturb",data:g})})}();return{code:0,data:this._handleResult(s)}}catch(s){oc("getAllReceiveMessageOpt",s)}})}_handleResult(s){const{OuterConstant:n}=this._core,{MSG_REMIND_ACPT_AND_NOTE:g,MSG_REMIND_DISCARD:u,MSG_REMIND_ACPT_NOT_NOTE:E}=n,m={0:g,1:u,2:E},{Level:D,StartTime:M,EndTime:T,IsRepeated:P}=s;return{messageRemindType:m[D]||g,startTime:M,endTime:T,isRepeated:P===is.ON}}},Uo=new class{init(s){s.ssoLog.debug("ReceiveMessageOptions.init"),this._core=s,jt.init(s),ci.init(s),BA.init(s),yA.init(s),Ao.init(s),Is.init(s)}};const ii=s=>!Bt(s)&&!ug(s)&&!ks(s),Fr={getConversationProfile:[{key:"conversationID",required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!ii(s)||"conversationID is invalid."}],setMessageRead:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!ii(s)||"conversationID is invalid."}},pinConversation:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!ii(s)||"conversationID is invalid."},isPinned:{required:!0,rules:["boolean"],allowEmpty:!1}},deleteConversation:[{key:"options",required:!0,rules:["string","object"],allowEmpty:!1,customValidator:s=>{const{core:{utils:{isArray:n,isObject:g,isString:u}}}=ho;if(!u(s)&&!g(s))return"options is String or Object.";if(u(s)&&ii(s))return"conversationID is invalid.";if(g(s)){if(!n(s.conversationIDList))return"conversationIDList is not Array.";if(s.conversationIDList.length===0)return"conversationIDList is empty.";if(s.conversationIDList.some(E=>{if(ii(E))return!0}))return"conversationIDList includes invalid conversationID.";if(s.clearHistoryMessage&&typeof s.clearHistoryMessage!="boolean")return"clearHistoryMessage is not Boolean."}return!0}}],setConversationDraft:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!(!Bt(s)&&!ug(s))||"conversationID is invalid."},draftText:{required:!0,rules:["string"],allowEmpty:!0}},setAllReceiveMessageOpt:{messageRemindType:{required:!1,rules:["string"],allowEmpty:!0},startHour:{required:!1,rules:["number"],allowEmpty:!0},startMinute:{required:!1,rules:["number"],allowEmpty:!0},startSecond:{required:!1,rules:["number"],allowEmpty:!0},duration:{required:!1,rules:["number"],allowEmpty:!0},isRepeated:{required:!1,rules:["boolean"],allowEmpty:!0}}},Zo={getConversationList:!0,getConversationProfile:!0,getTotalUnreadCount:!0,setMessageRead:!0,pinConversation:!0,deleteConversation:!0,setConversationDraft:!0,setMessageRemindType:!0,getAllReceiveMessageOpt:!0,setAllReceiveMessageOpt:!0};var jn=new class{constructor(){this.name="Conversation"}install(s){ho.init(s),Bi.init(s),Uo.init(s),NA.init(s),s.helper.registerValidateConfig({auth:Zo,params:Fr})}};const Wn=new class{init(s){this.core=s}},ta="AVChatRoom",qr="AV_HISTORY_MSG",sc="GRP_COUNTER",Hu="Set",mm="Increase",Ri="Decrease",oi=0,yo=1,on=2,os=["Type","Name","Introduction","Notification","FaceUrl","Owner_Account","CreateTime","InfoSeq","LastInfoTime","LastMsgTime","MemberNum","MaxMemberNum","ApplyJoinOption","NextMsgSeq","ShutUpAllMember","InviteJoinOption","LastRecallTime"],Eg=["Type","Name","Introduction","Notification","FaceUrl","CreateTime","Owner_Account","LastInfoTime","LastMsgTime","NextMsgSeq","MemberNum","MaxMemberNum","ApplyJoinOption","InviteJoinOption"],Ol=["Role","JoinTime","MsgFlag","MsgSeq"],fd=["Role","JoinTime","MsgSeq","MsgFlag","NameCard"],Lc=0,Mr=1,SI="notStart",su="resolved",Og="rejected",nu=10018,MI=11e3,Uc=2,qu=["Owner","Admin","Member"],fm=["Role","JoinTime","NameCard","ShutUpUntil","OnlineStatus"],ym=0,Dm=1,Sm=2,gD=4,cD=1,kv=2,lD=3,ID=4,Lv=5,dT=1,yd=0,CT=4,uD=6,hT=400,ED=300,BT={from:!0,groupID:!0,groupName:!0,to:!0},Uv={from:!0,groupID:!0,groupName:!0,to:!0,type:!0},QT=2,Fv=4,pT=5,mT=7,dD=8,CD=15,TQ=20,Mm=21,vm=2600,Dd=2602,fT=2603,yT=2620,Rm=2621,hD=2623,Ih=2660,DT=2661,ST=2681,wm=2683,Ov=2684,BD=2685,_m=2687,Pv=3122,MT=10018,vT={0:"DisableInvite",1:"NeedPermission",2:"FreeAccess"},xv=s=>s===Wn.core.OuterConstant.GRP_PUBLIC,Sd=s=>s===Wn.core.OuterConstant.GRP_AVCHATROOM,Tm=(s,n)=>{const{isArray:g}=Wn.core.utils;if(!g(s)||!g(n))return!1;let u=!1;return n.forEach(({key:E,value:m})=>{const D=s.find(M=>M.key===E);D?D.value!==m&&(D.value=m,u=!0):(s.push({key:E,value:m}),u=!0)}),u},Md=s=>{const n=[];if(!s)return n;for(let g=0,u=s.length;g{const n=[];for(let g=0,u=s.length;g0&&M.members.forEach(T=>{T.userID===this.selfInfo.userID&&D(this.selfInfo,T,["sequence"])})}updateSelfInfo(n){const{nameCard:g,joinTime:u,role:E,messageRemindType:m,readedSequence:D,excludedUnreadSequenceList:M}=n,{common:{deepMerge:T}}=Wn.core;T(this.selfInfo,{nameCard:g,joinTime:u,role:E,messageRemindType:m,readedSequence:D,excludedUnreadSequenceList:M},[],["",null,void 0,0,NaN])}setSelfNameCard(n){this.selfInfo.nameCard=n}}var Yi=new class{constructor(){this._name="GroupDataHandler"}init(s){this._core=s;const{appStore:{groupStore:n}}=s;this._groupMap=n.getGroupMap()}hasLocalGroup(s){return this._groupMap.has(s)}getLocalGroup(s){return this._groupMap.get(s)}updateLocalGroup(s){const{common:{getCurrentUserID:n}}=this._core;let g;s.forEach(E=>{var m;g=E.groupID,this.hasLocalGroup(g)?(m=this.getLocalGroup(g))===null||m===void 0||m.updateGroup(E):(this._groupMap.set(g,new Ku(E)),this._clearGroupLocalMessage(g))});const u=n();for(const[,E]of this._groupMap)E.selfInfo.userID=u,E.selfInfo.role==="Owner"&&(E.ownerID=u)}deleteLocalGroup(s){this._groupMap.delete(s)}getLocalGroupList(){const{OuterConstant:{GRP_ROOM:s,GRP_LIVE:n}}=this._core;return[...this._groupMap.values()].filter(g=>{const{type:u}=g;return u!==s&&u!==n})}clearLocalGroup(){this._groupMap.clear()}emitGroupListUpdate(){const s=this.getLocalGroupList(),{OuterEvent:{GROUP_LIST_UPDATED:n},notificationCenter:g}=this._core;g.emitOuterEvent(n,{name:n,data:s})}updateConversationGroupProfile(s){const{appStore:{conversationStore:n},OuterConstant:{CONV_GROUP:g}}=this._core,u=`${g}${s}`,E=n.getConversation(u);if(E){const m=this.getLocalGroup(s);E.setProfileCompleted(),n.updateConversation(u,{groupProfile:m})}}reset(){this.clearLocalGroup()}_clearGroupLocalMessage(s){const{message:{messageHistory:n,messageDataHandler:g},OuterConstant:{CONV_GROUP:u},ssoLog:E}=this._core;E.debug("_clearGroupLocalMessage",`groupID:${s}`);const m=`${u}${s}`;n.completedHistoryConversations.delete(m),g.deleteConversationMessageList(m)}};function Gm(s,n){return pA(this,void 0,void 0,function*(){const{type:g,limit:u,offset:E,supportTopic:m=0,memberAccount:D,responseFilter:M}=s,T={Type:g,Limit:u,Offset:E,Member_Account:D,ResponseFilter:M,SupportTopic:m,NeedAppDefineData:1};return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_joined_group_list",data:T})})}const dn=function(s,n){return{code:0,data:s||{},successLog:n}};var Yv=new class{constructor(){this._name="GetGroupList",this._pagingStatus=SI,this.PAGING_GRP_COUNT_LIMIT=200}init(s){this._core=s;const{helper:n,constants:{WORKFLOW_NAME:g,WORKFLOW_STEP:u}}=s;n.registerApi({apiName:"getGroupList",context:this}),n.registerWorkflowStep(g.SYNC_SERVER_INFO_AFTER_LOGIN,u.GROUP_LIST_SYNC,this._syncGroupList,this)}getGroupList(){return pA(this,arguments,void 0,function*(s=!1){if(s){const g=[];return yield this._pagingGetJoinedCommunityList({limit:this.PAGING_GRP_COUNT_LIMIT,offset:0,groupList:g}),Yi.updateLocalGroup(g),Yi.getLocalGroupList()}if(this._core.ssoLog.debug("getGroupList",`${this._name}.getGroupList pagingStatus:${this._pagingStatus}`),this._pagingStatus===Og||this._pagingStatus===SI)return this._syncGroupList().then(()=>{const g=Yi.getLocalGroupList();return dn({groupList:g,isSyncCompleted:this._isSyncCompleted()})}).catch(g=>{throw g});const n=Yi.getLocalGroupList();return dn({groupList:n,isSyncCompleted:this._isSyncCompleted()},{message:`return group count:${n.length}`})})}_syncGroupList(){return pA(this,void 0,void 0,function*(){this._pagingStatus===SI&&Yi.clearLocalGroup();const s=this.PAGING_GRP_COUNT_LIMIT,n=[];try{yield this._pagingGetGroupList({limit:s,offset:0,groupList:n}),this._pagingStatus=su,this._groupListTreeShaking(n),Yi.updateLocalGroup(n);const g=Yi.getLocalGroupList();return this._core.ssoLog.debug("_syncGroupList",`${this._name}._syncGroupList ok, count:${g.length}`),Yi.emitGroupListUpdate(),g}catch(g){throw this._pagingStatus=Og,g}})}_pagingGetGroupList(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n}=this._core,{isCommunityRelay:g=!1,groupList:u}=s;let E,{limit:m,offset:D}=s;const M=[...os];g&&(E=this._core.OuterConstant.GRP_COMMUNITY,M.push("AtInfoList"));try{const T=yield Gm({type:E,limit:m,offset:D,memberAccount:this._core.store.get("login").userId,responseFilter:{GroupBaseInfoFilter:M,SelfInfoFilter:[...Ol]}},this._core),{GroupIdList:P=[],TotalCount:W=0}=T||{},iA=this._convertGroupKey(P);u.push(...iA);const EA=D+m,RA=!(W>EA),kA=`offset:${D} limit:${m} total:${W} isCompleted:${RA} current:${u.length} isCommunityRelay:${g}`;return n.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList ok. ${kA}`),g?RA?u:(D=EA,this._pagingGetGroupList({isCommunityRelay:!0,limit:m,offset:D,groupList:u})):RA?(n.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList start to get community list`),D=0,this._pagingGetGroupList({isCommunityRelay:!0,limit:m,offset:D,groupList:u})):(D=EA,this._pagingGetGroupList({limit:m,offset:D,groupList:u}))}catch(T){if(T.ErrorCode===nu)return n.warn("_pagingGetGroupList",`${this._name}._pagingGetGroupList response size exceeds the limit, request count:${m}`),m=50,this._pagingGetGroupList({isCommunityRelay:g,limit:m,offset:D,groupList:u});if(g)return T.code===MI&&n.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList ok. community unavailable`),u;throw T}})}_pagingGetJoinedCommunityList(s){return pA(this,void 0,void 0,function*(){const{common:{getCurrentUserID:n},OuterConstant:g,ssoLog:u}=this._core,{groupList:E}=s;let{limit:m,offset:D}=s;try{const M=yield Gm({limit:m,offset:D,type:g.GRP_COMMUNITY,memberAccount:n(),supportTopic:1,responseFilter:{GroupBaseInfoFilter:[...os],SelfInfoFilter:[...Ol]}},this._core),{GroupIdList:T=[],TotalCount:P=0}=M||{},W=this._convertGroupKey(T);E.push(...W);const iA=D+m,EA=!(P>iA),RA=`offset:${D} limit:${m} total:${P} isCompleted:${EA} current:${E.length}`;return u.debug("_pagingGetJoinedCommunityList",`${this._name}._pagingGetJoinedCommunityList ok. ${RA}`),EA?E:(D=iA,this._pagingGetJoinedCommunityList({limit:m,offset:D,groupList:E}))}catch(M){if(M.code===MT)return u.warn("_pagingGetJoinedCommunityList",`${this._name}._pagingGetJoinedCommunityList response size exceeds the limit, request count:${m}`),m=50,this._pagingGetJoinedCommunityList({limit:m,offset:D,groupList:E});throw M}})}_groupListTreeShaking(s){const n=new Map([...Yi.getLocalGroupList()]);for(let u=0,E=s.length;u{const{AtFlagList:E,AtMsgSeq:m,From_Account:D}=u;g.push({groupID:s,groupAtType:E,sequence:m,from:D})}),g}},ju=new class{constructor(){this._name="CreateGroup"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"createGroup",context:this})}createGroup(s){return pA(this,void 0,void 0,function*(){var n;this._preCheckParams(s);const{helper:{ChatError:g}}=this._core;try{const{utils:{isEmpty:u},common:{getCurrentUserID:E},OuterConstant:{GRP_AVCHATROOM:m}}=this._core,D=yield function(iA,EA){return pA(this,void 0,void 0,function*(){const{name:RA,type:kA,groupID:xA,introduction:LA,notification:SA,avatar:OA,maxMemberNum:JA,joinOption:ae,inviteOption:re,memberList:_i,groupCustomField:Ti,isSupportTopic:Lt}=iA;let Ni,cs;_i&&(Ni=_i.map(mt=>{const{userID:UA,memberCustomField:si}=mt;return{Member_Account:UA,AppMemberDefinedData:si?VE(si):void 0}})),Ti&&(cs=VE(Ti));const Me={Name:RA,Type:kA,GroupId:xA,Introduction:LA,Notification:SA,FaceUrl:OA,MaxMemberCount:JA,ApplyJoinOption:ae,InviteJoinOption:re,MemberList:Ni,AppDefinedData:cs,SupportTopic:Lt,webPushFlag:1};return EA.common.buildAndSendPacket({servcmd:"group_open_http_svc.create_group",data:Me})})}(Object.assign(Object.assign({},s),{ownerID:E()}),this._core),{GroupId:M,OverJoinedGroupLimit_Account:T=[]}=D||{},P=`${this._name}.createGroup ok, type:${s.type} groupID:${M} overLimitUserIDList:${T}`;if(u(s.memberList)||u(T)||(s.memberList=(n=s.memberList)===null||n===void 0?void 0:n.filter(iA=>T.includes(iA.userID))),s.type===m)return dn({group:new Ku(Object.assign(Object.assign({},s),{groupID:M}))},{message:P});Yi.updateLocalGroup([Object.assign(Object.assign({},s),{groupID:M})]);const W=Yi.getLocalGroup(M);return this._notNeedSendCustomMessage(s)||(this._sendCustomMessage(M,s.type),Yi.emitGroupListUpdate()),dn({group:W},{message:P})}catch(u){const{errorCode:E,errorInfo:m}=u;throw new g({functionName:"createGroup",code:E,message:m,moreMessage:` groupID:${s.groupID}`})}})}_preCheckParams(s){const{type:n,groupID:g}=s,{utils:{isEmpty:u,isUndefined:E},common:{isCommunity:m}}=this._core,D=!u(g);if(!(()=>{const{GRP_PUBLIC:M,GRP_WORK:T,GRP_MEETING:P,GRP_AVCHATROOM:W,GRP_COMMUNITY:iA}=Wn.core.OuterConstant;return[M,T,P,W,iA]})().includes(n))throw new this._core.helper.ChatError({code:vm});if(!m({type:n})){if(D&&m({groupID:g}))throw new this._core.helper.ChatError({code:Dd});E(s.isSupportTopic)||(s.isSupportTopic=void 0)}if(this._canIUseMemberList(n)||E(s.memberList)||(s.memberList=void 0),this._canIUseJoinOption(n)||E(s.joinOption)||(s.joinOption=void 0),m({type:n})){if(D&&!m({groupID:g}))throw new this._core.helper.ChatError({code:Dd});s.isSupportTopic=this._canIUseTopic(s)?1:0}}_canIUseMemberList(s){return!Sd(s)}_canIUseJoinOption(s){return xv(s)||this._core.common.isCommunity({type:s})}_canIUseTopic(s){const{isSupportTopic:n}=s;return n===!0}_notNeedSendCustomMessage(s){const{type:n,isSupportTopic:g}=s,{OuterConstant:{GRP_AVCHATROOM:u,GRP_COMMUNITY:E}}=this._core;return n===u||n===E&&g===1}_sendCustomMessage(s,n){var g,u,E,m,D,M;const{OuterConstant:T,common:{t:P}}=this._core;let W=P("CREATE_GROUP"),iA=Lc;n===T.GRP_COMMUNITY&&(W=P("CREATE_COMMUNITY"),iA=Mr);const EA={to:s,conversationType:"GROUP",payload:{data:JSON.stringify({businessID:"group_create",content:W,cmd:iA,opUser:this._core.store.get("login").userId,version:4})}},RA=(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageFactory)===null||E===void 0?void 0:E.createCustomMessage(EA);(M=(D=(m=this._core)===null||m===void 0?void 0:m.message)===null||D===void 0?void 0:D.messageSender)===null||M===void 0||M.sendMessage(RA,{})}},zs=new class{constructor(){this._name="AttributesDataHandler",this._groupAttributesCache=new Map,this._groupAttributesCacheValuesCopy={}}init(s){this._core=s;const{helper:n,constants:g}=s;n.registerWorkflowStep(g.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,g.WORKFLOW_STEP.GROUP_ATTRIBUTE_CACHE_CLEAR,this.clearLocalMainSequence,this)}clearLocalMainSequence(){this._groupAttributesCache.forEach(s=>{s.localMainSequence=0})}isGroupAttributesUpdated(s){const{elements:{newGroupProfile:n}}=s,{utils:{isEmpty:g,isUndefined:u}}=this._core;return!u(n)&&!g(n.groupAttributeOption)}handleGroupAttributesUpdated(s){const{groupID:n,groupAttributeOption:g}=s,{serverMainSequence:u,groupAttributeList:E=[],operation:m}=g;this._core.ssoLog.debug("handleGroupAttributesUpdated",`${this._name}.handleGroupAttributesUpdated groupID:${n} operation:${m}`);const{utils:{isUndefined:D}}=this._core;D(m)||(this.refreshGroupAttributesCache({groupID:n,serverMainSequence:u,groupAttributeList:E,operation:m}),this.emitGroupAttributesUpdated(n))}initGroupAttributesCache(s){const{groupID:n,avChatRoomKey:g}=s;this._groupAttributesCache.set(n,{lastUpdateTime:0,localMainSequence:0,serverMainSequence:0,avChatRoomKey:g,values:new Map}),this._core.ssoLog.debug("initGroupAttributesCache",`${this._name}.initGroupAttributesCache. groupID:${n} avChatRoomKey:${g}`)}hasGroupAttributesCache(s){return this._groupAttributesCache.has(s)}getGroupAttributesCache(s){return this.hasGroupAttributesCache(s)||this.initGroupAttributesCache({groupID:s}),this._groupAttributesCache.get(s)}deleteGroupAttributesCache(s){this.hasGroupAttributesCache(s)&&this._groupAttributesCache.delete(s)}refreshGroupAttributesCache(s){const{groupID:n,serverMainSequence:g,groupAttributeList:u,operation:E}=s;if(this.hasGroupAttributesCache(n)){const m=this.getGroupAttributesCache(n),{localMainSequence:D}=m;E!==Lv&&g-D!==1||(m.serverMainSequence=g,m.localMainSequence=g,m.lastUpdateTime=Date.now(),this._updateGroupAttributesCacheValues({groupAttributes:m,groupAttributeList:u,operation:E})),g-D>1&&(m.serverMainSequence=g),this._groupAttributesCache.set(n,m),this._core.ssoLog.debug("refreshGroupAttributesCache",`${this._name}.refreshGroupAttributesCache. operation:${E} localMainSequence:${D} serverMainSequence:${g}`)}}_updateGroupAttributesCacheValues(s){const{groupAttributes:n,groupAttributeList:g=[],operation:u}=s;u!==lD?u!==ID?(u===cD&&n.values.clear(),g.forEach(E=>{const{key:m,value:D,sequence:M}=E;n.values.set(m,{value:D,sequence:M})})):g.forEach(E=>{n.values.delete(E.key)}):n.values.clear()}getGroupAttributesCacheValues(s){var n;const{groupID:g,keyList:u=[]}=s,E={};if(this.hasGroupAttributesCache(g)){const{values:m}=this.getGroupAttributesCache(g);if(u.length===0){for(const D of m.keys())E[D]=((n=m.get(D))===null||n===void 0?void 0:n.value)||"";return E}return u.forEach(D=>{var M;m.has(D)&&(E[D]=((M=m.get(D))===null||M===void 0?void 0:M.value)||"")}),E}return E}saveGroupAttributesCacheValuesCopy(s){this._groupAttributesCacheValuesCopy=this.getGroupAttributesCacheValues({groupID:s})}emitGroupAttributesUpdated(s){var n,g;const{OuterConstant:{GRP_ROOM:u,GRP_LIVE:E}}=this._core,m=this.getGroupAttributesCacheValues({groupID:s}),D=this._core.appStore.groupStore.getGroup(s),{updatedKeyList:M,deletedKeyList:T}=this._computeValuesChangedData(m);M.length===0&&T.length===0||([u,E].includes(D.type)?(this._core.ssoLog.debug("RICH_STATUS_CHANGED",`${this._name}.emitRichStatusChanged update count:${M.length}, delete count:${T.length}`),this._emitEvent({name:(n=this._core)===null||n===void 0?void 0:n.OuterEvent.RICH_STATUS_CHANGED,data:{groupID:s,richStatus:m,updatedKeyList:M,deletedKeyList:T}})):(this._core.ssoLog.debug("emitGroupAttributesUpdated",`${this._name}.emitGroupAttributesUpdated update count:${M.length}, delete count:${T.length}`),this._emitEvent({name:(g=this._core)===null||g===void 0?void 0:g.OuterEvent.GROUP_ATTRIBUTES_UPDATED,data:{groupID:s,groupAttributes:m,updatedKeyList:M,deletedKeyList:T}})))}_computeValuesChangedData(s){const{utils:{isUndefined:n}}=this._core,g=[],u=[];return Object.keys(s).forEach(E=>{s[E]!==this._groupAttributesCacheValuesCopy[E]&&g.push(E)}),Object.keys(this._groupAttributesCacheValuesCopy).forEach(E=>{n(s[E])&&u.push(E)}),this._groupAttributesCacheValuesCopy={},{updatedKeyList:g,deletedKeyList:u}}_emitEvent(s){var n;(n=this._core)===null||n===void 0||n.notificationCenter.emitOuterEvent(s.name,s)}convertKeyValueMapToList(s){const n=[];return Object.keys(s).forEach(g=>{n.push({key:g,value:s[g]})}),n}reset(){this._groupAttributesCache.clear(),this._groupAttributesCacheValuesCopy={}}},Eh=new class{constructor(){this._name="DismissGroup"}init(s,n){this._core=s;const{helper:g}=s;g.registerApi({apiName:"dismissGroup",context:this,matcher:()=>!n.getInstalledSubPlugins().includes(ta)})}dismissGroup(s){return pA(this,void 0,void 0,function*(){const{helper:{ChatError:n}}=this._core;try{yield function(u,E){return pA(this,void 0,void 0,function*(){const m={GroupId:u};return E.common.buildAndSendPacket({servcmd:"group_open_http_svc.destroy_group",data:m})})}(s,this._core);const{type:g}=Yi.getLocalGroup(s);return Yi.deleteLocalGroup(s),Yi.emitGroupListUpdate(),zs.deleteGroupAttributesCache(s),dn({groupID:s,type:g},{message:s})}catch(g){const{errorCode:u,errorInfo:E}=g;throw new n({functionName:"dismissGroup",code:u,message:E})}})}},Pl=new class{constructor(){this._name="GetGroupProfile"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"getGroupProfile",context:this})}getGroupProfile(s){return pA(this,void 0,void 0,function*(){const{groupID:n,groupCustomFieldFilter:g}=s,u={groupIDList:[n],responseFilter:{GroupBaseInfoFilter:[...os],AppDefinedDataFilter_Group:g,MemberInfoFilter:[...fd]}},{helper:{ChatError:E}}=this._core;try{const m=yield this.getGroupProfileAdvance(u),{successGroupList:D,failureGroupList:M}=m;if(M.length>0)throw M[0];let T;return!Yi.hasLocalGroup(n)&&Sd(D[0].type)?T=new Ku(D[0]):(Yi.updateLocalGroup(D),T=Yi.getLocalGroup(n)),T.isSupportTopic||Yi.updateConversationGroupProfile(n),dn({group:T},{message:`groupID:${n}`})}catch(m){const{code:D,message:M}=m;throw new E({functionName:"getGroupProfile",code:D,message:M})}})}getGroupProfileAdvance(s){return pA(this,void 0,void 0,function*(){const{groupIDList:n}=s,{common:{isCommunity:g}}=this._core,u=n.filter(T=>!g({groupID:T})),E=n.filter(T=>g({groupID:T}));u.length>50&&(u.length=50),E.length>50&&(E.length=50);const m=yield Promise.all([this._getGroupProfileAdvance(Object.assign(Object.assign({},s),{groupIDList:u})),this._getGroupProfileAdvance(Object.assign(Object.assign({},s),{groupIDList:E,isCommunityProfile:!0}))]),D=[],M=[];return m.forEach(T=>{D.push(...T.successGroupList),M.push(...T.failureGroupList)}),{successGroupList:D,failureGroupList:M}})}_getGroupProfileAdvance(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{isUndefined:g}}=this._core,{isCommunityProfile:u=!1}=s,E=Do(s,["isCommunityProfile"]);if(E.groupIDList.length===0)return{successGroupList:[],failureGroupList:[]};try{const m=yield function(W,iA){return pA(this,void 0,void 0,function*(){const{groupIDList:EA,responseFilter:RA}=W,kA={GroupIdList:EA,ResponseFilter:RA};return iA.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_self_member_info",data:kA})})}(E,this._core),{GroupInfo:D=[]}=m||{},M=this._convertGroupProfileKey(D),T=M.filter(W=>g(W.errorCode)||W.errorCode===0),P=M.filter(W=>W.errorCode&&W.errorCode!==0).map(W=>({code:W.errorCode,message:W.errorInfo,data:{groupID:W.groupID}}));return n.debug("_getGroupProfileAdvance",`${this._name}._getGroupProfileAdvance ok, groupID:${E.groupIDList.join(",")}`),{successGroupList:T,failureGroupList:P}}catch(m){if(u)return{successGroupList:[],failureGroupList:[]};throw m}})}_convertGroupProfileKey(s){const n=[];for(let g=0,u=s.length;g0&&u{const{Key:T,Value:P=0}=M;E.set(T,P)}),this._groupCountersMap.set(n,{lastUpdateTime:Date.now(),groupCounterSeq:u,counters:E,avChatRoomKey:m})}}initGroupCountersCache(s){const{groupID:n,avChatRoomKey:g}=s;this._groupCountersMap.set(n,{lastUpdateTime:0,groupCounterSeq:0,counters:new Map,avChatRoomKey:g})}getLocalCounters(s,n){const g={};if(!this._hasLocalGroupCounters(s))return g;const{counters:u}=this.getLocalGroupCounters(s);if(n.length>0)n.forEach(E=>{u.has(E)&&(g[E]=u.get(E))});else for(const E of u.keys())g[E]=u.get(E);return g}deleteLocalGroupCounters(s){const{groupID:n,counterList:g=[],groupCounterSeq:u}=s;if(this._hasLocalGroupCounters(n)){const{counters:E,avChatRoomKey:m}=this.getLocalGroupCounters(n);g.forEach(D=>{E.delete(D.key)}),this._groupCountersMap.set(n,{lastUpdateTime:Date.now(),groupCounterSeq:u,counters:E,avChatRoomKey:m})}}setGroupCounters(s,n){if(!this._hasLocalGroupCounters(s))return;const g=this.getLocalGroupCounters(s),{counters:u}=g;let E=!1;Object.entries(n).forEach(([m,D])=>{u.has(m)&&u.get(m)!==D&&(u.set(m,D),E=!0)}),E&&this._groupCountersMap.set(s,Object.assign(Object.assign({},g),{lastUpdateTime:Date.now(),counters:u}))}_hasLocalGroupCounters(s){return this._groupCountersMap.has(s)}reset(){this._groupCountersMap.clear()}},JE=new class{constructor(){this._name="JoinGroup"}init(s,n){this._core=s;const{helper:g}=s;g.registerApi({apiName:"joinGroup",context:this,matcher:()=>!n.getInstalledSubPlugins().includes(ta)})}joinGroup(s){return pA(this,void 0,void 0,function*(){const{groupID:n}=s,{helper:{ChatError:g},OuterConstant:u,ssoLog:E}=this._core;try{if(Yi.hasLocalGroup(n))try{return yield Pl.getGroupProfile({groupID:n}),dn({status:u.JOIN_STATUS_ALREADY_IN_GROUP,group:Yi.getLocalGroup(n)},{message:`groupID:${n} joinedStatus:${u.JOIN_STATUS_ALREADY_IN_GROUP}`})}catch{return E.warn("joinGroup",`${this._name}.joinGroup ${n} was unjoined, start to join!`),Yi.deleteLocalGroup(n),yield this._applyJoinGroup(s)}return yield this._applyJoinGroup(s)}catch(m){const{errorCode:D,errorInfo:M}=m;throw new g({functionName:"joinGroup",code:D,message:M,moreMessage:`groupID:${n}`})}})}_applyJoinGroup(s){return pA(this,void 0,void 0,function*(){const{OuterConstant:n,helper:g,ssoLog:u}=this._core,{groupID:E}=s,m=Object.assign({},s),D=g.checkBusinessCapabilityBits(qr);D&&(m.historyMessageFlag=1);const M=yield function(SA,OA){return pA(this,void 0,void 0,function*(){const{groupID:JA,applyMessage:ae,historyMessageFlag:re}=SA,_i={GroupId:JA,ApplyMsg:ae,HugeGroupHistoryMsgFlag:re};return OA.common.buildAndSendPacket({servcmd:"group_open_http_svc.apply_join_group",data:_i})})}(m,this._core),{Type:T,JoinedStatus:P,LongPollingKey:W,StartSeq:iA,HugeGroupFlag:EA,AVChatRoomKey:RA,RspMsgList:kA=[]}=M||{},xA=`groupID:${E} joinedStatus:${P} longPollingKey:${W} startSeq:${iA} avChatRoomFlag:${EA} canGetAVChatRoomHistoryMsg:${D}, historyMessageCount:${kA.length}`;u.debug("_applyJoinGroup",`${this._name}._applyJoinGroup ok, ${xA}`);let LA=new Ku({groupID:E,type:T});if(P===n.JOIN_STATUS_WAIT_APPROVAL)return dn({status:n.JOIN_STATUS_WAIT_APPROVAL,group:LA});if(P===n.JOIN_STATUS_SUCCESS){try{LA=(yield Pl.getGroupProfile({groupID:E})).data.group}catch(SA){u.warn("_applyJoinGroup",`${this._name}._applyJoinGroup getGroupProfile failed, groupID: ${E}, errorCode:${SA?.code}`)}return this._handleJoinResult({group:LA,avChatRoomFlag:EA,longPollingKey:W,startSequence:iA,avChatRoomKey:RA,historyMessageList:kA})}throw new this._core.helper.ChatError({code:Ih})})}_handleJoinResult(s){const{group:n,avChatRoomFlag:g,avChatRoomKey:u}=s;return g===1?(zs.initGroupAttributesCache({groupID:n.groupID,avChatRoomKey:u}),nc.initGroupCountersCache({groupID:n.groupID,avChatRoomKey:u}),dn(s)):(Yi.updateLocalGroup([n]),Yi.emitGroupListUpdate(),dn({status:this._core.OuterConstant.JOIN_STATUS_SUCCESS,group:n},{message:`groupID:${n.groupID}`}))}},NQ=new class{constructor(){this._name="QuitGroup"}init(s,n){this._core=s;const{helper:g}=s;g.registerApi({apiName:"quitGroup",context:this,matcher:()=>!n.getInstalledSubPlugins().includes(ta)})}quitGroup(s){return pA(this,void 0,void 0,function*(){if(!Yi.hasLocalGroup(s))throw new this._core.helper.ChatError({code:hD});const{helper:{ChatError:n}}=this._core;try{yield function(u,E){return pA(this,void 0,void 0,function*(){const m={GroupId:u};return E.common.buildAndSendPacket({servcmd:"group_open_http_svc.quit_group",data:m})})}(s,this._core);const{type:g}=Yi.getLocalGroup(s);return Yi.deleteLocalGroup(s),Yi.emitGroupListUpdate(),zs.deleteGroupAttributesCache(s),dn({groupID:s,type:g},{message:`groupID:${s}`})}catch(g){const{errorCode:u,errorInfo:E}=g;throw new n({functionName:"quitGroup",code:u,message:E,moreMessage:`groupID:${s}`})}})}},cB=new class{constructor(){this._name="SearchGroup"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"searchGroupByID",context:this})}searchGroupByID(s){return pA(this,void 0,void 0,function*(){try{const n=yield function(OA,JA){return pA(this,void 0,void 0,function*(){const ae={GroupIdList:[OA],GroupBasePublicInfoFilter:[...Eg]};return JA.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_public_info",data:ae})})}(s,this._core),{GroupInfo:g=[]}=n||{},{AppDefinedData:u=[],ApplyJoinOption:E,CreateTime:m,FaceUrl:D,Introduction:M,InviteJoinOption:T,MaxMemberNum:P,MemberNum:W,Name:iA,Owner_Account:EA,Type:RA,ErrorCode:kA,ErrorInfo:xA}=g[0];if(kA!==0)throw new this._core.helper.ChatError({code:kA,message:xA});const LA=Md(u),SA=new Ku({groupID:s,name:iA,avatar:D,introduction:M,joinOption:E,inviteOption:T,maxMemberCount:P,memberCount:W,type:RA,ownerID:EA,createTime:m,groupCustomField:LA});return dn({group:SA})}catch(n){const{errorCode:g,errorInfo:u}=n;throw new this._core.helper.ChatError({functionName:"searchGroupByID",code:g,message:u})}})}},RT=new class{constructor(){this._name="UpdateGroupProfile"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"updateGroupProfile",context:this})}updateGroupProfile(s){return pA(this,void 0,void 0,function*(){const{groupID:n}=s,{utils:{isUndefined:g,safeStringify:u},ssoLog:E,helper:m}=this._core;let D=Yi.getLocalGroup(n);if(D){const{type:M}=D;this._canIUseJoinOption(M)||g(s.joinOption)||(E.warn("updateGroupProfile",`${this._name}.updateGroupProfile groupID:${n} joinOption is unavailable for Work/Meeting/AVChatRoom`),s.joinOption=void 0)}g(s.muteAllMembers)||(s.muteAllMembers=s.muteAllMembers===!0?"On":"Off");try{return yield function(M,T){return pA(this,void 0,void 0,function*(){const{groupID:P,name:W,avatar:iA,introduction:EA,notification:RA,muteAllMembers:kA,joinOption:xA,inviteOption:LA,groupCustomField:SA}=M,OA={GroupId:P,Name:W,FaceUrl:iA,Introduction:EA,Notification:RA,ShutUpAllMember:kA,ApplyJoinOption:xA,InviteJoinOption:LA,AppDefinedData:SA?VE(SA):void 0};return T.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_base_info",data:OA})})}(s,this._core),D?(D.updateGroup(s),Yi.emitGroupListUpdate()):D=new Ku(s),dn({group:D},{message:`groupID:${n}`})}catch(M){const{errorCode:T,errorInfo:P}=M;throw new m.ChatError({code:T,message:P,moreMessage:`options:${u(s)}`})}})}_canIUseJoinOption(s){return xv(s)||this._core.common.isCommunity({type:s})}},wT=new class{constructor(){this._name="ChangeGroupOwner"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"changeGroupOwner",context:this})}changeGroupOwner(s){return pA(this,void 0,void 0,function*(){const n="changeGroupOwner",{groupID:g,newOwnerID:u}=s,E=Yi.getLocalGroup(g),{helper:m,OuterConstant:D,common:{getCurrentUserID:M}}=this._core;if(E?.type===D.GRP_AVCHATROOM)throw new m.ChatError({functionName:n,code:yT});if(u===M())throw new m.ChatError({functionName:n,code:Rm});try{return yield function(T,P){return pA(this,void 0,void 0,function*(){const{groupID:W,newOwnerID:iA}=T,EA={GroupId:W,NewOwner_Account:iA};return P.common.buildAndSendPacket({servcmd:"group_open_http_svc.change_group_owner",data:EA})})}(s,this._core),E.ownerID=u,Yi.emitGroupListUpdate(),dn({group:E})}catch(T){throw new m.ChatError({functionName:n,code:T?.errorCode,message:T?.errorInfo})}})}},GQ=new class{constructor(){this._name="GetGroupOnlineMemberCount",this._onlineMemberCountMap=new Map}init(s,n){this._core=s;const{helper:g}=s;g.registerApi({apiName:"getGroupOnlineMemberCount",context:this,matcher:()=>!n.getInstalledSubPlugins().includes(ta)})}getGroupOnlineMemberCount(s){return pA(this,void 0,void 0,function*(){const n="getGroupOnlineMemberCount";if(!Yi.hasLocalGroup(s))return dn({memberCount:0});const g=Date.now();if(this._onlineMemberCountMap.has(s)){const u=this._onlineMemberCountMap.get(s),{lastReqTime:E=0,memberCount:m=0}=u||{};if(g-E<=6e4)return dn({memberCount:m})}try{const u=yield function(D,M){return pA(this,void 0,void 0,function*(){const T={GroupId:D};return M.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_online_member_num",data:T})})}(s,this._core),{OnlineMemberNum:E=0}=u||{};this._onlineMemberCountMap.set(s,{lastReqTime:Date.now(),memberCount:E});const m=`${this._name}.${n} ok. groupID:${s} memberCount:${E}`;return dn({memberCount:E},{message:m})}catch(u){throw new this._core.helper.ChatError({functionName:n,code:u?.errorCode,message:u?.errorInfo})}})}},bQ=new class{init(s,n){s.ssoLog.debug("GroupAction.init"),Yv.init(s),ju.init(s),Eh.init(s,n),JE.init(s,n),NQ.init(s,n),cB.init(s),Pl.init(s),RT.init(s),wT.init(s),GQ.init(s,n)}dismissGroup(s){return Eh.dismissGroup(s)}joinGroup(s){return JE.joinGroup(s)}quitGroup(s){return NQ.quitGroup(s)}getGroupOnlineMemberCount(s){return GQ.getGroupOnlineMemberCount(s)}},Vv=new class{constructor(){this._name="GetGroupApplicationList"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"getGroupApplicationList",context:this})}getGroupApplicationList(){return pA(this,void 0,void 0,function*(){const s="getGroupApplicationList";try{const n=yield Promise.all([this._getGroupApplicationList(),this._getGroupApplicationList({type:this._core.OuterConstant.GRP_COMMUNITY})]);this._core.ssoLog.debug("getGroupApplicationList",`${this._name}.${s} ok.`);const g=this._handleGroupApplicationResult([...n[0],...n[1]]);return dn({applicationList:g})}catch(n){throw new this._core.helper.ChatError({functionName:s,code:n?.errorCode,message:n?.errorInfo})}})}_getGroupApplicationList(s){return pA(this,void 0,void 0,function*(){const{type:n,startTime:g=0,limit:u=20}=s||{},{common:E}=this._core;let m;try{m=yield function(P,W){return pA(this,void 0,void 0,function*(){const{type:iA,startTime:EA,limit:RA,handleAccount:kA}=P,xA={Type:iA,StartTime:EA,Limit:RA,Handle_Account:kA};return W.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_pendency",data:xA})})}({type:n,startTime:g,limit:u,handleAccount:E.getCurrentUserID()},this._core)}catch(P){if(P?.errorCode!==11e3)throw P;m={}}const{NextStartTime:D=0,PendencyList:M=[]}=m||{};if(D===0)return M;const T=yield this._getGroupApplicationList(Object.assign(Object.assign({},s),{startTime:D}));return[...M,...T]})}_handleGroupApplicationResult(s){const n=[];return s.forEach(g=>{const u=this._convertApplicationData(g),{handled:E}=u,m=Do(u,["handled"]);E===0&&n.push(m)}),n}_convertApplicationData(s){const{Handled:n,AddTime:g,ApplyInviteMsg:u,Authentication:E,FromUserNickName:m,From_Account:D,GroupId:M,GroupName:T,PendencyType:P,To_Account:W}=s;return{handled:n,messageKey:g,applicant:D,applicantNick:m,groupID:M,groupName:T,authentication:E,applicationType:P,userID:W,note:u,addTime:g}}},Jv=new class{constructor(){this._name="HandleGroupApplication"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"handleGroupApplication",context:this})}handleGroupApplication(s){return pA(this,void 0,void 0,function*(){const{application:n}=s,g=this._handleParams(s);try{n?.applicationType===Uc?yield function(E,m){return pA(this,void 0,void 0,function*(){const{groupID:D,handleAction:M,handleMessage:T,applicant:P,authentication:W,invitee:iA}=E,EA={GroupId:D,HandleMsg:M,ApprovalMsg:T,Applicant_Account:P,Authentication:W,Invited_Account:iA};return m.common.buildAndSendPacket({servcmd:"group_open_http_svc.handle_invite_join_permission_group",data:EA})})}(g,this._core):yield function(E,m){return pA(this,void 0,void 0,function*(){const{groupID:D,handleAction:M,handleMessage:T,applicant:P,authentication:W,messageKey:iA}=E,EA={GroupId:D,HandleMsg:M,ApprovalMsg:T,Applicant_Account:P,Authentication:W,MsgKey:iA};return m.common.buildAndSendPacket({servcmd:"group_open_http_svc.handle_apply_join_group",data:EA})})}(g,this._core);const u=Yi.getLocalGroup(g.groupID);return dn({group:u})}catch(u){throw new this._core.helper.ChatError({functionName:"handleGroupApplication",code:u?.errorCode,message:u?.errorInfo})}})}_handleParams(s){var n;const{handleAction:g,handleMessage:u,message:E,application:m}=s;let D,M,T,P,W;if(E){const{payload:iA}=E||{};D=iA.operatorID,M=(n=iA.groupProfile)===null||n===void 0?void 0:n.groupID,T=iA.authentication,P=iA.messageKey}else D=m?.applicant||"",M=m?.groupID||"",T=m?.authentication||"",P=m?.messageKey||0;return m?.applicationType===Uc&&(W=m.userID),{handleAction:g,handleMessage:u,applicant:D,invitee:W,groupID:M,authentication:T,messageKey:P}}},QD=new class{init(s){s.ssoLog.debug("GroupApplication.init"),Vv.init(s),Jv.init(s)}};let DC=class{constructor(s){this.userID="",this.avatar="",this.nick="",this.role="",this.joinTime="",this.nameCard="",this.muteUntil=0,this.memberCustomField=[],this.isOnline=!1,this.updateMember(s)}updateMember(s){const{core:{utils:{isUndefined:n},common:{deepMerge:g}}}=Wn;n(s.muteTime)||(this.muteUntil=Math.floor((Date.now()+1e3*s.muteTime)/1e3)),n(s.onlineStatus)||(this.isOnline=s.onlineStatus==="Online");const u=[null,void 0,"",0,NaN];s.memberCustomField&&Tm(this.memberCustomField,s.memberCustomField),g(this,s,["memberCustomField","marks","onlineStatus","muteTime"],u)}};function lB(s,n){return pA(this,void 0,void 0,function*(){const{groupID:g,userID:u,muteTime:E,role:m,nameCard:D,memberCustomField:M}=s;let T;M&&(T=VE(M));const P={GroupId:g,Member_Account:u,ShutUpTime:E,Role:m,NameCard:D,AppMemberDefinedData:T};return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:P})})}var pD=new class{constructor(){this._name="GetGroupMemberList"}init(s,n){this._core=s;const{helper:g}=s;g.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>!n.getInstalledSubPlugins().includes(ta)})}getGroupMemberList(s){return pA(this,void 0,void 0,function*(){const n="getGroupMemberList",{groupID:g,offset:u=0,count:E=100,role:m="",filter:D=""}=s,M=Yi.getLocalGroup(g),T=E>100?100:E,P={groupID:g,offset:u,limit:T,memberRoleFilter:qu.includes(m)?[m]:void 0,memberInfoFilter:fm};try{const W=yield function(re,_i){return pA(this,void 0,void 0,function*(){const{isCommunity:Ti}=_i.common,{groupID:Lt,offset:Ni,limit:cs,memberRoleFilter:Me,memberInfoFilter:mt}=re,UA={GroupId:Lt,Limit:cs,MemberRoleFilter:Me,MemberInfoFilter:mt};return Ti({groupID:Lt})?UA.Next=String(Ni):UA.Offset=Ni,_i.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_member_info",data:UA})})}(P,this._core),{MemberList:iA,MemberNum:EA,Next:RA}=W||{},kA=`${this._name}.${n} ok, totalMemberCount:${EA} next:${RA}`,{utils:{isArray:xA,isEmpty:LA},common:{isCommunity:SA}}=this._core;if(M&&(M.memberCount=EA),!xA(iA)||iA.length===0)return dn({memberList:[],offset:0},{message:kA});let OA=u+T;SA({groupID:g})&&(OA=LA(RA)?0:RA),iA.lengthD.userID),u=yield(n=this._core.user.userProfile)===null||n===void 0?void 0:n.getUserProfile({userIDList:g}),E=u?.data||[],m=new Map(E.map(D=>[D.userID,D]));return s.forEach(D=>{if(m.has(D.userID)){const{nick:M="",avatar:T=""}=m.get(D.userID);D.nick=M,D.avatar=T}}),s})}_generateGroupMember(s){const n=[];for(let g=0,u=s.length;g50&&(T.warn("getGroupMemberProfile",`${this._name}.${n} userIDList length:${u.length} exceeds limit 50`),u.splice(50));const P=`userIDList length:${u.length} groupID:${g}`;try{const W=yield function(kA,xA){return pA(this,void 0,void 0,function*(){const{groupID:LA,userIDList:SA,memberInfoFilter:OA,memberCustomFieldFilter:JA}=kA,ae={GroupId:LA,Member_List_Account:SA,MemberInfoFilter:OA,AppDefinedDataFilter_GroupMember:JA};return xA.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_specified_group_member_info",data:ae})})}({groupID:g,userIDList:u,memberCustomFieldFilter:E,memberInfoFilter:[...fm]},this._core),{MemberList:iA}=W||{};if(!M(iA)||iA.length===0)return dn({memberList:[]});let EA=this._convertMemberInfo(iA);EA=yield this._getMemberAvatarAndNick(EA);const RA=this._generateGroupMember(EA);return dn({memberList:RA},{message:P})}catch(W){throw new D.ChatError({functionName:n,code:W?.errorCode,message:W?.errorInfo,moreMessage:P})}})}_convertMemberInfo(s){const n=[];for(let g=0,u=s.length;gD.userID),u=yield(n=this._core.user.userProfile)===null||n===void 0?void 0:n.getUserProfile({userIDList:g}),E=u?.data||[],m=new Map(E.map(D=>[D.userID,D]));return s.forEach(D=>{if(m.has(D.userID)){const{nick:M="",avatar:T=""}=m.get(D.userID);D.nick=M,D.avatar=T}}),s})}_generateGroupMember(s){const n=[];for(let g=0,u=s.length;g({Member_Account:M}));try{const M=yield function(RA,kA){return pA(this,void 0,void 0,function*(){const{groupID:xA,userIDList:LA}=RA,SA={GroupId:xA,MemberList:LA};return kA.common.buildAndSendPacket({servcmd:"group_open_http_svc.add_group_member",data:SA})})}({groupID:g,userIDList:D},this._core),{MemberList:T=[]}=M||{},{failureUserIDList:P,successUserIDList:W,existedUserIDList:iA,overLimitUserIDList:EA}=this._handleResult(T);return dn({failureUserIDList:P,successUserIDList:W,existedUserIDList:iA,overLimitUserIDList:EA,group:E},{message:` groupID:${g} successUserIDList:${W} failureUserIDList:${P} existedUserIDList:${iA} overLimitUserIDList:${EA}`})}catch(M){throw new m.ChatError({functionName:n,code:M?.errorCode,message:M?.errorInfo})}})}_handleResult(s){const n=[],g=[],u=[],E=[];return s.forEach(m=>{const{Result:D,Member_Account:M}=m;D===ym?n.push(M):D===Dm?g.push(M):D===Sm?u.push(M):D===gD&&E.push(M)}),{failureUserIDList:n,successUserIDList:g,existedUserIDList:u,overLimitUserIDList:E}}},Rd=new class{constructor(){this._name="DeleteGroupMember"}init(s,n){this._core=s;const{helper:g}=s;g.registerApi({apiName:"deleteGroupMember",context:this,matcher:()=>!n.getInstalledSubPlugins().includes(ta)})}deleteGroupMember(s){return pA(this,void 0,void 0,function*(){const n="deleteGroupMember",{groupID:g,userIDList:u}=s,E=Yi.getLocalGroup(g),{helper:m,utils:{isUndefined:D},ssoLog:M}=this._core;if(D(E))throw new m.ChatError({functionName:n,code:fT});u.length>20&&(M.warn("deleteGroupMember",`${this._name}.${n} userIDList length:${u.length} exceeds limit 20`),u.splice(20));try{return yield function(T,P){return pA(this,void 0,void 0,function*(){const{groupID:W,userIDList:iA,reason:EA}=T,RA={GroupId:W,MemberToDel_Account:iA,Reason:EA};return P.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_member",data:RA})})}({groupID:g,userIDList:u},this._core),dn({group:E,userIDList:u},{message:`groupID:${g} userIDList length:${u.length}`})}catch(T){throw new m.ChatError({functionName:n,code:T?.errorCode,message:T?.errorInfo})}})}},Hv=new class{constructor(){this._name="SetGroupMemberMuteTime"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"setGroupMemberMuteTime",context:this})}setGroupMemberMuteTime(s){return pA(this,void 0,void 0,function*(){const{helper:n}=this._core,{groupID:g,userID:u,muteTime:E}=s,m=` groupID:${g} userID:${u} muteTime:${E}`;this._preCheckSettingMuteParams(s);try{yield lB(s,this._core);const D=Yi.getLocalGroup(g),M=new DC({userID:u,muteTime:E});return dn({group:D,member:M},{message:m})}catch(D){throw new n.ChatError({functionName:"setGroupMemberMuteTime",code:D?.errorCode,message:D?.errorInfo,moreMessage:m})}})}_preCheckSettingMuteParams(s){const{userID:n}=s,{store:g,helper:u}=this._core;if(n===g.get("login").userId)throw new u.ChatError({functionName:"setGroupMemberMuteTime",code:BD})}},LQ=new class{constructor(){this._name="SetGroupMemberRole"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"setGroupMemberRole",context:this})}setGroupMemberRole(s){return pA(this,void 0,void 0,function*(){const n="setGroupMemberRole",{helper:g}=this._core,{groupID:u,userID:E,role:m}=s,D=`${this._name}.${n} ok, groupID:${u} userID:${E} role:${m}`;this._preCheckSettingRoleParams(s);try{yield lB(s,this._core);const M=Yi.getLocalGroup(u),T=new DC({userID:E,role:m});return dn({group:M,member:T},{message:D})}catch(M){throw new g.ChatError({functionName:n,code:M?.errorCode,message:M?.errorInfo,moreMessage:D})}})}_preCheckSettingRoleParams(s){var n;const{groupID:g,userID:u,role:E}=s,{store:m,helper:D,OuterConstant:M,common:{isCommunity:T}}=this._core,P=Yi.getLocalGroup(g);if(((n=P?.selfInfo)===null||n===void 0?void 0:n.role)!==M.GRP_MBR_ROLE_OWNER)throw new D.ChatError({functionName:"setGroupMemberRole",code:ST});if(u===m.get("login").userId)throw new D.ChatError({functionName:"setGroupMemberRole",code:Ov});const W=[...qu];if(T({groupID:g})&&W.push(M.GRP_MBR_ROLE_CUSTOM),!W.includes(E))throw new D.ChatError({functionName:"setGroupMemberRole",code:wm})}},mD=new class{constructor(){this._name="SetGroupMemberNameCard"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"setGroupMemberNameCard",context:this})}setGroupMemberNameCard(s){return pA(this,void 0,void 0,function*(){var n;const g="setGroupMemberNameCard",{helper:u,common:{getCurrentUserID:E}}=this._core,{groupID:m,userID:D=E(),nameCard:M}=s,T=`${this._name}.${g} ok, groupID:${m} userID:${D} nameCard:${M}`;this._preCheckSettingNameCardParams(s);try{yield lB({groupID:m,userID:D,nameCard:M},this._core);const W=Yi.getLocalGroup(m);D===((n=W?.selfInfo)===null||n===void 0?void 0:n.userID)&&(W.updateSelfInfo({nameCard:M}),Yi.emitGroupListUpdate(),Yi.updateConversationGroupProfile(m));const iA=new DC({userID:D,nameCard:M});return dn({group:W,member:iA},{message:T})}catch(P){throw new u.ChatError({functionName:g,code:P?.errorCode,message:P?.errorInfo,moreMessage:T})}})}_preCheckSettingNameCardParams(s){const{groupID:n}=s,{helper:g}=this._core,u=Yi.getLocalGroup(n);if(Sd(u?.type))throw new g.ChatError({functionName:"setGroupMemberNameCard",code:_m})}},bm=new class{constructor(){this._name="SetGroupMemberCustomField"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"setGroupMemberCustomField",context:this})}setGroupMemberCustomField(s){return pA(this,void 0,void 0,function*(){const n="setGroupMemberCustomField",{helper:g,common:{getCurrentUserID:u}}=this._core;this._preCheckSettingCustomFiledParams(s);const{groupID:E,userID:m=u(),memberCustomField:D}=s,M=`${this._name}.${n} ok, groupID:${E}userID:${m} memberCustomField:${JSON.stringify(D)}`;try{yield lB({groupID:E,userID:m,memberCustomField:D},this._core);const P=Yi.getLocalGroup(E),W=new DC({userID:m,memberCustomField:D});return dn({group:P,member:W},{message:M})}catch(T){throw new g.ChatError({functionName:n,code:T?.errorCode,message:T?.errorInfo,moreMessage:M})}})}_preCheckSettingCustomFiledParams(s){const{groupID:n}=s,{helper:g}=this._core,u=Yi.getLocalGroup(n);if(Sd(u?.type))throw new g.ChatError({functionName:"setGroupMemberCustomField",code:_m})}},qv=new class{init(s,n){s.ssoLog.debug("GroupMember.init"),pD.init(s,n),kQ.init(s),vd.init(s),Rd.init(s,n),Hv.init(s),LQ.init(s),mD.init(s),bm.init(s)}getGroupMemberList(s){return pD.getGroupMemberList(s)}deleteGroupMember(s){return Rd.deleteGroupMember(s)}},_T=new class{init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"getGroupCounters",context:this})}getGroupCounters(s){return pA(this,void 0,void 0,function*(){const n="getGroupCounters";try{Nm(n,sc);const{groupID:g,keyList:u=[]}=s,{avChatRoomKey:E,lastUpdateTime:m}=nc.getLocalGroupCounters(g);if(!(Date.now()-m>=this._getExpireTime()))return{code:0,data:{counters:nc.getLocalCounters(g,u)}};const D=yield function(P){return pA(this,void 0,void 0,function*(){const{groupID:W,GroupCounterKeys:iA,avChatRoomKey:EA}=P,{common:RA}=Wn.core,kA={GroupId:W,keyList:iA,BytesKey:EA};return RA.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_counter",data:kA})})}({groupID:g,keyList:u,avChatRoomKey:E}),{GroupCounter:M=[],GroupCounterSeq:T}=D;return nc.updateLocalGroupCounters({groupID:g,counterList:M,groupCounterSeq:T}),{code:0,data:{counters:nc.getLocalCounters(g,u)}}}catch(g){yC(n,g)}})}_getExpireTime(){const{store:s,utils:{isUndefined:n}}=this._core,g=s.get("cloudConfig")||{},{grp_counter_expire_time:u}=g;return n(u)?3e4:Number(u)}},km=new class{init(s){const{helper:n}=s;n.registerApi({apiName:"setGroupCounters",context:this}),n.registerApi({apiName:"increaseGroupCounter",context:this}),n.registerApi({apiName:"decreaseGroupCounter",context:this})}setGroupCounters(s){return pA(this,void 0,void 0,function*(){return this._handleCounterOperation(Hu,s)})}increaseGroupCounter(s){return pA(this,void 0,void 0,function*(){return this._handleCounterOperation(mm,s)})}decreaseGroupCounter(s){return pA(this,void 0,void 0,function*(){return this._handleCounterOperation(Ri,s)})}_handleCounterOperation(s,n){return pA(this,void 0,void 0,function*(){const g=`${s}GroupCounter`;try{Nm(g,sc);const{groupID:u,key:E,value:m=0}=n,{avChatRoomKey:D}=nc.getLocalGroupCounters(u),M=s===Hu?this._convertObjectToList(n.counters):[{Key:E,Value:m}],T=yield this._updateGroupCounters({groupID:u,counterList:M,avChatRoomKey:D,mode:s});return nc.setGroupCounters(u,T),{code:0,data:{counters:T}}}catch(u){yC(g,u)}})}_updateGroupCounters(s){return pA(this,void 0,void 0,function*(){const n=yield function(E){const{groupID:m,counterList:D,mode:M,avChatRoomKey:T}=E,{common:P}=Wn.core,W={GroupId:m,GroupCounter:D,Mode:M,BytesKey:T};return P.buildAndSendPacket({servcmd:"group_open_http_svc.update_group_counter",data:W})}(s),{GroupCounter:g=[]}=n,u={};return g.forEach(E=>{const{Key:m,Value:D=0}=E;u[m]=D}),u})}_convertObjectToList(s){return Object.entries(s).map(([n,g])=>({Key:n,Value:g||0}))}},IB=new class{init(s){this._core=s,_T.init(s),km.init(s)}isGroupCounterUpdated(s){const{elements:{groupCounterInfo:n}}=s,{utils:{isEmpty:g}}=this._core;return!g(n)}handleGroupCounterUpdated(s){const{to:n,elements:{groupCounterInfo:g}}=s;g.forEach(u=>{const{type:E,groupCounterSeq:m,counterList:D=[]}=u;E!==oi&&E!==on||this._processAndNotifyCounterUpdate(n,m,D),E===yo&&nc.deleteLocalGroupCounters({groupID:n,groupCounterSeq:m,counterList:D})})}_processAndNotifyCounterUpdate(s,n,g){const{OuterEvent:u,notificationCenter:E}=this._core;nc.updateLocalGroupCounters({groupID:s,groupCounterSeq:n,counterList:g}),g.forEach(({Key:m,Value:D=0})=>{E.emitOuterEvent(u.GROUP_COUNTER_UPDATED,{name:u.GROUP_COUNTER_UPDATED,data:{groupID:s,key:m,value:D}})})}reset(){nc.reset()}},Lm=new class{constructor(){this._name="InitGroupAttributes"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"initGroupAttributes",context:this})}initGroupAttributes(s){return pA(this,void 0,void 0,function*(){const{groupID:n,groupAttributes:g}=s,{serverMainSequence:u,avChatRoomKey:E}=zs.getGroupAttributesCache(n),m=zs.convertKeyValueMapToList(g);try{const D=yield function(W,iA){return pA(this,void 0,void 0,function*(){const{groupID:EA,mainSequence:RA,groupAttributeList:kA,avChatRoomKey:xA}=W,LA={GroupId:EA,AttrMainSeq:RA,GroupAttr:kA,BytesKey:xA,AttrControl:["RaceConflict"]};return iA.common.buildAndSendPacket({servcmd:"group_open_http_svc.set_group_attr",data:LA})})}({groupID:n,avChatRoomKey:E,groupAttributeList:m,mainSequence:u},this._core),{AttrMainSeq:M,GroupAttr:T}=D||{},P=T.map(W=>{const{Key:iA,seq:EA}=W;return{key:iA,value:g[iA],sequence:EA}});return zs.saveGroupAttributesCacheValuesCopy(n),zs.refreshGroupAttributesCache({groupID:n,serverMainSequence:M,groupAttributeList:P,operation:cD}),zs.emitGroupAttributesUpdated(n),dn({groupAttributes:g},{message:` groupID:${n} serverMainSequence:${M}`})}catch(D){throw new this._core.helper.ChatError({functionName:"initGroupAttributes",code:D?.errorCode,message:D?.errorInfo})}})}},TT=new class{constructor(){this._name="SetGroupAttributes"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"setGroupAttributes",context:this}),n.registerExperimentalAPI("setRichStatus",this)}setGroupAttributes(s){return pA(this,void 0,void 0,function*(){const{groupID:n,groupAttributes:g,richStatusMode:u}=s,{serverMainSequence:E,avChatRoomKey:m,values:D}=zs.getGroupAttributesCache(n),M=zs.convertKeyValueMapToList(g).map(T=>{var P;const{key:W,value:iA}=T;return{key:W,value:iA,seq:((P=D.get(T.key))===null||P===void 0?void 0:P.sequence)||0}});try{const T=yield function(EA,RA){return pA(this,void 0,void 0,function*(){const{groupID:kA,mainSequence:xA,groupAttributeList:LA,avChatRoomKey:SA,richStatusMode:OA}=EA,JA={GroupId:kA,AttrMainSeq:xA,GroupAttr:LA,BytesKey:SA,AttrControl:["RaceConflict"],AllowRoomEngineOpt:OA};return RA.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_attr",data:JA})})}({groupID:n,avChatRoomKey:m,groupAttributeList:M,mainSequence:E,richStatusMode:u},this._core),{AttrMainSeq:P,GroupAttr:W}=T||{},iA=W.map(EA=>{const{Key:RA,seq:kA}=EA;return{key:RA,value:g[RA],sequence:kA}});return zs.saveGroupAttributesCacheValuesCopy(n),zs.refreshGroupAttributesCache({groupID:n,serverMainSequence:P,groupAttributeList:iA,operation:kv}),zs.emitGroupAttributesUpdated(n),dn({groupAttributes:g},{message:` groupID:${n} serverMainSequence:${P}`})}catch(T){throw new this._core.helper.ChatError({functionName:"setGroupAttributes",code:T?.errorCode,message:T?.errorInfo})}})}setRichStatus(s){return pA(this,void 0,void 0,function*(){const{groupID:n,richStatus:g}=s;return this.setGroupAttributes({groupID:n,groupAttributes:g,richStatusMode:!0})})}},fD=new class{constructor(){this._name="DeleteGroupAttributes"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"deleteGroupAttributes",context:this}),n.registerExperimentalAPI("deleteRichStatus",this)}deleteGroupAttributes(s){return pA(this,void 0,void 0,function*(){const n="deleteGroupAttributes",{groupID:g,keyList:u=[],richStatusMode:E}=s;try{let m;m=u.length===0?yield this._clearGroupAttributes(g,{richStatusMode:E}):yield this._deleteGroupAttributes(g,{keyList:u,richStatusMode:E});const{resultList:D,serverMainSequence:M,operation:T,groupAttributeList:P}=m||{},W=`${this._name}.${n} ok. groupID:${g} operation: ${T}`;return zs.saveGroupAttributesCacheValuesCopy(g),zs.refreshGroupAttributesCache({groupID:g,serverMainSequence:M,groupAttributeList:P,operation:T}),zs.emitGroupAttributesUpdated(g),dn({keyList:D},{message:W})}catch(m){throw new this._core.helper.ChatError({functionName:n,code:m?.errorCode,message:m?.errorInfo})}})}deleteRichStatus(s){return pA(this,void 0,void 0,function*(){return this.deleteGroupAttributes(Object.assign(Object.assign({},s),{richStatusMode:!0}))})}_deleteGroupAttributes(s,n){return pA(this,void 0,void 0,function*(){const{serverMainSequence:g,avChatRoomKey:u,values:E}=zs.getGroupAttributesCache(s),{keyList:m,richStatusMode:D}=n,M=[],T=[];m.forEach(iA=>{if(E.has(iA)){const{sequence:EA=0}=E.get(iA)||{};T.push({key:iA,seq:EA}),M.push(iA)}});const P=yield function(iA,EA){return pA(this,void 0,void 0,function*(){const{groupID:RA,mainSequence:kA,groupAttributeList:xA,avChatRoomKey:LA,richStatusMode:SA}=iA,OA={GroupId:RA,AttrMainSeq:kA,GroupAttr:xA,BytesKey:LA,AttrControl:["RaceConflict"],AllowRoomEngineOpt:SA};return EA.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_attr",data:OA})})}({groupID:s,avChatRoomKey:u,groupAttributeList:T,mainSequence:g,richStatusMode:D},this._core),{AttrMainSeq:W}=P||{};return{resultList:M,serverMainSequence:W,groupAttributeList:T,operation:ID}})}_clearGroupAttributes(s,n){return pA(this,void 0,void 0,function*(){const{serverMainSequence:g,avChatRoomKey:u,values:E}=zs.getGroupAttributesCache(s),{richStatusMode:m}=n||{},D=[...E.keys()],M=yield function(P,W){return pA(this,void 0,void 0,function*(){const{groupID:iA,mainSequence:EA,avChatRoomKey:RA,richStatusMode:kA}=P,xA={GroupId:iA,AttrMainSeq:EA,BytesKey:RA,AttrControl:["RaceConflict"],AllowRoomEngineOpt:kA};return W.common.buildAndSendPacket({servcmd:"group_open_http_svc.clear_group_attr",data:xA})})}({groupID:s,avChatRoomKey:u,mainSequence:g,richStatusMode:m},this._core),{AttrMainSeq:T}=M||{};return{resultList:D,serverMainSequence:T,operation:lD}})}},yD=new class{constructor(){this._name="GetGroupAttributes"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"getGroupAttributes",context:this}),n.registerExperimentalAPI("getRichStatus",this,"getGroupAttributes")}getGroupAttributes(s){return pA(this,void 0,void 0,function*(){const{groupID:n}=s,{avChatRoomKey:g,lastUpdateTime:u,localMainSequence:E,serverMainSequence:m}=zs.getGroupAttributesCache(n),{helper:{ChatError:D}}=this._core,M=`groupID:${n} localMainSequence:${E} serverMainSequence:${m} keyList:${s.keyList}`;if(Date.now()-u>=3e4||E{const{key:iA,value:EA,seq:RA}=W;return{key:iA,value:EA,sequence:RA}});return zs.refreshGroupAttributesCache({groupID:u,serverMainSequence:M,groupAttributeList:P,operation:Lv}),{serverGroupAttributeList:T}})}},UQ=new class{init(s){s.ssoLog.debug("GroupAttribute.init"),Lm.init(s),TT.init(s),fD.init(s),yD.init(s),zs.init(s)}isGroupAttributesUpdated(s){return zs.isGroupAttributesUpdated(s)}handleGroupAttributesUpdated(s){const{to:n,elements:{newGroupProfile:g}}=s,{groupAttributeOption:u}=g,{serverMainSequence:E,withChangedAttributeInfo:m}=u,{localMainSequence:D}=zs.getGroupAttributesCache(n),M=E-D;if(console.log(`GroupAttribute.handleGroupAttributesUpdated groupID:${n} withChangedAttributeInfo:${m} diffSequence:${M}`),M!==0)if(zs.saveGroupAttributesCacheValuesCopy(n),m!==1||M!==1){if(zs.hasGroupAttributesCache(n)){const{avChatRoomKey:T}=zs.getGroupAttributesCache(n);yD.getGroupAttributesFromServer({groupID:n,avChatRoomKey:T}).then(()=>{zs.emitGroupAttributesUpdated(n)}).catch(()=>{})}}else zs.handleGroupAttributesUpdated({groupID:n,groupAttributeOption:u})}reset(){zs.reset()}};function HE(s,n="tips"){const{ClientSeq:g,From_Account:u,MsgClientTime:E,MsgPriority:m,MsgRandom:D,MsgSeq:M,MsgTimeStamp:T,TinyId:P,ToGroupId:W,GroupInfo:iA,MsgBody:EA}=s,RA=function(kA){const{GroupCode:xA,GroupId:LA,GroupName:SA,GroupType:OA,MsgFrom_AccountExtraInfo:JA,From_Account:ae,To_Account:re}=kA;return{groupCode:xA,groupID:LA,groupName:SA,type:OA,messageFromAccountExtraInformation:JA,from:ae,to:re}}(iA);return{clientSequence:g,from:u,clientTime:E,priority:m,random:D,sequence:M,time:T,tinyID:P,to:W,groupProfile:RA,elements:n==="tips"?Wu(EA):dh(EA)}}function Wu(s){const n={};return Object.keys(s).forEach(g=>{var u,E;switch(g){case"MemberNum":n.memberCount=s[g];break;case"OpType":n.operationType=s[g];break;case"Operator_Account":n.operatorID=s[g];break;case"List_Account":n.userIDList=s[g];break;case"MsgMemberExtraInfo":n.memberInfoList=(u=s[g])===null||u===void 0?void 0:u.map(m=>DD(m));break;case"MsgOperatorMemberExtraInfo":n.operatorInfo=DD(s[g]);break;case"MsgGroupNewInfo":n.newGroupProfile=function(m){const D={};return Object.keys(m).forEach(M=>{switch(M){case"GroupIntroduction":D.introduction=m[M];break;case"GroupName":D.groupName=m[M];break;case"GroupFaceUrl":D.avatar=m[M];break;case"GroupNotification":D.notification=m[M];break;case"ApplyJoinOption":D.joinOption=m[M];break;case"InviteJoinOption":D.inviteOption=m[M];break;case"ShutupAll":D.muteAllMembers=m[M];break;case"Owner_Account":D.ownerID=m[M];break;case"GroupAttrOption":D.groupAttributeOption=function(P){const{BytesChangedKeys:W,GroupAttrSeq:iA,OpType:EA,PushChangedAttrValFlag:RA,GroupAttrInfo:kA}=P,xA=kA.map(LA=>{const{Key:SA,Val:OA,SubKeySeq:JA}=LA;return{key:SA,value:OA,sequence:JA}});return{changedKeyList:W,groupAttributeList:xA,serverMainSequence:iA,operation:EA,withChangedAttributeInfo:RA}}(m[M]);break;case"MsgAppDefinedData":D.groupCustomField=(T=m[M])==null?void 0:T.map(P=>({key:P.Key,value:P.Value}));break;case"InviteOption":D.inviteOption=vT[m[M]]||m[M]}var T}),D}(s[g]);break;case"MsgMemberInfo":n.msgMemberInfo=(E=s[g])===null||E===void 0?void 0:E.map(m=>function(D){const{ShutupTime:M,User_Account:T}=D;return{muteTime:M,userID:T}}(m));break;case"OnlineMemberInfo":n.onlineMemberInfo=function(m){const{ExpireTime:D,OnlineMemberNum:M}=m;return{expireTime:D,onlineMemberNum:M}}(s[g]);break;case"GroupCounterInfo":n.groupCounterInfo=function(m){return m.map(D=>{const{GroupCounterSeq:M,GroupCounter:T,Type:P}=D;return{type:P,groupCounterSeq:M,counterList:T}})}(s[g])}}),n}function DD(s){const{ImageUrl:n,NickName:g,Role:u,UserId:E}=s;return{avatar:n,nick:g,role:u,userID:E}}function dh(s){const n={};return Object.keys(s).forEach(g=>{switch(g){case"MsgKey":n.messageKey=s[g];break;case"Operator_Account":n.operatorID=s[g];break;case"ReportType":n.operationType=s[g];break;case"Authentication":n.authentication=s[g];break;case"MsgFlag":n.messageRemindType=s[g];break;case"UserDefinedField":n.userDefinedField=s[g];break;case"RemarkInfo":n.remarkInfo=s[g];break;case"BanDuration":n.duration=s[g];break;case"MuteTime":n.muteTime=s[g];break;case"MsgMemberExtraInfoList":n.inviteeInfoList=(u=s[g]||[])==null?void 0:u.map(E=>{const{UserId:m,ImageUrl:D,NickName:M}=E;return{userID:m,avatar:D,nick:M}});break;case"MemberList_Account":n.inviteeList=s[g]}var u}),n}class Um{constructor(n){this.type=Wn.core.OuterConstant.MSG_GRP_TIP,this.content={},this._initContent(n)}static parseServerPushElement(n){const g=Wu(n);return new Um(g)}_initContent(n){Object.keys(n).forEach(g=>{switch(g){case"groupProfile":this._initGroupProfile(n[g]);break;case"operatorInfo":this._initOperatorInfo(n[g]);break;case"memberInfoList":case"msgMemberInfo":this._updateMemberList(n[g]);break;case"newGroupProfile":this._initNewGroupProfile(n[g]);break;case"memberExtraInfo":case"remarkInfo":case"onlineMemberInfo":break;default:this.content[g]=n[g]}}),this.content.userIDList||(this.content.userIDList=[this.content.operatorID])}_initGroupProfile(n){this.content.groupProfile={};const g=Object.keys(n);for(let u=0;u{n.forEach(u=>{g.userID===u.userID&&Object.assign(g,u)})}):this.content.memberList=n}_initNewGroupProfile(n){this.content.newGroupProfile={};const g=Object.keys(n);for(let u=0;u0&&this._handleGroupTipMessage(g),{conversationUpdateFieldList:u,messageList:g}}_emitGroupTipsEvent(s){var n;const{constants:{WORKFLOW_STEP:g}}=this._core,{messageList:u=[]}=((n=s?.result)===null||n===void 0?void 0:n[g.HANDLE_GROUP_TIPS_NOTIFICATION])||{};if(u.length>0){const{notificationCenter:E,OuterEvent:m}=this._core;E.emitOuterEvent(m.MESSAGE_RECEIVED,{name:m.MESSAGE_RECEIVED,data:u})}}_handleGroupTips(s,n=!0){const{Event:g,GroupTips:u}=s,E=new Map,m=[],D=[];for(let M=0,T=u.length;M{const{operationType:u}=g.payload;switch(u){case n.JOINED:this._handleNewMemberJoined(g);break;case n.QUITTED:this._handleMemberQuitted(g);break;case n.KICKED:this._handleMemberKicked(g);break;case n.GROUP_PROFILE_UPDATED:this._handleGroupProfileUpdated(g);break;case n.ADMIN_SET:this._handleMemberGrantAdmin(g);break;case n.ADMIN_CANCELED:this._handleMemberRevokeAdmin(g)}})}_handleNewMemberJoined(s){this._handleGroupMemberCountUpdated(s)}_handleMemberQuitted(s){this._handleGroupMemberCountUpdated(s)}_handleMemberKicked(s){this._handleGroupMemberCountUpdated(s)}_handleGroupProfileUpdated(s){var n;const{newGroupProfile:g,groupProfile:u,operatorInfo:E}=s.payload,{groupID:m}=u,D=Yi.getLocalGroup(m);Object.keys(g).forEach(T=>{switch(T){case"ownerID":this._handleGroupOwnerChanged(m,g);break;case"groupName":D.name=g[T];break;case"groupCustomField":Array.isArray(D[T])&&Array.isArray(g[T])?Tm(D[T],g[T]):D[T]=g[T];break;default:D[T]=g[T]}});const{utils:{isUndefined:M}}=this._core;M(E)||((n=D?.selfInfo)===null||n===void 0?void 0:n.userID)!==E.userID||Object.keys(E).forEach(T=>{T==="nameCard"&&D.updateSelfInfo({nameCard:E[T]}),T==="role"&&this._updateSelfRole(D,E[T])}),Yi.emitGroupListUpdate(),Yi.updateConversationGroupProfile(m)}_handleGroupOwnerChanged(s,n){const{common:g,OuterConstant:u}=this._core,E=Yi.getLocalGroup(s),m=g.getCurrentUserID(),{ownerID:D}=n;m===D&&E.updateGroup({ownerID:D,selfInfo:{role:u.GRP_MBR_ROLE_OWNER}})}_updateSelfRole(s,n){const{OuterConstant:g}=this._core;let u=g.GRP_MBR_ROLE_MEMBER;n===hT?u=g.GRP_MBR_ROLE_OWNER:n===ED&&(u=g.GRP_MBR_ROLE_ADMIN),s.updateSelfInfo({role:u})}_handleGroupMemberCountUpdated(s){const{memberCount:n,groupProfile:{groupID:g}}=s.payload,u=Yi.getLocalGroup(g),{utils:{isNumber:E}}=this._core;u&&E(n)&&u.memberCount!==n&&(u.memberCount=n,Yi.emitGroupListUpdate(),Yi.updateConversationGroupProfile(g))}_handleGroupTipsRecover(s){const{utils:{isArray:n}}=this._core,{groupTipList:g}=s?.result||{};n(g)&&g.forEach(u=>{const{messageList:E}=this._handleGroupTips({Event:u.Event,GroupTips:[u]},!1);this._handleGroupTipMessage(E)})}_handleMemberGrantAdmin(s){const{OuterConstant:n}=this._core,{groupProfile:g,userIDList:u}=s.payload,E=this._core.common.getCurrentUserID(),{groupID:m}=g,D=Yi.getLocalGroup(m);D&&u.includes(E)&&(D.updateSelfInfo({role:n.GRP_MBR_ROLE_ADMIN}),Yi.emitGroupListUpdate(),Yi.updateConversationGroupProfile(m))}_handleMemberRevokeAdmin(s){const{OuterConstant:n}=this._core,{groupProfile:g,userIDList:u}=s.payload,E=this._core.common.getCurrentUserID(),{groupID:m}=g,D=Yi.getLocalGroup(m);D&&u.includes(E)&&(D.updateSelfInfo({role:n.GRP_MBR_ROLE_MEMBER}),Yi.emitGroupListUpdate(),Yi.updateConversationGroupProfile(m))}};class FQ{constructor(n){this.type=Wn.core.OuterConstant.MSG_GRP_SYS_NOTICE,this.content={},this._initContent(n)}static parseServerPushElement(n){const g=dh(n);return new FQ(g)}_initContent(n){Object.keys(n).forEach(g=>{switch(g){case"remarkInfo":this.content.handleMessage=n[g];break;case"groupProfile":this._initGroupProfile(n[g]);break;case"memberInfoList":break;default:this.content[g]=n[g]}})}_initGroupProfile(n){this.content.groupProfile={};const g=Object.keys(n);for(let u=0;u0&&this._handleGroupSysTemMessage(g,E),g===!0&&E.length>0&&m.emitOuterEvent(D.MESSAGE_RECEIVED,{name:D.MESSAGE_RECEIVED,data:E})}_handleGroupSystemNotification(s,n){const g=[];let u={};for(let E=0;E0?[u]:[],messageList:g}}_assembleMessage(s){const{message:{messageFactory:n},OuterConstant:g,utils:{randomInt:u}}=this._core;s.flow="in",s.conversationType=g.CONV_SYSTEM,s.conversationSubType=s.groupProfile.type,s.conversationID=g.CONV_SYSTEM;const E=n.createMessage(s),m=new FQ(Object.assign(Object.assign({},s.elements),{groupProfile:Object.assign({},s.groupProfile)}));E.setElement(m),E.isSystemMessage=!0;const D=E.sequence===1&&E.random===1,M=E.sequence===2&&E.random===2;return(D||M)&&(E.sequence=u(),E.random=u(),E.generateMessageID()),E}_handleConversationOptions(s,n){const{OuterConstant:g}=this._core,u={conversationID:g.CONV_SYSTEM,unreadCount:0,type:g.CONV_SYSTEM,subType:s.conversationSubType,lastMessage:null};return n&&u.unreadCount++,u}_handleGroupSysTemMessage(s,n){s&&n.forEach(g=>{const{operationType:u}=g.payload;switch(u){case QT:this._handleGroupJoinResult(g);break;case Fv:this._handleMemberKicked(g);break;case pT:this._handleGroupDismissed(g);break;case mT:this._handleGroupInvitedResult(g);break;case dD:this._handleGroupQuitResult(g);break;case TQ:this._handleMessageRemindTypeSynced(g);break;case Mm:this._handleAVChatRoomMemberBanned(g)}})}_handleGroupJoinResult(s){const{groupProfile:n}=s.payload,{groupID:g,type:u}=n,E=Yi.hasLocalGroup(g);this._core.ssoLog.debug("_handleGroupJoinResult",` groupID:${g} type:${u} hasLocalGroup:${E}`),E||Sd(u)||(Yi.updateLocalGroup([Object.assign({},n)]),Yi.emitGroupListUpdate())}_handleMemberKicked(s){const{groupProfile:{groupID:n,type:g}}=s.payload;Yi.hasLocalGroup(n)&&this._deleteLocalGroup(n,g),this._updateConversationProfile(n,{unreadCount:0})}_handleGroupDismissed(s){const{groupProfile:{groupID:n,type:g}}=s.payload;Yi.hasLocalGroup(n)&&this._deleteLocalGroup(n,g),this._updateConversationProfile(n,{unreadCount:0})}_handleGroupInvitedResult(s){const{groupProfile:n}=s.payload,{groupID:g}=n,u=Yi.hasLocalGroup(g);this._core.ssoLog.debug("_handleGroupInvitedResult",` groupID:${g} hasLocalGroup:${u}`),u||Pl.getGroupProfile({groupID:g}).then(E=>{const{data:{group:m}}=E;Yi.updateLocalGroup([Object.assign({},m)]),Yi.emitGroupListUpdate()})}_handleGroupQuitResult(s){const{groupProfile:{groupID:n,type:g}}=s.payload,u=Yi.hasLocalGroup(n);this._core.ssoLog.debug("_handleGroupQuitResult",` groupID:${n} type:${g} hasLocalGroup:${u}`),u&&this._deleteLocalGroup(n,g),this._updateConversationProfile(n,{unreadCount:0})}_handleMessageRemindTypeSynced(s){const{groupProfile:{groupID:n},messageRemindType:g}=s.payload;this._updateConversationProfile(n,{messageRemindType:g})}_handleAVChatRoomMemberBanned(s){const{groupProfile:{groupID:n,type:g}}=s.payload;this._deleteLocalGroup(n,g)}_deleteLocalGroup(s,n){if(Sd(n)){const{appStore:{conversationStore:g},OuterConstant:{CONV_GROUP:u}}=this._core;g.deleteConversation(`${u}${s}`)}Yi.deleteLocalGroup(s),Yi.emitGroupListUpdate()}_updateConversationProfile(s,n){const{appStore:{conversationStore:g},OuterConstant:{CONV_GROUP:u}}=this._core,E=`${u}${s}`;g.getConversation(E)&&g.updateConversation(E,n)}},SD=new class{init(s){this._core=s,s.ssoLog.debug("GroupNotificationHandler.init"),Kv.init(s),jv.init(s);const{notificationCenter:n,InnerEvent:g}=s,{InnerEventSubType:u}=n;n.subscribeInnerEvent(g.MESSAGE_PUSH,u.GROUP_TIPS_NOTIFICATION,this._onNewGroupTipsNotification,this),n.subscribeInnerEvent(g.MESSAGE_PUSH,u.GROUP_SYSTEM_NOTIFICATION,this._onNewGroupSystemNotification,this),n.subscribeInnerEvent(g.DESTROY,this._dispose,this)}_onNewGroupTipsNotification(s){const{common:{workflowManager:n},constants:{WORKFLOW_NAME:g}}=this._core;n.executeWorkflow(g.RECEIVE_GROUP_TIPS_NOTIFICATION,s)}_onNewGroupSystemNotification(s){jv.onNewGroupSystemNotification(s)}_dispose(){const{notificationCenter:s,InnerEvent:n}=this._core,{InnerEventSubType:g}=s;s.unSubscribeInnerEvent(n.MESSAGE_PUSH,g.GROUP_TIPS_NOTIFICATION,this._onNewGroupTipsNotification,this),s.unSubscribeInnerEvent(n.MESSAGE_PUSH,g.GROUP_SYSTEM_NOTIFICATION,this._onNewGroupSystemNotification,this)}};const vn={required:!0,rules:["string"],allowEmpty:!1},OQ={required:!0,rules:["number"],allowEmpty:!1},wd={required:!0,rules:["array"],allowEmpty:!1},MD={required:!0,rules:["object"],allowEmpty:!1},NT={createGroup:{name:vn,type:vn},dismissGroup:[Object.assign({key:"groupID"},vn)],joinGroup:{groupID:vn,applyMessage:{required:!1,rules:["string"],allowEmpty:!0}},quitGroup:[Object.assign({key:"groupID"},vn)],searchGroupByID:[Object.assign({key:"groupID"},vn)],getGroupProfile:{groupID:vn,groupCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},updateGroupProfile:{groupID:vn,muteAllMembers:{required:!1,rules:["boolean"],allowEmpty:!1}},changeGroupOwner:{groupID:vn,newOwnerID:vn},getGroupOnlineMemberCount:[Object.assign({key:"groupID"},vn)],handleGroupApplication:{handleAction:vn},getGroupMemberList:{groupID:vn},getGroupMemberProfile:{groupID:vn,userIDList:wd,memberCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},addGroupMember:{groupID:vn,userIDList:wd},deleteGroupMember:{groupID:vn,userIDList:wd},setGroupMemberMuteTime:{groupID:vn,userID:vn,muteTime:Object.assign(Object.assign({},OQ),{customValidator:s=>!(s<0)||"muteTime must be a non-negative number."})},setGroupMemberRole:{groupID:vn,userID:vn,role:vn},setGroupMemberNameCard:{groupID:vn,userID:{required:!1,rules:["string"],allowEmpty:!1},nameCard:vn},setGroupMemberCustomField:{groupID:vn,userID:{required:!1,rules:["string"],allowEmpty:!1},memberCustomField:wd},markGroupMemberList:{groupID:vn,markType:Object.assign(Object.assign({},OQ),{customValidator:s=>!(s<1e3)||"markType must be greater than or equal to 1000."}),enableMark:{required:!0,rules:["boolean"],allowEmpty:!1},userIDList:wd},initGroupAttributes:{groupID:vn,groupAttributes:MD},setGroupAttributes:{groupID:vn,groupAttributes:MD},deleteGroupAttributes:{groupID:vn,keyList:Object.assign(Object.assign({},wd),{allowEmpty:!0})},getGroupAttributes:{groupID:vn,keyList:Object.assign(Object.assign({},wd),{allowEmpty:!0})},getGroupCounters:{groupID:vn,keyList:{required:!1,rules:["array"],allowEmpty:!0}},setGroupCounters:{groupID:vn,counters:MD},increaseGroupCounter:{groupID:vn,key:vn,value:OQ},decreaseGroupCounter:{groupID:vn,key:vn,value:OQ}},GT={getGroupList:!0,createGroup:!0,dismissGroup:!0,joinGroup:!0,quitGroup:!0,searchGroupByID:!0,getGroupProfile:!0,updateGroupProfile:!0,changeGroupOwner:!0,getGroupOnlineMemberCount:!0,getGroupApplicationList:!0,handleGroupApplication:!0,getGroupMemberList:!0,getGroupMemberProfile:!0,addGroupMember:!0,deleteGroupMember:!0,setGroupMemberMuteTime:!0,setGroupMemberRole:!0,setGroupMemberNameCard:!0,setGroupMemberCustomField:!0,markGroupMemberList:!0,initGroupAttributes:!0,setGroupAttributes:!0,getGroupAttributes:!0,deleteGroupAttributes:!0,getGroupCounters:!0,setGroupCounters:!0,increaseGroupCounter:!0,decreaseGroupCounter:!0};var bT=new class{constructor(){this._installedSubPlugins=[],this.groupDataHandler=Yi,this.groupAction=bQ,this.groupAttribute=UQ,this.groupMember=qv,this.groupCounter=IB,this.name="Group"}install(s,n=[]){this._core=s,Wn.init(s),Yi.init(s),bQ.init(s,this),qv.init(s,this),QD.init(s),IB.init(s),UQ.init(s),SD.init(s),s.helper.registerValidateConfig({auth:GT,params:NT}),this._installSubPlugins(n);const{notificationCenter:g,InnerEvent:u}=s;g.subscribeInnerEvent(u.LOGOUT,this._reset,this),g.subscribeInnerEvent(u.DESTROY,this._dispose,this)}getInstalledSubPlugins(){return this._installedSubPlugins}_installSubPlugins(s){const{utils:{isArray:n}}=this._core;s&&n(s)&&s.forEach(g=>{var u;this._installedSubPlugins.includes(g.name)||((u=g.install)===null||u===void 0||u.call(g,this._core,this),this._installedSubPlugins.push(g.name))})}_reset(){Yi.reset(),UQ.reset(),IB.reset()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(n.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this)}};const uB=new class{init(s){this.core=s}},Wv="AV_MBR_LIST",kT="AV_BAN_MBR",qE={NORMAL_MESSAGE:3,GROUP_TIPS_HAS_ROAMING:4,GROUP_SYSTEM_MESSAGE:5,GROUP_TIPS_HAS_NO_ROAMING:6,BROADCAST_MESSAGE:17,MESSAGE_REVOKED:20,MESSAGE_REACTION:21,LIVE_CUSTOM_DATA:100},Ch={GROUP_DISMISSED:5,QUIT_GROUP:8,AVCHATROOM_MEMBER_BANNED:21},vD=60,RD=2603,LT=2686,UT=2688,PQ=3122;class zv{constructor(n){const{core:g,manager:u,groupID:E,getRequestParams:m,onSuccess:D,onFail:M}=n;this._name="Polling",this._core=g,this._manager=u,this._timeoutID=-1,this._isRunning=!1,this._groupID=E,this._getRequestParams=m,this._onSuccess=D,this._onFail=M}start(){this._isRunning=!0,this._request(),console.log(`${this._name}.start pollingInterval:${this._manager.getCurrentPollingInterval(this._groupID)}`)}isRunning(){return this._isRunning}_request(){return pA(this,void 0,void 0,function*(){try{const n=this._getRequestParams(this._groupID),g=yield function(E,m){return pA(this,void 0,void 0,function*(){const{longPollingKey:D,startSequence:M,startBroadcastSeq:T,simplifiedMessage:P}=E,W={Key:D,StartSeq:M,StartBroadcastSeq:T,DownsizeFlag:P,USP:1,HoldTime:90};return m.common.buildAndSendPacket({servcmd:"group_open_long_polling_http_svc.get_msg",data:W})})}(n,this._core);this._onSuccess(this._groupID,g);const u=this._manager.getCurrentPollingInterval(this._groupID);this._runNextPolling(u)}catch(n){this._onFail(this._groupID,n),this._runNextPolling(2e3)}})}_runNextPolling(n){this.isRunning()&&(this._timeoutID>-1&&clearTimeout(this._timeoutID),this._timeoutID=setTimeout(this._request.bind(this),n))}stop(){console.log(`${this._name}.stop timerID:${this._timeoutID}`),this._timeoutID>-1&&(clearTimeout(this._timeoutID),this._timeoutID=-1),this._isRunning=!1}}class hh{constructor(n){this._maxLength=n,this._map=new Map}set(n){var g;if(this._map.size>=this._maxLength){const u=((g=this._map.entries().next().value)===null||g===void 0?void 0:g[0])||"";this._map.delete(u)}this._map.set(n,1)}has(n){return this._map.has(n)}delete(n){this.has(n)&&this._map.delete(n)}clear(){this._map.clear()}}const zu=s=>s===qE.GROUP_TIPS_HAS_NO_ROAMING||s===qE.GROUP_TIPS_HAS_ROAMING,xQ=s=>s===qE.GROUP_SYSTEM_MESSAGE;function Fm(s){const n=function(g){const{E:u,MCT:E,MR:m,MP:D,MTS:M,GId:T,MS:P,CCD:W,F_Account:iA,IsSys:EA,GInf:RA,MsgBody:kA}=g,xA=Do(g,["E","MCT","MR","MP","MTS","GId","MS","CCD","F_Account","IsSys","GInf","MsgBody"]);return Object.assign({Event:u,MsgClientTime:E,MsgRandom:m,MsgPriority:D,MsgTimeStamp:M,ToGroupId:T,MsgSeq:P,CloudCustomData:W,From_Account:iA,IsSystemMsg:EA,GroupInfo:wD(RA),MsgBody:FT(kA)},xA)}(s);return function(g){const{Event:u}=g;(zu(u)||xQ(u))&&(g.From_Account=g.From_Account||"@TIM#SYSTEM"),E=u,(E===qE.BROADCAST_MESSAGE||(m=>m===qE.NORMAL_MESSAGE)(u))&&function(m){const{core:{OuterConstant:D}}=uB;m.CloudCustomData=m.CloudCustomData||"",m.MsgBody=m.MsgBody.map(M=>{if(M.MsgType===D.MSG_CUSTOM){const{content:T={}}=M;M.content=Object.assign({Data:"",Desc:"",Ext:""},T)}return M})}(g);var E;zu(u)&&function(m){const{GroupJoinType:D,MsgOperatorMemberExtraInfo:M={},MsgMemberExtraInfo:T,Operator_Account:P,List_Account:W,OpType:iA}=m.MsgBody||{};typeof D=="number"||iA!==1&&iA!==2||(m.MsgBody.GroupJoinType=iA===2?0:1),T||(m.MsgBody.MsgMemberExtraInfo=W?.map(EA=>({UserId:EA}))),iA!==1||T||(m.MsgBody.MsgMemberExtraInfo=[{UserId:M.UserId}]),m.MsgBody.MsgOperatorMemberExtraInfo=Object.assign({Operator_Account:P,ImageUrl:"",NickName:""},M)}(g),xQ(u)&&function(m){const{MsgOperatorMemberExtraInfo:D={},Operator_Account:M}=m.MsgBody||{};m.MsgBody.MsgMemberExtraInfo=Object.assign({UserId:M,ImageUrl:"",NickName:""},D),m.MsgBody=Object.assign({Authentication:"",RemarkInfo:"",MsgKey:1e3*m.MsgTimeStamp},m.MsgBody),m.MsgBody=Object.keys(m.MsgBody).filter(T=>T!=="MsgOperatorMemberExtraInfo").reduce((T,P)=>Object.assign(Object.assign({},T),{[P]:m.MsgBody[P]}),{})}(g)}(n),n}function wD(s){const n=s||{},{GN:g,GT:u,F_Hd:E,F_NN:m,F_Ll:D}=n,M=Do(n,["GN","GT","F_Hd","F_NN","F_Ll"]),T=Object.assign({GroupName:g,GroupType:u},M);return E&&(T.From_AccountHeadurl=E),m&&(T.From_AccountNick=m),D&&(T.From_AccountLevel=D),T}function FT(s){let n=s;Array.isArray(s)||(n=[s]);const g=n.map(u=>{const{O_Account:E,Opt:m,L_Account:D,RT:M,UDF:T,OpInf:P,OnlineInf:W,MsgMemberExtraInfo:iA}=u,EA=Do(u,["O_Account","Opt","L_Account","RT","UDF","OpInf","OnlineInf","MsgMemberExtraInfo"]),RA=Object.assign({Operator_Account:E,OpType:m,List_Account:D,ReportType:M,UserDefinedField:T},EA);return P&&(RA.MsgOperatorMemberExtraInfo=function(kA){const{Img:xA,NN:LA}=kA,SA=Do(kA,["Img","NN"]);return Object.assign({ImageUrl:xA,NickName:LA},SA)}(P)),iA&&(RA.MsgMemberExtraInfo=function(kA){return kA?.map(xA=>{const{Img:LA,NN:SA}=xA,OA=Do(xA,["Img","NN"]);return Object.assign({ImageUrl:LA,NickName:SA},OA)})}(iA)),W&&(RA.OnlineMemberInfo=function(kA){const{ET:xA,Num:LA}=kA;return{ExpireTime:xA,OnlineMemberNum:LA}}(W)),RA});return Array.isArray(s)?g:g[0]}var Bh=new class{constructor(){this._name="MessageParser",this._sequenceList=new hh(200),this._messageIDList=new hh(100),this._broadcastMessageIDMap=new Map,this._reportMessageStackedCount=0}init(s,n){this._core=s,this._avChatRoomHandler=n}onMessageReceived(s,n,g=!1){this._sortServerMessageList({groupID:s,serverMessageList:n,isHistoryMessage:g});const u=this._handleMessageList(s,n);if(u.length===0)return;if(!g){const{appStore:{conversationStore:T},OuterConstant:{CONV_GROUP:P},common:{buildLastMessage:W}}=this._core,iA=W(u[u.length-1]);T.updateConversation(`${P}${s}`,{lastMessage:iA})}this._checkMessageStacked(u);const E=u.filter(T=>T.isModified===!0),m=u.filter(T=>T.isModified===!1),{OuterEvent:{MESSAGE_RECEIVED:D,MESSAGE_MODIFIED:M}}=this._core;E.length>0&&this._emitEvent({name:M,data:E}),m.length>0&&this._emitEvent({name:D,data:m})}_sortServerMessageList(s){const{groupID:n,serverMessageList:g,isHistoryMessage:u}=s;let E=[];this._avChatRoomHandler.isPollingSimplifiedMessage()&&!u?(g.sort((m,D)=>m.MS-D.MS),E=g.map(m=>m.MS)):(g.sort((m,D)=>m.MsgSeq-D.MsgSeq),E=g.map(m=>m.MsgSeq)),console.log(`${this._name}._sortServerMessageList groupID:${n} count:${E.length} sequenceList:${E}`),E.length=0}_handleMessageList(s,n){var g;const{message:{messageDataHandler:u,messageHelper:E}}=this._core,m=this._avChatRoomHandler.isPollingSimplifiedMessage(),D=[],M=n.length;for(let T=0;Tg===qE.MESSAGE_REVOKED)(n)?(this._handleMessageRevoked(s),null):(g=>g===qE.LIVE_CUSTOM_DATA)(n)?(this._onLiveCustomData(s),null):(g=>g===qE.MESSAGE_REACTION)(n)?null:s:(console.warn(`${this._name}.onMessageReceived unknown event:${n}`),null)}_createMessage(s){const{message:{messageFactory:n},OuterConstant:g}=this._core;let u=g.CONV_GROUP;s.elements.type===g.MSG_GRP_SYS_NOTICE&&(u=g.CONV_SYSTEM);const E=!!s.isSystemMessage,m=n.createMessage(Object.assign(Object.assign({},s),{conversationType:u,isSystemMessage:E,flow:"in"}));return m.setElement(s.elements),m}_filterDuplicateMessage(s){const{common:n}=this._core;if(!n.isUnlimitedAVChatRoom()){if(this._sequenceList.has(s.sequence))return null;this._sequenceList.set(s.sequence)}const g=this._messageIDList.has(s.ID);return g?(console.warn(`${this._name}_filterDuplicateMessageItem ID:${s.ID} has:${g}`),null):(this._messageIDList.set(s.ID),s)}_handleMessageRevoked(s){const{OuterConstant:n,OuterEvent:{MESSAGE_REVOKED:g}}=this._core,{ToGroupId:u,MsgBody:{RevokeMsgList:E},RevokerInfo:{Revoker_Account:m,Reason:D=""}}=s,M=[];E.forEach(T=>{const{TinyId:P,MsgClientTime:W,Random:iA,MsgSeq:EA}=T,RA={conversationID:`${n.CONV_GROUP}${u}`,ID:`${P}-${W}-${iA}`,revoker:m,revokeReason:D,revokerInfo:{userID:m,nick:"",avatar:""},sequence:EA};M.push(RA)}),M.length!==0&&this._emitEvent({name:g,data:M})}_onLiveCustomData(s){const{OuterEvent:{ROOM_CUSTOM_DATA_RECEIVED:n}}=this._core,{ToGroupId:g,MsgSeq:u,MsgTimeStamp:E,MsgBody:m}=s,D=m?.Content||m?.MsgContent||"";this._emitEvent({name:n,data:D}),console.log(`${this._name}._onLiveCustomData groupID:${g} sequence:${u} time:${E} data:${D}`)}_onGroupDismissed(s){this._avChatRoomHandler.reset(s)}_checkMessageStacked(s){const{length:n}=s;if(n>=100&&this._reportMessageStackedCount<5){const g=this._avChatRoomHandler.getJoinedGroups();this._core.ssoLog.info("MessageStacked",`count:${n} groupID:${g.join(",")}`),this._reportMessageStackedCount+=1}}_emitEvent(s){this._core.notificationCenter.emitOuterEvent(s.name,s)}onBroadcastMessageReceived(s){const{message:{messageHelper:n},OuterEvent:{MESSAGE_RECEIVED:g}}=this._core,u=this._avChatRoomHandler.isPollingSimplifiedMessage(),E=[],m=s.length;for(let D=0;D0&&this._emitEvent({name:g,data:E})}_updateLocalOnlineMemberCountFromTips(s){const{utils:{isEmpty:n}}=this._core,{ToGroupId:g,MsgBody:{OnlineMemberInfo:u}}=s;if(n(u))return;const{OnlineMemberNum:E=0,ExpireTime:m=vD}=u,D=Date.now();let M=this._avChatRoomHandler.getLocalOnlineMemberCount(g);n(M)?M={lastReqTime:0,lastSyncTime:0,latestUpdateTime:D,memberCount:E,expireTime:m}:(M.latestUpdateTime=D,M.memberCount=E),this._avChatRoomHandler.updateLocalOnlineMemberCount(g,M)}reset(){this._reportMessageStackedCount=0,this._sequenceList.clear(),this._messageIDList.clear(),this._broadcastMessageIDMap.clear()}};const EB=s=>{const{core:{store:n}}=uB;return(n.get("cloudConfig")||{})[s]},Qh=s=>{const{core:{utils:{isUndefined:n}}}=uB;return!n(s)},YQ=()=>{const s=EB("polling_interval");return Qh(s)?parseInt(s,10):300},dB=()=>{const s=EB("polling_simplified_msg");return Qh(s)?parseInt(s,10):0};var Zv=new class{constructor(){this._name="GetAVChatRoomOnlineMemberCount"}init(s,n){this._core=s,this._parentPlugin=n;const{helper:g}=s;g.registerApi({apiName:"getGroupOnlineMemberCount",context:this,matcher:()=>n.getInstalledSubPlugins().length>0})}getGroupOnlineMemberCount(s){return pA(this,void 0,void 0,function*(){const{appStore:{groupStore:n},OuterConstant:g}=this._core,u=n.getGroup(s);return u?u.type===g.GRP_AVCHATROOM?this._getOnlineMemberCount(s):this._parentPlugin.groupAction.getGroupOnlineMemberCount(s):{code:0,data:{memberCount:0}}})}_getOnlineMemberCount(s){return pA(this,void 0,void 0,function*(){const n="_getOnlineMemberCount",{utils:{isEmpty:g}}=this._core,u=Pg.getLocalOnlineMemberCount(s);if(g(u)||this._isExpired(s)){const{memberCount:E=0}=yield this._getOnlineMemberCountFromServer(s);return console.log(`${this._name}.${n} ok, groupID:${s} memberCount:${E} from server.`),{code:0,data:{memberCount:E}}}return console.log(`${this._name}.${n} ok, groupID:${s} memberCount:${u.memberCount} from local.`),{code:0,data:{memberCount:u.memberCount}}})}_isExpired(s){const n=Pg.getLocalOnlineMemberCount(s),g=Date.now(),u=g-n.lastSyncTime>1e3*n.expireTime,E=g-n.latestUpdateTime>1e4,m=g-n.lastReqTime>3e3;return u&&E&&m}_getOnlineMemberCountFromServer(s){return pA(this,void 0,void 0,function*(){const n="_getOnlineMemberCountFromServer";try{const g=yield function(M,T){return pA(this,void 0,void 0,function*(){const P={GroupId:M};return T.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_online_member_num",data:P})})}(s,this._core),{OnlineMemberNum:u=0,ExpireTime:E=vD}=g||{},m=Date.now(),D={lastSyncTime:m,latestUpdateTime:m,lastReqTime:m,memberCount:u,expireTime:E};return Pg.updateLocalOnlineMemberCount(s,D),{memberCount:u}}catch(g){const u=new this._core.helper.ChatError({functionName:n,code:g?.errorCode,message:g?.errorInfo});throw console.error(`${this._name}.${n} fail:`,u),u}})}},Pg=new class{constructor(){this._name="AVChatRoomHandler",this._joinedGroupMap=new Map,this._pollingRequestInfoMap=new Map,this._pollingInstanceMap=new Map,this._onlineMemberCountMap=new Map,this._pollingIntervalMap=new Map,this._pollingNoMessageCountMap=new Map,this._membersReqInfoMap=new Map,this._startBroadcastSequence=1}init(s,n){this._core=s,this._parentPlugin=n,Bh.init(s,this),s.ssoLog.debug("AVChatRoomHandler.init")}onAVChatRoomSystemNotification(s){const{OuterConstant:{GRP_AVCHATROOM:n}}=this._core,{GroupTips:g=[]}=s;for(let u=0;u0&&(n=[...this._joinedGroupMap.values()].filter(g=>g.type===s)),n}handleJoinGroupResult(s){return pA(this,void 0,void 0,function*(){const{utils:{isUndefined:n},OuterConstant:{CONV_GROUP:g},apiMap:{getConversationProfile:u},OuterConstant:E}=this._core,{longPollingKey:m,group:D,historyMessageList:M=[]}=s,{groupID:T}=D;return yield this._preCheck(D),this._joinedGroupMap.set(T,D),this._parentPlugin.groupDataHandler.updateLocalGroup([D]),this._parentPlugin.groupDataHandler.emitGroupListUpdate(),u(`${g}${T}`),Zv.getGroupOnlineMemberCount(T),M.length>0&&Bh.onMessageReceived(T,M,!0),n(m)?{code:0,data:{status:E.JOIN_STATUS_SUCCESS,group:D}}:{code:0,data:this.startMessageLongPolling(s)}})}isGroupCounterUpdated(s){return this._parentPlugin.groupCounter.isGroupCounterUpdated(s)}handleGroupCounterUpdated(s){this._parentPlugin.groupCounter.handleGroupCounterUpdated(s)}_preCheck(s){return pA(this,void 0,void 0,function*(){const{common:n,OuterConstant:g,helper:u,apiMap:{quitGroup:E},ssoLog:m}=this._core;if(n.isUnlimitedAVChatRoom()){if(this._pollingInstanceMap.size>(()=>{const T=EB("polling_count_limit");return Qh(T)&&T>0?parseInt(T,10):20})())throw new u.ChatError({code:UT,message:"the count of longPolling exceeds the max limit"});return}if(this._joinedAVChatRoomCount()===0||s.type===g.GRP_LIVE)return;const[D,M]=this._joinedGroupMap.entries().next().value;if(M.selfInfo.role===g.GRP_MBR_ROLE_OWNER)this._parentPlugin.groupDataHandler.deleteLocalGroup(D);else try{yield E(D)}catch(T){m.debug("quitGroup",`${this._name}._preCheck quitGroup failed, groupID:${D} info:`,T)}this.reset(D)})}startMessageLongPolling(s){const{OuterConstant:n}=this._core,{longPollingKey:g,startSequence:u=1,group:E}=s,{groupID:m}=E;return this._pollingRequestInfoMap.set(m,{longPollingKey:g,startSequence:u}),this._pollingIntervalMap.set(m,YQ()),this._startPolling(m),this._reportLongPollingCount(),{status:n.JOIN_STATUS_SUCCESS,group:E}}_startPolling(s){if(this._core.ssoLog.debug("_startPolling",`${this._name}._startPolling groupID:${s}`),this._pollingInstanceMap.has(s)){const g=this._pollingInstanceMap.get(s);return void(g?.isRunning()||g==null||g.start())}const n=new zv({core:this._core,manager:this,groupID:s,getRequestParams:this._handleRequestParams.bind(this),onSuccess:this._handleSuccess.bind(this),onFail:this._handleFailure.bind(this)});n.start(),this._pollingInstanceMap.set(s,n)}_handleRequestParams(s){const{longPollingKey:n,startSequence:g}=this._pollingRequestInfoMap.get(s)||{};return s===[...this._pollingInstanceMap.keys()][0]?{longPollingKey:n,startSequence:g,startBroadcastSeq:this._startBroadcastSequence,simplifiedMessage:dB()}:{longPollingKey:n,startSequence:g,simplifiedMessage:dB()}}_handleSuccess(s,n){const{ErrorCode:g}=n;if(g!==0){const{longPollingKey:u,startSequence:E}=this._pollingRequestInfoMap.get(s)||{};return void console.warn(`${this._name}._handleSuccess groupID:${s} key:${u} startSeq:${E} errorCode:${g}`)}this._hasJoinedAVChatRoom(s)&&this._handleResponseData(s,n)}_handleResponseData(s,n){const{Key:g,NextSeq:u,NextBroadcastSeq:E,RspMsgList:m=[],RspBroadcastMsgList:D=[]}=n;if(g&&u&&this._pollingRequestInfoMap.set(s,{longPollingKey:g,startSequence:u}),E&&E>this._startBroadcastSequence&&(this._startBroadcastSequence=E),m.length>0)this._getPollingNoMessageCount(s)!==0&&(this._updatePollingNoMessageCount(s,0),this._pollingIntervalMap.set(s,YQ())),Bh.onMessageReceived(s,m);else{let M=this._getPollingNoMessageCount(s);if(M+=1,this._updatePollingNoMessageCount(s,M),M===(()=>{const T=EB("polling_no_msg_count");return Qh(T)?parseInt(T,10):20})()){const T=YQ()+(()=>{const P=EB("polling_interval_plus");return Qh(P)?parseInt(P,10):2e3})();this._pollingIntervalMap.set(s,T)}}D.length>0&&Bh.onBroadcastMessageReceived(D)}_handleFailure(s,n){const{ssoLog:g,utils:{safeStringify:u}}=this._core;g.warn("polling",`${this._name}._handleFailure groupID:${s} error: ${u(n)}`)}_joinedAVChatRoomCount(){const{OuterConstant:s}=this._core;let n=[];return this._joinedGroupMap.size>0&&(n=this.getJoinedGroups().filter(g=>g.type===s.GRP_AVCHATROOM)),n.length}_hasJoinedAVChatRoom(s){return this._joinedGroupMap.has(s)}getJoinedGroups(){return[...this._joinedGroupMap.values()]}updateLocalLiveGroup(s,n){this._joinedGroupMap.set(s,n),this._parentPlugin.groupDataHandler.updateLocalGroup([n])}handleLiveHistoryMessages(s,n){Bh.onMessageReceived(s,n,!0)}isOverFrequencyLimit(s){if(!this._membersReqInfoMap.has(s))return this._membersReqInfoMap.set(s,{startTime:Date.now(),requestCount:1}),!1;let{startTime:n,requestCount:g}=this._membersReqInfoMap.get(s);const{interval:u,count:E}=(()=>{const m=EB("av_members_freq_limit");if(Qh(m)){const{interval:D,count:M}=JSON.parse(m);if(M>0&&D>0)return{interval:D,count:M}}return{interval:30,count:4}})();return Date.now()-n>1e3*u?(this._membersReqInfoMap.set(s,{startTime:Date.now(),requestCount:1}),!1):(g+=1,this._membersReqInfoMap.set(s,{startTime:n,requestCount:g}),g>E)}_stopPolling(s){if(this._core.ssoLog.debug("_stopPolling",`${this._name}._stopPolling groupID:${s}`),s){const{appStore:{conversationStore:n},OuterConstant:{CONV_GROUP:g}}=this._core;n.deleteConversation(`${g}${s}`);const u=this._pollingInstanceMap.get(s);return u?.stop(),this._parentPlugin.groupDataHandler.deleteLocalGroup(s),this._pollingInstanceMap.delete(s),this._pollingRequestInfoMap.delete(s),this._joinedGroupMap.delete(s),this._onlineMemberCountMap.delete(s),this._pollingIntervalMap.delete(s),this._pollingNoMessageCountMap.delete(s),void this._membersReqInfoMap.delete(s)}for(const n of this._pollingInstanceMap.values())n?.stop();this._pollingInstanceMap.clear(),this._pollingRequestInfoMap.clear(),this._joinedGroupMap.clear(),this._onlineMemberCountMap.clear(),this._pollingIntervalMap.clear(),this._pollingNoMessageCountMap.clear(),this._membersReqInfoMap.clear()}_updatePollingNoMessageCount(s,n){this._pollingNoMessageCountMap.set(s,n)}_getPollingNoMessageCount(s){return this._pollingNoMessageCountMap.get(s)||0}_reportLongPollingCount(){const s=this._joinedGroupMap.size;if(s>1){const{common:n,OuterConstant:g,ssoLog:u}=this._core,E=n.isUnlimitedAVChatRoom()?1:0,m=[],D=[];Array.from(this._joinedGroupMap.values()).forEach(({groupID:M,type:T})=>{T===g.GRP_LIVE?D.push(M):m.push(M)}),u.info("longPollingCount",String(s),{moreMessage:`av:${m.join(",")} live:${D.join(",")} code: ${E}`,eventType:29})}}reset(s){this._stopPolling(s),this._startBroadcastSequence=1,Bh.reset()}},Xv=new class{init(s,n){this._core=s,this._parentPlugin=n;const{helper:g}=s;g.registerApi({apiName:"joinGroup",context:this,matcher:()=>n.getInstalledSubPlugins().length>0})}joinGroup(s){return pA(this,void 0,void 0,function*(){const{OuterConstant:n}=this._core,g=yield this._parentPlugin.groupAction.joinGroup(s),{data:{status:u,group:{type:E}}}=g;return E===n.GRP_AVCHATROOM?u===n.JOIN_STATUS_ALREADY_IN_GROUP?g:Pg.handleJoinGroupResult(g.data):g})}},OT=new class{init(s,n){this._core=s,this._parentPlugin=n;const{helper:g}=s;g.registerApi({apiName:"quitGroup",context:this,matcher:()=>n.getInstalledSubPlugins().length>0})}quitGroup(s){return pA(this,void 0,void 0,function*(){const{OuterConstant:n}=this._core,g=yield this._parentPlugin.groupAction.quitGroup(s),{data:{type:u}}=g;return u===n.GRP_AVCHATROOM&&Pg.reset(s),g})}},$v=new class{init(s,n){this._core=s,this._parentPlugin=n;const{helper:g}=s;g.registerApi({apiName:"dismissGroup",context:this,matcher:()=>n.getInstalledSubPlugins().length>0})}dismissGroup(s){return pA(this,void 0,void 0,function*(){const{OuterConstant:n}=this._core,g=yield this._parentPlugin.groupAction.dismissGroup(s),{data:{type:u}}=g;return u===n.GRP_AVCHATROOM&&Pg.reset(s),g})}},Om=new class{constructor(){this._name="GetAVChatRoomMemberList"}init(s,n){this._core=s,this._parentPlugin=n;const{helper:g}=s;g.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>n.getInstalledSubPlugins().length>0})}getGroupMemberList(s){return pA(this,void 0,void 0,function*(){const{appStore:{groupStore:n},helper:g,OuterConstant:u}=this._core,{groupID:E}=s,m=n.getGroup(E);if(m?.type===u.GRP_AVCHATROOM&&g.checkBusinessCapabilityBits(Wv)){if(Pg.isOverFrequencyLimit(E))throw{code:2996,message:`Over frequency limit: get_members-${E}`};return this._getGroupMemberList(s)}return this._parentPlugin.groupMember.getGroupMemberList(s)})}_getGroupMemberList(s){return pA(this,void 0,void 0,function*(){const n="_getGroupMemberList",{helper:g}=this._core;try{const u=yield function(M,T){return pA(this,void 0,void 0,function*(){const{groupID:P,offset:W=0}=M,iA={GroupId:P,Timestamp:W};return T.common.buildAndSendPacket({servcmd:"group_open_avchatroom_http_svc.get_members",data:iA})})}(s,this._core),{MemberList:E=[],NextTimestamp:m=0}=u||{},D=this._handleMemberList(E);return console.log(`${this._name}.${n} ok, groupID:${s.groupID} count:${D.length} nextOffset:${m}`),{code:0,data:{memberList:D,offset:m}}}catch(u){const E=new g.ChatError({functionName:n,code:u?.errorCode,message:u?.errorInfo});throw console.error(`${this._name}.${n} fail:`,E),E}})}_handleMemberList(s){return s.map(n=>{const{Member_Account:g,NickName:u="",Avatar:E="",Remark:m="",JoinTime:D=0,Marks:M=[]}=n;return{userID:g,nick:u,avatar:E,remark:m,joinTime:D,marks:M,isOnline:!0}})}},Pm=new class{constructor(){this._name="DeleteAVChatRoomMember"}init(s,n){this._core=s,this._parentPlugin=n;const{helper:g}=s;g.registerApi({apiName:"deleteGroupMember",context:this,matcher:()=>n.getInstalledSubPlugins().length>0})}deleteGroupMember(s){return pA(this,void 0,void 0,function*(){const n="deleteGroupMember",{appStore:{groupStore:g},utils:{isUndefined:u},helper:E,OuterConstant:m}=this._core,{groupID:D}=s,M=g.getGroup(D);if(u(M))throw new E.ChatError({functionName:n,code:RD});if(M.type===m.GRP_AVCHATROOM){if(E.checkBusinessCapabilityBits(kT))return this._deleteGroupMember(s);throw new E.ChatError({functionName:n,code:PQ})}return this._parentPlugin.groupMember.deleteGroupMember(s)})}_deleteGroupMember(s){return pA(this,void 0,void 0,function*(){const n="_deleteGroupMember",{appStore:{groupStore:g},helper:u,ssoLog:E}=this._core,{groupID:m,duration:D=0,userIDList:M}=s;if(D===0)throw new u.ChatError({functionName:n,code:LT});try{return yield function(T,P){return pA(this,void 0,void 0,function*(){const{groupID:W,userIDList:iA,duration:EA,reason:RA}=T,kA={GroupId:W,Members_Account:iA,Duration:EA,Description:RA};return P.common.buildAndSendPacket({servcmd:"group_open_http_svc.ban_group_member",data:kA})})}(s,this._core),E.debug(n,`${this._name}.${n} ok, groupID:${m}`),{code:0,data:{group:g.getGroup(m),userIDList:M}}}catch(T){throw new u.ChatError({functionName:n,code:T?.errorCode,message:T?.errorInfo})}})}},_d=new class{constructor(){this._name="MarkAVChatRoomMember"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"markGroupMemberList",context:this})}markGroupMemberList(s){return pA(this,void 0,void 0,function*(){const n="markGroupMemberList",{groupID:g,markType:u,enableMark:E,userIDList:m=[]}=s,D=this._generateRequestData(s);try{const M=yield function(iA,EA){return pA(this,void 0,void 0,function*(){const{groupID:RA,operationType:kA,memberList:xA}=iA,LA={GroupId:RA,CommandType:kA,MemberList:xA};return EA.common.buildAndSendPacket({servcmd:"group_open_avchatroom_http_svc.modify_user_info",data:LA})})}(D,this._core),{MemberList:T=[]}=M||{},{successUserIDList:P,failureUserIDList:W}=this._handleResult(T,m);return{code:0,data:{successUserIDList:P,failureUserIDList:W},successLog:{message:`${this._name}.${n} ok, groupID:${g} markType:${u} enableMark:${E} success:${P.length} fail:${W.length}`}}}catch(M){throw new this._core.helper.ChatError({functionName:n,code:M?.errorCode,message:M?.errorInfo})}})}_generateRequestData(s){const{groupID:n,markType:g,enableMark:u,userIDList:E=[]}=s,m=u===!0?1:2,D=[...E];return D.length>500&&console.warn(`${this._name}._generateRequestData, the length of userIDList cannot exceed 500`),{groupID:n,operationType:m,memberList:D.map(M=>({Member_Account:M,Marks:[g]}))}}_handleResult(s,n){const g=[],u=[];return s.length===n.length?(g.push(...n),{successUserIDList:g,failureUserIDList:u}):(n.forEach(E=>{s.find(m=>m.Member_Account===E)?g.push(E):u.push(E)}),{successUserIDList:g,failureUserIDList:u})}},AR=new class{init(s,n){s.ssoLog.debug("AVChatRoomAction.init"),Xv.init(s,n),OT.init(s,n),$v.init(s,n),Om.init(s,n),Zv.init(s,n),Pm.init(s,n),_d.init(s)}},eR=new class{constructor(){this._name="LiveHandler"}init(s){this._core=s;const{helper:n,ssoLog:g}=s;n.registerExperimentalAPI("startMessageLongPolling",this),n.registerExperimentalAPI("stopMessageLongPolling",this),g.debug("LiveHandler.init")}startMessageLongPolling(s){const{common:n,utils:{isEmpty:g},OuterConstant:u,ssoLog:E}=this._core,{groupID:m,longPollingKey:D,longPollingSequence:M=1}=s;if(g(D))return E.warn("startMessageLongPolling",`${this._name}.startMessageLongPolling longPollingKey is empty.`),Promise.resolve({});Pg.hasPollingInstance(m)&&this.stopMessageLongPolling({groupID:m});const T=Pg.getJoinedLiveList(),P=n.isUnlimitedAVChatRoom();!P&&T.length>0&&this.stopMessageLongPolling({groupID:T[0].groupID}),E.debug("startMessageLongPolling",`${this._name}.startMessageLongPolling isUnlimited:${P} groupID:${m} longPollingKey:${D} longPollingSequence:${M}`);const W={groupID:m,type:u.GRP_LIVE};return Pg.updateLocalLiveGroup(m,W),this._getLiveHistoryMessages({groupID:m,longPollingKey:D,startSequence:M}),Pg.startMessageLongPolling({group:W,longPollingKey:D,startSequence:M})}stopMessageLongPolling(s){const{groupID:n}=s;return Pg.reset(n),this._core.ssoLog.debug("stopMessageLongPolling",`${this._name}.stopMessageLongPolling ok, groupID:${n}`),Promise.resolve({groupID:n})}_getLiveHistoryMessages(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n}=this._core,{groupID:g}=s;try{const u=yield function(m,D){return pA(this,void 0,void 0,function*(){const{groupID:M,longPollingKey:T,startSequence:P}=m,W={GroupId:M,LongPollingKey:T,PullPreSeq:P};return D.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_huge_group_msg",data:W})})}(s,this._core),{RspMsgList:E=[]}=u||{};n.debug("_getLiveHistoryMessages",`${this._name}._getLiveHistoryMessages ok, groupID:${g} count:${E.length}`),E.length>0&&Pg.handleLiveHistoryMessages(g,E)}catch(u){n.debug("_getLiveHistoryMessages",`${this._name}._getLiveHistoryMessages failed, groupID:${g} info:${u.message}`)}})}},xm=new class{constructor(){this.name="AVChatRoom"}install(s,n){this._core=s,uB.init(s),Pg.init(s,n),AR.init(s,n),eR.init(s);const{notificationCenter:g,InnerEvent:u}=s,{InnerEventSubType:E}=g;g.subscribeInnerEvent(u.MESSAGE_PUSH,E.GROUP_SYSTEM_NOTIFICATION,this._onAVChatRoomSystemNotification,this),g.subscribeInnerEvent(u.LOGOUT,this._reset,this),g.subscribeInnerEvent(u.DESTROY,this._dispose,this)}_onAVChatRoomSystemNotification(s){Pg.onAVChatRoomSystemNotification(s)}_reset(){Pg.reset()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:n}=this._core,{InnerEventSubType:g}=s;s.unSubscribeInnerEvent(n.MESSAGE_PUSH,g.GROUP_SYSTEM_NOTIFICATION,this._onAVChatRoomSystemNotification,this),s.unSubscribeInnerEvent(n.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this)}};const Ag=new class{init(s){this.core=s}},Ym="message",CB="user",hB={OR:"or",AND:"and"},vI=20,PT=20,tR=20,ph={required:!1,rules:["array"],allowEmpty:!0,customValidator:s=>!s||!!(Array.isArray(s)&&s.length<=5)||"keywordList should be an array and length <= 5"},Vm={required:!1,rules:["string"],allowEmpty:!0,customValidator:s=>!s||!![hB.OR,hB.AND].includes(s)||"keywordListMatchType should be OR or AND"},SC={required:!1,rules:["number"],allowEmpty:!0,customValidator:s=>typeof s=="number"&&s>=1&&s<=100||"count must be a number between 1 and 100"},VQ={required:!1,rules:["string"],allowEmpty:!0},iR={required:!1,rules:["array"],allowEmpty:!0,customValidator:s=>{const{OuterConstant:n}=Ag.core;if(!Array.isArray(s))return"groupTypeList should be an array";const g=[n.GRP_PUBLIC,n.GRP_COMMUNITY,n.GRP_WORK,n.GRP_MEETING];let u=!1;for(let E=0;E{const{OuterConstant:n}=Ag.core,g=[n.MSG_TEXT,n.MSG_IMAGE,n.MSG_AUDIO,n.MSG_FILE,n.MSG_VIDEO,n.MSG_LOCATION,n.MSG_CUSTOM,n.MSG_MERGER];let u=!1;for(let E=0;E{const{OuterConstant:n}=Ag.core;return!(!s?.startsWith(n.CONV_C2C)&&!s?.startsWith(n.CONV_GROUP)&&s!==n.CONV_SYSTEM)||"conversationID is invalid"}},Jm=s=>({required:!1,rules:["number"],allowEmpty:!0,customValidator:n=>typeof n=="number"&&n>=0||`${s} should be a number >= 0';`}),_D={required:!1,rules:["string"],allowEmpty:!0,customValidator:s=>{const{OuterConstant:n}=Ag.core;return!![n.GENDER_FEMALE,n.GENDER_MALE].includes(s)||"gender is invalid"}},Hm={searchCloudMessages:{keywordList:ph,keywordListMatchType:Vm,cursor:VQ,senderUserIDList:{required:!1,rules:["array"],allowEmpty:!0,customValidator:s=>!!(Array.isArray(s)&&s.length<=5)||"senderUserIDList should be an array and length <= 5"},messageTypeList:oR,conversationID:sR,timePosition:Jm("timePosition"),timePeriod:Jm("timePeriod")},searchCloudUsers:{keywordList:ph,keywordListMatchType:Vm,cursor:VQ,count:SC,miniBirthday:Jm("miniBirthday"),maxBirthday:Jm("maxBirthday"),gender:_D},searchCloudGroupMembers:{keywordList:ph,keywordListMatchType:Vm,cursor:VQ,count:SC,groupTypeList:iR,groupIDList:{required:!1,rules:["array"],allowEmpty:!0}},searchCloudGroups:{keywordList:ph,keywordListMatchType:Vm,cursor:VQ,count:SC,groupTypeList:iR}},TD={searchCloudMessages:!0,searchCloudUsers:!0,searchCloudGroupMembers:!0,searchCloudGroups:!0};var ND=new class{constructor(){this.name="CloudSearch"}install(s){this._core=s,Ag.init(s),s.helper.registerApi({apiName:"searchCloudMessages",context:this}),s.helper.registerApi({apiName:"searchCloudUsers",context:this}),s.helper.registerApi({apiName:"searchCloudGroupMembers",context:this}),s.helper.registerApi({apiName:"searchCloudGroups",context:this}),s.helper.registerValidateConfig({auth:TD,params:Hm})}searchCloudMessages(s){return pA(this,void 0,void 0,function*(){try{const{OuterConstant:n,helper:g}=this._core,{conversationID:u,timePeriod:E,timePosition:m}=s,D=Do(s,["conversationID","timePeriod","timePosition"]),M=Object.assign({count:100},D);u&&(u.startsWith(n.CONV_C2C)?M.account=u.replace(n.CONV_C2C,""):u.startsWith(n.CONV_GROUP)&&(M.groupID=u.replace(n.CONV_GROUP,""))),this._setTimeRangeParams(M,{timePeriod:E,timePosition:m});const T=yield function(LA){return pA(this,void 0,void 0,function*(){const{count:SA,keywordList:OA,keywordListMatchType:JA,senderUserIDList:ae,messageTypeList:re,endTime:_i,startTime:Ti,cursor:Lt,account:Ni,groupID:cs}=LA,Me={Count:SA,KeywordList:OA,MatchType:JA,SendUserIDList:ae,MsgTypeList:re,EndTime:_i,StartTime:Ti,Cursor:Lt,PeerAccount:Ni,GroupID:cs};return Ag.core.common.buildAndSendPacket({servcmd:"message_search.query",data:Me})})}(M);if(!T)return{code:0,data:{}};const{ErrorCode:P,ErrorInfo:W,TotalCount:iA,Cursor:EA="",ConversationMsgs:RA=[]}=T;if(P!==0)throw{errorCode:P,errorInfo:W};const kA=`keywordList:${s.keywordList} keywordListMatchType:${s.keywordListMatchType} cursor:${s.cursor} res: totalCount:${iA}`;return{code:0,data:{searchResultList:RA.map(LA=>{const{MsgList:SA,Count:OA,GroupID:JA,UserID:ae}=LA,re=JA?`${n.CONV_GROUP}${JA}`:`${n.CONV_C2C}${ae}`;if(this._isSearchingAllConversations(s)&&OA>1)return{conversationID:re,messageCount:OA,messageList:[]};const _i=SA.map(Ti=>g.isEmpty(JA)?function(Lt,Ni){const cs=Ni.OuterConstant.CONV_C2C,Me=Ni.message.messageHelper.parseServerPushMessage(Lt),mt=Ni.message.messageFactory.createMessage(Object.assign(Object.assign({},Me),{conversationType:cs,flow:"in"}));return mt.setElement(Me.elements),mt}(Ti,this._core):function(Lt,Ni){const cs=Ni.OuterConstant.CONV_GROUP,Me=Ni.message.messageHelper.parseServerGroupMessage(Lt),mt=Ni.message.messageFactory.createMessage(Object.assign(Object.assign({},Me),{conversationType:cs,flow:"in"}));return mt.setElement(Me.elements),mt}(Ti,this._core));return{conversationID:re,messageCount:OA,messageList:_i}}),cursor:EA,totalCount:iA},successLog:{message:kA}}}catch(n){const{errorCode:g,errorInfo:u}=n||{};this._handleError({errorCode:g,errorInfo:u,searchType:Ym,functionName:"searchCloudMessages"})}})}searchCloudUsers(s){return pA(this,void 0,void 0,function*(){var n;try{const{keywordListMatchType:g,count:u=PT}=s,E=Do(s,["keywordListMatchType","count"]),m=Object.assign({count:u,keywordListMatchType:g===hB.AND?1:0},E);this._setBirthdayRangeParams(m,s);const D=yield function(kA){return pA(this,void 0,void 0,function*(){const{count:xA,keywordList:LA,keywordListMatchType:SA,miniBirthday:OA,maxBirthday:JA,cursor:ae,gender:re}=kA,_i={Count:xA,Keywords:LA,KeywordMatchType:SA,Cursor:ae,UserBirthStart:OA,UserBirthEnd:JA,Gender:re};return Ag.core.common.buildAndSendPacket({servcmd:"user_search.query",data:_i})})}(m);if(!D)return{error:0,data:{}};const{ErrorCode:M,ErrorInfo:T,TotalCount:P,Cursor:W="",Users:iA=[]}=D;if(M!==0)throw{errorCode:M,errorInfo:T};const EA=`keywordList:${s.keywordList} keywordListMatchType:${s.keywordListMatchType} cursor:${s.cursor} count:${s.count} res: totalCount:${P}`,RA=[];for(let kA=0,xA=iA.length;kA({tag:ae.Tag,value:ae.StrValue})),JA=(n=this._core.user.userProfile)===null||n===void 0?void 0:n.createProfile(LA,OA);RA.push(JA)}return{code:0,data:{searchResultList:RA,cursor:W,totalCount:P},successLog:{message:EA}}}catch(g){const{errorCode:u,errorInfo:E}=g||{};this._handleError({errorCode:u,errorInfo:E,searchType:CB,functionName:"searchCloudUsers"})}})}searchCloudGroupMembers(s){return pA(this,void 0,void 0,function*(){try{const{count:n=tR,keywordListMatchType:g}=s,u=Do(s,["count","keywordListMatchType"]),E=Object.assign({count:n,keywordListMatchType:g===hB.AND?1:0},u),m=yield function(RA){return pA(this,void 0,void 0,function*(){const{count:kA,keywordList:xA,keywordListMatchType:LA,groupTypeList:SA,cursor:OA,groupIDList:JA}=RA,ae={Count:kA,Keywords:xA,KeywordMatchType:LA,Cursor:OA,GroupType:SA,GroupIdList:JA};return Ag.core.common.buildAndSendPacket({servcmd:"group_member_search.query",data:ae})})}(E);if(!m)return{code:0,data:{}};const{ErrorCode:D,ErrorInfo:M,GroupMembers:T=[],Cursor:P,TotalCount:W}=m;if(D!==0)throw{errorCode:D,errorInfo:M};const iA=`keywordList:${s.keywordList} keywordListMatchType:${s.keywordListMatchType} cursor:${s.cursor} count:${s.count} res: totalCount:${W}`,EA=new Map;return T.forEach(RA=>{const{GroupID:kA,GroupName:xA,GroupType:LA,GroupFaceUrl:SA,GroupMemberUserName:OA,GroupMemberUserID:JA,GroupMemberNameCard:ae,GroupMemberAvatar:re=""}=RA,_i={groupID:kA,name:xA,type:LA,avatar:SA},Ti={userID:JA,nick:OA,nameCard:ae,avatar:re};if(EA.has(kA)){const Lt=EA.get(kA);Lt.memberList.push(Ti),EA.set(kA,Lt)}else EA.set(kA,{groupInfo:_i,memberList:[Ti]})}),{code:0,data:{searchResultList:[...EA.values()],cursor:P,totalCount:W},successLog:{message:iA}}}catch(n){const{errorCode:g,errorInfo:u}=n||{};this._handleError({errorCode:g,errorInfo:u,searchType:CB,functionName:"searchCloudGroupMembers"})}})}searchCloudGroups(s){return pA(this,void 0,void 0,function*(){try{const{count:n=vI,keywordListMatchType:g}=s,u=Do(s,["count","keywordListMatchType"]),E=Object.assign({count:n,keywordListMatchType:g===hB.AND?1:0},u),m=yield function(EA){return pA(this,void 0,void 0,function*(){const{count:RA,keywordList:kA,keywordListMatchType:xA,groupTypeList:LA,cursor:SA}=EA,OA={Count:RA,Keywords:kA,KeywordMatchType:xA,Cursor:SA,GroupType:LA};return Ag.core.common.buildAndSendPacket({servcmd:"group_search.query",data:OA})})}(E);if(!m)return{code:0,data:{}};const{ErrorCode:D,ErrorInfo:M,Groups:T,Cursor:P,TotalCount:W}=m;if(D!==0)throw{errorCode:D,errorInfo:M};const iA=`keywordList:${s.keywordList} keywordListMatchType:${s.keywordListMatchType} cursor:${s.cursor} count:${s.count} res: totalCount:${W}`;return{code:0,data:{searchResultList:T?.map(EA=>function(RA){const{GroupFaceUrl:kA,GroupID:xA,GroupIntroduction:LA,GroupMemberNum:SA,GroupName:OA,GroupOwnerTinyID:JA,GroupOwnerUserID:ae,GroupOwnerUserName:re,GroupType:_i,GroupAddOption:Ti,GroupInviteOption:Lt}=RA;return{avatar:kA,groupID:xA,introduction:LA,memberCount:SA,name:OA,ownerTinyID:JA,ownerID:ae,ownerNick:re,type:_i,joinOption:Ti,inviteOption:Lt}}(EA))||[],cursor:P,totalCount:W},successLog:{message:iA}}}catch(n){const{errorCode:g,errorInfo:u}=n||{};this._handleError({errorCode:g,errorInfo:u,searchType:CB,functionName:"searchCloudGroups"})}})}_setTimeRangeParams(s,{timePeriod:n,timePosition:g}){n&&n>0&&(s.startTime=g&&g>0?g-n:this._core.helper.timeManager.getServerTimeSeconds()-n),s.startTime&&s.startTime<0&&(s.startTime=void 0),g&&g>0&&(s.endTime=g)}_handleError({errorCode:s,errorMessage:n,searchType:g}){const{helper:u}=this._core;let E=s;throw s===60020?E="SearchUnable":g!==Ym&&s===27003?E="SearchParamsError":g!==Ym&&s===60018&&(E="SearchOverLimit"),new u.ChatError({code:E,message:n})}_isSearchingAllConversations(s){return this._core.helper.isEmpty(s.conversationID)}_setBirthdayRangeParams(s,n){const{miniBirthday:g,maxBirthday:u}=n;g!==void 0&&(s.miniBirthday=g,u===void 0&&(s.maxBirthday=4294967295)),u!==void 0&&(s.maxBirthday=u)}};function mh(s,n){return Math.round(Number(s)*Math.pow(10,n))/Math.pow(10,n)}const nR="qualityStat",GD="im-ssolog-quality-stat";var bD;(function(s){s[s.ONLINE=8]="ONLINE"})(bD||(bD={}));const qm="networkRTT",fh="messageE2EDelay",BB="sendMessageC2C",yh="sendMessageGroup",Dh="sendMessageGroupAV",QB="sendMessageRichMedia",pB="cosUpload",MC="messageReceivedGroup",JQ="messageReceivedGroupAVPush",HQ="messageReceivedGroupAVPull",xT={[qm]:2,[fh]:3,[BB]:4,[yh]:5,[Dh]:6,[QB]:7,[MC]:8,[JQ]:9,[HQ]:10,[pB]:11},rR=[BB,yh,Dh,QB,pB],Sh=[MC,JQ,HQ],mB=[qm,fh,BB,yh,Dh,QB,pB,MC,JQ,HQ],kD={ERR_SVR_COMM_SENSITIVE_TEXT:80001,ERR_SVR_COMM_BODY_SIZE_LIMIT:80002,OPEN_SERVICE_OVERLOAD_ERROR:60022,ERR_SVR_MSG_PKG_PARSE_FAILED:20001,ERR_SVR_MSG_INTERNAL_AUTH_FAILED:20002,ERR_SVR_MSG_INVALID_ID:20003,ERR_SVR_MSG_PUSH_DENY:20006,ERR_SVR_MSG_IN_PEER_BLACKLIST:20007,ERR_SVR_MSG_BOTH_NOT_FRIEND:20009,ERR_SVR_MSG_NOT_PEER_FRIEND:20010,ERR_SVR_MSG_NOT_SELF_FRIEND:20011,ERR_SVR_MSG_SHUTUP_DENY:20012,ERR_SVR_GROUP_INVALID_PARAMETERS:10004,ERR_SVR_GROUP_PERMISSION_DENY:10007,ERR_SVR_GROUP_NOT_FOUND:10010,ERR_SVR_GROUP_INVALID_GROUPID:10015,ERR_SVR_GROUP_REJECT_FROM_THIRDPARTY:10016,ERR_SVR_GROUP_SHUTUP_DENY:10017,MSG_SEND_FAIL:2100,OVER_FREQUENCY_LIMIT:2996},Km="quality_stat";var qQ=new class{constructor(){this._messageStatsMap=new Map,this._userSideErrorCodes=new Set(Object.values(kD))}init(s){this._core=s,Object.values(rR).forEach(n=>{this._messageStatsMap.set(n,{totalCount:0,successCount:0,failedCountOfUserSide:0,costSum:0,costCount:0,fileSizeSum:0})})}dispatchSendStats(s){const{name:n,message:g,error:u,startTs:E}=s,{SEND_MESSAGE_STAT:m}=this._core.constants;switch(n){case m.TOTAL_COUNT:this._handleTotalCount(g);break;case m.SUCCESS_COUNT:this._handleSuccessCount(g);break;case m.FAILED_COUNT:this._handleFailedCount(g,u);break;case m.SEND_COST:this._handleSendCost(g,E)}}getStatResult(s){const n=this._messageStatsMap.get(s);if(!n||n.totalCount===0)return null;const{totalCount:g,successCount:u,failedCountOfUserSide:E}=n,m=mh(u/g*100,2),D=u+E,M=mh(D/g*100,2),T=this._calcAverageValue(n,s);return this._resetStat(s),{total_count:g,success_count_business:u,percent_business:m,success_count_platform:D,percent_platform:M,average_value:T}}_handleTotalCount(s){const n=this._getSendMessageSpecifiedKey(s),g=n&&this._messageStatsMap.get(n);g&&g.totalCount++}_handleSuccessCount(s){const n=this._getSendMessageSpecifiedKey(s),g=n&&this._messageStatsMap.get(n);g&&g.successCount++}_handleFailedCount(s,n){var g;const u=(g=n?.code)!==null&&g!==void 0?g:n?.errorCode;if(this._isUserSideError(u)){const E=this._getSendMessageSpecifiedKey(s),m=E&&this._messageStatsMap.get(E);m&&m.failedCountOfUserSide++}}_handleSendCost(s,n){const g=this._getSendMessageSpecifiedKey(s),u=g&&this._messageStatsMap.get(g);u&&(u.costSum+=Date.now()-n,u.costCount++)}_isUserSideError(s){return this._userSideErrorCodes.has(s)||s>=120001&&s<=13e4||s>=10100&&s<=10200}_getSendMessageSpecifiedKey(s){const{MSG_IMAGE:n,MSG_AUDIO:g,MSG_VIDEO:u,MSG_FILE:E,CONV_C2C:m,CONV_GROUP:D,GRP_AVCHATROOM:M}=this._core.OuterConstant;if([n,g,u,E].includes(s.type))return QB;if(s.conversationType===m)return BB;if(s.conversationType===D){const{groupStore:T}=this._core.appStore,P=T.getGroup(s.to);if(!P)return;const{type:W}=P;return W===M?Dh:yh}}_calcAverageValue(s,n){return s.costCount===0?0:Math.round(n===pB?1e3*s.fileSizeSum/s.costSum:s.costSum/s.costCount)}_resetStat(s){const n=this._messageStatsMap.get(s);n&&(n.totalCount=0,n.successCount=0,n.failedCountOfUserSide=0,n.costSum=0,n.costCount=0,n.fileSizeSum=0)}},KQ=new class{constructor(){this._lastCycleStats=new Map,this._currentCycleStats=new Map}init(s){this._core=s;const{OuterEvent:n,notificationCenter:g}=s;this._initStatsMap(),g.subscribeOuterEvent(n.MESSAGE_RECEIVED,this._onMessageReceived,this)}addMessageSequence(s){const n=this._getReceivedMessageSpecifiedKey(s),{utils:{isUndefined:g},OuterConstant:{CONV_GROUP:u},ssoLog:E}=this._core;if(g(n)||!this._currentCycleStats.has(n))return void E.debug("addMessageSequence",`${nR}.addMessageSequence invalid key:${n}`);const{conversationID:m,sequence:D}=s,M=m.replace(u,""),T=this._lastCycleStats.get(n);if(T.size===0||!T.has(M))return void this._addToCurrentCycle(n,M,D);const P=T.get(M);D>P.minSeq&&D{const{sortedSequences:m,minSeq:D,maxSeq:M}=E;m.length>0&&(u+=m.length,g+=M-D+1)}),g===0?null:(this._transferCycleDataOptimized(s),{total_count:g,success_count_business:u,percent_business:mh(u/g*100,2)})}reset(){this._lastCycleStats.clear(),this._currentCycleStats.clear()}dispose(){const{notificationCenter:s,OuterEvent:{MESSAGE_RECEIVED:n}}=this._core;s.unSubscribeOuterEvent(n,this._onMessageReceived,this),this.reset()}_initStatsMap(){Object.values(Sh).forEach(s=>{this._lastCycleStats.set(s,new Map),this._currentCycleStats.set(s,new Map)})}_onMessageReceived(s){const{data:n=[]}=s;n.forEach(g=>{this.addMessageSequence(g)})}_transferCycleDataOptimized(s){const n=this._currentCycleStats.get(s);if(!n)return;const g=new Map;n.forEach((u,E)=>{const m=u.dirty?[...u.sortedSequences].sort((D,M)=>D-M):u.sortedSequences;g.set(E,{sortedSequences:m,minSeq:u.minSeq,maxSeq:u.maxSeq,dirty:!1})}),this._lastCycleStats.set(s,g),this._currentCycleStats.set(s,new Map)}_getReceivedMessageSpecifiedKey(s){const{OuterConstant:{CONV_GROUP:n,GRP_AVCHATROOM:g}}=this._core;if(s.conversationType===n&&s?._onlineOnlyFlag!==!0){const{groupStore:u}=this._core.appStore,E=u.getGroup(s.to);if(!E)return null;const{type:m}=E;return m===g?HQ:MC}}_insertToLastCycle(s,n){n.dirty&&(n.sortedSequences.sort((u,E)=>u-E),n.dirty=!1);const g=this._findInsertPos(n.sortedSequences,s);n.sortedSequences.splice(g,0,s),n.minSeq=Math.min(n.minSeq,s),n.maxSeq=Math.max(n.maxSeq,s)}_findInsertPos(s,n){let g=0,u=s.length-1;for(;g<=u;){const E=Math.floor((g+u)/2);if(s[E]===n)return E;s[E]0&&(this._totalDelay+=g,this._totalCount++,g<=1?this._countLessThan1s++:g<=3&&this._countLessThan3s++)}getStatResult(){if(this._totalCount===0)return null;const s={total_count:this._totalCount,success_count_business:this._countLessThan1s,success_count_platform:this._countLessThan3s,percent_business:this._calculatePercentage(this._countLessThan1s,this._totalCount),percent_platform:this._calculatePercentage(this._countLessThan3s,this._totalCount),average_value:this._calculateAverageDelay(this._totalCount)};return this.reset(),s}reset(){this._totalDelay=0,this._totalCount=0,this._countLessThan1s=0,this._countLessThan3s=0}dispose(){const{notificationCenter:s,OuterEvent:{MESSAGE_RECEIVED:n}}=this._core;s.unSubscribeOuterEvent(n,this._onMessageReceived,this),this.reset()}_onMessageReceived(s){const{data:n=[]}=s,{OuterConstant:{MSG_GRP_TIP:g,MSG_GRP_SYS_NOTICE:u}}=this._core,E=[g,u];n.forEach(m=>{!E.includes(m.type)&&m.clientTime>0&&this.addMessageDelay(m.clientTime)})}_calculateAverageDelay(s){return s===0?0:mh(this._totalDelay/s,1)}_calculatePercentage(s,n){return mh(s/n*100,2)}},aR=new class{init(s){this.core=s}},YT=new class{constructor(){this.name="MessageQualityStat",this._reportIndex=0,this._wholePeriod=!1,this._pendingReports=[],this._failedLogsCache=new Map}install(s){this._core=s;const{helper:n,notificationCenter:g,InnerEvent:{QUALITY_STAT:u,LOGOUT:E,DESTROY:m},constants:{WORKFLOW_NAME:D,WORKFLOW_STEP:M}}=s;aR.init(s),qQ.init(s),KQ.init(s),jQ.init(s),n.registerWorkflowStep(D.SYNC_SERVER_INFO_AFTER_LOGIN,M.QUALITY_REPORT,this.handleLoginSuccess,this),g.subscribeInnerEvent(u,this._handleQualityStat,this),g.subscribeInnerEvent(E,this._reset,this),g.subscribeInnerEvent(m,this._dispose,this)}handleLoginSuccess(){const{store:s,helper:n,utils:{isUndefined:g}}=this._core,u=s.get("cloudConfig")||{},{q_rpt_interval:E}=u,m=g(E)?12e4:Number(E);n.taskScheduler.addTask({id:Km,intervalMs:m,callback:this.report,context:this})}report(){this._wholePeriod=!0;const s=[...mB.map(n=>{const g=this._buildQualityReportItem(n);return g?Object.assign(Object.assign({},g),{report_index:this._reportIndex,whole_period:this._wholePeriod}):null}).filter(Boolean),...this._pendingReports];this._pendingReports=[],this._needSkipReport()||this._uploadQualityReports(s)}_handleQualityStat(s){const{constants:{QUALITY_METRICS:n}}=this._core,{label:g,data:u}=s;g===n.MESSAGE_SEND_SUCCESS_RATE&&qQ.dispatchSendStats(u)}_needSkipReport(){return this._isSDKAppIDInBlacklist()&&!this._isTinyIDInWhitelist()}_isSDKAppIDInBlacklist(){const{store:s,utils:n}=this._core,g=s.get("cloudConfig")||{},u=s.get("instance")||{},{sdkAppId:E}=u,{q_rpt_sdkappid_bl:m=[]}=g;if(!n.isEmpty(m))return m.split(",").map(D=>Number(D)).includes(E)}_isTinyIDInWhitelist(){const{store:s,utils:n}=this._core,g=s.get("cloudConfig")||{},u=s.get("login")||{},E=Number(u.tinyID),{q_rpt_tinyid_wl:m=[]}=g;if(!n.isEmpty(m))return m.split(",").includes(E)}_buildQualityReportItem(s){const n=this._getStatResultByKey(s);if(n===null)return null;const g={quality_type:xT[s],timestamp:Date.now(),network_type:bD.ONLINE,extension:""};return Object.assign(Object.assign({},g),n)}_getStatResultByKey(s){switch(s){case fh:return jQ.getStatResult();case BB:case yh:case Dh:case QB:case pB:return qQ.getStatResult(s);case MC:case JQ:case HQ:return KQ.getStatResult(s);default:return null}}_uploadQualityReports(s){return pA(this,void 0,void 0,function*(){try{const n={header:this._core.common.getCommonHead(),quality:s};yield function(g){const{common:u,channel:E}=aR.core,m="imopenstat.tim_web_report_v2",D=u.generateSSOLogProtocolData({servcmd:m,data:g}),M=`${D.head.seq}${m}`;return E.sendPacket(D,{requestId:M})}(n),this._reportIndex++,this._wholePeriod=!1}catch(n){console.warn("doReport failed. error:",n),this._pendingReports=this._pendingReports.concat(s),this._cacheFailedLogs()}})}_cacheFailedLogs(){const s=this._pendingReports,n=`${nR}._cacheFailedLogs`;let g=[...this._failedLogsCache.get(GD)||[],...s];g.length>10&&(g=g.slice(g.length-10),console.log(`${n} logs overflow, keeping last 10 items`)),this._failedLogsCache.set(GD,g),console.log(`${n} count: ${g.length}`),this._pendingReports=[]}_reset(){const{helper:s}=this._core;s.taskScheduler.removeTask(Km)}_dispose(){const{notificationCenter:s,InnerEvent:{QUALITY_STAT:n,LOGOUT:g,DESTROY:u}}=this._core;s.unSubscribeInnerEvent(n,this._handleQualityStat,this),s.unSubscribeInnerEvent(g,this._reset,this),s.unSubscribeInnerEvent(u,this._dispose,this),this._reset(),jQ.dispose(),KQ.dispose()}};const ll=new class{init(s){this.core=s}};function gR(s){return pA(this,void 0,void 0,function*(){var n;const{message:g,user:u,appStore:E,constants:{OuterConstant:m}}=ll.core,D=E.conversationStore.getConversationMap();if(D.has(s)){const T=(n=D.get(s))===null||n===void 0?void 0:n.userProfile;if(T&&s.startsWith(m.CONV_C2C)){const{avatar:P,nick:W}=T;ll.core.message.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:s,latestAvatar:P,latestNick:W,isSentByMe:!1})}}const{data:M}=(yield u.userProfile.getMyProfile())||{};if(M){const{avatar:T,nick:P}=M;g.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:s,latestAvatar:T,latestNick:P,isSentByMe:!0})}})}function cR(s){return pA(this,void 0,void 0,function*(){const n=s.map(g=>g.revoker);try{const g=yield function(u){return pA(this,void 0,void 0,function*(){var E,m;const D=yield(E=ll.core.user.userProfile)===null||E===void 0?void 0:E.getUserProfile({userIDList:u});return D?.data?(m=D.data)===null||m===void 0?void 0:m.reduce((M,{userID:T,nick:P,avatar:W})=>(M[T]={nick:P||"",avatar:W||""},M),{}):null})}(n);g&&s.forEach(u=>{const{revoker:E}=u;g[E]&&(u.revokerInfo.nick=g[E].nick||"",u.revokerInfo.avatar=g[E].avatar||"",u.revokerInfo.userID=E)})}catch(g){console.debug(g)}})}const LD=1,lR=2,Mh=20,WQ=2500,IR=1,vh=300;function zQ(s){return pA(this,void 0,void 0,function*(){var n,g;const{appStore:u,utils:{isEmpty:E},common:{getCurrentUserID:m},notificationCenter:D,OuterEvent:M,OuterConstant:{CONV_C2C:T}}=ll.core,{messageList:P,conversationID:W}=s,iA=u.conversationStore.getConversationMap();let EA=(n=iA.get(W))===null||n===void 0?void 0:n.peerReadTime;if(!EA){const kA=W.replace(T,""),xA=yield function(LA){return pA(this,void 0,void 0,function*(){const SA={To_Account:LA};return ll.core.common.buildAndSendPacket({servcmd:"openim.get_peer_read_time",data:SA})})}([kA]);if(xA){const{ReadTime:LA}=xA;EA=LA?.[0],iA.has(W)&&(iA.get(W).peerReadTime=EA)}}if(iA.has(W)){const kA=(g=iA.get(W))===null||g===void 0?void 0:g.lastMessage;E(kA)||kA.fromAccount===m()&&kA.lastTime<=EA&&!kA.isPeerRead&&(kA.isPeerRead=!0,u.conversationStore.updateConversation(W,{lastMessage:kA}))}const RA=[];P.forEach(kA=>{kA.time<=EA&&!kA.isPeerRead&&kA.flow==="out"&&(kA.isPeerRead=!0,RA.push(kA))}),RA.length>0&&D.emitOuterEvent(M.MESSAGE_READ_BY_PEER,{name:M.MESSAGE_READ_BY_PEER,data:RA})})}var uR=new class{init(s){this._core=s,s.helper.registerApi({apiName:"getMessageList",context:this}),s.helper.registerApi({apiName:"getMessageListHopping",context:this}),s.helper.registerApi({apiName:"clearHistoryMessage",context:this})}getMessageList(s){return pA(this,void 0,void 0,function*(){try{const{message:n,OuterConstant:{Direction:g,CONV_C2C:u,CONV_GROUP:E},InnerEvent:{HISTORY_MESSAGE_FETCHED:m},notificationCenter:D}=this._core,{conversationID:M,nextReqMessageID:T}=s,P=Mh;if(M==="@TIM#SYSTEM")return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}};const W=this._getAvailableLocalMessagesCount({conversationID:M,nextReqMessageID:T});if(this._needFetchHistoryMessageList({conversationID:M,availableLocalMessagesCount:W,targetCount:P})){let iA=null;if(M.startsWith(E)?iA=yield n.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:M,sequence:Number(T),count:P,direction:g.FORWARD,shouldMarkCompleted:!0}):M.startsWith(u)&&(iA=yield n.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:M,messageID:T,count:P,direction:g.FORWARD,shouldMarkCompleted:!0})),iA){const{nextReqMessageIDFromServer:EA,hasNoMoreHistoryMessage:RA,messageList:kA}=iA,xA=n.messageDataHandler.prependLocalMessageList({messageList:kA,conversationID:M});(function(ae){const{appStore:re,message:_i,OuterConstant:Ti}=ll.core,Lt=re.conversationStore.getConversation(ae),Ni=_i.messageDataHandler.getLocalMessageList(ae);if(!Lt||Ni.length===0||ae===Ti.CONV_SYSTEM)return;const cs=[];for(let mt=0;mtUA.isRevoked).length;Me=cs.length-Lt.unreadCount-mt}else Me=cs.length-Lt.unreadCount;for(let mt=0;mtae.isRevoked);yield cR(SA),D.emitInnerEvent(m,xA);const OA={nextReqMessageID:RA?"":String(EA),messageList:LA,isCompleted:RA},JA=LA.map(ae=>ae.sequence);return{code:0,data:OA,successLog:{message:`conversationID: ${M} nextReqMessageID: ${T} availableLocalMessagesCount: ${W} sequenceList: ${JSON.stringify(JA)}`}}}return{code:0,data:{messageList:[],isCompleted:!1,nextReqMessageID:""}}}return{code:0,data:yield this._getMessageListFromMemory({conversationID:M,nextReqMessageID:T,count:P}),successLog:{message:`conversationID: ${M} nextReqMessageID: ${T} availableLocalMessagesCount: ${W}}`}}}catch(n){const{code:g,message:u}=n||{};throw new this._core.helper.ChatError({code:g,message:u,moreMessage:`options: ${this._core.utils.safeStringify(s)}`})}})}getMessageListHopping(s){return pA(this,void 0,void 0,function*(){var n,g;const{OuterConstant:{Direction:u,CONV_C2C:E,CONV_GROUP:m},utils:{safeStringify:D}}=this._core,{conversationID:M,sequence:T,time:P,direction:W=u.FORWARD}=s,{utils:{isEmpty:iA},message:EA,notificationCenter:RA,InnerEvent:{HISTORY_MESSAGE_FETCHED:kA}}=this._core;if(![u.BACKWARD,u.FORWARD].includes(W))throw new this._core.helper.ChatError({message:"direction must be 0 or 1",moreMessage:`options: ${D(s)}`});let{count:xA=Mh}=s;xA=xA>Mh?Mh:xA;let LA=null;if(M.startsWith(m)){if(LA=yield EA.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:M,sequence:T,count:xA,direction:W}),LA){const{nextReqMessageIDFromServer:SA,hasNoMoreHistoryMessage:OA,messageList:JA,invisibleSequenceList:ae}=LA;if(this._core.message.messageDataHandler.storeSparseMessageList(JA),RA.emitInnerEvent(kA,JA),W===u.FORWARD){const re=OA&&SA<1;return{code:0,data:{messageList:JA,isCompleted:re,nextMessageSeq:re?"":SA}}}if(W===u.BACKWARD){if(iA(JA)&&iA(ae))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};const re=((n=JA?.[JA.length-1])===null||n===void 0?void 0:n.sequence)||0,_i=((g=ae?.[ae.length-1])===null||g===void 0?void 0:g.sequence)||0;return{code:0,data:{messageList:JA.filter(Ti=>Ti.sequence>=T),isCompleted:!OA,nextMessageSeq:OA?Math.max(re,_i)+1:""}}}return{code:0,data:LA}}}else if(M.startsWith(E)&&(LA=yield EA.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:M,count:xA+1,time:P,direction:W}),LA)){const{messageList:SA,lastMessageTime:OA,hasNoMoreHistoryMessage:JA}=LA;return RA.emitInnerEvent(kA,SA),JA||(W===u.FORWARD?SA.shift():SA.pop()),EA.messageDataHandler.storeSparseMessageList(SA),yield zQ({messageList:SA,conversationID:M}),{code:0,data:{messageList:SA,isCompleted:JA,nextMessageTime:JA?"":OA}}}})}clearHistoryMessage(s){return pA(this,void 0,void 0,function*(){var n;const{appStore:g,common:{ChatError:u,getCurrentUserID:E},OuterConstant:{CONV_C2C:m,CONV_GROUP:D},apiMap:M,message:T}=this._core,P=g.conversationStore.getConversation(s);if(!P)throw new u({code:WQ});const W={fromAccount:E()},{type:iA}=P;iA===m?(W.type=LD,W.toAccount=s.replace(m,"")):iA===D&&(W.type=lR,W.toGroupID=s.replace(D,""));try{return yield(n=M?.setMessageRead)===null||n===void 0?void 0:n.call(M,{conversationID:s}),(yield function(RA){return pA(this,void 0,void 0,function*(){const{fromAccount:kA,type:xA,toAccount:LA,toGroupID:SA}=RA,OA={From_Account:kA,Type:xA,To_Account:LA,ToGroupid:SA};return ll.core.common.buildAndSendPacket({servcmd:"recentcontact.clear_msg",data:OA})})}(W))&&(T.messageDataHandler.deleteConversationMessageList(s),T.messageHistory.completedHistoryConversations.delete(s),T.messageHistory.clearHistoryMessageListFetchAnchors(s),this._updateConversationLastMessage(s)),{code:0,data:{conversationID:s},successLog:{message:`convID:${s}`}}}catch(EA){const{errorCode:RA}=EA;throw new this._core.helper.ChatError({functionName:"clearHistoryMessage",code:RA,moreMessage:`convID:${s}`})}})}_updateConversationLastMessage(s){const{appStore:n}=this._core;n.conversationStore.updateConversation(s,{lastMessage:this._generateLastMessage()},{needSort:!0})}_getAvailableLocalMessagesCount({conversationID:s,nextReqMessageID:n}){const{OuterConstant:{CONV_C2C:g,CONV_GROUP:u}}=this._core,E=this._core.message.messageDataHandler.getLocalMessageList(s),{length:m}=E;if(!n)return m;let D=-1;return s?.startsWith(g)?D=E.findIndex(M=>M.ID===n):s?.startsWith(u)&&(D=E.findIndex(M=>n.includes("-")?M.ID===n:String(M.sequence)===n)),D===-1?0:D}_needFetchHistoryMessageList({conversationID:s,availableLocalMessagesCount:n,targetCount:g}){const{message:u}=this._core;return nn.startsWith(E)?EA.ID===g:String(EA.sequence)===g),W=iA>u?iA-u:0,T=iA):W=M>u?M-u:0,P.messageList=D.slice(W,iA),P.isCompleted=T<=u&&m.messageHistory.completedHistoryConversations.has(n),P.isCompleted?P.nextReqMessageID="":P.nextReqMessageID=this._generateNextReqMessageID({conversationID:n,targetIndex:W}),n.startsWith(E)&&(yield gR(n),yield zQ({messageList:P.messageList,conversationID:n})),P})}_generateNextReqMessageID({conversationID:s,targetIndex:n}){const g=this._core.message.messageDataHandler.getLocalMessageList(s);return s.startsWith("C2C")?g[n].ID:String(g[n].sequence)}_generateLastMessage(){return{lastTime:0,lastSequence:0,fromAccount:"",messageForShow:"",payload:null,type:"",isRevoked:!1,cloudCustomData:"",onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:!1,revoker:null}}},fB=new class{constructor(){this._lastMessageSequenceMapOnDisconnect=new Map,this._lastMessageTimeMapOnDisconnect=new Map}init(s){this._core=s;const{common:{workflowManager:n},constants:{WORKFLOW_NAME:g,WORKFLOW_STEP:u,InnerEvent:E}}=s;n.registerWorkflowStep(g.SYNC_SERVER_INFO_AFTER_RE_ONLINE,u.HISTORY_MESSAGE_RECOVER,this._syncGroupOfflineMessage,this),n.registerWorkflowStep(g.SYNC_SERVER_INFO_AFTER_RE_ONLINE,u.C2C_HISTORY_MESSAGE_RECOVER,this._syncC2COfflineMessage,this),s.notificationCenter.subscribeInnerEvent(E.SOCKET_DISCONNECTED,this._updateLastMessageSequenceMapOnDisconnect,this)}_syncGroupOfflineMessage(s){const{conversationList:n}=s?.result||{},{OuterConstant:g,utils:{isArray:u}}=this._core;if(u(n)){const E=n.filter(m=>m.type===g.CONV_GROUP&&m.groupProfile.type!==g.GRP_AVCHATROOM);return this._recoverGroupHistoryMessage(E)}}_recoverGroupHistoryMessage(s){return pA(this,void 0,void 0,function*(){const{OuterConstant:n}=this._core,g=[],u=[];return yield Promise.all(s?.map(E=>pA(this,void 0,void 0,function*(){const{groupProfile:{groupID:m}={},lastMessage:{lastSequence:D}={}}=E,M=`${n.CONV_GROUP}${m}`;let T=this._getLocalLastMessageSequence(M);this._shouldRecoverHistory({localLastMessageSequence:T,serverLastMessageSequence:D})&&(yield this._recoverGroupHistoryForConversation({conversationID:M,localLastMessageSequence:T,serverLastMessageSequence:D,groupTipList:u})),g.push(M.replace(n.CONV_GROUP,""))}))),{recoverRevokeNoticeGroupIDList:g,groupTipList:u}})}_recoverGroupHistoryForConversation(s){return pA(this,arguments,void 0,function*({conversationID:n,localLastMessageSequence:g,serverLastMessageSequence:u,groupTipList:E}){try{const{utils:{isArray:m,isObject:D,isEmpty:M},OuterEvent:T,OuterConstant:P,notificationCenter:W,message:iA,appStore:EA,common:{getMessagePreviewText:RA,buildLastMessage:kA}}=this._core,xA=u-g,LA=Math.min(20,xA),SA={},OA=yield iA.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:n,sequence:g+LA,direction:P.Direction.FORWARD,count:LA}),{nextReqMessageIDFromServer:JA,hasNoMoreHistoryMessage:ae,messageList:re,serverGroupTipList:_i}=OA;m(_i)&&E.push(..._i);const Ti=ae&&JA<0,Lt=[];if(m(re)&&(re.forEach(Ni=>{iA.messageReceiver.groupMessageReceiver.updateMessageProfile(Ni),Ni.from===P.CONV_SYSTEM&&(Ni.isSystemMessage=!1),iA.messageDataHandler.storeConversationMessage(Ni)&&!M(Ni.payload)&&(Lt.push(Ni),Ni._isExcludedFromLastMessage||(SA.lastMessage=kA(Ni)))}),Lt.length>0&&W.emitOuterEvent(T.MESSAGE_RECEIVED,{name:T.MESSAGE_RECEIVED,data:Lt})),!Ti&&re.length>0){const Ni=re[re.length-1].sequence;yield this._recoverGroupHistoryForConversation({conversationID:n,localLastMessageSequence:Ni,serverLastMessageSequence:u,groupTipList:E})}D(SA.lastMessage)&&(SA.lastMessage.messageForShow=RA(SA.lastMessage.type,SA.lastMessage.payload),EA.conversationStore.updateConversation(n,SA))}catch(m){this._core.ssoLog.error("_recoverGroupHistoryForConversation",`Recovery failed for conversation:${n}`,{error:m})}})}_updateLastMessageSequenceMapOnDisconnect(){const{message:s}=this._core,n=s.messageDataHandler.getContinuousMessagesByConversation();for(const[g,u]of n){const E=Array.from(u.values());if(E?.length>0){const m=E[E.length-1];g.startsWith("C2C")?this._lastMessageTimeMapOnDisconnect.set(g,m.time):g.startsWith("GROUP")&&this._lastMessageSequenceMapOnDisconnect.set(g,m.sequence)}}}_getLocalLastMessageSequence(s){const{message:n}=this._core;if(this._lastMessageSequenceMapOnDisconnect.has(s))return this._lastMessageSequenceMapOnDisconnect.get(s);const g=n.messageDataHandler.getLocalMessageList(s),u=g[g.length-1];return u?.sequence}_shouldRecoverHistory(s){const{localLastMessageSequence:n,serverLastMessageSequence:g}=s;if(typeof n!="number"||typeof g!="number")return!1;const u=g-n;return g!==0&&n>0&&u>=IR&&u{m.type===g.CONV_C2C&&E.push(m)}),this._recoverC2CHistoryMessage(E)}}_recoverC2CHistoryMessage(s){return pA(this,void 0,void 0,function*(){yield Promise.all(s?.map(n=>pA(this,void 0,void 0,function*(){const{conversationID:g,lastMessage:{lastTime:u}={}}=n,E=this._getLocalLastMessageTime(g);this._shouldRecoverC2CHistory({localLastMessageTime:E,serverLastMessageTime:u})&&(yield this._recoverHistoryForC2CConversation({conversationID:g,localLastMessageTime:E,serverLastMessageTime:u}))})))})}_shouldRecoverC2CHistory(s){const{localLastMessageTime:n,serverLastMessageTime:g}=s,u=g-n;return n>0&&u>=1&&u<=600}_recoverHistoryForC2CConversation(s){return pA(this,void 0,void 0,function*(){var n;const{conversationID:g,localLastMessageTime:u,serverLastMessageTime:E}=s,{utils:{isArray:m,isObject:D,isEmpty:M,safeStringify:T},OuterEvent:P,OuterConstant:W,notificationCenter:iA,message:EA,appStore:RA,common:{getMessagePreviewText:kA,buildLastMessage:xA}}=this._core;try{const LA={},SA=yield EA.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:g,direction:W.Direction.BACKWARD,time:u,count:20});if(M(SA))return;const{hasNoMoreHistoryMessage:OA,messageList:JA}=SA,ae=[];m(JA)&&(JA.forEach(_i=>{EA.messageDataHandler.storeConversationMessage(_i)&&!M(_i.payload)&&(ae.push(_i),_i._isExcludedFromLastMessage||(LA.lastMessage=xA(_i)))}),ae.length>0&&iA.emitOuterEvent(P.MESSAGE_RECEIVED,{name:P.MESSAGE_RECEIVED,data:ae}));const re=(n=JA[JA.length-1])===null||n===void 0?void 0:n.time;!OA&&re>E&&(yield this._recoverHistoryForC2CConversation({conversationID:g,localLastMessageTime:re,serverLastMessageTime:E})),D(LA.lastMessage)&&(LA.lastMessage.messageForShow=kA(LA.lastMessage.type,LA.lastMessage.payload),RA.conversationStore.updateConversation(g,LA))}catch(LA){this._core.ssoLog.error("_recoverHistoryForC2CConversation",`Recovery failed for conversation:${g} error: ${T(LA)}`)}})}_getLocalLastMessageTime(s){const{message:n}=this._core;if(this._lastMessageTimeMapOnDisconnect.has(s))return this._lastMessageTimeMapOnDisconnect.get(s);const g=n.messageDataHandler.getLocalMessageList(s),u=g[g.length-1];return u?.time}reset(){this._lastMessageSequenceMapOnDisconnect.clear(),this._lastMessageTimeMapOnDisconnect.clear()}dispose(){this.reset()}},yB=new class{constructor(){this.name="HistoryMessage"}install(s){this._core=s,ll.init(s),uR.init(s),fB.init(s),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.LOGOUT,this._reset,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this.dispose,this)}dispose(){const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(n.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(n.DESTROY,this.dispose,this),fB.dispose()}_reset(){fB.reset()}},UD=new class{init(s){this.core=s}},vC=new class{constructor(){this._reportedAtomicStoreIDs=new Set}init(s){const{helper:{registerExperimentalAPI:n}}=s;this._core=s,n("reportModalView",this),n("reportTUIFeatureUsage",this),n("reportRoomEngineEvent",this)}reportModalView(s){const{ssoLog:n,utils:{safeStringify:g,isString:u}}=this._core;try{if(!u(s))throw new Error("reportModalView data is not a string");n.createSSOLogData({method:"reportModalView",message:s,eventType:30}).end(!0)}catch(E){n.debug(`reportModalView Report failed: ${g(E)}`)}}reportTUIFeatureUsage(s){const{ssoLog:n,utils:{safeStringify:g,isEmpty:u}}=this._core,{atomicStoreID:E}=s;try{u(E)||this._reportedAtomicStoreIDs.has(E)||(this._core.ssoLog.info("reportTUIFeatureUsage",`atomicStoreID: ${s.atomicStoreID}`,{method:"reportTUIFeatureUsage",eventType:31,code:E}),this._reportedAtomicStoreIDs.add(E))}catch(m){n.debug(`reportTUIFeatureUsage Report failed: ${g(m)}`)}}reportRoomEngineEvent(s){const{utils:{safeStringify:n},ssoLog:g}=this._core;try{g.debug(`reportRoomEngineEvent Report: ${n(s)}`);const{eventId:u,eventCode:E,eventResult:m,eventMessage:D,moreMessage:M,extensionMessage:T}=s;g.createSSOLogData({method:T,code:u,message:D,eventType:30,costTime:E,uiPlatform:m,moreMessage:M}).end(!0)}catch(u){g.debug(`reportRoomEngineEvent Report failed: ${n(u)}`)}}reset(){this._reportedAtomicStoreIDs.clear()}dispose(){this.reset()}},ZQ=new class{constructor(){this.name="DataReport"}install(s){this._core=s;const{notificationCenter:n,InnerEvent:{LOGOUT:g,DESTROY:u}}=s;UD.init(s),vC.init(s),n.subscribeInnerEvent(g,this._reset,this),n.subscribeInnerEvent(u,this._dispose,this)}_reset(){vC.reset()}_dispose(){const{notificationCenter:s,InnerEvent:{LOGOUT:n,DESTROY:g}}=this._core;s.unSubscribeInnerEvent(n,this._reset,this),s.unSubscribeInnerEvent(g,this._dispose,this),vC.dispose()}};let jm=nr.STANDARD,DB=[];jm=nr.STANDARD,DB=[ah,IC,uC,EC,Rc,YT,yB,ZQ,PE,vi,jn,bT,xm,ND,ZI];function SB(s,n){const{operationType:g,memberInfoList:u,operatorInfo:E}=s||{};let m={};if(Rs(u)?Rs(E)||(m=E):g!==Tg.JOINED&&g!==Tg.KICKED&&g!==Tg.ADMIN_SET&&g!==Tg.ADMIN_CANCELED||(m=Object.assign({},u[0])),!Rs(m)){const{nick:D="",avatar:M=""}=m;n.nick=D,n.avatar=M}}const XQ=s=>({lastTime:s?.time||s?.lastTime||0,lastSequence:s?.sequence||s?.lastSequence||0,fromAccount:s?.from||s?.fromAccount||"",messageForShow:Zc(s?.type,s?.payload),payload:s?.payload||null,type:s?.type||"",isRevoked:s?.isRevoked||!1,cloudCustomData:s?.cloudCustomData||"",onlineOnlyFlag:s?._onlineOnlyFlag||!1,nick:s?.nick||"",nameCard:s?.nameCard||"",version:s?.version||0,isPeerRead:s?.isPeerRead||!1,revoker:s?.revoker||null});var $Q=Object.freeze({__proto__:null,ChatError:gs,WorkflowManager:ws,buildAndSendPacket:gg,buildLastMessage:XQ,get builtInPlugins(){return DB},checkBusinessCapabilityBits:tn,deepMerge:Cd,getCurrentUserID:Ar,getErrorMessage:rs,getMessagePreviewText:Zc,isC2CConv:s=>l(s)&&s.slice(0,3)===ka.CONV_C2C,isCommunity:Xr,isGroupConv:s=>l(s)&&s.slice(0,5)===ka.CONV_GROUP,isInternational:wl,isTopic:zc,isUnlimitedAVChatRoom:function(){var s;return!!(!((s=ye.store.get("instance"))===null||s===void 0)&&s.unlimitedAVChatRoom)},liteChatInstanceMap:Ca,registerInterceptor:Mc,registerValidateConfig:Wc,requireAuth:ud,get sdkEdition(){return jm},setGroupTipsUserInfo:SB,t:Gu,updateGroupAtInfo:(s,n)=>{const{CONV_AT_ME:g,CONV_AT_ALL:u,CONV_AT_ALL_AT_ME:E}=Lo;if(function(M,T){const{CONV_AT_ME:P,CONV_AT_ALL:W,CONV_AT_ALL_AT_ME:iA}=Lo,{groupID:EA,sequence:RA}=M;let kA=!1;return Xr({groupID:EA})&&T.forEach(xA=>{xA.messageSequence===RA&&(xA.atTypeArray.includes(P)&&M.groupAtType.includes(W)&&(xA.atTypeArray=[iA]),xA.atTypeArray.includes(W)&&M.groupAtType.includes(P)&&(xA.atTypeArray=[iA],xA.__random=M.__random,xA.__sequence=M.__sequence),kA=!0)}),kA}(s,n))return;let m=[...s.groupAtType];m.includes(g)&&m.includes(u)&&(m=[E]);const D={from:s.from,groupID:s.groupID,topicID:s.topicID,messageSequence:s.sequence,atTypeArray:m,__random:s.__random,__sequence:s.__sequence};n.push(D)},validateAndExecute:Sr,validateParameters:II});class ru{constructor(){this._builtInPlugins=new Set,this._externalPlugins=new Set}static getInstance(){return ru._instance||(ru._instance=new ru),ru._instance}static setInstance(n){ru._instance=n}installBuiltInPlugin(n){n&&this._installPlugin(n,this._builtInPlugins)}installExternalPlugin(n){n&&this._installPlugin(n,this._externalPlugins)}clear(){this._builtInPlugins=new Set,this._externalPlugins=new Set}_installPlugin(n,g){let u=[];u=h(n)?n:[n];const E=u.findIndex(D=>D?.name==="AVChatRoom"),m=E>-1?u.splice(E,1):[];u.forEach(D=>{this._isPluginInstalled(D.name)||(D&&vg(D.install)?(g.add(D.name),vg(D.getInstalledSubPlugins)?(m?.forEach(M=>g.add(M?.name)),D.install(Cr.getInstance().exposeApiForPlugin(),m)):D.install(Cr.getInstance().exposeApiForPlugin()),vg(D.handleLoginSuccess)&&this._isLoggedIn()&&D.handleLoginSuccess()):vg(D)?(g.add(D.name),D(Cr.getInstance().exposeApiForPlugin()),vg(D.handleLoginSuccess)&&this._isLoggedIn()&&D.handleLoginSuccess()):console.warn('A plugin must either be a function or an object with an "install" function.'))})}_isPluginInstalled(n){return this._builtInPlugins.has(n)||this._externalPlugins.has(n)}_isLoggedIn(){var n;return((n=ye.store.get("login"))===null||n===void 0?void 0:n.isLoggedIn)===!0}}var MB=new class{constructor(){this._conversationMap=new Map}getConversationMap(){return this._conversationMap}getConversation(s){return this._conversationMap.get(s)}updateConversation(s,n,g){const{emit:u=!0,needSort:E=!1}=g||{},m=this._conversationMap.get(s);m&&!Rs(n)&&(Object.keys(n).forEach(D=>{m[D]=n[D]}),u&&ye.notificationCenter.emitInnerEvent(so.CONVERSATION_UPDATED,{needSort:E}))}deleteConversation(s){this._conversationMap.has(s)&&(this._conversationMap.delete(s),ye.notificationCenter.emitInnerEvent(so.CONVERSATION_UPDATED))}},Ap=new class{constructor(){this._groupMap=new Map}getGroupMap(){return this._groupMap}getGroup(s){return this._groupMap.get(s)}updateGroup(s,n){const g=this._groupMap.get(s);g&&!Rs(n)&&Object.keys(n).forEach(u=>{g[u]=n[u]})}},ep=new class{constructor(){this._messagesByConversation=new Map}updateMessage(s,n,g){var u;const{operation:E,updateUnreadCount:m=!0}=g,D=Do(g,["operation","updateUnreadCount"]),M=[];for(const T of n){const P=(u=this._messagesByConversation.get(s))===null||u===void 0?void 0:u.get(T);if(!P)return!1;Object.keys(D).forEach(W=>{P[W]=D[W]}),M.push(P)}return this._emitMessageStoreOperationEvent(E,{conversationID:s,messageList:M,updateUnreadCount:m}),M}getMessagesByConversation(s){var n;return[...((n=this._messagesByConversation.get(s))===null||n===void 0?void 0:n.values())||[]]}getMessages(){return this._messagesByConversation}_emitMessageStoreOperationEvent(s,n){const{conversationID:g}=n;zc(g)?ye.notificationCenter.emitInnerEvent(Ru[s],n):ye.notificationCenter.emitInnerEvent(s,n)}},rc=new class{constructor(){this.userProfileMap=new Map,this.friendMap=new Map}getUserProfileMap(){return this.userProfileMap}getFriendMap(){return this.friendMap}getUserProfile(s){return this.userProfileMap.get(s)}getFriend(s){return this.friendMap.get(s)}},FD=Object.freeze({__proto__:null,conversationStore:MB,groupStore:Ap,messageStore:ep,userStore:rc});class Cr{static getInstance(){return Cr._instance||(Cr._instance=new Cr),Cr._instance}static setInstance(n){Cr._instance=n}constructor(){this._experimentalApiMap={statTUIKeyFeatures:this.statKeyFeatureUsage.bind(this),setApplicationID:this.setApplicationID.bind(this)},this._apiHandlersMap={},this._apiMap={on:ye.notificationCenter.subscribeOuterEvent.bind(ye.notificationCenter),off:ye.notificationCenter.unSubscribeOuterEvent.bind(ye.notificationCenter),destroy:this.destroy.bind(this),callExperimentalAPI:this.callExperimentalAPI.bind(this),use:ru.getInstance().installExternalPlugin.bind(ru.getInstance()),registerPlugin:this.registerPlugin.bind(this),setLogLevel:this.setLogLevel.bind(this)}}registerPlugin(n){ye.ssoLog.debug("registerPlugin",n)}statKeyFeatureUsage(n){ye.ssoLog.debug("statTUIKeyFeatures",n)}setLogLevel(n){ye.ssoLog.debug("setLogLevel",n),ye.ssoLog.setLogLevel(n)}setApplicationID(n){ye.store.set("instance",{applicationID:n})}getApiMap(){return this._apiMap}setApiMap(n){this._apiMap=n}registerApi(n){const{common:{timeManager:g},utils:{safeStringify:u}}=ye,{apiName:E,context:m,methodName:D=E,matcher:M}=n;this._apiHandlersMap[E]||(this._apiHandlersMap[E]=[]),this._apiHandlersMap[E].push({context:m,methodName:D,matcher:M}),this._apiMap[E]&&this._apiHandlersMap[E].length!==1||(this._apiMap[E]=(...T)=>{const P=g.getServerTimeMs();let W=0;E==="login"&&(W=4),HI.includes(E)&&ye.ssoLog.debug(E,`${E} start params: ${u(T)}`),Sr(D,T);const iA=this._apiHandlersMap[E];for(const EA of iA)if(!EA.matcher||EA.matcher(T))try{const RA=EA.context[EA.methodName].bind(EA.context)(...T);return this._isPromiseLike(RA)?this._handleAsyncResult(RA,E,W,P):(this._reportApiSuccessLog({result:RA,apiName:E,eventType:W,startTime:P}),RA)}catch(RA){throw ye.ssoLog.error(E,`${E} fail ${RA?.message||RA?.errorMessage})`,{error:RA,costTime:g.getServerTimeMs()-P,eventType:W,method:E}),RA}})}registerExperimentalAPI(n,g,u){const E=u||n;this._experimentalApiMap[n]=g[E].bind(g)}destroy(){return pA(this,void 0,void 0,function*(){var n,g;try{!((n=ye.store.get("login"))===null||n===void 0)&&n.isLogin&&(yield this._apiMap.logout()),ye.notificationCenter.emitInnerEvent(so.DESTROY)}catch(u){console.debug("destroy error: ",u)}finally{ye.notificationCenter.emitOuterEvent(Dr.SDK_DESTROY,{SDKAppID:(g=ye.store.get("instance"))===null||g===void 0?void 0:g.sdkAppId}),Ca.clear(),ru.getInstance().clear(),ws.getInstance().destroy(),ye.destroy()}})}exposeApiForClient(){return this._apiMap}exposeApiForPlugin(){return Object.assign(Object.assign({InnerEvent:so,InnerEventSubType:ye.notificationCenter.InnerEventSubType,OuterEvent:Dr,OuterConstant:Lo,SignalingEvent:qc,helper:Object.assign(Object.assign(Object.assign({},ye.utils),ye.common),{registerApi:this.registerApi.bind(this),registerExperimentalAPI:this.registerExperimentalAPI.bind(this),registerInterceptor:Mc,registerValidateConfig:Wc,checkBusinessCapabilityBits:tn,registerWorkflowStep:ws.getInstance().registerWorkflowStep.bind(ws.getInstance()),ChatError:gs}),apiMap:this._apiMap},ye),{constants:Object.assign(Object.assign({},za),ye.constants),common:Object.assign(Object.assign(Object.assign({},$Q),ye.common),{workflowManager:ws.getInstance()}),utils:ye.utils,appStore:FD})}callExperimentalAPI(n,g){return ye.ssoLog.debug(`callExperimentalAPI.${n} start params: ${ye.utils.safeStringify(g)}`),this._experimentalApiMap[n]?this._experimentalApiMap[n](g):(ye.ssoLog.error("callExperimentalAPI",`callExperimentalAPI.${n} not found, params: ${ye.utils.safeStringify(g)}`),Promise.reject(new gs({code:da.INVALID_OPERATION})))}_isPromiseLike(n){return n!==null&&typeof n=="object"&&typeof n.then=="function"}_handleAsyncResult(n,g,u,E){return n.then(m=>(this._reportApiSuccessLog({result:m,apiName:g,eventType:u,startTime:E}),m)).catch(m=>{throw ye.ssoLog.error(g,`${g} fail ${m?.message||m?.errorMessage})`,{error:m,costTime:ye.common.timeManager.getServerTimeMs()-E,eventType:u,method:g,startTime:E}),m})}_reportApiSuccessLog(n){let{result:g,apiName:u,startTime:E,eventType:m}=n;const{timeManager:D}=ye.common,{successLog:{message:M,moreMessage:T}={message:"",moreMessage:""}}=g||{},P=D.getServerTimeMs();u==="login"&&(E+=D.getTimeOffsetWithServer()),HI.includes(u)&&ye.ssoLog.info(u,`${u} success ${M} ${T}`,{costTime:P-E,eventType:m,message:M,moreMessage:T,startTime:E}),g?.successLog&&delete g.successLog}}class ER{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120,this._customLoginInfo=""}init(){const{notificationCenter:n,store:g}=ye;g.set("login",{isReady:!1}),Cr.getInstance().registerApi({apiName:"login",context:this}),Cr.getInstance().registerApi({apiName:"logout",context:this}),Cr.getInstance().registerApi({apiName:"getLoginUser",context:this}),Cr.getInstance().registerApi({apiName:"isReady",context:this}),Cr.getInstance().registerApi({apiName:"getServerTime",context:this}),Cr.getInstance().registerExperimentalAPI("setCustomLoginInfo",this),n.subscribeInnerEvent(so.RECONNECTED,this._reLogin,this),ye.notificationCenter.subscribeInnerEvent(so.DESTROY,this._dispose,this)}login(n){return pA(this,void 0,void 0,function*(){var g;const{sdkEdition:u}=ye.store.get("instance")||{};try{if(this._isLoginIn())return this._createRepeatLoginResponse();if(this._isLoginFrequencyExceeded())throw new gs({functionName:"login",code:da.REPEAT_LOGIN});const E=yield this._performLogin(n);this._validateAfterLogin(E),this._handleLoginSuccess(E),yield this._ensureAsyncComplete(),this._updateAndEmitSDKReady(),this._latestLoginAt=0;const m=(g=ye.channel.getSocketAdapter())===null||g===void 0?void 0:g.getId(),{appId:D,href:M}=ye.store.get("instance")||{},{instanceID:T,customStatus:P}=E||{};return{code:0,data:E,successLog:{message:u,moreMessage:`socketID:${m} instanceID:${T} customStatus:${P} href: ${M} appId: ${D}`}}}catch(E){const{errorCode:m}=E;m!==da.REPEAT_LOGIN&&(this._latestLoginAt=0);const D=new gs({functionName:"login",code:m});throw console.error(D),D}})}_reLogin(){return pA(this,void 0,void 0,function*(){var n;try{if(!this._isLoginIn())return;const g=yield Nu(this._customLoginInfo);if(g){const{instanceID:u,customStatus:E}=g;ye.store.set("login",{statusInstanceId:u}),ws.getInstance().executeWorkflow(Yt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,{customStatus:E,statusType:SE.USER_STATUS_ONLINE});const m=(n=ye.channel.getSocketAdapter())===null||n===void 0?void 0:n.getId();ye.ssoLog.info("reLogin",`socketId:${m} instanceId:${u}`)}}catch(g){console.warn(g)}})}logout(){return pA(this,arguments,void 0,function*(n=na.USER_INITIATED){const{ssoLog:g}=ye;g.debug("logout",`logout start logoutReason: ${n}`);try{yield this._performLogout(n),g.info("logout","logout success"),ye.ssoLog.uploadSSOLogData()}catch(u){const{errorCode:E}=u;throw new gs({functionName:"logout",code:E})}finally{this.handleLogoutCompleted()}return{code:0,data:{}}})}getLoginUser(){return this._isLoginIn()?Ar():""}isReady(){var n;return(n=ye.store.get("login"))===null||n===void 0?void 0:n.isReady}setCustomLoginInfo(n=""){this._customLoginInfo=n}handleLogoutCompleted(){this._updateAndEmitSDKNotReady(),this._reset(),ws.getInstance().reset(),ye.notificationCenter.emitInnerEvent("logout")}getServerTime(){const{timeManager:n}=ye.common;return n.getServerTimeMs()}_updateAndEmitSDKReady(){ye.store.set("login",{isReady:!0}),setTimeout(()=>{ye.notificationCenter.emitOuterEvent(Dr.SDK_READY,{name:Dr.SDK_READY})},1)}_updateAndEmitSDKNotReady(){ye.store.set("login",{isReady:!1}),ye.notificationCenter.emitOuterEvent(Dr.SDK_NOT_READY,{name:Dr.SDK_NOT_READY})}_validateAfterLogin(n){const g="login";if(!n)throw new gs({functionName:g,message:"login response is empty"});const{tinyID:u,a2Key:E}=n||{};if(!u)throw new gs({functionName:g,code:da.NO_TINYID});if(!E)throw new gs({functionName:g,code:da.NO_A2KEY})}_createRepeatLoginResponse(){var n;return{code:0,data:{actionStatus:"OK",errorCode:0,errorInfo:rs({code:"RepeatLogin",replacement1:(n=ye.store.get("login"))===null||n===void 0?void 0:n.userId}),repeatLogin:!0}}}_performLogin(n){return pA(this,void 0,void 0,function*(){const{userID:g,userSig:u}=n;return ye.store.set("login",{userId:g,userSig:u}),this._latestLoginAt=Date.now(),Nu(this._customLoginInfo)})}_ensureAsyncComplete(){return pA(this,void 0,void 0,function*(){yield new Promise(n=>{setTimeout(()=>n(null),1)})})}_handleLoginSuccess(n){const{timeManager:g}=ye.common,{helloInterval:u,timeStamp:E,customStatus:m,purchaseBits:D}=n,M=1e3*E;g.calculateTimeOffsetWithServer(this._latestLoginAt,M),this._helloInterval=u||120,this._updateLoginStore(n),ye.user.userStatus.setCustomStatus(m),ws.getInstance().executeWorkflow(Yt.SYNC_SERVER_INFO_AFTER_LOGIN,{purchaseBits:D}),ye.common.taskScheduler.addTask({id:Gg,intervalMs:1e3*this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this})}_performLogout(n){return function(g){return pA(this,void 0,void 0,function*(){const{logoutReason:u}=g,E="im_open_status.wslogout",m=ye.common.generateProtocolData({servcmd:E,data:{wslogout_type:u,isWebUniapp:0}}),D=`${m.head.seq}${E}`;return yield ye.channel.sendPacket(m,{requestId:D})})}({logoutReason:n})}_updateLoginStore(n){const{a2Key:g,tinyID:u,instanceID:E,authKey:m}=n;ye.store.set("login",{a2Key:g,tinyID:u,statusInstanceId:E,authKey:m,isLoggedIn:!0})}_sendOnlinePresenceRequest(){return pA(this,void 0,void 0,function*(){this._latestSendOnlinePresenceRequestTime=Date.now();try{yield function(){const n="im_open_status.wshello",g=ye.common.generateProtocolData({servcmd:n,data:{isWebUniapp:0}}),u=`${g.head.seq}${n}`;return ye.channel.sendPacket(g,{requestId:u})}()}catch(n){ye.ssoLog.warn("_sendOnlinePresenceRequest",` error:${n.message}`)}})}_isLoginIn(){var n;return((n=ye.store.get("login"))===null||n===void 0?void 0:n.isLoggedIn)===!0}_isLoginFrequencyExceeded(){return Date.now()-this._latestLoginAt<=15e3}_reset(){ye.common.taskScheduler.removeTask(Gg),this._helloInterval=120,this._latestSendOnlinePresenceRequestTime=0,this._latestLoginAt=0,this._customLoginInfo="",ye.store.clear("login"),ye.store.set("login",{isReady:!1}),ye.store.set("instance",{applicationID:0})}_dispose(){this._reset();const{notificationCenter:n}=ye;n.unSubscribeInnerEvent(so.RECONNECTED,this._reLogin,this),n.unSubscribeInnerEvent(so.DESTROY,this._dispose,this)}}const dR={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}},VT={logout:!0};class Rh{constructor(){this.loginAction=new ER,this.kickedOutHandler=new Tu,this.loginAction.init(),this.kickedOutHandler.init(),Wc({auth:VT,params:dR})}}var Kr,Zu,KE;(function(s){s.CONV_C2C="C2C",s.CONV_GROUP="GROUP",s.CONV_TOPIC="TOPIC",s.CONV_SYSTEM="@TIM#SYSTEM"})(Kr||(Kr={})),function(s){s.MSG_PRIORITY_HIGH="High",s.MSG_PRIORITY_NORMAL="Normal",s.MSG_PRIORITY_LOW="Low",s.MSG_PRIORITY_LOWEST="Lowest"}(Zu||(Zu={})),function(s){s.MSG_TEXT="TIMTextElem",s.MSG_CUSTOM="TIMCustomElem",s.MSG_LOCATION="TIMLocationElem",s.MSG_FACE="TIMFaceElem",s.MSG_IMAGE="TIMImageElem",s.MSG_AUDIO="TIMSoundElem",s.MSG_FILE="TIMFileElem",s.MSG_VIDEO="TIMVideoFileElem",s.MSG_GRP_TIP="TIMGroupTipElem",s.MSG_GRP_SYS_NOTICE="TIMGroupSystemNoticeElem",s.MSG_MERGER="TIMRelayElem"}(KE||(KE={}));const OD={1:Zu.MSG_PRIORITY_HIGH,2:Zu.MSG_PRIORITY_NORMAL,3:Zu.MSG_PRIORITY_LOW,4:Zu.MSG_PRIORITY_LOWEST},PD=0,CR=1;var Xu;(function(s){s.IN="in",s.OUT="out"})(Xu||(Xu={}));const hR=2,tp={};function au(s){if(!s)return 0;if(tp[s]===void 0){const n=new Date,g=`3${n.getHours()}`.slice(-2),u=`0${n.getMinutes()}`.slice(-2),E=`0${n.getSeconds()}`.slice(-2);tp[s]=parseInt([g,u,E,"0001"].join(""),10),console.log(`autoIncrementIndex start index:${tp[s]}`)}else tp[s]+=1;return tp[s]}class jE{constructor(n){this.ID="",this.random=0,this.sequence=0,this.nameCard="",this.isRead=!1,this.isPeerRead=!1,this.isDeleted=!1,this.isResend=!1,this.hasRiskContent=!1,this._onlineOnlyFlag=!1,this.atUserList=[],this._groupAtInfoList=[],this.isBroadcastMessage=!1,this.priority=Zu.MSG_PRIORITY_NORMAL,this._relayFlag=!1;const{clientTime:g=ye.common.timeManager.getServerTimeSeconds()||0,senderTinyID:u,currentUser:E,needReadReceipt:m,isSupportExtension:D,customModerationConfigurationId:M,to:T,from:P,nick:W="",avatar:iA="",time:EA,messageControlInfo:RA,tinyID:kA,cloudCustomData:xA="",messageLifeTime:LA,messageVersion:SA=0,conversationType:OA,sequence:JA,checkResult:ae=0,isPlaceMessage:re=0,messageFlagBits:_i,receiverList:Ti,isSystemMessage:Lt=!1,status:Ni=Yr.SUCCESS,revokeReason:cs="",conversationSubType:Me,clientSequence:mt,protocol:UA="JSON",revokerInfo:si={userID:"",nick:"",avatar:""},readReceiptInfo:_s={readCount:void 0,unreadCount:void 0,isPeerRead:void 0,timestamp:0},random:Gi,groupProfile:Or,atUserList:xi,flow:gr,isRead:Tt=!1,priority:Nt=Zu.MSG_PRIORITY_NORMAL,onlineOnlyFlag:AE=!1,nameCard:ln="",quoteInfo:Bo}=n;var Il;this.clientTime=g,this.senderTinyID=u||kA,this.needReadReceipt=m===!0||m===1,this.isSupportExtension=D===!0||D===1,this._cmConfigID=M,this.to=T,this.nick=W,this.avatar=iA,this.protocol=UA,this.random=Gi===void 0?(Il=Il||99999999,Math.round(Math.random()*Il)):Gi,this.time=EA||Math.ceil(Date.now()/1e3),this._isExcludedFromLastMessage=!!RA?.excludedFromLastMessage,this._isExcludedFromUnreadCount=!!RA?.excludedFromUnreadCount,this.isModified=!!SA,this.cloudCustomData=xA,this.messageLifeTime=LA,this.from=P||null,this.sequence=JA||0,this.conversationType=OA||Kr.CONV_C2C,this.hasRiskContent=ae>1,this.version=SA,this.isPlaceMessage=re,this.isRevoked=re===2||_i===8,this.isSystemMessage=Lt,this.readReceiptInfo=_s,this.revokeReason=cs,this.revokerInfo=si,this._receiverList=Ti,this.conversationSubType=Me,this.revoker=si?.revoker||"",this.clientSequence=mt||JA||0,this.status=Ni,this.atUserList=xi||[],this.flow=gr,this.isRead=Tt,this.priority=Nt,this._onlineOnlyFlag=AE,this.nameCard=ln,this.quoteInfo=Bo,this.reInitialize(E),this._initC2CReadReceiptInfo(n),this._extractGroupInfo(Or)}getElements(){return this._elements}isOnlineMessage(){return this.messageLifeTime===0}setElement(n){Array.isArray(n)?this._elements=n:this._elements=[n],this._updatePayloadAndType()}transformElementsToServerFormat(){return this._elements?Array.isArray(this._elements)?this._elements.map(n=>n.transformToServerFormat()):this._elements.transformToServerFormat():null}setRelayFlag(n){this._relayFlag=n}validateBeforeSend(){var n,g,u;return this._relayFlag?{isValid:!0}:((n=this._elements)===null||n===void 0?void 0:n.length)>0?(u=(g=this._elements[0])===null||g===void 0?void 0:g.validateBeforeSend)===null||u===void 0?void 0:u.call(g):{isValid:!1}}_updatePayloadAndType(){this._elements[0]&&(this.payload=this._elements[0].content,this.type=this._elements[0].type)}_initC2CReadReceiptInfo(n){const{readReceiptSentByPeer:g,timestamp:u=0}=n;this.conversationType===Kr.CONV_C2C&&this.needReadReceipt===!0&&(this.readReceiptInfo.isPeerRead=g===1,this.readReceiptInfo.timestamp=u)}_extractGroupInfo(n){if(!n)return;const{From_AccountNick:g,From_AccountHeadurl:u,MsgFrom_AccountExtraInfo:E,GroupType:m}=n,{NameCard:D}=E||{};typeof g=="string"&&(this.nick=g),typeof u=="string"&&(this.avatar=u),typeof D=="string"&&(this.nameCard=D),this.conversationSubType=m}reInitialize(n){n===this.from&&(this.isRead=!0),this._initSequence(n),this._concatConversationID(n),this.generateMessageID()}_concatConversationID(n){let g="";const u=this.conversationType;u!==Kr.CONV_SYSTEM?(g=u===Kr.CONV_C2C?n===this.from?this.to:this.from:this.to,this.conversationID=g?`${u}${g}`:null):this.conversationID=Kr.CONV_SYSTEM}_initSequence(n){this.clientSequence===0&&n&&(this.clientSequence=au(n)),this.sequence===0&&this.conversationType===Kr.CONV_C2C&&(this.sequence=this.clientSequence)}generateMessageID(){this.from===Kr.CONV_SYSTEM&&(this.senderTinyID="144115198244471703"),this.ID=`${this.senderTinyID}-${this.clientTime}-${this.random}`}setIsRead(n){this.isRead=n}}class Td{static parseServerPushElement(n){const{MsgContent:g={}}=n,{Data:u,Ext:E,Desc:m}=g;return new Td({data:u,description:m,extension:E})}constructor(n){this.type=KE.MSG_CUSTOM;const{data:g="",description:u="",extension:E=""}=n;this.content={data:g,description:u,extension:E}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},u=g?this.payload:this.content,{data:E,description:m,extension:D}=u;return{MsgType:this.type,MsgContent:{Data:E,Ext:D,Desc:m}}}validateBeforeSend(){const{isEmpty:n}=ye.utils,g=[this.content.data,this.content.description,this.content.extension].some(u=>!n(u));return{isValid:g,error:g?null:{message:"content can not be empty"}}}}class Nd{static parseServerPushElement(n){const{MsgContent:g={Text:""}}=n,{Text:u}=g;return new Nd({text:u})}constructor(n){this.type=wg.MSG_TEXT,this.content={text:n.text||""}}validateBeforeSend(){var n,g;return((g=(n=this.content)===null||n===void 0?void 0:n.text)===null||g===void 0?void 0:g.length)>0?{isValid:!0}:{isValid:!1,error:{message:"content can not be empty"}}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},u=g?this.payload:this.content,{text:E}=u;return{MsgType:this.type,MsgContent:{Text:E}}}}var Wm=new class{constructor(){this._elementClassMap={[KE.MSG_CUSTOM]:Td,[KE.MSG_TEXT]:Nd}}init(){Cr.getInstance().registerApi({apiName:"createCustomMessage",context:this}),Cr.getInstance().registerApi({apiName:"createTextMessage",context:this})}registerElementClass(s,n){var g;(g=n).prototype!==void 0&&"constructor"in g.prototype&&(this._elementClassMap[s]=n)}getElementClass(s){return this._elementClassMap[s]}createMessage(s){const{from:n,flow:g=Xu.OUT}=s,{userId:u}=ye.store.get("login")||{};this._isSendByCurrentInstance({from:n,flow:g,currentUser:u})?this._updateWithSenderInfo(s):this._isMultiEndpointSyncMessage({from:n,flow:g,currentUser:u})&&(s.flow=Xu.OUT);const E=Object.assign(Object.assign({},s),{currentUser:u});return new jE(E)}createCustomMessage(s){const n=Ar(),g=this.createMessage(Object.assign(Object.assign({},s),{from:n})),u=this._elementClassMap[KE.MSG_CUSTOM];if(!g)return null;if(u){const E=new u(s.payload);g.setElement(E)}return g}createTextMessage(s){var n;if(!s)return null;const g=typeof s.payload=="string"?s.payload:((n=s?.payload)===null||n===void 0?void 0:n.text)||"",u=new Nd({text:g}),E=Ar(),m=ye.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:E}));return m.setElement(u),m}_updateWithSenderInfo(s){var n,g;const{nick:u,avatar:E,conversationType:m,to:D}=s,{userId:M,tinyID:T}=ye.store.get("login")||{},P=rc.getUserProfile(M);return s.nick=u||P?.nick||"",s.avatar=E||P?.avatar||"",s.tinyID=s.tinyID||T||"",s.from=M,s.status=Yr.UNSENT,s.flow=Xu.OUT,m===ka.CONV_GROUP&&(s.nameCard=(g=(n=Ap.getGroup(D))===null||n===void 0?void 0:n.selfInfo)===null||g===void 0?void 0:g.nameCard),s}_isMultiEndpointSyncMessage(s){const{from:n,flow:g,currentUser:u}=s;return n===u&&g===Xu.IN}_isSendByCurrentInstance(s){const{from:n,flow:g,currentUser:u}=s;return n===u&&g===Xu.OUT}};const BR={PushFlag:0,Title:"",Desc:"",Ext:"",ApnsInfo:{Sound:"",BadgeMode:0,IsVoipPush:void 0,Image:"",InterruptionLevel:"active",ContentAvailable:0},AndroidInfo:{Sound:"",XiaoMiChannelID:"",OPPOChannelID:"",GoogleChannelID:"",VIVOClassification:1,VIVOCategory:"",HuaWeiCategory:"",OPPOCategory:"",HuaWeiImage:"",HonorImage:"",GoogleImage:"",HonorImportance:"",MeizuNotifyType:void 0}},Gd={HonorImportance:{range:["LOW","NORMAL"],defaultValue:void 0},MeizuNotifyType:{range:[0,1],defaultValue:void 0}},xD={enableIOSBackgroundNotification:{range:[!0,!1],defaultValue:!1},interruptionLevel:{range:["passive","active","time-sensitive","critical"],defaultValue:"active"}};function QR(s,n){return Object.keys(n).forEach(g=>{const{range:u,defaultValue:E}=n[g];s[g]=u.includes(s[g])?s[g]:E}),s}function ip(s){const n=s.lastIndexOf(".");return n===-1?s:s.slice(0,n)}function pR(s){const{androidInfo:n={},androidOPPOChannelID:g=""}=s,u=n.OPPOChannelID||g,E=QR(n,Gd),{sound:m="",FCMChannelID:D=""}=E,M=Do(E,["sound","FCMChannelID"]);return Object.assign(Object.assign({},M),{Sound:ip(m),OPPOChannelID:u,GoogleChannelID:D})}function mR(s){const{apnsInfo:n={},ignoreIOSBadge:g=!1,disableVoipPush:u}=s,E=QR(n,xD),{ignoreIOSBadge:m,disableVoipPush:D,enableIOSBackgroundNotification:M}=E,T=Do(E,["ignoreIOSBadge","disableVoipPush","enableIOSBackgroundNotification"]),P=m===!0||g===!0?1:0;let W;return r(u)||(W=u===!1?1:0),r(D)||(W=D===!1?1:0),Object.assign(Object.assign({},T),{BadgeMode:P,IsVoipPush:W,ContentAvailable:M?1:0})}function YD(s){return ye.utils.isPlainObject(s)?{PushFlag:s.disablePush===!0?1:0,Title:s.title||"",Desc:s.description||"",Ext:s.extension||"",ApnsInfo:mR(s),AndroidInfo:pR(s)}:BR}function zm(s){const{From_AccountHeadurl:n,From_AccountNick:g,IsNeedReadReceipt:u,IsPeerRead:E,IsSyncMsg:m,MsgBody:D,MsgClientTime:M,MsgLifeTime:T,MsgRandom:P,MsgSeq:W,MsgTimeStamp:iA,SendMsgControl:EA,SupportMessageExtension:RA,TinyId:kA,MsgCheckResult:xA,CloudCustomData:LA,MsgVersion:SA,MsgFlagBits:OA,RevokerInfo:JA,InnerSdkCustomData:ae}=s;let re,{From_Account:_i,To_Account:Ti}=s;if(m===1){const Lt=Ti;Ti=_i,_i=Lt}if(JA){const{Reason:Lt,Revoker_Account:Ni,Revoker_FromUin:cs}=JA;re={reason:Lt,revoker:Ni,revokerFromUin:cs,userID:Ni}}return{from:_i,avatar:n,nick:g,needReadReceipt:u===1,isSyncMessage:m,clientTime:M,messageLifeTime:T,random:P,sequence:W,time:iA,messageControlInfo:{excludedFromLastMessage:EA?.NoLastMsg===1,excludedFromUnreadCount:EA?.NoUnread===1},isSupportExtension:RA,to:Ti,tinyID:kA,checkResult:xA,cloudCustomData:LA,revokerInfo:re,messageVersion:SA,messageFlagBits:OA,readReceiptSentByPeer:E,elements:RC(D),onlineOnlyFlag:T===0,quoteInfo:op(ae)}}function Zm(s){const{From_Account:n,MsgBody:g,MsgClientTime:u,MsgRandom:E,MsgSeq:m,MsgTimeStamp:D,To_Account:M,MsgVersion:T,CloudCustomData:P,MsgCheckResult:W}=s;return{from:n,clientTime:u,random:E,sequence:m,time:D,to:M,elements:RC(g),messageVersion:T,cloudCustomData:P,checkResult:W}}function VD(s){const{ClientSeq:n,From_Account:g,GroupInfo:u,MsgBody:E,MsgClientTime:m,MsgRandom:D,MsgSeq:M,MsgTimeStamp:T,SendMsgControl:P,SupportMessageExtension:W,TinyId:iA,CloudCustomData:EA,MsgVersion:RA,MsgCheckResult:kA,NeedReadReceipt:xA,IsPlaceMsg:LA,RevokerInfo:SA,GroupAtInfo:OA,OnlineOnlyFlag:JA,InnerSdkCustomData:ae}=s;let re,_i=Zu.MSG_PRIORITY_NORMAL;if(Object.keys(OD).includes(String(s.MsgPriority))&&(_i=OD[s.MsgPriority]),SA){const{Reason:Lt,Revoker_Account:Ni,Revoker_FromUin:cs}=SA;re={reason:Lt,revoker:Ni,revokerFromUin:cs,userID:Ni}}const Ti=function(Lt){const Ni=[];return Array.isArray(Lt)&&Lt.forEach(cs=>{cs.GroupAtAllFlag===PD?Ni.push(cs.GroupAt_Account):cs.GroupAtAllFlag===CR&&Ni.push(Lo.MSG_AT_ALL)}),Ni}(OA);return{clientSequence:n,from:g,groupProfile:u,clientTime:m,priority:_i,random:D,sequence:M,time:T,messageControlInfo:{excludedFromLastMessage:P?.NoLastMsg===1,excludedFromUnreadCount:P?.NoUnread===1},isSupportExtension:W,tinyID:iA,cloudCustomData:EA,messageVersion:RA,checkResult:kA,needReadReceipt:xA,isPlaceMessage:LA,revokerInfo:re,atUserList:Ti,elements:RC(E),to:JT(s),onlineOnlyFlag:JA===1,quoteInfo:op(ae)}}function JT(s){const{utils:{isEmpty:n},constants:{IS_TOPIC_MESSAGE:g}}=ye,{ToGroupId:u,GroupInfo:{MillionGroupFlag:E=0,TopicId:m}={}}=s;return E!==g||n(m)?u:m}function RC(s){if(!s)return null;if(Array.isArray(s))return s.map(g=>{const u=ye.message.messageFactory.getElementClass(g.MsgType);return u?.parseServerPushElement(g)});const n=ye.message.messageFactory.getElementClass(s.MsgType);return n?.parseServerPushElement(s)}function JD(s){const{From_Account:n,MsgBody:g,MsgClientTime:u,MsgRandom:E,MsgSeq:m,MsgTimeStamp:D,GroupId:M,TopicId:T,MsgVersion:P,CloudCustomData:W,MsgCheckResult:iA}=s;return{from:n,clientTime:u,random:E,sequence:m,time:D,groupID:M,topicID:T,elements:RC(g),messageVersion:P,cloudCustomData:W,checkResult:iA}}function op(s){const{utils:{isString:n,safeStringify:g},ssoLog:u}=ye;if(!n(s))return null;try{const{messageID:E,messageTime:m,messageSequence:D}=JSON.parse(s).businessQuote;return{msgID:E,messageTime:m,messageSequence:D}}catch(E){return u.debug("_parseServerQuoteInfo",g(E)),null}}function sp({conversationUpdateFields:s,message:n}){const{conversationID:g,conversationType:u,conversationSubType:E,flow:m,_isExcludedFromUnreadCount:D,_isExcludedFromLastMessage:M}=n,T=M?"":XQ(n),P=!D&&m===Xu.IN;s.has(g)?(s.get(g).lastMessage=T,P&&s.get(g).unreadCount++):s.set(g,{conversationID:g,type:u,subType:E,unreadCount:P?1:0,lastMessage:T})}function vB(s){return s.filter(n=>{const g=!Rs(n?._elements),u=n?.isPlaceMessage===1;return g||ye.ssoLog.error("emptyMessageBody",`from:${n.from} to:${n.to} sequence:${n.sequence}`),g&&!u})}function RB(s){const{messageDataHandler:n}=ye.message;return!n.isInMessageList(s)&&!n.isMessageSentByCurrentInstance(s)}var fR=Object.freeze({__proto__:null,autoIncrementIndex:au,createAndroidPushInfo:pR,createApnsPushInfo:mR,createOfflinePushInfo:YD,filterValidMessages:vB,getAndroidSoundName:ip,parseServerGroupMessage:VD,parseServerPushC2CModifyMessage:Zm,parseServerPushGroupModifyMessage:JD,parseServerPushMessage:zm,parseServerPushMessageElement:RC,shouldStoreMessage:RB,updateConversationFields:sp});const{isPlainObject:yR}=ye.utils;function np(s,n={}){const{onlineUserOnly:g,messageControlInfo:u}=n;let{offlinePushInfo:E}=n;s.conversationType===Kr.CONV_C2C&&g===!0&&(E?E.disablePush=!0:E={disablePush:!0});let m="";typeof s.cloudCustomData=="string"&&s.cloudCustomData.length>0&&(m=s.cloudCustomData);const D=[];if(u&&yR(u)){const{excludedFromUnreadCount:M,excludedFromLastMessage:T,excludedFromContentModeration:P}=u;M===!0&&D.push("NoUnread"),T===!0&&D.push("NoLastMsg"),P===!0&&D.push("NoMsgCheck")}return{onlineUserOnly:g,cloudCustomData:m,messageControlInfo:D,offlinePushInfo:E}}function HD(s){const{webhookInfo:{disableCloudMessagePreHook:n=!1,disableCloudMessagePostHook:g=!1}={}}=s||{};if(!n&&!g)return;const u=[];return n&&u.push("ForbidBeforeSendMsgCallback"),g&&u.push("ForbidAfterSendMsgCallback"),u}function wh(s,n){return pA(this,void 0,void 0,function*(){const g=s.conversationType===Kr.CONV_GROUP?function(E,m){var D;const M=np(E,m),{onlineUserOnly:T,cloudCustomData:P,messageControlInfo:W,offlinePushInfo:iA}=M,EA=JSON.parse(JSON.stringify(E.transformElementsToServerFormat()));let RA;return h(E._receiverList)&&E._receiverList.length>0&&(RA=E._receiverList,E._receiverList.length>50&&(RA=E._receiverList.slice(0,50),console.warn("ReceiverListLimit"))),{servcmd:"group_open_http_svc.send_group_msg",data:{From_Account:(D=ye.store.get("login"))===null||D===void 0?void 0:D.userId,GroupId:E.to,MsgBody:EA,CloudCustomData:P,Random:E.random,MsgPriority:E.priority,ClientSeq:E.clientSequence,GroupAtInfo:E._groupAtInfoList,OnlineOnlyFlag:T?1:0,MsgClientTime:E.clientTime,OfflinePushInfo:YD(iA),SendMsgControl:T?void 0:W,NeedReadReceipt:E.needReadReceipt===!0?1:0,To_Account:RA,SupportMessageExtension:E.isSupportExtension===!0?1:0,IsRelayMsg:E._relayFlag===!0?1:0,CustomModerationConfigID:E._cmConfigID,ForbidCallbackControl:HD(m),InnerSdkCustomData:_B(E)}}}(s,n):function(E,m){var D;const M=np(E,m),{onlineUserOnly:T,cloudCustomData:P,messageControlInfo:W,offlinePushInfo:iA}=M,EA=T===!0?0:void 0,RA=JSON.parse(JSON.stringify(E.transformElementsToServerFormat()));return{servcmd:"openim.sendmsg",data:{From_Account:(D=ye.store.get("login"))===null||D===void 0?void 0:D.userId,To_Account:E.to,MsgBody:RA,CloudCustomData:P,MsgSeq:E.sequence,MsgRandom:E.random,MsgLifeTime:EA,From_AccountNick:E.nick,From_AccountHeadurl:E.avatar,SendMsgControl:EA!==0?W:void 0,MsgClientTime:E.clientTime,IsNeedReadReceipt:E.needReadReceipt===!0?1:0,SupportMessageExtension:E.isSupportExtension===!0?1:0,IsRelayMsg:E._relayFlag===!0?1:0,CustomModerationConfigID:E._cmConfigID,OfflinePushInfo:YD(iA),ForbidCallbackControl:HD(m),InnerSdkCustomData:_B(E)}}}(s,n),u=yield gg(g);return u?{time:u.MsgTime,messageDropReason:u.MsgDropReason,sequence:u.MsgSeq}:null})}function _h(s){return pA(this,void 0,void 0,function*(){const{from:n,to:g,version:u=0,sequence:E,random:m,time:D,type:M,cloudCustomData:T}=s,P={From_Account:n,To_Account:g,MsgVersion:u,MsgSeq:E,MsgRandom:m,MsgTime:D,MsgType:M,MsgBody:s.transformElementsToServerFormat(),CloudCustomData:T},W=yield gg({servcmd:"openim.modify_c2c_msg",data:P});if(W){const{MsgBody:iA,MsgVersion:EA,CloudCustomData:RA}=W;return{elements:RC(iA),messageVersion:EA,cloudCustomData:RA}}})}function wB(s){return pA(this,void 0,void 0,function*(){const{to:n,version:g=0,sequence:u,cloudCustomData:E}=s,m={GroupId:n,MsgVersion:g,MsgSeq:u,MsgBody:s.transformElementsToServerFormat(),CloudCustomData:E},D=yield gg({servcmd:"openim.modify_group_msg",data:m});if(D){const{MsgBody:M,MsgVersion:T,CloudCustomData:P}=D;return{elements:RC(M),messageVersion:T,cloudCustomData:P}}})}function Th(s){return pA(this,void 0,void 0,function*(){const{groupID:n,count:g,messageSequence:u,messageSequenceList:E,getType:m}=s,D={GroupId:n,ReqMsgNumber:g,WithRecalledMsg:1,Version:1,GetType:m};return u&&(D.ReqMsgSeq=u),h(E)&&E.length>0&&(D.ReqMsgSeqList=E),yield gg({servcmd:"group_open_http_svc.group_msg_get",data:D})})}function Xm(s){return pA(this,void 0,void 0,function*(){const{peerAccount:n,count:g,lastMessageTime:u,messageKey:E,direction:m}=s;return gg({servcmd:"openim.getroammsg",data:{Peer_Account:n,MaxCnt:g,WithRecalledMsg:1,LastMsgTime:u,MsgKey:E,GetDirection:m}})})}function _B(s){if(ye.utils.isObject(s.quoteInfo)){const{msgID:n,messageSequence:g,messageTime:u}=s.quoteInfo;return JSON.stringify({businessQuote:{messageID:n,messageSequence:g,messageTime:u}})}}var qD=Object.freeze({__proto__:null,createMessagePackOptions:np,generateForbidCallbackControl:HD,getC2CRoamingMessagesByAnchor:Xm,getGroupRoamingMessagesByAnchor:Th,getRoamingMessages:function(s){return pA(this,void 0,void 0,function*(){const{peerAccount:n,count:g,lastMessageTime:u,messageKey:E}=s;return(yield gg({servcmd:"openim.getroammsg",data:{Peer_Account:n,MaxCnt:g||15,LastMsgTime:u||0,MsgKey:E,GetDirection:0,WithRecalledMsg:1}}))||[]})},modifyC2CMessage:_h,modifyGroupMessage:wB,sendMessage:wh});const{isPlainObject:HT}=ye.utils,{MSG_AUDIO:KD,MSG_FILE:jD,MSG_IMAGE:DR,MSG_VIDEO:SR,MSG_MERGER:MR}=Lo;class $m{constructor(){this._sendProtocolMap=new Map}init(){Cr.getInstance().registerApi({apiName:"sendMessage",context:this,matcher:n=>![KD,jD,DR,SR,MR].includes(n[0].type)})}registerSendProtocol(n,g,u){this._sendProtocolMap.set(n,g.bind(u))}sendMessage(n,g){return pA(this,void 0,void 0,function*(){const{TOTAL_COUNT:u,SEND_COST:E,SUCCESS_COUNT:m,FAILED_COUNT:D}=rr;if(!(n instanceof jE))throw new gs({code:da.MSG_INSTANCE_REQUIRED});const M=n.validateBeforeSend();if(!M.isValid){const{code:W,message:iA=""}=M.error||{};throw new gs({code:W,message:iA})}this._reportMessageSendQuality({name:u,message:n});let T=!1;const{messageDataHandler:P}=ye.message||{};try{const{messageControlInfo:W}=g||{};let iA=null;P.addRandomOfSentMessage(n.random);const EA=Date.now(),RA=this._getSendProtocol(n);if(n.conversationType===Kr.CONV_C2C?(T=g?.onlineUserOnly===!0,iA=yield RA(n,g)):n.conversationType===Kr.CONV_GROUP&&(yield this._validateBeforeSendGroupMessage(n),iA=yield RA(n,g)),iA){const{messageDropReason:kA,sequence:xA,time:LA}=iA;if(this._updateNickAndAvatarOfSentMessageByMe(n),kA&&this._logRateLimitInfo(n,xA,kA),this._reportMessageSendQuality({name:m,message:n}),this._reportMessageSendQuality({name:E,message:n,startTs:EA}),n.isResend===!0){const SA=P.findMessage(n.ID);SA&&(ye.ssoLog.debug("sendMessage",`sendMessage resend ok. ID:${SA.ID}`),P.deleteConversationMessage(SA))}return n.status=Yr.SUCCESS,n.time=LA,n.conversationType===Kr.CONV_GROUP&&(n.sequence=xA),T?n._onlineOnlyFlag=!0:(P.storeConversationMessage(n),this._applySentMessageControlInfo(n,W),this._emitOnlineMessageSent(n)),n.type===wg.MSG_STREAM?{code:0,data:{message:n,streamMessageID:iA.streamMessageID}}:{code:0,data:{message:n}}}}catch(W){n.status=Yr.FAIL,P.removeRandomOfSentMessage(n.random);let{errorCode:iA}=W||{},EA=W?.errorInfo||W?.message||"";throw this._hasRiskContent(iA)&&(n.hasRiskContent=!0),T||this._isRejectedByRestApi(iA)||P.storeConversationMessage(n),this._reportMessageSendQuality({name:D,message:n,error:W}),new gs({code:iA,message:EA,data:{message:n},moreMessage:`type:${n.type} from:${n.from} to:${n.to}`})}})}_hasRiskContent(n){return n===80001||n===80004}_isRejectedByRestApi(n){return n>=10100&&n<=10200||n>=120001&&n<=13e4}_emitOnlineMessageSent(n){const g=n._isExcludedFromLastMessage?"":n,{conversationID:u,conversationType:E}=n,m=zc(u)?so.TOPIC_NEW_MESSAGE:so.NEW_MESSAGE;ye.notificationCenter.emitInnerEvent(m,{result:{conversationUpdateFieldList:[{conversationID:u,type:E,message:n,lastMessage:g,unreadCount:0}]}})}_applySentMessageControlInfo(n,g){g&&HT(g)&&(g.excludedFromLastMessage===!0&&(n._isExcludedFromLastMessage=!0),g.excludedFromUnreadCount===!0&&(n._isExcludedFromUnreadCount=!0))}_logRateLimitInfo(n,g,u){const E=`from:${n.from} to:${n.to} sequence:${g} messageDropReason:${u}`;ye.ssoLog.warn("messageDropReason",E)}_updateNickAndAvatarOfSentMessageByMe(n){const{messageDataHandler:g}=ye.message||{};let u=!1;const{conversationID:E}=n,m=g.getLatestMsgSentByMe(E);if(m){const{nick:D,avatar:M}=m;D===n.nick&&M===n.avatar||(u=!0),u&&g.updateNickAndAvatarOfSentMessage({conversationID:E,latestNick:n.nick,latestAvatar:n.avatar,isSentByMe:!0})}}_validateBeforeSendGroupMessage(n){return pA(this,void 0,void 0,function*(){var g,u,E;const{to:m,from:D}=n;let M=m,T=Ap.getGroup(M);if(Xr({groupID:M})&&T?.isSupportTopic)throw new gs({code:da.MSG_SEND_GRP_WITH_TOPIC_FAIL});if(zc(m)&&([M]=m.split(sa.TOPIC),T=Ap.getGroup(M)),!T&&typeof((g=Cr.getInstance().getApiMap())===null||g===void 0?void 0:g.getGroupProfile)=="function"){const P=yield Cr.getInstance().getApiMap().getGroupProfile({groupID:M});if(((E=(u=P?.data)===null||u===void 0?void 0:u.group)===null||E===void 0?void 0:E.type)===Lo.GRP_AVCHATROOM){const W=rs({code:da.MSG_SEND_FAIL_NOT_IN_AV,replacement1:D,replacement2:M});throw new gs({code:da.MSG_SEND_FAIL_NOT_IN_AV,message:W})}}return!0})}_reportMessageSendQuality(n){ye.notificationCenter.emitInnerEvent(so.QUALITY_STAT,{label:cI.MESSAGE_SEND_SUCCESS_RATE,data:n})}_getSendProtocol(n){return this._sendProtocolMap.get(n.type)||wh}}var qT=new class{constructor(){this._sparseMessagesByConversation=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new Set}init(){ye.notificationCenter.subscribeInnerEvent(so.LOGOUT,this._reset,this),ye.notificationCenter.subscribeInnerEvent(so.DESTROY,this._dispose,this)}get _messagesByConversation(){return ep.getMessages()}storeConversationMessage(s,n=!1){if(an)return!0;const{conversationID:g}=s;if(!g||(this._messagesByConversation.has(g)||this._messagesByConversation.set(g,new Map),this._shouldSkipStoreMessage(s,n)))return!1;const u=this._getUniqueIdOfMessage(s);return this._messagesByConversation.get(g).set(u,s),this._updateLatestMessageMap(s),!0}_updateLatestMessageMap(s){const{conversationID:n}=s;s.flow==="out"?this._setLatestMsgSentByMe(n,s):n.startsWith("C2C")&&this._setLatestMsgSentByPeer(n,s)}_shouldSkipStoreMessage(s,n){const g=this._getUniqueIdOfMessage(s),u=this._messagesByConversation.get(s.conversationID);if(u?.has(g)){const E=u?.get(g);if(!n||E?.isModified===!0)return!0}return!1}deleteConversationMessage(s){var n;const{conversationID:g=""}=s,u=this._getUniqueIdOfMessage(s);this._messagesByConversation.has(g)&&((n=this._messagesByConversation.get(g))===null||n===void 0||n.delete(u))}modifyConversationMessage(s,n){var g;if(!this._messagesByConversation.has(s)&&!this._sparseMessagesByConversation.has(s))return{isUpdated:!1,message:null};const u=this._getUniqueIdOfMessage(n),E=this._getMessageFromLocalMessage(s,u);if(E){const{messageVersion:m,elements:D,cloudCustomData:M,checkResult:T=0}=n,P=T>1;if(ye.ssoLog.debug("modifyConversationMessage",`conversationToMessageMap modifyConversationMessage localVersion:${E.version} remoteVersion:${m}`),E.versionE.ID===s)||null,n)break;if(!n){const u=Array.from(this._sparseMessagesByConversation.values());for(const E of u)if(n=E.get(s)||null,n)break}return n}deleteConversationMessageList(s){this._messagesByConversation.has(s)&&(this._messagesByConversation.delete(s),this._latestMessageSentByMeMap.delete(s),this._latestMessageSentByPeerMap.delete(s)),this._sparseMessagesByConversation.has(s)&&this._sparseMessagesByConversation.delete(s)}revokeMessage({conversationID:s,sequence:n,random:g,revoker:u}){const E=this._messagesByConversation.get(s);let m=null;if(E){const D=Array.from(E.values());if(m=this._findMessageBySequenceAndRandom({messageList:D,random:g,sequence:n}),m){const M=this._getUniqueIdOfMessage(m);return ep.updateMessage(s,[M],{isRevoked:!0,revoker:u,operation:yc.revoke}),m}}if(this._sparseMessagesByConversation.has(s)){const D=Array.from(this._sparseMessagesByConversation.get(s).values());if(m=this._findMessageBySequenceAndRandom({messageList:D,random:g,sequence:n}),m)return m.isRevoked=!0,m.revoker=u,m}}_findMessageBySequenceAndRandom({messageList:s,sequence:n,random:g}){for(let u=0;u0){const D=new Map([...E,...m.entries()]);this._messagesByConversation.set(g,D),this._updateLatestMessageSentByMe(g),this._updateLatestMessageSentByPeer(g)}return u}storeSparseMessageList(s){if(s.length===0)return;const{conversationID:n}=s[0],g=s.length;this._sparseMessagesByConversation.has(n)||this._sparseMessagesByConversation.set(n,new Map);const u=this._sparseMessagesByConversation.get(n);for(let E=0;E=0;u--)if(g[u].flow==="out"){this._setLatestMsgSentByMe(s,g[u]);break}}}_updateLatestMessageSentByPeer(s){var n;const g=Array.from(((n=this._messagesByConversation.get(s))===null||n===void 0?void 0:n.values())||[]);if(g.length!==0&&s.startsWith("C2C")){for(let u=g.length-1;u>=0;u--)if(g[u].flow==="in"){this._setLatestMsgSentByPeer(s,g[u]);break}}}_getUniqueIdOfMessage(s){const{from:n,to:g,random:u,sequence:E,time:m}=s;return`${n}-${g}-${u}-${E}-${m}`}_setLatestMsgSentByPeer(s,n){this._latestMessageSentByPeerMap.set(s,n)}_setLatestMsgSentByMe(s,n){this._latestMessageSentByMeMap.set(s,n)}getLatestMsgSentByPeer(s){return this._latestMessageSentByPeerMap.get(s)}getLatestMsgSentByMe(s){return this._latestMessageSentByMeMap.get(s)}addRandomOfSentMessage(s){this._randomOfSentMessageList.add(s)}removeRandomOfSentMessage(s){this._randomOfSentMessageList.delete(s)}updateNickAndAvatarOfSentMessage(s){const{conversationID:n="",latestAvatar:g,latestNick:u,isSentByMe:E=!0}=s,m=this._messagesByConversation.get(n);if(!m)return;const D=Array.from(m.values()),M=E?"out":"in";D.forEach(T=>{const{nick:P,avatar:W,flow:iA}=T;iA===M&&(P!==u&&(T.nick=u),W!==g&&(T.avatar=g))})}isInMessageList(s){var n;const{conversationID:g}=s;if(!g||!this._messagesByConversation.has(g))return!1;const u=this._getUniqueIdOfMessage(s);return(n=this._messagesByConversation.get(g))===null||n===void 0?void 0:n.has(u)}isMessageSentByCurrentInstance(s){const{random:n}=s;return this._randomOfSentMessageList.has(n)}getContinuousMessagesByConversation(){return this._messagesByConversation}getLocalMessageList(s){const n=this._messagesByConversation.get(s);return n?[...n.values()]:[]}getSparseMessageList(s){const n=this._sparseMessagesByConversation.get(s);return n?[...n.values()]:[]}_reset(){this._messagesByConversation.clear(),this._latestMessageSentByPeerMap.clear(),this._latestMessageSentByMeMap.clear(),this._randomOfSentMessageList.clear()}_dispose(){this._reset(),ye.notificationCenter.unSubscribeInnerEvent(so.LOGOUT,this._reset,this),ye.notificationCenter.unSubscribeInnerEvent(so.DESTROY,this._dispose,this)}};function Af(s,n){const g=MB.getConversation(s);if(g?.lastMessage){const{lastMessage:u}=g,{lastTime:E,lastSequence:m,version:D}=u,{time:M,sequence:T,messageVersion:P,elements:W,cloudCustomData:iA}=n;E===M&&m===T&&D!==P&&(u.type=W[0].type,u.payload=W[0].content,u.messageForShow=Zc(u.type,u.payload),u.cloudCustomData=iA,u.version=P,MB.updateConversation(s,{lastMessage:u}))}}class vR{init(){Cr.getInstance().registerApi({apiName:"modifyMessage",context:this})}modifyMessage(n){return pA(this,void 0,void 0,function*(){const{to:g,payload:u,sequence:E,conversationType:m,random:D,time:M,from:T,type:P}=n;if(this._canModifyMessageElement(P)){const W=n?._elements||[];W.length>=1&&(W[0].type=P,W[0].content=u)}try{let W=null,iA=null;if(m===Kr.CONV_C2C?W=yield _h(n):m===Kr.CONV_GROUP&&(W=yield wB(n)),W){let EA=`${m}${g}`;return g===Ar()&&m===Kr.CONV_C2C&&(EA=`${m}${T}`),iA={conversationType:m,from:T,to:g,time:M,random:D,sequence:E,elements:W?.elements,cloudCustomData:W?.cloudCustomData,messageVersion:W?.messageVersion,conversationID:EA},this._handleModifyMessageSuccess(iA),{code:0,data:{message:n},successLog:{message:`to:${g}`}}}}catch(W){const{errorCode:iA}=W||{};throw new gs({functionName:"modifyMessage",code:iA,moreMessage:`to:${g}`})}})}_handleModifyMessageSuccess(n){const{conversationID:g}=n,{isUpdated:u,message:E}=ye.message.messageDataHandler.modifyConversationMessage(g,n);u===!0&&ye.notificationCenter.emitOuterEvent(Dr.MESSAGE_MODIFIED,{name:Dr.MESSAGE_MODIFIED,data:[E]}),ye.notificationCenter.emitInnerEvent(so.MESSAGE_MODIFIED,{conversationID:g,message:E}),Af(g,n)}_canModifyMessageElement(n){return[KE.MSG_TEXT,KE.MSG_CUSTOM,KE.MSG_LOCATION,KE.MSG_FACE].includes(n)}}class Nh{init(){const{notificationCenter:n}=ye,{InnerEventSubType:g}=n;ws.getInstance().registerWorkflowStep(Yt.RECEIVE_C2C_NEW_MESSAGE,qt.HANDLE_C2C_NEW_MESSAGE,this._handleC2CMessagePush,this),ws.getInstance().registerWorkflowStep(Yt.RECEIVE_C2C_NEW_MESSAGE,qt.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterReceiveNewMessage,this),ws.getInstance().registerWorkflowStep(Yt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,qt.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterSyncUnreadMessage,this),n.subscribeInnerEvent(so.MESSAGE_PUSH,g.C2C_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),n.subscribeInnerEvent(so.MESSAGE_PUSH,g.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),n.subscribeInnerEvent(so.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(n){ws.getInstance().executeWorkflow(Yt.RECEIVE_C2C_NEW_MESSAGE,n)}_handleC2CMessagePush(n){const g=n.data||{},{messageDataHandler:u}=ye.message||{},E=[],m=new Map;return g.C2cMsgArray.forEach(D=>{const M=this._generateC2CMessage(D);this._updateMessageProfile(M);let T=M.isModified===1;u.isMessageSentByCurrentInstance(M)?M.isModified=T:T=!1,M._onlineOnlyFlag?u.isMessageSentByCurrentInstance(M)||E.push(M):RB(M)&&(u.storeConversationMessage(M)&&sp({conversationUpdateFields:m,message:M}),u.isMessageSentByCurrentInstance(M)&&!T||E.push(M))}),{conversationUpdateFieldList:[...m.values()],messages:E}}_emitMessageEventsAfterReceiveNewMessage(n){var g;const{messages:u=[]}=((g=n.result)===null||g===void 0?void 0:g[qt.HANDLE_C2C_NEW_MESSAGE])||{};this._emitMessageEvents(u)}_emitMessageEventsAfterSyncUnreadMessage(n){var g;const{messages:u=[]}=((g=n.result)===null||g===void 0?void 0:g[qt.UNREAD_MESSAGE_SYNC])||{};this._emitMessageEvents(u)}_emitMessageEvents(n){const g=n?.filter(E=>E?.isModified===!0)||[];g.length>0&&ye.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:g});const u=n?.filter(E=>!E?.isModified);u.length>0&&ye.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:u})}_generateC2CMessage(n){const g=Kr.CONV_C2C,u=zm(n),E=ye.message.messageFactory.createMessage(Object.assign(Object.assign({},u),{conversationType:g,flow:Xu.IN})),{elements:m}=u;return E.setElement(m),E}_updateMessageProfile(n){var g;const{messageDataHandler:u}=ye.message||{},E=(g=ye.store.get("login"))===null||g===void 0?void 0:g.userId,{from:m,nick:D,avatar:M,conversationID:T=""}=n;if(m!==E){const P=u.getLatestMsgSentByPeer(T);if(P){const{nick:W,avatar:iA}=P;r(D)||r(M)?(n.nick=l(W)?W:n.nick,n.avatar=l(iA)?iA:n.avatar):D===W&&M===iA||(u.updateNickAndAvatarOfSentMessage({conversationID:T,latestNick:D,latestAvatar:M,isSentByMe:!1}),this._updateConversationUserProfile({conversationID:T,nick:D,avatar:M}))}}else{const P=u.getLatestMsgSentByMe(T);!P||D===P.nick&&M===P.avatar||u.updateNickAndAvatarOfSentMessage({conversationID:T,latestNick:D,latestAvatar:M,isSentByMe:!0})}}_updateConversationUserProfile(n){const{conversationID:g,nick:u,avatar:E}=n,m=MB.getConversation(g),{userProfile:D={}}=m||{};D.avatar===E&&D.nick===u||MB.updateConversation(g,{userProfile:Object.assign(Object.assign({},D),{nick:u,avatar:E})})}_updateMessageListDueToModify(n){const{conversationID:g}=n,{isUpdated:u,message:E}=ye.message.messageDataHandler.modifyConversationMessage(g,n);u===!0&&ye.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[E]}),ye.notificationCenter.emitInnerEvent("ModifyMessageSuccess",n),Af(g,n)}_handleC2CMessageModify(n){n.C2cMsgModNotifys.forEach(g=>{var u;const E=Kr.CONV_C2C;let m=Zm(g);const{to:D,from:M}=m;let T=`${E}${D}`;D===((u=ye.store.get("login"))===null||u===void 0?void 0:u.userId)&&(T=`${E}${M}`),m=Object.assign({conversationType:E,conversationID:T},m),this._updateMessageListDueToModify(m)})}_dispose(){const{notificationCenter:n}=ye,{InnerEventSubType:g}=n;ye.notificationCenter.unSubscribeInnerEvent(so.MESSAGE_PUSH,g.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),ye.notificationCenter.unSubscribeInnerEvent(so.MESSAGE_PUSH,g.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),ye.notificationCenter.unSubscribeInnerEvent(so.DESTROY,this._dispose,this)}}class Gh{init(){const{notificationCenter:n}=ye,{InnerEventSubType:g}=n;ws.getInstance().registerWorkflowStep(Yt.RECEIVE_GROUP_NEW_MESSAGE,qt.HANDLE_GROUP_NEW_MESSAGE,this._handleGroupMessagePush,this),ws.getInstance().registerWorkflowStep(Yt.RECEIVE_GROUP_NEW_MESSAGE,qt.EMIT_GROUP_MESSAGE_EVENT,this._emitMessageEvents,this),n.subscribeInnerEvent(so.MESSAGE_PUSH,g.GROUP_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),n.subscribeInnerEvent(so.MESSAGE_PUSH,g.GROUP_MESSAGE_MODIFIED,this._handleGroupMessageModify,this),n.subscribeInnerEvent(so.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(n){this._canExecuteReceiverNewMessageWorkFlow(n)&&ws.getInstance().executeWorkflow(Yt.RECEIVE_GROUP_NEW_MESSAGE,n)}_handleGroupMessagePush(n){const g=n.data||{},{messageDataHandler:u}=ye.message,E=[],m=new Map,D=g?.GroupMsgArray;return D?.forEach(M=>{if(M.GroupInfo.NotVisible===1)return;const T=this._generateGroupMessage(M);this.updateMessageProfile(T);let P=T.isModified===1;u.isMessageSentByCurrentInstance(T)?T.isModified=P:P=!1,T._onlineOnlyFlag?u.isMessageSentByCurrentInstance(T)||E.push(T):RB(T)&&u.storeConversationMessage(T)&&(E.push(T),sp({conversationUpdateFields:m,message:T}))}),{conversationUpdateFieldList:[...m.values()],messages:E}}_emitMessageEvents(n){var g;const{messages:u}=((g=n.result)===null||g===void 0?void 0:g[qt.HANDLE_GROUP_NEW_MESSAGE])||{},E=u?.filter(D=>D?.isModified===!0)||[];E.length>0&&ye.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:E});const m=u?.filter(D=>!D?.isModified)||[];m.length>0&&ye.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:m})}_generateGroupMessage(n){const g=Kr.CONV_GROUP,u=VD(n),E=ye.message.messageFactory.createMessage(Object.assign(Object.assign({},u),{conversationType:g,flow:Xu.IN})),{elements:m}=u;return E.setElement(m),E}updateMessageProfile(n){var g;const{messageDataHandler:u}=ye.message||{},E=(g=ye.store.get("login"))===null||g===void 0?void 0:g.userId,{from:m,nick:D,avatar:M,conversationID:T="",_elements:P}=n;if(m===E){const W=u.getLatestMsgSentByMe(T);!W||D===W.nick&&M===W.avatar||u.updateNickAndAvatarOfSentMessage({conversationID:T,latestNick:D,latestAvatar:M,isSentByMe:!0})}else if(m===Lo.CONV_SYSTEM){const{operationType:W,memberInfoList:iA,operatorInfo:EA}=P;let RA={};if(Rs(iA)?Rs(EA)||(RA=EA):[Tg.JOINED,Tg.KICKED,Tg.ADMIN_SET,Tg.ADMIN_CANCELED].includes(W)&&(RA=Object.assign({},iA[0])),!Rs(RA)){const{nick:kA="",avatar:xA=""}=RA;n.nick=kA,n.avatar=xA}}}_updateMessageListDueToModify(n){const{conversationID:g}=n,{isUpdated:u,message:E}=ye.message.messageDataHandler.modifyConversationMessage(g,n);u===!0&&ye.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[E]}),Af(g,n)}_handleGroupMessageModify(n){n.GroupMsgModNotifys.forEach(g=>{const u=Kr.CONV_GROUP;let E=JD(g);const{topicID:m,groupID:D}=E,M=m||D,T=`${u}${M}`;E=Object.assign({conversationType:u,conversationID:T,to:M},E),this._updateMessageListDueToModify(E)})}_dispose(){const{notificationCenter:n}=ye,{InnerEventSubType:{GROUP_REALTIME_MESSAGE:g,GROUP_MESSAGE_MODIFIED:u}}=n;n.unSubscribeInnerEvent(so.MESSAGE_PUSH,g,this._handleGroupMessagePush,this),n.unSubscribeInnerEvent(so.MESSAGE_PUSH,u,this._handleGroupMessageModify,this),n.unSubscribeInnerEvent(so.DESTROY,this._dispose,this)}_canExecuteReceiverNewMessageWorkFlow(n){var g,u;const{GroupId:E,GroupType:m}=((u=(g=n?.GroupMsgArray)===null||g===void 0?void 0:g[0])===null||u===void 0?void 0:u.GroupInfo)||{},D=m===La.GRP_AVCHATROOM;return!(!Ap.getGroup(E)&&D)}}var WD=new class{constructor(){this.c2cMessageReceiver=new Nh,this.groupMessageReceiver=new Gh}init(){this.c2cMessageReceiver.init(),this.groupMessageReceiver.init()}};const RR={createCustomMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1},cloudCustomData:{required:!1,rules:["string"],allowEmpty:!1},priority:{required:!1,rules:["string"],allowEmpty:!1},customModerationConfigurationID:{required:!1,rules:["string"],allowEmpty:!1}},sendMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"options",required:!1,rules:["object"],allowEmpty:!1}],createTextMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!(!s.startsWith("C2C")&&!s.startsWith("GROUP"))||"conversationType is invalid."},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>function(n){var g;return typeof n?.text!="string"||typeof n.text=="string"&&((g=n?.text)===null||g===void 0?void 0:g.length)===0?"payload.text must be a string":!0}(s)}}},KT={createCustomMessage:!0,sendMessage:!0,modifyMessage:!0};var jT=new class{constructor(){this._historyMessageListFetchAnchors=new Map,this.completedHistoryConversations=new Set}getGroupRoamingMessagesByAnchor(s){return pA(this,void 0,void 0,function*(){try{const{conversationID:n,count:g,direction:u,sequence:E,messageSequenceList:m,shouldMarkCompleted:D=!1,getType:M}=s,T=n.replace(ka.CONV_GROUP,""),P=[];let W=E;if(u===Kc.BACKWARD){if(typeof E!="number")return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};W=E+g-1}const iA=yield Th({groupID:T,count:g,messageSequence:W,messageSequenceList:m,getType:M});if(iA){const{RspMsgList:EA=[],NextReqMsgSeq:RA=0,IsFinished:kA,InvisibleMsgSeq:xA}=iA,LA=`groupID:${T} sequence:${E} reqSeq:${W} direction:${u} complete:${kA} nextSequence:${RA} remoteMsgCount:${EA.length} invisibleSequenceList:${xA}`,SA=[];for(let ae=0;ae=E),OA&&D&&this.completedHistoryConversations.add(n);const JA=vB(SA);return ye.ssoLog.info("getGroupRoamingMessagesByAnchor",LA),{messageList:JA,invisibleSequenceList:xA,nextReqMessageIDFromServer:RA,hasNoMoreHistoryMessage:OA,serverGroupTipList:P}}}catch(n){const{errorCode:g,errorInfo:u}=n||{};throw new gs({code:g,message:u})}})}clearHistoryMessageListFetchAnchors(s){this._historyMessageListFetchAnchors.delete(s)}isHistoryMessageFetchCompleted(s){return this.completedHistoryConversations.has(s)}_parseMessage(s){var n;const g=ka.CONV_GROUP;s.Event===4&&(s.MsgBody.MsgType=Lo.MSG_GRP_TIP);const u=VD(s),E=Wm.createMessage(Object.assign(Object.assign({},u),{conversationType:g,flow:"in"}));return SB(((n=u.elements)===null||n===void 0?void 0:n.content)||{},E),E.setElement(u.elements),E}getC2CRoamingMessagesByAnchor(s){return pA(this,void 0,void 0,function*(){var n;try{const{conversationID:g,count:u,messageID:E,time:m,direction:D,shouldMarkCompleted:M=!1}=s;let T=m,P="";if(!m){const EA=E?ye.message.messageDataHandler.findMessage(E):null;if(T=EA?.time||0,E&&this._historyMessageListFetchAnchors.has(g)){const RA=this._historyMessageListFetchAnchors.get(g);T=RA.lastMessageTime,P=RA.messageKey}}const W=g.replace(ka.CONV_C2C,""),iA=yield Xm({count:u,lastMessageTime:T,messageKey:P,peerAccount:W,direction:D});if(iA){const{MsgList:EA=[],Complete:RA,MsgKey:kA,LastMsgTime:xA}=iA;this._historyMessageListFetchAnchors.set(g,{messageKey:kA,lastMessageTime:xA});const LA=[];for(let ae=0;ae{const{tag:E,value:m}=u;E&&E.indexOf(ZD)>-1?g.profileCustomField.push({key:E,value:m}):bd.has(E)&&(g[bd.get(E)]=m)}),Object.assign(Object.assign({},ef),g)}parseProfileItem(s=[]){const n=[];return s.forEach(g=>{n.push({tag:g.Tag,value:g.Value})}),n}parseProfileList(s=[]){const n=[];return s.forEach(g=>{n.push({tag:g.Tag,value:g.ValueBytes})}),n}convertParamsToProfile(s){const n=[];return Object.keys(s).forEach(g=>{g!==XD&&n.push({tag:xl[g.toUpperCase()],value:s[g]})}),s.profileCustomField&&h(s.profileCustomField)&&s.profileCustomField.forEach(g=>{n.push({tag:g.key,value:g.value})}),n}normalizeProfileFields(s){const n={},g=[];return s.forEach(u=>{const{tag:E,value:m}=u;if(E&&E.indexOf(ZD)>-1&&g.push({key:E,value:m}),bd.has(E)&&m!==void 0){const D=bd.get(E);n[D]=m}}),g.length>0&&(n.profileCustomField=g),n}};const{generateProtocolData:_R}=ye.common;function TR(s){return pA(this,void 0,void 0,function*(){const n="profile.portrait_get_all",g={From_Account:Ar(),UserItem:[]};s.forEach(D=>{g.UserItem.push({CustomSequence:0,StandardSequence:0,To_Account:D})});const u=_R({servcmd:n,data:g}),E=`${u.head.seq}${n}`,m=yield ye.channel.sendPacket(u,{requestId:E});if(m)return function(D){const{ActionStatus:M,ErrorCode:T,ErrorDisplay:P,ErrorInfo:W,UserProfileItem:iA}=D,EA=[];return iA.map(RA=>{const{To_Account:kA,CustomSequence:xA,ResultCode:LA,ResultInfo:SA,StandardSequence:OA,ProfileItem:JA}=RA,ae=$u.parseProfileItem(JA);EA.push({userId:kA,customSequence:xA,resultCode:LA,resultInfo:SA,standardSequence:OA,profileItem:ae})}),{actionStatus:M,errorCode:T,errorDisplay:P,errorInfo:W,userProfile:EA}}(m)})}function WE(s){return rc.getFriendMap().has(s)}const{isEmpty:$D}=ye.utils;class tf{constructor(){this._strangerProfileMap=new Map}init(){Cr.getInstance().registerApi({apiName:"getMyProfile",context:this}),Cr.getInstance().registerApi({apiName:"getUserProfile",context:this}),Cr.getInstance().registerApi({apiName:"updateMyProfile",context:this}),this.createProfile=$u.createProfile.bind($u);const{notificationCenter:n}=ye;ws.getInstance().registerWorkflowStep(Yt.SYNC_SERVER_INFO_AFTER_LOGIN,qt.USER_PROFILE_SYNC,this.getMyProfileCacheThenServer,this),n.subscribeInnerEvent(so.MESSAGE_PUSH,n.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),n.subscribeInnerEvent(so.LOGOUT,this._reset,this),n.subscribeInnerEvent(so.DESTROY,this._dispose,this)}getMyProfile(){return pA(this,void 0,void 0,function*(){try{const n=Ar(),g=yield TR([n]);if(g){const u=this._handleProfileFormResponse(g)[0];return rc.getUserProfileMap().set(n,u),{code:0,data:u}}}catch(n){const{errorCode:g,errorInfo:u}=n;throw new gs({functionName:"getMyProfile",code:g,message:u})}})}getUserProfile(n){return pA(this,void 0,void 0,function*(){try{let{userIDList:g}=n;const{userIdListToRequest:u,profileFromCache:E}=this._filterRequestAndCacheUsers(g);if(u.length===0)return{code:0,data:E,successLog:{message:`userIDList.length:${g.length}`}};u.length>wR&&(ye.ssoLog.warn("getUserProfile","userIdListToRequest.length > 1000"),u.length=wR);const{data:m,error:D}=yield this._batchFetchUserProfiles(u),M=u.length,T=m.length,P=M-T;if(E.length===0&&M===P&&!$D(D))throw D;if(h(m))return m.forEach(iA=>{WE(iA.userID)?rc.getUserProfileMap().set(iA.userID,iA):this._strangerProfileMap.set(iA.userID,iA)}),{code:0,data:m.concat(E),successLog:{message:`getUserProfile query:${M} success:${T} fail:${P} from cache:${E.length}`}}}catch(g){throw new gs(g)}})}getMyProfileCacheThenServer(){return pA(this,void 0,void 0,function*(){const n=Ar(),g=rc.getUserProfileMap().has(n);return g?{code:0,data:g}:this.getMyProfile()})}updateMyProfile(n){return pA(this,void 0,void 0,function*(){const g=Ar(),u={};for(const m in n)n[m]!==void 0&&(u[m]=n[m]);const E=$u.convertParamsToProfile(u);try{yield function(P){return pA(this,void 0,void 0,function*(){const W="profile.portrait_set",iA=_R({servcmd:W,data:P}),EA=`${iA.head.seq}${W}`,RA=yield ye.channel.sendPacket(iA,{requestId:EA});if(RA){const{ActionStatus:kA,ErrorCode:xA,ErrorDisplay:LA,ErrorInfo:SA}=RA;return{actionStatus:kA,errorCode:xA,errorDisplay:LA,errorInfo:SA}}})}({From_Account:g,ProfileItem:E});const D=rc.getUserProfile(g);let M;M=D?Object.assign(Object.assign({},D),u):$u.createProfile(g,E);const T=!rg(D,M,["lastUpdatedTime"]);return M.lastUpdatedTime=Date.now(),rc.getUserProfileMap().set(g,M),T&&this._emitProfileUpdated(M),{code:0,data:M,successLog:{message:`profileArray: ${ye.utils.safeStringify(E)}`}}}catch(m){const{errorCode:D,errorInfo:M}=m;throw new gs({functionName:"updateMyProfile",code:D,message:M,moreMessage:`params: ${ye.utils.safeStringify(n)}`})}})}updateMyNickAndAvatar(n){return pA(this,void 0,void 0,function*(){const g=Ar(),u=Date.now(),E=rc.getUserProfile(g);let m={};m=E?Object.assign(E,n):$u.createProfile(g,n),m.lastUpdatedTime=u,rc.getUserProfileMap().set(g,m)})}_onProfileDataModify(n){const g=function(m){const{Profile_Account:D,PushType:M,ProfileList:T}=m;return{userId:D,pushType:M,profileList:$u.parseProfileList(T)}}(n.ProfileDataMod[0]);if($D(g))return;const{isProfileUpdated:u,profile:E}=this._handleProfileModified(g);u&&this._emitProfileUpdated(E)}_emitProfileUpdated(n){ye.notificationCenter.emitInnerEvent(so.PROFILE_UPDATE,{name:so.PROFILE_UPDATE,data:[n]}),ye.notificationCenter.emitOuterEvent(Dr.PROFILE_UPDATED,{name:Dr.PROFILE_UPDATED,data:[n]}),MB.updateConversation(`C2C${n?.userID}`,{userProfile:n})}_dispose(){const{notificationCenter:n}=ye;n.unSubscribeInnerEvent(so.LOGOUT,this._reset,this),n.unSubscribeInnerEvent(so.MESSAGE_PUSH,n.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),n.unSubscribeInnerEvent(so.DESTROY,this._dispose,this),this._reset()}_handleProfileModified(n){const{userId:g,profileList:u}=n,E=rc.getUserProfile(g);if(!(Ar()===g||WE(g)&&E))return{isProfileUpdated:!1,profile:null};const m=$u.normalizeProfileFields(u),D=Object.keys(m).some(W=>W===XD?this._isCustomFieldChanged(E.profileCustomField,m.profileCustomField):E[W]!==m[W]);if(!D)return{isProfileUpdated:!1,profile:E};const M=Date.now(),T=Object.prototype.hasOwnProperty.call(m,XD)?this._mergeProfileCustomField(E.profileCustomField,m.profileCustomField):E.profileCustomField,P=Object.assign(Object.assign(Object.assign({},E),m),{profileCustomField:T,lastUpdatedTime:M});return rc.getUserProfileMap().set(g,P),{isProfileUpdated:D,profile:P}}_filterRequestAndCacheUsers(n){const g=[],u=[];return n.forEach(E=>{const m=rc.getUserProfileMap().has(E);WE(E)&&m?u.push(rc.getUserProfile(E)):this._isStrangerAndProfileValid(E)?u.push(this._strangerProfileMap.get(E)):g.push(E)}),{userIdListToRequest:g,profileFromCache:u}}_handleProfileFormResponse(n){const{userProfile:g}=n;if(!Array.isArray(g))return[];const u=g.filter(m=>m.userId!=="@TLS#NOT_FOUND"&&m.userId!==""&&!$D(m.profileItem)),E=Date.now();return u.map(m=>{const D=$u.createProfile(m.userId,m.profileItem);return D.lastUpdatedTime=E,D})}_isStrangerAndProfileValid(n){var g;if(!WE(n)){const{lastUpdatedTime:u=0}=this._strangerProfileMap.get(n)||{},E=((g=ye.store.get("cloudConfig"))===null||g===void 0?void 0:g.stranger_profile_expiration_time)||6e5;return Date.now()-u<=E}return!1}_chunkUserIDList(n,g){return Array.from({length:Math.ceil(n.length/g)},(u,E)=>n.slice(E*g,(E+1)*g))}_batchFetchUserProfiles(n){return pA(this,void 0,void 0,function*(){const g=[],u=[];let E={};return this._chunkUserIDList(n,100).forEach(m=>{g.push(TR(m))}),(yield Promise.allSettled(g)).forEach(m=>{if(m.status==="fulfilled"){const D=m.value,M=this._handleProfileFormResponse(D);h(M)&&u.push(...M)}else if(m.status==="rejected"){const{code:D,message:M}=m.reason||{};E={errorCode:D,message:M}}}),{data:u,error:E}})}_isCustomFieldChanged(n=[],g=[]){if(!h(g)||g.length===0)return!1;if(!h(n)||n.length===0)return!0;const u=new Map(n.map(E=>[E.key,E.value]));return g.some(E=>u.get(E.key)!==E.value)}_mergeProfileCustomField(n=[],g=[]){const u=h(n)?n.map(E=>Object.assign({},E)):[];return h(g)&&g.length!==0&&g.forEach(({key:E,value:m})=>{const D=u.find(M=>M.key===E);D?D.value=m:u.push({key:E,value:m})}),u}_reset(){rc.getUserProfileMap().clear(),this._strangerProfileMap.clear()}}const of=new Map,AS=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let s=0,n=AS.length;s>(-2*m&6)):0)E="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(E);try{return decodeURIComponent(escape(g))}catch(u){return console.warn(u),""}}const{isEmpty:zT}=ye.utils,{generateProtocolData:sf}=ye.common;function NR(s){return pA(this,void 0,void 0,function*(){const n="im_open_status.ws_get_user_status",g=sf({servcmd:n,data:{To_Account:s}}),u=`${g.head.seq}${n}`,E=yield ye.channel.sendPacket(g,{requestId:u});if(E)return function(m){const{ErrorCode:D,ErrorInfo:M,ErrorList:T=[],UserStatusList:P=[]}=m,W=P.map(EA=>{const{To_Account:RA,Status:kA,CustomStatus:xA,Detail:LA=[]}=EA;return{userID:RA,statusType:kA,customStatus:rp(xA),onlineDevices:ZT(LA)}}),iA=T.map(EA=>{const{To_Account:RA,Invalid_Account:kA,ErrorCode:xA,ErrorInfo:LA}=EA;return{userID:zT(kA)?RA:kA,code:xA,message:LA}});return{errorCode:D,errorInfo:M,successUserList:W,failureUserList:iA}}(E)})}function ZT(s){const n=[];return s?.forEach(g=>{const{Platform:u,Status:E}=g;E==="Online"&&n.push(u)}),n}class XT{constructor(){this._customStatus=""}init(){const{notificationCenter:n}=ye;Cr.getInstance().registerApi({apiName:"getUserStatus",context:this}),Cr.getInstance().registerApi({apiName:"setSelfStatus",context:this}),Cr.getInstance().registerApi({apiName:"subscribeUserStatus",context:this}),Cr.getInstance().registerApi({apiName:"unsubscribeUserStatus",context:this}),ws.getInstance().registerWorkflowStep(Yt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,qt.USER_STATUS_UPDATE,this._onReOnline,this),n.subscribeInnerEvent(so.MESSAGE_PUSH,n.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),n.subscribeInnerEvent(so.LOGOUT,this._reset,this),n.subscribeInnerEvent(so.DESTROY,this._dispose,this)}setSelfStatus(n){return pA(this,void 0,void 0,function*(){const g=Ar(),{customStatus:u}=n;try{return yield function(E){return pA(this,void 0,void 0,function*(){const m="im_open_status.ws_set_custom_status",D=sf({servcmd:m,data:{CustomStatus:E}}),M=`${D.head.seq}${m}`,T=yield ye.channel.sendPacket(D,{requestId:M});if(T){const{ErrorCode:P,ErrorInfo:W}=T;return{errorCode:P,errorInfo:W}}})}(u),this._customStatus=u,{code:0,data:{userID:g,statusType:bh,customStatus:u},successLog:{message:`customStatus: ${u}`}}}catch(E){const{errorCode:m,errorInfo:D}=E;throw new gs({functionName:"setSelfStatus",code:m,message:D})}})}getUserStatus(n){return pA(this,void 0,void 0,function*(){const{userIDList:g=[]}=n;if(this._isOnlyMeInArray(g))return this._getMyStatus();const u=yield this._getUserStatus(g);return Object.assign(Object.assign({},u),{successLog:{message:`userIDList length: ${g.length}`}})})}setCustomStatus(n){const g=rp(n);this._customStatus=g}subscribeUserStatus(n){return pA(this,void 0,void 0,function*(){try{const{userIDList:g=[]}=n;this._checkBusinessCapabilityBits("subscribeUserStatus");const u=this._getMaxUserCount("subscribe"),E=this._sliceUserIDList(g,u),m=yield function(M){return pA(this,void 0,void 0,function*(){const{channel:T}=ye,P="im_open_status.ws_status_subscribe",W=sf({servcmd:P,data:{To_Account:M}}),iA=`${W.head.seq}${P}`;return yield T.sendPacket(W,{requestId:iA})})}(E),D=this._parseResponse(m);return{code:0,data:{failureUserList:D},successLog:{message:`userID length:${g.length} failCount: ${D.length}`}}}catch(g){const{errorCode:u}=g;throw new gs({functionName:"subscribeUserStatus",code:u})}})}unsubscribeUserStatus(n){return pA(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("unsubscribeUserStatus");const{userIDList:g=[]}=n,u=this._getMaxUserCount("unsubscribe"),E=this._sliceUserIDList(g,u),m=yield function(M){return pA(this,void 0,void 0,function*(){const{channel:T}=ye,P="im_open_status.ws_status_unsubscribe";let W={};W=M.length===0?{UnsubscribeAll:1}:{To_Account:M};const iA=sf({servcmd:P,data:W}),EA=`${iA.head.seq}${P}`;return yield T.sendPacket(iA,{requestId:EA})})}(E),D=this._parseResponse(m);return{code:0,data:{failureUserList:D},successLog:{message:`userID length:${g.length} failCount: ${D.length}`}}}catch(g){const{errorCode:u}=g;throw new gs({functionName:"unsubscribeUserStatus",code:u})}})}_onUserStatusUpdate(n){const{UserStatusList:g=[]}=n||{},u=g.map(E=>{const{To_Account:m,Status:D,CustomStatus:M,Platform:T}=E,P={userID:m,statusType:D,customStatus:rp(M)};return T&&(P.onlineDevices=T),P});this._emitUserStatusUpdatedEvent(u)}_onReOnline(n){const g=rp(n.data.customStatus);if(this._customStatus===g)return;this._customStatus=g;const u={userID:Ar(),statusType:bh,customStatus:g};this._emitUserStatusUpdatedEvent(u)}_emitUserStatusUpdatedEvent(n){ye.notificationCenter.emitOuterEvent(Dr.USER_STATUS_UPDATED,{name:Dr.USER_STATUS_UPDATED,data:n})}_sliceUserIDList(n,g){return n.slice(0,g)}_parseResponse(n){const{ErrorList:g=[]}=n;return g.map(u=>{const{To_Account:E,Invalid_Account:m,ErrorCode:D,ErrorInfo:M}=u;return{userID:ye.utils.isEmpty(m)?E:m,code:D,message:M}})}_checkBusinessCapabilityBits(n){if(!ye.store.get("commercialConfig").get(WT))throw new gs({functionName:n,code:da.NO_USE,replacement1:n})}_getMaxUserCount(n){const g=ye.store.get("cloudConfig")||{},u={query:{key:"status_query_count",default:500},subscribe:{key:"status_sub_count",default:100},unsubscribe:{key:"status_unsub_count",default:100}},{key:E,default:m}=u[n],D=g[E]||m;return parseInt(D,10)}_getMyStatus(){return{code:0,data:{successUserList:[{userID:Ar(),statusType:bh,customStatus:this._customStatus}],failureUserList:[]}}}_getUserStatus(n){return pA(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("getUserStatus");const g=this._getMaxUserCount("query"),u=this._sliceUserIDList(n,g),E=yield NR(u),{successUserList:m,failureUserList:D}=E||{};return{code:0,data:{successUserList:m,failureUserList:D}}}catch(g){const{errorCode:u}=g;throw new gs({functionName:"getUserStatus",code:u})}})}_isOnlyMeInArray(n){const g=Ar();return n.length===1&&n.indexOf(g)>-1}_dispose(){const{notificationCenter:n}=ye;n.unSubscribeInnerEvent(so.MESSAGE_PUSH,n.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),n.unSubscribeInnerEvent(so.DESTROY,this._dispose,this),n.unSubscribeInnerEvent(so.LOGOUT,this._reset,this),this._reset()}_reset(){this._customStatus=""}}const eS={getUserProfile:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},updateMyProfile:{nick:{required:!1,rules:["string"],allowEmpty:!0},avatar:{required:!1,rules:["string"],allowEmpty:!0},gender:{required:!1,rules:["string"],allowEmpty:!0},selfSignature:{required:!1,rules:["string"],allowEmpty:!0},allowType:{required:!1,rules:["string"],allowEmpty:!0},birthday:{required:!1,rules:["number"],allowEmpty:!1},language:{required:!1,rules:["string"],allowEmpty:!0},messageSettings:{required:!1,rules:["string"],allowEmpty:!0},adminForbidType:{required:!1,rules:["string"],allowEmpty:!0},level:{required:!1,rules:["number"],allowEmpty:!1},role:{required:!1,rules:["number"],allowEmpty:!0},profileCustomField:{required:!1,rules:["array"],allowEmpty:!0,customValidator:function(s){for(const n of s){if(typeof n!="object")return"Each item in profileCustomField must be an object";if(typeof n?.key!="string")return"Each item.key in profileCustomField must be a string";if(!n?.key.startsWith(ZD))return'Each item.key in profileCustomField must start with "Tag_Profile_Custom"'}return!0}}},setSelfStatus:{customStatus:{required:!0,rules:["string"],allowEmpty:!0}},getUserStatus:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},subscribeUserStatus:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},unsubscribeUserStatus:{userIDList:{required:!1,rules:["array"],allowEmpty:!0}}},$T={getMyProfile:!0,getUserProfile:!0,updateMyProfile:!0,setSelfStatus:!0,getUserStatus:!0,subscribeUserStatus:!0,unsubscribeUserStatus:!0};class AN{constructor(){this.userProfile=new tf,this.userStatus=new XT,this.userProfile.init(),this.userStatus.init(),Wc({auth:$T,params:eS})}}function tS(s){const n=[];if(!l(s))return n;const g=s.length;if(g===0)return n;for(let u=g-1;u>=0;u--)s[u]==="1"&&n.push(2**(g-u-1));return n}var kd,wC,Ld;(function(s){s.NOT_START="notStart",s.PENDING="pending",s.RESOLVED="resolved",s.REJECTED="rejected"})(kd||(kd={})),function(s){s[s.C2C=1]="C2C",s[s.GROUP=2]="GROUP"}(wC||(wC={})),function(s){s[s.C2C=8]="C2C",s[s.GROUP=2]="GROUP"}(Ld||(Ld={}));class iS{constructor(){this._name="SyncConversationHandler",this._pagingStatus=kd.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}init(){const{notificationCenter:n}=ye;ws.getInstance().registerWorkflowStep(Yt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,qt.CONVERSATION_RECOVER,this._syncConversationList,this),ws.getInstance().registerWorkflowStep(Yt.SYNC_SERVER_INFO_AFTER_LOGIN,qt.CONVERSATION_LIST_SYNC,this._syncConversationListAfterLogin,this),n.subscribeInnerEvent(so.LOGOUT,this._reset,this),n.subscribeInnerEvent(so.DESTROY,this._dispose,this),ye.ssoLog.debug(`${this._name}.init`)}isSyncCompleted(){return this._pagingStatus===kd.RESOLVED}_syncConversationListAfterLogin(){return pA(this,void 0,void 0,function*(){return this._pagingStatus=kd.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0,this._syncConversationList()})}_syncConversationList(){return pA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g}}=ye;n.debug("_syncConversationList","start");try{const u=yield this._pagingGetConversationList(!0);this._pagingStatus=kd.RESOLVED;const{conversationList:E=[]}=u||{};return n.info("_syncConversationList",`success count:${E.length}`),u}catch(u){const E=new gs(u);n.error("_syncConversationList",`fail ${g(u)}`,{error:E})}})}_pagingGetConversationList(n){return pA(this,void 0,void 0,function*(){try{const g=[];this._pagingStatus=kd.PENDING;const u=yield function(iA){return pA(this,void 0,void 0,function*(){const{fromAccount:EA,pagingTimeStamp:RA,pagingStartIndex:kA,pagingPinnedTimeStamp:xA,pagingPinnedStartIndex:LA}=iA;return gg({servcmd:"recentcontact.page_get",data:{AssistFlags:31,MsgAssistFlags:15,OrderType:1,From_Account:EA,StartIndex:kA,TimeStamp:RA,TopStartIndex:LA,TopTimeStamp:xA}})})}({fromAccount:Ar(),pagingTimeStamp:n?this._pagingTimeStamp:0,pagingStartIndex:n?this._pagingStartIndex:0,pagingPinnedTimeStamp:n?this._pagingPinnedTimeStamp:0,pagingPinnedStartIndex:n?this._pagingPinnedStartIndex:0}),{CompleteFlag:E,SessionItem:m=[],TimeStamp:D,StartIndex:M,TopTimeStamp:T,TopStartIndex:P}=u||{};let W=[];if(E===1&&(this._pagingStatus=kd.RESOLVED),m.length>0&&(W=this._getConversationOptions(m),g.push(...W)),ye.notificationCenter.emitInnerEvent(so.SYNC_CONVERSATION_LIST,{conversationUpdateFieldList:W}),this._pagingTimeStamp=D,this._pagingStartIndex=M,this._pagingPinnedTimeStamp=T,this._pagingPinnedStartIndex=P,E!==1){const{conversationList:iA}=yield this._pagingGetConversationList(n);g.push(...iA)}return{conversationList:g}}catch(g){throw g}})}_getConversationOptions(n){const{utils:{isUndefined:g}}=ye,u=this._convertConversationKey(n);return this._filterValidConversations(u).map(E=>(g(E.lastMsg)&&(E.lastMsg={elements:[]}),E.type===wC.C2C?this._assembleC2COption(E):this._assembleGroupOption(E)))}_filterValidConversations(n){return n.filter(({type:g,userID:u})=>g===wC.C2C&&!function(E){let m;return E.startsWith(Lo.CONV_C2C)&&(m=E.replace(Lo.CONV_C2C,"")),m==="@TLS#ERROR"||m==="@TLS#NOT_FOUND"}(u)||g===2)}_assembleC2COption(n){var g,u,E,m,D,M,T,P;const W=this._createUserprofile(n);return{conversationID:`${Lo.CONV_C2C}${n.userID}`,type:Lo.CONV_C2C,lastMessage:{lastTime:n.time,lastSequence:n.sequence,fromAccount:n.lastC2CMsgFromAccount,type:!((g=n.lastMsg)===null||g===void 0)&&g.elements[0]?(u=n.lastMsg)===null||u===void 0?void 0:u.elements[0].type:null,payload:!((E=n.lastMsg)===null||E===void 0)&&E.elements[0]?this._amendLayersOverLimitProp(n.lastMsg.elements[0].content):null,cloudCustomData:((M=(D=(m=n.lastMsg)===null||m===void 0?void 0:m.elements)===null||D===void 0?void 0:D[0])===null||M===void 0?void 0:M.cloudCustomData)||"",isRevoked:n.lastMessageFlag===Ld.C2C,onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:this._computeIsPeerRead(n),revoker:((P=(T=n.lastMsg)===null||T===void 0?void 0:T.revokerInfo)===null||P===void 0?void 0:P.revoker)||null},unreadCount:0,userProfile:W,peerReadTime:n.peerReadTime,isPinned:n.isPinned===1,customData:n.customMark||"",markList:tS(n.standardMark),conversationGroupList:[],remark:n.friendRemark||"",messageRemindType:this._transMsgRemindType(n.messageRemindType)}}_createUserprofile(n){var g;const{userID:u,nick:E,peerAvatar:m}=n,D=[{tag:"Tag_Profile_IM_Nick",value:E},{tag:"Tag_Profile_IM_Image",value:m}];return(g=ye.user.userProfile)===null||g===void 0?void 0:g.createProfile(u,D)}_computeIsPeerRead(n){const g=Ar(),{lastC2CMsgFromAccount:u,time:E,c2cPeerReadTime:m}=n;return u===g&&E<=m}_assembleGroupOption(n){var g,u,E,m,D;return{conversationID:`${Lo.CONV_GROUP}${n.groupID}`,type:Lo.CONV_GROUP,lastMessage:Object.assign(Object.assign({lastTime:n.time,lastSequence:n.sequence,fromAccount:n.msgGroupFromAccount},this._patchTypeAndPayload(n)),{cloudCustomData:((E=(u=(g=n.lastMsg)===null||g===void 0?void 0:g.elements)===null||u===void 0?void 0:u[0])===null||E===void 0?void 0:E.cloudCustomData)||"",isRevoked:n.lastMessageFlag===Ld.GROUP,onlineOnlyFlag:!1,nick:n.msgGroupFromNickName||"",nameCard:n.msgGroupFromCardName||"",revoker:((D=(m=n.lastMsg)===null||m===void 0?void 0:m.revokerInfo)===null||D===void 0?void 0:D.revoker)||null}),groupProfile:{groupID:n.groupID,name:n.groupNick,avatar:n.groupImage,type:n.groupType,nextMessageSeq:n.nextMessageSeq},unreadCount:this._computeGroupUnreadCount(n),peerReadTime:0,isPinned:n.isPinned===1,version:0,customData:n.customMark||"",markList:tS(n.standardMark),conversationGroupList:[],messageRemindType:this._transMsgRemindType(n.messageRemindType),subType:n.groupType}}_convertConversationKey(n){return n.map(g=>({type:g.Type,userID:g.To_Account,nick:g.C2cNick,peerAvatar:g.C2cImage,time:g.MsgTimeStamp,sequence:g.MsgSeq,lastC2CMsgFromAccount:g.LastC2cMsgFrom_Account,lastMsg:this._convertLastMsgKey(g.LastMsg),lastMessageFlag:g.LastMsgFlags,c2cPeerReadTime:g.C2cPeerReadTime,peerReadTime:g.C2cPeerReadTime,friendRemark:g.C2cRemark,isPinned:g.TopFlags,standardMark:g.StandardMark,customMark:g.CustomMark,messageRemindType:g.MsgRecvOption,groupID:g.ToAccount,groupNick:g.GroupNick,groupImage:g.GroupImage,groupType:g.GroupType,nextMessageSeq:g.GroupNextMsgSeq,msgGroupFromAccount:g.MsgGroupFrom_Account,msgGroupFromNickName:g.MsgGroupFromNickName,msgGroupFromCardName:g.MsgGroupFromCardName,unreadCount:g.UnreadMsgCount,noUnreadCount:g.GroupIgnoredUnreadSeqCount}))}_convertLastMsgKey(n){var g,u,E;const{utils:{isEmpty:m}}=ye;if(m(n))return null;let D="",M=null;if(!m(n.GroupTips)){const{From_Account:T,GroupName:P}=((g=n.GroupTips)===null||g===void 0?void 0:g.GroupInfo)||{};D=Lo.MSG_GRP_TIP,M=Object.assign(Object.assign({},this._parseContent(D,n.GroupTips.MsgBody)),{groupProfile:{from:T,groupName:P}})}return n.MsgBody&&(D=(u=n.MsgBody[0])===null||u===void 0?void 0:u.MsgType,M=this._parseContent(D,n.MsgBody[0])),{event:n.Event,elements:[{type:D,content:M,cloudCustomData:n.CloudCustomData}],revokerInfo:{revoker:(E=n.RevokerInfo)===null||E===void 0?void 0:E.Revoker_Account}}}_parseContent(n,g){var u;if(!g)return g;const E=ye.message.messageFactory.getElementClass(n);return E?(u=E.parseServerPushElement(g))===null||u===void 0?void 0:u.content:g}_amendLayersOverLimitProp(n){const{LayersOverLimit:g}=n;return Do(n,["LayersOverLimit"]).layersOverLimit=g===1,n}_transMsgRemindType(n){let g="";return n===0?g=Lo.MSG_REMIND_ACPT_AND_NOTE:n===1?g=Lo.MSG_REMIND_DISCARD:n===2?g=Lo.MSG_REMIND_ACPT_NOT_NOTE:n===3&&(g=Lo.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),g}_patchTypeAndPayload(n){var g;const{utils:{isUndefined:u}}=ye,{event:E,elements:m=[]}=n.lastMsg||{};return u(E)?{type:m[0]?m[0].type:null,payload:m[0]?this._amendLayersOverLimitProp(m[0].content):null}:{type:Lo.MSG_GRP_TIP,payload:((g=m?.[0])===null||g===void 0?void 0:g.content)||{}}}_computeGroupUnreadCount(n){const{unreadCount:g=0,noUnreadCount:u=0}=n,E=g-u;return E>0?E:0}_reset(){this._pagingStatus=kd.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}_dispose(){this._reset();const{notificationCenter:n}=ye;n.unSubscribeInnerEvent(so.LOGOUT,this._reset,this),n.unSubscribeInnerEvent(so.DESTROY,this._dispose,this)}}class oS{constructor(){this.syncConversationHandler=new iS,this.syncConversationHandler.init()}}console.log(`TencentCloudLiteChat.VERSION:${Zr}`);var sS={create:function(s){var n,g;const{SDKAppID:u,testEnv:E=!1,devMode:m=!1,unlimitedAVChatRoom:D=!1,scene:M="",oversea:T=!1,instance:P,disableIndependentDomain:W=!1,proxyServer:iA=""}=s;let EA=u;if(!function(kA){if(typeof kA=="number")return!0;const xA=Number(kA);return!Number.isNaN(xA)}(EA))return console.error("Create SDK instance failed. Failed to parse the SDKAppID, please check the arguments"),null;if(EA=Number(EA),Ca.has(EA))return Ca.get(EA);let RA=null;if(P)RA=P,RA._workflowManager&&ws.setInstance(RA._workflowManager),RA._pluginManager&&RA._pluginManager.installBuiltInPlugin(DB),P.isReady()&&((g=(n=ws.getInstance()).executeWorkflow)===null||g===void 0||g.call(n,Yt.SYNC_SERVER_INFO_AFTER_LOGIN));else{const kA=function(){function ae(){return(65536*(1+Math.random())|0).toString(16).substring(1)}return`${ae()+ae()}${ae()}${ae()}${ae()}${ae()}${ae()}${ae()}`}();ye.init({sdkAppId:EA,instanceId:kA,testEnv:E,devMode:m,unlimitedAVChatRoom:D,disableIndependentDomain:W,scene:M,oversea:T,sdkEdition:jm,version:Zr,proxyServer:iA}),ws.getInstance().init(),ye.message=new zD,ye.user=new AN,ye.login=new Rh,ye.conversation=new oS,ru.getInstance().installBuiltInPlugin(DB),RA=Cr.getInstance().exposeApiForClient(),RA._workflowManager=ws.getInstance(),RA._pluginManager=ru.getInstance();const{utils:{IS_WORKER_AVAILABLE:xA,USER_AGENT:LA,getPlatformType:SA,isIOSWebView:OA}}=ye,JA=`instanceID:${kA} SDKAppID:${u} platform:${HA} host:${SA()} isIOSWebView:${OA} workerAvailable:${xA} UserAgent:${LA}`;ye.ssoLog.info("sdkConstruct",JA)}return Ca.set(EA,RA),RA},TSignaling:qc,EVENT:Dr,VERSION:Zr,TYPES:Lo};return sS})}(j1)),j1.exports}var xoA=PoA();const ig=QW(xoA);var W1={exports:{}},YoA=W1.exports,i8;function VoA(){return i8||(i8=1,function(t,i){(function(r,l){t.exports=l()})(YoA,function(){function r(ge,XA){if(!(ge instanceof XA))throw new TypeError("Cannot call a class as a function")}function l(ge,XA){for(var _e=0;_e"u"&&typeof uni.requireNativePlugin=="function",WA=TA&&uni.getDeviceInfo().platform.toLocaleLowerCase()==="ios",Ee=(TA&&uni.getDeviceInfo().platform.toLocaleLowerCase(),IA||nA||mA||lA||cA||TA),de=U!==void 0&&(U.nativeModuleProxy!==void 0||U.ReactNative!==void 0),Pe=nA?qq:mA?tt:lA?swan:cA?my:IA?wx:TA?uni:{},pe=function(ge){if(b(ge)!=="object"||ge===null)return!1;var XA=Object.getPrototypeOf(ge);if(XA===null)return!0;for(var _e=XA;Object.getPrototypeOf(_e)!==null;)_e=Object.getPrototypeOf(_e);return XA===_e};function gt(ge){if(ge==null)return!0;if(typeof ge=="boolean")return!1;if(typeof ge=="number")return ge===0;if(typeof ge=="string"||typeof ge=="function"||Array.isArray(ge))return ge.length===0;if(ge instanceof Error)return ge.message==="";if(pe(ge)){for(var XA in ge)if(Object.prototype.hasOwnProperty.call(ge,XA))return!1;return!0}return!1}var pt=function(){return I(function ge(){r(this,ge),this._n="WebRequest"},[{key:"request",value:function(ge,XA){var _e=this,je="".concat(this._n,".request"),Ut=ge.downloadUrl||"",gi=(ge.method||"PUT").toUpperCase(),Fi=ge.url;if(console.log("%c tim-upload-plugin %c","background:#0abf5b; padding:1px; border-radius:3px; color: #fff","background:transparent","".concat(je," URL:").concat(Fi)),ge.qs){var To=function(ki){var ns=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"&",jo=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"=";return gt(ki)?"":pe(ki)?Object.keys(ki).map(function($i){var Wt=encodeURIComponent($i)+jo;return Array.isArray(ki[$i])?ki[$i].map(function(io){return Wt+encodeURIComponent(io)}).join(ns):Wt+encodeURIComponent(ki[$i])}).filter(Boolean).join(ns):void 0}(ge.qs);To&&(Fi+="".concat(Fi.indexOf("?")===-1?"?":"&").concat(To))}var to=new XMLHttpRequest;to.open(gi,Fi,!0),to.responseType=ge.dataType||"text";var Eo=ge.headers||{};if(ge.uploadByIP&&(Eo=w(w({},Eo),{},{host:ge.uploadIP})),!gt(Eo))for(var Vs in Eo)Eo.hasOwnProperty(Vs)&&Vs.toLowerCase()!=="content-length"&&Vs.toLowerCase()!=="user-agent"&&Vs.toLowerCase()!=="origin"&&Vs.toLowerCase()!=="host"&&to.setRequestHeader(Vs,Eo[Vs]);return to.onload=function(){if(to.status===200)XA(null,_e._xhrRes(to,_e._xhrBody(to,Ut,ge.uploadByIP&&ge.uploadIP),Eo));else{if(ge.uploadIP&&ge.url.indexOf(ge.uploadIP)===-1)return ge.url=function(ns,jo){return ns.replace(/^http(s)?:\/\/(.*?)\//,"https://".concat(jo,"/"))}(ge.url,ge.uploadIP),ge.uploadByIP=!0,_e.request(ge,XA);var ki={code:to.status,message:JSON.stringify(to.responseText)};XA(ki,_e._xhrRes(to,_e._xhrBody(to,Ut,ge.uploadByIP&&ge.uploadIP),Eo))}},to.onerror=function(ki){var ns=_e._xhrBody(to,Ut,ge.uploadByIP&&ge.uploadIP),jo={code:to.status,message:JSON.stringify(to.responseText)};ns||to.statusText||to.status!==0||(ki.message="CORS blocked or network error"),XA(jo,_e._xhrRes(to,ns)),jo=null},ge.onProgress&&to.upload&&(to.upload.onprogress=function(ki){var ns=ki.total,jo=ki.loaded,$i=Math.floor(100*jo/ns);ge.onProgress({total:ns,loaded:jo,percent:($i>=100?100:$i)/100})}),to.send(ge.resources),to}},{key:"_xhrRes",value:function(ge,XA){var _e={};return ge.getAllResponseHeaders().trim().split(`
+`).forEach(function(je){if(je){var Ut=je.indexOf(":"),gi=je.substr(0,Ut).trim().toLowerCase(),Fi=je.substr(Ut+1).trim();_e[gi]=Fi}}),{statusCode:ge.status,statusMessage:ge.statusText,headers:_e,data:XA}}},{key:"_xhrBody",value:function(ge,XA,_e){return ge.status===200&&XA?{location:XA,uploadIP:_e}:{response:ge.responseText,uploadIP:_e}}}])}(),We=["unknown","image","video","audio","log"],Dt=["name"],Kt=function(){return I(function ge(){r(this,ge)},[{key:"request",value:function(ge,XA){var _e=this,je=ge.resources,Ut=je===void 0?"":je,gi=ge.headers,Fi=gi===void 0?{}:gi,To=ge.url,to=ge.downloadUrl,Eo=to===void 0?"":to,Vs=To,ki=null,ns=Eo.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/),jo=decodeURIComponent(ns[3]),$i=jo.indexOf("?")>-1?jo.split("?")[0]:jo,Wt={key:ge.fileKey?ge.fileKey:$i,success_action_status:200,"Content-Type":""},io={};if(WA){var bi=To.split("?sign=");if(bi.length>1){var vs=bi[1];Vs="".concat(bi[0],"?sign=").concat(encodeURIComponent("".concat(vs))),io.sign=decodeURIComponent(vs),io.signature=decodeURIComponent(vs)}}var HA={url:Vs,header:Fi,name:"file",filePath:Ut,formData:w(w({},Wt),io),timeout:ge.timeout||3e5};if(cA){var le=HA;le.name,HA=w(w({},function(Ve,Ft){if(Ve==null)return{};var nt,It,Ai=function(ke,Ze){if(ke==null)return{};var vt={};for(var _t in ke)if({}.hasOwnProperty.call(ke,_t)){if(Ze.includes(_t))continue;vt[_t]=ke[_t]}return vt}(Ve,Ft);if(Object.getOwnPropertySymbols){var ei=Object.getOwnPropertySymbols(Ve);for(It=0;It=3e4&&(this.systemClockOffset=To-Fi,XA=!0)}else Math.floor(ge.statusCode/100)===5&&(XA=!0)}return XA}}],[{key:"getVersion",value:function(){return"1.4.3"}}])}()})}(W1)),W1.exports}var JoA=VoA();const HoA=QW(JoA);/**
* @vue/shared v3.5.13
* (c) 2018-present Yuxi (Evan) You and Vue contributors
* @license MIT
-**//*! #__NO_SIDE_EFFECTS__ */function QW(t){const i=Object.create(null);for(const r of t.split(","))i[r]=1;return r=>r in i}const ya={},x_=[],vQ=()=>{},VoA=()=>!1,ZY=t=>t.charCodeAt(0)===111&&t.charCodeAt(1)===110&&(t.charCodeAt(2)>122||t.charCodeAt(2)<97),pW=t=>t.startsWith("onUpdate:"),oI=Object.assign,mW=(t,i)=>{const r=t.indexOf(i);r>-1&&t.splice(r,1)},JoA=Object.prototype.hasOwnProperty,Wr=(t,i)=>JoA.call(t,i),Ms=Array.isArray,Y_=t=>XY(t)==="[object Map]",I6=t=>XY(t)==="[object Set]",$s=t=>typeof t=="function",fg=t=>typeof t=="string",dm=t=>typeof t=="symbol",Na=t=>t!==null&&typeof t=="object",u6=t=>(Na(t)||$s(t))&&$s(t.then)&&$s(t.catch),E6=Object.prototype.toString,XY=t=>E6.call(t),HoA=t=>XY(t).slice(8,-1),d6=t=>XY(t)==="[object Object]",fW=t=>fg(t)&&t!=="NaN"&&t[0]!=="-"&&""+parseInt(t,10)===t,HL=QW(",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"),$Y=t=>{const i=Object.create(null);return r=>i[r]||(i[r]=t(r))},qoA=/-(\w)/g,oh=$Y(t=>t.replace(qoA,(i,r)=>r?r.toUpperCase():"")),KoA=/\B([A-Z])/g,tD=$Y(t=>t.replace(KoA,"-$1").toLowerCase()),AV=$Y(t=>t.charAt(0).toUpperCase()+t.slice(1)),mj=$Y(t=>t?`on${AV(t)}`:""),Hy=(t,i)=>!Object.is(t,i),Z1=(t,...i)=>{for(let r=0;r{Object.defineProperty(t,i,{configurable:!0,enumerable:!1,writable:l,value:r})},h3=t=>{const i=parseFloat(t);return isNaN(i)?t:i},joA=t=>{const i=fg(t)?Number(t):NaN;return isNaN(i)?t:i};let i8;const eV=()=>i8||(i8=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{});function Br(t){if(Ms(t)){const i={};for(let r=0;r{if(r){const l=r.split(zoA);l.length>1&&(i[l[0].trim()]=l[1].trim())}}),i}function Zi(t){let i="";if(fg(t))i=t;else if(Ms(t))for(let r=0;r!!(t&&t.__v_isRef===!0),hi=t=>fg(t)?t:t==null?"":Ms(t)||Na(t)&&(t.toString===E6||!$s(t.toString))?B6(t)?hi(t.value):JSON.stringify(t,Q6,2):String(t),Q6=(t,i)=>B6(i)?Q6(t,i.value):Y_(i)?{[`Map(${i.size})`]:[...i.entries()].reduce((r,[l,I],h)=>(r[fj(l,h)+" =>"]=I,r),{})}:I6(i)?{[`Set(${i.size})`]:[...i.values()].map(r=>fj(r))}:dm(i)?fj(i):Na(i)&&!Ms(i)&&!d6(i)?String(i):i,fj=(t,i="")=>{var r;return dm(t)?`Symbol(${(r=t.description)!=null?r:i})`:t};/**
+**//*! #__NO_SIDE_EFFECTS__ */function pW(t){const i=Object.create(null);for(const r of t.split(","))i[r]=1;return r=>r in i}const Da={},Y_=[],RQ=()=>{},qoA=()=>!1,ZY=t=>t.charCodeAt(0)===111&&t.charCodeAt(1)===110&&(t.charCodeAt(2)>122||t.charCodeAt(2)<97),mW=t=>t.startsWith("onUpdate:"),sI=Object.assign,fW=(t,i)=>{const r=t.indexOf(i);r>-1&&t.splice(r,1)},KoA=Object.prototype.hasOwnProperty,Wr=(t,i)=>KoA.call(t,i),Ms=Array.isArray,V_=t=>XY(t)==="[object Map]",u6=t=>XY(t)==="[object Set]",$s=t=>typeof t=="function",fg=t=>typeof t=="string",Cm=t=>typeof t=="symbol",Na=t=>t!==null&&typeof t=="object",E6=t=>(Na(t)||$s(t))&&$s(t.then)&&$s(t.catch),d6=Object.prototype.toString,XY=t=>d6.call(t),joA=t=>XY(t).slice(8,-1),C6=t=>XY(t)==="[object Object]",yW=t=>fg(t)&&t!=="NaN"&&t[0]!=="-"&&""+parseInt(t,10)===t,HL=pW(",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"),$Y=t=>{const i=Object.create(null);return r=>i[r]||(i[r]=t(r))},WoA=/-(\w)/g,sh=$Y(t=>t.replace(WoA,(i,r)=>r?r.toUpperCase():"")),zoA=/\B([A-Z])/g,nD=$Y(t=>t.replace(zoA,"-$1").toLowerCase()),AV=$Y(t=>t.charAt(0).toUpperCase()+t.slice(1)),fj=$Y(t=>t?`on${AV(t)}`:""),jy=(t,i)=>!Object.is(t,i),z1=(t,...i)=>{for(let r=0;r{Object.defineProperty(t,i,{configurable:!0,enumerable:!1,writable:l,value:r})},B3=t=>{const i=parseFloat(t);return isNaN(i)?t:i},ZoA=t=>{const i=fg(t)?Number(t):NaN;return isNaN(i)?t:i};let o8;const eV=()=>o8||(o8=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{});function Br(t){if(Ms(t)){const i={};for(let r=0;r{if(r){const l=r.split($oA);l.length>1&&(i[l[0].trim()]=l[1].trim())}}),i}function qi(t){let i="";if(fg(t))i=t;else if(Ms(t))for(let r=0;r!!(t&&t.__v_isRef===!0),ni=t=>fg(t)?t:t==null?"":Ms(t)||Na(t)&&(t.toString===d6||!$s(t.toString))?Q6(t)?ni(t.value):JSON.stringify(t,p6,2):String(t),p6=(t,i)=>Q6(i)?p6(t,i.value):V_(i)?{[`Map(${i.size})`]:[...i.entries()].reduce((r,[l,I],h)=>(r[yj(l,h)+" =>"]=I,r),{})}:u6(i)?{[`Set(${i.size})`]:[...i.values()].map(r=>yj(r))}:Cm(i)?yj(i):Na(i)&&!Ms(i)&&!C6(i)?String(i):i,yj=(t,i="")=>{var r;return Cm(t)?`Symbol(${(r=t.description)!=null?r:i})`:t};/**
* @vue/reactivity v3.5.13
* (c) 2018-present Yuxi (Evan) You and Vue contributors
* @license MIT
-**/let tC;class tsA{constructor(i=!1){this.detached=i,this._active=!0,this.effects=[],this.cleanups=[],this._isPaused=!1,this.parent=tC,!i&&tC&&(this.index=(tC.scopes||(tC.scopes=[])).push(this)-1)}get active(){return this._active}pause(){if(this._active){this._isPaused=!0;let i,r;if(this.scopes)for(i=0,r=this.scopes.length;i0)return;if(KL){let i=KL;for(KL=void 0;i;){const r=i.next;i.next=void 0,i.flags&=-9,i=r}}let t;for(;qL;){let i=qL;for(qL=void 0;i;){const r=i.next;if(i.next=void 0,i.flags&=-9,i.flags&1)try{i.trigger()}catch(l){t||(t=l)}i=r}}if(t)throw t}function y6(t){for(let i=t.deps;i;i=i.nextDep)i.version=-1,i.prevActiveLink=i.dep.activeLink,i.dep.activeLink=i}function D6(t){let i,r=t.depsTail,l=r;for(;l;){const I=l.prevDep;l.version===-1?(l===r&&(r=I),SW(l),osA(l)):i=l,l.dep.activeLink=l.prevActiveLink,l.prevActiveLink=void 0,l=I}t.deps=i,t.depsTail=r}function B3(t){for(let i=t.deps;i;i=i.nextDep)if(i.dep.version!==i.version||i.dep.computed&&(S6(i.dep.computed)||i.dep.version!==i.version))return!0;return!!t._dirty}function S6(t){if(t.flags&4&&!(t.flags&16)||(t.flags&=-17,t.globalVersion===uU))return;t.globalVersion=uU;const i=t.dep;if(t.flags|=2,i.version>0&&!t.isSSR&&t.deps&&!B3(t)){t.flags&=-3;return}const r=_a,l=oB;_a=t,oB=!0;try{y6(t);const I=t.fn(t._value);(i.version===0||Hy(I,t._value))&&(t._value=I,i.version++)}catch(I){throw i.version++,I}finally{_a=r,oB=l,D6(t),t.flags&=-3}}function SW(t,i=!1){const{dep:r,prevSub:l,nextSub:I}=t;if(l&&(l.nextSub=I,t.prevSub=void 0),I&&(I.prevSub=l,t.nextSub=void 0),r.subs===t&&(r.subs=l,!l&&r.computed)){r.computed.flags&=-5;for(let h=r.computed.deps;h;h=h.nextDep)SW(h,!0)}!i&&!--r.sc&&r.map&&r.map.delete(r.key)}function osA(t){const{prevDep:i,nextDep:r}=t;i&&(i.nextDep=r,t.prevDep=void 0),r&&(r.prevDep=i,t.nextDep=void 0)}let oB=!0;const M6=[];function iD(){M6.push(oB),oB=!1}function oD(){const t=M6.pop();oB=t===void 0?!0:t}function o8(t){const{cleanup:i}=t;if(t.cleanup=void 0,i){const r=_a;_a=void 0;try{i()}finally{_a=r}}}let uU=0;class ssA{constructor(i,r){this.sub=i,this.dep=r,this.version=r.version,this.nextDep=this.prevDep=this.nextSub=this.prevSub=this.prevActiveLink=void 0}}class MW{constructor(i){this.computed=i,this.version=0,this.activeLink=void 0,this.subs=void 0,this.map=void 0,this.key=void 0,this.sc=0}track(i){if(!_a||!oB||_a===this.computed)return;let r=this.activeLink;if(r===void 0||r.sub!==_a)r=this.activeLink=new ssA(_a,this),_a.deps?(r.prevDep=_a.depsTail,_a.depsTail.nextDep=r,_a.depsTail=r):_a.deps=_a.depsTail=r,v6(r);else if(r.version===-1&&(r.version=this.version,r.nextDep)){const l=r.nextDep;l.prevDep=r.prevDep,r.prevDep&&(r.prevDep.nextDep=l),r.prevDep=_a.depsTail,r.nextDep=void 0,_a.depsTail.nextDep=r,_a.depsTail=r,_a.deps===r&&(_a.deps=l)}return r}trigger(i){this.version++,uU++,this.notify(i)}notify(i){yW();try{for(let r=this.subs;r;r=r.prevSub)r.sub.notify()&&r.sub.dep.notify()}finally{DW()}}}function v6(t){if(t.dep.sc++,t.sub.flags&4){const i=t.dep.computed;if(i&&!t.dep.subs){i.flags|=20;for(let l=i.deps;l;l=l.nextDep)v6(l)}const r=t.dep.subs;r!==t&&(t.prevSub=r,r&&(r.nextSub=t)),t.dep.subs=t}}const dY=new WeakMap,Cv=Symbol(""),Q3=Symbol(""),EU=Symbol("");function Bu(t,i,r){if(oB&&_a){let l=dY.get(t);l||dY.set(t,l=new Map);let I=l.get(r);I||(l.set(r,I=new MW),I.map=l,I.key=r),I.track()}}function cm(t,i,r,l,I,h){const f=dY.get(t);if(!f){uU++;return}const w=_=>{_&&_.trigger()};if(yW(),i==="clear")f.forEach(w);else{const _=Ms(t),k=_&&fW(r);if(_&&r==="length"){const U=Number(l);f.forEach((j,lA)=>{(lA==="length"||lA===EU||!dm(lA)&&lA>=U)&&w(j)})}else switch((r!==void 0||f.has(void 0))&&w(f.get(r)),k&&w(f.get(EU)),i){case"add":_?k&&w(f.get("length")):(w(f.get(Cv)),Y_(t)&&w(f.get(Q3)));break;case"delete":_||(w(f.get(Cv)),Y_(t)&&w(f.get(Q3)));break;case"set":Y_(t)&&w(f.get(Cv));break}}DW()}function nsA(t,i){const r=dY.get(t);return r&&r.get(i)}function B_(t){const i=Nr(t);return i===t?i:(Bu(i,"iterate",EU),eh(t)?i:i.map(Qu))}function tV(t){return Bu(t=Nr(t),"iterate",EU),t}const rsA={__proto__:null,[Symbol.iterator](){return Dj(this,Symbol.iterator,Qu)},concat(...t){return B_(this).concat(...t.map(i=>Ms(i)?B_(i):i))},entries(){return Dj(this,"entries",t=>(t[1]=Qu(t[1]),t))},every(t,i){return tm(this,"every",t,i,void 0,arguments)},filter(t,i){return tm(this,"filter",t,i,r=>r.map(Qu),arguments)},find(t,i){return tm(this,"find",t,i,Qu,arguments)},findIndex(t,i){return tm(this,"findIndex",t,i,void 0,arguments)},findLast(t,i){return tm(this,"findLast",t,i,Qu,arguments)},findLastIndex(t,i){return tm(this,"findLastIndex",t,i,void 0,arguments)},forEach(t,i){return tm(this,"forEach",t,i,void 0,arguments)},includes(...t){return Sj(this,"includes",t)},indexOf(...t){return Sj(this,"indexOf",t)},join(t){return B_(this).join(t)},lastIndexOf(...t){return Sj(this,"lastIndexOf",t)},map(t,i){return tm(this,"map",t,i,void 0,arguments)},pop(){return dL(this,"pop")},push(...t){return dL(this,"push",t)},reduce(t,...i){return s8(this,"reduce",t,i)},reduceRight(t,...i){return s8(this,"reduceRight",t,i)},shift(){return dL(this,"shift")},some(t,i){return tm(this,"some",t,i,void 0,arguments)},splice(...t){return dL(this,"splice",t)},toReversed(){return B_(this).toReversed()},toSorted(t){return B_(this).toSorted(t)},toSpliced(...t){return B_(this).toSpliced(...t)},unshift(...t){return dL(this,"unshift",t)},values(){return Dj(this,"values",Qu)}};function Dj(t,i,r){const l=tV(t),I=l[i]();return l!==t&&!eh(t)&&(I._next=I.next,I.next=()=>{const h=I._next();return h.value&&(h.value=r(h.value)),h}),I}const asA=Array.prototype;function tm(t,i,r,l,I,h){const f=tV(t),w=f!==t&&!eh(t),_=f[i];if(_!==asA[i]){const j=_.apply(t,h);return w?Qu(j):j}let k=r;f!==t&&(w?k=function(j,lA){return r.call(this,Qu(j),lA,t)}:r.length>2&&(k=function(j,lA){return r.call(this,j,lA,t)}));const U=_.call(f,k,l);return w&&I?I(U):U}function s8(t,i,r,l){const I=tV(t);let h=r;return I!==t&&(eh(t)?r.length>3&&(h=function(f,w,_){return r.call(this,f,w,_,t)}):h=function(f,w,_){return r.call(this,f,Qu(w),_,t)}),I[i](h,...l)}function Sj(t,i,r){const l=Nr(t);Bu(l,"iterate",EU);const I=l[i](...r);return(I===-1||I===!1)&&wW(r[0])?(r[0]=Nr(r[0]),l[i](...r)):I}function dL(t,i,r=[]){iD(),yW();const l=Nr(t)[i].apply(t,r);return DW(),oD(),l}const gsA=QW("__proto__,__v_isRef,__isVue"),R6=new Set(Object.getOwnPropertyNames(Symbol).filter(t=>t!=="arguments"&&t!=="caller").map(t=>Symbol[t]).filter(dm));function csA(t){dm(t)||(t=String(t));const i=Nr(this);return Bu(i,"has",t),i.hasOwnProperty(t)}class w6{constructor(i=!1,r=!1){this._isReadonly=i,this._isShallow=r}get(i,r,l){if(r==="__v_skip")return i.__v_skip;const I=this._isReadonly,h=this._isShallow;if(r==="__v_isReactive")return!I;if(r==="__v_isReadonly")return I;if(r==="__v_isShallow")return h;if(r==="__v_raw")return l===(I?h?psA:G6:h?N6:T6).get(i)||Object.getPrototypeOf(i)===Object.getPrototypeOf(l)?i:void 0;const f=Ms(i);if(!I){let _;if(f&&(_=rsA[r]))return _;if(r==="hasOwnProperty")return csA}const w=Reflect.get(i,r,tI(i)?i:l);return(dm(r)?R6.has(r):gsA(r))||(I||Bu(i,"get",r),h)?w:tI(w)?f&&fW(r)?w:w.value:Na(w)?I?sd(w):lv(w):w}}class _6 extends w6{constructor(i=!1){super(!1,i)}set(i,r,l,I){let h=i[r];if(!this._isShallow){const _=vv(h);if(!eh(l)&&!vv(l)&&(h=Nr(h),l=Nr(l)),!Ms(i)&&tI(h)&&!tI(l))return _?!1:(h.value=l,!0)}const f=Ms(i)&&fW(r)?Number(r)t,w1=t=>Reflect.getPrototypeOf(t);function dsA(t,i,r){return function(...l){const I=this.__v_raw,h=Nr(I),f=Y_(h),w=t==="entries"||t===Symbol.iterator&&f,_=t==="keys"&&f,k=I[t](...l),U=r?p3:i?m3:Qu;return!i&&Bu(h,"iterate",_?Q3:Cv),{next(){const{value:j,done:lA}=k.next();return lA?{value:j,done:lA}:{value:w?[U(j[0]),U(j[1])]:U(j),done:lA}},[Symbol.iterator](){return this}}}}function _1(t){return function(...i){return t==="delete"?!1:t==="clear"?void 0:this}}function CsA(t,i){const r={get(I){const h=this.__v_raw,f=Nr(h),w=Nr(I);t||(Hy(I,w)&&Bu(f,"get",I),Bu(f,"get",w));const{has:_}=w1(f),k=i?p3:t?m3:Qu;if(_.call(f,I))return k(h.get(I));if(_.call(f,w))return k(h.get(w));h!==f&&h.get(I)},get size(){const I=this.__v_raw;return!t&&Bu(Nr(I),"iterate",Cv),Reflect.get(I,"size",I)},has(I){const h=this.__v_raw,f=Nr(h),w=Nr(I);return t||(Hy(I,w)&&Bu(f,"has",I),Bu(f,"has",w)),I===w?h.has(I):h.has(I)||h.has(w)},forEach(I,h){const f=this,w=f.__v_raw,_=Nr(w),k=i?p3:t?m3:Qu;return!t&&Bu(_,"iterate",Cv),w.forEach((U,j)=>I.call(h,k(U),k(j),f))}};return oI(r,t?{add:_1("add"),set:_1("set"),delete:_1("delete"),clear:_1("clear")}:{add(I){!i&&!eh(I)&&!vv(I)&&(I=Nr(I));const h=Nr(this);return w1(h).has.call(h,I)||(h.add(I),cm(h,"add",I,I)),this},set(I,h){!i&&!eh(h)&&!vv(h)&&(h=Nr(h));const f=Nr(this),{has:w,get:_}=w1(f);let k=w.call(f,I);k||(I=Nr(I),k=w.call(f,I));const U=_.call(f,I);return f.set(I,h),k?Hy(h,U)&&cm(f,"set",I,h):cm(f,"add",I,h),this},delete(I){const h=Nr(this),{has:f,get:w}=w1(h);let _=f.call(h,I);_||(I=Nr(I),_=f.call(h,I)),w&&w.call(h,I);const k=h.delete(I);return _&&cm(h,"delete",I,void 0),k},clear(){const I=Nr(this),h=I.size!==0,f=I.clear();return h&&cm(I,"clear",void 0,void 0),f}}),["keys","values","entries",Symbol.iterator].forEach(I=>{r[I]=dsA(I,t,i)}),r}function vW(t,i){const r=CsA(t,i);return(l,I,h)=>I==="__v_isReactive"?!t:I==="__v_isReadonly"?t:I==="__v_raw"?l:Reflect.get(Wr(r,I)&&I in l?r:l,I,h)}const hsA={get:vW(!1,!1)},BsA={get:vW(!1,!0)},QsA={get:vW(!0,!1)};const T6=new WeakMap,N6=new WeakMap,G6=new WeakMap,psA=new WeakMap;function msA(t){switch(t){case"Object":case"Array":return 1;case"Map":case"Set":case"WeakMap":case"WeakSet":return 2;default:return 0}}function fsA(t){return t.__v_skip||!Object.isExtensible(t)?0:msA(HoA(t))}function lv(t){return vv(t)?t:RW(t,!1,IsA,hsA,T6)}function ysA(t){return RW(t,!1,EsA,BsA,N6)}function sd(t){return RW(t,!0,usA,QsA,G6)}function RW(t,i,r,l,I){if(!Na(t)||t.__v_raw&&!(i&&t.__v_isReactive))return t;const h=I.get(t);if(h)return h;const f=fsA(t);if(f===0)return t;const w=new Proxy(t,f===2?l:r);return I.set(t,w),w}function V_(t){return vv(t)?V_(t.__v_raw):!!(t&&t.__v_isReactive)}function vv(t){return!!(t&&t.__v_isReadonly)}function eh(t){return!!(t&&t.__v_isShallow)}function wW(t){return t?!!t.__v_raw:!1}function Nr(t){const i=t&&t.__v_raw;return i?Nr(i):t}function DsA(t){return!Wr(t,"__v_skip")&&Object.isExtensible(t)&&C6(t,"__v_skip",!0),t}const Qu=t=>Na(t)?lv(t):t,m3=t=>Na(t)?sd(t):t;function tI(t){return t?t.__v_isRef===!0:!1}function Ze(t){return SsA(t,!1)}function SsA(t,i){return tI(t)?t:new MsA(t,i)}class MsA{constructor(i,r){this.dep=new MW,this.__v_isRef=!0,this.__v_isShallow=!1,this._rawValue=r?i:Nr(i),this._value=r?i:Qu(i),this.__v_isShallow=r}get value(){return this.dep.track(),this._value}set value(i){const r=this._rawValue,l=this.__v_isShallow||eh(i)||vv(i);i=l?i:Nr(i),Hy(i,r)&&(this._rawValue=i,this._value=l?i:Qu(i),this.dep.trigger())}}function aA(t){return tI(t)?t.value:t}const vsA={get:(t,i,r)=>i==="__v_raw"?t:aA(Reflect.get(t,i,r)),set:(t,i,r,l)=>{const I=t[i];return tI(I)&&!tI(r)?(I.value=r,!0):Reflect.set(t,i,r,l)}};function b6(t){return V_(t)?t:new Proxy(t,vsA)}function Gs(t){const i=Ms(t)?new Array(t.length):{};for(const r in t)i[r]=k6(t,r);return i}class RsA{constructor(i,r,l){this._object=i,this._key=r,this._defaultValue=l,this.__v_isRef=!0,this._value=void 0}get value(){const i=this._object[this._key];return this._value=i===void 0?this._defaultValue:i}set value(i){this._object[this._key]=i}get dep(){return nsA(Nr(this._object),this._key)}}class wsA{constructor(i){this._getter=i,this.__v_isRef=!0,this.__v_isReadonly=!0,this._value=void 0}get value(){return this._value=this._getter()}}function Mj(t,i,r){return tI(t)?t:$s(t)?new wsA(t):Na(t)&&arguments.length>1?k6(t,i,r):Ze(t)}function k6(t,i,r){const l=t[i];return tI(l)?l:new RsA(t,i,r)}class _sA{constructor(i,r,l){this.fn=i,this.setter=r,this._value=void 0,this.dep=new MW(this),this.__v_isRef=!0,this.deps=void 0,this.depsTail=void 0,this.flags=16,this.globalVersion=uU-1,this.next=void 0,this.effect=this,this.__v_isReadonly=!r,this.isSSR=l}notify(){if(this.flags|=16,!(this.flags&8)&&_a!==this)return f6(this,!0),!0}get value(){const i=this.dep.track();return S6(this),i&&(i.version=this.dep.version),this._value}set value(i){this.setter&&this.setter(i)}}function TsA(t,i,r=!1){let l,I;return $s(t)?l=t:(l=t.get,I=t.set),new _sA(l,I,r)}const T1={},CY=new WeakMap;let iv;function NsA(t,i=!1,r=iv){if(r){let l=CY.get(r);l||CY.set(r,l=[]),l.push(t)}}function GsA(t,i,r=ya){const{immediate:l,deep:I,once:h,scheduler:f,augmentJob:w,call:_}=r,k=ue=>I?ue:eh(ue)||I===!1||I===0?lm(ue,1):lm(ue);let U,j,lA,rA,mA=!1,IA=!1;if(tI(t)?(j=()=>t.value,mA=eh(t)):V_(t)?(j=()=>k(t),mA=!0):Ms(t)?(IA=!0,mA=t.some(ue=>V_(ue)||eh(ue)),j=()=>t.map(ue=>{if(tI(ue))return ue.value;if(V_(ue))return k(ue);if($s(ue))return _?_(ue,2):ue()})):$s(t)?i?j=_?()=>_(t,2):t:j=()=>{if(lA){iD();try{lA()}finally{oD()}}const ue=iv;iv=U;try{return _?_(t,3,[rA]):t(rA)}finally{iv=ue}}:j=vQ,i&&I){const ue=j,xe=I===!0?1/0:I;j=()=>lm(ue(),xe)}const cA=isA(),TA=()=>{U.stop(),cA&&cA.active&&mW(cA.effects,U)};if(h&&i){const ue=i;i=(...xe)=>{ue(...xe),TA()}}let WA=IA?new Array(t.length).fill(T1):T1;const ge=ue=>{if(!(!(U.flags&1)||!U.dirty&&!ue))if(i){const xe=U.run();if(I||mA||(IA?xe.some((Be,ut)=>Hy(Be,WA[ut])):Hy(xe,WA))){lA&&lA();const Be=iv;iv=U;try{const ut=[xe,WA===T1?void 0:IA&&WA[0]===T1?[]:WA,rA];_?_(i,3,ut):i(...ut),WA=xe}finally{iv=Be}}}else U.run()};return w&&w(ge),U=new p6(j),U.scheduler=f?()=>f(ge,!1):ge,rA=ue=>NsA(ue,!1,U),lA=U.onStop=()=>{const ue=CY.get(U);if(ue){if(_)_(ue,4);else for(const xe of ue)xe();CY.delete(U)}},i?l?ge(!0):WA=U.run():f?f(ge.bind(null,!0),!0):U.run(),TA.pause=U.pause.bind(U),TA.resume=U.resume.bind(U),TA.stop=TA,TA}function lm(t,i=1/0,r){if(i<=0||!Na(t)||t.__v_skip||(r=r||new Set,r.has(t)))return t;if(r.add(t),i--,tI(t))lm(t.value,i,r);else if(Ms(t))for(let l=0;l{lm(l,i,r)});else if(d6(t)){for(const l in t)lm(t[l],i,r);for(const l of Object.getOwnPropertySymbols(t))Object.prototype.propertyIsEnumerable.call(t,l)&&lm(t[l],i,r)}return t}/**
+**/let iC;class ssA{constructor(i=!1){this.detached=i,this._active=!0,this.effects=[],this.cleanups=[],this._isPaused=!1,this.parent=iC,!i&&iC&&(this.index=(iC.scopes||(iC.scopes=[])).push(this)-1)}get active(){return this._active}pause(){if(this._active){this._isPaused=!0;let i,r;if(this.scopes)for(i=0,r=this.scopes.length;i0)return;if(KL){let i=KL;for(KL=void 0;i;){const r=i.next;i.next=void 0,i.flags&=-9,i=r}}let t;for(;qL;){let i=qL;for(qL=void 0;i;){const r=i.next;if(i.next=void 0,i.flags&=-9,i.flags&1)try{i.trigger()}catch(l){t||(t=l)}i=r}}if(t)throw t}function D6(t){for(let i=t.deps;i;i=i.nextDep)i.version=-1,i.prevActiveLink=i.dep.activeLink,i.dep.activeLink=i}function S6(t){let i,r=t.depsTail,l=r;for(;l;){const I=l.prevDep;l.version===-1?(l===r&&(r=I),MW(l),rsA(l)):i=l,l.dep.activeLink=l.prevActiveLink,l.prevActiveLink=void 0,l=I}t.deps=i,t.depsTail=r}function Q3(t){for(let i=t.deps;i;i=i.nextDep)if(i.dep.version!==i.version||i.dep.computed&&(M6(i.dep.computed)||i.dep.version!==i.version))return!0;return!!t._dirty}function M6(t){if(t.flags&4&&!(t.flags&16)||(t.flags&=-17,t.globalVersion===uU))return;t.globalVersion=uU;const i=t.dep;if(t.flags|=2,i.version>0&&!t.isSSR&&t.deps&&!Q3(t)){t.flags&=-3;return}const r=_a,l=sB;_a=t,sB=!0;try{D6(t);const I=t.fn(t._value);(i.version===0||jy(I,t._value))&&(t._value=I,i.version++)}catch(I){throw i.version++,I}finally{_a=r,sB=l,S6(t),t.flags&=-3}}function MW(t,i=!1){const{dep:r,prevSub:l,nextSub:I}=t;if(l&&(l.nextSub=I,t.prevSub=void 0),I&&(I.prevSub=l,t.nextSub=void 0),r.subs===t&&(r.subs=l,!l&&r.computed)){r.computed.flags&=-5;for(let h=r.computed.deps;h;h=h.nextDep)MW(h,!0)}!i&&!--r.sc&&r.map&&r.map.delete(r.key)}function rsA(t){const{prevDep:i,nextDep:r}=t;i&&(i.nextDep=r,t.prevDep=void 0),r&&(r.prevDep=i,t.nextDep=void 0)}let sB=!0;const v6=[];function rD(){v6.push(sB),sB=!1}function aD(){const t=v6.pop();sB=t===void 0?!0:t}function s8(t){const{cleanup:i}=t;if(t.cleanup=void 0,i){const r=_a;_a=void 0;try{i()}finally{_a=r}}}let uU=0;class asA{constructor(i,r){this.sub=i,this.dep=r,this.version=r.version,this.nextDep=this.prevDep=this.nextSub=this.prevSub=this.prevActiveLink=void 0}}class vW{constructor(i){this.computed=i,this.version=0,this.activeLink=void 0,this.subs=void 0,this.map=void 0,this.key=void 0,this.sc=0}track(i){if(!_a||!sB||_a===this.computed)return;let r=this.activeLink;if(r===void 0||r.sub!==_a)r=this.activeLink=new asA(_a,this),_a.deps?(r.prevDep=_a.depsTail,_a.depsTail.nextDep=r,_a.depsTail=r):_a.deps=_a.depsTail=r,R6(r);else if(r.version===-1&&(r.version=this.version,r.nextDep)){const l=r.nextDep;l.prevDep=r.prevDep,r.prevDep&&(r.prevDep.nextDep=l),r.prevDep=_a.depsTail,r.nextDep=void 0,_a.depsTail.nextDep=r,_a.depsTail=r,_a.deps===r&&(_a.deps=l)}return r}trigger(i){this.version++,uU++,this.notify(i)}notify(i){DW();try{for(let r=this.subs;r;r=r.prevSub)r.sub.notify()&&r.sub.dep.notify()}finally{SW()}}}function R6(t){if(t.dep.sc++,t.sub.flags&4){const i=t.dep.computed;if(i&&!t.dep.subs){i.flags|=20;for(let l=i.deps;l;l=l.nextDep)R6(l)}const r=t.dep.subs;r!==t&&(t.prevSub=r,r&&(r.nextSub=t)),t.dep.subs=t}}const EY=new WeakMap,Bv=Symbol(""),p3=Symbol(""),EU=Symbol("");function Qu(t,i,r){if(sB&&_a){let l=EY.get(t);l||EY.set(t,l=new Map);let I=l.get(r);I||(l.set(r,I=new vW),I.map=l,I.key=r),I.track()}}function lm(t,i,r,l,I,h){const f=EY.get(t);if(!f){uU++;return}const w=_=>{_&&_.trigger()};if(DW(),i==="clear")f.forEach(w);else{const _=Ms(t),b=_&&yW(r);if(_&&r==="length"){const U=Number(l);f.forEach((j,IA)=>{(IA==="length"||IA===EU||!Cm(IA)&&IA>=U)&&w(j)})}else switch((r!==void 0||f.has(void 0))&&w(f.get(r)),b&&w(f.get(EU)),i){case"add":_?b&&w(f.get("length")):(w(f.get(Bv)),V_(t)&&w(f.get(p3)));break;case"delete":_||(w(f.get(Bv)),V_(t)&&w(f.get(p3)));break;case"set":V_(t)&&w(f.get(Bv));break}}SW()}function gsA(t,i){const r=EY.get(t);return r&&r.get(i)}function Q_(t){const i=Gr(t);return i===t?i:(Qu(i,"iterate",EU),th(t)?i:i.map(pu))}function tV(t){return Qu(t=Gr(t),"iterate",EU),t}const csA={__proto__:null,[Symbol.iterator](){return Sj(this,Symbol.iterator,pu)},concat(...t){return Q_(this).concat(...t.map(i=>Ms(i)?Q_(i):i))},entries(){return Sj(this,"entries",t=>(t[1]=pu(t[1]),t))},every(t,i){return im(this,"every",t,i,void 0,arguments)},filter(t,i){return im(this,"filter",t,i,r=>r.map(pu),arguments)},find(t,i){return im(this,"find",t,i,pu,arguments)},findIndex(t,i){return im(this,"findIndex",t,i,void 0,arguments)},findLast(t,i){return im(this,"findLast",t,i,pu,arguments)},findLastIndex(t,i){return im(this,"findLastIndex",t,i,void 0,arguments)},forEach(t,i){return im(this,"forEach",t,i,void 0,arguments)},includes(...t){return Mj(this,"includes",t)},indexOf(...t){return Mj(this,"indexOf",t)},join(t){return Q_(this).join(t)},lastIndexOf(...t){return Mj(this,"lastIndexOf",t)},map(t,i){return im(this,"map",t,i,void 0,arguments)},pop(){return CL(this,"pop")},push(...t){return CL(this,"push",t)},reduce(t,...i){return n8(this,"reduce",t,i)},reduceRight(t,...i){return n8(this,"reduceRight",t,i)},shift(){return CL(this,"shift")},some(t,i){return im(this,"some",t,i,void 0,arguments)},splice(...t){return CL(this,"splice",t)},toReversed(){return Q_(this).toReversed()},toSorted(t){return Q_(this).toSorted(t)},toSpliced(...t){return Q_(this).toSpliced(...t)},unshift(...t){return CL(this,"unshift",t)},values(){return Sj(this,"values",pu)}};function Sj(t,i,r){const l=tV(t),I=l[i]();return l!==t&&!th(t)&&(I._next=I.next,I.next=()=>{const h=I._next();return h.value&&(h.value=r(h.value)),h}),I}const lsA=Array.prototype;function im(t,i,r,l,I,h){const f=tV(t),w=f!==t&&!th(t),_=f[i];if(_!==lsA[i]){const j=_.apply(t,h);return w?pu(j):j}let b=r;f!==t&&(w?b=function(j,IA){return r.call(this,pu(j),IA,t)}:r.length>2&&(b=function(j,IA){return r.call(this,j,IA,t)}));const U=_.call(f,b,l);return w&&I?I(U):U}function n8(t,i,r,l){const I=tV(t);let h=r;return I!==t&&(th(t)?r.length>3&&(h=function(f,w,_){return r.call(this,f,w,_,t)}):h=function(f,w,_){return r.call(this,f,pu(w),_,t)}),I[i](h,...l)}function Mj(t,i,r){const l=Gr(t);Qu(l,"iterate",EU);const I=l[i](...r);return(I===-1||I===!1)&&_W(r[0])?(r[0]=Gr(r[0]),l[i](...r)):I}function CL(t,i,r=[]){rD(),DW();const l=Gr(t)[i].apply(t,r);return SW(),aD(),l}const IsA=pW("__proto__,__v_isRef,__isVue"),w6=new Set(Object.getOwnPropertyNames(Symbol).filter(t=>t!=="arguments"&&t!=="caller").map(t=>Symbol[t]).filter(Cm));function usA(t){Cm(t)||(t=String(t));const i=Gr(this);return Qu(i,"has",t),i.hasOwnProperty(t)}class _6{constructor(i=!1,r=!1){this._isReadonly=i,this._isShallow=r}get(i,r,l){if(r==="__v_skip")return i.__v_skip;const I=this._isReadonly,h=this._isShallow;if(r==="__v_isReactive")return!I;if(r==="__v_isReadonly")return I;if(r==="__v_isShallow")return h;if(r==="__v_raw")return l===(I?h?ysA:b6:h?G6:N6).get(i)||Object.getPrototypeOf(i)===Object.getPrototypeOf(l)?i:void 0;const f=Ms(i);if(!I){let _;if(f&&(_=csA[r]))return _;if(r==="hasOwnProperty")return usA}const w=Reflect.get(i,r,iI(i)?i:l);return(Cm(r)?w6.has(r):IsA(r))||(I||Qu(i,"get",r),h)?w:iI(w)?f&&yW(r)?w:w.value:Na(w)?I?CE(w):Ev(w):w}}class T6 extends _6{constructor(i=!1){super(!1,i)}set(i,r,l,I){let h=i[r];if(!this._isShallow){const _=Rv(h);if(!th(l)&&!Rv(l)&&(h=Gr(h),l=Gr(l)),!Ms(i)&&iI(h)&&!iI(l))return _?!1:(h.value=l,!0)}const f=Ms(i)&&yW(r)?Number(r)t,R1=t=>Reflect.getPrototypeOf(t);function BsA(t,i,r){return function(...l){const I=this.__v_raw,h=Gr(I),f=V_(h),w=t==="entries"||t===Symbol.iterator&&f,_=t==="keys"&&f,b=I[t](...l),U=r?m3:i?f3:pu;return!i&&Qu(h,"iterate",_?p3:Bv),{next(){const{value:j,done:IA}=b.next();return IA?{value:j,done:IA}:{value:w?[U(j[0]),U(j[1])]:U(j),done:IA}},[Symbol.iterator](){return this}}}}function w1(t){return function(...i){return t==="delete"?!1:t==="clear"?void 0:this}}function QsA(t,i){const r={get(I){const h=this.__v_raw,f=Gr(h),w=Gr(I);t||(jy(I,w)&&Qu(f,"get",I),Qu(f,"get",w));const{has:_}=R1(f),b=i?m3:t?f3:pu;if(_.call(f,I))return b(h.get(I));if(_.call(f,w))return b(h.get(w));h!==f&&h.get(I)},get size(){const I=this.__v_raw;return!t&&Qu(Gr(I),"iterate",Bv),Reflect.get(I,"size",I)},has(I){const h=this.__v_raw,f=Gr(h),w=Gr(I);return t||(jy(I,w)&&Qu(f,"has",I),Qu(f,"has",w)),I===w?h.has(I):h.has(I)||h.has(w)},forEach(I,h){const f=this,w=f.__v_raw,_=Gr(w),b=i?m3:t?f3:pu;return!t&&Qu(_,"iterate",Bv),w.forEach((U,j)=>I.call(h,b(U),b(j),f))}};return sI(r,t?{add:w1("add"),set:w1("set"),delete:w1("delete"),clear:w1("clear")}:{add(I){!i&&!th(I)&&!Rv(I)&&(I=Gr(I));const h=Gr(this);return R1(h).has.call(h,I)||(h.add(I),lm(h,"add",I,I)),this},set(I,h){!i&&!th(h)&&!Rv(h)&&(h=Gr(h));const f=Gr(this),{has:w,get:_}=R1(f);let b=w.call(f,I);b||(I=Gr(I),b=w.call(f,I));const U=_.call(f,I);return f.set(I,h),b?jy(h,U)&&lm(f,"set",I,h):lm(f,"add",I,h),this},delete(I){const h=Gr(this),{has:f,get:w}=R1(h);let _=f.call(h,I);_||(I=Gr(I),_=f.call(h,I)),w&&w.call(h,I);const b=h.delete(I);return _&&lm(h,"delete",I,void 0),b},clear(){const I=Gr(this),h=I.size!==0,f=I.clear();return h&&lm(I,"clear",void 0,void 0),f}}),["keys","values","entries",Symbol.iterator].forEach(I=>{r[I]=BsA(I,t,i)}),r}function RW(t,i){const r=QsA(t,i);return(l,I,h)=>I==="__v_isReactive"?!t:I==="__v_isReadonly"?t:I==="__v_raw"?l:Reflect.get(Wr(r,I)&&I in l?r:l,I,h)}const psA={get:RW(!1,!1)},msA={get:RW(!1,!0)},fsA={get:RW(!0,!1)};const N6=new WeakMap,G6=new WeakMap,b6=new WeakMap,ysA=new WeakMap;function DsA(t){switch(t){case"Object":case"Array":return 1;case"Map":case"Set":case"WeakMap":case"WeakSet":return 2;default:return 0}}function SsA(t){return t.__v_skip||!Object.isExtensible(t)?0:DsA(joA(t))}function Ev(t){return Rv(t)?t:wW(t,!1,dsA,psA,N6)}function MsA(t){return wW(t,!1,hsA,msA,G6)}function CE(t){return wW(t,!0,CsA,fsA,b6)}function wW(t,i,r,l,I){if(!Na(t)||t.__v_raw&&!(i&&t.__v_isReactive))return t;const h=I.get(t);if(h)return h;const f=SsA(t);if(f===0)return t;const w=new Proxy(t,f===2?l:r);return I.set(t,w),w}function J_(t){return Rv(t)?J_(t.__v_raw):!!(t&&t.__v_isReactive)}function Rv(t){return!!(t&&t.__v_isReadonly)}function th(t){return!!(t&&t.__v_isShallow)}function _W(t){return t?!!t.__v_raw:!1}function Gr(t){const i=t&&t.__v_raw;return i?Gr(i):t}function vsA(t){return!Wr(t,"__v_skip")&&Object.isExtensible(t)&&h6(t,"__v_skip",!0),t}const pu=t=>Na(t)?Ev(t):t,f3=t=>Na(t)?CE(t):t;function iI(t){return t?t.__v_isRef===!0:!1}function ze(t){return RsA(t,!1)}function RsA(t,i){return iI(t)?t:new wsA(t,i)}class wsA{constructor(i,r){this.dep=new vW,this.__v_isRef=!0,this.__v_isShallow=!1,this._rawValue=r?i:Gr(i),this._value=r?i:pu(i),this.__v_isShallow=r}get value(){return this.dep.track(),this._value}set value(i){const r=this._rawValue,l=this.__v_isShallow||th(i)||Rv(i);i=l?i:Gr(i),jy(i,r)&&(this._rawValue=i,this._value=l?i:pu(i),this.dep.trigger())}}function aA(t){return iI(t)?t.value:t}const _sA={get:(t,i,r)=>i==="__v_raw"?t:aA(Reflect.get(t,i,r)),set:(t,i,r,l)=>{const I=t[i];return iI(I)&&!iI(r)?(I.value=r,!0):Reflect.set(t,i,r,l)}};function k6(t){return J_(t)?t:new Proxy(t,_sA)}function Gs(t){const i=Ms(t)?new Array(t.length):{};for(const r in t)i[r]=L6(t,r);return i}class TsA{constructor(i,r,l){this._object=i,this._key=r,this._defaultValue=l,this.__v_isRef=!0,this._value=void 0}get value(){const i=this._object[this._key];return this._value=i===void 0?this._defaultValue:i}set value(i){this._object[this._key]=i}get dep(){return gsA(Gr(this._object),this._key)}}class NsA{constructor(i){this._getter=i,this.__v_isRef=!0,this.__v_isReadonly=!0,this._value=void 0}get value(){return this._value=this._getter()}}function vj(t,i,r){return iI(t)?t:$s(t)?new NsA(t):Na(t)&&arguments.length>1?L6(t,i,r):ze(t)}function L6(t,i,r){const l=t[i];return iI(l)?l:new TsA(t,i,r)}class GsA{constructor(i,r,l){this.fn=i,this.setter=r,this._value=void 0,this.dep=new vW(this),this.__v_isRef=!0,this.deps=void 0,this.depsTail=void 0,this.flags=16,this.globalVersion=uU-1,this.next=void 0,this.effect=this,this.__v_isReadonly=!r,this.isSSR=l}notify(){if(this.flags|=16,!(this.flags&8)&&_a!==this)return y6(this,!0),!0}get value(){const i=this.dep.track();return M6(this),i&&(i.version=this.dep.version),this._value}set value(i){this.setter&&this.setter(i)}}function bsA(t,i,r=!1){let l,I;return $s(t)?l=t:(l=t.get,I=t.set),new GsA(l,I,r)}const _1={},dY=new WeakMap;let rv;function ksA(t,i=!1,r=rv){if(r){let l=dY.get(r);l||dY.set(r,l=[]),l.push(t)}}function LsA(t,i,r=Da){const{immediate:l,deep:I,once:h,scheduler:f,augmentJob:w,call:_}=r,b=de=>I?de:th(de)||I===!1||I===0?Im(de,1):Im(de);let U,j,IA,nA,mA=!1,lA=!1;if(iI(t)?(j=()=>t.value,mA=th(t)):J_(t)?(j=()=>b(t),mA=!0):Ms(t)?(lA=!0,mA=t.some(de=>J_(de)||th(de)),j=()=>t.map(de=>{if(iI(de))return de.value;if(J_(de))return b(de);if($s(de))return _?_(de,2):de()})):$s(t)?i?j=_?()=>_(t,2):t:j=()=>{if(IA){rD();try{IA()}finally{aD()}}const de=rv;rv=U;try{return _?_(t,3,[nA]):t(nA)}finally{rv=de}}:j=RQ,i&&I){const de=j,Pe=I===!0?1/0:I;j=()=>Im(de(),Pe)}const cA=nsA(),TA=()=>{U.stop(),cA&&cA.active&&fW(cA.effects,U)};if(h&&i){const de=i;i=(...Pe)=>{de(...Pe),TA()}}let WA=lA?new Array(t.length).fill(_1):_1;const Ee=de=>{if(!(!(U.flags&1)||!U.dirty&&!de))if(i){const Pe=U.run();if(I||mA||(lA?Pe.some((pe,gt)=>jy(pe,WA[gt])):jy(Pe,WA))){IA&&IA();const pe=rv;rv=U;try{const gt=[Pe,WA===_1?void 0:lA&&WA[0]===_1?[]:WA,nA];_?_(i,3,gt):i(...gt),WA=Pe}finally{rv=pe}}}else U.run()};return w&&w(Ee),U=new m6(j),U.scheduler=f?()=>f(Ee,!1):Ee,nA=de=>ksA(de,!1,U),IA=U.onStop=()=>{const de=dY.get(U);if(de){if(_)_(de,4);else for(const Pe of de)Pe();dY.delete(U)}},i?l?Ee(!0):WA=U.run():f?f(Ee.bind(null,!0),!0):U.run(),TA.pause=U.pause.bind(U),TA.resume=U.resume.bind(U),TA.stop=TA,TA}function Im(t,i=1/0,r){if(i<=0||!Na(t)||t.__v_skip||(r=r||new Set,r.has(t)))return t;if(r.add(t),i--,iI(t))Im(t.value,i,r);else if(Ms(t))for(let l=0;l{Im(l,i,r)});else if(C6(t)){for(const l in t)Im(t[l],i,r);for(const l of Object.getOwnPropertySymbols(t))Object.prototype.propertyIsEnumerable.call(t,l)&&Im(t[l],i,r)}return t}/**
* @vue/runtime-core v3.5.13
* (c) 2018-present Yuxi (Evan) You and Vue contributors
* @license MIT
-**/function bU(t,i,r,l){try{return l?t(...l):t()}catch(I){iV(I,i,r)}}function nB(t,i,r,l){if($s(t)){const I=bU(t,i,r,l);return I&&u6(I)&&I.catch(h=>{iV(h,i,r)}),I}if(Ms(t)){const I=[];for(let h=0;h>>1,I=hE[l],h=dU(I);h=dU(r)?hE.push(t):hE.splice(ksA(i),0,t),t.flags|=1,U6()}}function U6(){hY||(hY=L6.then(O6))}function LsA(t){Ms(t)?J_.push(...t):by&&t.id===-1?by.splice(y_+1,0,t):t.flags&1||(J_.push(t),t.flags|=1),U6()}function n8(t,i,r=BQ+1){for(;rdU(r)-dU(l));if(J_.length=0,by){by.push(...i);return}for(by=i,y_=0;y_t.id==null?t.flags&2?-1:1/0:t.id;function O6(t){try{for(BQ=0;BQ{l._d&&p8(-1);const h=BY(i);let f;try{f=t(...I)}finally{BY(h),l._d&&p8(1)}return f};return l._n=!0,l._c=!0,l._d=!0,l}function Ta(t,i){if(eI===null)return t;const r=gV(eI),l=t.dirs||(t.dirs=[]);for(let I=0;It.__isTeleport,jL=t=>t&&(t.disabled||t.disabled===""),r8=t=>t&&(t.defer||t.defer===""),a8=t=>typeof SVGElement<"u"&&t instanceof SVGElement,g8=t=>typeof MathMLElement=="function"&&t instanceof MathMLElement,f3=(t,i)=>{const r=t&&t.to;return fg(r)?i?i(r):null:r},Y6={name:"Teleport",__isTeleport:!0,process(t,i,r,l,I,h,f,w,_,k){const{mc:U,pc:j,pbc:lA,o:{insert:rA,querySelector:mA,createText:IA,createComment:cA}}=k,TA=jL(i.props);let{shapeFlag:WA,children:ge,dynamicChildren:ue}=i;if(t==null){const xe=i.el=IA(""),Be=i.anchor=IA("");rA(xe,r,l),rA(Be,r,l);const ut=(ze,_e)=>{WA&16&&(I&&I.isCE&&(I.ce._teleportTarget=ze),U(ge,ze,_e,I,h,f,w,_))},pt=()=>{const ze=i.target=f3(i.props,mA),_e=V6(ze,i,IA,rA);ze&&(f!=="svg"&&a8(ze)?f="svg":f!=="mathml"&&g8(ze)&&(f="mathml"),TA||(ut(ze,_e),X1(i,!1)))};TA&&(ut(r,Be),X1(i,!0)),r8(i.props)?dE(()=>{pt(),i.el.__isMounted=!0},h):pt()}else{if(r8(i.props)&&!t.el.__isMounted){dE(()=>{Y6.process(t,i,r,l,I,h,f,w,_,k),delete t.el.__isMounted},h);return}i.el=t.el,i.targetStart=t.targetStart;const xe=i.anchor=t.anchor,Be=i.target=t.target,ut=i.targetAnchor=t.targetAnchor,pt=jL(t.props),ze=pt?r:Be,_e=pt?xe:ut;if(f==="svg"||a8(Be)?f="svg":(f==="mathml"||g8(Be))&&(f="mathml"),ue?(lA(t.dynamicChildren,ue,ze,I,h,f,w),NW(t,i,!0)):_||j(t,i,ze,_e,I,h,f,w,!1),TA)pt?i.props&&t.props&&i.props.to!==t.props.to&&(i.props.to=t.props.to):N1(i,r,xe,k,1);else if((i.props&&i.props.to)!==(t.props&&t.props.to)){const We=i.target=f3(i.props,mA);We&&N1(i,We,null,k,0)}else pt&&N1(i,Be,ut,k,1);X1(i,TA)}},remove(t,i,r,{um:l,o:{remove:I}},h){const{shapeFlag:f,children:w,anchor:_,targetStart:k,targetAnchor:U,target:j,props:lA}=t;if(j&&(I(k),I(U)),h&&I(_),f&16){const rA=h||!jL(lA);for(let mA=0;mA{t.isMounted=!0}),Z6(()=>{t.isUnmounting=!0}),t}const VC=[Function,Array],J6={mode:String,appear:Boolean,persisted:Boolean,onBeforeEnter:VC,onEnter:VC,onAfterEnter:VC,onEnterCancelled:VC,onBeforeLeave:VC,onLeave:VC,onAfterLeave:VC,onLeaveCancelled:VC,onBeforeAppear:VC,onAppear:VC,onAfterAppear:VC,onAppearCancelled:VC},H6=t=>{const i=t.subTree;return i.component?H6(i.component):i},PsA={name:"BaseTransition",props:J6,setup(t,{slots:i}){const r=LnA(),l=OsA();return()=>{const I=i.default&&j6(i.default(),!0);if(!I||!I.length)return;const h=q6(I),f=Nr(t),{mode:w}=f;if(l.isLeaving)return vj(h);const _=c8(h);if(!_)return vj(h);let k=y3(_,f,l,r,j=>k=j);_.type!==BE&&CU(_,k);let U=r.subTree&&c8(r.subTree);if(U&&U.type!==BE&&!sv(_,U)&&H6(r).type!==BE){let j=y3(U,f,l,r);if(CU(U,j),w==="out-in"&&_.type!==BE)return l.isLeaving=!0,j.afterLeave=()=>{l.isLeaving=!1,r.job.flags&8||r.update(),delete j.afterLeave,U=void 0},vj(h);w==="in-out"&&_.type!==BE?j.delayLeave=(lA,rA,mA)=>{const IA=K6(l,U);IA[String(U.key)]=U,lA[ky]=()=>{rA(),lA[ky]=void 0,delete k.delayedLeave,U=void 0},k.delayedLeave=()=>{mA(),delete k.delayedLeave,U=void 0}}:U=void 0}else U&&(U=void 0);return h}}};function q6(t){let i=t[0];if(t.length>1){for(const r of t)if(r.type!==BE){i=r;break}}return i}const xsA=PsA;function K6(t,i){const{leavingVNodes:r}=t;let l=r.get(i.type);return l||(l=Object.create(null),r.set(i.type,l)),l}function y3(t,i,r,l,I){const{appear:h,mode:f,persisted:w=!1,onBeforeEnter:_,onEnter:k,onAfterEnter:U,onEnterCancelled:j,onBeforeLeave:lA,onLeave:rA,onAfterLeave:mA,onLeaveCancelled:IA,onBeforeAppear:cA,onAppear:TA,onAfterAppear:WA,onAppearCancelled:ge}=i,ue=String(t.key),xe=K6(r,t),Be=(ze,_e)=>{ze&&nB(ze,l,9,_e)},ut=(ze,_e)=>{const We=_e[1];Be(ze,_e),Ms(ze)?ze.every(Le=>Le.length<=1)&&We():ze.length<=1&&We()},pt={mode:f,persisted:w,beforeEnter(ze){let _e=_;if(!r.isMounted)if(h)_e=cA||_;else return;ze[ky]&&ze[ky](!0);const We=xe[ue];We&&sv(t,We)&&We.el[ky]&&We.el[ky](),Be(_e,[ze])},enter(ze){let _e=k,We=U,Le=j;if(!r.isMounted)if(h)_e=TA||k,We=WA||U,Le=ge||j;else return;let oe=!1;const je=ze[G1]=Dt=>{oe||(oe=!0,Dt?Be(Le,[ze]):Be(We,[ze]),pt.delayedLeave&&pt.delayedLeave(),ze[G1]=void 0)};_e?ut(_e,[ze,je]):je()},leave(ze,_e){const We=String(t.key);if(ze[G1]&&ze[G1](!0),r.isUnmounting)return _e();Be(lA,[ze]);let Le=!1;const oe=ze[ky]=je=>{Le||(Le=!0,_e(),je?Be(IA,[ze]):Be(mA,[ze]),ze[ky]=void 0,xe[We]===t&&delete xe[We])};xe[We]=t,rA?ut(rA,[ze,oe]):oe()},clone(ze){const _e=y3(ze,i,r,l,I);return I&&I(_e),_e}};return pt}function vj(t){if(sV(t))return t=Zy(t),t.children=null,t}function c8(t){if(!sV(t))return x6(t.type)&&t.children?q6(t.children):t;const{shapeFlag:i,children:r}=t;if(r){if(i&16)return r[0];if(i&32&&$s(r.default))return r.default()}}function CU(t,i){t.shapeFlag&6&&t.component?(t.transition=i,CU(t.component.subTree,i)):t.shapeFlag&128?(t.ssContent.transition=i.clone(t.ssContent),t.ssFallback.transition=i.clone(t.ssFallback)):t.transition=i}function j6(t,i=!1,r){let l=[],I=0;for(let h=0;h1)for(let h=0;hQY(mA,i&&(Ms(i)?i[IA]:i),r,l,I));return}if(H_(l)&&!I){l.shapeFlag&512&&l.type.__asyncResolved&&l.component.subTree.component&&QY(t,i,r,l.component.subTree);return}const h=l.shapeFlag&4?gV(l.component):l.el,f=I?null:h,{i:w,r:_}=t,k=i&&i.r,U=w.refs===ya?w.refs={}:w.refs,j=w.setupState,lA=Nr(j),rA=j===ya?()=>!1:mA=>Wr(lA,mA);if(k!=null&&k!==_&&(fg(k)?(U[k]=null,rA(k)&&(j[k]=null)):tI(k)&&(k.value=null)),$s(_))bU(_,w,12,[f,U]);else{const mA=fg(_),IA=tI(_);if(mA||IA){const cA=()=>{if(t.f){const TA=mA?rA(_)?j[_]:U[_]:_.value;I?Ms(TA)&&mW(TA,h):Ms(TA)?TA.includes(h)||TA.push(h):mA?(U[_]=[h],rA(_)&&(j[_]=U[_])):(_.value=[h],t.k&&(U[t.k]=_.value))}else mA?(U[_]=f,rA(_)&&(j[_]=f)):IA&&(_.value=f,t.k&&(U[t.k]=f))};f?(cA.id=-1,dE(cA,r)):cA()}}}eV().requestIdleCallback;eV().cancelIdleCallback;const H_=t=>!!t.type.__asyncLoader,sV=t=>t.type.__isKeepAlive;function YsA(t,i){z6(t,"a",i)}function VsA(t,i){z6(t,"da",i)}function z6(t,i,r=OI){const l=t.__wdc||(t.__wdc=()=>{let I=r;for(;I;){if(I.isDeactivated)return;I=I.parent}return t()});if(nV(i,l,r),r){let I=r.parent;for(;I&&I.parent;)sV(I.parent.vnode)&&JsA(l,i,r,I),I=I.parent}}function JsA(t,i,r,l){const I=nV(i,t,l,!0);Kg(()=>{mW(l[i],I)},r)}function nV(t,i,r=OI,l=!1){if(r){const I=r[t]||(r[t]=[]),h=i.__weh||(i.__weh=(...f)=>{iD();const w=kU(r),_=nB(i,r,t,f);return w(),oD(),_});return l?I.unshift(h):I.push(h),h}}const Cm=t=>(i,r=OI)=>{(!QU||t==="sp")&&nV(t,(...l)=>i(...l),r)},HsA=Cm("bm"),hc=Cm("m"),qsA=Cm("bu"),KsA=Cm("u"),Z6=Cm("bum"),Kg=Cm("um"),jsA=Cm("sp"),WsA=Cm("rtg"),zsA=Cm("rtc");function ZsA(t,i=OI){nV("ec",t,i)}const XsA="components";function $sA(t,i){return enA(XsA,t,!0,i)||t}const AnA=Symbol.for("v-ndc");function enA(t,i,r=!0,l=!1){const I=eI||OI;if(I){const h=I.type;{const w=xnA(h,!1);if(w&&(w===i||w===oh(i)||w===AV(oh(i))))return h}const f=l8(I[t]||h[t],i)||l8(I.appContext[t],i);return!f&&l?h:f}}function l8(t,i){return t&&(t[i]||t[oh(i)]||t[AV(oh(i))])}function gd(t,i,r,l){let I;const h=r,f=Ms(t);if(f||fg(t)){const w=f&&V_(t);let _=!1;w&&(_=!eh(t),t=tV(t)),I=new Array(t.length);for(let k=0,U=t.length;ki(w,_,void 0,h));else{const w=Object.keys(t);I=new Array(w.length);for(let _=0,k=w.length;_BU(i)?!(i.type===BE||i.type===Gr&&!X6(i.children)):!0)?t:null}const D3=t=>t?h9(t)?gV(t):D3(t.parent):null,WL=oI(Object.create(null),{$:t=>t,$el:t=>t.vnode.el,$data:t=>t.data,$props:t=>t.props,$attrs:t=>t.attrs,$slots:t=>t.slots,$refs:t=>t.refs,$parent:t=>D3(t.parent),$root:t=>D3(t.root),$host:t=>t.ce,$emit:t=>t.emit,$options:t=>A9(t),$forceUpdate:t=>t.f||(t.f=()=>{_W(t.update)}),$nextTick:t=>t.n||(t.n=hv.bind(t.proxy)),$watch:t=>fnA.bind(t)}),Rj=(t,i)=>t!==ya&&!t.__isScriptSetup&&Wr(t,i),tnA={get({_:t},i){if(i==="__v_skip")return!0;const{ctx:r,setupState:l,data:I,props:h,accessCache:f,type:w,appContext:_}=t;let k;if(i[0]!=="$"){const rA=f[i];if(rA!==void 0)switch(rA){case 1:return l[i];case 2:return I[i];case 4:return r[i];case 3:return h[i]}else{if(Rj(l,i))return f[i]=1,l[i];if(I!==ya&&Wr(I,i))return f[i]=2,I[i];if((k=t.propsOptions[0])&&Wr(k,i))return f[i]=3,h[i];if(r!==ya&&Wr(r,i))return f[i]=4,r[i];S3&&(f[i]=0)}}const U=WL[i];let j,lA;if(U)return i==="$attrs"&&Bu(t.attrs,"get",""),U(t);if((j=w.__cssModules)&&(j=j[i]))return j;if(r!==ya&&Wr(r,i))return f[i]=4,r[i];if(lA=_.config.globalProperties,Wr(lA,i))return lA[i]},set({_:t},i,r){const{data:l,setupState:I,ctx:h}=t;return Rj(I,i)?(I[i]=r,!0):l!==ya&&Wr(l,i)?(l[i]=r,!0):Wr(t.props,i)||i[0]==="$"&&i.slice(1)in t?!1:(h[i]=r,!0)},has({_:{data:t,setupState:i,accessCache:r,ctx:l,appContext:I,propsOptions:h}},f){let w;return!!r[f]||t!==ya&&Wr(t,f)||Rj(i,f)||(w=h[0])&&Wr(w,f)||Wr(l,f)||Wr(WL,f)||Wr(I.config.globalProperties,f)},defineProperty(t,i,r){return r.get!=null?t._.accessCache[i]=0:Wr(r,"value")&&this.set(t,i,r.value,null),Reflect.defineProperty(t,i,r)}};function I8(t){return Ms(t)?t.reduce((i,r)=>(i[r]=null,i),{}):t}let S3=!0;function inA(t){const i=A9(t),r=t.proxy,l=t.ctx;S3=!1,i.beforeCreate&&u8(i.beforeCreate,t,"bc");const{data:I,computed:h,methods:f,watch:w,provide:_,inject:k,created:U,beforeMount:j,mounted:lA,beforeUpdate:rA,updated:mA,activated:IA,deactivated:cA,beforeDestroy:TA,beforeUnmount:WA,destroyed:ge,unmounted:ue,render:xe,renderTracked:Be,renderTriggered:ut,errorCaptured:pt,serverPrefetch:ze,expose:_e,inheritAttrs:We,components:Le,directives:oe,filters:je}=i;if(k&&onA(k,l,null),f)for(const Jt in f){const gi=f[Jt];$s(gi)&&(l[Jt]=gi.bind(r))}if(I){const Jt=I.call(r,r);Na(Jt)&&(t.data=lv(Jt))}if(S3=!0,h)for(const Jt in h){const gi=h[Jt],Fi=$s(gi)?gi.bind(r,r):$s(gi.get)?gi.get.bind(r,r):vQ,To=!$s(gi)&&$s(gi.set)?gi.set.bind(r):vQ,to=bt({get:Fi,set:To});Object.defineProperty(l,Jt,{enumerable:!0,configurable:!0,get:()=>to.value,set:uo=>to.value=uo})}if(w)for(const Jt in w)$6(w[Jt],l,r,Jt);if(_){const Jt=$s(_)?_.call(r):_;Reflect.ownKeys(Jt).forEach(gi=>{rd(gi,Jt[gi])})}U&&u8(U,t,"c");function ni(Jt,gi){Ms(gi)?gi.forEach(Fi=>Jt(Fi.bind(r))):gi&&Jt(gi.bind(r))}if(ni(HsA,j),ni(hc,lA),ni(qsA,rA),ni(KsA,mA),ni(YsA,IA),ni(VsA,cA),ni(ZsA,pt),ni(zsA,Be),ni(WsA,ut),ni(Z6,WA),ni(Kg,ue),ni(jsA,ze),Ms(_e))if(_e.length){const Jt=t.exposed||(t.exposed={});_e.forEach(gi=>{Object.defineProperty(Jt,gi,{get:()=>r[gi],set:Fi=>r[gi]=Fi})})}else t.exposed||(t.exposed={});xe&&t.render===vQ&&(t.render=xe),We!=null&&(t.inheritAttrs=We),Le&&(t.components=Le),oe&&(t.directives=oe),ze&&W6(t)}function onA(t,i,r=vQ){Ms(t)&&(t=M3(t));for(const l in t){const I=t[l];let h;Na(I)?"default"in I?h=YI(I.from||l,I.default,!0):h=YI(I.from||l):h=YI(I),tI(h)?Object.defineProperty(i,l,{enumerable:!0,configurable:!0,get:()=>h.value,set:f=>h.value=f}):i[l]=h}}function u8(t,i,r){nB(Ms(t)?t.map(l=>l.bind(i.proxy)):t.bind(i.proxy),i,r)}function $6(t,i,r,l){let I=l.includes(".")?I9(r,l):()=>r[l];if(fg(t)){const h=i[t];$s(h)&&xr(I,h)}else if($s(t))xr(I,t.bind(r));else if(Na(t))if(Ms(t))t.forEach(h=>$6(h,i,r,l));else{const h=$s(t.handler)?t.handler.bind(r):i[t.handler];$s(h)&&xr(I,h,t)}}function A9(t){const i=t.type,{mixins:r,extends:l}=i,{mixins:I,optionsCache:h,config:{optionMergeStrategies:f}}=t.appContext,w=h.get(i);let _;return w?_=w:!I.length&&!r&&!l?_=i:(_={},I.length&&I.forEach(k=>pY(_,k,f,!0)),pY(_,i,f)),Na(i)&&h.set(i,_),_}function pY(t,i,r,l=!1){const{mixins:I,extends:h}=i;h&&pY(t,h,r,!0),I&&I.forEach(f=>pY(t,f,r,!0));for(const f in i)if(!(l&&f==="expose")){const w=snA[f]||r&&r[f];t[f]=w?w(t[f],i[f]):i[f]}return t}const snA={data:E8,props:d8,emits:d8,methods:SL,computed:SL,beforeCreate:IE,created:IE,beforeMount:IE,mounted:IE,beforeUpdate:IE,updated:IE,beforeDestroy:IE,beforeUnmount:IE,destroyed:IE,unmounted:IE,activated:IE,deactivated:IE,errorCaptured:IE,serverPrefetch:IE,components:SL,directives:SL,watch:rnA,provide:E8,inject:nnA};function E8(t,i){return i?t?function(){return oI($s(t)?t.call(this,this):t,$s(i)?i.call(this,this):i)}:i:t}function nnA(t,i){return SL(M3(t),M3(i))}function M3(t){if(Ms(t)){const i={};for(let r=0;r1)return r&&$s(i)?i.call(l&&l.proxy):i}}const t9={},i9=()=>Object.create(t9),o9=t=>Object.getPrototypeOf(t)===t9;function cnA(t,i,r,l=!1){const I={},h=i9();t.propsDefaults=Object.create(null),s9(t,i,I,h);for(const f in t.propsOptions[0])f in I||(I[f]=void 0);r?t.props=l?I:ysA(I):t.type.props?t.props=I:t.props=h,t.attrs=h}function lnA(t,i,r,l){const{props:I,attrs:h,vnode:{patchFlag:f}}=t,w=Nr(I),[_]=t.propsOptions;let k=!1;if((l||f>0)&&!(f&16)){if(f&8){const U=t.vnode.dynamicProps;for(let j=0;j{_=!0;const[lA,rA]=n9(j,i,!0);oI(f,lA),rA&&w.push(...rA)};!r&&i.mixins.length&&i.mixins.forEach(U),t.extends&&U(t.extends),t.mixins&&t.mixins.forEach(U)}if(!h&&!_)return Na(t)&&l.set(t,x_),x_;if(Ms(h))for(let U=0;Ut[0]==="_"||t==="$stable",TW=t=>Ms(t)?t.map(mQ):[mQ(t)],unA=(t,i,r)=>{if(i._n)return i;const l=Li((...I)=>TW(i(...I)),r);return l._c=!1,l},a9=(t,i,r)=>{const l=t._ctx;for(const I in t){if(r9(I))continue;const h=t[I];if($s(h))i[I]=unA(I,h,l);else if(h!=null){const f=TW(h);i[I]=()=>f}}},g9=(t,i)=>{const r=TW(i);t.slots.default=()=>r},c9=(t,i,r)=>{for(const l in i)(r||l!=="_")&&(t[l]=i[l])},EnA=(t,i,r)=>{const l=t.slots=i9();if(t.vnode.shapeFlag&32){const I=i._;I?(c9(l,i,r),r&&C6(l,"_",I,!0)):a9(i,l)}else i&&g9(t,i)},dnA=(t,i,r)=>{const{vnode:l,slots:I}=t;let h=!0,f=ya;if(l.shapeFlag&32){const w=i._;w?r&&w===1?h=!1:c9(I,i,r):(h=!i.$stable,a9(i,I)),f=i}else i&&(g9(t,i),f={default:1});if(h)for(const w in I)!r9(w)&&f[w]==null&&delete I[w]},dE=wnA;function CnA(t){return hnA(t)}function hnA(t,i){const r=eV();r.__VUE__=!0;const{insert:l,remove:I,patchProp:h,createElement:f,createText:w,createComment:_,setText:k,setElementText:U,parentNode:j,nextSibling:lA,setScopeId:rA=vQ,insertStaticContent:mA}=t,IA=(HA,ce,Ve,Ut=null,nt=null,It=null,Xt=void 0,$t=null,be=!!ce.dynamicChildren)=>{if(HA===ce)return;HA&&!sv(HA,ce)&&(Ut=$i(HA),uo(HA,nt,It,!0),HA=null),ce.patchFlag===-2&&(be=!1,ce.dynamicChildren=null);const{type:Xe,ref:vt,shapeFlag:wt}=ce;switch(Xe){case aV:cA(HA,ce,Ve,Ut);break;case BE:TA(HA,ce,Ve,Ut);break;case _j:HA==null&&WA(ce,Ve,Ut,Xt);break;case Gr:Le(HA,ce,Ve,Ut,nt,It,Xt,$t,be);break;default:wt&1?xe(HA,ce,Ve,Ut,nt,It,Xt,$t,be):wt&6?oe(HA,ce,Ve,Ut,nt,It,Xt,$t,be):(wt&64||wt&128)&&Xe.process(HA,ce,Ve,Ut,nt,It,Xt,$t,be,bi)}vt!=null&&nt&&QY(vt,HA&&HA.ref,It,ce||HA,!ce)},cA=(HA,ce,Ve,Ut)=>{if(HA==null)l(ce.el=w(ce.children),Ve,Ut);else{const nt=ce.el=HA.el;ce.children!==HA.children&&k(nt,ce.children)}},TA=(HA,ce,Ve,Ut)=>{HA==null?l(ce.el=_(ce.children||""),Ve,Ut):ce.el=HA.el},WA=(HA,ce,Ve,Ut)=>{[HA.el,HA.anchor]=mA(HA.children,ce,Ve,Ut,HA.el,HA.anchor)},ge=({el:HA,anchor:ce},Ve,Ut)=>{let nt;for(;HA&&HA!==ce;)nt=lA(HA),l(HA,Ve,Ut),HA=nt;l(ce,Ve,Ut)},ue=({el:HA,anchor:ce})=>{let Ve;for(;HA&&HA!==ce;)Ve=lA(HA),I(HA),HA=Ve;I(ce)},xe=(HA,ce,Ve,Ut,nt,It,Xt,$t,be)=>{ce.type==="svg"?Xt="svg":ce.type==="math"&&(Xt="mathml"),HA==null?Be(ce,Ve,Ut,nt,It,Xt,$t,be):ze(HA,ce,nt,It,Xt,$t,be)},Be=(HA,ce,Ve,Ut,nt,It,Xt,$t)=>{let be,Xe;const{props:vt,shapeFlag:wt,transition:Oi,dirs:po}=HA;if(be=HA.el=f(HA.type,It,vt&&vt.is,vt),wt&8?U(be,HA.children):wt&16&&pt(HA.children,be,null,Ut,nt,wj(HA,It),Xt,$t),po&&zM(HA,null,Ut,"created"),ut(be,HA,HA.scopeId,Xt,Ut),vt){for(const oo in vt)oo!=="value"&&!HL(oo)&&h(be,oo,null,vt[oo],It,Ut);"value"in vt&&h(be,"value",null,vt.value,It),(Xe=vt.onVnodeBeforeMount)&&hQ(Xe,Ut,HA)}po&&zM(HA,null,Ut,"beforeMount");const No=BnA(nt,Oi);No&&Oi.beforeEnter(be),l(be,ce,Ve),((Xe=vt&&vt.onVnodeMounted)||No||po)&&dE(()=>{Xe&&hQ(Xe,Ut,HA),No&&Oi.enter(be),po&&zM(HA,null,Ut,"mounted")},nt)},ut=(HA,ce,Ve,Ut,nt)=>{if(Ve&&rA(HA,Ve),Ut)for(let It=0;It{for(let Xe=be;Xe{const $t=ce.el=HA.el;let{patchFlag:be,dynamicChildren:Xe,dirs:vt}=ce;be|=HA.patchFlag&16;const wt=HA.props||ya,Oi=ce.props||ya;let po;if(Ve&&ZM(Ve,!1),(po=Oi.onVnodeBeforeUpdate)&&hQ(po,Ve,ce,HA),vt&&zM(ce,HA,Ve,"beforeUpdate"),Ve&&ZM(Ve,!0),(wt.innerHTML&&Oi.innerHTML==null||wt.textContent&&Oi.textContent==null)&&U($t,""),Xe?_e(HA.dynamicChildren,Xe,$t,Ve,Ut,wj(ce,nt),It):Xt||gi(HA,ce,$t,null,Ve,Ut,wj(ce,nt),It,!1),be>0){if(be&16)We($t,wt,Oi,Ve,nt);else if(be&2&&wt.class!==Oi.class&&h($t,"class",null,Oi.class,nt),be&4&&h($t,"style",wt.style,Oi.style,nt),be&8){const No=ce.dynamicProps;for(let oo=0;oo{po&&hQ(po,Ve,ce,HA),vt&&zM(ce,HA,Ve,"updated")},Ut)},_e=(HA,ce,Ve,Ut,nt,It,Xt)=>{for(let $t=0;$t{if(ce!==Ve){if(ce!==ya)for(const It in ce)!HL(It)&&!(It in Ve)&&h(HA,It,ce[It],null,nt,Ut);for(const It in Ve){if(HL(It))continue;const Xt=Ve[It],$t=ce[It];Xt!==$t&&It!=="value"&&h(HA,It,$t,Xt,nt,Ut)}"value"in Ve&&h(HA,"value",ce.value,Ve.value,nt)}},Le=(HA,ce,Ve,Ut,nt,It,Xt,$t,be)=>{const Xe=ce.el=HA?HA.el:w(""),vt=ce.anchor=HA?HA.anchor:w("");let{patchFlag:wt,dynamicChildren:Oi,slotScopeIds:po}=ce;po&&($t=$t?$t.concat(po):po),HA==null?(l(Xe,Ve,Ut),l(vt,Ve,Ut),pt(ce.children||[],Ve,vt,nt,It,Xt,$t,be)):wt>0&&wt&64&&Oi&&HA.dynamicChildren?(_e(HA.dynamicChildren,Oi,Ve,nt,It,Xt,$t),(ce.key!=null||nt&&ce===nt.subTree)&&NW(HA,ce,!0)):gi(HA,ce,Ve,vt,nt,It,Xt,$t,be)},oe=(HA,ce,Ve,Ut,nt,It,Xt,$t,be)=>{ce.slotScopeIds=$t,HA==null?ce.shapeFlag&512?nt.ctx.activate(ce,Ve,Ut,Xt,be):je(ce,Ve,Ut,nt,It,Xt,be):Dt(HA,ce,be)},je=(HA,ce,Ve,Ut,nt,It,Xt)=>{const $t=HA.component=knA(HA,Ut,nt);if(sV(HA)&&($t.ctx.renderer=bi),UnA($t,!1,Xt),$t.asyncDep){if(nt&&nt.registerDep($t,ni,Xt),!HA.el){const be=$t.subTree=Gt(BE);TA(null,be,ce,Ve)}}else ni($t,HA,ce,Ve,nt,It,Xt)},Dt=(HA,ce,Ve)=>{const Ut=ce.component=HA.component;if(vnA(HA,ce,Ve))if(Ut.asyncDep&&!Ut.asyncResolved){Jt(Ut,ce,Ve);return}else Ut.next=ce,Ut.update();else ce.el=HA.el,Ut.vnode=ce},ni=(HA,ce,Ve,Ut,nt,It,Xt)=>{const $t=()=>{if(HA.isMounted){let{next:wt,bu:Oi,u:po,parent:No,vnode:oo}=HA;{const an=l9(HA);if(an){wt&&(wt.el=oo.el,Jt(HA,wt,Xt)),an.asyncDep.then(()=>{HA.isUnmounted||$t()});return}}let Go=wt,An;ZM(HA,!1),wt?(wt.el=oo.el,Jt(HA,wt,Xt)):wt=oo,Oi&&Z1(Oi),(An=wt.props&&wt.props.onVnodeBeforeUpdate)&&hQ(An,No,wt,oo),ZM(HA,!0);const rn=B8(HA),Es=HA.subTree;HA.subTree=rn,IA(Es,rn,j(Es.el),$i(Es),HA,nt,It),wt.el=rn.el,Go===null&&RnA(HA,rn.el),po&&dE(po,nt),(An=wt.props&&wt.props.onVnodeUpdated)&&dE(()=>hQ(An,No,wt,oo),nt)}else{let wt;const{el:Oi,props:po}=ce,{bm:No,m:oo,parent:Go,root:An,type:rn}=HA,Es=H_(ce);ZM(HA,!1),No&&Z1(No),!Es&&(wt=po&&po.onVnodeBeforeMount)&&hQ(wt,Go,ce),ZM(HA,!0);{An.ce&&An.ce._injectChildStyle(rn);const an=HA.subTree=B8(HA);IA(null,an,Ve,Ut,HA,nt,It),ce.el=an.el}if(oo&&dE(oo,nt),!Es&&(wt=po&&po.onVnodeMounted)){const an=ce;dE(()=>hQ(wt,Go,an),nt)}(ce.shapeFlag&256||Go&&H_(Go.vnode)&&Go.vnode.shapeFlag&256)&&HA.a&&dE(HA.a,nt),HA.isMounted=!0,ce=Ve=Ut=null}};HA.scope.on();const be=HA.effect=new p6($t);HA.scope.off();const Xe=HA.update=be.run.bind(be),vt=HA.job=be.runIfDirty.bind(be);vt.i=HA,vt.id=HA.uid,be.scheduler=()=>_W(vt),ZM(HA,!0),Xe()},Jt=(HA,ce,Ve)=>{ce.component=HA;const Ut=HA.vnode.props;HA.vnode=ce,HA.next=null,lnA(HA,ce.props,Ut,Ve),dnA(HA,ce.children,Ve),iD(),n8(HA),oD()},gi=(HA,ce,Ve,Ut,nt,It,Xt,$t,be=!1)=>{const Xe=HA&&HA.children,vt=HA?HA.shapeFlag:0,wt=ce.children,{patchFlag:Oi,shapeFlag:po}=ce;if(Oi>0){if(Oi&128){To(Xe,wt,Ve,Ut,nt,It,Xt,$t,be);return}else if(Oi&256){Fi(Xe,wt,Ve,Ut,nt,It,Xt,$t,be);return}}po&8?(vt&16&&jo(Xe,nt,It),wt!==Xe&&U(Ve,wt)):vt&16?po&16?To(Xe,wt,Ve,Ut,nt,It,Xt,$t,be):jo(Xe,nt,It,!0):(vt&8&&U(Ve,""),po&16&&pt(wt,Ve,Ut,nt,It,Xt,$t,be))},Fi=(HA,ce,Ve,Ut,nt,It,Xt,$t,be)=>{HA=HA||x_,ce=ce||x_;const Xe=HA.length,vt=ce.length,wt=Math.min(Xe,vt);let Oi;for(Oi=0;Oivt?jo(HA,nt,It,!0,!1,wt):pt(ce,Ve,Ut,nt,It,Xt,$t,be,wt)},To=(HA,ce,Ve,Ut,nt,It,Xt,$t,be)=>{let Xe=0;const vt=ce.length;let wt=HA.length-1,Oi=vt-1;for(;Xe<=wt&&Xe<=Oi;){const po=HA[Xe],No=ce[Xe]=be?Ly(ce[Xe]):mQ(ce[Xe]);if(sv(po,No))IA(po,No,Ve,null,nt,It,Xt,$t,be);else break;Xe++}for(;Xe<=wt&&Xe<=Oi;){const po=HA[wt],No=ce[Oi]=be?Ly(ce[Oi]):mQ(ce[Oi]);if(sv(po,No))IA(po,No,Ve,null,nt,It,Xt,$t,be);else break;wt--,Oi--}if(Xe>wt){if(Xe<=Oi){const po=Oi+1,No=poOi)for(;Xe<=wt;)uo(HA[Xe],nt,It,!0),Xe++;else{const po=Xe,No=Xe,oo=new Map;for(Xe=No;Xe<=Oi;Xe++){const Jn=ce[Xe]=be?Ly(ce[Xe]):mQ(ce[Xe]);Jn.key!=null&&oo.set(Jn.key,Xe)}let Go,An=0;const rn=Oi-No+1;let Es=!1,an=0;const Do=new Array(rn);for(Xe=0;Xe=rn){uo(Jn,nt,It,!0);continue}let Qr;if(Jn.key!=null)Qr=oo.get(Jn.key);else for(Go=No;Go<=Oi;Go++)if(Do[Go-No]===0&&sv(Jn,ce[Go])){Qr=Go;break}Qr===void 0?uo(Jn,nt,It,!0):(Do[Qr-No]=Xe+1,Qr>=an?an=Qr:Es=!0,IA(Jn,ce[Qr],Ve,null,nt,It,Xt,$t,be),An++)}const pA=Es?QnA(Do):x_;for(Go=pA.length-1,Xe=rn-1;Xe>=0;Xe--){const Jn=No+Xe,Qr=ce[Jn],ds=Jn+1{const{el:It,type:Xt,transition:$t,children:be,shapeFlag:Xe}=HA;if(Xe&6){to(HA.component.subTree,ce,Ve,Ut);return}if(Xe&128){HA.suspense.move(ce,Ve,Ut);return}if(Xe&64){Xt.move(HA,ce,Ve,bi);return}if(Xt===Gr){l(It,ce,Ve);for(let wt=0;wt$t.enter(It),nt);else{const{leave:wt,delayLeave:Oi,afterLeave:po}=$t,No=()=>l(It,ce,Ve),oo=()=>{wt(It,()=>{No(),po&&po()})};Oi?Oi(It,No,oo):oo()}else l(It,ce,Ve)},uo=(HA,ce,Ve,Ut=!1,nt=!1)=>{const{type:It,props:Xt,ref:$t,children:be,dynamicChildren:Xe,shapeFlag:vt,patchFlag:wt,dirs:Oi,cacheIndex:po}=HA;if(wt===-2&&(nt=!1),$t!=null&&QY($t,null,Ve,HA,!0),po!=null&&(ce.renderCache[po]=void 0),vt&256){ce.ctx.deactivate(HA);return}const No=vt&1&&Oi,oo=!H_(HA);let Go;if(oo&&(Go=Xt&&Xt.onVnodeBeforeUnmount)&&hQ(Go,ce,HA),vt&6)ns(HA.component,Ve,Ut);else{if(vt&128){HA.suspense.unmount(Ve,Ut);return}No&&zM(HA,null,ce,"beforeUnmount"),vt&64?HA.type.remove(HA,ce,Ve,bi,Ut):Xe&&!Xe.hasOnce&&(It!==Gr||wt>0&&wt&64)?jo(Xe,ce,Ve,!1,!0):(It===Gr&&wt&384||!nt&&vt&16)&&jo(be,ce,Ve),Ut&&Vs(HA)}(oo&&(Go=Xt&&Xt.onVnodeUnmounted)||No)&&dE(()=>{Go&&hQ(Go,ce,HA),No&&zM(HA,null,ce,"unmounted")},Ve)},Vs=HA=>{const{type:ce,el:Ve,anchor:Ut,transition:nt}=HA;if(ce===Gr){ki(Ve,Ut);return}if(ce===_j){ue(HA);return}const It=()=>{I(Ve),nt&&!nt.persisted&&nt.afterLeave&&nt.afterLeave()};if(HA.shapeFlag&1&&nt&&!nt.persisted){const{leave:Xt,delayLeave:$t}=nt,be=()=>Xt(Ve,It);$t?$t(HA.el,It,be):be()}else It()},ki=(HA,ce)=>{let Ve;for(;HA!==ce;)Ve=lA(HA),I(HA),HA=Ve;I(ce)},ns=(HA,ce,Ve)=>{const{bum:Ut,scope:nt,job:It,subTree:Xt,um:$t,m:be,a:Xe}=HA;h8(be),h8(Xe),Ut&&Z1(Ut),nt.stop(),It&&(It.flags|=8,uo(Xt,HA,ce,Ve)),$t&&dE($t,ce),dE(()=>{HA.isUnmounted=!0},ce),ce&&ce.pendingBranch&&!ce.isUnmounted&&HA.asyncDep&&!HA.asyncResolved&&HA.suspenseId===ce.pendingId&&(ce.deps--,ce.deps===0&&ce.resolve())},jo=(HA,ce,Ve,Ut=!1,nt=!1,It=0)=>{for(let Xt=It;Xt{if(HA.shapeFlag&6)return $i(HA.component.subTree);if(HA.shapeFlag&128)return HA.suspense.next();const ce=lA(HA.anchor||HA.el),Ve=ce&&ce[P6];return Ve?lA(Ve):ce};let jt=!1;const io=(HA,ce,Ve)=>{HA==null?ce._vnode&&uo(ce._vnode,null,null,!0):IA(ce._vnode||null,HA,ce,null,null,null,Ve),ce._vnode=HA,jt||(jt=!0,n8(),F6(),jt=!1)},bi={p:IA,um:uo,m:to,r:Vs,mt:je,mc:pt,pc:gi,pbc:_e,n:$i,o:t};return{render:io,hydrate:void 0,createApp:gnA(io)}}function wj({type:t,props:i},r){return r==="svg"&&t==="foreignObject"||r==="mathml"&&t==="annotation-xml"&&i&&i.encoding&&i.encoding.includes("html")?void 0:r}function ZM({effect:t,job:i},r){r?(t.flags|=32,i.flags|=4):(t.flags&=-33,i.flags&=-5)}function BnA(t,i){return(!t||t&&!t.pendingBranch)&&i&&!i.persisted}function NW(t,i,r=!1){const l=t.children,I=i.children;if(Ms(l)&&Ms(I))for(let h=0;h>1,t[r[w]]0&&(i[l]=r[h-1]),r[h]=l)}}for(h=r.length,f=r[h-1];h-- >0;)r[h]=f,f=i[f];return r}function l9(t){const i=t.subTree.component;if(i)return i.asyncDep&&!i.asyncResolved?i:l9(i)}function h8(t){if(t)for(let i=0;iYI(pnA);function cT(t,i){return GW(t,null,i)}function xr(t,i,r){return GW(t,i,r)}function GW(t,i,r=ya){const{immediate:l,deep:I,flush:h,once:f}=r,w=oI({},r),_=i&&l||!i&&h!=="post";let k;if(QU){if(h==="sync"){const rA=mnA();k=rA.__watcherHandles||(rA.__watcherHandles=[])}else if(!_){const rA=()=>{};return rA.stop=vQ,rA.resume=vQ,rA.pause=vQ,rA}}const U=OI;w.call=(rA,mA,IA)=>nB(rA,U,mA,IA);let j=!1;h==="post"?w.scheduler=rA=>{dE(rA,U&&U.suspense)}:h!=="sync"&&(j=!0,w.scheduler=(rA,mA)=>{mA?rA():_W(rA)}),w.augmentJob=rA=>{i&&(rA.flags|=4),j&&(rA.flags|=2,U&&(rA.id=U.uid,rA.i=U))};const lA=GsA(t,i,w);return QU&&(k?k.push(lA):_&&lA()),lA}function fnA(t,i,r){const l=this.proxy,I=fg(t)?t.includes(".")?I9(l,t):()=>l[t]:t.bind(l,l);let h;$s(i)?h=i:(h=i.handler,r=i);const f=kU(this),w=GW(I,h.bind(l),r);return f(),w}function I9(t,i){const r=i.split(".");return()=>{let l=t;for(let I=0;Ii==="modelValue"||i==="model-value"?t.modelModifiers:t[`${i}Modifiers`]||t[`${oh(i)}Modifiers`]||t[`${tD(i)}Modifiers`];function DnA(t,i,...r){if(t.isUnmounted)return;const l=t.vnode.props||ya;let I=r;const h=i.startsWith("update:"),f=h&&ynA(l,i.slice(7));f&&(f.trim&&(I=r.map(U=>fg(U)?U.trim():U)),f.number&&(I=r.map(h3)));let w,_=l[w=mj(i)]||l[w=mj(oh(i))];!_&&h&&(_=l[w=mj(tD(i))]),_&&nB(_,t,6,I);const k=l[w+"Once"];if(k){if(!t.emitted)t.emitted={};else if(t.emitted[w])return;t.emitted[w]=!0,nB(k,t,6,I)}}function u9(t,i,r=!1){const l=i.emitsCache,I=l.get(t);if(I!==void 0)return I;const h=t.emits;let f={},w=!1;if(!$s(t)){const _=k=>{const U=u9(k,i,!0);U&&(w=!0,oI(f,U))};!r&&i.mixins.length&&i.mixins.forEach(_),t.extends&&_(t.extends),t.mixins&&t.mixins.forEach(_)}return!h&&!w?(Na(t)&&l.set(t,null),null):(Ms(h)?h.forEach(_=>f[_]=null):oI(f,h),Na(t)&&l.set(t,f),f)}function rV(t,i){return!t||!ZY(i)?!1:(i=i.slice(2).replace(/Once$/,""),Wr(t,i[0].toLowerCase()+i.slice(1))||Wr(t,tD(i))||Wr(t,i))}function B8(t){const{type:i,vnode:r,proxy:l,withProxy:I,propsOptions:[h],slots:f,attrs:w,emit:_,render:k,renderCache:U,props:j,data:lA,setupState:rA,ctx:mA,inheritAttrs:IA}=t,cA=BY(t);let TA,WA;try{if(r.shapeFlag&4){const ue=I||l,xe=ue;TA=mQ(k.call(xe,ue,U,j,rA,lA,mA)),WA=w}else{const ue=i;TA=mQ(ue.length>1?ue(j,{attrs:w,slots:f,emit:_}):ue(j,null)),WA=i.props?w:SnA(w)}}catch(ue){zL.length=0,iV(ue,t,1),TA=Gt(BE)}let ge=TA;if(WA&&IA!==!1){const ue=Object.keys(WA),{shapeFlag:xe}=ge;ue.length&&xe&7&&(h&&ue.some(pW)&&(WA=MnA(WA,h)),ge=Zy(ge,WA,!1,!0))}return r.dirs&&(ge=Zy(ge,null,!1,!0),ge.dirs=ge.dirs?ge.dirs.concat(r.dirs):r.dirs),r.transition&&CU(ge,r.transition),TA=ge,BY(cA),TA}const SnA=t=>{let i;for(const r in t)(r==="class"||r==="style"||ZY(r))&&((i||(i={}))[r]=t[r]);return i},MnA=(t,i)=>{const r={};for(const l in t)(!pW(l)||!(l.slice(9)in i))&&(r[l]=t[l]);return r};function vnA(t,i,r){const{props:l,children:I,component:h}=t,{props:f,children:w,patchFlag:_}=i,k=h.emitsOptions;if(i.dirs||i.transition)return!0;if(r&&_>=0){if(_&1024)return!0;if(_&16)return l?Q8(l,f,k):!!f;if(_&8){const U=i.dynamicProps;for(let j=0;jt.__isSuspense;function wnA(t,i){i&&i.pendingBranch?Ms(t)?i.effects.push(...t):i.effects.push(t):LsA(t)}const Gr=Symbol.for("v-fgt"),aV=Symbol.for("v-txt"),BE=Symbol.for("v-cmt"),_j=Symbol.for("v-stc"),zL=[];let iC=null;function re(t=!1){zL.push(iC=t?null:[])}function _nA(){zL.pop(),iC=zL[zL.length-1]||null}let hU=1;function p8(t,i=!1){hU+=t,t<0&&iC&&i&&(iC.hasOnce=!0)}function d9(t){return t.dynamicChildren=hU>0?iC||x_:null,_nA(),hU>0&&iC&&iC.push(t),t}function gt(t,i,r,l,I,h){return d9(me(t,i,r,l,I,h,!0))}function Qi(t,i,r,l,I){return d9(Gt(t,i,r,l,I,!0))}function BU(t){return t?t.__v_isVNode===!0:!1}function sv(t,i){return t.type===i.type&&t.key===i.key}const C9=({key:t})=>t??null,$1=({ref:t,ref_key:i,ref_for:r})=>(typeof t=="number"&&(t=""+t),t!=null?fg(t)||tI(t)||$s(t)?{i:eI,r:t,k:i,f:!!r}:t:null);function me(t,i=null,r=null,l=0,I=null,h=t===Gr?0:1,f=!1,w=!1){const _={__v_isVNode:!0,__v_skip:!0,type:t,props:i,key:i&&C9(i),ref:i&&$1(i),scopeId:oV,slotScopeIds:null,children:r,component:null,suspense:null,ssContent:null,ssFallback:null,dirs:null,transition:null,el:null,anchor:null,target:null,targetStart:null,targetAnchor:null,staticCount:0,shapeFlag:h,patchFlag:l,dynamicProps:I,dynamicChildren:null,appContext:null,ctx:eI};return w?(bW(_,r),h&128&&t.normalize(_)):r&&(_.shapeFlag|=fg(r)?8:16),hU>0&&!f&&iC&&(_.patchFlag>0||h&6)&&_.patchFlag!==32&&iC.push(_),_}const Gt=TnA;function TnA(t,i=null,r=null,l=0,I=null,h=!1){if((!t||t===AnA)&&(t=BE),BU(t)){const w=Zy(t,i,!0);return r&&bW(w,r),hU>0&&!h&&iC&&(w.shapeFlag&6?iC[iC.indexOf(t)]=w:iC.push(w)),w.patchFlag=-2,w}if(YnA(t)&&(t=t.__vccOpts),i){i=NnA(i);let{class:w,style:_}=i;w&&!fg(w)&&(i.class=Zi(w)),Na(_)&&(wW(_)&&!Ms(_)&&(_=oI({},_)),i.style=Br(_))}const f=fg(t)?1:E9(t)?128:x6(t)?64:Na(t)?4:$s(t)?2:0;return me(t,i,r,l,I,f,h,!0)}function NnA(t){return t?wW(t)||o9(t)?oI({},t):t:null}function Zy(t,i,r=!1,l=!1){const{props:I,ref:h,patchFlag:f,children:w,transition:_}=t,k=i?R3(I||{},i):I,U={__v_isVNode:!0,__v_skip:!0,type:t.type,props:k,key:k&&C9(k),ref:i&&i.ref?r&&h?Ms(h)?h.concat($1(i)):[h,$1(i)]:$1(i):h,scopeId:t.scopeId,slotScopeIds:t.slotScopeIds,children:w,target:t.target,targetStart:t.targetStart,targetAnchor:t.targetAnchor,staticCount:t.staticCount,shapeFlag:t.shapeFlag,patchFlag:i&&t.type!==Gr?f===-1?16:f|16:f,dynamicProps:t.dynamicProps,dynamicChildren:t.dynamicChildren,appContext:t.appContext,dirs:t.dirs,transition:_,component:t.component,suspense:t.suspense,ssContent:t.ssContent&&Zy(t.ssContent),ssFallback:t.ssFallback&&Zy(t.ssFallback),el:t.el,anchor:t.anchor,ctx:t.ctx,ce:t.ce};return _&&l&&CU(U,_.clone(U)),U}function Da(t=" ",i=0){return Gt(aV,null,t,i)}function ei(t="",i=!1){return i?(re(),Qi(BE,null,t)):Gt(BE,null,t)}function mQ(t){return t==null||typeof t=="boolean"?Gt(BE):Ms(t)?Gt(Gr,null,t.slice()):BU(t)?Ly(t):Gt(aV,null,String(t))}function Ly(t){return t.el===null&&t.patchFlag!==-1||t.memo?t:Zy(t)}function bW(t,i){let r=0;const{shapeFlag:l}=t;if(i==null)i=null;else if(Ms(i))r=16;else if(typeof i=="object")if(l&65){const I=i.default;I&&(I._c&&(I._d=!1),bW(t,I()),I._c&&(I._d=!0));return}else{r=32;const I=i._;!I&&!o9(i)?i._ctx=eI:I===3&&eI&&(eI.slots._===1?i._=1:(i._=2,t.patchFlag|=1024))}else $s(i)?(i={default:i,_ctx:eI},r=32):(i=String(i),l&64?(r=16,i=[Da(i)]):r=8);t.children=i,t.shapeFlag|=r}function R3(...t){const i={};for(let r=0;rOI||eI;let mY,w3;{const t=eV(),i=(r,l)=>{let I;return(I=t[r])||(I=t[r]=[]),I.push(l),h=>{I.length>1?I.forEach(f=>f(h)):I[0](h)}};mY=i("__VUE_INSTANCE_SETTERS__",r=>OI=r),w3=i("__VUE_SSR_SETTERS__",r=>QU=r)}const kU=t=>{const i=OI;return mY(t),t.scope.on(),()=>{t.scope.off(),mY(i)}},m8=()=>{OI&&OI.scope.off(),mY(null)};function h9(t){return t.vnode.shapeFlag&4}let QU=!1;function UnA(t,i=!1,r=!1){i&&w3(i);const{props:l,children:I}=t.vnode,h=h9(t);cnA(t,l,h,i),EnA(t,I,r);const f=h?FnA(t,i):void 0;return i&&w3(!1),f}function FnA(t,i){const r=t.type;t.accessCache=Object.create(null),t.proxy=new Proxy(t.ctx,tnA);const{setup:l}=r;if(l){iD();const I=t.setupContext=l.length>1?PnA(t):null,h=kU(t),f=bU(l,t,0,[t.props,I]),w=u6(f);if(oD(),h(),(w||t.sp)&&!H_(t)&&W6(t),w){if(f.then(m8,m8),i)return f.then(_=>{f8(t,_)}).catch(_=>{iV(_,t,0)});t.asyncDep=f}else f8(t,f)}else B9(t)}function f8(t,i,r){$s(i)?t.type.__ssrInlineRender?t.ssrRender=i:t.render=i:Na(i)&&(t.setupState=b6(i)),B9(t)}function B9(t,i,r){const l=t.type;t.render||(t.render=l.render||vQ);{const I=kU(t);iD();try{inA(t)}finally{oD(),I()}}}const OnA={get(t,i){return Bu(t,"get",""),t[i]}};function PnA(t){const i=r=>{t.exposed=r||{}};return{attrs:new Proxy(t.attrs,OnA),slots:t.slots,emit:t.emit,expose:i}}function gV(t){return t.exposed?t.exposeProxy||(t.exposeProxy=new Proxy(b6(DsA(t.exposed)),{get(i,r){if(r in i)return i[r];if(r in WL)return WL[r](t)},has(i,r){return r in i||r in WL}})):t.proxy}function xnA(t,i=!0){return $s(t)?t.displayName||t.name:t.name||i&&t.__name}function YnA(t){return $s(t)&&"__vccOpts"in t}const bt=(t,i)=>TsA(t,i,QU);function VnA(t,i,r){const l=arguments.length;return l===2?Na(i)&&!Ms(i)?BU(i)?Gt(t,null,[i]):Gt(t,i):Gt(t,null,i):(l>3?r=Array.prototype.slice.call(arguments,2):l===3&&BU(r)&&(r=[r]),Gt(t,i,r))}const _3="3.5.13";/**
+**/function bU(t,i,r,l){try{return l?t(...l):t()}catch(I){iV(I,i,r)}}function rB(t,i,r,l){if($s(t)){const I=bU(t,i,r,l);return I&&E6(I)&&I.catch(h=>{iV(h,i,r)}),I}if(Ms(t)){const I=[];for(let h=0;h