@@ -207,6 +208,10 @@
ref="progressPanelRef"
@open-diagnosis="openDiagnosis"
/>
+
@@ -342,6 +347,7 @@ const EditPopup = defineAsyncComponent(() => import('@/views/tcm/diagnosis/edit.
const AppointmentPopup = defineAsyncComponent(() => import('@/views/tcm/diagnosis/appointment.vue'))
const OrderPanel = defineAsyncComponent(() => import('./components/OrderPanel.vue'))
const ProgressPanel = defineAsyncComponent(() => import('./components/ProgressPanel.vue'))
+const PaibanPanel = defineAsyncComponent(() => import('./components/PaibanPanel.vue'))
type StatusFilter = '' | 'unbooked' | 'pending_interview' | 'completed' | 'missed'
type DateType = 'all' | 'today' | 'tomorrow' | 'day_after' | 'last7' | 'last30' | 'custom'
@@ -355,6 +361,7 @@ const editRef = ref
()
const appointmentRef = ref()
const orderPanelRef = ref()
const progressPanelRef = ref()
+const paibanPanelRef = ref()
const qrcodeDialogVisible = ref(false)
const qrcodeLoading = ref(false)
const qrcodeUrl = ref('')
@@ -423,6 +430,7 @@ const canFillIdCard = computed(() => hasPermission(['tcm.diagnosis/edit']))
const workspaceLoading = computed(() => {
if (activeWorkspace.value === 'orders') return Boolean(orderPanelRef.value?.loading)
if (activeWorkspace.value === 'progress') return Boolean(progressPanelRef.value?.loading)
+ if (activeWorkspace.value === 'paiban') return Boolean(paibanPanelRef.value?.loading)
return pager.loading
})
@@ -437,6 +445,7 @@ function handleFilterChange() {
function refreshPage() {
if (activeWorkspace.value === 'orders') return orderPanelRef.value?.refresh?.()
if (activeWorkspace.value === 'progress') return progressPanelRef.value?.refresh?.()
+ if (activeWorkspace.value === 'paiban') return paibanPanelRef.value?.refresh?.()
return getLists()
}
diff --git a/app/src/doctor_workstation/services/mock_repository.py b/app/src/doctor_workstation/services/mock_repository.py
index c3b8b3522..3dc5b6bf7 100644
--- a/app/src/doctor_workstation/services/mock_repository.py
+++ b/app/src/doctor_workstation/services/mock_repository.py
@@ -5,7 +5,7 @@ from __future__ import annotations
import hashlib
import struct
import zlib
-from collections.abc import Mapping
+from collections.abc import Mapping, Sequence
from copy import deepcopy
from datetime import date, datetime, timedelta
from os import PathLike
@@ -163,8 +163,27 @@ class DemoDoctorRepository:
"room_id": "demo-room-501",
"status": 2,
"status_text": "已结束",
- "recording_status_text": "录制完成",
- "recording_urls_list": ["https://media.example.invalid/demo/diagnosis-501.mp4"],
+ "recording_status_text": "录制完成",
+ "recording_urls_list": ["https://media.example.invalid/demo/diagnosis-501.mp4"],
+ "transcription_status": "completed",
+ "transcription_status_text": "文字已生成",
+ "transcript_text": "患者:最近睡眠比上周好一些。\n医生:继续记录睡眠和空腹血糖。",
+ "transcript_segments": [
+ {
+ "segment_id": "demo-1",
+ "speaker_role": "patient",
+ "speaker_user_id": "patient_301",
+ "timestamp": 1,
+ "text": "最近睡眠比上周好一些。",
+ },
+ {
+ "segment_id": "demo-2",
+ "speaker_role": "doctor",
+ "speaker_user_id": "doctor_1001",
+ "timestamp": 2,
+ "text": "继续记录睡眠和空腹血糖。",
+ },
+ ],
"start_time_text": f"{self._today.isoformat()} 09:10:00",
"end_time_text": f"{self._today.isoformat()} 09:22:00",
"duration_text": "12分00秒",
@@ -2233,8 +2252,12 @@ class DemoDoctorRepository:
"room_id": "manual-upload",
"status": 2,
"status_text": "已结束",
- "recording_status_text": "待上传",
- "recording_urls_list": [],
+ "recording_status_text": "待上传",
+ "recording_urls_list": [],
+ "transcription_status": "not_started",
+ "transcription_status_text": "未生成文字",
+ "transcript_text": "",
+ "transcript_segments": [],
"start_time_text": datetime.now().replace(microsecond=0).isoformat(sep=" "),
"end_time_text": datetime.now().replace(microsecond=0).isoformat(sep=" "),
"duration_text": "0秒",
@@ -2531,8 +2554,12 @@ class DemoDoctorRepository:
replay = {
**record,
"status_text": "呼叫中",
- "recording_status_text": "未录制",
- "recording_urls_list": [],
+ "recording_status_text": "未录制",
+ "recording_urls_list": [],
+ "transcription_status": "not_started",
+ "transcription_status_text": "未生成文字",
+ "transcript_text": "",
+ "transcript_segments": [],
"start_time_text": datetime.now().replace(microsecond=0).isoformat(sep=" "),
"end_time_text": "",
"duration_text": "—",
@@ -2567,7 +2594,7 @@ class DemoDoctorRepository:
)
return deepcopy(record)
- def bind_call_room(self, diagnosis_id: int, room_id: str) -> dict[str, Any]:
+ def bind_call_room(self, diagnosis_id: int, room_id: str) -> dict[str, Any]:
"""Persist the room identifier on the active demo call."""
if not room_id.strip():
@@ -2594,11 +2621,133 @@ class DemoDoctorRepository:
"status_text": "通话中",
}
)
- return {
- "diagnosis_id": diagnosis_id,
- "room_id": room_id.strip(),
- "cloud_recording": {"started": False, "message": "演示模式不录制"},
- }
+ return {
+ "diagnosis_id": diagnosis_id,
+ "room_id": room_id.strip(),
+ "cloud_recording": {"started": False, "message": "演示模式不录制"},
+ }
+
+ def _demo_call_record(
+ self, diagnosis_id: int, call_record_id: int | str
+ ) -> dict[str, Any]:
+ record = next(
+ (
+ row
+ for row in self._call_records.get(diagnosis_id, [])
+ if str(row.get("id") or row.get("call_record_id") or "")
+ == str(call_record_id)
+ ),
+ None,
+ )
+ if record is None:
+ raise RepositoryNotFoundError(f"call record {call_record_id} not found")
+ return record
+
+ def start_call_transcription(
+ self,
+ diagnosis_id: int,
+ call_record_id: int | str,
+ transcription_session_id: str,
+ *,
+ language: str = "zh-CN",
+ ) -> dict[str, Any]:
+ """Start an in-memory transcript attached to one demo call record."""
+
+ clean_session = transcription_session_id.strip()
+ if not clean_session:
+ raise ValueError("transcription_session_id is required")
+ with self._lock:
+ self._find_consultation(diagnosis_id)
+ record = self._demo_call_record(diagnosis_id, call_record_id)
+ existing = str(record.get("transcription_session_id") or "")
+ if existing and existing != clean_session:
+ raise ValueError("another transcription session already exists")
+ record.update(
+ {
+ "transcription_session_id": clean_session,
+ "transcription_language": language.strip() or "zh-CN",
+ "transcription_status": "running",
+ "transcription_status_text": "录音转写中",
+ "transcript_text": "",
+ "transcript_segments": [],
+ }
+ )
+ return deepcopy(record)
+
+ def upsert_call_transcript_segments(
+ self,
+ diagnosis_id: int,
+ call_record_id: int | str,
+ transcription_session_id: str,
+ segments: Sequence[Mapping[str, Any]],
+ ) -> dict[str, Any]:
+ """Idempotently append/update completed segments in demo mode."""
+
+ with self._lock:
+ record = self._demo_call_record(diagnosis_id, call_record_id)
+ if record.get("transcription_session_id") != transcription_session_id:
+ raise ValueError("transcription session does not match the call record")
+ stored = record.setdefault("transcript_segments", [])
+ for incoming in segments:
+ segment_id = str(incoming.get("segment_id") or "").strip()
+ text = str(incoming.get("text") or "").strip()
+ if not segment_id or not text:
+ raise ValueError("transcript segment_id and text are required")
+ normalized = {
+ "segment_id": segment_id,
+ "speaker_role": str(incoming.get("speaker_role") or "unknown"),
+ "speaker_user_id": str(incoming.get("speaker_user_id") or ""),
+ "timestamp": int(incoming.get("timestamp") or 0),
+ "text": text,
+ }
+ current = next(
+ (row for row in stored if row.get("segment_id") == segment_id), None
+ )
+ if current is None:
+ stored.append(normalized)
+ else:
+ current.update(normalized)
+ stored.sort(key=lambda row: (int(row.get("timestamp") or 0), row["segment_id"]))
+ labels = {"doctor": "医生", "patient": "患者", "unknown": "未知说话人"}
+ record["transcript_text"] = "\n".join(
+ f"{labels.get(str(row.get('speaker_role')), '未知说话人')}:{row['text']}"
+ for row in stored
+ )
+ return deepcopy(record)
+
+ def finish_call_transcription(
+ self,
+ diagnosis_id: int,
+ call_record_id: int | str,
+ transcription_session_id: str,
+ expected_segment_count: int,
+ *,
+ status: str = "completed",
+ ) -> dict[str, Any]:
+ """Finalize demo transcript fields on the same call record."""
+
+ clean_status = status.strip().lower()
+ if clean_status not in {"completed", "partial", "failed"}:
+ raise ValueError("transcription status is invalid")
+ with self._lock:
+ record = self._demo_call_record(diagnosis_id, call_record_id)
+ if record.get("transcription_session_id") != transcription_session_id:
+ raise ValueError("transcription session does not match the call record")
+ actual_count = len(record.get("transcript_segments") or [])
+ final_status = clean_status
+ if clean_status == "completed" and actual_count < expected_segment_count:
+ final_status = "partial"
+ record["transcription_status"] = final_status
+ record["transcription_status_text"] = {
+ "completed": "文字已生成",
+ "partial": "文字部分保存",
+ "failed": "文字生成失败",
+ }[final_status]
+ record["transcription_segment_count"] = actual_count
+ record["transcription_finished_at"] = datetime.now().replace(
+ microsecond=0
+ ).isoformat(sep=" ")
+ return deepcopy(record)
def my_self(self) -> Session:
"""Compatibility alias for :meth:`get_session`."""
diff --git a/app/src/doctor_workstation/services/repository.py b/app/src/doctor_workstation/services/repository.py
index 97d34f9de..57c450e3f 100644
--- a/app/src/doctor_workstation/services/repository.py
+++ b/app/src/doctor_workstation/services/repository.py
@@ -5,7 +5,7 @@ from __future__ import annotations
import mimetypes
import re
import time
-from collections.abc import Mapping
+from collections.abc import Mapping, Sequence
from contextlib import suppress
from datetime import date
from io import BytesIO
@@ -619,8 +619,38 @@ class DoctorRepository(Protocol):
def end_call(self, diagnosis_id: int) -> Any:
"""End the active diagnosis call."""
- def bind_call_room(self, diagnosis_id: int, room_id: str) -> Any:
- """Bind a TRTC room to the active call."""
+ def bind_call_room(self, diagnosis_id: int, room_id: str) -> Any:
+ """Bind a TRTC room to the active call."""
+
+ def start_call_transcription(
+ self,
+ diagnosis_id: int,
+ call_record_id: int | str,
+ transcription_session_id: str,
+ *,
+ language: str = "zh-CN",
+ ) -> Any:
+ """Start a transcript stored on one exact call record."""
+
+ def upsert_call_transcript_segments(
+ self,
+ diagnosis_id: int,
+ call_record_id: int | str,
+ transcription_session_id: str,
+ segments: Sequence[Mapping[str, Any]],
+ ) -> Any:
+ """Idempotently persist completed transcript segments."""
+
+ def finish_call_transcription(
+ self,
+ diagnosis_id: int,
+ call_record_id: int | str,
+ transcription_session_id: str,
+ expected_segment_count: int,
+ *,
+ status: str = "completed",
+ ) -> Any:
+ """Finalize and materialize the transcript text on a call record."""
def my_self(self) -> Session:
"""Compatibility alias for :meth:`get_session`."""
@@ -2171,32 +2201,157 @@ class RemoteDoctorRepository:
ticket.diagnosis_id = diagnosis_id
return ticket
- def start_call(self, diagnosis_id: int, patient_id: int, *, call_type: int = 2) -> Any:
- """Create the server-side call record before ringing participants."""
-
- return self.client.post(
- "tcm.diagnosis/startCall",
- {
- "diagnosis_id": diagnosis_id,
- "patient_id": patient_id,
- "call_type": call_type,
- },
- )
+ def start_call(self, diagnosis_id: int, patient_id: int, *, call_type: int = 2) -> Any:
+ """Create the server-side call record before ringing participants."""
+
+ payload = self.client.post(
+ "tcm.diagnosis/startCall",
+ {
+ "diagnosis_id": diagnosis_id,
+ "patient_id": patient_id,
+ "call_type": call_type,
+ },
+ )
+ if not isinstance(payload, Mapping):
+ raise ApiProtocolError(
+ "tcm.diagnosis/startCall returned no valid call_record_id object", data=payload
+ )
+ raw_id = next(
+ (
+ payload[key]
+ for key in ("call_record_id", "callRecordId", "id")
+ if key in payload
+ ),
+ None,
+ )
+ try:
+ if isinstance(raw_id, bool):
+ raise ValueError
+ call_record_id = int(raw_id)
+ except (TypeError, ValueError) as exc:
+ raise ApiProtocolError(
+ "tcm.diagnosis/startCall returned no valid call_record_id",
+ data=dict(payload),
+ ) from exc
+ if call_record_id <= 0:
+ raise ApiProtocolError(
+ "tcm.diagnosis/startCall returned no valid call_record_id",
+ data=dict(payload),
+ )
+ return {"call_record_id": call_record_id}
def end_call(self, diagnosis_id: int) -> Any:
"""End the active call/recording associated with a diagnosis."""
return self.client.post("tcm.diagnosis/endCall", {"diagnosis_id": diagnosis_id})
- def bind_call_room(self, diagnosis_id: int, room_id: str) -> Any:
- """Bind the actual TRTC room to the active call record."""
+ def bind_call_room(self, diagnosis_id: int, room_id: str) -> Any:
+ """Bind the actual TRTC room to the active call record."""
if not room_id.strip():
raise ValueError("room_id is required")
- return self.client.post(
- "tcm.diagnosis/bindCallRoom",
- {"diagnosis_id": diagnosis_id, "room_id": room_id.strip()},
- )
+ return self.client.post(
+ "tcm.diagnosis/bindCallRoom",
+ {"diagnosis_id": diagnosis_id, "room_id": room_id.strip()},
+ )
+
+ @staticmethod
+ def _transcription_identity(
+ diagnosis_id: int,
+ call_record_id: int | str,
+ transcription_session_id: str,
+ ) -> dict[str, Any]:
+ if diagnosis_id <= 0:
+ raise ValueError("diagnosis_id must be positive")
+ if isinstance(call_record_id, bool) or not str(call_record_id).strip():
+ raise ValueError("call_record_id is required")
+ clean_session = transcription_session_id.strip()
+ if not clean_session or len(clean_session) > 128:
+ raise ValueError("transcription_session_id must contain 1 to 128 characters")
+ return {
+ "diagnosis_id": diagnosis_id,
+ "call_record_id": call_record_id,
+ "transcription_session_id": clean_session,
+ }
+
+ def start_call_transcription(
+ self,
+ diagnosis_id: int,
+ call_record_id: int | str,
+ transcription_session_id: str,
+ *,
+ language: str = "zh-CN",
+ ) -> Any:
+ """Create the server transcript session for one call record."""
+
+ body = self._transcription_identity(
+ diagnosis_id, call_record_id, transcription_session_id
+ )
+ body["language"] = language.strip()[:32] or "zh-CN"
+ return self.client.post("tcm.diagnosis/startCallTranscription", body)
+
+ def upsert_call_transcript_segments(
+ self,
+ diagnosis_id: int,
+ call_record_id: int | str,
+ transcription_session_id: str,
+ segments: Sequence[Mapping[str, Any]],
+ ) -> Any:
+ """Upsert a bounded batch using each segment_id as the idempotency key."""
+
+ body = self._transcription_identity(
+ diagnosis_id, call_record_id, transcription_session_id
+ )
+ normalized: list[dict[str, Any]] = []
+ if len(segments) > 50:
+ raise ValueError("at most 50 transcript segments may be submitted at once")
+ for segment in segments:
+ segment_id = str(segment.get("segment_id") or "").strip()
+ text = str(segment.get("text") or "").strip()
+ if not segment_id or len(segment_id) > 160:
+ raise ValueError("transcript segment_id is invalid")
+ if not text or len(text) > 4_000:
+ raise ValueError("transcript text is invalid")
+ normalized.append(
+ {
+ "segment_id": segment_id,
+ "speaker_user_id": str(segment.get("speaker_user_id") or "")[:160],
+ "speaker_role": str(segment.get("speaker_role") or "unknown")[:20],
+ "timestamp": max(int(segment.get("timestamp") or 0), 0),
+ "text": text,
+ }
+ )
+ if not normalized:
+ raise ValueError("at least one transcript segment is required")
+ body["segments"] = normalized
+ return self.client.post("tcm.diagnosis/upsertCallTranscriptSegments", body)
+
+ def finish_call_transcription(
+ self,
+ diagnosis_id: int,
+ call_record_id: int | str,
+ transcription_session_id: str,
+ expected_segment_count: int,
+ *,
+ status: str = "completed",
+ ) -> Any:
+ """Finalize a transcript; repeated requests use the same session identity."""
+
+ body = self._transcription_identity(
+ diagnosis_id, call_record_id, transcription_session_id
+ )
+ clean_status = status.strip().lower()
+ if clean_status not in {"completed", "partial", "failed"}:
+ raise ValueError("transcription status is invalid")
+ if expected_segment_count < 0:
+ raise ValueError("expected_segment_count must not be negative")
+ body.update(
+ {
+ "expected_segment_count": expected_segment_count,
+ "status": clean_status,
+ }
+ )
+ return self.client.post("tcm.diagnosis/finishCallTranscription", body)
# Compatibility aliases keep UI naming independent from endpoint history.
def my_self(self) -> Session:
diff --git a/app/src/doctor_workstation/ui/dialogs/diagnosis.py b/app/src/doctor_workstation/ui/dialogs/diagnosis.py
index 144847b46..e92a14078 100644
--- a/app/src/doctor_workstation/ui/dialogs/diagnosis.py
+++ b/app/src/doctor_workstation/ui/dialogs/diagnosis.py
@@ -20,6 +20,7 @@ from PySide6.QtWidgets import (
QInputDialog,
QLabel,
QMessageBox,
+ QPlainTextEdit,
QPushButton,
QScrollArea,
QSizePolicy,
@@ -1411,7 +1412,7 @@ class DiagnosisDialog(QDialog):
layout.setContentsMargins(16, 14, 16, 18)
layout.setSpacing(12)
toolbar = QHBoxLayout()
- hint = QLabel("每条通话记录可包含多个回放地址,并可追加指定记录的视频。")
+ hint = QLabel("每条通话记录可包含多个回放地址;录音转写完成后可查看本次面诊对话文字。")
hint.setObjectName("DiagnosisDialogGuidance")
hint.setWordWrap(True)
toolbar.addWidget(hint, 1)
@@ -1553,7 +1554,7 @@ class DiagnosisDialog(QDialog):
("房间号", 180),
("时长", 110),
("状态", 90),
- ("录制", 100),
+ ("录制 / 文字", 120),
("操作", 130),
),
"assign": (
@@ -3365,11 +3366,71 @@ class DiagnosisDialog(QDialog):
cell.stop()
self._inline_recording_cells.clear()
+ @staticmethod
+ def _call_transcript_text(row: Any) -> str:
+ raw = first_value(
+ row,
+ "transcript_text",
+ "call_transcript",
+ "conversation_text",
+ "transcript",
+ default="",
+ )
+ if isinstance(raw, Mapping):
+ raw = first_value(raw, "text", "full_text", "content", default="")
+ text = str(raw or "").strip()
+ if text:
+ return text
+ segments = first_value(row, "transcript_segments", "segments", default=[]) or []
+ if isinstance(segments, Sequence) and not isinstance(
+ segments, (str, bytes, bytearray)
+ ):
+ labels = {"doctor": "医生", "patient": "患者", "unknown": "未知说话人"}
+ lines: list[str] = []
+ for segment in segments:
+ content = str(first_value(segment, "text", "sourceText", default="") or "").strip()
+ if not content:
+ continue
+ role = str(
+ first_value(segment, "speaker_role", "speakerRole", default="unknown")
+ or "unknown"
+ )
+ lines.append(f"{labels.get(role, '未知说话人')}:{content}")
+ return "\n".join(lines)
+ return ""
+
+ def _view_call_transcript(self, call_record_id: int, transcript: str) -> None:
+ dialog = QDialog(self)
+ dialog.setObjectName("DiagnosisCallTranscriptDialog")
+ dialog.setWindowTitle(f"面诊对话文字 · 通话记录 #{call_record_id}")
+ dialog.resize(680, 520)
+ layout = QVBoxLayout(dialog)
+ layout.setContentsMargins(20, 18, 20, 18)
+ layout.setSpacing(12)
+ title = QLabel("录音转写对话")
+ title.setObjectName("DiagnosisDailySectionTitle")
+ layout.addWidget(title)
+ hint = QLabel("以下内容由语音自动转写,仅作为面诊记录辅助,请由医生核对。")
+ hint.setObjectName("DiagnosisDialogGuidance")
+ hint.setWordWrap(True)
+ layout.addWidget(hint)
+ content = QPlainTextEdit(dialog)
+ content.setObjectName("DiagnosisCallTranscriptText")
+ content.setReadOnly(True)
+ content.setPlainText(transcript)
+ layout.addWidget(content, 1)
+ close_button = QPushButton("关闭")
+ close_button.setProperty("variant", "primary")
+ close_button.clicked.connect(dialog.accept)
+ layout.addWidget(close_button, 0, Qt.AlignmentFlag.AlignRight)
+ dialog.exec()
+
def _fill_video(self, rows: Sequence[Any]) -> None:
self._stop_inline_recordings()
matrix: list[tuple[Any, ...]] = []
row_urls: list[list[str]] = []
record_ids: list[int] = []
+ transcripts: list[str] = []
for row in rows:
raw_urls = first_value(row, "recording_urls_list", "recording_urls", default=[]) or []
if isinstance(raw_urls, str) or not isinstance(raw_urls, Sequence):
@@ -3382,6 +3443,8 @@ class DiagnosisDialog(QDialog):
normalized.append(url)
row_urls.append(normalized)
record_ids.append(_int(first_value(row, "id", "call_record_id"), 0))
+ transcript = self._call_transcript_text(row)
+ transcripts.append(transcript)
call_type = _raw_value(row, "call_type_text")
if call_type is _MISSING:
raw_call_type = _raw_value(row, "call_type")
@@ -3398,6 +3461,15 @@ class DiagnosisDialog(QDialog):
3: "未接听",
4: "已取消",
}.get(_int(raw_status, -1), "—")
+ recording_status = first_value(
+ row, "recording_status_text", "record_status_text", "record_status"
+ )
+ transcript_status = first_value(
+ row,
+ "transcription_status_text",
+ "transcript_status_text",
+ default="文字已生成" if transcript else "未生成文字",
+ )
matrix.append(
(
"" if normalized else "暂无录制回放",
@@ -3407,9 +3479,7 @@ class DiagnosisDialog(QDialog):
first_value(row, "room_id", "room_no"),
first_value(row, "duration_text", "duration"),
status,
- first_value(
- row, "recording_status_text", "record_status_text", "record_status"
- ),
+ f"{display_text(recording_status)}\n{display_text(transcript_status)}",
"",
)
)
@@ -3434,6 +3504,20 @@ class DiagnosisDialog(QDialog):
if item is not None:
item.setText("")
call_record_id = record_ids[row_index]
+ actions: list[QPushButton] = []
+ transcript = transcripts[row_index]
+ if transcript and call_record_id > 0:
+ view_transcript = self._action_button(
+ "查看文字", f"查看通话记录 #{call_record_id} 的录音转写"
+ )
+ view_transcript.setObjectName("DiagnosisVideoTranscriptView")
+ view_transcript.setProperty("callRecordId", call_record_id)
+ view_transcript.clicked.connect(
+ lambda _checked=False, selected=call_record_id, text=transcript: self._view_call_transcript(
+ selected, text
+ )
+ )
+ actions.append(view_transcript)
if self._editable and self._can_video_upload and call_record_id > 0:
upload = self._action_button(
"追加回放", f"上传并绑定通话记录 #{call_record_id}"
@@ -3452,12 +3536,16 @@ class DiagnosisDialog(QDialog):
selected
)
)
- upload_host = QWidget()
- upload_host.setObjectName("DiagnosisVideoRowUploadCell")
- upload_layout = QVBoxLayout(upload_host)
- upload_layout.setContentsMargins(0, 0, 0, 0)
- upload_layout.addWidget(upload, 0, Qt.AlignmentFlag.AlignCenter)
- table.setCellWidget(row_index, 8, upload_host)
+ actions.append(upload)
+ if actions:
+ action_host = QWidget()
+ action_host.setObjectName("DiagnosisVideoRowUploadCell")
+ action_layout = QVBoxLayout(action_host)
+ action_layout.setContentsMargins(0, 0, 0, 0)
+ action_layout.setSpacing(2)
+ for action in actions:
+ action_layout.addWidget(action, 0, Qt.AlignmentFlag.AlignCenter)
+ table.setCellWidget(row_index, 8, action_host)
upload_item = table.item(row_index, 8)
if upload_item is not None:
upload_item.setText("")
diff --git a/app/src/doctor_workstation/video/launcher.py b/app/src/doctor_workstation/video/launcher.py
index d59f1ae7c..8104efea9 100644
--- a/app/src/doctor_workstation/video/launcher.py
+++ b/app/src/doctor_workstation/video/launcher.py
@@ -130,6 +130,7 @@ def _ticket_mapping(ticket: Any) -> Mapping[str, Any]:
"patientUserId": "patient_user_id",
"diagnosisId": "diagnosis_id",
"patientId": "patient_id",
+ "callRecordId": "call_record_id",
}
adapted = {
json_name: getattr(ticket, attribute_name)
@@ -196,6 +197,7 @@ class VideoCallRequest:
target_user_id: str
diagnosis_id: Identifier
patient_id: Identifier | None = None
+ call_record_id: Identifier | None = None
backend_mode: BackendMode = BackendMode.EMBEDDED
def __post_init__(self) -> None:
@@ -218,6 +220,12 @@ class VideoCallRequest:
"patient_id",
_identifier(self.patient_id, "patientId"),
)
+ if self.call_record_id is not None:
+ object.__setattr__(
+ self,
+ "call_record_id",
+ _identifier(self.call_record_id, "callRecordId"),
+ )
object.__setattr__(self, "backend_mode", BackendMode.parse(self.backend_mode))
@classmethod
@@ -257,6 +265,7 @@ class VideoCallRequest:
return {
"diagnosis_id": self.diagnosis_id,
"patient_id": self.patient_id,
+ "call_record_id": self.call_record_id,
"backend_mode": self.backend_mode.value,
}
@@ -285,6 +294,13 @@ def normalize_backend_ticket(
_identifier,
required=False,
)
+ payload_call_record = _read_aliases(
+ payload,
+ ("callRecordId", "call_record_id"),
+ "callRecordId",
+ _identifier,
+ required=False,
+ )
normalized_diagnosis = _merge_identifier(
payload_diagnosis,
@@ -323,6 +339,7 @@ def normalize_backend_ticket(
),
diagnosis_id=normalized_diagnosis,
patient_id=normalized_patient,
+ call_record_id=payload_call_record,
backend_mode=BackendMode.parse(backend_mode),
)
diff --git a/app/src/doctor_workstation/video/lifecycle.py b/app/src/doctor_workstation/video/lifecycle.py
index 97c7ca4ff..0a9906ce0 100644
--- a/app/src/doctor_workstation/video/lifecycle.py
+++ b/app/src/doctor_workstation/video/lifecycle.py
@@ -74,6 +74,71 @@ def _call_repository_method(method: Callable[..., Any], payload: Mapping[str, An
return _resolve_result(result)
+def _mapping_candidate(value: Any) -> Mapping[str, Any] | None:
+ if isinstance(value, Mapping):
+ return value
+ for attribute in ("raw", "data"):
+ candidate = getattr(value, attribute, None)
+ if isinstance(candidate, Mapping):
+ return candidate
+ return None
+
+
+def _extract_call_record_id(result: Any) -> int | str | None:
+ """Read a positive call-record identity from common backend envelopes."""
+
+ pending = [result]
+ visited: set[int] = set()
+ while pending:
+ candidate = pending.pop(0)
+ mapping = _mapping_candidate(candidate)
+ if mapping is None or id(mapping) in visited:
+ continue
+ visited.add(id(mapping))
+ for key in ("call_record_id", "callRecordId", "id"):
+ value = mapping.get(key)
+ if isinstance(value, bool) or value is None:
+ continue
+ if isinstance(value, int) and value > 0:
+ return value
+ if isinstance(value, str) and value.strip():
+ return value.strip()
+ for key in ("data", "result", "record", "call_record", "callRecord"):
+ nested = mapping.get(key)
+ if isinstance(nested, Mapping):
+ pending.append(nested)
+ return None
+
+
+def _clean_transcript_segment(segment: Mapping[str, Any], session_id: str) -> dict[str, Any]:
+ segment_id = str(segment.get("segment_id", segment.get("segmentId", ""))).strip()
+ text = str(segment.get("text", segment.get("sourceText", ""))).strip()
+ speaker_user_id = str(
+ segment.get("speaker_user_id", segment.get("speakerUserId", ""))
+ ).strip()
+ speaker_role = str(segment.get("speaker_role", segment.get("speakerRole", "unknown"))).strip()
+ if not segment_id or len(segment_id) > 160:
+ raise ValueError("transcript segment_id must contain 1 to 160 characters")
+ if not text or len(text) > 4_000:
+ raise ValueError("transcript text must contain 1 to 4000 characters")
+ if len(speaker_user_id) > 160:
+ raise ValueError("transcript speaker_user_id is too long")
+ if speaker_role not in {"doctor", "patient", "unknown"}:
+ speaker_role = "unknown"
+ try:
+ timestamp = int(segment.get("timestamp") or 0)
+ except (TypeError, ValueError):
+ timestamp = 0
+ return {
+ "segment_id": segment_id,
+ "transcription_session_id": session_id,
+ "speaker_user_id": speaker_user_id,
+ "speaker_role": speaker_role,
+ "timestamp": max(timestamp, 0),
+ "text": text,
+ }
+
+
@dataclass(slots=True)
class _WorkItem:
operation: str
@@ -169,11 +234,17 @@ class OrderedCallLifecycle:
self.logger = logger
self.started = False
self.ended = False
+ self.call_record_id: int | str | None = request.call_record_id
self.bound_room_id: str | None = None
self._claimed_room_id: str | None = None
self._start_future: Future[bool] | None = None
self._bind_future: Future[bool] | None = None
self._end_future: Future[bool] | None = None
+ self._transcription_start_future: Future[bool] | None = None
+ self._transcription_finish_future: Future[bool] | None = None
+ self._transcription_session_id: str | None = None
+ self._transcription_active = False
+ self._segment_futures: dict[str, Future[bool]] = {}
self._lock = threading.RLock()
self._worker = _OrderedDaemonWorker(logger, request.safe_log_context())
@@ -181,6 +252,10 @@ class OrderedCallLifecycle:
def worker_is_daemon(self) -> bool:
return self._worker.is_daemon
+ @property
+ def transcription_session_id(self) -> str | None:
+ return self._transcription_session_id
+
def start(self) -> Future[bool]:
with self._lock:
if self._start_future is not None:
@@ -196,9 +271,13 @@ class OrderedCallLifecycle:
payload["patient_id"] = self.request.patient_id
def operation() -> bool:
- _call_repository_method(method, payload)
+ result = _call_repository_method(method, payload)
+ record_id = _extract_call_record_id(result)
+ if record_id is None:
+ raise ValueError("startCall response did not include the current call_record_id")
with self._lock:
self.started = True
+ self.call_record_id = record_id
self.logger.info(
"video call record started",
extra={"video_call": self.request.safe_log_context()},
@@ -309,10 +388,167 @@ class OrderedCallLifecycle:
return self._worker.submit("screenshot", operation)
+ def start_transcription(self, session_id: str, *, language: str = "zh-CN") -> Future[bool]:
+ """Start persisted realtime transcription for this exact call record."""
+
+ clean_session = str(session_id or "").strip()
+ clean_language = str(language or "zh-CN").strip()[:32] or "zh-CN"
+ if not clean_session or len(clean_session) > 128:
+ raise ValueError("transcription session id must contain 1 to 128 characters")
+ with self._lock:
+ if self._end_future is not None:
+ raise RuntimeError("video call has already ended")
+ if self._transcription_start_future is not None:
+ if self._transcription_session_id != clean_session:
+ raise RuntimeError("another transcription session already exists")
+ return self._transcription_start_future
+ if self._start_future is None:
+ self.start()
+ method = getattr(self.repository, "start_call_transcription", None)
+ if not callable(method):
+ raise ValueError("video repository does not implement call transcription storage")
+ self._transcription_session_id = clean_session
+
+ def operation() -> bool:
+ with self._lock:
+ started = self.started
+ record_id = self.call_record_id
+ if not started:
+ return False
+ if record_id is None:
+ raise ValueError("server did not return the current call_record_id")
+ _call_repository_method(
+ method,
+ {
+ "diagnosis_id": self.request.diagnosis_id,
+ "call_record_id": record_id,
+ "transcription_session_id": clean_session,
+ "language": clean_language,
+ },
+ )
+ with self._lock:
+ self._transcription_active = True
+ self.logger.info(
+ "video call transcription started",
+ extra={"video_call": self.request.safe_log_context()},
+ )
+ return True
+
+ self._transcription_start_future = self._worker.submit(
+ "transcription-start", operation
+ )
+ return self._transcription_start_future
+
+ def save_transcript_segment(self, segment: Mapping[str, Any]) -> Future[bool]:
+ """Upsert one completed, bounded transcript segment without logging its text."""
+
+ with self._lock:
+ session_id = self._transcription_session_id
+ if not session_id or self._transcription_start_future is None:
+ raise RuntimeError("call transcription has not started")
+ if self._transcription_finish_future is not None:
+ raise RuntimeError("call transcription has already stopped")
+ cleaned = _clean_transcript_segment(segment, session_id)
+ segment_id = cleaned["segment_id"]
+ existing = self._segment_futures.get(segment_id)
+ if existing is not None:
+ return existing
+ method = getattr(self.repository, "upsert_call_transcript_segments", None)
+ if not callable(method):
+ raise ValueError("video repository does not implement transcript segment storage")
+
+ def operation() -> bool:
+ with self._lock:
+ active = self._transcription_active
+ record_id = self.call_record_id
+ if not active:
+ return False
+ if record_id is None:
+ raise ValueError("server did not return the current call_record_id")
+ _call_repository_method(
+ method,
+ {
+ "diagnosis_id": self.request.diagnosis_id,
+ "call_record_id": record_id,
+ "transcription_session_id": session_id,
+ "segments": [cleaned],
+ },
+ )
+ return True
+
+ future = self._worker.submit("transcription-segment", operation)
+ self._segment_futures[segment_id] = future
+
+ def release_failed(completed: Future[bool]) -> None:
+ if completed.cancelled() or completed.exception() is not None:
+ with self._lock:
+ if self._segment_futures.get(segment_id) is completed:
+ self._segment_futures.pop(segment_id, None)
+
+ future.add_done_callback(release_failed)
+ return future
+
+ def finish_transcription(self, *, status: str = "completed") -> Future[bool]:
+ """Flush and finalize the current transcript exactly once."""
+
+ clean_status = str(status or "completed").strip().lower()
+ if clean_status not in {"completed", "partial", "failed"}:
+ raise ValueError("transcription status is invalid")
+ with self._lock:
+ if self._transcription_finish_future is not None:
+ return self._transcription_finish_future
+ if self._transcription_start_future is None or not self._transcription_session_id:
+ return _settled_future(False)
+ method = getattr(self.repository, "finish_call_transcription", None)
+ if not callable(method):
+ raise ValueError("video repository does not implement transcription finalization")
+ session_id = self._transcription_session_id
+
+ def operation() -> bool:
+ with self._lock:
+ active = self._transcription_active
+ record_id = self.call_record_id
+ expected_count = len(self._segment_futures)
+ if not active:
+ return False
+ if record_id is None:
+ raise ValueError("server did not return the current call_record_id")
+ _call_repository_method(
+ method,
+ {
+ "diagnosis_id": self.request.diagnosis_id,
+ "call_record_id": record_id,
+ "transcription_session_id": session_id,
+ "expected_segment_count": expected_count,
+ "status": clean_status,
+ },
+ )
+ with self._lock:
+ self._transcription_active = False
+ self.logger.info(
+ "video call transcription finalized",
+ extra={
+ "video_call": self.request.safe_log_context(),
+ "transcription_status": clean_status,
+ "segment_count": expected_count,
+ },
+ )
+ return True
+
+ self._transcription_finish_future = self._worker.submit(
+ "transcription-finish", operation
+ )
+ return self._transcription_finish_future
+
def end(self, reason: str) -> Future[bool]:
with self._lock:
if self._end_future is not None:
return self._end_future
+ if (
+ self._transcription_start_future is not None
+ and self._transcription_finish_future is None
+ ):
+ self.finish_transcription(status="partial")
method = getattr(self.repository, "end_call", None)
def operation() -> bool:
diff --git a/app/src/doctor_workstation/video/window.py b/app/src/doctor_workstation/video/window.py
index 9bf05f01d..32112f0f7 100644
--- a/app/src/doctor_workstation/video/window.py
+++ b/app/src/doctor_workstation/video/window.py
@@ -210,6 +210,7 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
call_error = Signal(str) # type: ignore[misc]
_start_completed = Signal(bool) # type: ignore[misc]
_screenshot_completed = Signal(bool, str) # type: ignore[misc]
+ _transcription_completed = Signal(str, str, str, bool, str) # type: ignore[misc]
def __init__(
self,
@@ -284,6 +285,7 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
self._start_completed.connect(self._on_lifecycle_started)
self._screenshot_completed.connect(self._on_screenshot_completed)
+ self._transcription_completed.connect(self._on_transcription_completed)
self.web_view.loadFinished.connect(self._on_load_finished)
self.web_view.setUrl(QUrl(self.location.url))
@@ -426,6 +428,21 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
str(message.get("message") or "截屏图片无效。")[:200],
)
return
+ if event == "transcription-start-request":
+ self._start_transcription(
+ str(message.get("sessionId") or ""),
+ str(message.get("language") or "zh-CN"),
+ )
+ return
+ if event == "transcription-segment":
+ self._save_transcript_segment(message)
+ return
+ if event == "transcription-stop":
+ self._finish_transcription(
+ str(message.get("sessionId") or ""),
+ str(message.get("status") or "completed"),
+ )
+ return
room_id = message.get("roomId", message.get("room_id"))
if room_id not in (None, ""):
self.lifecycle.bind_room(room_id)
@@ -434,8 +451,6 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
if event == "status":
status = str(message.get("status", "unknown"))[:80]
self.status_changed.emit(status)
- if status == "idle" and not self.open_im:
- self._close_from_companion("remote-idle")
elif event == "hangup":
status = str(message.get("status", "ended"))[:80]
self.call_ended.emit(status)
@@ -509,6 +524,109 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
f"window.doctorConsultation?.screenshotResult?.({state}, {payload});"
)
+ def _notify_transcription_completed(
+ self,
+ operation: str,
+ session_id: str,
+ segment_id: str,
+ future: Future[bool],
+ ) -> None:
+ try:
+ succeeded = bool(future.result())
+ except Exception as error:
+ succeeded = False
+ message = str(error)[:200] or "录音文字保存失败。"
+ else:
+ message = {
+ "start": "录音文字存储已准备。",
+ "segment": "",
+ "stop": "本次面诊对话文字已保存。",
+ }.get(operation, "")
+ with suppress(RuntimeError):
+ self._transcription_completed.emit(
+ operation, session_id, segment_id, succeeded, message
+ )
+
+ def _on_transcription_completed(
+ self,
+ operation: str,
+ session_id: str,
+ segment_id: str,
+ succeeded: bool,
+ message: str,
+ ) -> None:
+ payload = json.dumps(str(message)[:200], ensure_ascii=True)
+ state = "true" if succeeded else "false"
+ self._page.runJavaScript(
+ "window.doctorConsultation?.transcriptionResult?.("
+ f"{json.dumps(operation)}, {json.dumps(session_id)}, "
+ f"{json.dumps(segment_id)}, {state}, {payload});"
+ )
+
+ def _start_transcription(self, session_id: str, language: str) -> None:
+ try:
+ future = self.lifecycle.start_transcription(session_id, language=language)
+ except Exception as error:
+ self._on_transcription_completed(
+ "start", session_id, "", False, str(error)[:200]
+ )
+ return
+ future.add_done_callback(
+ lambda completed: self._notify_transcription_completed(
+ "start", session_id, "", completed
+ )
+ )
+
+ def _save_transcript_segment(self, message: Mapping[str, Any]) -> None:
+ session_id = str(message.get("sessionId") or "").strip()
+ segment = message.get("segment")
+ segment_id = (
+ str(segment.get("segment_id") or segment.get("segmentId") or "").strip()
+ if isinstance(segment, Mapping)
+ else ""
+ )
+ if not isinstance(segment, Mapping):
+ self._on_transcription_completed(
+ "segment", session_id, segment_id, False, "录音文字片段无效。"
+ )
+ return
+ if session_id != str(self.lifecycle.transcription_session_id or ""):
+ self._on_transcription_completed(
+ "segment", session_id, segment_id, False, "录音会话标识不匹配。"
+ )
+ return
+ try:
+ future = self.lifecycle.save_transcript_segment(segment)
+ except Exception as error:
+ self._on_transcription_completed(
+ "segment", session_id, segment_id, False, str(error)[:200]
+ )
+ return
+ future.add_done_callback(
+ lambda completed: self._notify_transcription_completed(
+ "segment", session_id, segment_id, completed
+ )
+ )
+
+ def _finish_transcription(self, session_id: str, status: str) -> None:
+ if session_id.strip() != str(self.lifecycle.transcription_session_id or ""):
+ self._on_transcription_completed(
+ "stop", session_id, "", False, "录音会话标识不匹配。"
+ )
+ return
+ try:
+ future = self.lifecycle.finish_transcription(status=status)
+ except Exception as error:
+ self._on_transcription_completed(
+ "stop", session_id, "", False, str(error)[:200]
+ )
+ return
+ future.add_done_callback(
+ lambda completed: self._notify_transcription_completed(
+ "stop", session_id, "", completed
+ )
+ )
+
def _close_from_companion(self, reason: str) -> None:
self._companion_ended = True
self._close_reason = reason
diff --git a/app/tests/test_mock_repository.py b/app/tests/test_mock_repository.py
index 8dc1c0f7d..093160694 100644
--- a/app/tests/test_mock_repository.py
+++ b/app/tests/test_mock_repository.py
@@ -232,6 +232,69 @@ def test_demo_call_lifecycle_mutates_record(repository: DemoDoctorRepository) ->
assert ended["room_id"] == "room-501"
+def test_demo_transcript_upsert_and_finish_round_trip_in_call_records(
+ repository: DemoDoctorRepository,
+) -> None:
+ """Demo replay reads expose one finalized segment for a repeated segment ID."""
+
+ started = repository.start_call(501, 301)
+ call_record_id = started["id"]
+ repository.start_call_transcription(501, call_record_id, "session-1")
+ repository.upsert_call_transcript_segments(
+ 501,
+ call_record_id,
+ "session-1",
+ [
+ {
+ "segment_id": "seg-1",
+ "speaker_user_id": "patient_301",
+ "speaker_role": "patient",
+ "timestamp": 1200,
+ "text": "draft words",
+ }
+ ],
+ )
+ repository.upsert_call_transcript_segments(
+ 501,
+ call_record_id,
+ "session-1",
+ [
+ {
+ "segment_id": "seg-1",
+ "speaker_user_id": "patient_301",
+ "speaker_role": "patient",
+ "timestamp": 1200,
+ "text": "final words",
+ }
+ ],
+ )
+ repository.finish_call_transcription(
+ 501,
+ call_record_id,
+ "session-1",
+ expected_segment_count=1,
+ status="completed",
+ )
+ repository.end_call(501)
+
+ record = next(
+ row for row in repository.list_call_records(501) if row["id"] == call_record_id
+ )
+ assert record["status"] == 2
+ assert record["transcription_status"] == "completed"
+ assert record["transcription_segment_count"] == 1
+ assert record["transcript_segments"] == [
+ {
+ "segment_id": "seg-1",
+ "speaker_role": "patient",
+ "speaker_user_id": "patient_301",
+ "timestamp": 1200,
+ "text": "final words",
+ }
+ ]
+ assert "final words" in record["transcript_text"]
+
+
def test_tolerant_page_parsing_accepts_aliases_and_bad_rows() -> None:
"""List parsing handles nullable fields, aliases and non-object rows safely."""
@@ -315,6 +378,8 @@ class _StubApiClient:
"userSig": "short-lived",
"patientUserId": "patient_2",
}
+ if endpoint == "tcm.diagnosis/startCall":
+ return {"call_record_id": 901}
return {"ok": True}
diff --git a/app/tests/test_repository_parity.py b/app/tests/test_repository_parity.py
index b5196b748..0843aabf6 100644
--- a/app/tests/test_repository_parity.py
+++ b/app/tests/test_repository_parity.py
@@ -7,6 +7,7 @@ from typing import Any
import pytest
+from doctor_workstation.core.errors import ApiProtocolError
from doctor_workstation.core.models import Appointment, Consultation, PageResult, Prescription
from doctor_workstation.services.mock_repository import DemoDoctorRepository
from doctor_workstation.services.repository import (
@@ -76,6 +77,8 @@ class RecordingClient:
self.post_calls.append((endpoint, body))
if endpoint in {"tcm.prescription/add", "tcm.prescriptionOrder/create"}:
return {"id": 88}
+ if endpoint == "tcm.diagnosis/startCall":
+ return {"call_record_id": 901}
return {"ok": True}
@@ -253,6 +256,106 @@ def test_remote_new_contracts_use_exact_admin_endpoints_and_dtos() -> None:
} <= get_endpoints
+def test_remote_transcription_endpoints_use_exact_normalized_dtos() -> None:
+ """Realtime transcript persistence stays within the three audited POST DTOs."""
+
+ client = RecordingClient()
+ repository = RemoteDoctorRepository(client) # type: ignore[arg-type]
+
+ repository.start_call_transcription(501, 901, " session-1 ", language=" zh-CN ")
+ repository.upsert_call_transcript_segments(
+ 501,
+ 901,
+ "session-1",
+ [
+ {
+ "segment_id": "seg-1",
+ "speaker_user_id": "patient_301",
+ "speaker_role": "patient",
+ "timestamp": "1200",
+ "text": " patient words ",
+ }
+ ],
+ )
+ repository.finish_call_transcription(
+ 501,
+ 901,
+ "session-1",
+ expected_segment_count=1,
+ status="completed",
+ )
+
+ assert client.post_calls == [
+ (
+ "tcm.diagnosis/startCallTranscription",
+ {
+ "diagnosis_id": 501,
+ "call_record_id": 901,
+ "transcription_session_id": "session-1",
+ "language": "zh-CN",
+ },
+ ),
+ (
+ "tcm.diagnosis/upsertCallTranscriptSegments",
+ {
+ "diagnosis_id": 501,
+ "call_record_id": 901,
+ "transcription_session_id": "session-1",
+ "segments": [
+ {
+ "segment_id": "seg-1",
+ "speaker_user_id": "patient_301",
+ "speaker_role": "patient",
+ "timestamp": 1200,
+ "text": "patient words",
+ }
+ ],
+ },
+ ),
+ (
+ "tcm.diagnosis/finishCallTranscription",
+ {
+ "diagnosis_id": 501,
+ "call_record_id": 901,
+ "transcription_session_id": "session-1",
+ "expected_segment_count": 1,
+ "status": "completed",
+ },
+ ),
+ ]
+
+
+def test_remote_start_call_requires_and_normalizes_current_record_id() -> None:
+ client = RecordingClient()
+ repository = RemoteDoctorRepository(client) # type: ignore[arg-type]
+
+ assert repository.start_call(501, 301) == {"call_record_id": 901}
+ assert client.post_calls == [
+ (
+ "tcm.diagnosis/startCall",
+ {"diagnosis_id": 501, "patient_id": 301, "call_type": 2},
+ )
+ ]
+
+
+@pytest.mark.parametrize(
+ "response",
+ [None, {}, {"ok": True}, {"call_record_id": 0}, {"callRecordId": -1}, {"id": True}],
+)
+def test_remote_start_call_rejects_missing_or_invalid_record_id(response: Any) -> None:
+ class StartCallClient(RecordingClient):
+ def post(self, endpoint: str, payload: dict[str, Any] | None = None) -> Any:
+ if endpoint == "tcm.diagnosis/startCall":
+ self.post_calls.append((endpoint, dict(payload or {})))
+ return response
+ return super().post(endpoint, payload)
+
+ repository = RemoteDoctorRepository(StartCallClient()) # type: ignore[arg-type]
+
+ with pytest.raises(ApiProtocolError, match="call_record"):
+ repository.start_call(501, 301)
+
+
@pytest.mark.parametrize(
"unsafe_reference",
[r"C:\records\tongue.jpg", r"\\server\share\report.pdf", "file:///tmp/a.jpg"],
diff --git a/app/tests/test_video_contract.py b/app/tests/test_video_contract.py
index 53241ccc1..a9ed2b647 100644
--- a/app/tests/test_video_contract.py
+++ b/app/tests/test_video_contract.py
@@ -188,10 +188,13 @@ def test_call_lifecycle_is_fifo_daemon_and_never_blocks_caller() -> None:
release_start = threading.Event()
class Repository:
- def start_call(self, diagnosis_id: int, patient_id: int, *, call_type: int) -> None:
+ def start_call(
+ self, diagnosis_id: int, patient_id: int, *, call_type: int
+ ) -> dict[str, int]:
start_entered.set()
assert release_start.wait(2)
events.append(("start", diagnosis_id, patient_id, call_type))
+ return {"call_record_id": 900}
def bind_call_room(self, diagnosis_id: int, room_id: str) -> None:
events.append(("bind", diagnosis_id, room_id))
@@ -237,6 +240,208 @@ def test_call_lifecycle_is_fifo_daemon_and_never_blocks_caller() -> None:
]
+def test_transcription_lifecycle_uses_start_record_id_and_remains_fifo() -> None:
+ events: list[tuple[object, ...]] = []
+
+ class Repository:
+ def start_call(
+ self, diagnosis_id: int, patient_id: int, *, call_type: int
+ ) -> dict[str, object]:
+ events.append(("start", diagnosis_id, patient_id, call_type))
+ return {"data": {"callRecordId": 901}}
+
+ def start_call_transcription(
+ self,
+ diagnosis_id: int,
+ call_record_id: int,
+ transcription_session_id: str,
+ *,
+ language: str,
+ ) -> None:
+ events.append(
+ (
+ "transcription-start",
+ diagnosis_id,
+ call_record_id,
+ transcription_session_id,
+ language,
+ )
+ )
+
+ def upsert_call_transcript_segments(
+ self,
+ diagnosis_id: int,
+ call_record_id: int,
+ transcription_session_id: str,
+ segments: list[dict[str, object]],
+ ) -> None:
+ events.append(
+ (
+ "segment",
+ diagnosis_id,
+ call_record_id,
+ transcription_session_id,
+ segments,
+ )
+ )
+
+ def finish_call_transcription(
+ self,
+ diagnosis_id: int,
+ call_record_id: int,
+ transcription_session_id: str,
+ expected_segment_count: int,
+ *,
+ status: str,
+ ) -> None:
+ events.append(
+ (
+ "finish",
+ diagnosis_id,
+ call_record_id,
+ transcription_session_id,
+ expected_segment_count,
+ status,
+ )
+ )
+
+ def end_call(self, diagnosis_id: int) -> None:
+ events.append(("end", diagnosis_id))
+
+ request = VideoCallRequest(
+ sdk_app_id=1400123456,
+ user_id="doctor_42",
+ user_sig="short-lived-ticket",
+ target_user_id="patient_8",
+ diagnosis_id=123,
+ patient_id=8,
+ )
+ lifecycle = OrderedCallLifecycle(request, Repository(), logging.getLogger(__name__))
+
+ start = lifecycle.start()
+ transcription_start = lifecycle.start_transcription("session-1")
+ segment = lifecycle.save_transcript_segment(
+ {
+ "segment_id": "seg-1",
+ "speaker_user_id": "patient_8",
+ "speaker_role": "patient",
+ "timestamp": 1200,
+ "text": "patient words",
+ }
+ )
+ duplicate = lifecycle.save_transcript_segment(
+ {"segment_id": "seg-1", "text": "must not produce another write"}
+ )
+ finish = lifecycle.finish_transcription(status="completed")
+ end = lifecycle.end("test")
+
+ assert duplicate is segment
+ assert start.result(timeout=2) is True
+ assert transcription_start.result(timeout=2) is True
+ assert segment.result(timeout=2) is True
+ assert finish.result(timeout=2) is True
+ assert end.result(timeout=2) is True
+ assert lifecycle.wait(1) is True
+ assert lifecycle.call_record_id == 901
+ assert events == [
+ ("start", 123, 8, 2),
+ ("transcription-start", 123, 901, "session-1", "zh-CN"),
+ (
+ "segment",
+ 123,
+ 901,
+ "session-1",
+ [
+ {
+ "segment_id": "seg-1",
+ "transcription_session_id": "session-1",
+ "speaker_user_id": "patient_8",
+ "speaker_role": "patient",
+ "timestamp": 1200,
+ "text": "patient words",
+ }
+ ],
+ ),
+ ("finish", 123, 901, "session-1", 1, "completed"),
+ ("end", 123),
+ ]
+
+
+def test_end_auto_finishes_active_transcription_as_partial() -> None:
+ events: list[tuple[object, ...]] = []
+
+ class Repository:
+ def start_call(
+ self, diagnosis_id: int, patient_id: int, *, call_type: int
+ ) -> dict[str, int]:
+ events.append(("start", diagnosis_id, patient_id, call_type))
+ return {"call_record_id": 902}
+
+ def start_call_transcription(
+ self,
+ diagnosis_id: int,
+ call_record_id: int,
+ transcription_session_id: str,
+ *,
+ language: str,
+ ) -> None:
+ events.append(
+ (
+ "transcription-start",
+ diagnosis_id,
+ call_record_id,
+ transcription_session_id,
+ language,
+ )
+ )
+
+ def finish_call_transcription(
+ self,
+ diagnosis_id: int,
+ call_record_id: int,
+ transcription_session_id: str,
+ expected_segment_count: int,
+ *,
+ status: str,
+ ) -> None:
+ events.append(
+ (
+ "finish",
+ diagnosis_id,
+ call_record_id,
+ transcription_session_id,
+ expected_segment_count,
+ status,
+ )
+ )
+
+ def end_call(self, diagnosis_id: int) -> None:
+ events.append(("end", diagnosis_id))
+
+ request = VideoCallRequest(
+ sdk_app_id=1400123456,
+ user_id="doctor_42",
+ user_sig="short-lived-ticket",
+ target_user_id="patient_8",
+ diagnosis_id=123,
+ patient_id=8,
+ )
+ lifecycle = OrderedCallLifecycle(request, Repository(), logging.getLogger(__name__))
+
+ lifecycle.start()
+ lifecycle.start_transcription("session-auto-partial")
+ ended = lifecycle.end("window-closed")
+
+ assert ended.result(timeout=2) is True
+ assert lifecycle.wait(1) is True
+ assert events == [
+ ("start", 123, 8, 2),
+ ("transcription-start", 123, 902, "session-auto-partial", "zh-CN"),
+ ("finish", 123, 902, "session-auto-partial", 0, "partial"),
+ ("end", 123),
+ ]
+
+
def test_failed_start_prevents_bind_and_end_writes() -> None:
events: list[str] = []
@@ -278,8 +483,9 @@ def test_video_screenshot_is_uploaded_and_appended_to_patient_tongue_images() ->
events: list[tuple[object, ...]] = []
class Repository:
- def start_call(self, diagnosis_id: int, *, call_type: int) -> None:
+ def start_call(self, diagnosis_id: int, *, call_type: int) -> dict[str, int]:
events.append(("start", diagnosis_id, call_type))
+ return {"call_record_id": 903}
def upload_material_bytes(
self,
@@ -325,6 +531,28 @@ def test_video_screenshot_is_uploaded_and_appended_to_patient_tongue_images() ->
]
+def test_start_rejects_missing_record_id_without_using_ticket_fallback() -> None:
+ class Repository:
+ def start_call(self, diagnosis_id: int, *, call_type: int) -> dict[str, object]:
+ del diagnosis_id, call_type
+ return {}
+
+ request = VideoCallRequest(
+ sdk_app_id=1400123456,
+ user_id="doctor_42",
+ user_sig="short-lived-ticket",
+ target_user_id="patient_8",
+ diagnosis_id=123,
+ call_record_id=77,
+ )
+ lifecycle = OrderedCallLifecycle(request, Repository(), logging.getLogger(__name__))
+
+ with pytest.raises(ValueError, match="startCall response did not include"):
+ lifecycle.start().result(timeout=2)
+
+ assert lifecycle.started is False
+
+
def test_https_document_policy_is_exact_and_origin_scoped() -> None:
policy = TrustedDocumentPolicy.from_url(
"https://RTC.Example.com/doctor-call/index.html?tenant=a#boot",
diff --git a/app/video_companion/dist/assets/index-qOBmgxQV.css b/app/video_companion/dist/assets/index-CED5X2W4.css
similarity index 81%
rename from app/video_companion/dist/assets/index-qOBmgxQV.css
rename to app/video_companion/dist/assets/index-CED5X2W4.css
index eb58fccce..81f6da93b 100644
--- a/app/video_companion/dist/assets/index-qOBmgxQV.css
+++ b/app/video_companion/dist/assets/index-CED5X2W4.css
@@ -1 +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-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;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--overlay{position:fixed;z-index:1000;inset:0}.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}.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}.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}@media (max-width: 820px){.consultation-shell{min-width:620px}.message-list{padding-inline:18px}.message-bubble{max-width:82%}}
+: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-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;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--overlay{position:fixed;z-index:1000;inset:0}.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}.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}@media (max-width: 820px){.consultation-shell{min-width:620px}.message-list{padding-inline:18px}.message-bubble{max-width:82%}}
diff --git a/app/video_companion/dist/assets/index-DwSVWep6.js b/app/video_companion/dist/assets/index-R5GzqA8s.js
similarity index 67%
rename from app/video_companion/dist/assets/index-DwSVWep6.js
rename to app/video_companion/dist/assets/index-R5GzqA8s.js
index 0836105c4..6cf09de1b 100644
--- a/app/video_companion/dist/assets/index-DwSVWep6.js
+++ b/app/video_companion/dist/assets/index-R5GzqA8s.js
@@ -1,4 +1,4 @@
-(function(){const i=document.createElement("link").relList;if(i&&i.supports&&i.supports("modulepreload"))return;for(const u of document.querySelectorAll('link[rel="modulepreload"]'))l(u);new MutationObserver(u=>{for(const p of u)if(p.type==="childList")for(const y of p.addedNodes)y.tagName==="LINK"&&y.rel==="modulepreload"&&l(y)}).observe(document,{childList:!0,subtree:!0});function r(u){const p={};return u.integrity&&(p.integrity=u.integrity),u.referrerPolicy&&(p.referrerPolicy=u.referrerPolicy),u.crossOrigin==="use-credentials"?p.credentials="include":u.crossOrigin==="anonymous"?p.credentials="omit":p.credentials="same-origin",p}function l(u){if(u.ep)return;u.ep=!0;const p=r(u);fetch(u.href,p)}})();var pg=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function B3(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function ZL(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 u=Object.getOwnPropertyDescriptor(t,l);Object.defineProperty(r,l,u.get?u:{enumerable:!0,get:function(){return t[l]}})}),r}var l1={exports:{}},RiA=l1.exports,z5;function wiA(){return z5||(z5=1,function(t,i){(function(r,l){t.exports=l()})(RiA,function(){const r=s=>s===void 0,l=s=>typeof s=="string",u=s=>{var n;return(n=Object.prototype.toString.call(s).match(/^\[object (.*)\]$/))===null||n===void 0?void 0:n[1].toLowerCase()},p=s=>typeof Array.isArray=="function"?Array.isArray(s):u(s)==="array",y=s=>s!==null&&typeof s=="object",w=s=>p(s)||y(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 F(s=99999999){return Math.round(Math.random()*s)}const j=(s,n,g,I)=>{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=It&&typeof wx.miniapp=="object",uo=typeof uni<"u",Ys=ft&&typeof tt.enterChat=="function",ki=It||qe||ft||Vt||gi||_o||Fi,os=typeof window>"u"&&!ki&&typeof pg<"u"&&pg.NativeScriptGlobals!==void 0,Ko=typeof pg<"u"&&(pg.nativeModuleProxy!==void 0||pg.ReactNative!==void 0),$i=typeof wx<"u"&&typeof wx.getAccountInfoSync=="function"&&!!wx.getAccountInfoSync().plugin,jt=typeof uni<"u"?!ki:typeof window<"u"&&!ki&&!Ko,io=qe?qq:ft?tt:Vt?swan:gi?my:It?wx:_o?uni:Fi?jd:{},bi=jt&&window&&window.navigator&&window.navigator.userAgent||"",Ms=/(micromessenger|webbrowser)/i.test(bi),qA=function(){let s="WEB";return Ms?s="WEB":qe?s="QQ_MP":ft?s="TT_MP":Vt?s="BAIDU_MP":gi?s="ALI_MP":It?s=to?"DONUT_NATIVE_APP":"WX_MP":_o?s="UNI_NATIVE_APP":os?s="NS_NATIVE_APP":Ko&&(s="RN_NATIVE_APP"),aA[s]}(),ce=/iPad/i.test(bi),Pe=/iPhone/i.test(bi)&&!ce,kt=/iPod/i.test(bi),it=Pe||ce||kt,gt=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}(),Ge=/Firefox/i.test(bi),je=/Edge/i.test(bi),Mt=!je&&/Chrome/i.test(bi),Rt=/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}(),Qo=/Safari/i.test(bi)&&!Mt&&!Xt&&!je,To=/Windows/i.test(bi),oo=/MAC OS X/i.test(bi),No=jt&&typeof Worker<"u"&&!Rt,$s=Xt||it,rn=function(){if(typeof window>"u"||window.navigator===void 0)return!1;const{standalone:s}=window.navigator;return!(!it||s||Qo)}();function us(){let s="unknown";if(oo&&(s="mac"),To&&(s="windows"),it&&(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 yo(s,n){var g={};for(var I in s)Object.prototype.hasOwnProperty.call(s,I)&&n.indexOf(I)<0&&(g[I]=s[I]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function"){var E=0;for(I=Object.getOwnPropertySymbols(s);E{io.request({url:g,data:I,method:n,timeout:E,header:{"content-type":jr},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":${Br}}`))},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",jr),M.send(I||null)})})}function vs(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 ir(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(ir(M,g),ir(D,g))}),m}if(s instanceof Set){const m=new Set;return g.set(s,m),s.forEach(D=>{m.add(ir(D,g))}),m}if(Array.isArray(s)){const m=[];return g.set(s,m),s.forEach(D=>{m.push(ir(D,g))}),m}const I=Object.getPrototypeOf(s),E=Object.create(I);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]=ir(s[m],g))}),E}function An(s,n,g){const I=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(I.has(D))return"[Circular]";I.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,I)=>{s=g,n=I}),resolve:s,reject:n}}var Jt,fg=Object.freeze({__proto__:null,ANDROID_VERSION:$t,IE_VERSION:Oi,IN_ALIPAY_MINI_APP:gi,IN_BAIDU_MINI_APP:Vt,IN_BROWSER:jt,IN_DONUT_NATIVE_APP:to,IN_FEISHU_MINI_APP:Ys,IN_JD_MINI_APP:Fi,IN_MINI_APP:ki,IN_NODE:an,IN_NS_NATIVE_APP:os,IN_QQ_MINI_APP:qe,IN_RN_APP:Ko,IN_TT_MINI_APP:ft,IN_TT_MINI_GAME:si,IN_UNI_APP:uo,IN_UNI_NATIVE_APP:_o,IN_WX_MINI_APP:It,IN_WX_MINI_APP_DESK:qt,IN_WX_MINI_GAME:re,IN_WX_MINI_PLUGIN:$i,IOS_VERSION:gt,IS_ANDROID:Xt,IS_CHROME:Mt,IS_EDGE:je,IS_FIREFOX:Ge,IS_IE:Rt,IS_IOS:it,IS_IPAD:ce,IS_IPHONE:Pe,IS_IPOD:kt,IS_MAC:oo,IS_SAFARI:Qo,IS_WECHAT:Ms,IS_WIN:To,IS_WORKER_AVAILABLE:No,MINI_APP_NAMESPACE:io,USER_AGENT:bi,base16EncodeBinaryString:lA,deepCopyWithMethods:ir,deepMerge:j,generatePromise:wn,getPlatformType:us,getType:u,httpRequest:Pi,isArray:p,isArrayOrObject:w,isEmpty:vs,isH5:$s,isIOSWebView:rn,isNumber:s=>s!==null&&(typeof s=="number"&&!Number.isNaN(s-0)||typeof s=="object"&&s.constructor===Number),isObject:y,isPlainObject:k,isString:l,isUndefined:r,isUniIOSApp:function(){return _o&&uni.getDeviceInfo().platform.toLocaleLowerCase()==="ios"},isValidRequestKey:_,platform:qA,randomInt:F,randomString:function(){const s="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let n="";for(let g=32;g>0;--g)n+=s[Math.floor(62*Math.random())];return n},safeStringify:An});class On{constructor(){this.listeners={}}on(n,g,I){this.listeners[n]||(this.listeners[n]=[]),this.listeners[n].push({fn:g,context:I})}off(n,g,I){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=!I||m.context===I;return!(D&&M)}))}emit(n,...g){const I=this.listeners[n];I&&I.forEach(E=>{const{fn:m,context:D}=E;try{m.apply(D,g)}catch(M){console.warn(`Error in event handler for ${n} error: ${An(M)}`)}})}once(n,g,I){const E=(...m)=>{g.apply(I,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"})(Jt||(Jt={}));const Gn=[16,17];function Vs(s){var n;const g=[];return(n=s?.GroupTips)===null||n===void 0||n.forEach(I=>{var E;I.GroupInfo.MillionGroupFlag===2?g.push(Jt.TOPIC_TIPS_NOTIFICATION):Gn.includes((E=I?.MsgBody)===null||E===void 0?void 0:E.OpType)?g.push(Jt.GROUP_MESSAGE_PINNED):g.push(Jt.GROUP_TIPS_NOTIFICATION)}),g}const Qr=[{conditions:[{type:"event",value:100}],subType:Jt.BUSINESS_COMMAND},{conditions:[{type:"event",value:24}],subType:Jt.ALL_RECEIVE_MESSAGE_OPTION},{conditions:[{type:"event",value:26}],subType:Jt.TOPIC_LATEST_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgArray"}],subType:Jt.C2C_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgModNotifys"}],subType:Jt.C2C_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"ProfileDataMod"}],subType:Jt.PROFILE_MODIFIED},{conditions:[{type:"hasKey",value:"UserStatusList"}],subType:Jt.USER_STATUS_UPDATE},{conditions:[{type:"hasKey",value:"FriendListMod"}],subType:Jt.FRIEND_LIST_MODIFIED},{conditions:[{type:"hasKey",value:"GroupMsgArray"}],subType:Jt.GROUP_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"GroupMsgModNotifys"}],subType:Jt.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(I=>{I.WithdrawC2cMsgNotify&&g.push(Jt.C2C_REVOKED_MESSAGE),I.C2cReadedReceipt&&g.push(Jt.C2C_MESSAGE_PEER_READ),I.ReadC2cMsgNotify&&g.push(Jt.C2C_MESSAGE_READ_SYNC),I.MuteNotificationsSync&&g.push(Jt.C2C_REMIND_TYPE_SYNC)}),g}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:4}],subTypeParser:Vs},{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(I=>{Array.isArray(I.MsgBody.GroupWithdrawInfoArray)?g.push(Jt.GROUP_MESSAGE_REVOKED):Array.isArray(I.MsgBody.GroupMsgReceiptList)?g.push(Jt.GROUP_MESSAGE_READ_RECEIPT):Array.isArray(I.MsgBody.GroupReadInfoArray)?I.MsgBody.GroupReadInfoArray[0].TopicId?g.push(Jt.TOPIC_MESSAGE_READ_SYNC):g.push(Jt.GROUP_MESSAGE_READ_SYNC):I.GroupInfo.MillionGroupFlag===2?g.push(Jt.TOPIC_SYSTEM_NOTIFICATION):g.push(Jt.GROUP_SYSTEM_NOTIFICATION)}),g}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:6}],subTypeParser:Vs},{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(I=>{const{GroupAtTips:{TopicId:E}}=I;E?g.push(Jt.TOPIC_AT_TIPS):g.push(Jt.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(I=>{switch(I.PushType){case Ke.CONV_MARK_UPDATED:g.push(Jt.CONVERSATION_MARK_UPDATED);break;case Ke.CONV_GROUP_ADDED:g.push(Jt.CONVERSATION_GROUP_ADD);break;case Ke.CONV_GROUP_DELETED:g.push(Jt.CONVERSATION_GROUP_DELETED);break;case Ke.CONV_GROUP_UPDATED:g.push(Jt.CONVERSATION_GROUP_UPDATED);break;default:g.push(Jt.CONV_MODIFIED)}}),g}},{conditions:[{type:"hasKey",value:"MsgReactionNotifyList"}],subType:Jt.MESSAGE_REACTION_UPDATED},{conditions:[{type:"hasKey",value:"MsgReactionNotify"}],subType:Jt.MESSAGE_REACTION_UPDATED_SYNC},{conditions:[{type:"hasKey",value:"C2cMsgInfo"}],subType:Jt.C2C_MESSAGE_READ_RECEIPT},{conditions:[{type:"hasKey",value:"FollowChangeList"}],subType:Jt.FOLLOW_LIST_UPDATED},{conditions:[{type:"hasKey",value:"MsgExtensionNotify"}],subType:Jt.MESSAGE_EXTENSIONS_UPDATED},{conditions:[{type:"hasKey",value:"C2CReadAllMsg"}],subType:Jt.ALL_MESSAGE_READ}];var Pn;function pr(s){var n;const g=Array.isArray((n=s?.body)===null||n===void 0?void 0:n.EventArray)?s.body.EventArray:[],I=[];return g.forEach(E=>{E.Flag=s.body.Flag;const m=Qr.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=>{I.push({type:`${Pn.SERVER_PUSH_MESSAGE}:${M}`,data:E})}):I.push({type:`${Pn.SERVER_PUSH_MESSAGE}:${D}`,data:E})}),I}(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 po={[Pn.SERVER_PUSH_MESSAGE]:pr,[Pn.SERVER_PUSH_MESSAGE_MULTIPLE]:pr,[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=Jt}subscribeInnerEvent(s,n,g,I,E){var m;let D,M,T,P;["string","number"].includes(typeof n)?(T=`${s}:${n}`,P=g,M=I,D=E):(T=s,P=n,M=g,D=typeof I=="function"?I: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,I;if((g=this._innerEventEmitter)===null||g===void 0||g.emit(s,n),Object.keys(po).includes(s)){const E=(I=po[s])===null||I===void 0?void 0:I.call(po,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 I;(I=this._outerEventEmitter)===null||I===void 0||I.on(s,n,g)}unSubscribeOuterEvent(s,n,g){var I;(I=this._outerEventEmitter)===null||I===void 0||I.off(s,n,g)}unSubscribeInnerEvent(s,n,g,I){if(["string","number"].includes(typeof n)){const E=g,m=`${s}:${n}`;this._unsubscribeEvent(m,E,I)}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,I){var E;const m=D=>{I.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:I,context:g}),(E=this._innerEventEmitter)===null||E===void 0||E.on(s,m,g)}_unsubscribeEvent(s,n,g){var I,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(I=this._innerEventEmitter)===null||I===void 0||I.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 fl{constructor(){this._socket=null}connectSocket(n){return this._socket=new WebSocket(n),this._socket}send(n){var g,I;try{(g=this._socket)===null||g===void 0||g.send(n)}catch(E){(I=this._onSendFail)===null||I===void 0||I.call(this,E)}}bindSocketHandlers(n){const{onOpen:g,onMessage:I,onClose:E,onError:m,onSendFail:D}=n;this._socket&&(this._socket.binaryType="arraybuffer",this._socket.onopen=g,this._socket.onmessage=I,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:I=>g._onError(I)}),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:I,onClose:E,onError:m,onSendFail:D}=n;this._socket&&(this._socket.onClose(E),this._socket.onOpen(g),this._socket.onMessage(I),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 mr="CONNECT",ks="SEND",Yc="DISCONNECT",ps="OPEN",rs="MESSAGE",Bu="CLOSE",ja="ERROR",ds="SEND_FAIL";class og{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 u of document.querySelectorAll('link[rel="modulepreload"]'))l(u);new MutationObserver(u=>{for(const B of u)if(B.type==="childList")for(const f of B.addedNodes)f.tagName==="LINK"&&f.rel==="modulepreload"&&l(f)}).observe(document,{childList:!0,subtree:!0});function r(u){const B={};return u.integrity&&(B.integrity=u.integrity),u.referrerPolicy&&(B.referrerPolicy=u.referrerPolicy),u.crossOrigin==="use-credentials"?B.credentials="include":u.crossOrigin==="anonymous"?B.credentials="omit":B.credentials="same-origin",B}function l(u){if(u.ep)return;u.ep=!0;const B=r(u);fetch(u.href,B)}})();var mg=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function F3(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 u=Object.getOwnPropertyDescriptor(t,l);Object.defineProperty(r,l,u.get?u:{enumerable:!0,get:function(){return t[l]}})}),r}var S1={exports:{}},ziA=S1.exports,Bz;function ZiA(){return Bz||(Bz=1,function(t,i){(function(r,l){t.exports=l()})(ziA,function(){const r=s=>s===void 0,l=s=>typeof s=="string",u=s=>{var n;return(n=Object.prototype.toString.call(s).match(/^\[object (.*)\]$/))===null||n===void 0?void 0:n[1].toLowerCase()},B=s=>typeof Array.isArray=="function"?Array.isArray(s):u(s)==="array",f=s=>s!==null&&typeof s=="object",w=s=>B(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 F(s=99999999){return Math.round(Math.random()*s)}const j=(s,n,g,I)=>{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=It&&typeof wx.miniapp=="object",uo=typeof uni<"u",Vs=ft&&typeof tt.enterChat=="function",ki=It||qe||ft||Vt||gi||_o||Fi,ns=typeof window>"u"&&!ki&&typeof mg<"u"&&mg.NativeScriptGlobals!==void 0,Ko=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&&!Ko,io=qe?qq:ft?tt:Vt?swan:gi?my:It?wx:_o?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":qe?s="QQ_MP":ft?s="TT_MP":Vt?s="BAIDU_MP":gi?s="ALI_MP":It?s=to?"DONUT_NATIVE_APP":"WX_MP":_o?s="UNI_NATIVE_APP":ns?s="NS_NATIVE_APP":Ko&&(s="RN_NATIVE_APP"),rA[s]}(),le=/iPad/i.test(bi),xe=/iPhone/i.test(bi)&&!le,Lt=/iPod/i.test(bi),it=xe||le||Lt,gt=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),je=/Edge/i.test(bi),Mt=!je&&/Chrome/i.test(bi),Rt=/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}(),Qo=/Safari/i.test(bi)&&!Mt&&!Xt&&!je,To=/Windows/i.test(bi),oo=/MAC OS X/i.test(bi),No=jt&&typeof Worker<"u"&&!Rt,An=Xt||it,rn=function(){if(typeof window>"u"||window.navigator===void 0)return!1;const{standalone:s}=window.navigator;return!(!it||s||Qo)}();function Es(){let s="unknown";if(oo&&(s="mac"),To&&(s="windows"),it&&(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 yo(s,n){var g={};for(var I in s)Object.prototype.hasOwnProperty.call(s,I)&&n.indexOf(I)<0&&(g[I]=s[I]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function"){var E=0;for(I=Object.getOwnPropertySymbols(s);E{io.request({url:g,data:I,method:n,timeout:E,header:{"content-type":jr},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":${Br}}`))},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",jr),M.send(I||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 ir(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(ir(M,g),ir(D,g))}),m}if(s instanceof Set){const m=new Set;return g.set(s,m),s.forEach(D=>{m.add(ir(D,g))}),m}if(Array.isArray(s)){const m=[];return g.set(s,m),s.forEach(D=>{m.push(ir(D,g))}),m}const I=Object.getPrototypeOf(s),E=Object.create(I);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]=ir(s[m],g))}),E}function en(s,n,g){const I=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(I.has(D))return"[Circular]";I.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,I)=>{s=g,n=I}),resolve:s,reject:n}}var Jt,yg=Object.freeze({__proto__:null,ANDROID_VERSION:$t,IE_VERSION:Oi,IN_ALIPAY_MINI_APP:gi,IN_BAIDU_MINI_APP:Vt,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:qe,IN_RN_APP:Ko,IN_TT_MINI_APP:ft,IN_TT_MINI_GAME:ni,IN_UNI_APP:uo,IN_UNI_NATIVE_APP:_o,IN_WX_MINI_APP:It,IN_WX_MINI_APP_DESK:qt,IN_WX_MINI_GAME:ge,IN_WX_MINI_PLUGIN:$i,IOS_VERSION:gt,IS_ANDROID:Xt,IS_CHROME:Mt,IS_EDGE:je,IS_FIREFOX:be,IS_IE:Rt,IS_IOS:it,IS_IPAD:le,IS_IPHONE:xe,IS_IPOD:Lt,IS_MAC:oo,IS_SAFARI:Qo,IS_WECHAT:vs,IS_WIN:To,IS_WORKER_AVAILABLE:No,MINI_APP_NAMESPACE:io,USER_AGENT:bi,base16EncodeBinaryString:IA,deepCopyWithMethods:ir,deepMerge:j,generatePromise:wn,getPlatformType:Es,getType:u,httpRequest:Pi,isArray:B,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 _o&&uni.getDeviceInfo().platform.toLocaleLowerCase()==="ios"},isValidRequestKey:_,platform:HA,randomInt:F,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,I){this.listeners[n]||(this.listeners[n]=[]),this.listeners[n].push({fn:g,context:I})}off(n,g,I){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=!I||m.context===I;return!(D&&M)}))}emit(n,...g){const I=this.listeners[n];I&&I.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,I){const E=(...m)=>{g.apply(I,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"})(Jt||(Jt={}));const Gn=[16,17];function Js(s){var n;const g=[];return(n=s?.GroupTips)===null||n===void 0||n.forEach(I=>{var E;I.GroupInfo.MillionGroupFlag===2?g.push(Jt.TOPIC_TIPS_NOTIFICATION):Gn.includes((E=I?.MsgBody)===null||E===void 0?void 0:E.OpType)?g.push(Jt.GROUP_MESSAGE_PINNED):g.push(Jt.GROUP_TIPS_NOTIFICATION)}),g}const Qr=[{conditions:[{type:"event",value:100}],subType:Jt.BUSINESS_COMMAND},{conditions:[{type:"event",value:24}],subType:Jt.ALL_RECEIVE_MESSAGE_OPTION},{conditions:[{type:"event",value:26}],subType:Jt.TOPIC_LATEST_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgArray"}],subType:Jt.C2C_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgModNotifys"}],subType:Jt.C2C_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"ProfileDataMod"}],subType:Jt.PROFILE_MODIFIED},{conditions:[{type:"hasKey",value:"UserStatusList"}],subType:Jt.USER_STATUS_UPDATE},{conditions:[{type:"hasKey",value:"FriendListMod"}],subType:Jt.FRIEND_LIST_MODIFIED},{conditions:[{type:"hasKey",value:"GroupMsgArray"}],subType:Jt.GROUP_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"GroupMsgModNotifys"}],subType:Jt.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(I=>{I.WithdrawC2cMsgNotify&&g.push(Jt.C2C_REVOKED_MESSAGE),I.C2cReadedReceipt&&g.push(Jt.C2C_MESSAGE_PEER_READ),I.ReadC2cMsgNotify&&g.push(Jt.C2C_MESSAGE_READ_SYNC),I.MuteNotificationsSync&&g.push(Jt.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(I=>{Array.isArray(I.MsgBody.GroupWithdrawInfoArray)?g.push(Jt.GROUP_MESSAGE_REVOKED):Array.isArray(I.MsgBody.GroupMsgReceiptList)?g.push(Jt.GROUP_MESSAGE_READ_RECEIPT):Array.isArray(I.MsgBody.GroupReadInfoArray)?I.MsgBody.GroupReadInfoArray[0].TopicId?g.push(Jt.TOPIC_MESSAGE_READ_SYNC):g.push(Jt.GROUP_MESSAGE_READ_SYNC):I.GroupInfo.MillionGroupFlag===2?g.push(Jt.TOPIC_SYSTEM_NOTIFICATION):g.push(Jt.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(I=>{const{GroupAtTips:{TopicId:E}}=I;E?g.push(Jt.TOPIC_AT_TIPS):g.push(Jt.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(I=>{switch(I.PushType){case Ke.CONV_MARK_UPDATED:g.push(Jt.CONVERSATION_MARK_UPDATED);break;case Ke.CONV_GROUP_ADDED:g.push(Jt.CONVERSATION_GROUP_ADD);break;case Ke.CONV_GROUP_DELETED:g.push(Jt.CONVERSATION_GROUP_DELETED);break;case Ke.CONV_GROUP_UPDATED:g.push(Jt.CONVERSATION_GROUP_UPDATED);break;default:g.push(Jt.CONV_MODIFIED)}}),g}},{conditions:[{type:"hasKey",value:"MsgReactionNotifyList"}],subType:Jt.MESSAGE_REACTION_UPDATED},{conditions:[{type:"hasKey",value:"MsgReactionNotify"}],subType:Jt.MESSAGE_REACTION_UPDATED_SYNC},{conditions:[{type:"hasKey",value:"C2cMsgInfo"}],subType:Jt.C2C_MESSAGE_READ_RECEIPT},{conditions:[{type:"hasKey",value:"FollowChangeList"}],subType:Jt.FOLLOW_LIST_UPDATED},{conditions:[{type:"hasKey",value:"MsgExtensionNotify"}],subType:Jt.MESSAGE_EXTENSIONS_UPDATED},{conditions:[{type:"hasKey",value:"C2CReadAllMsg"}],subType:Jt.ALL_MESSAGE_READ}];var Pn;function pr(s){var n;const g=Array.isArray((n=s?.body)===null||n===void 0?void 0:n.EventArray)?s.body.EventArray:[],I=[];return g.forEach(E=>{E.Flag=s.body.Flag;const m=Qr.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=>{I.push({type:`${Pn.SERVER_PUSH_MESSAGE}:${M}`,data:E})}):I.push({type:`${Pn.SERVER_PUSH_MESSAGE}:${D}`,data:E})}),I}(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 po={[Pn.SERVER_PUSH_MESSAGE]:pr,[Pn.SERVER_PUSH_MESSAGE_MULTIPLE]:pr,[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=Jt}subscribeInnerEvent(s,n,g,I,E){var m;let D,M,T,P;["string","number"].includes(typeof n)?(T=`${s}:${n}`,P=g,M=I,D=E):(T=s,P=n,M=g,D=typeof I=="function"?I: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,I;if((g=this._innerEventEmitter)===null||g===void 0||g.emit(s,n),Object.keys(po).includes(s)){const E=(I=po[s])===null||I===void 0?void 0:I.call(po,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 I;(I=this._outerEventEmitter)===null||I===void 0||I.on(s,n,g)}unSubscribeOuterEvent(s,n,g){var I;(I=this._outerEventEmitter)===null||I===void 0||I.off(s,n,g)}unSubscribeInnerEvent(s,n,g,I){if(["string","number"].includes(typeof n)){const E=g,m=`${s}:${n}`;this._unsubscribeEvent(m,E,I)}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,I){var E;const m=D=>{I.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:I,context:g}),(E=this._innerEventEmitter)===null||E===void 0||E.on(s,m,g)}_unsubscribeEvent(s,n,g){var I,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(I=this._innerEventEmitter)===null||I===void 0||I.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 yl{constructor(){this._socket=null}connectSocket(n){return this._socket=new WebSocket(n),this._socket}send(n){var g,I;try{(g=this._socket)===null||g===void 0||g.send(n)}catch(E){(I=this._onSendFail)===null||I===void 0||I.call(this,E)}}bindSocketHandlers(n){const{onOpen:g,onMessage:I,onClose:E,onError:m,onSendFail:D}=n;this._socket&&(this._socket.binaryType="arraybuffer",this._socket.onopen=g,this._socket.onmessage=I,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:I=>g._onError(I)}),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:I,onClose:E,onError:m,onSendFail:D}=n;this._socket&&(this._socket.onClose(E),this._socket.onOpen(g),this._socket.onMessage(I),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 mr="CONNECT",Ls="SEND",Vc="DISCONNECT",ms="OPEN",as="MESSAGE",mu="CLOSE",ja="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:mr,url:n})}send(n){var g,I;try{(g=this._worker)===null||g===void 0||g.postMessage({type:ks,data:n})}catch(E){(I=this._onSendFail)===null||I===void 0||I.call(this,E)}}bindSocketHandlers(n){const{onOpen:g,onMessage:I,onClose:E,onError:m,onSendFail:D}=n;if(this._worker){const M={[ps]:g,[rs]:I,[Bu]:E,[ja]:m,[ds]: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:Yc}),this._worker.terminate(),this._worker=null),this._blobUrl&&(URL.revokeObjectURL(this._blobUrl),this._blobUrl=null)}}class LI{}var Xo,Zi=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 Qc{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:I,onClose:E,onError:m,onSendFail:D}=n;this._socket&&(this._socket.onClose(E),this._socket.onOpen(g),this._socket.onMessage(M=>I(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"})(Xo||(Xo={}));class sg{constructor(n){this._url="",this._readyState=Xo.DISCONNECTED,this._url=n,this._id=F(),this._emitter=new On,gi?this._socket=new Qc:It||_o||ft||qe||Fi||Vt?this._socket=new cn({onError:this._onError.bind(this)}):an?this._socket=new LI:this._canUseWebWorker()?this._socket=new og:this._socket=new fl,this.connect()}connect(){this.doOpen(),this._bindSocketHandlers()}doOpen(){[Xo.CONNECTED,Xo.CONNECTING].includes(this._readyState)||(this._readyState=Xo.CONNECTING,this._ws=this._socket.connectSocket(this._url))}send(n){this._readyState!==Xo.CONNECTED?this.reconnect():this._socket.send(n)}reconnect(){[Xo.CONNECTED,Xo.CONNECTING].includes(this._readyState)||(this.disconnect(),this.doOpen())}getId(){return this._id}on(n,g,I){this._emitter.on(n,g,I)}off(n,g,I){this._emitter.off(n,g,I)}isConnected(){return this._readyState===Xo.CONNECTED}disconnect(){this._readyState=Xo.DISCONNECTED,this._unbindSocketHandlers(),this._socket.disconnect()}_onOpen(n){this._readyState===Xo.CONNECTING&&(this._readyState=Xo.CONNECTED,this._emitter.emit("connect",{socketId:this._id,event:n}))}_onMessage(n){this._emitter.emit("message",n)}_onClose(n){this._readyState=Xo.DISCONNECTED,this._emitter.emit("close",{socketId:this._id,event:n})}_onError(n){this._readyState=Xo.DISCONNECTED,this._emitter.emit("error",{socketId:this._id,error:n})}_onSendFail(n){this._readyState=Xo.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=Zi.get("cloudConfig")||{};return(r(n.isWorkerEnabled)||n.isWorkerEnabled==="1")&&No}}const yg={[ct.SINGAPORE]:[[2e7,3e7],[172e7,173e7]],[ct.KOREA]:[[3e7,4e7],[173e7,174e7]],[ct.GERMANY]:[[4e7,5e7],[174e7,175e7]],[ct.IND]:[[5e7,6e7],[175e7,176e7]],[ct.JPN]:[[6e7,7e7],[176e7,177e7]],[ct.USA]:[[7e7,8e7],[177e7,178e7]],[ct.INDONESIA]:[[8e7,9e7],[178e7,179e7]],[ct.KSA]:[[9e7,1e8],[179e7,18e8]]};function la(s){var n;if(!((n=Zi.get("instance"))===null||n===void 0)&&n.oversea)return ct.OVERSEA;for(const g of Object.keys(yg))for(const[I,E]of yg[g])if(s>=I&&s`${oA}=${W[oA]}`).join("&"));var W;return g?`${s}/binfo?${P}&compress=gzip`:`${s}/info?${P}`}function Js(s){const n=Zi.get("instance"),{sdkAppId:g,testEnv:I,proxyServer:E}=n,m=la(g);if(I)return Hn(mt.TEST[m].DEFAULT,{isBinary:s});if(!vs(E))return Hn(E,{isBinary:s});const D=mt.PRODUCTION[m],M=jt&&D.ANYCAST,T=jt,P=!!D.BACKUP_CN;return Hn({[Go.INITIAL]:()=>(wo=Go.DEFAULT,D.DEFAULT),[Go.DEFAULT]:()=>(wo=Go.IPV6,D.IPV6),[Go.IPV6]:()=>(wo=Go.BACKUP,D.BACKUP),[Go.BACKUP]:()=>T?(wo=Go.BACKUP_WEB_ONLY,function(W){const oA=Math.floor(10001*Math.random())+1e4;return W.replace("*",String(oA))}(D.BACKUP_WEB_ONLY)):P?(wo=Go.BACKUP_CN,D.BACKUP_CN):M?(wo=Go.ANYCAST,D.ANYCAST):D.DEFAULT,[Go.BACKUP_WEB_ONLY]:()=>P?(wo=Go.BACKUP_CN,D.BACKUP_CN):M?(wo=Go.ANYCAST,D.ANYCAST):D.DEFAULT,[Go.BACKUP_CN]:()=>(wo=M?Go.ANYCAST:Go.DEFAULT,D[wo]),[Go.ANYCAST]:()=>(wo=Go.DEFAULT,D.ANYCAST="",D.DEFAULT)}[wo](),{isBinary:s})}var Dg=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(),I=g-s;this._timeOffsetWithServer=n+I-g}};const pc=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:I,isOnce:E=!1,intervalMs:m=pc}=s,D=Math.max(m,pc);return{id:n,nextExecuteTime:Date.now()+D,intervalMs:m,callback:g,context:I,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 Na(s){const n=[];for(let g=0;g=55296&&I<=56319){const E=s.charCodeAt(++g)-56320+(I-55296<<10)+65536;n.push(240|E>>18,128|E>>12&63,128|E>>6&63,128|63&E)}else I<=127?n.push(I):I<=2047?n.push(192|I>>6,128|63&I):n.push(224|I>>12,128|I>>6&63,128|63&I)}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 ms(s,n){if(mA.includes(s))return 0;const g=Na(JSON.stringify(n));let I=4294967295;const{length:E}=g;for(let m=0;m>>=1:I=I>>>1^3988292384}return(4294967295^I)>>>0}function Ia(s){const{servcmd:n,data:g}=s,I=function(m){const D=Zi.get("login")||{},M=Zi.get("instance")||{};return{servcmd:m,ver:"v4",platform:qA,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:ya(),cs:0}}(n),E=In(g);return I.cs=ms(n,E),{head:I,body:E}}function yn(s){const{servcmd:n,data:g}=s,I=function(m){const D=Zi.get("login")||{},M=Zi.get("instance")||{};return{servcmd:m,ver:"v4",platform:qA,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:ya(),cs:0}}(n),E=In(g);return I.cs=ms(n,E),{head:I,body:E}}let Ga=F();function ya(){return Ga=Ga<2415919103?Ga+1:F(),Ga}function $(){var s;const n=Zi.get("login")||{},g=Zi.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=Zi.get("webPush"))===null||s===void 0?void 0:s.userId),platform:qA,instance_id:g.instanceId,trace_id:new Date().getTime()}}var K,RA=Object.freeze({__proto__:null,calcBodyCRC:ms,filterProtocolDataInvalidFields:In,generateCosSpecifiedData:function(s){const{servcmd:n,data:g}=s,I=function(m){const D=Zi.get("login")||{},M=Zi.get("instance")||{};return{servcmd:m,ver:"v4",platform:qA,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:ya(),cs:0}}(n),E=In(g);return I.cs=ms(n,E),{head:I,body:E}},generateProtocolData:Ia,generateSSOLogProtocolData:yn,generateSequence:ya,getCommonHead:$,getHostSite:la,taskScheduler:fn,timeManager:Dg});(function(s){s[s.info=4]="info",s[s.warning=5]="warning",s[s.error=6]="error"})(K||(K={}));const KA={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=Dg.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:I=0,message:E="",costTime:m=0,error:D,uiPlatform:M,moreMessage:T="",code:P=0,startTime:W=0}=n||{};this.eventType=I,this.method=g,this.message=E,this.costTime=m,this.moreMessage=`${T} startTime:${W}`,this.code=P,D&&this.setError(D),vs(M)||(this.uiPlatform=M)}setMoreMessage(n){this.moreMessage=`${this.moreMessage} ${n}`}updateLogCreatedAtByTimeOffset(){this._logCreatedAt+=Dg.getTimeOffsetWithServer()}end(n=!1){this._canSendLog&&(this._canSendLog=!1,this.timestamp=Dg.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe()),n&&this._ssoLogModule.uploadSSOLogData())}setError(n){var g;return n instanceof Error?this._canSendLog?(!((g=Zi.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(KA).includes(g)&&(this[g]=n[g])}),this}setSSOLogModule(n){this._ssoLogModule=n}_convertSSOLogDataKeyToServe(){const n={};return Object.keys(this).forEach(g=>{const I=g;KA[I]&&(n[KA[I]]=this[I])}),n}_getUiPlatform(){var n;const g=(n=Zi.get("instance"))===null||n===void 0?void 0:n.scene;if(typeof g=="string"){const I=Number(g);return isNaN(I)?void 0:I}}_getSDKEdition(){var n;return(n=Zi.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 Fe=pe;const Ue=20,ot=6e4,ut=[4,5,6],St="report-logger";var Ot=new class{constructor(){this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._reportLevel=[4,5,6],this._minThreshold=Ue,this._maxThreshold=100,this._waitingTime=ot,this._lastReportAt=Date.now(),this._ssoLogMap=new Map,this._logLevel=IA.DEBUG,this._throttleConfig={global:{throttleTime:Ve,maxCount:Be},single:{throttleTime:ge,maxCount:de}},this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap=new Map,gn.subscribeInnerEvent(Fe.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),fn.addTask({id:St,intervalMs:1e3,callback:this._checkAndReportIfDue,context:this}),this._logQueue=[],this._savePlatFormInfo()}_handleCloudConfigUpdate(s){const{evt_rpt_threshold:n=Ue,evt_rpt_waiting:g=ot,evt_rpt_level:I=ut,evt_rpt_sdkappid_bl:E="",evt_rpt_tinyid_wl:m="",evt_rpt_global_throttle_time:D=Ve,evt_rpt_global_throttle_count:M=Be,evt_rpt_single_throttle_time:T=ge,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=I,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};vs(g.Header.user_id)||(yield function(I){const E="imopenstat.tim_web_report_v2",m=yn({servcmd:E,data:I}),D=`${m.head.seq}${E}`;return fe.sendPacket(m,{requestId:D})}(g))}catch(n){this._requeueFailedLogs(s),this.debug("uploadSSOLogData",An(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(It){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:I,envVersion:E}=g;Zi.set("instance",{appId:I,envVersion:E})}}else jt&&Zi.set("instance",{href:window.location.href})}_filterLogs(s){const{tinyID:n}=Zi.get("login")||{},{sdkAppId:g}=Zi.get("instance")||{};return this._sdkAppIdBlackList.includes(g)&&!this._tinyIdWhiteList.includes(n)?[]:s.filter(I=>this._reportLevel.includes(I.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(PA[s])}_formatLog(s,n,g,I){const E=new Date,m=`${E.getHours()}:${E.getMinutes()}:${E.getSeconds()}:${E.getMilliseconds()}`,D=`<${IA[s]}>`;return Rt||ki?[`${tA} [${m}] ${D} [${n}] ${g}`]:["%c%s%c%s","background:#0abf5b; padding:1px; border-radius:3px; color: #fff",tA,"",`[${m}] ${D} [${n}] ${g} params: ${An(I)}`]}_log(s,n,g,I){if(this._shouldLog(s)){const E=this._formatLog(s,n,g,I);MA[s].apply(console,E)}if(this._shouldReport(s)){const E=this._getThrottleKey(n,g,I);this._checkThrottle(E)||this.createSSOLogData(Object.assign(Object.assign({message:g},I),{method:n})).end()}}_getThrottleKey(s,n,g){const I=`${s}${n}${An(Object.assign(Object.assign({},g),{costTime:""}))}`,E=Na(JSON.stringify(I));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(St),gn.unSubscribeInnerEvent(Fe.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),this._lastReportAt=0,this.uploadSSOLogData(),this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._minThreshold=Ue,this._maxThreshold=100,this._waitingTime=ot,this._logQueue=[],this._logLevel=IA.DEBUG,this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap.clear()}};const li=15e3,nt="Channel",Ft="channel_schedule_task",Ji="channel_reconnect_task",qi="connected",Hs="connecting",Mi="disconnected",Wo=1e3,Sg="network_status_change",or="activity_status_change",fr="send_fail",xn="reconnect_failed",yl="socket_error",qs="socket_close";function tI(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function jg(s){return jg=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},jg(s)}function mc(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 Qu,Da={exports:{}},Dl=(Qu||(Qu=1,function(s){s.exports=function n(g,I,E){function m(T,P){if(!I[T]){if(!g[T]){if(!P&&mc)return mc(T);if(D)return D(T,!0);var W=new Error("Cannot find module '"+T+"'");throw W.code="MODULE_NOT_FOUND",W}var oA=I[T]={exports:{}};g[T][0].call(oA.exports,function(EA){return m(g[T][1][EA]||EA)},oA,oA.exports,n,g,I,E)}return I[T].exports}for(var D=mc,M=0;M>>6:(EA<65536?oA[YA++]=224|EA>>>12:(oA[YA++]=240|EA>>>18,oA[YA++]=128|EA>>>12&63),oA[YA++]=128|EA>>>6&63),oA[YA++]=128|63&EA);return oA},I.buf2binstring=function(W){return P(W,W.length)},I.binstring2buf=function(W){for(var oA=new E.Buf8(W.length),EA=0,wA=oA.length;EA>10&1023,SA[wA++]=56320|1023&kA)}return P(SA,wA)},I.utf8border=function(W,oA){var EA;for((oA=oA||W.length)>W.length&&(oA=W.length),EA=oA-1;0<=EA&&(192&W[EA])==128;)EA--;return EA<0||EA===0?oA:EA+M[W[EA]]>oA?EA:oA}},{"./common":1}],3:[function(n,g,I){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 oA=T;oA>>8^P[255&(m^D[oA])];return-1^m}},{}],6:[function(n,g,I){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,I){g.exports=function(E,m){var D,M,T,P,W,oA,EA,wA,kA,YA,LA,SA,OA,HA,se,oe,_i,Ti,bt,Ni,gs,De,Bt,UA,ii;D=E.state,M=E.next_in,UA=E.input,T=M+(E.avail_in-5),P=E.next_out,ii=E.output,W=P-(m-E.avail_out),oA=P+(E.avail_out-257),EA=D.dmax,wA=D.wsize,kA=D.whave,YA=D.wnext,LA=D.window,SA=D.hold,OA=D.bits,HA=D.lencode,se=D.distcode,oe=(1<>>=bt=Ti>>>24,OA-=bt,(bt=Ti>>>16&255)==0)ii[P++]=65535&Ti;else{if(!(16&bt)){if(!(64&bt)){Ti=HA[(65535&Ti)+(SA&(1<>>=bt,OA-=bt),OA<15&&(SA+=UA[M++]<>>=bt=Ti>>>24,OA-=bt,!(16&(bt=Ti>>>16&255))){if(!(64&bt)){Ti=se[(65535&Ti)+(SA&(1<>>=bt,OA-=bt,(bt=P-W)>3,SA&=(1<<(OA-=Ni<<3))-1,E.next_in=M,E.next_out=P,E.avail_in=M>>24&255)+(De>>>8&65280)+((65280&De)<<8)+((255&De)<<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(De){var Bt;return De&&De.state?(Bt=De.state,De.total_in=De.total_out=Bt.total=0,De.msg="",Bt.wrap&&(De.adler=1&Bt.wrap),Bt.mode=wA,Bt.last=0,Bt.havedict=0,Bt.dmax=32768,Bt.head=null,Bt.hold=0,Bt.bits=0,Bt.lencode=Bt.lendyn=new E.Buf32(kA),Bt.distcode=Bt.distdyn=new E.Buf32(YA),Bt.sane=1,Bt.back=-1,oA):EA}function HA(De){var Bt;return De&&De.state?((Bt=De.state).wsize=0,Bt.whave=0,Bt.wnext=0,OA(De)):EA}function se(De,Bt){var UA,ii;return De&&De.state?(ii=De.state,Bt<0?(UA=0,Bt=-Bt):(UA=1+(Bt>>4),Bt<48&&(Bt&=15)),Bt&&(Bt<8||15=Gi.wsize?(E.arraySet(Gi.window,Bt,UA-Gi.wsize,Gi.wsize,0),Gi.wnext=0,Gi.whave=Gi.wsize):(ii<(ws=Gi.wsize-Gi.wnext)&&(ws=ii),E.arraySet(Gi.window,Bt,UA-ii,ws,Gi.wnext),(ii-=ws)?(E.arraySet(Gi.window,Bt,UA-ii,ii,0),Gi.wnext=ii,Gi.whave=Gi.wsize):(Gi.wnext+=ws,Gi.wnext===Gi.wsize&&(Gi.wnext=0),Gi.whave>>8&255,UA.check=D(UA.check,Eg,2,0),_t=wt=0,UA.mode=2;break}if(UA.flags=0,UA.head&&(UA.head.done=!1),!(1&UA.wrap)||(((255&wt)<<8)+(wt>>8))%31){De.msg="incorrect header check",UA.mode=30;break}if((15&wt)!=8){De.msg="unknown compression method",UA.mode=30;break}if(_t-=4,Ya=8+(15&(wt>>>=4)),UA.wbits===0)UA.wbits=Ya;else if(Ya>UA.wbits){De.msg="invalid window size",UA.mode=30;break}UA.dmax=1<>8&1),512&UA.flags&&(Eg[0]=255&wt,Eg[1]=wt>>>8&255,UA.check=D(UA.check,Eg,2,0)),_t=wt=0,UA.mode=3;case 3:for(;_t<32;){if(xi===0)break A;xi--,wt+=ii[Gi++]<<_t,_t+=8}UA.head&&(UA.head.time=wt),512&UA.flags&&(Eg[0]=255&wt,Eg[1]=wt>>>8&255,Eg[2]=wt>>>16&255,Eg[3]=wt>>>24&255,UA.check=D(UA.check,Eg,4,0)),_t=wt=0,UA.mode=4;case 4:for(;_t<16;){if(xi===0)break A;xi--,wt+=ii[Gi++]<<_t,_t+=8}UA.head&&(UA.head.xflags=255&wt,UA.head.os=wt>>8),512&UA.flags&&(Eg[0]=255&wt,Eg[1]=wt>>>8&255,UA.check=D(UA.check,Eg,2,0)),_t=wt=0,UA.mode=5;case 5:if(1024&UA.flags){for(;_t<16;){if(xi===0)break A;xi--,wt+=ii[Gi++]<<_t,_t+=8}UA.length=wt,UA.head&&(UA.head.extra_len=wt),512&UA.flags&&(Eg[0]=255&wt,Eg[1]=wt>>>8&255,UA.check=D(UA.check,Eg,2,0)),_t=wt=0}else UA.head&&(UA.head.extra=null);UA.mode=6;case 6:if(1024&UA.flags&&(xi<(ho=UA.length)&&(ho=xi),ho&&(UA.head&&(Ya=UA.head.extra_len-UA.length,UA.head.extra||(UA.head.extra=new Array(UA.head.extra_len)),E.arraySet(UA.head.extra,ii,Gi,ho,Ya)),512&UA.flags&&(UA.check=D(UA.check,ii,ho,Gi)),xi-=ho,Gi+=ho,UA.length-=ho),UA.length))break A;UA.length=0,UA.mode=7;case 7:if(2048&UA.flags){if(xi===0)break A;for(ho=0;Ya=ii[Gi+ho++],UA.head&&Ya&&UA.length<65536&&(UA.head.name+=String.fromCharCode(Ya)),Ya&&ho>9&1,UA.head.done=!0),De.adler=UA.check=0,UA.mode=12;break;case 10:for(;_t<32;){if(xi===0)break A;xi--,wt+=ii[Gi++]<<_t,_t+=8}De.adler=UA.check=LA(wt),_t=wt=0,UA.mode=11;case 11:if(UA.havedict===0)return De.next_out=Lr,De.avail_out=ar,De.next_in=Gi,De.avail_in=xi,UA.hold=wt,UA.bits=_t,2;De.adler=UA.check=1,UA.mode=12;case 12:if(Bt===5||Bt===6)break A;case 13:if(UA.last){wt>>>=7&_t,_t-=7&_t,UA.mode=27;break}for(;_t<3;){if(xi===0)break A;xi--,wt+=ii[Gi++]<<_t,_t+=8}switch(UA.last=1&wt,_t-=1,3&(wt>>>=1)){case 0:UA.mode=14;break;case 1:if(Ni(UA),UA.mode=20,Bt!==6)break;wt>>>=2,_t-=2;break A;case 2:UA.mode=17;break;case 3:De.msg="invalid block type",UA.mode=30}wt>>>=2,_t-=2;break;case 14:for(wt>>>=7&_t,_t-=7&_t;_t<32;){if(xi===0)break A;xi--,wt+=ii[Gi++]<<_t,_t+=8}if((65535&wt)!=(wt>>>16^65535)){De.msg="invalid stored block lengths",UA.mode=30;break}if(UA.length=65535&wt,_t=wt=0,UA.mode=15,Bt===6)break A;case 15:UA.mode=16;case 16:if(ho=UA.length){if(xi>>=5,_t-=5,UA.ndist=1+(31&wt),wt>>>=5,_t-=5,UA.ncode=4+(15&wt),wt>>>=4,_t-=4,286>>=3,_t-=3}for(;UA.have<19;)UA.lens[YD[UA.have++]]=0;if(UA.lencode=UA.lendyn,UA.lenbits=7,DI={bits:UA.lenbits},Ol=T(0,UA.lens,0,19,UA.lencode,0,UA.work,DI),UA.lenbits=DI.bits,Ol){De.msg="invalid code lengths set",UA.mode=30;break}UA.have=0,UA.mode=19;case 19:for(;UA.have>>16&255,yI=65535&xg,!((Rr=xg>>>24)<=_t);){if(xi===0)break A;xi--,wt+=ii[Gi++]<<_t,_t+=8}if(yI<16)wt>>>=Rr,_t-=Rr,UA.lens[UA.have++]=yI;else{if(yI===16){for(Ku=Rr+2;_t>>=Rr,_t-=Rr,UA.have===0){De.msg="invalid bit length repeat",UA.mode=30;break}Ya=UA.lens[UA.have-1],ho=3+(3&wt),wt>>>=2,_t-=2}else if(yI===17){for(Ku=Rr+3;_t>>=Rr)),wt>>>=3,_t-=3}else{for(Ku=Rr+7;_t>>=Rr)),wt>>>=7,_t-=7}if(UA.have+ho>UA.nlen+UA.ndist){De.msg="invalid bit length repeat",UA.mode=30;break}for(;ho--;)UA.lens[UA.have++]=Ya}}if(UA.mode===30)break;if(UA.lens[256]===0){De.msg="invalid code -- missing end-of-block",UA.mode=30;break}if(UA.lenbits=9,DI={bits:UA.lenbits},Ol=T(P,UA.lens,0,UA.nlen,UA.lencode,0,UA.work,DI),UA.lenbits=DI.bits,Ol){De.msg="invalid literal/lengths set",UA.mode=30;break}if(UA.distbits=6,UA.distcode=UA.distdyn,DI={bits:UA.distbits},Ol=T(W,UA.lens,UA.nlen,UA.ndist,UA.distcode,0,UA.work,DI),UA.distbits=DI.bits,Ol){De.msg="invalid distances set",UA.mode=30;break}if(UA.mode=20,Bt===6)break A;case 20:UA.mode=21;case 21:if(6<=xi&&258<=ar){De.next_out=Lr,De.avail_out=ar,De.next_in=Gi,De.avail_in=xi,UA.hold=wt,UA.bits=_t,M(De,ln),Lr=De.next_out,ws=De.output,ar=De.avail_out,Gi=De.next_in,ii=De.input,xi=De.avail_in,wt=UA.hold,_t=UA.bits,UA.mode===12&&(UA.back=-1);break}for(UA.back=0;Pg=(xg=UA.lencode[wt&(1<>>16&255,yI=65535&xg,!((Rr=xg>>>24)<=_t);){if(xi===0)break A;xi--,wt+=ii[Gi++]<<_t,_t+=8}if(Pg&&!(240&Pg)){for(rc=Rr,Wm=Pg,XQ=yI;Pg=(xg=UA.lencode[XQ+((wt&(1<>rc)])>>>16&255,yI=65535&xg,!(rc+(Rr=xg>>>24)<=_t);){if(xi===0)break A;xi--,wt+=ii[Gi++]<<_t,_t+=8}wt>>>=rc,_t-=rc,UA.back+=rc}if(wt>>>=Rr,_t-=Rr,UA.back+=Rr,UA.length=yI,Pg===0){UA.mode=26;break}if(32&Pg){UA.back=-1,UA.mode=12;break}if(64&Pg){De.msg="invalid literal/length code",UA.mode=30;break}UA.extra=15&Pg,UA.mode=22;case 22:if(UA.extra){for(Ku=UA.extra;_t>>=UA.extra,_t-=UA.extra,UA.back+=UA.extra}UA.was=UA.length,UA.mode=23;case 23:for(;Pg=(xg=UA.distcode[wt&(1<>>16&255,yI=65535&xg,!((Rr=xg>>>24)<=_t);){if(xi===0)break A;xi--,wt+=ii[Gi++]<<_t,_t+=8}if(!(240&Pg)){for(rc=Rr,Wm=Pg,XQ=yI;Pg=(xg=UA.distcode[XQ+((wt&(1<>rc)])>>>16&255,yI=65535&xg,!(rc+(Rr=xg>>>24)<=_t);){if(xi===0)break A;xi--,wt+=ii[Gi++]<<_t,_t+=8}wt>>>=rc,_t-=rc,UA.back+=rc}if(wt>>>=Rr,_t-=Rr,UA.back+=Rr,64&Pg){De.msg="invalid distance code",UA.mode=30;break}UA.offset=yI,UA.extra=15&Pg,UA.mode=24;case 24:if(UA.extra){for(Ku=UA.extra;_t>>=UA.extra,_t-=UA.extra,UA.back+=UA.extra}if(UA.offset>UA.dmax){De.msg="invalid distance too far back",UA.mode=30;break}UA.mode=25;case 25:if(ar===0)break A;if(ho=ln-ar,UA.offset>ho){if((ho=UA.offset-ho)>UA.whave&&UA.sane){De.msg="invalid distance too far back",UA.mode=30;break}ho>UA.wnext?(ho-=UA.wnext,cl=UA.wsize-ho):cl=UA.wnext-ho,ho>UA.length&&(ho=UA.length),QC=UA.window}else QC=ws,cl=Lr-UA.offset,ho=UA.length;for(ar_i?(bt=cl[QC+YA[Bt]],Ni=_t[qu+YA[Bt]]):(bt=96,Ni=0),SA=1<>Lr)+(OA-=SA)]=Ti<<24|bt<<16|Ni,OA!==0;);for(SA=1<>=1;if(SA!==0?(wt&=SA-1,wt+=SA):wt=0,Bt++,--ln[De]==0){if(De===ii)break;De=W[oA+YA[Bt]]}if(ws{const M=new Uint8Array(D).slice(4);let T;try{T=Dl.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 I;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?Na(E).buffer:E;(I=this._socketAdapter)===null||I===void 0||I.send(P)}else this._pendingRequests.delete(g)})}_onConnect(s){const{socketId:n,event:g={}}=s||{};this._connectionId=n,this._connectionEstablishedTime=Date.now();const I=Date.now()-this._connectionStartTime,E=`${nt}.onConnect cost:${I} ms. socketID:${n} res:${JSON.stringify(g)}`;if(this._ssoLog({method:"onConnect",message:E}),this._checkPendingRequestsAndResend(),this._sendHeartbeatIfReady(),this._isReconnecting){const m=`${nt}.reconnect success`;this._ssoLog({method:"reconnectSuccess",message:m}),gn.emitInnerEvent(Fe.RECONNECTED),this._isReconnecting=!1}this._resetReconnectDelay(),this._handleConnectStateChange({state:qi,shouldEmitEvent:!0,shouldAttemptReconnect:!1})}_sendAck(s){const n=Ia({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=Ia({servcmd:"heartbeat.alive",data:{}});try{const g=`${n.head.seq}${n.head.servcmd}`;yield this.sendPacket(n,{requestId:g,timeout:3e3})}catch(g){const I=(s=Zi.get("netWorkMonitor"))===null||s===void 0?void 0:s.isNetworkOnline,E=`${nt}.sendHeartbeat failed. isNetWorkOnline:${I} error: ${An(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=_o?Date.now()+5e3:Date.now()+1e4}_handleNetworkStatusChange(s){const n=`${nt}.networkStatusChange ${JSON.stringify(s)}`;this._ssoLog({method:"networkStatusChange",message:n});const{isNetworkOnline:g,networkType:I}=s;g&&I!=="none"?this._handleConnectStateChange({state:qi,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Sg}):this._handleConnectStateChange({state:Mi,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Sg})}isPrivateNetWork(){const s=Zi.get("instance")||{};return s.proxyServer&&!s.fileDownloadProxy}_handleConnectStateChange(s){const{state:n,shouldAttemptReconnect:g,shouldEmitEvent:I,reason:E}=s,m=`${nt}._handleConnectStateChange currentConnectState: ${this._currentConnectState} shouldAttemptReconnect: ${g} shouldEmitEvent: ${I} reason: ${E}`;this._currentConnectState!==n&&(this._ssoLog({method:"handleConnectStateChange",message:m}),I&&(Ot.info("_handleConnectStateChange",` from ${this._currentConnectState} to ${n}`),gn.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:n}}),this._currentConnectState=n,n===Mi&&gn.emitInnerEvent(Fe.SOCKET_DISCONNECTED)),g&&(this._resetReconnectDelay(),fn.addTask({id:Ji,intervalMs:this._intendedDelay,callback:this._scheduleReconnectWithBackoff,context:this})))}_handleActivityStatusChange(s){var n,g;const I=(g=(n=this._socketAdapter)===null||n===void 0?void 0:n._ws)===null||g===void 0?void 0:g.readyState,E=`${nt}.activityStatusChange ${JSON.stringify(s)} readyState: ${I}`;Ot.debug("activityStatusChange",E),I===3&&this._handleConnectStateChange({state:Mi,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:or})}_resetReconnectDelay(){var s;Ot.debug(`${nt}._resetReconnectDelay`),fn.removeTask(Ji);const n=(s=Zi.get("activityMonitor"))===null||s===void 0?void 0:s.isActive;this._intendedDelay=n?Wo:1e3}_scheduleReconnectWithBackoff(){var s;const n=(s=Zi.get("activityMonitor"))===null||s===void 0?void 0:s.isActive;this._intendedDelay=n?Math.min(5e3,Math.max(Wo,1.5*this._intendedDelay)):Math.min(3e5,Math.max(1e3,1.5*this._intendedDelay));const g=new Date().toTimeString().slice(0,8),I=`${nt}.scheduleReconnectWithBackoff timeStr: ${g} intendedDelay: ${this._intendedDelay}`;Ot.debug(I),this.reconnect(),fn.updateTaskInterval(Ji,this._intendedDelay)}_ssoLog(s){const{method:n,message:g}=s;Ot.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(I){Ot.warn("diagnoseBySSO",`diagnoseBySSO failed. error:${I.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){Ot.warn(`diagnoseByCDN', 'diagnoseByCDN failed. error:${g.message}`)}})}(this._url),this._beforeSendInterceptors=[])}_clearTimeoutRequest(){for(const[s,n]of this._pendingRequests.entries()){const{reject:g,timestamp:I,timeout:E}=n;Date.now()-I>=E&&(this._pendingRequests.delete(s),Date.now()-this._lastDiagnoseAt>=3e4&&this._diagnose(),g({errorCode:Br,errorInfo:"NETWORK_TIMEOUT",data:{requestId:s}}))}}_updateIsBinarySupported(){var s;if(!((s=Zi.get("instance"))===null||s===void 0)&&s.devMode)return void(this._isBinarySupported=!1);const n=us();if((gi||It&&n==="windows"||Ys)&&(this._isBinarySupported=!1),_o){const{uniRuntimeVersion:g=""}=io.getSystemInfoSync();(function(I){const E=I.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 me={init:function(s){Zi.set("instance",s),fe.init()},destroy:function(){fe.dispose(),Zi.clear(),fn.dispose()},notificationCenter:gn,channel:fe,store:Zi,ssoLog:Ot,utils:fg,common:RA,constants:Dt},Mg=s=>typeof s=="function";function ng(s,n,g){const I=g||[];if(!s||!n)return!1;const E=Object.keys(s).filter(D=>!I.includes(D)),m=Object.keys(n).filter(D=>!I.includes(D));return E.length===m.length&&E.every(D=>!!n.hasOwnProperty(D)&&(typeof s[D]=="object"&&s[D]!==null?ng(s[D],n[D],g):s[D]===n[D]))}var vg;(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"})(vg||(vg={}));var Dn,yr=vg;(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 Jc=Ii;const Wg=Object.assign({},{KICKED_OUT_MULT_ACCOUNT:"multipleAccount",KICKED_OUT_MULT_DEVICE:"multipleDevice",KICKED_OUT_USERSIG_EXPIRED:"userSigExpired",KICKED_OUT_REST_API:"REST_API_Kick"}),Rg={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 Or;(function(s){s.UNSENT="unSend",s.SUCCESS="success",s.FAIL="fail"})(Or||(Or={}));const fc={modify:so.MESSAGE_MODIFIED,delete:so.MESSAGE_DELETED,revoke:so.MESSAGE_REVOKED};var Hc;(function(s){s[s.FORWARD=0]="FORWARD",s[s.BACKWARD=1]="BACKWARD"})(Hc||(Hc={}));const rg=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Rg),{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:Or,Direction:Hc}),pu={[fc.modify]:so.TOPIC_MESSAGE_MODIFIED,[fc.delete]:so.TOPIC_MESSAGE_DELETED,[fc.revoke]:so.TOPIC_MESSAGE_REVOKED},uE={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"},wg=Object.assign({},uE),ba={CONV_C2C:"C2C",CONV_GROUP:"GROUP",CONV_TOPIC:"TOPIC",CONV_SYSTEM:"@TIM#SYSTEM"},yc=Object.assign(Object.assign(Object.assign(Object.assign({},ba),{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"}),EE=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"}),ka={GRP_WORK:"Private",GRP_PUBLIC:"Public",GRP_MEETING:"ChatRoom",GRP_AVCHATROOM:"AVChatRoom",GRP_COMMUNITY:"Community",GRP_ROOM:"Room",GRP_LIVE:"Live"},oa={COMMUNITY:"@TGS#_",TOPIC:"@TOPIC#_"},_g={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},iI=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},ka),{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:oa,GROUP_TIPS_OPERATION_TYPE:_g}),Cs={IOS_OFFLINE_PUSH_NO_SOUND:"push.no_sound",IOS_OFFLINE_PUSH_DEFAULT_SOUND:"default"},ko=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Wg),rg),wg),yc),EE),iI),Cs),{NET_STATE_CONNECTING:"connecting",NET_STATE_DISCONNECTED:"disconnected",NET_STATE_CONNECTED:"connected"}),ua={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},sr={BASIC:"1",STANDARD:"2",PROFESSIONAL:"3",NODE:"4"},Pt={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"},Ht={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"},Tg={[Pt.SYNC_SERVER_INFO_AFTER_RE_ONLINE]:[{stepId:Ht.USER_STATUS_UPDATE},{stepId:Ht.GROUP_ATTRIBUTE_CACHE_CLEAR},{stepId:Ht.UNREAD_MESSAGE_SYNC,dependency:Ht.C2C_HISTORY_MESSAGE_RECOVER},{stepId:Ht.CONVERSATION_RECOVER},{stepId:Ht.HISTORY_MESSAGE_RECOVER,dependency:Ht.CONVERSATION_RECOVER},{stepId:Ht.BLACKLIST_RECOVER},{stepId:Ht.FRIEND_RECOVER},{stepId:Ht.FRIEND_APPLICATION_LIST_RECOVER},{stepId:Ht.GROUP_REVOKED_NOTICE_RECOVER,dependency:Ht.HISTORY_MESSAGE_RECOVER},{stepId:Ht.GROUP_TIPS_RECOVER,dependency:Ht.HISTORY_MESSAGE_RECOVER},{stepId:Ht.TOPIC_REQUEST_INFO_RESET},{stepId:Ht.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,dependency:Ht.UNREAD_MESSAGE_SYNC},{stepId:Ht.HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD,dependency:Ht.UNREAD_MESSAGE_SYNC},{stepId:Ht.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Ht.UNREAD_MESSAGE_SYNC,Ht.CONVERSATION_RECOVER]},{stepId:Ht.EMIT_C2C_MESSAGE_EVENT,dependency:[Ht.UNREAD_MESSAGE_SYNC,Ht.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED],skipIfDependencyMissing:!1},{stepId:Ht.C2C_HISTORY_MESSAGE_RECOVER,dependency:Ht.CONVERSATION_RECOVER},{stepId:Ht.STREAM_MESSAGE_RECOVER}],[Pt.SYNC_SERVER_INFO_AFTER_LOGIN]:[{stepId:Ht.COMMERCIAL_CONFIG_UPDATE},{stepId:Ht.CLOUD_CONFIG_SYNC},{stepId:Ht.USER_PROFILE_SYNC},{stepId:Ht.UNREAD_MESSAGE_SYNC},{stepId:Ht.FRIEND_AND_BLACKLIST_SYNC},{stepId:Ht.GROUP_LIST_SYNC},{stepId:Ht.CONVERSATION_LIST_SYNC},{stepId:Ht.SIGNALING_MESSAGE_RECOVER,dependency:Ht.UNREAD_MESSAGE_SYNC},{stepId:Ht.UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED,dependency:[Ht.UNREAD_MESSAGE_SYNC]},{stepId:Ht.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Ht.UNREAD_MESSAGE_SYNC,Ht.CONVERSATION_LIST_SYNC]},{stepId:Ht.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,dependency:[Ht.GROUP_LIST_SYNC,Ht.CONVERSATION_LIST_SYNC]},{stepId:Ht.CONVERSATION_GROUP_LIST_SYNC},{stepId:Ht.CONVERSATION_GROUP_UPDATE,dependency:[Ht.CONVERSATION_LIST_SYNC,Ht.CONVERSATION_GROUP_LIST_SYNC]},{stepId:Ht.QUALITY_REPORT}],[Pt.RECEIVE_C2C_NEW_MESSAGE]:[{stepId:Ht.HANDLE_C2C_NEW_MESSAGE},{stepId:Ht.UNREAD_MESSAGE_SYNC},{stepId:Ht.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Ht.HANDLE_C2C_NEW_MESSAGE},{stepId:Ht.EMIT_C2C_MESSAGE_EVENT,dependency:[Ht.HANDLE_C2C_NEW_MESSAGE,Ht.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1},{stepId:Ht.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Ht.UNREAD_MESSAGE_SYNC]}],[Pt.RECEIVE_GROUP_NEW_MESSAGE]:[{stepId:Ht.HANDLE_GROUP_NEW_MESSAGE},{stepId:Ht.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Ht.HANDLE_GROUP_NEW_MESSAGE},{stepId:Ht.UPDATE_GROUP_NEXT_SEQUENCE,dependency:Ht.HANDLE_GROUP_NEW_MESSAGE},{stepId:Ht.UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE,dependency:Ht.HANDLE_GROUP_NEW_MESSAGE},{stepId:Ht.EMIT_GROUP_MESSAGE_EVENT,dependency:[Ht.HANDLE_GROUP_NEW_MESSAGE,Ht.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1}],[Pt.RECEIVE_GROUP_TIPS_NOTIFICATION]:[{stepId:Ht.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:Ht.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Ht.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:Ht.EMIT_GROUP_TIPS_EVENT,dependency:[Ht.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,Ht.HANDLE_GROUP_TIPS_NOTIFICATION],skipIfDependencyMissing:!1}]},oI={MESSAGE_SEND_SUCCESS_RATE:"messageSendSuccessRate"},nr={TOTAL_COUNT:"sendMessageTotalCount",SUCCESS_COUNT:"sendMessageSuccessCount",FAILED_COUNT:"sendMessageFailedCount",SEND_COST:"sendMessageCost"},UI=["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 Wa=Object.freeze({__proto__:null,ERROR_CODE:ua,InnerEvent:so,NEED_LOG_API:UI,OuterConstant:ko,OuterEvent:yr,PUSH:Cs,QUALITY_METRICS:oI,SDK_EDITION:sr,SDK_INFO:{VERSION:"1.7.3",APPID:537048168},SEND_MESSAGE_STAT:nr,SignalingEvent:Jc,WEB_PUSH_ACCOUNT_TYPE:1,WORKFLOW_DEFINITIONS:Tg,WORKFLOW_NAME:Pt,WORKFLOW_STEP:Ht}),sa,un,Sn;(function(s){s[s.USER_INITIATED=0]="USER_INITIATED",s[s.KICKED_OUT=1]="KICKED_OUT"})(sa||(sa={})),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 mu={[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"},Ng="login_online_presence_task",{ERROR:La,DESTROY:qc,FORCE_OFFLINE:FI}=so,{KICKED_OUT_MULT_ACCOUNT:dE,KICKED_OUT_MULT_DEVICE:sI,KICKED_OUT_REST_API:fu,ACCOUNT_A2KEY_EXPIRED:Sl,MSG_A2KEY_EXPIRED:Dc}=ua;class yu{init(){const{notificationCenter:n}=me;n.subscribeInnerEvent(FI,this._handleForceOfflineFromServerPush,this),n.subscribeInnerEvent(La,Dc,this._handleForceOfflineFromResponse,this,this._isChatLoginEvent),n.subscribeInnerEvent(La,Sl,this._handleForceOfflineFromResponse,this,this._isChatLoginEvent),n.subscribeInnerEvent(La,dE,this._handleForceOfflineFromResponse,this),n.subscribeInnerEvent(La,sI,this._handleForceOfflineFromResponse,this),n.subscribeInnerEvent(La,fu,this._handleForceOfflineFromResponse,this),n.subscribeInnerEvent(qc,this._dispose,this)}_handleForceOfflineFromServerPush(n){var g;if(((g=me.store.get("login"))===null||g===void 0?void 0:g.isLoggedIn)===!0){const{EventArray:I=[]}=n?.body||{};this._extractKickedOutMessages(I).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,I)=>[...g,...I.C2cNotifyMsgArray||[]],[]).filter(g=>{var I;return this._isKickedOut((I=g?.KickoutMsgNotify)===null||I===void 0?void 0:I.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:I,utils:{safeStringify:E}}=me;try{this._logKickedOutEvent(n),this._shouldLogoutAfterKickedOut(g)?yield me.login.loginAction.logout(sa.KICKED_OUT):me.login.loginAction.handleLogoutCompleted()}catch(m){I.debug("_processKickedOutReasonInfo",` fail ${E(m)}`)}finally{me.notificationCenter.emitOuterEvent(yr.KICKED_OUT,{data:{type:mu[g]},name:yr.KICKED_OUT})}})}_logKickedOutEvent(n){const{kickedOutReasonCode:g,newInstanceInfo:I={}}=n,E=`type:${mu[g]} newInstanceInfo: ${JSON.stringify(I)}`;me.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:I}=me.store.get("login")||{};return g===!0&&n===I}_dispose(){const{notificationCenter:n}=me;n.unSubscribeInnerEvent(FI,this._handleForceOfflineFromServerPush,this),n.unSubscribeInnerEvent(La,Sl,this._handleForceOfflineFromResponse,this),n.unSubscribeInnerEvent(La,Dc,this._handleForceOfflineFromResponse,this),n.unSubscribeInnerEvent(La,dE,this._handleForceOfflineFromResponse,this),n.unSubscribeInnerEvent(La,sI,this._handleForceOfflineFromResponse,this),n.unSubscribeInnerEvent(La,fu,this._handleForceOfflineFromResponse,this),n.unSubscribeInnerEvent(qc,this._dispose,this)}}function Du(s){return pA(this,void 0,void 0,function*(){const n="im_open_status.wslogin",g=me.common.generateProtocolData({servcmd:n,data:{State:"Online",is_web_uniapp:0,InstType:0,CustomInfo:s}}),I=`${g.head.seq}${n}`,E=yield me.channel.sendPacket(g,{timeout:9e4,requestId:I});if(E){const{HelloInterval:m,InstId:D,TinyId:M,TimeStamp:T,CustomStatus:P,PurchaseBits:W,A2Key:oA,RichMsgAuthKey:EA,ErrorCode:wA,ErrorInfo:kA,ActionStatus:YA}=E;return{helloInterval:m,instanceID:D,tinyID:M,timeStamp:T,customStatus:P,purchaseBits:W,a2Key:oA,authKey:EA,errorCode:wA,errorInfo:kA,actionStatus:YA}}})}function Ml(){const{store:s}=me;return la(s.get("instance").sdkAppId)!==ct.CHINA}function ss(s){var n;try{const g=Zi.getStorage("errorMessage");if(!s||!g)return"";const I=((n=JSON.parse(g))===null||n===void 0?void 0:n.errorMessage)||{},{code:E,replacement1:m="",replacement2:D=""}=s;if(!E)return"";const M=Ml()?`${E}_en`:`${E}_cn`;let T=I[I[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 as extends Error{constructor(n={}){n.code=n.code||n.errorCode;let{functionName:g="Unknown",code:I,message:E="",data:m="",moreMessage:D="",errorMessage:M=""}=n;M=(I?ss(n):"")||M||E;let T=I?`${g} failed. error: {"message": ${M}, "code": ${I}}`:`${g} failed. error: {"message": ${M}}`;T=`${T} ${D}`,super(),this.code=I,this.errorCode=I,this.errorMessage=M,this.message=T,this.data=m}}function td(s,n){var g;if(s&&((g=me.store.get("login"))===null||g===void 0?void 0:g.isLoggedIn)!==!0)throw new as({code:ua.USER_NOT_LOGGED_IN,functionName:n})}function nI(s,n,g){if(Array.isArray(s))for(let I=0;I{return P===(W=I,Object.prototype.toString.call(W).match(/^\[object (.*)\]$/)[1].toLowerCase());var W})){for(let W=0;W{const{interceptor:E,context:m}=I;E.apply(m,[g])})}(s)}function Sc(s,n){CE.push({interceptor:s,context:n})}function Kc(s){const{params:n,auth:g}=s;n&&typeof n=="object"&&Object.assign(vl,n),g&&typeof g=="object"&&Object.assign(id,g)}function en(s){return me.store.get("commercialConfig").get(s)}class Rs{constructor(){this._handlers=new Map,this._activeWorkflows=new Map,this._stepStartTimes=new Map,this._logHandlers={start:(n,g)=>{const I=Date.now();g?(this._stepStartTimes.set(`${n}-${g}`,I),me.ssoLog.debug("_executeWorkflowStep",`[Workflow ${n}] Step ${g} started at ${new Date(I).toISOString()}`)):(this._workflowStartTimes.set(n,I),me.ssoLog.debug("_executeWorkflowStep",`[Workflow ${n}] started at ${new Date(I).toISOString()}`))},success:(n,g)=>{const I=Date.now();if(g){const E=this._stepStartTimes.get(`${n}-${g}`),m=E?I-E:0;this._stepStartTimes.delete(`${n}-${g}`),me.ssoLog.debug("_executeWorkflowStep",`[Workflow ${n}] Step ${g} completed successfully at ${new Date(I).toISOString()} (${m}ms)`)}else{const E=this._workflowStartTimes.get(n),m=E?I-E:0;this._workflowStartTimes.delete(n),me.ssoLog.debug("_executeWorkflowStep",`[Workflow ${n}] completed successfully at ${new Date(I).toISOString()} (${m}ms)`)}},error:(n,g,I)=>{const{ssoLog:E,utils:{safeStringify:m}}=me,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(I)}`,{error:I})}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(I)}`,{error:I})}}}}static getInstance(){return Rs._instance||(Rs._instance=new Rs),Rs._instance}static setInstance(n){Rs._instance=n}init(){this._initializeWorkflows()}registerWorkflowStep(n,g,I,E){if(!this._handlers.has(n))return void me.ssoLog.debug("registerWorkflowStep",`Workflow '${n}' not defined in core`);if(!Tg[n].find(D=>D.stepId===g))return void me.ssoLog.debug("registerWorkflowStep",`Step '${g}' not defined in workflow '${n}'`);const m=this._handlers.get(n);m.has(g)||m.set(g,E?I.bind(E):I)}executeWorkflow(n,g){return pA(this,void 0,void 0,function*(){if(!this._validateWorkflow(n))return;me.ssoLog.debug("executeWorkflow",`[Workflow ${n}] Started execution at ${new Date().toISOString()}`);const I=Tg[n],E={},m={cancelled:!1};this._activeWorkflows.set(n,{cancelToken:m});try{const D=new Map;I.forEach(T=>{D.set(T.stepId,T)});const M={workflowName:n,pendingSteps:new Set(I.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(oA=>!M.runningSteps.has(oA)).forEach(oA=>{M.completedSteps.has(oA)||M.runningSteps.has(oA)||this._executeWorkflowStep(oA,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&&(me.ssoLog.debug("executeWorkflow",`Workflow ${n} completed with some steps skipped due to dependency failures`),T())},onError:P,onStepComplete:W})})};W()}),me.ssoLog.debug("executeWorkflow",`[Workflow ${n}] Completed execution at ${new Date().toISOString()}`)}catch(D){me.ssoLog.error("executeWorkflow",`[Workflow ${n}] Failed execution at ${new Date().toISOString()}`,{error:D})}finally{this._activeWorkflows.delete(n)}})}_executeWorkflowStep(n,g,I){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 oA=this._handlers.get(E).get(n);if(oA){const EA=yield Promise.resolve(oA({data:T,result:W}));M[n]=EA,this._logWorkflowExecution(E,n,"success")}g.completedSteps.add(n)}catch(P){const W=`[Workflow].${E}.${n}`,{errorCode:oA,errorInfo:EA=`${W} failed`}=P||{},wA=new as({functionName:W,code:oA,message:EA});me.ssoLog.error(W,EA,{error:wA}),this._logWorkflowExecution(E,n,"error",P),I.onError(P)}finally{m.delete(n),g.pendingSteps.delete(n),I.onStepComplete(),I.onComplete()}})}reset(){this._cancelAllWorkflows()}destroy(){this.reset(),this._handlers.clear()}_initializeWorkflows(){Object.keys(Tg).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:I}=g;I.cancelled=!0,this._activeWorkflows.delete(n)}_cancelAllWorkflows(){Object.keys(Tg).forEach(n=>{this._cancelWorkFlow(n)})}_validateWorkflow(n){return Tg[n]?!!this._handlers.get(n):!1}_getExecutableSteps(n){const{pendingSteps:g,completedSteps:I,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})?I.has(T):!P;if(p(T)){if(T.filter(W=>!this._isStepRegistered({workflowName:m,stepId:W})).length>0&&P)return!1;for(const W of T)if(!I.has(W))return!1;return!0}return!1})}_isStepRegistered(n){var g;const{workflowName:I,stepId:E}=n;return(g=this._handlers.get(I))===null||g===void 0?void 0:g.has(E)}_logWorkflowExecution(n,g,I,E){this._logHandlers[I](n,g)}}const Ea=new Map,zr=({type:s,groupID:n})=>s===ko.GRP_COMMUNITY||`${n}`.startsWith(oa.COMMUNITY)&&!`${n}`.includes(oa.TOPIC),jc=(s="")=>{const n=s.startsWith("GROUP")?s.replace("GROUP",""):s;return n.startsWith(oa.COMMUNITY)&&`${n}`.includes(oa.TOPIC)},od="openim",zg="million_group_open_http_svc";function ag(s){return pA(this,void 0,void 0,function*(){const{servcmd:n,data:g}=function(m){const{data:D}=m;return hE(D)||Zg(D)}(s)?function(m){let{servcmd:D,data:M}=m;return Zg(M)?function(T){const{servcmd:P,data:W}=T;let{GroupId:oA=""}=W;const EA=oA;return[oA]=EA.split(oa.TOPIC),{servcmd:qn(P),data:Object.assign(Object.assign({},W),{GroupId:oA,TopicId:EA})}}(m):(hE(M)&&(D=qn(D)),{servcmd:D,data:M})}(s):s,I=me.common.generateProtocolData({servcmd:n,data:g}),E=`${I.head.seq}${n}`;return me.channel.sendPacket(I,{requestId:E,timeout:s.timeout})})}function hE(s){const{Type:n,GroupId:g,GroupIdList:I=[]}=s,E=g||I[0]||"";return zr({type:n,groupID:E})}function Zg(s){const{GroupId:n=""}=s;return jc(n)}function qn(s){if(s.includes(od))return s;const n=s.split(".")[1];return`${zg}.${n}`}function Ar(){var s;return(s=me.store.get("login"))===null||s===void 0?void 0:s.userId}const Ua=s=>p(s)||y(s),sd=(s,n,g,I)=>{if(!Ua(s)||!Ua(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===ko.MSG_TEXT)return n.text||"";const g=OI[s];return g?Su(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}],PI="im_sdk_config_mgr.fetch_config",aI="im_sdk_config_mgr.push_configv2",Zc="cloud-config",Xc=2996,Sa=new class{init(s){this.core=s}};function Gg(s){return pA(this,void 0,void 0,function*(){const{sdkAppId:n}=Sa.core.store.get("instance")||{},g=Sa.core.helper.generateProtocolData({servcmd:PI,data:{uint32_sdkappid:n,uint64_version:s}}),I=`${g.head.seq}${PI}`;return Sa.core.channel.sendPacket(g,{requestId:I})})}var fs=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:I,constants:{WORKFLOW_NAME:E,WORKFLOW_STEP:m},channel:D}=s;n.subscribeInnerEvent(aI,this._handlePushedConfig,this),I.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),I.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:I,methodCallCounter:E}=this._methodCallFrequencyMap.get(s);if(Date.now()-I>1e3*g)this._methodCallFrequencyMap.set(s,{startTime:Date.now(),methodCallCounter:1});else if(E+=1,this._methodCallFrequencyMap.set(s,{startTime:I,methodCallCounter:E}),E>n)throw new this._core.helper.ChatError({code:Xc,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 Gg(this._version);s.info("_fetchCloudConfigIfLogin",n(g)),yield this._updateCloudConfig(g)}this._core.helper.taskScheduler.addTask({id:Zc,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 Gg(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:I,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(I),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(I){console.warn(I)}})}_updateCmdFreqLimitMap(s){s.forEach(n=>{this._cmdFrequencyLimitMap.set(n.cmd,{interval:n.interval,count:n.count})})}_reset(){this._core.helper.taskScheduler.removeTask(Zc),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(aI,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 I=8-g.length;for(;I;)g=`0${g}`,I--}return n+g}}const Mc={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()},xI="CommercialConfig",YI="commercial-config";var BE=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:I,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(I.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 I,E=!0;for(let m=g-1,D=0;m>=0;m--,D++)if(n.charAt(m)==="1"&&(I=D<32?new Kn(0,2**D).toString():new Kn(2**(D-32),0).toString(),!this._featureMap.get(I))){E=!1;break}return this._core.ssoLog.debug("isFeatureEnabled",`${xI}.isFeatureEnabled decimalNumber:${s} key:${I} 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:I}}=this._core;try{this._isFetching=!0;const E=yield I({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:YI,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:I,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",`${xI}._parseCommercialConfig failed. Invalid message format:`,s),this._expirationTime=Date.now()+36e5):(n.warn("_parseCommercialConfig",`${xI}._parseCommercialConfig errorCode:${g} errorMessage:${I}`),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 I=null;for(let E=s.length-1,m=0;E>=0;E--,m++)if(I=m<32?new Kn(0,2**m).toString():new Kn(2**(m-32),0).toString(),s[E]==="1"){this._featureMap.set(I,!0);const D=this._getKeyByValue(Mc,I);D&&this._methodKeyMap.set(D,!0)}else{this._featureMap.set(I,!1);const D=this._getKeyByValue(Mc,I);D&&this._methodKeyMap.set(D,!1)}}else n.warn("_parsePurchaseBits",`${xI}.parsePurchaseBits invalid purchases:${g(s)}`)}_getKeyByValue(s,n){const g=Object.entries(s).find(([I,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(YI),this._core.store.set("commercialConfig",{}),this._expirationTime=0,this._isFetching=!1,this._featureMap.clear(),this._purchaseBits="0"}},zC=new class{constructor(){this._core=null,this._serverOverloadInfoMap=new Map}install(s){this._core=s;const{notificationCenter:n,InnerEvent:g,channel:I}=this._core;n.subscribeInnerEvent(g.OVERLOAD_PUSH,this._handleOverLoadPush,this),n.subscribeInnerEvent(g.LOGOUT,this._reset,this),n.subscribeInnerEvent(g.DESTROY,this._dispose,this),I.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)}},eC=new class{constructor(){this.name="ConfigCenter"}install(s){Sa.init(s),fs.install(s),BE.install(s),zC.install(s)}},ZC=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={},I=new RegExp(/'/g);for(let E=0;E{var HA,se,oe;const _i=function(Ti,bt){const{From_Account:Ni,From_AccountHeadurl:gs,From_AccountNick:De,IsNeedReadReceipt:Bt,MsgBody:UA,MsgClientTime:ii,MsgRandom:ws,MsgSeq:Gi,MsgTimeStamp:Lr,SendMsgControl:xi,SupportMessageExtension:ar,To_Account:wt,TinyId:_t,MsgCheckResult:qu,CloudCustomData:ln,IsPeerRead:ho,MsgFlagBits:cl,MsgVersion:QC,EventArray:Rr}=Ti;return{from:Ni,avatar:gs,nick:De,needReadReceipt:Bt===1,readReceiptSentByPeer:ho,clientTime:ii,messageFlagBits:cl,random:ws,sequence:Gi,time:Lr,messageControlInfo:xi,isSupportExtension:ar,to:wt,tinyID:_t,checkResult:qu,cloudCustomData:ln,messageVersion:QC,eventArray:Rr,elements:bt.message.messageHelper.parseServerPushMessageElement(UA)}}(OA,YA);if(!((oe=(se=(HA=OA?.EventArray)===null||HA===void 0?void 0:HA[0])===null||se===void 0?void 0:se.hasOwnProperty)===null||oe===void 0)&&oe.call(se,"C2cNotifyMsgArray"))SA.push(...function(Ti){var bt;const Ni=[];return(bt=Ti.EventArray)===null||bt===void 0||bt.forEach(gs=>{var De,Bt;const{C2cNotifyMsgArray:UA}=gs,ii=(Bt=(De=UA?.[0])===null||De===void 0?void 0:De.WithdrawC2cMsgNotify)===null||Bt===void 0?void 0:Bt.C2cWithdrawInfoArray;Array.isArray(ii)&&Ni.push(...ii)}),Ni}(OA));else{const Ti=YA.message.messageFactory.createMessage(Object.assign(Object.assign({},_i),{conversationType:"C2C",flow:"in"})),{elements:bt}=_i;Ti.setElement(bt),LA.push(Ti)}}),{unreadMessageList:LA,revokedMessageList:SA}}(T.MsgList,n);return{syncFlag:T?.SyncFlag,unreadMessageList:EA,revokedMessageList:wA,unreadCountList:P,overflowUnreadCountList:W,cookie:T?.Cookie,groupTipList:oA}}catch(T){console.warn(T)}})}var bg,no;(function(s){s[s.START_SYNC=0]="START_SYNC",s[s.SYNCING=1]="SYNCING",s[s.SYNC_COMPLETE=2]="SYNC_COMPLETE"})(bg||(bg={})),function(s){s[s.LOGIN_SUCCESS=0]="LOGIN_SUCCESS",s[s.NEW_MESSAGE_RECEIVED=1]="NEW_MESSAGE_RECEIVED"}(no||(no={}));var tC=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:I=!1}=s||{};let E=bg.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:oA=[],overflowUnreadCountList:EA,unreadCountList:wA,groupTipList:kA}=P;if(this._cookie=P?.cookie||"",E=P?.syncFlag,this._parseAndSaveUnreadMessageList(W),M.push(...oA),this._updateConversationUnreadOptions({unreadCountList:wA,overflowUnreadCountList:EA,conversationUpdateFieldList:m}),Array.isArray(kA)&&D.push(...kA),n){const{messages:YA}=this._handleNewMessageList(W);T.push(...YA)}}return n?{conversationUpdateFieldList:m,revokedMessageList:M,unreadMessageMap:this._unreadDBMessageMap,groupTipList:D,messages:T,isUnreadC2CMessage:!0}:{conversationUpdateFieldList:m,isInstantMessage:!I,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:I}=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=I.find(({conversationID:W})=>W===`${E}${M}`);P?P.unreadCount=T:I.push({conversationID:`${E}${M}`,unreadCount:T,type:E})}}),g?.forEach(D=>{const{From_Account:M,LastMsgTime:T}=D;M!==m&&(I.find(({conversationID:P})=>P===`${E}${M}`)||I.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||{},I=(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!==I){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,I=[];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)||I.push(E);else if(this._shouldStoreUnreadMessage(E)){if(n.storeConversationMessage(E)){const{conversationID:D,conversationType:M,conversationSubType:T,flow:P,_isExcludedFromUnreadCount:W,_isExcludedFromLastMessage:oA}=E,EA=oA?"":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||I.push(E)}}),{messages:I,conversationOptions:g}}_shouldStoreUnreadMessage(s){var n;const{conversationID:g}=s,{message:I,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!I.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 $c(s,this._core);if(!E)return null;const{syncFlag:m,unreadMessageList:D,revokedMessageList:M,cookie:T,unreadCountList:P,overflowUnreadCountList:W,groupTipList:oA}=E;return this._parseAndSaveUnreadMessageList(D),{syncFlag:m,cookie:T,unreadMessageList:D,revokedMessageList:M,unreadCountList:P,overflowUnreadCountList:W,groupTipList:oA}}catch(I){console.log(I)}})}_canContinueSync({cookie:s,syncFlag:n}){var g;return n===bg.START_SYNC||n===bg.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),I=g[g.length-1];return I?.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()}},QE=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()}},pE=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,I,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})})):((I=m?.onAppShow)===null||I===void 0||I.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()}},nd=new class{init(s){const{IN_MINI_APP:n,IN_WX_MINI_PLUGIN:g}=s.helper;g||(n?pE.init(s):QE.init(s))}};const mE="none",Al="online";var gI=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:I,networkType:E}=s;(n=this._core)===null||n===void 0||n.store.set("netWorkMonitor",{isNetworkOnline:I,networkType:E}),(g=this._core)===null||g===void 0||g.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:I,networkType:E})}_onOnline(){this._onNetworkStatusChange({isConnected:!0,networkType:Al})}_onOffline(){this._onNetworkStatusChange({isConnected:!1,networkType:mE})}_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()}},Mu=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:I,networkType:E}=s;(n=this._core)===null||n===void 0||n.store.set("netWorkMonitor",{isNetworkOnline:I,networkType:E}),(g=this._core)===null||g===void 0||g.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:I,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()}},vu=new class{init(s){const{IN_MINI_APP:n}=s.utils;n?Mu.init(s):gI.init(s)}},iC=new class{constructor(){this.name="SystemStateMonitor"}install(s){nd.init(s),vu.init(s)}};const Mr=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.*"]),gg="tui_room_svr.*";var vc=new class{constructor(){this.name="BusinessCommandTransfer",this._transferredCommands=Mr}install(s){this._core=s;const{notificationCenter:n,InnerEvent:g,helper:I}=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),I.registerExperimentalAPI("sendTRTCCustomData",this,"transferBusinessCommand"),I.registerExperimentalAPI("sendRoomCustomData",this,"transferBusinessCommand")}transferBusinessCommand(s){return pA(this,void 0,void 0,function*(){const n="transferBusinessCommand";try{const{serviceCommand:g=gg}=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=gg,data:P}=E||{};let W={};try{W=typeof P=="string"?JSON.parse(P):P}catch(wA){console.warn(wA)}const oA=D.generateProtocolData({servcmd:T,data:W}),EA=`${oA.head.seq}${T}`;return M.sendPacket(oA,{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:I}=s||{},{ROOM_CUSTOM_DATA_RECEIVED:E}=n;g.emitOuterEvent(E,{name:E,data:I})}_reset(){this._transferredCommands=Mr}_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 Ru=1,Rl=2,rd=3,Zr=4,cI=5,_n="TIMCustomElem",oC="C2C",el="GROUP",ad="invite",lI="accept",Fa="cancel",sC="reject",Oa="modifyInvitation",Ir="signaling",gd=8010,wu="signaling-timeout";function ur(s){return s.filter(n=>{if(n.type===_n){const{cloudCustomData:g="",payload:{data:I=""}={}}=n,E=g.match(/"type":"tsignaling"/),m=I.match(/inviteID/),D=I.match(/actionType/);return E||m&&D}return!1})}function Rc(s){const{data:n}=s.payload;try{return JSON.parse(n)}catch(g){return console.error(g),null}}function tl(s,n){return s.toString(16).padStart(n,"0")}function kg(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=`${Ir}.updateSignaling`,{inviteID:g,inviter:I,inviteeList:E,groupID:m}=s;if(console.log(`${n} inviteID:${g} inviter:${I} 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()}},Xg=new class{init(s){this._core=s}createInviteSignaling(s){const n=this._generateInviteID(),g=this._createInviteSignalingData(Object.assign(Object.assign({},s),{inviteID:n})),{groupID:I,inviteeList:E}=g,m=I||E[0];return{signaling:this._createSignaling(g,m),signalingData:g,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createAcceptSignaling(s){const n=this._createAcceptSignalingData(s),{groupID:g,inviter:I}=n,E=g||I;return{signaling:this._createSignaling(n,E),signalingData:n,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createCancelSignaling(s){const n=this._createCancelSignalingData(s),{groupID:g,inviteeList:I}=n,E=g||I[0];return{signaling:this._createSignaling(n,E),signalingData:n,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createRejectSignaling(s){const n=this._createRejectSignalingData(s),{groupID:g,inviter:I}=n,E=g||I;return{signaling:this._createSignaling(n,E),signalingData:n,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createTimeoutSignaling(s){const{isInviter:n=!1}=s,g=this._createTimeoutSignalingData(s),{groupID:I,inviteeList:E,inviter:m}=g,D=I||(n?E[0]:m);return{signaling:this._createSignaling(g,D),signalingData:g,signalingExtensionOptions:this._createSignalingExtensionOptions(g)}}_createSignalingExtensionOptions(s){var n,g;const{data:I="",onlineUserOnly:E,inviteID:m="",offlinePushInfo:D,actionType:M}=s,T=((g=(n=Fo.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(I,M)}}_createMessageControlInfo(s,n){const g=n===cI&&!!s.match(/excludeTimeoutSignalingFromHistoryMessage/),I=!!s.match(/excludeFromHistoryMessage/)||!!s.match(/excludeOriginalSignalingFromHistoryMessage/);return{excludedFromContentModeration:!0,excludedFromUnreadCount:g||I,excludedFromLastMessage:g||I}}_createInviteSignalingData(s){const n=`${Ir}._createInviteSignalingData`,{userID:g,timeout:I=0,groupID:E="",inviteeList:m=[]}=s,D=this._core.common.getCurrentUserID(),M=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:Ru,inviter:D,inviteeList:E?m:[g],timeout:I});return console.log(`${n} signalingData:`,M),M}_createAcceptSignalingData(s){const n=`${Ir}._createAcceptSignalingData`,{inviteID:g}=s,I=this._core.common.getCurrentUserID(),{inviter:E,groupID:m}=Fo.getSignaling(g),D=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:rd,groupID:m,inviter:E,inviteeList:[I]});return console.log(`${n} signalingData:`,D),D}_createCancelSignalingData(s){const n=`${Ir}._createCancelSignalingData`,{inviteID:g}=s,I=this._core.common.getCurrentUserID(),{inviteeList:E,groupID:m}=Fo.getSignaling(g),D=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:Rl,groupID:m,inviter:I,inviteeList:E});return console.log(`${n} signalingData:`,D),D}_createRejectSignalingData(s){const n=`${Ir}._createRejectSignalingData`,{inviteID:g}=s,I=this._core.common.getCurrentUserID(),{inviter:E,groupID:m}=Fo.getSignaling(g),D=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:Zr,groupID:m,inviter:E,inviteeList:[I]});return console.log(`${n} signalingData:`,D),D}_createTimeoutSignalingData(s){const n=`${Ir}._createTimeoutSignalingData`,{isInviter:g=!1,inviteID:I}=s,{inviteeList:E,inviter:m}=Fo.getSignaling(I),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,I,E;const{groupID:m=""}=s,D={to:n,conversationType:m?el:oC,priority:"High",payload:{data:JSON.stringify(s)}};return(E=(I=(g=this._core)===null||g===void 0?void 0:g.message)===null||I===void 0?void 0:I.messageFactory)===null||E===void 0?void 0:E.createCustomMessage(D)}_generateInviteID(){return[tl(kg(32),8),tl(kg(16),4),tl(16384|kg(12),4),tl(32768|kg(14),4),tl(kg(48),12)].join("-")}_generateBaseSignalData(s){const{data:n="",inviteID:g="",groupID:I=""}=s;return{businessID:1,timeout:0,data:n,inviteID:g,groupID:I}}},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:I,signalingExtensionOptions:E}=Xg.createInviteSignaling(s),m=yield this._sendSignaling(g,E);if(m?.code===0){const{inviteID:D,timeout:M}=I;return Fo.saveSignaling(D,Object.assign(Object.assign({},I),{signaling:g})),M>0&&((n=this._core)===null||n===void 0||n.helper.taskScheduler.addOnceTask({id:`${wu}-${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:I,signalingExtensionOptions:E}=Xg.createAcceptSignaling(s),m=yield this._sendSignaling(g,E);return m?.code===0?(Fo.updateSignaling(I),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:I}=Xg.createCancelSignaling(s),E=yield this._sendSignaling(g,I);return E?.code===0?(Fo.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:I}=Xg.createRejectSignaling(s),E=yield this._sendSignaling(g,I);return E?.code===0?(Fo.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:I,data:E}=s;let m="";try{this._validateBeforeModifyInvitation(I);const D=Fo.getSignaling(I),{signaling:M}=D,T=yo(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 Fo.hasSignaling(I)&&Fo.saveSignaling(I,Object.assign(Object.assign({},T),{signaling:M})),P}catch(D){if(m){const{signaling:M}=Fo.getSignaling(I);M.payload.data=m}throw D}})}getSignalingInfo(s){const{ssoLog:n,utils:{safeStringify:g}}=this._core;if(ur([s]).length===0)return;const I=Rc(s),E={businessID:I.businessID||1,inviteID:I.inviteID,groupID:I.groupID||"",inviter:I.inviter||"",inviteeList:I.inviteeList||[],data:I.data||"",actionType:I.actionType||Ru,timeout:I.timeout||0};return n.debug(`${Ir} getSignalingInfo ${g(E)}`),E}addSignalingListener(s,n,g){var I,E;s===((I=this._core)===null||I===void 0?void 0:I.SignalingEvent.NEW_INVITATION_RECEIVED)&&Fo.setSignalingListenStatus(!0),(E=this._core)===null||E===void 0||E.notificationCenter.subscribeOuterEvent(s,n,g)}removeSignalingListener(s,n,g){var I,E;s===((I=this._core)===null||I===void 0?void 0:I.SignalingEvent.NEW_INVITATION_RECEIVED)&&Fo.setSignalingListenStatus(!1),(E=this._core)===null||E===void 0||E.notificationCenter.unSubscribeOuterEvent(s,n,g)}handleInvitationExpiryTimer(s){const n=Fo.getOnlineSignalingMap(),g=this._core.common.getCurrentUserID();if(!n.has(s))return;const I=n.get(s).inviter===g;this._sendTimeoutNotice({inviteID:s,isInviter:I})}_sendSignaling(s,n){return pA(this,void 0,void 0,function*(){var g,I,E;return(E=(I=(g=this._core)===null||g===void 0?void 0:g.message)===null||I===void 0?void 0:I.messageSender)===null||E===void 0?void 0:E.sendMessage(s,n)})}_sendTimeoutNotice(s){return pA(this,void 0,void 0,function*(){var n,g,I;this._core.ssoLog.debug("_sendTimeoutNotice",`${Ir}._sendTimeoutNotice params:${JSON.stringify(s)}`);const{isInviter:E,inviteID:m}=s,{signaling:D,signalingData:M,signalingExtensionOptions:T}=Xg.createTimeoutSignaling(s),P=yield this._sendSignaling(D,T);if(P?.code===0){const{data:W,groupID:oA,inviteeList:EA,inviter:wA}=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:(I=this._core)===null||I===void 0?void 0:I.SignalingEvent.INVITATION_TIMEOUT,data:{data:W,groupID:oA,inviteID:m,inviteeList:EA,inviter:wA,isSelfTimeout:!0,message:D}}),E?Fo.removeSignaling(m):Fo.updateSignaling(M)}})}_validateInviteId(s,n){if(!Fo.hasSignaling(n))throw new this._core.helper.ChatError({functionName:s,code:gd})}_validateProcessStatus(s){if(this._isProcessingSignaling)throw new this._core.helper.ChatError({functionName:s,message:"processing other signaling operations"})}_validateBeforeInvite(s){const n=ad,{userID:g}=s,I=this._core.common.getCurrentUserID();if(g===I)throw new this._core.helper.ChatError({functionName:n,message:`cannot invite yourself, currentUserId:${I}, inviteeId:${g}`})}_validateBeforeAccept(s){const n=lI;this._validateInviteId(n,s),this._validateProcessStatus(n);const g=this._core.common.getCurrentUserID(),{inviteeList:I}=Fo.getSignaling(s);if(!I.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=Fa;this._validateInviteId(n,s),this._validateProcessStatus(n);const g=this._core.common.getCurrentUserID(),{inviter:I}=Fo.getSignaling(s);if(I!==g){const E=`unmatched inviter:${I} and my userID:${g}`;throw new this._core.helper.ChatError({functionName:n,message:E})}}_validateBeforeReject(s){const n=sC;this._validateInviteId(n,s),this._validateProcessStatus(n);const g=this._core.common.getCurrentUserID(),{inviteeList:I}=Fo.getSignaling(s);if(!I.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=Oa;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}},wl=new class{constructor(){this._actionProcessor=new Map([[Ru,this._onNewInvitationReceived.bind(this)],[Zr,this._onInviteeRejected.bind(this)],[rd,this._onInviteeAccepted.bind(this)],[Rl,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=Rc(n);if(g){const I=this._actionProcessor.get(g.actionType);I?.(g,n)}})}_handleMessageReceived(s){if(!Fo.getSignalingListenStatus())return;const n=ur(s.data);n.length!==0&&this.handleActionSignaling(n)}_handleMessageModified(s){if(!Fo.getSignalingListenStatus())return;const n=ur(s.data);n.length>0&&n.forEach(g=>{const I=Rc(g);I&&this._onInvitationModified(I,g)})}_onNewInvitationReceived(s,n){var g,I;const E=`${Ir}._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 oA=Fo.getSignaling(m);oA!==s&&(oA||Fo.saveSignaling(m,Object.assign(Object.assign({},s),{signaling:n})),P>0&&((g=this._core)===null||g===void 0||g.helper.taskScheduler.addOnceTask({id:`${wu}-${m}`,intervalMs:1e3*P,callback:za.handleInvitationExpiryTimer.bind(za,m)})),this._emitEvent({name:(I=this._core)===null||I===void 0?void 0:I.SignalingEvent.NEW_INVITATION_RECEIVED,data:Object.assign(Object.assign({},this._generateBaseEmitData(s)),{inviteeList:D})}))}_onInviteeRejected(s){var n;const g=`${Ir}._onInviteeRejected`,{inviteID:I,inviter:E,groupID:m,inviteeList:D}=s,M=Fo.hasSignaling(I);this._core.ssoLog.debug("_onInviteeRejected",`${g} inviteID:${I} hasInviteID:${M} inviter:${E} groupID:${m}`),M&&(Fo.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=`${Ir}._onInviteeAccepted`,{inviteID:I,inviter:E,groupID:m,inviteeList:D}=s,M=Fo.hasSignaling(I);this._core.ssoLog.debug("_onInviteeAccepted",`${g} inviteID:${I} hasInviteID:${M} inviter:${E} groupID:${m}`),M&&(Fo.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=`${Ir}._onInvitationCancelled`,{inviteID:I,inviter:E,groupID:m}=s,D=Fo.hasSignaling(I);this._core.ssoLog.debug("_onInvitationCancelled",`${g} inviteID:${I} hasInviteID:${D} inviter:${E} groupID:${m}`),D&&(Fo.removeSignaling(I),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=`${Ir}._onInvitationTimeout`,{inviteID:I,inviteeList:E}=s,m=Fo.hasSignaling(I);this._core.ssoLog.debug("_onInvitationTimeout",`${g} inviteID:${I} hasInviteID:${m} data:${s.data}`),m&&(Fo.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 I=`${Ir}._onInvitationModified`,{inviteID:E,data:m}=s,D=Fo.hasSignaling(E);this._core.ssoLog.debug("_onInvitationModified",`${I} inviteID:${E} data:${m}`),D&&(Fo.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:I,data:E}=s;return{inviteID:n,inviter:g,groupID:I,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)}},Xr=new class{constructor(){this._offlineSignalingMap=new Map}init(s){this._core=s;const{notificationCenter:n,helper:g,constants:{InnerEvent:I,WORKFLOW_STEP:E,WORKFLOW_NAME:m}}=s;n.subscribeInnerEvent(I.DESTROY,this._dispose,this),n.subscribeInnerEvent(I.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&&Fo.getSignalingListenStatus()))return;const g=ur([...n.values()]);if(g.length!==0&&(g.forEach(I=>{this._handleC2CActionType(I)}),this._offlineSignalingMap.size>0)){const I=this._sortOfflineSignalingByTime();wl.handleActionSignaling(I)}}_handleC2CActionType(s){const n=Rc(s);if(!n)return;const{actionType:g}=n;g===Ru?this._saveValidOfflineInvite(n,s):this._removeOfflineInvite(n)}_saveValidOfflineInvite(s,n){const{inviteID:g,inviteeList:I=[],timeout:E=0}=s,m=this._core.common.getCurrentUserID();if(!I.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 XC={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}}},Ks={invite:!0,cancel:!0,accept:!0,reject:!0,modifyInvitation:!0};var VI=new class{constructor(){this.name="Signaling"}install(s){za.init(s),wl.init(s),Xg.init(s),Fo.init(s),Xr.init(s),s.helper.registerValidateConfig({auth:Ks,params:XC})}};const Ls=new class{init(s){this.core=s}};function wc(s){let n;const{message:g}=Ls.core,{conversationID:I,messageID:E}=s;return n=g.messageDataHandler.getLocalMessageList(I).find(m=>m.ID===E),!n&&(n=g.messageDataHandler.getSparseMessageList(I).find(m=>m.ID===E)),n}function $g(s){return s.map(n=>{const{from:g,to:I,cloudCustomData:E,avatar:m,nick:D,ID:M,clientSequence:T,clientTime:P,messageRandom:W,messageSequence:oA,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:oA,MsgTimeStamp:EA,ReceiverId:I,SenderId:g,To_Account:I}})}function Er(s){var n;const{From_Account:g,From_AccountHeadurl:I,From_AccountNick:E,GroupId:m,MsgClientTime:D,ClientSeq:M,To_Account:T,MsgTimeStamp:P,TinyId:W,MsgRandom:oA,MsgSeq:EA}=s;return{from:g,avatar:I,nick:E,clientTime:D,time:P,tinyID:W,random:oA,sequence:EA,to:T,groupID:m,clientSequence:M,_elements:(n=s.MsgBody)===null||n===void 0?void 0:n.map(wA=>{const{MsgType:kA}=wA;return Ls.core.message.messageFactory.getElementClass(kA).parseServerPushElement(wA)})}}var Pr,Za;(function(s){s.MSG_TEXT="TIMTextElem",s.MSG_CUSTOM="TIMCustomElem",s.MSG_LOCATION="TIMLocationElem",s.MSG_FACE="TIMFaceElem",s.MSG_STREAM="TIMStreamElem"})(Pr||(Pr={})),function(s){s[s.FORWARD=0]="FORWARD",s[s.BACKWARD=1]="BACKWARD"}(Za||(Za={}));const fE="MSG_REACTION",nC="MSG_EXT",$C=0,ro=1,_c={ZH_CN:"zh (cmn-Hans-CN)",EN_US:"en-US",YUE_HK:"yue-Hant-HK",JA_JP:"ja-JP",ZH_PY:"zh-PY"},_l="16k_zh",rC="16k_en",aC="16k_yue",Tl="16k_ja",JI="16k_zh-PY",II={[_c.ZH_CN]:_l,[_c.EN_US]:rC,[_c.YUE_HK]:aC,[_c.JA_JP]:Tl,[_c.ZH_PY]:JI},uI=/\.(wav|pcm|ogg-opus|speex|silk|mp3|m4a|aac|amr)/,yE={READ:0,UNREAD:1},Nl=1,Gl=2,Lg=3;var Ac;(function(s){s.IN="in",s.OUT="out"})(Ac||(Ac={}));const cd=16,DE=17;var Tc;(function(s){s[s.DATA=0]="DATA",s[s.REVOKED=1]="REVOKED"})(Tc||(Tc={}));var HI;(function(s){s[s.NORMAL=0]="NORMAL",s[s.TIMEOUT=1]="TIMEOUT"})(HI||(HI={}));const co="StreamMsg.PushStreamHttp";var SE=new class{constructor(){this._reactionsMap=new Map}init(s){this._core=s;const{helper:n,notificationCenter:g,InnerEvent:{MESSAGE_PUSH:I},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(I,E,this._handleReactionUpdated,this),g.subscribeInnerEvent(I,m,this._handleReactionSync,this)}addMessageReaction(s,n){return pA(this,void 0,void 0,function*(){const{OuterConstant:g,ssoLog:I,helper:E}=this._core;this._validateMessageReactionBusinessCapability();const{conversationID:m,ID:D,conversationType:M,from:T,to:P,clientSequence:W,random:oA,time:EA,sequence:wA}=s,kA=`conversationID:${m} messageID:${D} reactionID:${n}`;try{return this._recordMessageReactedByMe(D,n),M===g.CONV_C2C?yield function(YA,LA){return pA(this,void 0,void 0,function*(){var SA;const{from:OA,to:HA,clientSequence:se,random:oe,time:_i,reactionID:Ti}=YA,bt={From_Account:OA,To_Account:HA,MsgKey:`${se}_${oe}_${_i}`,Reaction:Ti,Add_Account:[(SA=LA.store.get("login"))===null||SA===void 0?void 0:SA.userId]};return Ls.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_add",data:bt})})}({from:T,to:P,clientSequence:W,random:oA,time:EA,reactionID:n},this._core):M===g.CONV_GROUP&&(yield function(YA,LA){return pA(this,void 0,void 0,function*(){var SA;const{to:OA,reactionID:HA,sequence:se}=YA,oe={GroupId:OA,MsgSeq:se,Reaction:HA,Add_Account:[(SA=LA.store.get("login"))===null||SA===void 0?void 0:SA.userId]};return Ls.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_add",data:oe})})}({to:P,reactionID:n,sequence:wA},this._core)),{code:0,successLog:{message:kA}}}catch(YA){this._removeMyReactionRecord(D,n);const{errorCode:LA}=YA||{};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:I}=this._core;this._validateMessageReactionBusinessCapability();const{conversationID:E,ID:m,conversationType:D,from:M,to:T,clientSequence:P,random:W,time:oA,sequence:EA}=s,wA=`conversationID:${E} messageID:${m} reactionID:${n}`;try{return this._removeMyReactionRecord(m,n),D===g.CONV_C2C?yield function(kA,YA){return pA(this,void 0,void 0,function*(){var LA;const{from:SA,to:OA,clientSequence:HA,random:se,time:oe,reactionID:_i}=kA,Ti={From_Account:SA,To_Account:OA,MsgKey:`${HA}_${se}_${oe}`,Reaction:_i,Del_Account:[(LA=YA.store.get("login"))===null||LA===void 0?void 0:LA.userId]};return Ls.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_del",data:Ti})})}({from:M,to:T,clientSequence:P,random:W,time:oA,reactionID:n},this._core):D===g.CONV_GROUP&&(yield function(kA,YA){return pA(this,void 0,void 0,function*(){var LA;const{to:SA,reactionID:OA,sequence:HA}=kA,se={GroupId:SA,MsgSeq:HA,Reaction:OA,Del_Account:[(LA=YA.store.get("login"))===null||LA===void 0?void 0:LA.userId]};return Ls.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_del",data:se},YA)})}({to:T,reactionID:n,sequence:EA},this._core)),{code:0,successLog:{message:wA}}}catch(kA){const{errorCode:YA}=kA||{};throw new I.ChatError({functionName:"removeMessageReaction",code:YA,moreMessage:wA})}})}getAllUserListOfMessageReaction(s){return pA(this,void 0,void 0,function*(){this._validateMessageReactionBusinessCapability();const{message:n,reactionID:g,nextSeq:I=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:oA,nextSeq:EA,reactionID:wA,count:kA}=W,{from:YA,to:LA,clientSequence:SA,random:OA,time:HA}=oA,se={Reaction:wA,NextSeq:EA,Count:kA,From_Account:YA,To_Account:LA,MsgKey:`${SA}_${OA}_${HA}`};return Ls.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_iterate",data:se})})}({message:n,reactionID:g,nextSeq:I,count:E}):yield function(W){return pA(this,void 0,void 0,function*(){const{message:oA,nextSeq:EA,reactionID:wA,count:kA}=W,{sequence:YA,to:LA}=oA,SA={Reaction:wA,NextSeq:EA,GroupId:LA,Count:kA,MsgSeq:YA};return Ls.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_iterate",data:SA})})}({message:n,reactionID:g,nextSeq:I,count:E}),P){const{Reaction_Account:W,NextSeq:oA}=P,EA=yield this._getUserProfileList(W);return{code:0,data:{nextSeq:oA,isCompleted:I===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:I=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:YA,to:LA,messageKeyList:SA,maxUserCountPerReaction:OA}=kA,HA={From_Account:YA,To_Account:LA,MsgKeyList:SA,Count:OA};return Ls.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_multi_stat",data:HA})})}({from:M,to:T,messageKeyList:W,maxUserCountPerReaction:I}):P===n.OuterConstant.CONV_GROUP&&(m=yield function(kA){return pA(this,void 0,void 0,function*(){const{groupId:YA,messageSequenceList:LA,maxUserCountPerReaction:SA}=kA,OA={GroupId:YA,MsgSeqList:LA,Count:SA};return Ls.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_multi_stat",data:OA})})}({groupId:T,messageSequenceList:W,maxUserCountPerReaction:I}));const{Results:oA=[]}=m||{},EA=this._extractUserIDsFromReactionResults(oA),wA=yield this._getUserProfileMap(EA);return{code:0,data:{resultList:oA.map(kA=>{const{ReactionList:YA,MsgSeq:LA,MsgKey:SA}=kA;return{messageID:this._generateMessageID({messageSequence:LA,messageKey:SA,messageIDMap:D}),reactionList:YA.map(OA=>{const{Reaction:HA,Count:se,Reaction_Account:oe,ReactedByMe:_i}=OA;return{reactionID:HA,totalUserCount:se,partialUserList:this._generatePartialUserInfo({userIDList:oe,userProfileMap:wA}),reactedByMyself:_i===1}})}})}}})}dispose(){this._reactionsMap.clear()}_extractUserIDsFromReactionResults(s){const n=[];return s?.forEach(g=>{const{ReactionList:I=[]}=g;I.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:I,avatar:E,userID:m}=g;n.set(m,{nick:I,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:I}=s,E=`${n}-${g}`,m=this._reactionsMap.get(E)||{};this._reactionsMap.set(E,Object.assign(Object.assign({},m),I))}_validateMessageReactionBusinessCapability(){const{helper:s,constants:n}=this._core;if(!s.checkBusinessCapabilityBits(fE))throw new s.ChatError({functionName:"addMessageReaction",code:n.ERROR_CODE.NO_USE,replacement1:"addMessageReaction"})}_handleReactionUpdated(s){const{MsgReactionNotifyList:n}=s,{notificationCenter:g,constants:I}=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),oA=`${T}-${P}-${W}`,EA=this._extractUserIDsFromReactionResults([{ReactionList:M}]),wA=yield this._getUserProfileMap(EA),kA=M.map(YA=>{var LA;const{Reaction:SA,Reaction_Account:OA}=YA,HA=this._generatePartialUserInfo({userIDList:OA,userProfileMap:wA}),se=OA?YA.Count:0,oe=((LA=this._reactionsMap.get(`${oA}-${SA}`))===null||LA===void 0?void 0:LA.reactedByMe)||!1;return this._recordMessageReactionInfo({messageID:oA,reactionID:SA,reactionInfo:{reactionID:SA,totalUserCount:se,partialUserList:HA}}),{reactionID:SA,totalUserCount:se,partialUserList:HA,reactedByMyself:oe}});g.emitOuterEvent(I.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:I.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:oA,reactionList:kA}})}))}_handleReactionSync(s){var n;const{notificationCenter:g,constants:I}=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),oA=`${T}-${P}-${W}`,EA=`${oA}-${D}`;if(M===1?this._recordMessageReactedByMe(oA,D):this._removeMyReactionRecord(oA,D),(n=this._reactionsMap.get(EA))===null||n===void 0?void 0:n.reactionID){const wA=this._reactionsMap.get(EA);wA.reactedByMyself=M===1,g.emitOuterEvent(I.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:I.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:oA,reactionList:[wA]}})}}_generatePartialUserInfo({userIDList:s,userProfileMap:n}){const g=[];return s?.forEach(I=>{n.has(I)&&g.push(n.get(I))}),g}_generateMessageID(s){const{messageSequence:n,messageKey:g,messageIDMap:I}=s;return g?I.get(g):I.get(n)}_generateMessageKeyList(s,n){const{constants:g}=this._core,I=s[0],{conversationType:E}=I;let m=[];return E===g.OuterConstant.CONV_C2C?m=s.map(D=>{const{clientSequence:M,random:T,time:P,ID:W}=D,oA=`${M}_${T}_${P}`;return n.set(oA,W),oA}):E===g.OuterConstant.CONV_GROUP&&(m=s.map(D=>{const{ID:M,sequence:T}=D;return n.set(T,M),T})),m}},Xa=new class{init(s){this._core=s;const{helper:n,InnerEvent:{MESSAGE_PUSH:g},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:I,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,I,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:I}=this._core,E=this._filterValidMessageSendByOther(s);if(E.length===0)throw new g.ChatError({code:I.ERROR_CODE.READ_RECEIPT_MSG_LIST_EMPTY});try{const{conversationType:m}=E[0];return m===I.OuterConstant.CONV_C2C?yield function(D){return pA(this,void 0,void 0,function*(){const{common:M,constants:T}=Ls.core,P=D[0].conversationID.replace(T.OuterConstant.CONV_C2C,""),W=D.map(EA=>{const{from:wA,to:kA,sequence:YA,random:LA,time:SA,clientTime:OA}=EA;return{From_Account:wA,To_Account:kA,MsgSeq:YA,MsgRandom:LA,MsgTime:SA,MsgClientTime:OA}}),oA={Peer_Account:P,C2CMsgInfo:W};return M.buildAndSendPacket({servcmd:"openim.c2c_msg_read_receipt",data:oA})})}(E):yield function(D){return pA(this,void 0,void 0,function*(){const{common:M,constants:T}=Ls.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:I}=s[0];if(I===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}=Ls.core,W={GroupId:M[0].conversationID.replace(P.OuterConstant.CONV_GROUP,""),MsgSeqList:M.map(oA=>({MsgSeq:oA.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(I){const{errorCode:E,errorInfo:m}=I;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:I,filter:E=yE.READ,cursor:m=""}=s,{conversationID:D,sequence:M,ID:T}=I,P=D.replace(n.OuterConstant.CONV_GROUP,""),W=s.count>=100?100:s.count;try{const oA=yield function(EA){return pA(this,void 0,void 0,function*(){const{sequence:wA,groupID:kA,filter:YA,cursor:LA,count:SA}=EA,OA={MsgSeq:wA,GroupId:kA,Filter:YA,Cursor:LA,Num:SA};return Ls.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(oA){const{Cursor:EA,IsFinish:wA,UnreadList:kA,ReadList:YA}=oA,LA={cursor:EA,isCompleted:wA===1,messageID:T,unreadUserIDList:[],readUserIDList:[]};return E===yE.READ?LA.readUserIDList=YA.map(SA=>SA.Read_Account):E===yE.UNREAD&&(LA.unreadUserIDList=kA.map(SA=>SA.Unread_Account)),{code:0,data:LA}}}catch(oA){const{errorCode:EA,errorInfo:wA}=oA;throw new g.ChatError({code:EA,message:wA})}})}_handleC2CMessageReadReceipt(s){const n=[],{constants:g,helper:I}=this._core,{C2cMsgInfo:E,PeerReadTime:m,Peer_Account:D}=s;if(I.isEmpty(E))return;const M=`${g.OuterConstant.CONV_C2C}${D}`;E?.forEach(T=>{const{TinyId:P,MsgClientTime:W,MsgRandom:oA}=T,EA=`${P}-${W}-${oA}`,wA=wc({conversationID:M,messageID:EA});wA&&!wA.readReceiptInfo.isPeerRead&&(wA.readReceiptInfo.isPeerRead=!0,wA.readReceiptInfo.timestamp=m,n.push({userID:D,messageID:EA,isPeerRead:!0,timestamp:m}))}),this._emitReadReceiptEventIfNeed(n)}_updateGroupMessagesReadReceiptInfo(s){const{messageList:n,readReceiptList:g}=s,I=new Map;n.forEach(E=>{I.set(E.sequence,E)}),g?.forEach(E=>{if(E.Code===0){const{MsgSeq:m,ReadNum:D,UnreadNum:M}=E,T=I.get(m);T&&(T.readReceiptInfo.readCount=D,T.readReceiptInfo.unreadCount=M)}})}_handleGroupMessageReadReceipt(s){const n=[],{constants:g}=this._core,{GroupTips:I}=s;I.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:oA,ReadNum:EA,UnreadNum:wA}=T,kA=`${P}-${W}-${oA}`,YA=wc({conversationID:M,messageID:kA}),LA={groupID:D,messageID:kA,readCount:0,unreadCount:0};YA&&(typeof EA=="number"&&(YA.readReceiptInfo.readCount=EA,LA.readCount=EA),typeof wA=="number"&&(YA.readReceiptInfo.unreadCount=wA,LA.unreadCount=wA),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:I,status:E}=g;return I===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:I}=this._core;I.unSubscribeInnerEvent(s,n,this._handleC2CMessageReadReceipt,this),I.unSubscribeInnerEvent(s,g,this._handleGroupMessageReadReceipt,this)}};function qI(s,n,g){return pA(this,void 0,void 0,function*(){const{common:{buildAndSendPacket:I}}=Ls.core,{from:E,to:m,clientSequence:D,random:M,time:T}=s;return I({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 _u(s,n,g){return pA(this,void 0,void 0,function*(){const{common:{buildAndSendPacket:I}}=Ls.core,{to:E,sequence:m}=s;return I({servcmd:"openim_msg_ext_http_svc.group_set_key_values",data:{GroupId:E,MsgSeq:m,OperateType:g,ExtensionList:n}})})}var Nc=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:I,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(I,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:I}=this._core,{ID:E,conversationID:m,sequence:D,time:M,conversationType:T}=s;let P=n;n.length>20&&(P=n.slice(0,20),I.warn("setMessageExtensions","the length of extensions cannot exceed 20"));const W=this._generateServerExtensions(s,P),oA=`convID:${m} messageID:${E} sequence:${D} time:${M} count:${P.length}`;try{let EA;if(T===g.CONV_C2C?EA=yield qI(s,W,Nl):T===g.CONV_GROUP&&(EA=yield _u(s,W,Nl)),EA){const{resultList:wA,successCount:kA,failureCount:YA}=this._handleModifyMessageExtensions(s,EA);return{code:0,data:{extensions:wA},successLog:{message:`${oA} successCount:${kA} failCount:${YA}`}}}return{code:0,data:{extensions:[]}}}catch(EA){const{errorCode:wA}=EA;throw new this._core.helper.ChatError({functionName:"setMessageExtensions",code:wA,moreMessage:oA})}})}getMessageExtensions(s){return pA(this,void 0,void 0,function*(){const{utils:{isUndefined:n}}=this._core;this._validateMessageExtensionBusinessCapability("getMessageExtensions");const{conversationID:g,ID:I,sequence:E,time:m}=s,D=`convID:${g} messageID:${I} sequence:${E} time:${m}`;try{let M;this._completedFetchExtensions.has(I)&&(M=this._extensionsLatestSequenceMap.get(I));const T=yield this._fetchMessageExtensions(s,M);return n(M)&&T.length>1&&this._completedFetchExtensions.add(I),{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:I}}=this._core,{conversationType:E,conversationID:m,sequence:D,ID:M,time:T}=s;let P=Lg;const W=[];g(n)||(P=Gl,n?.forEach(wA=>{W.push({key:wA,value:"",seq:0})}));const oA=`convID:${m} messageID:${M} sequence:${D} time:${T} operateType:${P}`,EA=this._generateServerExtensions(s,W);try{let wA;if(E===I.CONV_C2C?wA=yield qI(s,EA,P):E===I.CONV_GROUP&&(wA=yield _u(s,EA,P)),wA){const{resultList:kA,successCount:YA,failureCount:LA}=this._handleModifyMessageExtensions(s,wA);return{code:0,data:{extensions:kA},successLog:{message:`${oA}successCount:${YA} failCount:${LA}`}}}return{code:0,data:{extensions:[]}}}catch(wA){const{errorCode:kA}=wA;throw new this._core.helper.ChatError({functionName:"deleteMessageExtensions",code:kA,moreMessage:oA})}})}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:I}}=this._core;s.unSubscribeInnerEvent(n,I,this._handleMessageExtensionsNotify,this),s.subscribeInnerEvent(g,this.reset,this)}_handleModifyMessageExtensions(s,n){const{ID:g}=s,{Seq:I}=n,E=n.ExtensionList||[],m=[];let D=0,M=0,T=[];return E.forEach(P=>{const{ErrorCode:W,Extension:oA}=P,{Key:EA,Value:wA,Seq:kA}=oA;m.push({code:W,key:EA,value:wA}),W===0?D++:M++,T.push({key:EA,value:wA,seq:kA})}),this._extensionsLatestSequenceMap.set(g,I),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(I=>{const{key:E,seq:m,value:D=""}=I;g?.set(E,{value:D,seq:m})})}_fetchMessageExtensions(s,n){return pA(this,void 0,void 0,function*(){const{constants:{OuterConstant:g},utils:{isEmpty:I}}=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}}=Ls.core,{from:W,to:oA,clientSequence:EA,random:wA,time:kA}=M;return P({servcmd:"openim_msg_ext_http_svc.get_key_values",data:{From_Account:W,To_Account:oA,MsgKey:`${EA}_${wA}_${kA}`,StartSeq:T}})}(s,n):m===g.CONV_GROUP&&(E=yield function(M,T){const{common:{buildAndSendPacket:P}}=Ls.core,{to:W,sequence:oA}=M;return P({servcmd:"openim_msg_ext_http_svc.group_get_key_values",data:{GroupId:W,MsgSeq:oA,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 oA=[];if(this._messageExtensionsMap.has(D)){const EA=this._messageExtensionsMap.get(D);EA?.forEach((wA,kA)=>{const{value:YA}=wA;I(YA)||oA.push({key:kA,value:YA})})}return oA}}catch(E){throw E}})}_clearLocationExtensions(s,n){if(!(n<=0)&&this._messageExtensionsMap.has(s)){const g=this._messageExtensionsMap.get(s);g?.forEach((I,E)=>{I.seq<=n&&g.delete(E)})}}_generateServerExtensions(s,n){const{ID:g}=s;if(this._messageExtensionsMap.has(g)){const I=this._messageExtensionsMap.get(g);return n.map(E=>{var m;const{key:D,value:M}=E;let T=0;return I?.has(D)&&(T=(m=I.get(D))===null||m===void 0?void 0:m.seq),{Key:D,Value:M,Seq:T}})}return n.map(I=>({Key:I.key,Value:I.value,Seq:0}))}_validateMessageExtensionBusinessCapability(s){const{helper:n,constants:g}=this._core;if(!n.checkBusinessCapabilityBits(nC))throw new n.ChatError({functionName:s,code:g.ERROR_CODE.NO_USE,replacement1:s})}_handleMessageExtensionsNotify(s){const{SetKVInfo:n,DeleteKVInfo:g,ClearKVInfo:I,MsgOptType:E,TinyId:m,MsgLastSeq:D,ExtensionC2cMsgInfo:M,ExtensionGroupMsgInfo:T}=s?.MsgExtensionNotify||{},P=M||T||{},{MsgClientTime:W,MsgRandom:oA}=P,EA=`${m}-${W}-${oA}`;this._extensionsLatestSequenceMap.set(EA,D),E===Nl?this._handleMessageExtensionsUpdated({messageID:EA,updateMessageExtensionsInfo:n}):E===Gl?this._handleMessageExtensionsDeleted({messageID:EA,deleteMessageExtensionsInfo:g}):E===Lg&&this._handleMessageExtensionsCleared({messageID:EA,clearMessageExtensionsInfo:I})}_handleMessageExtensionsUpdated(s){const{notificationCenter:n,OuterEvent:g}=this._core,{messageID:I,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(I,T)}),n.emitOuterEvent(g.MESSAGE_EXTENSIONS_UPDATED,{name:g.MESSAGE_EXTENSIONS_UPDATED,data:{messageID:I,extensions:m}})}_handleMessageExtensionsDeleted(s){const{notificationCenter:n,OuterEvent:g}=this._core,{messageID:I,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(I,T)}),n.emitOuterEvent(g.MESSAGE_EXTENSIONS_DELETED,{name:g.MESSAGE_EXTENSIONS_DELETED,data:{messageID:I,keyList:m}})}_handleMessageExtensionsCleared(s){const{notificationCenter:n,OuterEvent:{MESSAGE_EXTENSIONS_DELETED:g},utils:{isEmpty:I}}=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&&!I(P.value)&&D.push(W)}),this._clearLocationExtensions(E,T)}),n.emitOuterEvent(g,{name:g,data:{messageID:E,keyList:D}})}};const EI={key:"message",required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>{const{constants:{OuterConstant:n}}=Ls.core;return s.status!==n.MessageStatus.SUCCESS?"message is not success":s.isSupportExtension===!0||"message is not support extension"}},il={setMessageExtensions:[EI,{key:"extensions",required:!0,rules:["array"],allowEmpty:!1}],getMessageExtensions:[EI],deleteMessageExtensions:[EI]},ol=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 I;return typeof g?.text!="string"||typeof g.text=="string"&&((I=g?.text)===null||I===void 0?void 0:I.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}}=Ls.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}}}),il),{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}]}),Pa=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 ME{constructor(n){this._core=n}deleteMessage(n){return pA(this,void 0,void 0,function*(){const{to:g,messageIdentifiers:I}=n,E={From_Account:this._core.common.getCurrentUserID(),To_Account:g,MsgKeyList:I};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:I,sequence:E,time:m,random:D}=n,M={MsgInfo:{From_Account:I,To_Account:g,MsgSeq:E,MsgRandom:D,MsgTimeStamp:m}};return this._core.common.buildAndSendPacket({servcmd:"openim.msgwithdraw",data:M})})}}class na{constructor(n){this._core=n}deleteMessage(n){return pA(this,void 0,void 0,function*(){const{to:g,messageIdentifiers:I}=n,E={GroupId:g,Deleter_Account:this._core.common.getCurrentUserID(),Seqs:I};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:I}=n,E={GroupId:g,MsgSeqList:[{MsgSeq:I}]};return this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_recall",data:E})})}}const Mn=2116;class Nr{constructor(n){this._core=n}generateRevokeMessage(n){const{conversationID:g,sequence:I,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:I,random:E,revoker:T}),P||(P={conversationID:g,sequence:I},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(I=>I.revoker);try{const I=yield this._fetchUserInfos(g);I&&n.forEach(E=>{const{revoker:m}=E;I[m]&&(E.revokerInfo.nick=I[m].nick||"",E.revokerInfo.avatar=I[m].avatar||"",E.revokerInfo.userID=m)})}catch(I){console.debug(I)}})}_fetchUserInfos(n){return pA(this,void 0,void 0,function*(){var g,I;const E=yield(g=this._core.user.userProfile)===null||g===void 0?void 0:g.getUserProfile({userIDList:n});return E?.data?(I=E.data)===null||I===void 0?void 0:I.reduce((m,{userID:D,nick:M,avatar:T})=>(m[D]={nick:M||"",avatar:T||""},m),{}):null})}}var sl=new class{constructor(){this._core=null,this._c2cMessageAction=null,this._groupMessageAction=null}init(s){this._core=s,this._groupMessageAction=new na(s),this._c2cMessageAction=new ME(s),this._messageHelper=new Nr(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:I,conversationType:E}=s[0],m=I.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:oA,random:EA,time:wA}=D||{};if(P==="success"&&M===I&&T===E){if(!W){const kA=T==="C2C"?`${oA}_${EA}_${wA}`:String(oA);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:I,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(I)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,oA=((n=W?.[0])===null||n===void 0?void 0:n.RetCode)||0;if(oA!==0)throw new this._core.helper.ChatError({code:oA,moreMessage:P});return s.isRevoked=!0,yield this._handleRevokeMessageSuccess(s),{code:0,data:{message:s},successLog:{message:P}}}}catch(W){const{errorCode:oA}=W;throw new this._core.helper.ChatError({functionName:"revokeMessage",code:oA,moreMessage:P})}})}resendMessage(s,n){return pA(this,void 0,void 0,function*(){var g,I;return s.isResend=!0,s.status="unSend",(I=(g=this._core)===null||g===void 0?void 0:g.apiMap)===null||I===void 0?void 0:I.sendMessage(s,n)})}findMessage(s){return this._core.message.messageDataHandler.findMessage(s)}createQuoteMessage(s,n){const{ID:g,time:I,sequence:E}=n;return s.quoteInfo={msgID:g,messageTime:I,messageSequence:E},s}_handleDeleteMessageSuccess(s){if(s.length===0)return;const{message:{messageDataHandler:n},common:{isTopic:g},notificationCenter:I,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)?I.emitInnerEvent(E.TOPIC_MESSAGE_DELETED,m):I.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:I,sequence:E,random:m}=s;this._core.message.messageDataHandler.revokeMessage({conversationID:I,sequence:E,random:m,revoker:g}),yield this._messageHelper.updateRevokerInfo([s])})}};class bl{static parseServerPushElement(n){const{MsgContent:g={}}=n,{Index:I,Data:E}=g;return new bl({index:I,data:E})}constructor(n){this.type=Pr.MSG_FACE;const{index:g,data:I}=n;this.content={index:g,data:I}}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||{},I=g?this.payload:this.content,{index:E,data:m}=I;return{MsgType:this.type,MsgContent:{Index:E,Data:m}}}}class Gc{static parseServerPushElement(n){const{MsgContent:g={}}=n,{Desc:I,Longitude:E,Latitude:m}=g;return new Gc({description:I,longitude:E,latitude:m})}constructor(n){this.type=Pr.MSG_LOCATION;const{description:g,longitude:I,latitude:E}=n;this.content={description:g,longitude:I,latitude:E}}validateBeforeSend(){return{isValid:!0}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},I=g?this.payload:this.content,{description:E,longitude:m,latitude:D}=I;return{MsgType:this.type,MsgContent:{Desc:E,Longitude:m,Latitude:D}}}}class vE{static parseServerPushElement(n){const{MsgContent:g={}}=n,{StreamMsgID:I,CompatibleText:E,Markdown:m,BinaryData:D,ErrorCode:M,ErrorMsg:T}=g;return new vE({streamMessageID:I,compatibleText:E,markdown:m,binaryData:D,errorCode:M,errorMessage:T})}constructor(n){this.type=Pr.MSG_STREAM,this.content={streamMessageID:"",compatibleText:"",errorCode:0,errorMessage:"",isStreamEnded:!1},this._chunks=[],this._latestIndex=0;const{streamMessageID:g,compatibleText:I,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=I,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),I=this._getMaxRevokedChunkIndex(g);I>=0&&(this._chunks=[],this._latestIndex=I,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||{},I=g?this.payload:this.content,{streamMessageID:E,chunks:m}=I,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 I=[];let E=g;for(const m of n){if(m.index>E)break;m.index===E&&(I.push(m),E++)}return I}_mergeAndSortChunks(n){const g=new Map;this._chunks.forEach(I=>{g.set(I.index,I)}),n.forEach(I=>{g.set(I.index,I)}),this._chunks=Array.from(g.values()).sort((I,E)=>I.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),I=new Uint8Array(g);let E=0;for(const m of n)I.set(m,E),E+=m.length;this.content.binaryData=I}}_getMaxRevokedChunkIndex(n){let g=-1;for(let I=0;Ig&&(g=E.index)}return g}_getValidChunks(n){const g=n.filter(I=>I.eventType===Tc.DATA&&I.index>this._latestIndex);return this._filterContinuousChunks(g,this._latestIndex+1)}}var bc=new class{init(s){this._core=s,s.message.messageFactory.registerElementClass(Pr.MSG_FACE,bl),s.message.messageFactory.registerElementClass(Pr.MSG_LOCATION,Gc),s.message.messageFactory.registerElementClass(Pr.MSG_STREAM,vE),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||{},I=new bl({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(I),m}createTextAtMessage(s){const{atUserList:n}=s?.payload||{},g=this._core.apiMap.createTextMessage(s),{OuterConstant:I}=this._core;if(!g)return null;if(Array.isArray(n)){const E=[],m=[];n.forEach(D=>{D!==I.MSG_AT_ALL?(E.push({GroupAtAllFlag:$C,GroupAt_Account:D}),m.push(D)):(E.push({GroupAtAllFlag:ro}),m.push(I.MSG_AT_ALL))}),g._groupAtInfoList=E,g.atUserList=m}return g}createForwardMessage(s){const{helper:n,OuterConstant:g}=this._core,{to:I,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 oA=this._core.common.getCurrentUserID(),EA=this._core.message.messageFactory.createMessage({to:I,from:oA,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:I}=s?.payload||{},E=new Gc({description:n,longitude:g,latitude:I}),m=this._core.common.getCurrentUserID(),D=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:m}));return D.setElement(E),D}};let Tu=class{init(s){this._messageHelper=new Nr(s),this._core=s;const{notificationCenter:n,InnerEvent:{MESSAGE_PUSH:g},InnerEventSubType:{C2C_REVOKED_MESSAGE:I},helper:{registerWorkflowStep:E},constants:{WORKFLOW_NAME:m,WORKFLOW_STEP:D}}=s;n.subscribeInnerEvent(g,I,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:I,common:{getCurrentUserID:E}}=this._core;s.forEach(m=>{var D;const{MsgRand:M,MsgSeq:T,To_Account:P,From_Account:W,RevokerInfo:{Revoker_Account:oA,Revoke_Reason:EA}}=m,wA=E()===W?`C2C${P}`:`C2C${W}`,kA=((D=m?.RevokerInfo)===null||D===void 0?void 0:D.Reason)||EA,YA=this._messageHelper.generateRevokeMessage({conversationID:wA,sequence:T,random:M,revoker:oA,revokeReason:kA});n.push(YA)}),n.length>0&&(yield this._messageHelper.updateRevokerInfo(n),g.emitOuterEvent(I.MESSAGE_REVOKED,{name:I.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)}},gC=class{init(s){this._messageHelper=new Nr(s),this._core=s;const{notificationCenter:n,InnerEvent:{MESSAGE_PUSH:g},InnerEventSubType:{GROUP_MESSAGE_REVOKED:I}}=s;n.subscribeInnerEvent(g,I,this._handleGroupNotifyMessage,this)}_handleGroupNotifyMessage(s){const{GroupTips:n}=s;n?.forEach(g=>{var I;Array.isArray((I=g?.MsgBody)===null||I===void 0?void 0:I.GroupWithdrawInfoArray)&&this._handleGroupRevokeMessage(g)})}_handleGroupRevokeMessage(s){return pA(this,void 0,void 0,function*(){try{const{RevokerInfo:n,MsgBody:{GroupWithdrawInfoArray:g},GroupInfo:I}=s,E=[],m=[],{notificationCenter:D,OuterEvent:M,utils:{isEmpty:T},common:{isCommunity:P}}=this._core;let W=!1;I&&(W=P({groupID:I.GroupId})||!T(I.TopicId)),g.forEach(oA=>{const{Random:EA,MsgSeq:wA,GroupId:kA,MsgClientTime:YA,TinyId:LA,TopicId:SA,RevokerInfo:{Revoker_Account:OA=n?.Revoker_Account||"",Reason:HA=n?.Reason||""}}=oA,se=SA?`GROUP${SA}`:`GROUP${kA}`,oe=this._messageHelper.generateRevokeMessage({conversationID:se,sequence:wA,random:EA,tinyID:LA,clientTime:YA,revoker:OA,revokeReason:HA});W?(oe.revokerInfo.nick=I.From_AccountNick,oe.revokerInfo.avatar=I.From_AccountHeadurl,E.push(oe)):m.push(oe)}),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 KI=new class{constructor(){this._c2cMessageReceiver=new Tu,this._groupMessageReceiver=new gC}init(s){this._c2cMessageReceiver.init(s),this._groupMessageReceiver.init(s)}dispose(){this._c2cMessageReceiver.dispose(),this._groupMessageReceiver.dispose()}},Ah=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:I}=s,E=yield function(m,D){return pA(this,void 0,void 0,function*(){var M,T;const{sourceTextList:P,sourceLanguage:W,targetLanguage:oA}=m,{store:EA,common:wA}=D,kA={SourceText:P,Source:W,Target:oA,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},YA=yield wA.buildAndSendPacket({servcmd:"im_open_translate.ws_batch_trans_text",data:kA});if(YA){const{CmdErrorCode:LA,TargetText:SA}=YA;return{cmdErrorCode:LA,translatedTextList:SA}}})}({sourceLanguage:n,sourceTextList:g,targetLanguage:I},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:I}=n||{};throw new this._core.helper.ChatError({functionName:"translateText",code:g,message:I})}})}},Nu=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:I=_c.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=uI.exec(E))===null||n===void 0?void 0:n[1])||"mp3",M=II[I]||JI;try{const T=yield function(P){var W;const{store:oA,common:EA}=Ls.core,{url:wA,format:kA,serverLanguageType:YA}=P,LA={BytesUrl:wA,BytesEngServiceType:YA,BytesVoiceFormat:kA,Uint32Sdkappid:(W=oA.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(!uI.test(s))throw new this._core.common.ChatError({code:2119})}};class dI{constructor(n){const{constants:g,common:I,utils:E}=Ls.core,{CONV_C2C:m,CONV_GROUP:D}=g.OuterConstant,{ID:M,tinyID:T,from:P,to:W,clientTime:oA=I.timeManager.getServerTimeSeconds()||0,random:EA,sequence:wA,cloudCustomData:kA="",nick:YA="",avatar:LA="",clientSequence:SA,conversationType:OA,groupID:HA,_elements:se,time:oe}=n;this.ID=M||`${T}-${oA}-${EA}`,this.messageRandom=EA,this.from=P,this.messageSender=P,this.time=oe,this.messageSequence=wA,this.clientSequence=SA||wA,this.clientTime=oA,this.cloudCustomData=kA,this.messageReceiver=W,this.avatar=LA,this.nick=YA;const _i=E.deepCopyWithMethods(se);_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):HA?(this.receiverGroupID=HA,this.messageReceiver=HA):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 nl{static parseServerPushElement(n){const{MsgContent:g}=n,{MsgList:I=[],CompatibleText:E,AbstractList:m,Title:D,PbMsgKey:M,JsonMsgKey:T}=g||{},P=I.map(W=>Er(W));return new nl({messageList:P,title:D,abstractList:m,compatibleText:E,pbDownloadKey:M,downloadKey:T})}constructor(n){this.type=Ls.core.constants.OuterConstant.MSG_MERGER;const{messageList:g,title:I,abstractList:E,compatibleText:m,pbDownloadKey:D="",downloadKey:M="",version:T=0,layersOverLimit:P=!1}=n,W=[];g.forEach(oA=>{if(oA){const EA=new dI(oA);W.push(EA)}}),this.content={messageList:W,title:I,abstractList:E,compatibleText:m,version:T,downloadKey:M,pbDownloadKey:D,layersOverLimit:P}}validateBeforeSend(){const{isEmpty:n}=Ls.core.helper;return n(this.content.messageList)?{isValid:!1,error:{message:"content is invalid"}}:{isValid:!0}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},I=g?this.payload:this.content,{abstractList:E,compatibleText:m,downloadKey:D,layersOverLimit:M,pbDownloadKey:T,title:P,version:W,messageList:oA}=I;return{MsgType:this.type,MsgContent:{AbstractList:E,CompatibleText:m,JsonMsgKey:D,LayersOverLimit:M,PbMsgKey:T,Title:P,Version:W,MsgList:$g(oA)}}}}var cC=new class{init(s){this._core=s;const{message:n,helper:g,constants:{OuterConstant:I}}=s;n.messageFactory.registerElementClass(I.MSG_MERGER,nl),g.registerApi({apiName:"createMergerMessage",context:this}),g.registerApi({apiName:"sendMessage",context:this,matcher:E=>E[0].type===I.MSG_MERGER}),g.registerApi({apiName:"downloadMergerMessage",context:this})}createMergerMessage(s){const{common:n}=this._core;if(!s)return null;const g=new nl(s.payload),I=n.getCurrentUserID(),E=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:I}));return E.setRelayFlag(!0),E.setElement(g),E}sendMessage(s,n){return pA(this,void 0,void 0,function*(){var g,I,E;try{const m=function(P){let W="utf-8";Ls.core.helper.IN_BROWSER&&document&&(W=document.charset.toLowerCase());let oA,EA=0,wA=0;if(wA=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:wA}}=EA,kA={MsgList:$g(wA)};return Ls.core.common.buildAndSendPacket({servcmd:"im_long_msg.save_relay_json_msg",data:kA})})}(D),{payload:oA}=D;M=new nl(Object.assign(Object.assign({},oA),{messageList:[],downloadKey:P,pbDownloadKey:W})),D.setElement(M)}catch(P){console.error(P)}}const{data:{message:T}}=yield(E=(I=(g=this._core)===null||g===void 0?void 0:g.message)===null||I===void 0?void 0:I.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:I,pbDownload:E,type:m,messageList:D}=g,M=yo(g,["downloadKey","pbDownload","type","messageList"]);try{const T=yield function(oA){return pA(this,void 0,void 0,function*(){return Ls.core.common.buildAndSendPacket({servcmd:"im_long_msg.get_relay_json_msg",data:{JsonMsgKey:oA}})})}(I),{MsgList:P}=T||{},W=P?.map(oA=>{const EA=Er(oA);return new dI(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:${I}`),s}catch(T){const{errorCode:P}=T;throw new this._core.helper.ChatError({functionName:"downloadMergerMessage",code:P,moreMessage:I})}})}},ra=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:I},utils:{isArray:E}}=this._core,{GroupId:m,To_Account:D}=s;s.From_Account=s.From_Account||I();let M=null;if(m){M=this._generateGroupMessage(Object.assign(Object.assign({},s),{ToGroupId:m}));const T=n.userStore.getUserProfile(I());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,I=g,E=n.messageHelper.parseServerPushMessage(s),m=n.messageFactory.createMessage(Object.assign(Object.assign({},E),{conversationType:I,flow:Ac.OUT})),{elements:D}=E;return m.setElement(D),m}_generateGroupMessage(s){const{message:n,OuterConstant:{CONV_GROUP:g}}=this._core,I=g,E=n.messageHelper.parseServerGroupMessage(s),m=n.messageFactory.createMessage(Object.assign(Object.assign({},E),{conversationType:I,flow:Ac.OUT})),{elements:D}=E;return m.setElement(D),m}},ec=new class{init(s){this._core=s;const{helper:n,notificationCenter:g,InnerEvent:{MESSAGE_PUSH:I},InnerEventSubType:{GROUP_MESSAGE_PINNED:E}}=s;g.subscribeInnerEvent(I,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:I},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:oA}}=Ls.core,{groupID:EA,sequence:wA,isPinned:kA}=P,YA=oA(),LA=kA?"group_open_http_svc.pin_message":"group_open_http_svc.unpin_message",SA={GroupId:EA,MsgSeq:wA};return kA?SA.Pinner_Account=YA:SA.UnPinner_Account=YA,W({servcmd:LA,data:SA})})}({groupID:m,sequence:T,isPinned:M}),{code:0,data:{}}}catch(P){const{errorCode:W,errorInfo:oA}=P||{};throw new E({code:W,message:oA})}})}getPinnedGroupMessageList(s){return pA(this,void 0,void 0,function*(){let n=[];try{const g=yield function(I){return pA(this,void 0,void 0,function*(){const{groupID:E}=I,{common:{buildAndSendPacket:m}}=Ls.core;return m({servcmd:"group_open_http_svc.get_pinned_messages",data:{GroupId:E}})})}({groupID:s});if(g){const{PinnedMsgList:I=[]}=g;n=yield this._updatePinnedMessageInfo({serverPinnedMessageList:I,groupID:s})}return{code:0,data:{messageList:n}}}catch(g){throw g}})}_handleGroupMessagePinned(s){const{message:{messageHelper:n,messageFactory:g},notificationCenter:I,OuterEvent:E,OuterConstant:m}=this._core;s.GroupTips.forEach(D=>{const{ToGroupId:M,MsgBody:{PinnedMsg:T,OpType:P,MsgOperatorMemberExtraInfo:W,SdkGroupMessageId:oA}}=D,{UserId:EA,NickName:wA="",ImageUrl:kA=""}=W;let YA=null,LA=!1;if(P===cd){LA=!0;const SA=n.parseServerGroupMessage(T);YA=g.createMessage(Object.assign(Object.assign({},SA),{conversationType:m.CONV_GROUP,flow:"in"})),YA.setElement(SA.elements),YA.pinnerInfo={userID:EA,nick:wA,avatar:kA}}else if(P===DE){const{ClientTime:SA,Random:OA,SenderTinyId:HA,ServerTime:se,MsgSeq:oe}=oA;YA={ID:`${HA}-${SA}-${OA}`,sequence:oe,random:OA,time:se,clientTime:SA}}YA&&I.emitOuterEvent(E.PINNED_GROUP_MESSAGE_UPDATED,{name:E.PINNED_GROUP_MESSAGE_UPDATED,data:{groupID:M,message:YA,isPinned:LA,operatorInfo:{userID:EA,nick:wA,avatar:kA}}})})}_findMessageBySequence(s,n){const{message:{messageDataHandler:g}}=this._core;return[...g.getLocalMessageList(s),...g.getSparseMessageList(s)].find(I=>I.sequence===n)}_updatePinnedMessageInfo(s){return pA(this,arguments,void 0,function*({serverPinnedMessageList:n,groupID:g}){const{OuterConstant:{CONV_GROUP:I},utils:{isEmpty:E}}=this._core,m=[],D=[],M=[],T=new Map,P=`${I}${g}`;for(let oA=0;oA{const{sequence:kA}=wA,YA=T.get(kA),LA=oA[YA]||{userID:YA,nick:"",avatar:""};wA.pinnerInfo=LA}),m.sort((wA,kA)=>wA.sequence-kA.sequence),m}return[]})}_fetchPinnedMessageInfo(s){return pA(this,void 0,void 0,function*(){var n,g;const{message:{messageHistory:I},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(oA=>{const{userID:EA,nick:wA="",avatar:kA=""}=oA;W[EA]={userID:EA,nick:wA,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:I,messageSequenceList:E}=s;return n(E)?[]:g.getGroupRoamingMessagesByAnchor({conversationID:I,messageSequenceList:E,getType:3})})}};class cg{constructor(n){this.eventType=Tc.DATA,this.index=0,this.markdown="",this.isLast=!1,this.binaryData=null;const{EventType:g,Index:I,Markdown:E,IsLast:m,BinaryData:D}=n;this.eventType=g,this.index=I,this.markdown=E,this.isLast=m,this.binaryData=D}}var CI=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:I},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(I,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:I}=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){I.error("processHistoryMessage.error",g(E))}}_handleMessageReceived(s){const n=s.data;n?.forEach(g=>{var I,E;if(this._isValidStreamMessage(g)){const{streamMessageID:m}=((E=(I=g?._elements)===null||I===void 0?void 0:I[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:I}}=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===Pr.MSG_STREAM&&!I(E)}_fetchStreamMessageChunks(s){return pA(this,void 0,void 0,function*(){var n,g;const{constants:{ERROR_CODE:I},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 oA=yield function(EA){return pA(this,void 0,void 0,function*(){const{from:wA,to:kA,streamMessageID:YA,index:LA}=EA,SA={From_Account:wA,To_Account:kA,StreamMsgID:YA,AckIndex:LA};return Ls.core.common.buildAndSendPacket({servcmd:"StreamMsg.GetStreamHttp",data:SA,timeout:5e3})})}({from:T,to:P,streamMessageID:M,index:W});if(oA){const{ErrorCode:EA,ErrorInfo:wA}=oA;if(EA!==0)throw D.content.errorCode=EA,D.content.errorMessage=wA,{errorCode:EA,errorMessage:wA}}}catch(T){if(T.errorCode===I.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:I}=this._core;g.content.isStreamEnded=!0,g.stopReason=n,this._messageMap.delete(s),I.debug("_onStreamEnded",`streamMessage end, StopReason: ${n}`)}_handleStreamMessageChunkPush(s){var n;const{ssoLog:g}=this._core,{StopReason:I,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 cg(P));M.updateChunks(T)}this._emitMessageModify(D),function(T,P){pA(this,void 0,void 0,function*(){const{common:{generateProtocolData:W},utils:{safeStringify:oA},ssoLog:EA,channel:wA}=Ls.core,kA={StreamMsgID:T,AckIndex:P};try{const YA=W({servcmd:"StreamMsg.AckHttp",data:kA});wA.sendPacket(YA)}catch(YA){EA.debug("sendStreamChunkAck",oA(YA))}})}(m,M.getLatestIndex()),M.content.isStreamEnded&&this._onStreamEnded(m,I,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 I=!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 I=Math.max(0,g.length-300);I{const LA=this._getResponseBody(kA,E,oA&&EA),SA=this._buildResponse(kA,LA);if(kA.status===200)n(null,SA);else{if(EA&&!wA.includes(EA))return s.url=this._domainName2IP(wA,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,oA&&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,HA=Math.min(Math.floor(100*OA/SA),100);s.onProgress({total:SA,loaded:OA,percent:HA/100})}),kA.send(P),kA})}_buildResponse(s,n){const g={};return s.getAllResponseHeaders().trim().split(`
-`).forEach(I=>{if(I){const[E,m]=I.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 I;const{isEmpty:E,isPlainObject:m}=(I=this._core)===null||I===void 0?void 0:I.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 bu=["unknown","image","video","audio","log"];var hI=new class{init(s){this._core=s}request(s,n){var g;const{MINI_APP_NAMESPACE:I,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,oA=null;const EA=P?P.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/):null;if(!EA)return void console.warn("message Invalid download URL format");const wA=decodeURIComponent(EA[3]),kA=wA.includes("?")?wA.split("?")[0]:wA||"",YA={key:s.fileKey||kA,success_action_status:200,"Content-Type":""},LA={};if(m()){const[OA,HA]=T.split("?sign=");HA&&(W=`${OA}?sign=${encodeURIComponent(HA)}`,LA.sign=decodeURIComponent(HA),LA.signature=decodeURIComponent(HA))}let SA={url:W,header:M,name:"file",filePath:D,formData:Object.assign(Object.assign({},YA),LA),timeout:s.timeout||3e5};if(E){const{name:OA}=SA,HA=yo(SA,["name"]);SA=Object.assign(Object.assign({},HA),{fileName:"file",fileType:s.fileType?bu[s.fileType]:"image"})}return oA=I.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})}})),oA.onProgressUpdate&&oA.onProgressUpdate(OA=>{s.onProgress&&s.onProgress({total:OA.totalBytesExpectedToSend||0,loaded:OA.totalBytesSent||0,percent:OA.progress?Math.floor(OA.progress)/100:0})}),oA}_handleResponse(s){const{downloadUrl:n,response:g,callback:I}=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?I(null,{statusCode:m,headers:E,data:Object.assign(Object.assign({},g.data),{location:n})}):I({code:m,message:JSON.stringify(g.data)},{statusCode:m,headers:E,data:void 0})}};function rl(s){return function(n){return Object.prototype.toString.call(n).match(/^\[object (.*)\]$/)[1].toLowerCase()}(s)==="file"}function Gr(s){const n=s||99999999;return Math.round(Math.random()*n)}function br(s,n=!0,g=!0){const I=Date.now();return n?g?I-s+" ms":`${Math.round((I-s)/1e3)} s`:g?I-s:Math.round((I-s)/1e3)}function lg(s){return`${Array.from({length:8},()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1)).join("")}-${s}`}function rr(s,n){return Math.round(Number(s)*10**n)/10**n}function vr(s){return s<=1048576?`${rr(s/1024,1)}KB/s`:`${rr(s/1048576,1)}MB/s`}const tc="TIMImageElem",Ug="TIMSoundElem",xa="TIMFileElem",kl="TIMVideoFileElem",da="RichMediaMessagePlugin",BI=["rich.my-imcloud.com","imrich.qcloud.com"],jI=1,Ca=2,al=3,wE=255;var WI;(function(s){s.UNSENT="unSend",s.SUCCESS="success",s.FAIL="fail"})(WI||(WI={}));const _E={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\/)/},xr=Symbol("isCustomUpload");var zI,Ut=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[I,E]=n.split("?");if(!E)return I;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?`${I}?${D}`:I}(s,"authKey")}_isMiniProgramTempFile(s){return!!this.getPlatformFlags().IN_MINI_APP&&Object.values(_E).some(n=>n.test(s))}extractFileFromInput(s){const{utils:{isArray:n}}=this._core;return rl(s)?s:function(g){if(typeof g!="object"||g===null)return!1;const I=Object.getPrototypeOf(g);if(I===null)return!0;let E=I;for(;Object.getPrototypeOf(E)!==null;)E=Object.getPrototypeOf(E);return I===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:I}=((n=this._core)===null||n===void 0?void 0:n.utils)||{};return this._shouldSkipProbing()?{width:0,height:0}:I?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=BI;const g=((s=this._core)===null||s===void 0?void 0:s.store.get("cloudConfig"))||{},{file_dn_list:I}=g;if(I===void 0)return n;try{JSON.parse(I).forEach(E=>{n.includes(E)||n.push(E)})}catch(E){console.warn(E),n=BI}return n}getPlatform(){var s;return(s=this._core)===null||s===void 0?void 0:s.utils.platform}generateUUID(s,n){var g;let I=`${this.getSDKAppID()}-${this.getCurrentUserID()}-${(g=this._core)===null||g===void 0?void 0:g.utils.randomString()}`;if(n)return`${I}.${n}`;const E=s.name||s.value||s.url||s.tempFilePath,m=E&&E.slice(E.lastIndexOf(".")+1);return m&&(I=`${I}.${m}`),I}processResourceUrl(s){if(!s)return"";let n=s;const g=this.getFileDownloadProxy(),I=this.getAuthKey(),E=this.getFileDNList();return g&&(s.startsWith("http://")?n=s.replace(/^http:\/\/[^/]+/,g):s.startsWith("https://")&&(n=s.replace(/^https:\/\/[^/]+/,g))),I&&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 oA=0;oA-1?`${n}&authKey=${I}`:`${n}?authKey=${I}`),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:I,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:I,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(I=>{g.getImageInfo({src:s,success:E=>I({width:E.width,height:E.height}),fail:()=>I({width:0,height:0})})})}_shouldSkipProbing(){var s;const{IN_RN_APP:n,IS_IE:g,IE_VERSION:I,IN_WX_MINI_GAME:E}=((s=this._core)===null||s===void 0?void 0:s.utils)||{};return n||g&&I===9||E}_probeImageDimensionsWeb(s){return new Promise(n=>{const g=new Image,I=()=>{g.onload=null,g.onerror=null,g.src=""};g.onload=()=>{n({width:g.width,height:g.height}),I()},g.onerror=()=>{n({width:0,height:0}),I()},g.src=s})}},ku={exports:{}},Lu=(zI||(zI=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 I(LA,SA){var OA=LA[0],HA=LA[1],se=LA[2],oe=LA[3];HA=((HA+=((se=((se+=((oe=((oe+=((OA=((OA+=(HA&se|~HA&oe)+SA[0]-680876936|0)<<7|OA>>>25)+HA|0)&HA|~OA&se)+SA[1]-389564586|0)<<12|oe>>>20)+OA|0)&OA|~oe&HA)+SA[2]+606105819|0)<<17|se>>>15)+oe|0)&oe|~se&OA)+SA[3]-1044525330|0)<<22|HA>>>10)+se|0,HA=((HA+=((se=((se+=((oe=((oe+=((OA=((OA+=(HA&se|~HA&oe)+SA[4]-176418897|0)<<7|OA>>>25)+HA|0)&HA|~OA&se)+SA[5]+1200080426|0)<<12|oe>>>20)+OA|0)&OA|~oe&HA)+SA[6]-1473231341|0)<<17|se>>>15)+oe|0)&oe|~se&OA)+SA[7]-45705983|0)<<22|HA>>>10)+se|0,HA=((HA+=((se=((se+=((oe=((oe+=((OA=((OA+=(HA&se|~HA&oe)+SA[8]+1770035416|0)<<7|OA>>>25)+HA|0)&HA|~OA&se)+SA[9]-1958414417|0)<<12|oe>>>20)+OA|0)&OA|~oe&HA)+SA[10]-42063|0)<<17|se>>>15)+oe|0)&oe|~se&OA)+SA[11]-1990404162|0)<<22|HA>>>10)+se|0,HA=((HA+=((se=((se+=((oe=((oe+=((OA=((OA+=(HA&se|~HA&oe)+SA[12]+1804603682|0)<<7|OA>>>25)+HA|0)&HA|~OA&se)+SA[13]-40341101|0)<<12|oe>>>20)+OA|0)&OA|~oe&HA)+SA[14]-1502002290|0)<<17|se>>>15)+oe|0)&oe|~se&OA)+SA[15]+1236535329|0)<<22|HA>>>10)+se|0,HA=((HA+=((se=((se+=((oe=((oe+=((OA=((OA+=(HA&oe|se&~oe)+SA[1]-165796510|0)<<5|OA>>>27)+HA|0)&se|HA&~se)+SA[6]-1069501632|0)<<9|oe>>>23)+OA|0)&HA|OA&~HA)+SA[11]+643717713|0)<<14|se>>>18)+oe|0)&OA|oe&~OA)+SA[0]-373897302|0)<<20|HA>>>12)+se|0,HA=((HA+=((se=((se+=((oe=((oe+=((OA=((OA+=(HA&oe|se&~oe)+SA[5]-701558691|0)<<5|OA>>>27)+HA|0)&se|HA&~se)+SA[10]+38016083|0)<<9|oe>>>23)+OA|0)&HA|OA&~HA)+SA[15]-660478335|0)<<14|se>>>18)+oe|0)&OA|oe&~OA)+SA[4]-405537848|0)<<20|HA>>>12)+se|0,HA=((HA+=((se=((se+=((oe=((oe+=((OA=((OA+=(HA&oe|se&~oe)+SA[9]+568446438|0)<<5|OA>>>27)+HA|0)&se|HA&~se)+SA[14]-1019803690|0)<<9|oe>>>23)+OA|0)&HA|OA&~HA)+SA[3]-187363961|0)<<14|se>>>18)+oe|0)&OA|oe&~OA)+SA[8]+1163531501|0)<<20|HA>>>12)+se|0,HA=((HA+=((se=((se+=((oe=((oe+=((OA=((OA+=(HA&oe|se&~oe)+SA[13]-1444681467|0)<<5|OA>>>27)+HA|0)&se|HA&~se)+SA[2]-51403784|0)<<9|oe>>>23)+OA|0)&HA|OA&~HA)+SA[7]+1735328473|0)<<14|se>>>18)+oe|0)&OA|oe&~OA)+SA[12]-1926607734|0)<<20|HA>>>12)+se|0,HA=((HA+=((se=((se+=((oe=((oe+=((OA=((OA+=(HA^se^oe)+SA[5]-378558|0)<<4|OA>>>28)+HA|0)^HA^se)+SA[8]-2022574463|0)<<11|oe>>>21)+OA|0)^OA^HA)+SA[11]+1839030562|0)<<16|se>>>16)+oe|0)^oe^OA)+SA[14]-35309556|0)<<23|HA>>>9)+se|0,HA=((HA+=((se=((se+=((oe=((oe+=((OA=((OA+=(HA^se^oe)+SA[1]-1530992060|0)<<4|OA>>>28)+HA|0)^HA^se)+SA[4]+1272893353|0)<<11|oe>>>21)+OA|0)^OA^HA)+SA[7]-155497632|0)<<16|se>>>16)+oe|0)^oe^OA)+SA[10]-1094730640|0)<<23|HA>>>9)+se|0,HA=((HA+=((se=((se+=((oe=((oe+=((OA=((OA+=(HA^se^oe)+SA[13]+681279174|0)<<4|OA>>>28)+HA|0)^HA^se)+SA[0]-358537222|0)<<11|oe>>>21)+OA|0)^OA^HA)+SA[3]-722521979|0)<<16|se>>>16)+oe|0)^oe^OA)+SA[6]+76029189|0)<<23|HA>>>9)+se|0,HA=((HA+=((se=((se+=((oe=((oe+=((OA=((OA+=(HA^se^oe)+SA[9]-640364487|0)<<4|OA>>>28)+HA|0)^HA^se)+SA[12]-421815835|0)<<11|oe>>>21)+OA|0)^OA^HA)+SA[15]+530742520|0)<<16|se>>>16)+oe|0)^oe^OA)+SA[2]-995338651|0)<<23|HA>>>9)+se|0,HA=((HA+=((oe=((oe+=(HA^((OA=((OA+=(se^(HA|~oe))+SA[0]-198630844|0)<<6|OA>>>26)+HA|0)|~se))+SA[7]+1126891415|0)<<10|oe>>>22)+OA|0)^((se=((se+=(OA^(oe|~HA))+SA[14]-1416354905|0)<<15|se>>>17)+oe|0)|~OA))+SA[5]-57434055|0)<<21|HA>>>11)+se|0,HA=((HA+=((oe=((oe+=(HA^((OA=((OA+=(se^(HA|~oe))+SA[12]+1700485571|0)<<6|OA>>>26)+HA|0)|~se))+SA[3]-1894986606|0)<<10|oe>>>22)+OA|0)^((se=((se+=(OA^(oe|~HA))+SA[10]-1051523|0)<<15|se>>>17)+oe|0)|~OA))+SA[1]-2054922799|0)<<21|HA>>>11)+se|0,HA=((HA+=((oe=((oe+=(HA^((OA=((OA+=(se^(HA|~oe))+SA[8]+1873313359|0)<<6|OA>>>26)+HA|0)|~se))+SA[15]-30611744|0)<<10|oe>>>22)+OA|0)^((se=((se+=(OA^(oe|~HA))+SA[6]-1560198380|0)<<15|se>>>17)+oe|0)|~OA))+SA[13]+1309151649|0)<<21|HA>>>11)+se|0,HA=((HA+=((oe=((oe+=(HA^((OA=((OA+=(se^(HA|~oe))+SA[4]-145523070|0)<<6|OA>>>26)+HA|0)|~se))+SA[11]-1120210379|0)<<10|oe>>>22)+OA|0)^((se=((se+=(OA^(oe|~HA))+SA[2]+718787259|0)<<15|se>>>17)+oe|0)|~OA))+SA[9]-343485551|0)<<21|HA>>>11)+se|0,LA[0]=OA+LA[0]|0,LA[1]=HA+LA[1]|0,LA[2]=se+LA[2]|0,LA[3]=oe+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,HA,se,oe,_i,Ti=LA.length,bt=[1732584193,-271733879,-1732584194,271733878];for(SA=64;SA<=Ti;SA+=64)I(bt,E(LA.substring(SA-64,SA)));for(OA=(LA=LA.substring(SA-64)).length,HA=[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(HA[SA>>2]|=128<<(SA%4<<3),SA>55)for(I(bt,HA),SA=0;SA<16;SA+=1)HA[SA]=0;return se=(se=8*Ti).toString(16).match(/(.*?)(.{0,8})$/),oe=parseInt(se[2],16),_i=parseInt(se[1],16)||0,HA[14]=oe,HA[15]=_i,I(bt,HA),bt}function M(LA){var SA,OA,HA,se,oe,_i,Ti=LA.length,bt=[1732584193,-271733879,-1732584194,271733878];for(SA=64;SA<=Ti;SA+=64)I(bt,m(LA.subarray(SA-64,SA)));for(OA=(LA=SA-64>2]|=LA[SA]<<(SA%4<<3);if(HA[SA>>2]|=128<<(SA%4<<3),SA>55)for(I(bt,HA),SA=0;SA<16;SA+=1)HA[SA]=0;return se=(se=8*Ti).toString(16).match(/(.*?)(.{0,8})$/),oe=parseInt(se[2],16),_i=parseInt(se[1],16)||0,HA[14]=oe,HA[15]=_i,I(bt,HA),bt}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 HA,se,oe,_i,Ti=this.byteLength,bt=LA(SA,Ti),Ni=Ti;return OA!==n&&(Ni=LA(OA,Ti)),bt>Ni?new ArrayBuffer(0):(HA=Ni-bt,se=new ArrayBuffer(HA),oe=new Uint8Array(se),_i=new Uint8Array(this,bt,HA),oe.set(_i),se)}}(),YA.prototype.append=function(LA){return this.appendBinary(W(LA)),this},YA.prototype.appendBinary=function(LA){this._buff+=LA,this._length+=LA.length;var SA,OA=this._buff.length;for(SA=64;SA<=OA;SA+=64)I(this._hash,E(this._buff.substring(SA-64,SA)));return this._buff=this._buff.substring(SA-64),this},YA.prototype.end=function(LA){var SA,OA,HA=this._buff,se=HA.length,oe=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(SA=0;SA>2]|=HA.charCodeAt(SA)<<(SA%4<<3);return this._finish(oe,se),OA=P(this._hash),LA&&(OA=kA(OA)),this.reset(),OA},YA.prototype.reset=function(){return this._buff="",this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},YA.prototype.getState=function(){return{buff:this._buff,length:this._length,hash:this._hash.slice()}},YA.prototype.setState=function(LA){return this._buff=LA.buff,this._length=LA.length,this._hash=LA.hash,this},YA.prototype.destroy=function(){delete this._hash,delete this._buff,delete this._length},YA.prototype._finish=function(LA,SA){var OA,HA,se,oe=SA;if(LA[oe>>2]|=128<<(oe%4<<3),oe>55)for(I(this._hash,LA),oe=0;oe<16;oe+=1)LA[oe]=0;OA=(OA=8*this._length).toString(16).match(/(.*?)(.{0,8})$/),HA=parseInt(OA[2],16),se=parseInt(OA[1],16)||0,LA[14]=HA,LA[15]=se,I(this._hash,LA)},YA.hash=function(LA,SA){return YA.hashBinary(W(LA),SA)},YA.hashBinary=function(LA,SA){var OA=P(D(LA));return SA?kA(OA):OA},YA.ArrayBuffer=function(){this.reset()},YA.ArrayBuffer.prototype.append=function(LA){var SA,OA=wA(this._buff.buffer,LA),HA=OA.length;for(this._length+=LA.byteLength,SA=64;SA<=HA;SA+=64)I(this._hash,m(OA.subarray(SA-64,SA)));return this._buff=SA-64>2]|=HA[SA]<<(SA%4<<3);return this._finish(oe,se),OA=P(this._hash),LA&&(OA=kA(OA)),this.reset(),OA},YA.ArrayBuffer.prototype.reset=function(){return this._buff=new Uint8Array(0),this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},YA.ArrayBuffer.prototype.getState=function(){var LA=YA.prototype.getState.call(this);return LA.buff=EA(LA.buff),LA},YA.ArrayBuffer.prototype.setState=function(LA){return LA.buff=oA(LA.buff,!0),YA.prototype.setState.call(this,LA)},YA.ArrayBuffer.prototype.destroy=YA.prototype.destroy,YA.ArrayBuffer.prototype._finish=YA.prototype._finish,YA.ArrayBuffer.hash=function(LA,SA){var OA=P(M(new Uint8Array(LA)));return SA?kA(OA):OA},YA}()}(ku)),ku.exports),lC=tI(Lu),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?hI:Gu,(n=this.httpRequest)===null||n===void 0||n.init(s)}uploadToCOS(s){return pA(this,void 0,void 0,function*(){const n=`${da} uploadToCOS`,{ssoLog:g,utils:{safeStringify:I}}=this._core,{file:E}=s;this.uploadFileType=s.uploadFileType,g.debug("uploadToCOS",`${n} options:${I(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),oA=`size:${W} time:${P}ms speed:${vr(1e3*E.size/P)}`;return g.debug("uploadToCOS",`${n} ok. name:${E.name} ${oA}`),{uploadOptions:D,response:T}}catch(m){throw g.warn("uploadToCOS",`${n} failed, error:${I(m)}`),m}})}_handleUploadError(s,n){var g,I;const{ChatError:E}=(g=this._core)===null||g===void 0?void 0:g.helper;if(s.statusCode===403)throw n.url,!((I=s?.data)===null||I===void 0)&&I.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:br(Date.now(),!1),uploadSpeed:vr(1e3*s.size/br(Date.now(),!1))}}_createCosOptions(s){return pA(this,void 0,void 0,function*(){const{fileName:n,resources:g,uploadMethod:I}=yield this._prepareUploadParams(s),E=this._isC2CConversation(s.message.conversationID)?1:2;try{const m=yield this._fetchCosSignatureUrl({fileType:this.uploadFileType,fileName:n,uploadMethod:I,duration:this.duration,userID:s.message.from,conversationType:E}),{uploadUrl:D,downloadUrl:M,requestSnapshotUrl:T,thumbUrl:P,largeUrl:W,fileKey:oA,existFlag:EA}=m,wA=!Ut.isPrivateNetWork()&&m.uploadIP;return{url:this._getRawOrUploadProxyUrl(D),fileType:this.uploadFileType,fileName:n,resources:g,downloadUrl:M,requestSnapshotUrl:T,thumbUrl:P,largeUrl:W,fileKey:oA,uploadIP:wA||"",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:I}}=this._core;n.debug("_prepareUploadParams",` prepareUploadParams:${g(s)}`);const{file:E}=s,{IN_MINI_APP:m,IN_RN_APP:D}=Ut.getPlatformFlags(),M=m||D,T=M&&s.message.type!==xa,{name:P}=E,W=P.slice(P.lastIndexOf(".")),oA=`${Gr(999999)}${W}`,EA=T?E.name:oA,wA=yield this._generateHashFileName(E);return{fileName:I(wA)?lg(EA):`${wA}${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:I,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]),I||(M=yield this._generateFileNameInMiniProgram(s)),I&&(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 I="";try{I=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 lC.ArrayBuffer,oA=new FileReader,EA=setTimeout(()=>{oA.abort(),n.warn("_generateHashFileNameInWeb","File hash generation timeout"),E("")},2e3);function wA(){const kA=P*M,YA=kA+M>=s.size?s.size:kA+M;oA.readAsArrayBuffer(D.call(s,kA,YA))}oA.onload=kA=>{n.debug("_generateHashFileNameInWeb",`read chunk nr ${P+1} of ${T}`),W.append(kA.target.result),P++,P{clearTimeout(EA),m(kA)},wA()})}catch(E){n.warn("_generateHashFileNameInWeb",g(E))}return I})}_generateFileNameInMiniProgram(s){return pA(this,void 0,void 0,function*(){const{utils:{MINI_APP_NAMESPACE:n,safeStringify:g,isEmpty:I},ssoLog:E}=this._core;let m="";if(I(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:I},ssoLog:E}=this._core;let m="";if(I(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,I=Ut.isSimpleCos(),E=this._prepareCosRequestData(s),m=I?"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:oA,channel:EA}=W,wA=oA.generateCosSpecifiedData({servcmd:T,data:P}),kA=`${wA.head.seq}${T}`;return yield EA.sendPacket(wA,{requestId:kA})}catch(oA){throw console.warn("getCosSig error:",oA),oA}})}(m,E,this._core);this.fetchCosTryCount=0;const M=this._processResponse(D);return n.debug("_fetchCosSignatureUrl",` ok. isSimpleCos:${I} 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=Ut.isSimpleCos(),I=g?(n=s?.rpt_pre_sig)===null||n===void 0?void 0:n[0]:s;if(!I)return{};if(g){const{str_final_ip:W,rpt_pre_sig:oA,uint32_file_id:EA,uint32_exist_flag:wA,str_download_url:kA,str_upload_url:YA,str_snapshot_url:LA,str_file_key:SA}=I;return{uploadIP:W,preSig:oA,fileID:EA,existFlag:wA,downloadUrl:kA,uploadUrl:YA,requestSnapshotUrl:LA,fileKey:SA}}const{upload_url:E,download_url:m,snapshot_url:D,thumb_url:M,large_url:T,file_key:P}=I;return{uploadUrl:E,downloadUrl:m,requestSnapshotUrl:D,thumbUrl:M,largeUrl:T,fileKey:P}}_prepareCosRequestData(s){return Ut.isSimpleCos()?{uint32_upload_method:s.uploadMethod,uint32_platform:Ut.getPlatform(),uint32_sdkappid:Ut.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,(I,E)=>{I&&this.uploadFileTryCount=3e4}_syncSystemClock(s){var n,g,I;const E=((n=s.headers)===null||n===void 0?void 0:n.date)||((g=s.headers)===null||g===void 0?void 0:g.Date)||((I=s.error)===null||I===void 0?void 0:I.ServerTime);if(E){const m=Date.now(),D=Date.parse(E);this.systemClockOffset=D-m}}_getRawOrUploadProxyUrl(s){const n=Ut.getFileUploadProxy();let g=s;return n&&(g=s.replace(/^https:\/\/[^/]+/,n)),g}_isC2CConversation(s){return s.slice(0,3)==="C2C"}};const L=2108,sA=2251,G=2252,x=2253,iA=["jpg","jpeg","gif","png","bmp","image","webp"],uA={JPG:1,JPEG:1,GIF:2,PNG:3,BMP:4,UNKNOWN:255},_A=1,XA=2;class Qe{constructor(n,g){this.instanceID=Gr(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=Ut.addAuthToUrl(n.imageUrl||n.url||""),this.url=Ut.addAuthToUrl(n.url||g)}setSizeType(n){this.sizeType=n}setType(n){this.type=n}setImageUrl(n){n&&(this.imageUrl=Ut.addAuthToUrl(n))}getImageUrl(){return this.imageUrl}}function Q(s){const{originUrl:n,originWidth:g,originHeight:I,min:E=198}=s,m=parseInt(g)||0,D=parseInt(I)||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 yo(M,["url"])}return M}class h{constructor(n){this._imageMemoryURL="",this._percent=0,this.type=tc;const{uuid:g,file:I,imageFormat:E,imageInfoArray:m=[],isCustomUpload:D=!1}=n;this._imageMemoryURL=this.createImageDataAsURL(I),this.content={imageFormat:E,uuid:g,imageInfoArray:[]},this[xr]=D,this.initImageInfoArray(m),this.autoFixUrl()}static parseServerPushElement(n){const{MsgContent:g}=n,{ImageFormat:I,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 h({imageFormat:I,imageInfoArray:D,uuid:m})}createImageDataAsURL(n){let g="";const{IN_MINI_APP:I,IN_RN_APP:E,IN_BROWSER:m}=Ut.getPlatformFlags();return n&&((I||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 I=0;I<3;I++){const E=n[I]||Object.assign({},g),m=new Qe(E,this._imageMemoryURL);m.setSizeType(I+1),m.setType(I),this.addImageInfo(m)}this.updateAccessSideImageInfoArray()}autoFixUrl(){const n=["http","https"];this.content.imageInfoArray.forEach(g=>{if(!g.url||g.imageUrl==="")return;const[I,...E]=g.imageUrl.split("://"),m=E.join("://");n.includes(I)||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 I;for(let E=0;E({InstanceId:g.instanceID,Type:g.sizeType,MsgType:g.type,Size:g.size,Width:g.width,Height:g.height,URL:Ut.removeAuthToUrl(g.imageUrl)}))}}const v=new class{init(s){this.core=s}},N={[jI]:"i",[al]:"a",[Ca]:"v",[wE]:"f"};let O=null,z=null;function X(s){var n;const{store:g,utils:{isNumber:I,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(I(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:I,InnerEvent:E,message:m}=s;I.registerApi({apiName:"createImageMessage",context:this}),I.registerExperimentalAPI("createImageMessage",this,"createCustomUploadImageMessage"),(n=m?.messageFactory)===null||n===void 0||n.registerElementClass(tc,h),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createImageMessage(s){var n,g,I;try{const E=(n=this._core.store.get("login"))===null||n===void 0?void 0:n.userId,m=(I=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||I===void 0?void 0:I.createMessage(Object.assign(Object.assign({},s),{from:E})),D=this._processImage(s);s.payload.file=D;const M={imageFormat:uA.UNKNOWN,uuid:Ut.generateUUID(D),file:D,imageInfoArray:[]},T=new h(M);return m.setElement(T),this._messageOptionsMap.set(m.clientSequence,s),m}catch(E){throw E}}createCustomUploadImageMessage(s){var n,g,I,E;const{store:m,utils:{isEmpty:D}}=this._core,M=(n=m.get("login"))===null||n===void 0?void 0:n.userId,T=(I=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||I===void 0?void 0:I.createMessage(Object.assign(Object.assign({},s),{from:M})),{largeImageUuid:P,largeFileSize:W,largeImageWidth:oA,largeImageHeight:EA,largeImageUrl:wA,originImageUuid:kA,originFileSize:YA,originImageWidth:LA,originImageHeight:SA,originImageUrl:OA,thumbImageUuid:HA,thumbFileSize:se,thumbImageWidth:oe,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 bt=new h({imageFormat:uA.UNKNOWN,uuid:kA,imageInfoArray:[{instanceID:kA,size:YA,width:LA,height:SA,imageUrl:OA,url:OA},{instanceID:P,size:W,width:oA,height:EA,imageUrl:wA,url:wA},{instanceID:HA,size:se,width:oe,height:_i,imageUrl:Ti,url:Ti}],isCustomUpload:!0});return T.setElement(bt),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 I=yield this._performImageUpload(n,s,g),E=this._generateImageInfo(I);return n.updateImageFormat(I?.fileType),n.updateImageInfoArray(E),this._updateImageType(n.content.imageInfoArray),s})}_performImageUpload(s,n,g){return pA(this,void 0,void 0,function*(){const{to:I}=n,E={uploadFileType:jI,file:g,to:I,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:I,height:E,smallImageUrl:m,smallImageWidth:D,smallImageHeight:M,largeImageUrl:T,largeImageWidth:P,largeImageHeight:W,imageInfoArray:oA}=s,EA=Ut.addAuthToUrl(n),wA={size:g,url:EA,width:I,height:E};return oA?.length>0?this._processImageInfoArray(oA,g):m&&T?[Object.assign({},wA),{largeImageUrl:T,largeImageWidth:P,largeImageHeight:W},{smallImageUrl:m,smallImageWidth:D,smallImageHeight:M}]:[Object.assign({},wA),this._generateThumbInfo(EA,I,E,720),this._generateThumbInfo(EA,I,E,198)]}_generateThumbInfo(s,n,g,I){return Q({originUrl:s,originWidth:n,originHeight:g,min:I})}_processImageInfoArray(s,n){let g,I,E;for(const m of s)m.type===1?(I=m,I.size=n):m.type===2?(E=m,E.size=n):(g=m,g.size=n);return[Object.assign({},g),Object.assign({},E),Object.assign({},I)]}_parseResponse(s,n){return pA(this,void 0,void 0,function*(){try{const{thumbUrl:g,largeUrl:I,downloadUrl:E}=s;if(g&&I&&(yield this._getImageInfoByUrl(g,n,"thumb"),yield this._getImageInfoByUrl(I,n,"large")),Ut.isSimpleCos()&&!Ut.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 I;try{const E=Ut.addAuthToUrl(s),{width:m=0,height:D=0}=yield Ut.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){(I=this._core)===null||I===void 0||I.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:sA});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:I}=s.payload;return I=g?this._processMiniAppImageFile(I):this._processWebImageFile(I),I}catch(g){throw g}}_processMiniAppImageFile(s){rl(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,I=Ut.extractFileFromInput(s);if(!I)throw new g({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return I}_getDownloadIP(s,n){return pA(this,void 0,void 0,function*(){const g=`${da} getDownloadIP domainName: ${s}`;try{const I=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},oA=M.generateProtocolData({servcmd:P,data:W}),EA=`${oA.head.seq}${P}`;return yield T.sendPacket(oA,{requestId:EA})}catch(M){throw console.warn("getFinalIP error:",M),M}})}(s,this._core);if(!I||!I.str_final_ip)return;console.log(`${g} ok. downloadIP:${I}`);const E=n.location.split("/");E[0]=I.str_final_ip,n.location=E.join("/")}catch(I){console.warn(I)}})}_getImageInfoArray(s,n){return pA(this,void 0,void 0,function*(){try{const g=yield function(I,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:I},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 I="";if(n.IN_MINI_APP&&(I=s.url.slice(s.url.lastIndexOf(".")+1)),n.IN_BROWSER&&(I=s.name.slice(s.name.lastIndexOf(".")+1)),iA.indexOf(I.toLowerCase())<0)throw new g.ChatError({code:G})}_checkImageSize(s){const{utils:n,helper:g,store:I}=this._core;let E=0;if(E=(n.IN_MINI_APP,s.size),E===0)throw new g.ChatError({code:L});if(E>=(X(jI)||20971520))throw new g.ChatError({code:x})}_updateImageType(s){s[1].type=XA,s[2].type=_A}_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,JA=2402,ee="2.5.0",ue="1.18.0";function He(s,n){const g=s.split("."),I=n.split("."),E=Math.max(g.length,I.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||{},I=g?this.payload:this.content,{uuid:E,downloadFlag:m,fileUrl:D,fileName:M,fileSize:T}=I;return{MsgType:this.type,MsgContent:{Download_Flag:m,Url:Ut.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:I}=n;return I?(g&&this._processNativeAppFile(I),{size:I.size,name:I.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=`${Gr(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)}}At=xr;var Gt=new class{constructor(){this._messageOptionsMap=new Map}init(s){var n;this._core=s;const{notificationCenter:g,helper:I,InnerEvent:E,message:m}=s;I.registerApi({apiName:"createFileMessage",context:this}),I.registerExperimentalAPI("createFileMessage",this,"createCustomUploadFileMessage"),(n=m?.messageFactory)===null||n===void 0||n.registerElementClass(xa,st),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createFileMessage(s){var n,g,I;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=(I=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||I===void 0?void 0:I.createMessage(Object.assign(Object.assign({},s),{from:m})),M={uuid:Ut.generateUUID(E),file:E},T=new st(M);return D.setElement(T),this._messageOptionsMap.set(D.clientSequence,s),D}catch(E){throw E}}createCustomUploadFileMessage(s){var n,g,I;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:oA=""}=((g=s?.payload)===null||g===void 0?void 0:g.file)||{};if(D(T))throw new Error("url is required");const EA=(I=m.messageFactory)===null||I===void 0?void 0:I.createMessage(Object.assign(Object.assign({},s),{from:M})),wA=new st({url:T,uuid:P,file:{size:W,name:oA},isCustomUpload:!0});return EA.setElement(wA),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],I=yield this._performFileUpload(g,s,n),E=Ut.addAuthToUrl(I?.location);return g.updateFileUrl(E),s})}_validateBeforeUploadFile(s){const{helper:{ChatError:n}}=this._core;if(!s)throw new n({code:GA});const g=X(wE)||104857600;if(s.size>g)throw new n({code:JA});if(s.size===0)throw new n({code:DA})}_performFileUpload(s,n,g){return pA(this,void 0,void 0,function*(){const{to:I}=n,E={uploadFileType:wE,file:g,to:I,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:I,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(I||M){const P=Ut.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:I,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(I){if(!(E||m||D))throw new M({message:"Unsupported mini app environment"});const T=g.getSystemInfoSync().SDKVersion;if(E&&He(T,ee)<0)throw new M({message:`WXChooseMessageFile requires SDK version ${ee} or higher`});if(m&&He(T,ue)<0)throw new M({message:`QQChooseMessageFile requires SDK version ${ue} or higher`})}}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this)}};const xt=2108,Ui=2351,ao=2352,zi=["mp4","quicktime","mov","video"];var ui;class Oo{constructor(n){this.type=kl,this.uploadProgress=0,this[ui]=!1;const g=typeof n?.videoSecond=="number"?n?.videoSecond:0;this[xr]=n.isCustomUpload||!1,this.content={remoteVideoUrl:Ut.addAuthToUrl(n.remoteVideoUrl||n.videoUrl||""),videoFormat:n.videoFormat,videoSecond:parseInt(g?.toString(),10),videoSize:n.videoSize,videoUrl:Ut.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:Ut.addAuthToUrl(n.thumbUrl),snapshotUrl:Ut.addAuthToUrl(n.thumbUrl)}}static parseServerPushElement(n){const{MsgContent:g}=n,{VideoUrl:I,VideoFormat:E,VideoSecond:m,VideoSize:D,VideoDownloadFlag:M,VideoUUID:T,ThumbUUID:P,ThumbFormat:W,ThumbWidth:oA,SnapshotWidth:EA,ThumbHeight:wA,SnapshotHeight:kA,ThumbSize:YA,SnapshotSize:LA,ThumbDownloadFlag:SA,ThumbUrl:OA,SnapshotUrl:HA}=g;return new Oo({videoUrl:I,videoFormat:E,videoSecond:m,videoSize:D,videoDownloadFlag:M,videoUUID:T,thumbUUID:P,thumbFormat:W,thumbWidth:oA,snapshotWidth:EA,thumbHeight:wA,snapshotHeight:kA,thumbSize:YA,snapshotSize:LA,thumbDownloadFlag:SA,thumbUrl:OA,snapshotUrl:HA})}updatePercent(n){this.uploadProgress=Math.min(n,1)}updateVideoUrl(n){n&&(this.content.remoteVideoUrl=n)}updateSnapshotInfo(n){const{snapshotUrl:g,snapshotWidth:I,snapshotHeight:E}=n;Ut.isEmpty(g)||(this.content.thumbUrl=this.content.snapshotUrl=g),Ut.isEmpty(I)||(this.content.thumbWidth=this.content.snapshotWidth=Number(I)),Ut.isEmpty(E)||(this.content.thumbHeight=this.content.snapshotHeight=Number(E))}validateBeforeSend(){if(this[xr])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||{},I=g?this.payload:this.content,{remoteVideoUrl:E,videoFormat:m,videoSecond:D,videoSize:M,videoDownloadFlag:T,videoUUID:P,thumbUUID:W,thumbFormat:oA,thumbWidth:EA,snapshotWidth:wA,thumbHeight:kA,snapshotHeight:YA,thumbSize:LA,snapshotSize:SA,thumbDownloadFlag:OA,thumbUrl:HA,snapshotUrl:se}=I;return{MsgType:this.type,MsgContent:{VideoUrl:Ut.removeAuthToUrl(E),VideoFormat:m,VideoSecond:D,VideoSize:M,VideoDownloadFlag:T,VideoUUID:P,ThumbUUID:W,ThumbFormat:oA,ThumbWidth:EA,SnapshotWidth:wA,ThumbHeight:kA,SnapshotHeight:YA,ThumbSize:LA,SnapshotSize:SA,ThumbDownloadFlag:OA,ThumbUrl:Ut.removeAuthToUrl(HA),SnapshotUrl:Ut.removeAuthToUrl(se)}}}}ui=xr;var $o,Qi=new class{constructor(){this._messageOptionsMap=new Map}init(s){var n;this._core=s;const{notificationCenter:g,helper:I,InnerEvent:E,message:m}=s;I.registerApi({apiName:"createVideoMessage",context:this}),I.registerExperimentalAPI("createVideoMessage",this,"createCustomUploadVideoMessage"),(n=m?.messageFactory)===null||n===void 0||n.registerElementClass(kl,Oo),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createVideoMessage(s){var n,g,I;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=(I=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||I===void 0?void 0:I.createMessage(Object.assign(Object.assign({},s),{from:m})),M={videoFormat:E.videoFile.type,videoSecond:rr(E.videoFile.second,0),videoSize:E.videoFile.size,remoteVideoUrl:"",videoUrl:E.videoFile.url,videoUUID:Ut.generateUUID(E.videoFile),thumbUUID:Ut.generateUUID(E.videoFile,"jpg"),thumbWidth:E.width||200,thumbHeight:E.height||200,thumbUrl:E.thumbUrl,thumbSize:E.thumbSize,thumbFormat:"jpg"},T=new Oo(M);return D.setElement(T),this._messageOptionsMap.set(D.clientSequence,s),D}catch(E){throw E}}createCustomUploadVideoMessage(s){var n,g,I;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:oA,videoFileSize:EA,videoType:wA,snapshotWidth:kA,snapshotHeight:YA,snapshotFileSize:LA,snapshotType:SA="jpg"}=((g=s?.payload)===null||g===void 0?void 0:g.file)||{},OA=(I=m.messageFactory)===null||I===void 0?void 0:I.createMessage(Object.assign(Object.assign({},s),{from:D})),HA=new Oo({videoFormat:wA,videoSecond:P||0,videoSize:EA,remoteVideoUrl:M,videoUrl:M,videoUUID:T,thumbUUID:oA,thumbWidth:kA||200,thumbHeight:YA||200,thumbUrl:W,thumbSize:LA,thumbFormat:SA,isCustomUpload:!0});return OA.setElement(HA),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 I=yield this._performVideoUpload(n,s,g),{location:E,snapshotInfo:m}=I,D=Ut.addAuthToUrl(E);return n.updateVideoUrl(D),Ut.isEmpty(m)||n.updateSnapshotInfo(m),s})}_validateBeforeUploadVideo(s){const{helper:{ChatError:n}}=this._core,g=X(Ca)||104857600;if(s.videoFile.size>g)throw new n({code:Ui});if(s.videoFile.size===0)throw new n({code:xt});if(zi.indexOf(s.videoFile.type)===-1)throw new n({code:ao})}_validateCustomUploadVideoMessage(s){var n;const{utils:{isEmpty:g,isNumber:I}}=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)||!I(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:I}=n,E={uploadFileType:Ca,file:g,to:I,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:I}=(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=Ut.extractFileFromInput(D);if(!T)throw new I({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(I){throw console.warn(`${da} _processFile error:`,I),I}}_processMiniVideoFile(s){const{utils:{IN_UNI_NATIVE_APP:n},helper:{ChatError:g}}=this._core;if(rl(s))throw new g({message:"FileUnsupportedInMiniApp"});Array.isArray(s.tempFiles)&&(s=s.tempFiles[0]);let I=s.tempFilePath.slice(s.tempFilePath.lastIndexOf(".")+1).toLowerCase();return n&&(I=s.fileType||I),{url:s.tempFilePath,name:s.tempFilePath.slice(s.tempFilePath.lastIndexOf("/")+1),size:s.size||1,second:s.duration||0,type:I}}_processWebVideoFile(s){const{name:n,size:g=1,duration:I=0,type:E}=s,m=E.split("/")[1];return{url:window.URL.createObjectURL(s),name:n,size:g,second:I,type:m}}_getSnapshotInfoByUrl(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n}=this._core;try{n.debug("_getSnapshotInfoByUrl",`${da} _getSnapshotInfoByUrl url:${s}`);const g={version:1,platform:Ut.getPlatform(),cover_name:lg(Gr(99999)),snapshot_url:s},I=yield function(T,P){return pA(this,void 0,void 0,function*(){try{const W="im_cos_msg.video_cover",{helper:oA,channel:EA}=P,wA=oA.generateCosSpecifiedData({servcmd:W,data:T}),kA=`${wA.head.seq}${W}`;return yield EA.sendPacket(wA,{requestId:kA})}catch(W){throw console.warn("getSnapshotInfo error:",W),W}})}(g,this._core),{download_url:E}=I||{};if(n.debug("_getSnapshotInfoByUrl",`${da} _getSnapshotInfoByUrl OK snapshotUrl:${E}`),Ut.isEmpty(E))return{};const m=Ut.addAuthToUrl(E),{width:D=0,height:M=0}=yield Ut.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=Ug,this[$o]=!1,this[xr]=n.isCustomUpload||!1,this.content={downloadFlag:2,second:n.second,size:n.size,url:Ut.generateURL(n.url,{needAddAuthToUrl:!this[xr]}),remoteAudioUrl:Ut.addAuthToUrl(n.url||""),uuid:n.uuid}}static parseServerPushElement(n){const{MsgContent:g}=n,{Url:I,Download_Flag:E,Second:m,Size:D,UUID:M}=g;return new Ki({url:I,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[xr])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||{},I=g?this.payload:this.content,{uuid:E,downloadFlag:m,remoteAudioUrl:D,size:M,second:T}=I;return{MsgType:this.type,MsgContent:{Url:Ut.removeAuthToUrl(D),Download_Flag:m,Second:T,Size:M,UUID:E}}}}$o=xr;const js=2108,we=2300,vt=2301;var FA=new class{constructor(){this._messageOptionsMap=new Map}init(s){var n;this._core=s;const{notificationCenter:g,helper:I,InnerEvent:E,message:m}=s;I.registerApi({apiName:"createAudioMessage",context:this}),I.registerExperimentalAPI("createAudioMessage",this,"createCustomUploadAudioMessage"),(n=m?.messageFactory)===null||n===void 0||n.registerElementClass(Ug,Ki),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createAudioMessage(s){var n,g,I;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=(I=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||I===void 0?void 0:I.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:Ut.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,I;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)||{},oA=(I=m.messageFactory)===null||I===void 0?void 0:I.createMessage(Object.assign(Object.assign({},s),{from:D})),EA=new Ki({second:P,size:W||1,url:M,uuid:T,isCustomUpload:!0});return oA.setElement(EA),this._messageOptionsMap.set(oA.clientSequence,s),oA}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",`${da} uploadAudio message:${g(s)}`);const{file:I}=this._messageOptionsMap.get(s.clientSequence).payload;this._validateBeforeUploadAudio(I);const E=s.getElements()[0],m=yield this._performAudioUpload(E,s,I),D=Ut.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 I=X(al)||20971520;if(s.size>I)throw new n({code:vt});if(s.size===0)throw new n({code:js})}_performAudioUpload(s,n,g){return pA(this,void 0,void 0,function*(){const{to:I}=n,E={uploadFileType:al,file:g,to:I,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:I}=(n=this._core)===null||n===void 0?void 0:n.utils;return g?this._processMiniFile(s):I?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:I,uuid:E,duration:m}=((n=s?.payload)===null||n===void 0?void 0:n.file)||{};if(g(I)||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},Is={[tc]:rA,[xa]:Gt,[kl]:Qi,[Ug]: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:I,MSG_VIDEO:E}}}=s;v.init(s),rA.init(s),Gt.init(s),Qi.init(s),FA.init(s),q.init(s),Ut.init(s),s.helper.registerApi({apiName:"sendMessage",context:this,matcher:m=>[n,g,I,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,I,E;try{return this._isCustomUpload(s)||(yield this._upload(s)),yield(E=(I=(g=this._core)===null||g===void 0?void 0:g.message)===null||I===void 0?void 0:I.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 I=Is[s.type];I&&(yield I.upload(s),n.info("_upload",` type:${s.type}`))}catch(I){throw s.status=WI.FAIL,I instanceof Error&&(I.data={message:s}),this._core.message.messageDataHandler.storeConversationMessage(s),I}})}_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[xr])===!0}};const Co=new class{init(s){this.core=s}};class Et{constructor(n){this.conversationID=n.conversationID||"",this.unreadCount=n.unreadCount||0,this.type=n.type||"",this.lastMessage=Co.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:I}}}=Co;I(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),I(this.groupProfile)&&(this.groupProfile={groupID:this.conversationID.replace(g.CONV_GROUP,""),selfInfo:{},lastMessage:{},type:this.subType}))}updateUnreadCount(n){var g;const{core:{OuterConstant:I,utils:{isUndefined:E},store:m}}=Co,{nextUnreadCount:D,isFromGetConversations:M,isUnreadC2CMessage:T}=n;if(E(D))return;if(this.subType===I.GRP_AVCHATROOM)return void(this.unreadCount=0);if(M&&this.type===I.CONV_GROUP)return void(this.unreadCount=D);if(T&&this.type===I.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!==I.GRP_MEETING||P?this.unreadCount+=D:this.unreadCount=0}updateLastMessage(n){this.lastMessage=Co.core.common.buildLastMessage(n)}reduceUnreadCount(){return this.unreadCount>=1&&(this.unreadCount-=1,!0)}isLastMessageRevoked(n){const{core:{OuterConstant:g}}=Co,{sequence:I,time:E}=n;return this.type===g.CONV_C2C&&I===this.lastMessage.lastSequence&&E===this.lastMessage.lastTime||this.type===g.CONV_GROUP&&I===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}}}=Co;g(n,this.groupAtInfoList)}clearGroupAtInfoList(){this.groupAtInfoList.length=0}getProfileCompleted(){return this._isInfoCompleted}setProfileCompleted(){this._isInfoCompleted=!0}}const Ct=s=>{const{core:{OuterConstant:n,utils:{isString:g}}}=Co;return g(s)&&s.slice(0,3)===n.CONV_C2C},Ig=s=>{const{core:{OuterConstant:n,utils:{isString:g}}}=Co;return g(s)&&s.slice(0,5)===n.CONV_GROUP},bs=s=>{const{core:{OuterConstant:n,utils:{isString:g}}}=Co;return g(s)&&s===n.CONV_SYSTEM};function ji(s){const{OuterConstant:n}=Co.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 Yr(s){const{OuterConstant:n}=Co.core;let g;return s.startsWith(n.CONV_C2C)&&(g=s.replace(n.CONV_C2C,"")),g==="@TLS#ERROR"||g==="@TLS#NOT_FOUND"}function ic(s,n){const{helper:g}=Co.core,I=new g.ChatError({functionName:s,code:n?.errorCode||n?.code,message:n?.errorInfo||n?.message});throw console.error(`${s} fail:`,I),I}var es,aa;(function(s){s[s.OFF=0]="OFF",s[s.ON=1]="ON"})(es||(es={})),function(s){s[s.ONLY_CONVERSATIONID=1]="ONLY_CONVERSATIONID"}(aa||(aa={}));var ha;(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"})(ha||(ha={}));const $r=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:I=[]}=g||{};I.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(I,E){return pA(this,void 0,void 0,function*(){const{groupIDList:m,responseFilter:D}=I,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(I=>{var E;const{GroupId:m,MemberList:D}=I,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:I},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:oA,CONVERSATION_UPDATED:EA,LOGOUT:wA,DESTROY:kA},InnerEventSubType:{C2C_MESSAGE_PEER_READ:YA}}=s;this._conversationStore=I,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(oA,this._handleMessageModified,this),g.subscribeInnerEvent(EA,this._handleConversationUpdated,this),g.subscribeInnerEvent(M,YA,this._handleMessageRead,this),g.subscribeInnerEvent(wA,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:I=[],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(I)}_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:I=!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:I,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:I,MsgBody:E,MsgRandom:m,ClientSeq:D}=g;let M={};I?M=this._convertGroupAtTipsKey(I):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:I,GroupAtType:E}=s;return{from:n,groupID:g,sequence:I,groupAtType:E}}_updateGroupAtInfoList(){if(this._groupAtTipsList.length===0)return;const{common:s,OuterConstant:n}=this._core,g=s.getCurrentUserID();let I=!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),I=!0)}}),I&&this.emitConversationListUpdate(),this._groupAtTipsList.length=0}_handleMessageDeleted(s){var n,g;console.log(`${this._name}._handleMessageDeleted, conversationID:`,s);const{message:{messageDataHandler:I},OuterConstant:E}=this._core,m=I?.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 I=null,E=!1;n.forEach(m=>{I=this.getLocalConversation(m.conversationID),I&&(g&&I.reduceUnreadCount()&&(E=!0),I.isLastMessageRevoked({sequence:m.sequence,time:m.time})&&(I.setLastMessageRevoked(!0),I.setLastMessageRevoker(m.revoker),E=!0))}),E&&this.emitConversationListUpdate()}_handleMessageModified(s){const{utils:{isEmpty:n},common:{getMessagePreviewText:g},ssoLog:I}=this._core;I.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:I,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)?I.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(I).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:I,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===I){const T=D.replace(I,"");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:I},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 oA=((T=I.getFriend(P))===null||T===void 0?void 0:T.remark)||"";W.remark=oA,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:I},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",I(M))}})}_handleMessageRead(s){const{OuterConstant:{CONV_C2C:n}}=this._core,{C2cNotifyMsgArray:g=[]}=s||{};g.forEach(I=>{const{To_Account:E,UinPairReadArray:m=[]}=I?.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:I}}=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===I()&&T.lastTime<=m&&!T.isPeerRead&&(T.isPeerRead=!0,n.conversationStore.updateConversation(E,{lastMessage:T}))}}_updateMessageListPeerRead(s){const{notificationCenter:n,OuterEvent:g,message:I}=this._core,{conversationID:E,peerReadTime:m}=s,D=I.messageDataHandler.getLocalMessageList(E),M=I.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:I,GRP_ROOM:E,GRP_LIVE:m},utils:{isUndefined:D}}=this._core,M=this.getLocalConversation(s);if(D(M))return!0;const T=M.type===I&&((n=M.groupProfile)===null||n===void 0?void 0:n.type)===E,P=M.type===I&&((g=M.groupProfile)===null||g===void 0?void 0:g.type)===m;return!(T||P)}updateUnreadCount(s,n=!0){var g,I;let E=!1;const m=this.getLocalConversation(s),D=(I=(g=this._core)===null||g===void 0?void 0:g.message.messageDataHandler)===null||I===void 0?void 0:I.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:I},conversation:E}=this._core,m=this.getLocalConversationList();this._emitEvent({name:I,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 I=0;return g.forEach(E=>{E.type!==s.CONV_SYSTEM&&(n(E.messageRemindType)||E.messageRemindType===s.MSG_REMIND_ACPT_AND_NOTE)&&(I+=E.unreadCount)}),I}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(I=>{const E=this.getLocalConversation(I);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:I=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=I&&T.time>I,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(I=>I[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:I,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(I,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:I}}=this._core;if(n(s))return NA.getLocalConversationList();if(g(s))return s.length===0?[]:NA.getLocalConversationList().filter(E=>s.includes(E.conversationID));if(I(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}},ve=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:I},appStore:{groupStore:E},utils:{isEmpty:m}}=this._core,D={code:0,data:{}};let M=NA.getLocalConversation(s);if(bs(s))return D.data.conversation=M,D;let T=!1;const P=Ct(s)?n:g;if(m(M)&&(T=!0,M=new Et({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!==I&&(yield yA.get([W]))}return D})}_handleC2CConversation(s,n){return pA(this,void 0,void 0,function*(){var g,I;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:ha.USER_OR_GRP_NOT_FOUND});s.userProfile=W?.data[0];const oA=(I=T.getFriend(n))===null||I===void 0?void 0:I.remark;D(oA)||s.remark===oA||(s.remark=oA),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:I}}=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?I.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()}},Te=new class{constructor(){this._serverGroupConversationLastReadSeqMap=new Map,this._name="SetMessageRead"}init(s){this._core=s;const{helper:n,common:{isTopic:g},notificationCenter:I,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}),I.subscribeInnerEvent(E,m,this._handleAllMessageRead,this)}handleC2CMessageReadSync(s){const{helper:{isEmpty:n},OuterConstant:g}=this._core;s.forEach(I=>{const{ReadC2cMsgNotify:E}=I;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(I=>{const{GroupReadInfoArray:E}=I.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:I}=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===I.CONV_GROUP&&T&&this._deleteGroupAtTips(E),D.unreadCount===0)return m;const{helper:{ChatError:P}}=this._core;try{if(D.type===I.CONV_C2C){const W=this._getLocalMessageMaxTime(D);M+=`lastMessageTime:${W}`,yield this._setC2CMessageRead(E,W)}if(D.type===I.CONV_GROUP){const W=this._getLocalMessageMaxSequence(D);M+=`lastMessageSequence:${W}`,yield this._setGroupMessageRead(E,W)}}catch(W){const{errorCode:oA,errorInfo:EA}=W;throw new P({functionName:"setMessageRead",code:oA,message:EA,moreMessage:M})}return D.type===I.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 I=`scope:${s.scope}`;s.scope||(s.scope=n);const{scope:E}=s,m=this._generateSetAllMessageReadRequestData(E);if(m.allC2CMessageReadStatus===$r&&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 Co.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(),I+=`failureGroupInfoList:${g(P)}`}return{code:0,successLog:{message:I}}}catch(D){const{errorCode:M}=D;throw new this._core.helper.ChatError({functionName:"setAllMessageRead",code:M,moreMessage:I})}})}_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:I}=this._core,E=I.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:I},appStore:E}=this._core,m={allC2CMessageReadStatus:$r,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===$r){if(m.allC2CMessageReadStatus=H,s===I)break}else if(T===g){const W=this._getLocalMessageMaxSequence(M),{groupID:oA}=M.groupProfile;m.groupMessageReadInfoList.push({GroupId:oA,MsgSeq:W})}}}return m}_parseGroupReadInfo(s){const{utils:{isUndefined:n}}=this._core,g=[];return s?.forEach(I=>{const{GroupId:E,MsgSeq:m,RetCode:D,LastReadMsgSeq:M}=I;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:I,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:I(),MsgSeq:P.__sequence,MsgRandom:P.__random,GroupId:P.groupID}));yield function(P,W){return pA(this,void 0,void 0,function*(){const{messageListToDelete:oA}=P,EA={DelMsgList:oA};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(I){console.error(`${this._name}._deleteGroupAtTips fail:`,I)}})}_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,I=this._core.message.messageDataHandler.getLocalMessageList(g),E=Math.max(...I.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,I=this._core.message.messageDataHandler.getLocalMessageList(g),E=Math.max(...I.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,I){return pA(this,void 0,void 0,function*(){return I.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,I){return pA(this,void 0,void 0,function*(){const{groupID:E,lastMessageSequence:m}=g,D={GroupId:E,MsgReadedSeq:m};return I.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:I,READ_ALL_C2C_MSG:E,READ_ALL_GROUP_MSG:m}}=this._core,{type:D,scope:M,unreadCount:T}=s;return!(T<=0)&&(!(D!==n||![I,E].includes(M))||!(D!==g||![I,m].includes(M)))}},ne=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:I}=this._core;let E=!1;s.forEach(m=>{const{Type:D,Peer_Account:M,GroupId:T}=m;let P;D===1?P=NA.getLocalConversation(`${I.CONV_C2C}${M}`):D===2&&(P=NA.getLocalConversation(`${I.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:I}}=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(bs(E))return M&&(M.isPinned=m),NA.emitConversationListUpdate(!0),D;const T=`conversationID:${E} isPinned:${m}`;try{let P=null;if(Ct(E)?P={Type:1,To_Account:E.replace(n.CONV_C2C,"")}:Ig(E)&&(P={Type:2,GroupId:E.replace(n.CONV_GROUP,"")}),yield function(oA,EA){return pA(this,void 0,void 0,function*(){const{fromAccount:wA,operationType:kA,itemList:YA}=oA,LA={From_Account:wA,OperationType:kA,RecentContactItem:YA};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 oA=new Et({conversationID:E,type:Ct(E)?n.CONV_C2C:n.CONV_GROUP,isPinned:m});NA.setLocalConversation(E,oA)}NA.emitConversationListUpdate(!0)}return Object.assign(Object.assign({},D),{successLog:{message:T}})}catch(P){const{errorCode:W,errorInfo:oA}=P;throw new I({functionName:"pinConversation",code:W,message:oA,moreMessage:T})}})}},Le=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,I=[];s.forEach(E=>{const{Type:m,Peer_Account:D,GroupId:M}=E;m===1&&I.push(`${g.CONV_C2C}${D}`),m===2&&I.push(`${g.CONV_GROUP}${M}`)}),console.log(`${this._name}.handleConversationDeleted conversationIDList:${I}`),this._deleteLocalConversationList(I)}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:aa.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:I=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:ha.CONV_NOT_FOUND});return{code:0,data:I===aa.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 I;if(!NA.hasLocalConversation(g))return!1;const E=(I=NA.getLocalConversation(g))===null||I===void 0?void 0:I.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:I}=this._core,E={fromAccount:I.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,oA={From_Account:T,ContactItem:P,ClearRamble:W};return M.common.buildAndSendPacket({servcmd:"recentcontact.batch_delete",data:oA})})}(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,I=s.replace(n,"");return!!g.getGroup(I)}_deleteConversationLocalMessage(s){console.log(`${this._name}._deleteConversationLocalMessage conversationID:${s}`),this._core.message.messageDataHandler.deleteConversationMessageList(s),this._core.message.messageHistory.completedHistoryConversations.delete(s)}},yt=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:ha.CONV_NOT_FOUND});const I=NA.getLocalConversation(n);return I?.setDraftText(g),NA.emitConversationListUpdate(),{code:0,data:{conversation:I}}})}},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:oA}=Co.core.OuterConstant;return{[P]:0,[W]:1,[oA]:2}}()[n],I=yield function(P,W){return pA(this,void 0,void 0,function*(){const{userIDList:oA,receiveMessageOption:EA}=P,wA={Peer_Account:oA,Mute_Notifications:EA};return W.common.buildAndSendPacket({servcmd:"openim.set_c2c_peer_mute_notifications",data:wA})})}({userIDList:s,receiveMessageOption:g},this._core),{ErrorList:E=[]}=I||{},m=[];E.forEach(P=>{const{Peer_Account:W,ErrorCode:oA}=P;m.push({userID:W,code:oA});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:I},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),!I(s)){const m=`${E.CONV_GROUP}${s}`;NA.patchMessageRemindType([m],n)}return{code:0,data:{groupID:s,messageRemindType:n}}})}},Qt=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:I}=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);I.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:I,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(I))return M.debug(`${this._name}.${n} userIDList:${I} messageRemindType:${E}`),yield Kt.set(I,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:${I} messageRemindType:${E}`})}})}},hi=new class{init(s){s.ssoLog.debug("ConversationAction.init"),this._core=s,zA.init(s),ve.init(s),le.init(s),Te.init(s),ne.init(s),Le.init(s),yt.init(s),Qt.init(s);const{notificationCenter:n,InnerEvent:{MESSAGE_PUSH:g,DESTROY:I}}=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(I,this._dispose,this)}_onConversationModified(s){const{constants:{ConvModifyPushType:n}}=this._core,{RecentContactMod:g=[]}=s;g.forEach(I=>{const{PushType:E}=I;if(E===n.CONV_DELETED){const{RecentContactList:m}=I.RecentContactDeleteItem;Le.handleConversationDeleted(m)}if(E===n.CONV_PINED){const{RecentContactList:m}=I.RecentContactTopItem;ne.handleConversationPinned(m,!0)}if(E===n.CONV_UNPINED){const{RecentContactList:m}=I.RecentContactTopItem;ne.handleConversationPinned(m,!1)}})}_onC2CMessageReadSync(s){const{C2cNotifyMsgArray:n=[]}=s;Te.handleC2CMessageReadSync(n)}_onC2CMessageRemindTypeSync(s){const{C2cNotifyMsgArray:n=[]}=s;Qt.handleC2CMessageRemindTypeSync(n)}_onGroupMessageReadSync(s){const{GroupTips:n=[]}=s;Te.handleGroupMessageReadSync(n)}_dispose(){const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:n,DESTROY:g}}=this._core,{InnerEventSubType:{CONV_MODIFIED:I,C2C_MESSAGE_READ_SYNC:E,GROUP_MESSAGE_READ_SYNC:m,C2C_REMIND_TYPE_SYNC:D}}=s;s.unSubscribeInnerEvent(n,I,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:I=!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}=Co.core,{startTime:P,endTime:W,isRepeated:oA,messageRemindType:EA}=M,wA={StartTime:P,EndTime:W,IsRepeated:oA,Level:EA};return T.buildAndSendPacket({servcmd:"im_msg_db_logic.ws_set_do_not_disturb",data:wA})})}({messageRemindType:this._getType(g),startTime:E,endTime:m,isRepeated:I?es.ON:es.OFF});return{code:0,data:{errorCode:D.ErrorCode,errorInfo:D.ErrorInfo}}}catch(n){ic("setAllReceiveMessageOpt",n)}})}_calcStartAndEndTime(s){const{startHour:n=0,startMinute:g=0,startSecond:I=0,duration:E=0,isRepeated:m=!0}=s,D=new Date,M=new Date(D.getFullYear(),D.getMonth(),D.getDate(),n,g,I),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]}},ls=new class{init(s){this._core=s;const{helper:n,notificationCenter:g,InnerEvent:I}=s;n.registerApi({apiName:"getAllReceiveMessageOpt",context:this}),g.subscribeInnerEvent(I.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:I}}=this._core;g.emitOuterEvent(I,{name:I,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}=Co.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){ic("getAllReceiveMessageOpt",s)}})}_handleResult(s){const{OuterConstant:n}=this._core,{MSG_REMIND_ACPT_AND_NOTE:g,MSG_REMIND_DISCARD:I,MSG_REMIND_ACPT_NOT_NOTE:E}=n,m={0:g,1:I,2:E},{Level:D,StartTime:M,EndTime:T,IsRepeated:P}=s;return{messageRemindType:m[D]||g,startTime:M,endTime:T,isRepeated:P===es.ON}}},Lo=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),ls.init(s)}};const ei=s=>!Ct(s)&&!Ig(s)&&!bs(s),kr={getConversationProfile:[{key:"conversationID",required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!ei(s)||"conversationID is invalid."}],setMessageRead:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!ei(s)||"conversationID is invalid."}},pinConversation:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!ei(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:I}}}=Co;if(!I(s)&&!g(s))return"options is String or Object.";if(I(s)&&ei(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(ei(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=>!(!Ct(s)&&!Ig(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){Co.init(s),hi.init(s),Lo.init(s),NA.init(s),s.helper.registerValidateConfig({auth:zo,params:kr})}};const Wn=new class{init(s){this.core=s}},Aa="AVChatRoom",Vr="AV_HISTORY_MSG",oc="GRP_COUNTER",Uu="Set",lm="Increase",Ri="Decrease",ti=0,fo=1,tn=2,ts=["Type","Name","Introduction","Notification","FaceUrl","Owner_Account","CreateTime","InfoSeq","LastInfoTime","LastMsgTime","MemberNum","MaxMemberNum","ApplyJoinOption","NextMsgSeq","ShutUpAllMember","InviteJoinOption","LastRecallTime"],ug=["Type","Name","Introduction","Notification","FaceUrl","CreateTime","Owner_Account","LastInfoTime","LastMsgTime","NextMsgSeq","MemberNum","MaxMemberNum","ApplyJoinOption","InviteJoinOption"],Ll=["Role","JoinTime","MsgFlag","MsgSeq"],ld=["Role","JoinTime","MsgSeq","MsgFlag","NameCard"],kc=0,Sr=1,QI="notStart",ZI="resolved",Fg="rejected",XI=10018,pI=11e3,Lc=2,Fu=["Owner","Admin","Member"],Im=["Role","JoinTime","NameCard","ShutUpUntil","OnlineStatus"],um=0,Em=1,dm=2,Hy=4,qy=1,Cv=2,Ky=3,jy=4,hv=5,Y_=1,Id=0,V_=4,Wy=6,J_=400,zy=300,H_={from:!0,groupID:!0,groupName:!0,to:!0},Bv={from:!0,groupID:!0,groupName:!0,to:!0,type:!0},q_=2,Qv=4,K_=5,j_=7,Zy=8,Xy=15,mQ=20,Cm=21,hm=2600,ud=2602,W_=2603,z_=2620,Bm=2621,$y=2623,eh=2660,Z_=2661,X_=2681,Qm=2683,pv=2684,AD=2685,pm=2687,mv=3122,$_=10018,AT={0:"DisableInvite",1:"NeedPermission",2:"FreeAccess"},fv=s=>s===Wn.core.OuterConstant.GRP_PUBLIC,Ed=s=>s===Wn.core.OuterConstant.GRP_AVCHATROOM,mm=(s,n)=>{const{isArray:g}=Wn.core.utils;if(!g(s)||!g(n))return!1;let I=!1;return n.forEach(({key:E,value:m})=>{const D=s.find(M=>M.key===E);D?D.value!==m&&(D.value=m,I=!0):(s.push({key:E,value:m}),I=!0)}),I},dd=s=>{const n=[];if(!s)return n;for(let g=0,I=s.length;g{const n=[];for(let g=0,I=s.length;g0&&M.members.forEach(T=>{T.userID===this.selfInfo.userID&&D(this.selfInfo,T,["sequence"])})}updateSelfInfo(n){const{nameCard:g,joinTime:I,role:E,messageRemindType:m,readedSequence:D,excludedUnreadSequenceList:M}=n,{common:{deepMerge:T}}=Wn.core;T(this.selfInfo,{nameCard:g,joinTime:I,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 Ou(E)),this._clearGroupLocalMessage(g))});const I=n();for(const[,E]of this._groupMap)E.selfInfo.userID=I,E.selfInfo.role==="Owner"&&(E.ownerID=I)}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:I}=g;return I!==s&&I!==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,I=`${g}${s}`,E=n.getConversation(I);if(E){const m=this.getLocalGroup(s);E.setProfileCompleted(),n.updateConversation(I,{groupProfile:m})}}reset(){this.clearLocalGroup()}_clearGroupLocalMessage(s){const{message:{messageHistory:n,messageDataHandler:g},OuterConstant:{CONV_GROUP:I},ssoLog:E}=this._core;E.debug("_clearGroupLocalMessage",`groupID:${s}`);const m=`${I}${s}`;n.completedHistoryConversations.delete(m),g.deleteConversationMessageList(m)}};function ym(s,n){return pA(this,void 0,void 0,function*(){const{type:g,limit:I,offset:E,supportTopic:m=0,memberAccount:D,responseFilter:M}=s,T={Type:g,Limit:I,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=QI,this.PAGING_GRP_COUNT_LIMIT=200}init(s){this._core=s;const{helper:n,constants:{WORKFLOW_NAME:g,WORKFLOW_STEP:I}}=s;n.registerApi({apiName:"getGroupList",context:this}),n.registerWorkflowStep(g.SYNC_SERVER_INFO_AFTER_LOGIN,I.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===Fg||this._pagingStatus===QI)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===QI&&Yi.clearLocalGroup();const s=this.PAGING_GRP_COUNT_LIMIT,n=[];try{yield this._pagingGetGroupList({limit:s,offset:0,groupList:n}),this._pagingStatus=ZI,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=Fg,g}})}_pagingGetGroupList(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n}=this._core,{isCommunityRelay:g=!1,groupList:I}=s;let E,{limit:m,offset:D}=s;const M=[...ts];g&&(E=this._core.OuterConstant.GRP_COMMUNITY,M.push("AtInfoList"));try{const T=yield ym({type:E,limit:m,offset:D,memberAccount:this._core.store.get("login").userId,responseFilter:{GroupBaseInfoFilter:M,SelfInfoFilter:[...Ll]}},this._core),{GroupIdList:P=[],TotalCount:W=0}=T||{},oA=this._convertGroupKey(P);I.push(...oA);const EA=D+m,wA=!(W>EA),kA=`offset:${D} limit:${m} total:${W} isCompleted:${wA} current:${I.length} isCommunityRelay:${g}`;return n.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList ok. ${kA}`),g?wA?I:(D=EA,this._pagingGetGroupList({isCommunityRelay:!0,limit:m,offset:D,groupList:I})):wA?(n.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList start to get community list`),D=0,this._pagingGetGroupList({isCommunityRelay:!0,limit:m,offset:D,groupList:I})):(D=EA,this._pagingGetGroupList({limit:m,offset:D,groupList:I}))}catch(T){if(T.ErrorCode===XI)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:I});if(g)return T.code===pI&&n.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList ok. community unavailable`),I;throw T}})}_pagingGetJoinedCommunityList(s){return pA(this,void 0,void 0,function*(){const{common:{getCurrentUserID:n},OuterConstant:g,ssoLog:I}=this._core,{groupList:E}=s;let{limit:m,offset:D}=s;try{const M=yield ym({limit:m,offset:D,type:g.GRP_COMMUNITY,memberAccount:n(),supportTopic:1,responseFilter:{GroupBaseInfoFilter:[...ts],SelfInfoFilter:[...Ll]}},this._core),{GroupIdList:T=[],TotalCount:P=0}=M||{},W=this._convertGroupKey(T);E.push(...W);const oA=D+m,EA=!(P>oA),wA=`offset:${D} limit:${m} total:${P} isCompleted:${EA} current:${E.length}`;return I.debug("_pagingGetJoinedCommunityList",`${this._name}._pagingGetJoinedCommunityList ok. ${wA}`),EA?E:(D=oA,this._pagingGetJoinedCommunityList({limit:m,offset:D,groupList:E}))}catch(M){if(M.code===$_)return I.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 I=0,E=s.length;I{const{AtFlagList:E,AtMsgSeq:m,From_Account:D}=I;g.push({groupID:s,groupAtType:E,sequence:m,from:D})}),g}},Pu=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:I},common:{getCurrentUserID:E},OuterConstant:{GRP_AVCHATROOM:m}}=this._core,D=yield function(oA,EA){return pA(this,void 0,void 0,function*(){const{name:wA,type:kA,groupID:YA,introduction:LA,notification:SA,avatar:OA,maxMemberNum:HA,joinOption:se,inviteOption:oe,memberList:_i,groupCustomField:Ti,isSupportTopic:bt}=oA;let Ni,gs;_i&&(Ni=_i.map(Bt=>{const{userID:UA,memberCustomField:ii}=Bt;return{Member_Account:UA,AppMemberDefinedData:ii?TE(ii):void 0}})),Ti&&(gs=TE(Ti));const De={Name:wA,Type:kA,GroupId:YA,Introduction:LA,Notification:SA,FaceUrl:OA,MaxMemberCount:HA,ApplyJoinOption:se,InviteJoinOption:oe,MemberList:Ni,AppDefinedData:gs,SupportTopic:bt,webPushFlag:1};return EA.common.buildAndSendPacket({servcmd:"group_open_http_svc.create_group",data:De})})}(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(I(s.memberList)||I(T)||(s.memberList=(n=s.memberList)===null||n===void 0?void 0:n.filter(oA=>T.includes(oA.userID))),s.type===m)return dn({group:new Ou(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(I){const{errorCode:E,errorInfo:m}=I;throw new g({functionName:"createGroup",code:E,message:m,moreMessage:` groupID:${s.groupID}`})}})}_preCheckParams(s){const{type:n,groupID:g}=s,{utils:{isEmpty:I,isUndefined:E},common:{isCommunity:m}}=this._core,D=!I(g);if(!(()=>{const{GRP_PUBLIC:M,GRP_WORK:T,GRP_MEETING:P,GRP_AVCHATROOM:W,GRP_COMMUNITY:oA}=Wn.core.OuterConstant;return[M,T,P,W,oA]})().includes(n))throw new this._core.helper.ChatError({code:hm});if(!m({type:n})){if(D&&m({groupID:g}))throw new this._core.helper.ChatError({code:ud});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:ud});s.isSupportTopic=this._canIUseTopic(s)?1:0}}_canIUseMemberList(s){return!Ed(s)}_canIUseJoinOption(s){return fv(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:I,GRP_COMMUNITY:E}}=this._core;return n===I||n===E&&g===1}_sendCustomMessage(s,n){var g,I,E,m,D,M;const{OuterConstant:T,common:{t:P}}=this._core;let W=P("CREATE_GROUP"),oA=kc;n===T.GRP_COMMUNITY&&(W=P("CREATE_COMMUNITY"),oA=Sr);const EA={to:s,conversationType:"GROUP",payload:{data:JSON.stringify({businessID:"group_create",content:W,cmd:oA,opUser:this._core.store.get("login").userId,version:4})}},wA=(E=(I=(g=this._core)===null||g===void 0?void 0:g.message)===null||I===void 0?void 0:I.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(wA,{})}},Ws=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:I}}=this._core;return!I(n)&&!g(n.groupAttributeOption)}handleGroupAttributesUpdated(s){const{groupID:n,groupAttributeOption:g}=s,{serverMainSequence:I,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:I,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:I,operation:E}=s;if(this.hasGroupAttributesCache(n)){const m=this.getGroupAttributesCache(n),{localMainSequence:D}=m;E!==hv&&g-D!==1||(m.serverMainSequence=g,m.localMainSequence=g,m.lastUpdateTime=Date.now(),this._updateGroupAttributesCacheValues({groupAttributes:m,groupAttributeList:I,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:I}=s;I!==Ky?I!==jy?(I===qy&&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:I=[]}=s,E={};if(this.hasGroupAttributesCache(g)){const{values:m}=this.getGroupAttributesCache(g);if(I.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 I.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:I,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||([I,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=[],I=[];return Object.keys(s).forEach(E=>{s[E]!==this._groupAttributesCacheValuesCopy[E]&&g.push(E)}),Object.keys(this._groupAttributesCacheValuesCopy).forEach(E=>{n(s[E])&&I.push(E)}),this._groupAttributesCacheValuesCopy={},{updatedKeyList:g,deletedKeyList:I}}_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={}}},ih=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(Aa)})}dismissGroup(s){return pA(this,void 0,void 0,function*(){const{helper:{ChatError:n}}=this._core;try{yield function(I,E){return pA(this,void 0,void 0,function*(){const m={GroupId:I};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(),Ws.deleteGroupAttributesCache(s),dn({groupID:s,type:g},{message:s})}catch(g){const{errorCode:I,errorInfo:E}=g;throw new n({functionName:"dismissGroup",code:I,message:E})}})}},Ul=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,I={groupIDList:[n],responseFilter:{GroupBaseInfoFilter:[...ts],AppDefinedDataFilter_Group:g,MemberInfoFilter:[...ld]}},{helper:{ChatError:E}}=this._core;try{const m=yield this.getGroupProfileAdvance(I),{successGroupList:D,failureGroupList:M}=m;if(M.length>0)throw M[0];let T;return!Yi.hasLocalGroup(n)&&Ed(D[0].type)?T=new Ou(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,I=n.filter(T=>!g({groupID:T})),E=n.filter(T=>g({groupID:T}));I.length>50&&(I.length=50),E.length>50&&(E.length=50);const m=yield Promise.all([this._getGroupProfileAdvance(Object.assign(Object.assign({},s),{groupIDList:I})),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:I=!1}=s,E=yo(s,["isCommunityProfile"]);if(E.groupIDList.length===0)return{successGroupList:[],failureGroupList:[]};try{const m=yield function(W,oA){return pA(this,void 0,void 0,function*(){const{groupIDList:EA,responseFilter:wA}=W,kA={GroupIdList:EA,ResponseFilter:wA};return oA.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(I)return{successGroupList:[],failureGroupList:[]};throw m}})}_convertGroupProfileKey(s){const n=[];for(let g=0,I=s.length;g0&&I{const{Key:T,Value:P=0}=M;E.set(T,P)}),this._groupCountersMap.set(n,{lastUpdateTime:Date.now(),groupCounterSeq:I,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:I}=this.getLocalGroupCounters(s);if(n.length>0)n.forEach(E=>{I.has(E)&&(g[E]=I.get(E))});else for(const E of I.keys())g[E]=I.get(E);return g}deleteLocalGroupCounters(s){const{groupID:n,counterList:g=[],groupCounterSeq:I}=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:I,counters:E,avChatRoomKey:m})}}setGroupCounters(s,n){if(!this._hasLocalGroupCounters(s))return;const g=this.getLocalGroupCounters(s),{counters:I}=g;let E=!1;Object.entries(n).forEach(([m,D])=>{I.has(m)&&I.get(m)!==D&&(I.set(m,D),E=!0)}),E&&this._groupCountersMap.set(s,Object.assign(Object.assign({},g),{lastUpdateTime:Date.now(),counters:I}))}_hasLocalGroupCounters(s){return this._groupCountersMap.has(s)}reset(){this._groupCountersMap.clear()}},NE=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(Aa)})}joinGroup(s){return pA(this,void 0,void 0,function*(){const{groupID:n}=s,{helper:{ChatError:g},OuterConstant:I,ssoLog:E}=this._core;try{if(Yi.hasLocalGroup(n))try{return yield Ul.getGroupProfile({groupID:n}),dn({status:I.JOIN_STATUS_ALREADY_IN_GROUP,group:Yi.getLocalGroup(n)},{message:`groupID:${n} joinedStatus:${I.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:I}=this._core,{groupID:E}=s,m=Object.assign({},s),D=g.checkBusinessCapabilityBits(Vr);D&&(m.historyMessageFlag=1);const M=yield function(SA,OA){return pA(this,void 0,void 0,function*(){const{groupID:HA,applyMessage:se,historyMessageFlag:oe}=SA,_i={GroupId:HA,ApplyMsg:se,HugeGroupHistoryMsgFlag:oe};return OA.common.buildAndSendPacket({servcmd:"group_open_http_svc.apply_join_group",data:_i})})}(m,this._core),{Type:T,JoinedStatus:P,LongPollingKey:W,StartSeq:oA,HugeGroupFlag:EA,AVChatRoomKey:wA,RspMsgList:kA=[]}=M||{},YA=`groupID:${E} joinedStatus:${P} longPollingKey:${W} startSeq:${oA} avChatRoomFlag:${EA} canGetAVChatRoomHistoryMsg:${D}, historyMessageCount:${kA.length}`;I.debug("_applyJoinGroup",`${this._name}._applyJoinGroup ok, ${YA}`);let LA=new Ou({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 Ul.getGroupProfile({groupID:E})).data.group}catch(SA){I.warn("_applyJoinGroup",`${this._name}._applyJoinGroup getGroupProfile failed, groupID: ${E}, errorCode:${SA?.code}`)}return this._handleJoinResult({group:LA,avChatRoomFlag:EA,longPollingKey:W,startSequence:oA,avChatRoomKey:wA,historyMessageList:kA})}throw new this._core.helper.ChatError({code:eh})})}_handleJoinResult(s){const{group:n,avChatRoomFlag:g,avChatRoomKey:I}=s;return g===1?(Ws.initGroupAttributesCache({groupID:n.groupID,avChatRoomKey:I}),sc.initGroupCountersCache({groupID:n.groupID,avChatRoomKey:I}),dn(s)):(Yi.updateLocalGroup([n]),Yi.emitGroupListUpdate(),dn({status:this._core.OuterConstant.JOIN_STATUS_SUCCESS,group:n},{message:`groupID:${n.groupID}`}))}},fQ=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(Aa)})}quitGroup(s){return pA(this,void 0,void 0,function*(){if(!Yi.hasLocalGroup(s))throw new this._core.helper.ChatError({code:$y});const{helper:{ChatError:n}}=this._core;try{yield function(I,E){return pA(this,void 0,void 0,function*(){const m={GroupId:I};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(),Ws.deleteGroupAttributesCache(s),dn({groupID:s,type:g},{message:`groupID:${s}`})}catch(g){const{errorCode:I,errorInfo:E}=g;throw new n({functionName:"quitGroup",code:I,message:E,moreMessage:`groupID:${s}`})}})}},AB=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,HA){return pA(this,void 0,void 0,function*(){const se={GroupIdList:[OA],GroupBasePublicInfoFilter:[...ug]};return HA.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_public_info",data:se})})}(s,this._core),{GroupInfo:g=[]}=n||{},{AppDefinedData:I=[],ApplyJoinOption:E,CreateTime:m,FaceUrl:D,Introduction:M,InviteJoinOption:T,MaxMemberNum:P,MemberNum:W,Name:oA,Owner_Account:EA,Type:wA,ErrorCode:kA,ErrorInfo:YA}=g[0];if(kA!==0)throw new this._core.helper.ChatError({code:kA,message:YA});const LA=dd(I),SA=new Ou({groupID:s,name:oA,avatar:D,introduction:M,joinOption:E,inviteOption:T,maxMemberCount:P,memberCount:W,type:wA,ownerID:EA,createTime:m,groupCustomField:LA});return dn({group:SA})}catch(n){const{errorCode:g,errorInfo:I}=n;throw new this._core.helper.ChatError({functionName:"searchGroupByID",code:g,message:I})}})}},eT=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:I},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:oA,introduction:EA,notification:wA,muteAllMembers:kA,joinOption:YA,inviteOption:LA,groupCustomField:SA}=M,OA={GroupId:P,Name:W,FaceUrl:oA,Introduction:EA,Notification:wA,ShutUpAllMember:kA,ApplyJoinOption:YA,InviteJoinOption:LA,AppDefinedData:SA?TE(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 Ou(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:${I(s)}`})}})}_canIUseJoinOption(s){return fv(s)||this._core.common.isCommunity({type:s})}},tT=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:I}=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:z_});if(I===M())throw new m.ChatError({functionName:n,code:Bm});try{return yield function(T,P){return pA(this,void 0,void 0,function*(){const{groupID:W,newOwnerID:oA}=T,EA={GroupId:W,NewOwner_Account:oA};return P.common.buildAndSendPacket({servcmd:"group_open_http_svc.change_group_owner",data:EA})})}(s,this._core),E.ownerID=I,Yi.emitGroupListUpdate(),dn({group:E})}catch(T){throw new m.ChatError({functionName:n,code:T?.errorCode,message:T?.errorInfo})}})}},yQ=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(Aa)})}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 I=this._onlineMemberCountMap.get(s),{lastReqTime:E=0,memberCount:m=0}=I||{};if(g-E<=6e4)return dn({memberCount:m})}try{const I=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}=I||{};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(I){throw new this._core.helper.ChatError({functionName:n,code:I?.errorCode,message:I?.errorInfo})}})}},DQ=new class{init(s,n){s.ssoLog.debug("GroupAction.init"),yv.init(s),Pu.init(s),ih.init(s,n),NE.init(s,n),fQ.init(s,n),AB.init(s),Ul.init(s),eT.init(s),tT.init(s),yQ.init(s,n)}dismissGroup(s){return ih.dismissGroup(s)}joinGroup(s){return NE.joinGroup(s)}quitGroup(s){return fQ.quitGroup(s)}getGroupOnlineMemberCount(s){return yQ.getGroupOnlineMemberCount(s)}},Dv=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:I=20}=s||{},{common:E}=this._core;let m;try{m=yield function(P,W){return pA(this,void 0,void 0,function*(){const{type:oA,startTime:EA,limit:wA,handleAccount:kA}=P,YA={Type:oA,StartTime:EA,Limit:wA,Handle_Account:kA};return W.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_pendency",data:YA})})}({type:n,startTime:g,limit:I,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 I=this._convertApplicationData(g),{handled:E}=I,m=yo(I,["handled"]);E===0&&n.push(m)}),n}_convertApplicationData(s){const{Handled:n,AddTime:g,ApplyInviteMsg:I,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:I,addTime:g}}},Sv=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===Lc?yield function(E,m){return pA(this,void 0,void 0,function*(){const{groupID:D,handleAction:M,handleMessage:T,applicant:P,authentication:W,invitee:oA}=E,EA={GroupId:D,HandleMsg:M,ApprovalMsg:T,Applicant_Account:P,Authentication:W,Invited_Account:oA};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:oA}=E,EA={GroupId:D,HandleMsg:M,ApprovalMsg:T,Applicant_Account:P,Authentication:W,MsgKey:oA};return m.common.buildAndSendPacket({servcmd:"group_open_http_svc.handle_apply_join_group",data:EA})})}(g,this._core);const I=Yi.getLocalGroup(g.groupID);return dn({group:I})}catch(I){throw new this._core.helper.ChatError({functionName:"handleGroupApplication",code:I?.errorCode,message:I?.errorInfo})}})}_handleParams(s){var n;const{handleAction:g,handleMessage:I,message:E,application:m}=s;let D,M,T,P,W;if(E){const{payload:oA}=E||{};D=oA.operatorID,M=(n=oA.groupProfile)===null||n===void 0?void 0:n.groupID,T=oA.authentication,P=oA.messageKey}else D=m?.applicant||"",M=m?.groupID||"",T=m?.authentication||"",P=m?.messageKey||0;return m?.applicationType===Lc&&(W=m.userID),{handleAction:g,handleMessage:I,applicant:D,invitee:W,groupID:M,authentication:T,messageKey:P}}},eD=new class{init(s){s.ssoLog.debug("GroupApplication.init"),Dv.init(s),Sv.init(s)}};let uC=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 I=[null,void 0,"",0,NaN];s.memberCustomField&&mm(this.memberCustomField,s.memberCustomField),g(this,s,["memberCustomField","marks","onlineStatus","muteTime"],I)}};function eB(s,n){return pA(this,void 0,void 0,function*(){const{groupID:g,userID:I,muteTime:E,role:m,nameCard:D,memberCustomField:M}=s;let T;M&&(T=TE(M));const P={GroupId:g,Member_Account:I,ShutUpTime:E,Role:m,NameCard:D,AppMemberDefinedData:T};return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:P})})}var tD=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(Aa)})}getGroupMemberList(s){return pA(this,void 0,void 0,function*(){const n="getGroupMemberList",{groupID:g,offset:I=0,count:E=100,role:m="",filter:D=""}=s,M=Yi.getLocalGroup(g),T=E>100?100:E,P={groupID:g,offset:I,limit:T,memberRoleFilter:Fu.includes(m)?[m]:void 0,memberInfoFilter:Im};try{const W=yield function(oe,_i){return pA(this,void 0,void 0,function*(){const{isCommunity:Ti}=_i.common,{groupID:bt,offset:Ni,limit:gs,memberRoleFilter:De,memberInfoFilter:Bt}=oe,UA={GroupId:bt,Limit:gs,MemberRoleFilter:De,MemberInfoFilter:Bt};return Ti({groupID:bt})?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:oA,MemberNum:EA,Next:wA}=W||{},kA=`${this._name}.${n} ok, totalMemberCount:${EA} next:${wA}`,{utils:{isArray:YA,isEmpty:LA},common:{isCommunity:SA}}=this._core;if(M&&(M.memberCount=EA),!YA(oA)||oA.length===0)return dn({memberList:[],offset:0},{message:kA});let OA=I+T;SA({groupID:g})&&(OA=LA(wA)?0:wA),oA.lengthD.userID),I=yield(n=this._core.user.userProfile)===null||n===void 0?void 0:n.getUserProfile({userIDList:g}),E=I?.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,I=s.length;g50&&(T.warn("getGroupMemberProfile",`${this._name}.${n} userIDList length:${I.length} exceeds limit 50`),I.splice(50));const P=`userIDList length:${I.length} groupID:${g}`;try{const W=yield function(kA,YA){return pA(this,void 0,void 0,function*(){const{groupID:LA,userIDList:SA,memberInfoFilter:OA,memberCustomFieldFilter:HA}=kA,se={GroupId:LA,Member_List_Account:SA,MemberInfoFilter:OA,AppDefinedDataFilter_GroupMember:HA};return YA.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_specified_group_member_info",data:se})})}({groupID:g,userIDList:I,memberCustomFieldFilter:E,memberInfoFilter:[...Im]},this._core),{MemberList:oA}=W||{};if(!M(oA)||oA.length===0)return dn({memberList:[]});let EA=this._convertMemberInfo(oA);EA=yield this._getMemberAvatarAndNick(EA);const wA=this._generateGroupMember(EA);return dn({memberList:wA},{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,I=s.length;gD.userID),I=yield(n=this._core.user.userProfile)===null||n===void 0?void 0:n.getUserProfile({userIDList:g}),E=I?.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,I=s.length;g({Member_Account:M}));try{const M=yield function(wA,kA){return pA(this,void 0,void 0,function*(){const{groupID:YA,userIDList:LA}=wA,SA={GroupId:YA,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:oA,overLimitUserIDList:EA}=this._handleResult(T);return dn({failureUserIDList:P,successUserIDList:W,existedUserIDList:oA,overLimitUserIDList:EA,group:E},{message:` groupID:${g} successUserIDList:${W} failureUserIDList:${P} existedUserIDList:${oA} overLimitUserIDList:${EA}`})}catch(M){throw new m.ChatError({functionName:n,code:M?.errorCode,message:M?.errorInfo})}})}_handleResult(s){const n=[],g=[],I=[],E=[];return s.forEach(m=>{const{Result:D,Member_Account:M}=m;D===um?n.push(M):D===Em?g.push(M):D===dm?I.push(M):D===Hy&&E.push(M)}),{failureUserIDList:n,successUserIDList:g,existedUserIDList:I,overLimitUserIDList:E}}},hd=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(Aa)})}deleteGroupMember(s){return pA(this,void 0,void 0,function*(){const n="deleteGroupMember",{groupID:g,userIDList:I}=s,E=Yi.getLocalGroup(g),{helper:m,utils:{isUndefined:D},ssoLog:M}=this._core;if(D(E))throw new m.ChatError({functionName:n,code:W_});I.length>20&&(M.warn("deleteGroupMember",`${this._name}.${n} userIDList length:${I.length} exceeds limit 20`),I.splice(20));try{return yield function(T,P){return pA(this,void 0,void 0,function*(){const{groupID:W,userIDList:oA,reason:EA}=T,wA={GroupId:W,MemberToDel_Account:oA,Reason:EA};return P.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_member",data:wA})})}({groupID:g,userIDList:I},this._core),dn({group:E,userIDList:I},{message:`groupID:${g} userIDList length:${I.length}`})}catch(T){throw new m.ChatError({functionName:n,code:T?.errorCode,message:T?.errorInfo})}})}},Mv=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:I,muteTime:E}=s,m=` groupID:${g} userID:${I} muteTime:${E}`;this._preCheckSettingMuteParams(s);try{yield eB(s,this._core);const D=Yi.getLocalGroup(g),M=new uC({userID:I,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:I}=this._core;if(n===g.get("login").userId)throw new I.ChatError({functionName:"setGroupMemberMuteTime",code:AD})}},MQ=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:I,userID:E,role:m}=s,D=`${this._name}.${n} ok, groupID:${I} userID:${E} role:${m}`;this._preCheckSettingRoleParams(s);try{yield eB(s,this._core);const M=Yi.getLocalGroup(I),T=new uC({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:I,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:X_});if(I===m.get("login").userId)throw new D.ChatError({functionName:"setGroupMemberRole",code:pv});const W=[...Fu];if(T({groupID:g})&&W.push(M.GRP_MBR_ROLE_CUSTOM),!W.includes(E))throw new D.ChatError({functionName:"setGroupMemberRole",code:Qm})}},iD=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:I,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 eB({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 oA=new uC({userID:D,nameCard:M});return dn({group:W,member:oA},{message:T})}catch(P){throw new I.ChatError({functionName:g,code:P?.errorCode,message:P?.errorInfo,moreMessage:T})}})}_preCheckSettingNameCardParams(s){const{groupID:n}=s,{helper:g}=this._core,I=Yi.getLocalGroup(n);if(Ed(I?.type))throw new g.ChatError({functionName:"setGroupMemberNameCard",code:pm})}},Dm=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:I}}=this._core;this._preCheckSettingCustomFiledParams(s);const{groupID:E,userID:m=I(),memberCustomField:D}=s,M=`${this._name}.${n} ok, groupID:${E}userID:${m} memberCustomField:${JSON.stringify(D)}`;try{yield eB({groupID:E,userID:m,memberCustomField:D},this._core);const P=Yi.getLocalGroup(E),W=new uC({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,I=Yi.getLocalGroup(n);if(Ed(I?.type))throw new g.ChatError({functionName:"setGroupMemberCustomField",code:pm})}},vv=new class{init(s,n){s.ssoLog.debug("GroupMember.init"),tD.init(s,n),SQ.init(s),Cd.init(s),hd.init(s,n),Mv.init(s),MQ.init(s),iD.init(s),Dm.init(s)}getGroupMemberList(s){return tD.getGroupMemberList(s)}deleteGroupMember(s){return hd.deleteGroupMember(s)}},iT=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{fm(n,oc);const{groupID:g,keyList:I=[]}=s,{avChatRoomKey:E,lastUpdateTime:m}=sc.getLocalGroupCounters(g);if(!(Date.now()-m>=this._getExpireTime()))return{code:0,data:{counters:sc.getLocalCounters(g,I)}};const D=yield function(P){return pA(this,void 0,void 0,function*(){const{groupID:W,GroupCounterKeys:oA,avChatRoomKey:EA}=P,{common:wA}=Wn.core,kA={GroupId:W,keyList:oA,BytesKey:EA};return wA.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_counter",data:kA})})}({groupID:g,keyList:I,avChatRoomKey:E}),{GroupCounter:M=[],GroupCounterSeq:T}=D;return sc.updateLocalGroupCounters({groupID:g,counterList:M,groupCounterSeq:T}),{code:0,data:{counters:sc.getLocalCounters(g,I)}}}catch(g){IC(n,g)}})}_getExpireTime(){const{store:s,utils:{isUndefined:n}}=this._core,g=s.get("cloudConfig")||{},{grp_counter_expire_time:I}=g;return n(I)?3e4:Number(I)}},Sm=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(Uu,s)})}increaseGroupCounter(s){return pA(this,void 0,void 0,function*(){return this._handleCounterOperation(lm,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{fm(g,oc);const{groupID:I,key:E,value:m=0}=n,{avChatRoomKey:D}=sc.getLocalGroupCounters(I),M=s===Uu?this._convertObjectToList(n.counters):[{Key:E,Value:m}],T=yield this._updateGroupCounters({groupID:I,counterList:M,avChatRoomKey:D,mode:s});return sc.setGroupCounters(I,T),{code:0,data:{counters:T}}}catch(I){IC(g,I)}})}_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,I={};return g.forEach(E=>{const{Key:m,Value:D=0}=E;I[m]=D}),I})}_convertObjectToList(s){return Object.entries(s).map(([n,g])=>({Key:n,Value:g||0}))}},tB=new class{init(s){this._core=s,iT.init(s),Sm.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(I=>{const{type:E,groupCounterSeq:m,counterList:D=[]}=I;E!==ti&&E!==tn||this._processAndNotifyCounterUpdate(n,m,D),E===fo&&sc.deleteLocalGroupCounters({groupID:n,groupCounterSeq:m,counterList:D})})}_processAndNotifyCounterUpdate(s,n,g){const{OuterEvent:I,notificationCenter:E}=this._core;sc.updateLocalGroupCounters({groupID:s,groupCounterSeq:n,counterList:g}),g.forEach(({Key:m,Value:D=0})=>{E.emitOuterEvent(I.GROUP_COUNTER_UPDATED,{name:I.GROUP_COUNTER_UPDATED,data:{groupID:s,key:m,value:D}})})}reset(){sc.reset()}},Mm=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:I,avChatRoomKey:E}=Ws.getGroupAttributesCache(n),m=Ws.convertKeyValueMapToList(g);try{const D=yield function(W,oA){return pA(this,void 0,void 0,function*(){const{groupID:EA,mainSequence:wA,groupAttributeList:kA,avChatRoomKey:YA}=W,LA={GroupId:EA,AttrMainSeq:wA,GroupAttr:kA,BytesKey:YA,AttrControl:["RaceConflict"]};return oA.common.buildAndSendPacket({servcmd:"group_open_http_svc.set_group_attr",data:LA})})}({groupID:n,avChatRoomKey:E,groupAttributeList:m,mainSequence:I},this._core),{AttrMainSeq:M,GroupAttr:T}=D||{},P=T.map(W=>{const{Key:oA,seq:EA}=W;return{key:oA,value:g[oA],sequence:EA}});return Ws.saveGroupAttributesCacheValuesCopy(n),Ws.refreshGroupAttributesCache({groupID:n,serverMainSequence:M,groupAttributeList:P,operation:qy}),Ws.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})}})}},oT=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:I}=s,{serverMainSequence:E,avChatRoomKey:m,values:D}=Ws.getGroupAttributesCache(n),M=Ws.convertKeyValueMapToList(g).map(T=>{var P;const{key:W,value:oA}=T;return{key:W,value:oA,seq:((P=D.get(T.key))===null||P===void 0?void 0:P.sequence)||0}});try{const T=yield function(EA,wA){return pA(this,void 0,void 0,function*(){const{groupID:kA,mainSequence:YA,groupAttributeList:LA,avChatRoomKey:SA,richStatusMode:OA}=EA,HA={GroupId:kA,AttrMainSeq:YA,GroupAttr:LA,BytesKey:SA,AttrControl:["RaceConflict"],AllowRoomEngineOpt:OA};return wA.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_attr",data:HA})})}({groupID:n,avChatRoomKey:m,groupAttributeList:M,mainSequence:E,richStatusMode:I},this._core),{AttrMainSeq:P,GroupAttr:W}=T||{},oA=W.map(EA=>{const{Key:wA,seq:kA}=EA;return{key:wA,value:g[wA],sequence:kA}});return Ws.saveGroupAttributesCacheValuesCopy(n),Ws.refreshGroupAttributesCache({groupID:n,serverMainSequence:P,groupAttributeList:oA,operation:Cv}),Ws.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})})}},oD=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:I=[],richStatusMode:E}=s;try{let m;m=I.length===0?yield this._clearGroupAttributes(g,{richStatusMode:E}):yield this._deleteGroupAttributes(g,{keyList:I,richStatusMode:E});const{resultList:D,serverMainSequence:M,operation:T,groupAttributeList:P}=m||{},W=`${this._name}.${n} ok. groupID:${g} operation: ${T}`;return Ws.saveGroupAttributesCacheValuesCopy(g),Ws.refreshGroupAttributesCache({groupID:g,serverMainSequence:M,groupAttributeList:P,operation:T}),Ws.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:I,values:E}=Ws.getGroupAttributesCache(s),{keyList:m,richStatusMode:D}=n,M=[],T=[];m.forEach(oA=>{if(E.has(oA)){const{sequence:EA=0}=E.get(oA)||{};T.push({key:oA,seq:EA}),M.push(oA)}});const P=yield function(oA,EA){return pA(this,void 0,void 0,function*(){const{groupID:wA,mainSequence:kA,groupAttributeList:YA,avChatRoomKey:LA,richStatusMode:SA}=oA,OA={GroupId:wA,AttrMainSeq:kA,GroupAttr:YA,BytesKey:LA,AttrControl:["RaceConflict"],AllowRoomEngineOpt:SA};return EA.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_attr",data:OA})})}({groupID:s,avChatRoomKey:I,groupAttributeList:T,mainSequence:g,richStatusMode:D},this._core),{AttrMainSeq:W}=P||{};return{resultList:M,serverMainSequence:W,groupAttributeList:T,operation:jy}})}_clearGroupAttributes(s,n){return pA(this,void 0,void 0,function*(){const{serverMainSequence:g,avChatRoomKey:I,values:E}=Ws.getGroupAttributesCache(s),{richStatusMode:m}=n||{},D=[...E.keys()],M=yield function(P,W){return pA(this,void 0,void 0,function*(){const{groupID:oA,mainSequence:EA,avChatRoomKey:wA,richStatusMode:kA}=P,YA={GroupId:oA,AttrMainSeq:EA,BytesKey:wA,AttrControl:["RaceConflict"],AllowRoomEngineOpt:kA};return W.common.buildAndSendPacket({servcmd:"group_open_http_svc.clear_group_attr",data:YA})})}({groupID:s,avChatRoomKey:I,mainSequence:g,richStatusMode:m},this._core),{AttrMainSeq:T}=M||{};return{resultList:D,serverMainSequence:T,operation:Ky}})}},sD=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:I,localMainSequence:E,serverMainSequence:m}=Ws.getGroupAttributesCache(n),{helper:{ChatError:D}}=this._core,M=`groupID:${n} localMainSequence:${E} serverMainSequence:${m} keyList:${s.keyList}`;if(Date.now()-I>=3e4||E{const{key:oA,value:EA,seq:wA}=W;return{key:oA,value:EA,sequence:wA}});return Ws.refreshGroupAttributesCache({groupID:I,serverMainSequence:M,groupAttributeList:P,operation:hv}),{serverGroupAttributeList:T}})}},vQ=new class{init(s){s.ssoLog.debug("GroupAttribute.init"),Mm.init(s),oT.init(s),oD.init(s),sD.init(s),Ws.init(s)}isGroupAttributesUpdated(s){return Ws.isGroupAttributesUpdated(s)}handleGroupAttributesUpdated(s){const{to:n,elements:{newGroupProfile:g}}=s,{groupAttributeOption:I}=g,{serverMainSequence:E,withChangedAttributeInfo:m}=I,{localMainSequence:D}=Ws.getGroupAttributesCache(n),M=E-D;if(console.log(`GroupAttribute.handleGroupAttributesUpdated groupID:${n} withChangedAttributeInfo:${m} diffSequence:${M}`),M!==0)if(Ws.saveGroupAttributesCacheValuesCopy(n),m!==1||M!==1){if(Ws.hasGroupAttributesCache(n)){const{avChatRoomKey:T}=Ws.getGroupAttributesCache(n);sD.getGroupAttributesFromServer({groupID:n,avChatRoomKey:T}).then(()=>{Ws.emitGroupAttributesUpdated(n)}).catch(()=>{})}}else Ws.handleGroupAttributesUpdated({groupID:n,groupAttributeOption:I})}reset(){Ws.reset()}};function GE(s,n="tips"){const{ClientSeq:g,From_Account:I,MsgClientTime:E,MsgPriority:m,MsgRandom:D,MsgSeq:M,MsgTimeStamp:T,TinyId:P,ToGroupId:W,GroupInfo:oA,MsgBody:EA}=s,wA=function(kA){const{GroupCode:YA,GroupId:LA,GroupName:SA,GroupType:OA,MsgFrom_AccountExtraInfo:HA,From_Account:se,To_Account:oe}=kA;return{groupCode:YA,groupID:LA,groupName:SA,type:OA,messageFromAccountExtraInformation:HA,from:se,to:oe}}(oA);return{clientSequence:g,from:I,clientTime:E,priority:m,random:D,sequence:M,time:T,tinyID:P,to:W,groupProfile:wA,elements:n==="tips"?xu(EA):oh(EA)}}function xu(s){const n={};return Object.keys(s).forEach(g=>{var I,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=(I=s[g])===null||I===void 0?void 0:I.map(m=>nD(m));break;case"MsgOperatorMemberExtraInfo":n.operatorInfo=nD(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:oA,OpType:EA,PushChangedAttrValFlag:wA,GroupAttrInfo:kA}=P,YA=kA.map(LA=>{const{Key:SA,Val:OA,SubKeySeq:HA}=LA;return{key:SA,value:OA,sequence:HA}});return{changedKeyList:W,groupAttributeList:YA,serverMainSequence:oA,operation:EA,withChangedAttributeInfo:wA}}(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=AT[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 nD(s){const{ImageUrl:n,NickName:g,Role:I,UserId:E}=s;return{avatar:n,nick:g,role:I,userID:E}}function oh(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=(I=s[g]||[])==null?void 0:I.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 I}),n}class vm{constructor(n){this.type=Wn.core.OuterConstant.MSG_GRP_TIP,this.content={},this._initContent(n)}static parseServerPushElement(n){const g=xu(n);return new vm(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 I=0;I{n.forEach(I=>{g.userID===I.userID&&Object.assign(g,I)})}):this.content.memberList=n}_initNewGroupProfile(n){this.content.newGroupProfile={};const g=Object.keys(n);for(let I=0;I0&&this._handleGroupTipMessage(g),{conversationUpdateFieldList:I,messageList:g}}_emitGroupTipsEvent(s){var n;const{constants:{WORKFLOW_STEP:g}}=this._core,{messageList:I=[]}=((n=s?.result)===null||n===void 0?void 0:n[g.HANDLE_GROUP_TIPS_NOTIFICATION])||{};if(I.length>0){const{notificationCenter:E,OuterEvent:m}=this._core;E.emitOuterEvent(m.MESSAGE_RECEIVED,{name:m.MESSAGE_RECEIVED,data:I})}}_handleGroupTips(s,n=!0){const{Event:g,GroupTips:I}=s,E=new Map,m=[],D=[];for(let M=0,T=I.length;M{const{operationType:I}=g.payload;switch(I){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:I,operatorInfo:E}=s.payload,{groupID:m}=I,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])?mm(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:I}=this._core,E=Yi.getLocalGroup(s),m=g.getCurrentUserID(),{ownerID:D}=n;m===D&&E.updateGroup({ownerID:D,selfInfo:{role:I.GRP_MBR_ROLE_OWNER}})}_updateSelfRole(s,n){const{OuterConstant:g}=this._core;let I=g.GRP_MBR_ROLE_MEMBER;n===J_?I=g.GRP_MBR_ROLE_OWNER:n===zy&&(I=g.GRP_MBR_ROLE_ADMIN),s.updateSelfInfo({role:I})}_handleGroupMemberCountUpdated(s){const{memberCount:n,groupProfile:{groupID:g}}=s.payload,I=Yi.getLocalGroup(g),{utils:{isNumber:E}}=this._core;I&&E(n)&&I.memberCount!==n&&(I.memberCount=n,Yi.emitGroupListUpdate(),Yi.updateConversationGroupProfile(g))}_handleGroupTipsRecover(s){const{utils:{isArray:n}}=this._core,{groupTipList:g}=s?.result||{};n(g)&&g.forEach(I=>{const{messageList:E}=this._handleGroupTips({Event:I.Event,GroupTips:[I]},!1);this._handleGroupTipMessage(E)})}_handleMemberGrantAdmin(s){const{OuterConstant:n}=this._core,{groupProfile:g,userIDList:I}=s.payload,E=this._core.common.getCurrentUserID(),{groupID:m}=g,D=Yi.getLocalGroup(m);D&&I.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:I}=s.payload,E=this._core.common.getCurrentUserID(),{groupID:m}=g,D=Yi.getLocalGroup(m);D&&I.includes(E)&&(D.updateSelfInfo({role:n.GRP_MBR_ROLE_MEMBER}),Yi.emitGroupListUpdate(),Yi.updateConversationGroupProfile(m))}};class RQ{constructor(n){this.type=Wn.core.OuterConstant.MSG_GRP_SYS_NOTICE,this.content={},this._initContent(n)}static parseServerPushElement(n){const g=oh(n);return new RQ(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 I=0;I0&&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 I={};for(let E=0;E0?[I]:[],messageList:g}}_assembleMessage(s){const{message:{messageFactory:n},OuterConstant:g,utils:{randomInt:I}}=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 RQ(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=I(),E.random=I(),E.generateMessageID()),E}_handleConversationOptions(s,n){const{OuterConstant:g}=this._core,I={conversationID:g.CONV_SYSTEM,unreadCount:0,type:g.CONV_SYSTEM,subType:s.conversationSubType,lastMessage:null};return n&&I.unreadCount++,I}_handleGroupSysTemMessage(s,n){s&&n.forEach(g=>{const{operationType:I}=g.payload;switch(I){case q_:this._handleGroupJoinResult(g);break;case Qv:this._handleMemberKicked(g);break;case K_:this._handleGroupDismissed(g);break;case j_:this._handleGroupInvitedResult(g);break;case Zy:this._handleGroupQuitResult(g);break;case mQ:this._handleMessageRemindTypeSynced(g);break;case Cm:this._handleAVChatRoomMemberBanned(g)}})}_handleGroupJoinResult(s){const{groupProfile:n}=s.payload,{groupID:g,type:I}=n,E=Yi.hasLocalGroup(g);this._core.ssoLog.debug("_handleGroupJoinResult",` groupID:${g} type:${I} hasLocalGroup:${E}`),E||Ed(I)||(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,I=Yi.hasLocalGroup(g);this._core.ssoLog.debug("_handleGroupInvitedResult",` groupID:${g} hasLocalGroup:${I}`),I||Ul.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,I=Yi.hasLocalGroup(n);this._core.ssoLog.debug("_handleGroupQuitResult",` groupID:${n} type:${g} hasLocalGroup:${I}`),I&&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(Ed(n)){const{appStore:{conversationStore:g},OuterConstant:{CONV_GROUP:I}}=this._core;g.deleteConversation(`${I}${s}`)}Yi.deleteLocalGroup(s),Yi.emitGroupListUpdate()}_updateConversationProfile(s,n){const{appStore:{conversationStore:g},OuterConstant:{CONV_GROUP:I}}=this._core,E=`${I}${s}`;g.getConversation(E)&&g.updateConversation(E,n)}},rD=new class{init(s){this._core=s,s.ssoLog.debug("GroupNotificationHandler.init"),Rv.init(s),wv.init(s);const{notificationCenter:n,InnerEvent:g}=s,{InnerEventSubType:I}=n;n.subscribeInnerEvent(g.MESSAGE_PUSH,I.GROUP_TIPS_NOTIFICATION,this._onNewGroupTipsNotification,this),n.subscribeInnerEvent(g.MESSAGE_PUSH,I.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){wv.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},wQ={required:!0,rules:["number"],allowEmpty:!1},Bd={required:!0,rules:["array"],allowEmpty:!1},aD={required:!0,rules:["object"],allowEmpty:!1},sT={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:Bd,memberCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},addGroupMember:{groupID:vn,userIDList:Bd},deleteGroupMember:{groupID:vn,userIDList:Bd},setGroupMemberMuteTime:{groupID:vn,userID:vn,muteTime:Object.assign(Object.assign({},wQ),{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:Bd},markGroupMemberList:{groupID:vn,markType:Object.assign(Object.assign({},wQ),{customValidator:s=>!(s<1e3)||"markType must be greater than or equal to 1000."}),enableMark:{required:!0,rules:["boolean"],allowEmpty:!1},userIDList:Bd},initGroupAttributes:{groupID:vn,groupAttributes:aD},setGroupAttributes:{groupID:vn,groupAttributes:aD},deleteGroupAttributes:{groupID:vn,keyList:Object.assign(Object.assign({},Bd),{allowEmpty:!0})},getGroupAttributes:{groupID:vn,keyList:Object.assign(Object.assign({},Bd),{allowEmpty:!0})},getGroupCounters:{groupID:vn,keyList:{required:!1,rules:["array"],allowEmpty:!0}},setGroupCounters:{groupID:vn,counters:aD},increaseGroupCounter:{groupID:vn,key:vn,value:wQ},decreaseGroupCounter:{groupID:vn,key:vn,value:wQ}},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 rT=new class{constructor(){this._installedSubPlugins=[],this.groupDataHandler=Yi,this.groupAction=DQ,this.groupAttribute=vQ,this.groupMember=vv,this.groupCounter=tB,this.name="Group"}install(s,n=[]){this._core=s,Wn.init(s),Yi.init(s),DQ.init(s,this),vv.init(s,this),eD.init(s),tB.init(s),vQ.init(s),rD.init(s),s.helper.registerValidateConfig({auth:nT,params:sT}),this._installSubPlugins(n);const{notificationCenter:g,InnerEvent:I}=s;g.subscribeInnerEvent(I.LOGOUT,this._reset,this),g.subscribeInnerEvent(I.DESTROY,this._dispose,this)}getInstalledSubPlugins(){return this._installedSubPlugins}_installSubPlugins(s){const{utils:{isArray:n}}=this._core;s&&n(s)&&s.forEach(g=>{var I;this._installedSubPlugins.includes(g.name)||((I=g.install)===null||I===void 0||I.call(g,this._core,this),this._installedSubPlugins.push(g.name))})}_reset(){Yi.reset(),vQ.reset(),tB.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}},_v="AV_MBR_LIST",aT="AV_BAN_MBR",bE={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},sh={GROUP_DISMISSED:5,QUIT_GROUP:8,AVCHATROOM_MEMBER_BANNED:21},gD=60,cD=2603,gT=2686,cT=2688,_Q=3122;class Tv{constructor(n){const{core:g,manager:I,groupID:E,getRequestParams:m,onSuccess:D,onFail:M}=n;this._name="Polling",this._core=g,this._manager=I,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 I=this._manager.getCurrentPollingInterval(this._groupID);this._runNextPolling(I)}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 nh{constructor(n){this._maxLength=n,this._map=new Map}set(n){var g;if(this._map.size>=this._maxLength){const I=((g=this._map.entries().next().value)===null||g===void 0?void 0:g[0])||"";this._map.delete(I)}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 Yu=s=>s===bE.GROUP_TIPS_HAS_NO_ROAMING||s===bE.GROUP_TIPS_HAS_ROAMING,TQ=s=>s===bE.GROUP_SYSTEM_MESSAGE;function Rm(s){const n=function(g){const{E:I,MCT:E,MR:m,MP:D,MTS:M,GId:T,MS:P,CCD:W,F_Account:oA,IsSys:EA,GInf:wA,MsgBody:kA}=g,YA=yo(g,["E","MCT","MR","MP","MTS","GId","MS","CCD","F_Account","IsSys","GInf","MsgBody"]);return Object.assign({Event:I,MsgClientTime:E,MsgRandom:m,MsgPriority:D,MsgTimeStamp:M,ToGroupId:T,MsgSeq:P,CloudCustomData:W,From_Account:oA,IsSystemMsg:EA,GroupInfo:lD(wA),MsgBody:lT(kA)},YA)}(s);return function(g){const{Event:I}=g;(Yu(I)||TQ(I))&&(g.From_Account=g.From_Account||"@TIM#SYSTEM"),E=I,(E===bE.BROADCAST_MESSAGE||(m=>m===bE.NORMAL_MESSAGE)(I))&&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;Yu(I)&&function(m){const{GroupJoinType:D,MsgOperatorMemberExtraInfo:M={},MsgMemberExtraInfo:T,Operator_Account:P,List_Account:W,OpType:oA}=m.MsgBody||{};typeof D=="number"||oA!==1&&oA!==2||(m.MsgBody.GroupJoinType=oA===2?0:1),T||(m.MsgBody.MsgMemberExtraInfo=W?.map(EA=>({UserId:EA}))),oA!==1||T||(m.MsgBody.MsgMemberExtraInfo=[{UserId:M.UserId}]),m.MsgBody.MsgOperatorMemberExtraInfo=Object.assign({Operator_Account:P,ImageUrl:"",NickName:""},M)}(g),TQ(I)&&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 lD(s){const n=s||{},{GN:g,GT:I,F_Hd:E,F_NN:m,F_Ll:D}=n,M=yo(n,["GN","GT","F_Hd","F_NN","F_Ll"]),T=Object.assign({GroupName:g,GroupType:I},M);return E&&(T.From_AccountHeadurl=E),m&&(T.From_AccountNick=m),D&&(T.From_AccountLevel=D),T}function lT(s){let n=s;Array.isArray(s)||(n=[s]);const g=n.map(I=>{const{O_Account:E,Opt:m,L_Account:D,RT:M,UDF:T,OpInf:P,OnlineInf:W,MsgMemberExtraInfo:oA}=I,EA=yo(I,["O_Account","Opt","L_Account","RT","UDF","OpInf","OnlineInf","MsgMemberExtraInfo"]),wA=Object.assign({Operator_Account:E,OpType:m,List_Account:D,ReportType:M,UserDefinedField:T},EA);return P&&(wA.MsgOperatorMemberExtraInfo=function(kA){const{Img:YA,NN:LA}=kA,SA=yo(kA,["Img","NN"]);return Object.assign({ImageUrl:YA,NickName:LA},SA)}(P)),oA&&(wA.MsgMemberExtraInfo=function(kA){return kA?.map(YA=>{const{Img:LA,NN:SA}=YA,OA=yo(YA,["Img","NN"]);return Object.assign({ImageUrl:LA,NickName:SA},OA)})}(oA)),W&&(wA.OnlineMemberInfo=function(kA){const{ET:YA,Num:LA}=kA;return{ExpireTime:YA,OnlineMemberNum:LA}}(W)),wA});return Array.isArray(s)?g:g[0]}var rh=new class{constructor(){this._name="MessageParser",this._sequenceList=new nh(200),this._messageIDList=new nh(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 I=this._handleMessageList(s,n);if(I.length===0)return;if(!g){const{appStore:{conversationStore:T},OuterConstant:{CONV_GROUP:P},common:{buildLastMessage:W}}=this._core,oA=W(I[I.length-1]);T.updateConversation(`${P}${s}`,{lastMessage:oA})}this._checkMessageStacked(I);const E=I.filter(T=>T.isModified===!0),m=I.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:I}=s;let E=[];this._avChatRoomHandler.isPollingSimplifiedMessage()&&!I?(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:I,messageHelper:E}}=this._core,m=this._avChatRoomHandler.isPollingSimplifiedMessage(),D=[],M=n.length;for(let T=0;Tg===bE.MESSAGE_REVOKED)(n)?(this._handleMessageRevoked(s),null):(g=>g===bE.LIVE_CUSTOM_DATA)(n)?(this._onLiveCustomData(s),null):(g=>g===bE.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 I=g.CONV_GROUP;s.elements.type===g.MSG_GRP_SYS_NOTICE&&(I=g.CONV_SYSTEM);const E=!!s.isSystemMessage,m=n.createMessage(Object.assign(Object.assign({},s),{conversationType:I,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:I,MsgBody:{RevokeMsgList:E},RevokerInfo:{Revoker_Account:m,Reason:D=""}}=s,M=[];E.forEach(T=>{const{TinyId:P,MsgClientTime:W,Random:oA,MsgSeq:EA}=T,wA={conversationID:`${n.CONV_GROUP}${I}`,ID:`${P}-${W}-${oA}`,revoker:m,revokeReason:D,revokerInfo:{userID:m,nick:"",avatar:""},sequence:EA};M.push(wA)}),M.length!==0&&this._emitEvent({name:g,data:M})}_onLiveCustomData(s){const{OuterEvent:{ROOM_CUSTOM_DATA_RECEIVED:n}}=this._core,{ToGroupId:g,MsgSeq:I,MsgTimeStamp:E,MsgBody:m}=s,D=m?.Content||m?.MsgContent||"";this._emitEvent({name:n,data:D}),console.log(`${this._name}._onLiveCustomData groupID:${g} sequence:${I} 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,I=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:I}}=s;if(n(I))return;const{OnlineMemberNum:E=0,ExpireTime:m=gD}=I,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 oB=s=>{const{core:{store:n}}=iB;return(n.get("cloudConfig")||{})[s]},ah=s=>{const{core:{utils:{isUndefined:n}}}=iB;return!n(s)},NQ=()=>{const s=oB("polling_interval");return ah(s)?parseInt(s,10):300},sB=()=>{const s=oB("polling_simplified_msg");return ah(s)?parseInt(s,10):0};var Nv=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,I=n.getGroup(s);return I?I.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,I=Og.getLocalOnlineMemberCount(s);if(g(I)||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:${I.memberCount} from local.`),{code:0,data:{memberCount:I.memberCount}}})}_isExpired(s){const n=Og.getLocalOnlineMemberCount(s),g=Date.now(),I=g-n.lastSyncTime>1e3*n.expireTime,E=g-n.latestUpdateTime>1e4,m=g-n.lastReqTime>3e3;return I&&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:I=0,ExpireTime:E=gD}=g||{},m=Date.now(),D={lastSyncTime:m,latestUpdateTime:m,lastReqTime:m,memberCount:I,expireTime:E};return Og.updateLocalOnlineMemberCount(s,D),{memberCount:I}}catch(g){const I=new this._core.helper.ChatError({functionName:n,code:g?.errorCode,message:g?.errorInfo});throw console.error(`${this._name}.${n} fail:`,I),I}})}},Og=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,rh.init(s,this),s.ssoLog.debug("AVChatRoomHandler.init")}onAVChatRoomSystemNotification(s){const{OuterConstant:{GRP_AVCHATROOM:n}}=this._core,{GroupTips:g=[]}=s;for(let I=0;I0&&(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:I},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(),I(`${g}${T}`),Nv.getGroupOnlineMemberCount(T),M.length>0&&rh.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:I,apiMap:{quitGroup:E},ssoLog:m}=this._core;if(n.isUnlimitedAVChatRoom()){if(this._pollingInstanceMap.size>(()=>{const T=oB("polling_count_limit");return ah(T)&&T>0?parseInt(T,10):20})())throw new I.ChatError({code:cT,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:I=1,group:E}=s,{groupID:m}=E;return this._pollingRequestInfoMap.set(m,{longPollingKey:g,startSequence:I}),this._pollingIntervalMap.set(m,NQ()),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 Tv({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:sB()}:{longPollingKey:n,startSequence:g,simplifiedMessage:sB()}}_handleSuccess(s,n){const{ErrorCode:g}=n;if(g!==0){const{longPollingKey:I,startSequence:E}=this._pollingRequestInfoMap.get(s)||{};return void console.warn(`${this._name}._handleSuccess groupID:${s} key:${I} startSeq:${E} errorCode:${g}`)}this._hasJoinedAVChatRoom(s)&&this._handleResponseData(s,n)}_handleResponseData(s,n){const{Key:g,NextSeq:I,NextBroadcastSeq:E,RspMsgList:m=[],RspBroadcastMsgList:D=[]}=n;if(g&&I&&this._pollingRequestInfoMap.set(s,{longPollingKey:g,startSequence:I}),E&&E>this._startBroadcastSequence&&(this._startBroadcastSequence=E),m.length>0)this._getPollingNoMessageCount(s)!==0&&(this._updatePollingNoMessageCount(s,0),this._pollingIntervalMap.set(s,NQ())),rh.onMessageReceived(s,m);else{let M=this._getPollingNoMessageCount(s);if(M+=1,this._updatePollingNoMessageCount(s,M),M===(()=>{const T=oB("polling_no_msg_count");return ah(T)?parseInt(T,10):20})()){const T=NQ()+(()=>{const P=oB("polling_interval_plus");return ah(P)?parseInt(P,10):2e3})();this._pollingIntervalMap.set(s,T)}}D.length>0&&rh.onBroadcastMessageReceived(D)}_handleFailure(s,n){const{ssoLog:g,utils:{safeStringify:I}}=this._core;g.warn("polling",`${this._name}._handleFailure groupID:${s} error: ${I(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){rh.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:I,count:E}=(()=>{const m=oB("av_members_freq_limit");if(ah(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*I?(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 I=this._pollingInstanceMap.get(s);return I?.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:I}=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)}),I.info("longPollingCount",String(s),{moreMessage:`av:${m.join(",")} live:${D.join(",")} code: ${E}`,eventType:29})}}reset(s){this._stopPolling(s),this._startBroadcastSequence=1,rh.reset()}},Gv=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:I,group:{type:E}}}=g;return E===n.GRP_AVCHATROOM?I===n.JOIN_STATUS_ALREADY_IN_GROUP?g:Og.handleJoinGroupResult(g.data):g})}},IT=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:I}}=g;return I===n.GRP_AVCHATROOM&&Og.reset(s),g})}},bv=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:I}}=g;return I===n.GRP_AVCHATROOM&&Og.reset(s),g})}},wm=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:I}=this._core,{groupID:E}=s,m=n.getGroup(E);if(m?.type===I.GRP_AVCHATROOM&&g.checkBusinessCapabilityBits(_v)){if(Og.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 I=yield function(M,T){return pA(this,void 0,void 0,function*(){const{groupID:P,offset:W=0}=M,oA={GroupId:P,Timestamp:W};return T.common.buildAndSendPacket({servcmd:"group_open_avchatroom_http_svc.get_members",data:oA})})}(s,this._core),{MemberList:E=[],NextTimestamp:m=0}=I||{},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(I){const E=new g.ChatError({functionName:n,code:I?.errorCode,message:I?.errorInfo});throw console.error(`${this._name}.${n} fail:`,E),E}})}_handleMemberList(s){return s.map(n=>{const{Member_Account:g,NickName:I="",Avatar:E="",Remark:m="",JoinTime:D=0,Marks:M=[]}=n;return{userID:g,nick:I,avatar:E,remark:m,joinTime:D,marks:M,isOnline:!0}})}},_m=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:I},helper:E,OuterConstant:m}=this._core,{groupID:D}=s,M=g.getGroup(D);if(I(M))throw new E.ChatError({functionName:n,code:cD});if(M.type===m.GRP_AVCHATROOM){if(E.checkBusinessCapabilityBits(aT))return this._deleteGroupMember(s);throw new E.ChatError({functionName:n,code:_Q})}return this._parentPlugin.groupMember.deleteGroupMember(s)})}_deleteGroupMember(s){return pA(this,void 0,void 0,function*(){const n="_deleteGroupMember",{appStore:{groupStore:g},helper:I,ssoLog:E}=this._core,{groupID:m,duration:D=0,userIDList:M}=s;if(D===0)throw new I.ChatError({functionName:n,code:gT});try{return yield function(T,P){return pA(this,void 0,void 0,function*(){const{groupID:W,userIDList:oA,duration:EA,reason:wA}=T,kA={GroupId:W,Members_Account:oA,Duration:EA,Description:wA};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 I.ChatError({functionName:n,code:T?.errorCode,message:T?.errorInfo})}})}},Qd=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:I,enableMark:E,userIDList:m=[]}=s,D=this._generateRequestData(s);try{const M=yield function(oA,EA){return pA(this,void 0,void 0,function*(){const{groupID:wA,operationType:kA,memberList:YA}=oA,LA={GroupId:wA,CommandType:kA,MemberList:YA};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:${I} 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:I,userIDList:E=[]}=s,m=I===!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=[],I=[];return s.length===n.length?(g.push(...n),{successUserIDList:g,failureUserIDList:I}):(n.forEach(E=>{s.find(m=>m.Member_Account===E)?g.push(E):I.push(E)}),{successUserIDList:g,failureUserIDList:I})}},kv=new class{init(s,n){s.ssoLog.debug("AVChatRoomAction.init"),Gv.init(s,n),IT.init(s,n),bv.init(s,n),wm.init(s,n),Nv.init(s,n),_m.init(s,n),Qd.init(s)}},Lv=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:I,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({});Og.hasPollingInstance(m)&&this.stopMessageLongPolling({groupID:m});const T=Og.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:I.GRP_LIVE};return Og.updateLocalLiveGroup(m,W),this._getLiveHistoryMessages({groupID:m,longPollingKey:D,startSequence:M}),Og.startMessageLongPolling({group:W,longPollingKey:D,startSequence:M})}stopMessageLongPolling(s){const{groupID:n}=s;return Og.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 I=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=[]}=I||{};n.debug("_getLiveHistoryMessages",`${this._name}._getLiveHistoryMessages ok, groupID:${g} count:${E.length}`),E.length>0&&Og.handleLiveHistoryMessages(g,E)}catch(I){n.debug("_getLiveHistoryMessages",`${this._name}._getLiveHistoryMessages failed, groupID:${g} info:${I.message}`)}})}},Tm=new class{constructor(){this.name="AVChatRoom"}install(s,n){this._core=s,iB.init(s),Og.init(s,n),kv.init(s,n),Lv.init(s);const{notificationCenter:g,InnerEvent:I}=s,{InnerEventSubType:E}=g;g.subscribeInnerEvent(I.MESSAGE_PUSH,E.GROUP_SYSTEM_NOTIFICATION,this._onAVChatRoomSystemNotification,this),g.subscribeInnerEvent(I.LOGOUT,this._reset,this),g.subscribeInnerEvent(I.DESTROY,this._dispose,this)}_onAVChatRoomSystemNotification(s){Og.onAVChatRoomSystemNotification(s)}_reset(){Og.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 $a=new class{init(s){this.core=s}},Nm="message",nB="user",rB={OR:"or",AND:"and"},mI=20,uT=20,Uv=20,gh={required:!1,rules:["array"],allowEmpty:!0,customValidator:s=>!s||!!(Array.isArray(s)&&s.length<=5)||"keywordList should be an array and length <= 5"},Gm={required:!1,rules:["string"],allowEmpty:!0,customValidator:s=>!s||!![rB.OR,rB.AND].includes(s)||"keywordListMatchType should be OR or AND"},EC={required:!1,rules:["number"],allowEmpty:!0,customValidator:s=>typeof s=="number"&&s>=1&&s<=100||"count must be a number between 1 and 100"},GQ={required:!1,rules:["string"],allowEmpty:!0},Fv={required:!1,rules:["array"],allowEmpty:!0,customValidator:s=>{const{OuterConstant:n}=$a.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 I=!1;for(let E=0;E{const{OuterConstant:n}=$a.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 I=!1;for(let E=0;E{const{OuterConstant:n}=$a.core;return!(!s?.startsWith(n.CONV_C2C)&&!s?.startsWith(n.CONV_GROUP)&&s!==n.CONV_SYSTEM)||"conversationID is invalid"}},bm=s=>({required:!1,rules:["number"],allowEmpty:!0,customValidator:n=>typeof n=="number"&&n>=0||`${s} should be a number >= 0';`}),ID={required:!1,rules:["string"],allowEmpty:!0,customValidator:s=>{const{OuterConstant:n}=$a.core;return!![n.GENDER_FEMALE,n.GENDER_MALE].includes(s)||"gender is invalid"}},km={searchCloudMessages:{keywordList:gh,keywordListMatchType:Gm,cursor:GQ,senderUserIDList:{required:!1,rules:["array"],allowEmpty:!0,customValidator:s=>!!(Array.isArray(s)&&s.length<=5)||"senderUserIDList should be an array and length <= 5"},messageTypeList:Ov,conversationID:Pv,timePosition:bm("timePosition"),timePeriod:bm("timePeriod")},searchCloudUsers:{keywordList:gh,keywordListMatchType:Gm,cursor:GQ,count:EC,miniBirthday:bm("miniBirthday"),maxBirthday:bm("maxBirthday"),gender:ID},searchCloudGroupMembers:{keywordList:gh,keywordListMatchType:Gm,cursor:GQ,count:EC,groupTypeList:Fv,groupIDList:{required:!1,rules:["array"],allowEmpty:!0}},searchCloudGroups:{keywordList:gh,keywordListMatchType:Gm,cursor:GQ,count:EC,groupTypeList:Fv}},uD={searchCloudMessages:!0,searchCloudUsers:!0,searchCloudGroupMembers:!0,searchCloudGroups:!0};var ED=new class{constructor(){this.name="CloudSearch"}install(s){this._core=s,$a.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:uD,params:km})}searchCloudMessages(s){return pA(this,void 0,void 0,function*(){try{const{OuterConstant:n,helper:g}=this._core,{conversationID:I,timePeriod:E,timePosition:m}=s,D=yo(s,["conversationID","timePeriod","timePosition"]),M=Object.assign({count:100},D);I&&(I.startsWith(n.CONV_C2C)?M.account=I.replace(n.CONV_C2C,""):I.startsWith(n.CONV_GROUP)&&(M.groupID=I.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:HA,senderUserIDList:se,messageTypeList:oe,endTime:_i,startTime:Ti,cursor:bt,account:Ni,groupID:gs}=LA,De={Count:SA,KeywordList:OA,MatchType:HA,SendUserIDList:se,MsgTypeList:oe,EndTime:_i,StartTime:Ti,Cursor:bt,PeerAccount:Ni,GroupID:gs};return $a.core.common.buildAndSendPacket({servcmd:"message_search.query",data:De})})}(M);if(!T)return{code:0,data:{}};const{ErrorCode:P,ErrorInfo:W,TotalCount:oA,Cursor:EA="",ConversationMsgs:wA=[]}=T;if(P!==0)throw{errorCode:P,errorInfo:W};const kA=`keywordList:${s.keywordList} keywordListMatchType:${s.keywordListMatchType} cursor:${s.cursor} res: totalCount:${oA}`;return{code:0,data:{searchResultList:wA.map(LA=>{const{MsgList:SA,Count:OA,GroupID:HA,UserID:se}=LA,oe=HA?`${n.CONV_GROUP}${HA}`:`${n.CONV_C2C}${se}`;if(this._isSearchingAllConversations(s)&&OA>1)return{conversationID:oe,messageCount:OA,messageList:[]};const _i=SA.map(Ti=>g.isEmpty(HA)?function(bt,Ni){const gs=Ni.OuterConstant.CONV_C2C,De=Ni.message.messageHelper.parseServerPushMessage(bt),Bt=Ni.message.messageFactory.createMessage(Object.assign(Object.assign({},De),{conversationType:gs,flow:"in"}));return Bt.setElement(De.elements),Bt}(Ti,this._core):function(bt,Ni){const gs=Ni.OuterConstant.CONV_GROUP,De=Ni.message.messageHelper.parseServerGroupMessage(bt),Bt=Ni.message.messageFactory.createMessage(Object.assign(Object.assign({},De),{conversationType:gs,flow:"in"}));return Bt.setElement(De.elements),Bt}(Ti,this._core));return{conversationID:oe,messageCount:OA,messageList:_i}}),cursor:EA,totalCount:oA},successLog:{message:kA}}}catch(n){const{errorCode:g,errorInfo:I}=n||{};this._handleError({errorCode:g,errorInfo:I,searchType:Nm,functionName:"searchCloudMessages"})}})}searchCloudUsers(s){return pA(this,void 0,void 0,function*(){var n;try{const{keywordListMatchType:g,count:I=uT}=s,E=yo(s,["keywordListMatchType","count"]),m=Object.assign({count:I,keywordListMatchType:g===rB.AND?1:0},E);this._setBirthdayRangeParams(m,s);const D=yield function(kA){return pA(this,void 0,void 0,function*(){const{count:YA,keywordList:LA,keywordListMatchType:SA,miniBirthday:OA,maxBirthday:HA,cursor:se,gender:oe}=kA,_i={Count:YA,Keywords:LA,KeywordMatchType:SA,Cursor:se,UserBirthStart:OA,UserBirthEnd:HA,Gender:oe};return $a.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:oA=[]}=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}`,wA=[];for(let kA=0,YA=oA.length;kA({tag:se.Tag,value:se.StrValue})),HA=(n=this._core.user.userProfile)===null||n===void 0?void 0:n.createProfile(LA,OA);wA.push(HA)}return{code:0,data:{searchResultList:wA,cursor:W,totalCount:P},successLog:{message:EA}}}catch(g){const{errorCode:I,errorInfo:E}=g||{};this._handleError({errorCode:I,errorInfo:E,searchType:nB,functionName:"searchCloudUsers"})}})}searchCloudGroupMembers(s){return pA(this,void 0,void 0,function*(){try{const{count:n=Uv,keywordListMatchType:g}=s,I=yo(s,["count","keywordListMatchType"]),E=Object.assign({count:n,keywordListMatchType:g===rB.AND?1:0},I),m=yield function(wA){return pA(this,void 0,void 0,function*(){const{count:kA,keywordList:YA,keywordListMatchType:LA,groupTypeList:SA,cursor:OA,groupIDList:HA}=wA,se={Count:kA,Keywords:YA,KeywordMatchType:LA,Cursor:OA,GroupType:SA,GroupIdList:HA};return $a.core.common.buildAndSendPacket({servcmd:"group_member_search.query",data:se})})}(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 oA=`keywordList:${s.keywordList} keywordListMatchType:${s.keywordListMatchType} cursor:${s.cursor} count:${s.count} res: totalCount:${W}`,EA=new Map;return T.forEach(wA=>{const{GroupID:kA,GroupName:YA,GroupType:LA,GroupFaceUrl:SA,GroupMemberUserName:OA,GroupMemberUserID:HA,GroupMemberNameCard:se,GroupMemberAvatar:oe=""}=wA,_i={groupID:kA,name:YA,type:LA,avatar:SA},Ti={userID:HA,nick:OA,nameCard:se,avatar:oe};if(EA.has(kA)){const bt=EA.get(kA);bt.memberList.push(Ti),EA.set(kA,bt)}else EA.set(kA,{groupInfo:_i,memberList:[Ti]})}),{code:0,data:{searchResultList:[...EA.values()],cursor:P,totalCount:W},successLog:{message:oA}}}catch(n){const{errorCode:g,errorInfo:I}=n||{};this._handleError({errorCode:g,errorInfo:I,searchType:nB,functionName:"searchCloudGroupMembers"})}})}searchCloudGroups(s){return pA(this,void 0,void 0,function*(){try{const{count:n=mI,keywordListMatchType:g}=s,I=yo(s,["count","keywordListMatchType"]),E=Object.assign({count:n,keywordListMatchType:g===rB.AND?1:0},I),m=yield function(EA){return pA(this,void 0,void 0,function*(){const{count:wA,keywordList:kA,keywordListMatchType:YA,groupTypeList:LA,cursor:SA}=EA,OA={Count:wA,Keywords:kA,KeywordMatchType:YA,Cursor:SA,GroupType:LA};return $a.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 oA=`keywordList:${s.keywordList} keywordListMatchType:${s.keywordListMatchType} cursor:${s.cursor} count:${s.count} res: totalCount:${W}`;return{code:0,data:{searchResultList:T?.map(EA=>function(wA){const{GroupFaceUrl:kA,GroupID:YA,GroupIntroduction:LA,GroupMemberNum:SA,GroupName:OA,GroupOwnerTinyID:HA,GroupOwnerUserID:se,GroupOwnerUserName:oe,GroupType:_i,GroupAddOption:Ti,GroupInviteOption:bt}=wA;return{avatar:kA,groupID:YA,introduction:LA,memberCount:SA,name:OA,ownerTinyID:HA,ownerID:se,ownerNick:oe,type:_i,joinOption:Ti,inviteOption:bt}}(EA))||[],cursor:P,totalCount:W},successLog:{message:oA}}}catch(n){const{errorCode:g,errorInfo:I}=n||{};this._handleError({errorCode:g,errorInfo:I,searchType:nB,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:I}=this._core;let E=s;throw s===60020?E="SearchUnable":g!==Nm&&s===27003?E="SearchParamsError":g!==Nm&&s===60018&&(E="SearchOverLimit"),new I.ChatError({code:E,message:n})}_isSearchingAllConversations(s){return this._core.helper.isEmpty(s.conversationID)}_setBirthdayRangeParams(s,n){const{miniBirthday:g,maxBirthday:I}=n;g!==void 0&&(s.miniBirthday=g,I===void 0&&(s.maxBirthday=4294967295)),I!==void 0&&(s.maxBirthday=I)}};function ch(s,n){return Math.round(Number(s)*Math.pow(10,n))/Math.pow(10,n)}const xv="qualityStat",dD="im-ssolog-quality-stat";var CD;(function(s){s[s.ONLINE=8]="ONLINE"})(CD||(CD={}));const Lm="networkRTT",lh="messageE2EDelay",aB="sendMessageC2C",Ih="sendMessageGroup",uh="sendMessageGroupAV",gB="sendMessageRichMedia",cB="cosUpload",dC="messageReceivedGroup",bQ="messageReceivedGroupAVPush",kQ="messageReceivedGroupAVPull",ET={[Lm]:2,[lh]:3,[aB]:4,[Ih]:5,[uh]:6,[gB]:7,[dC]:8,[bQ]:9,[kQ]:10,[cB]:11},Yv=[aB,Ih,uh,gB,cB],Eh=[dC,bQ,kQ],lB=[Lm,lh,aB,Ih,uh,gB,cB,dC,bQ,kQ],hD={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},Um="quality_stat";var LQ=new class{constructor(){this._messageStatsMap=new Map,this._userSideErrorCodes=new Set(Object.values(hD))}init(s){this._core=s,Object.values(Yv).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:I,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,I);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:I,failedCountOfUserSide:E}=n,m=ch(I/g*100,2),D=I+E,M=ch(D/g*100,2),T=this._calcAverageValue(n,s);return this._resetStat(s),{total_count:g,success_count_business:I,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 I=(g=n?.code)!==null&&g!==void 0?g:n?.errorCode;if(this._isUserSideError(I)){const E=this._getSendMessageSpecifiedKey(s),m=E&&this._messageStatsMap.get(E);m&&m.failedCountOfUserSide++}}_handleSendCost(s,n){const g=this._getSendMessageSpecifiedKey(s),I=g&&this._messageStatsMap.get(g);I&&(I.costSum+=Date.now()-n,I.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:I,MSG_FILE:E,CONV_C2C:m,CONV_GROUP:D,GRP_AVCHATROOM:M}=this._core.OuterConstant;if([n,g,I,E].includes(s.type))return gB;if(s.conversationType===m)return aB;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?uh:Ih}}_calcAverageValue(s,n){return s.costCount===0?0:Math.round(n===cB?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)}},UQ=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:I},ssoLog:E}=this._core;if(g(n)||!this._currentCycleStats.has(n))return void E.debug("addMessageSequence",`${xv}.addMessageSequence invalid key:${n}`);const{conversationID:m,sequence:D}=s,M=m.replace(I,""),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&&(I+=m.length,g+=M-D+1)}),g===0?null:(this._transferCycleDataOptimized(s),{total_count:g,success_count_business:I,percent_business:ch(I/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(Eh).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((I,E)=>{const m=I.dirty?[...I.sortedSequences].sort((D,M)=>D-M):I.sortedSequences;g.set(E,{sortedSequences:m,minSeq:I.minSeq,maxSeq:I.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:I}=this._core.appStore,E=I.getGroup(s.to);if(!E)return null;const{type:m}=E;return m===g?kQ:dC}}_insertToLastCycle(s,n){n.dirty&&(n.sortedSequences.sort((I,E)=>I-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,I=s.length-1;for(;g<=I;){const E=Math.floor((g+I)/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:I}}=this._core,E=[g,I];n.forEach(m=>{!E.includes(m.type)&&m.clientTime>0&&this.addMessageDelay(m.clientTime)})}_calculateAverageDelay(s){return s===0?0:ch(this._totalDelay/s,1)}_calculatePercentage(s,n){return ch(s/n*100,2)}},Vv=new class{init(s){this.core=s}},dT=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:I,LOGOUT:E,DESTROY:m},constants:{WORKFLOW_NAME:D,WORKFLOW_STEP:M}}=s;Vv.init(s),LQ.init(s),UQ.init(s),FQ.init(s),n.registerWorkflowStep(D.SYNC_SERVER_INFO_AFTER_LOGIN,M.QUALITY_REPORT,this.handleLoginSuccess,this),g.subscribeInnerEvent(I,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,I=s.get("cloudConfig")||{},{q_rpt_interval:E}=I,m=g(E)?12e4:Number(E);n.taskScheduler.addTask({id:Um,intervalMs:m,callback:this.report,context:this})}report(){this._wholePeriod=!0;const s=[...lB.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:I}=s;g===n.MESSAGE_SEND_SUCCESS_RATE&&LQ.dispatchSendStats(I)}_needSkipReport(){return this._isSDKAppIDInBlacklist()&&!this._isTinyIDInWhitelist()}_isSDKAppIDInBlacklist(){const{store:s,utils:n}=this._core,g=s.get("cloudConfig")||{},I=s.get("instance")||{},{sdkAppId:E}=I,{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")||{},I=s.get("login")||{},E=Number(I.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:ET[s],timestamp:Date.now(),network_type:CD.ONLINE,extension:""};return Object.assign(Object.assign({},g),n)}_getStatResultByKey(s){switch(s){case lh:return FQ.getStatResult();case aB:case Ih:case uh:case gB:case cB:return LQ.getStatResult(s);case dC:case bQ:case kQ:return UQ.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:I,channel:E}=Vv.core,m="imopenstat.tim_web_report_v2",D=I.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=`${xv}._cacheFailedLogs`;let g=[...this._failedLogsCache.get(dD)||[],...s];g.length>10&&(g=g.slice(g.length-10),console.log(`${n} logs overflow, keeping last 10 items`)),this._failedLogsCache.set(dD,g),console.log(`${n} count: ${g.length}`),this._pendingReports=[]}_reset(){const{helper:s}=this._core;s.taskScheduler.removeTask(Um)}_dispose(){const{notificationCenter:s,InnerEvent:{QUALITY_STAT:n,LOGOUT:g,DESTROY:I}}=this._core;s.unSubscribeInnerEvent(n,this._handleQualityStat,this),s.unSubscribeInnerEvent(g,this._reset,this),s.unSubscribeInnerEvent(I,this._dispose,this),this._reset(),FQ.dispose(),UQ.dispose()}};const gl=new class{init(s){this.core=s}};function Jv(s){return pA(this,void 0,void 0,function*(){var n;const{message:g,user:I,appStore:E,constants:{OuterConstant:m}}=gl.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;gl.core.message.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:s,latestAvatar:P,latestNick:W,isSentByMe:!1})}}const{data:M}=(yield I.userProfile.getMyProfile())||{};if(M){const{avatar:T,nick:P}=M;g.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:s,latestAvatar:T,latestNick:P,isSentByMe:!0})}})}function Hv(s){return pA(this,void 0,void 0,function*(){const n=s.map(g=>g.revoker);try{const g=yield function(I){return pA(this,void 0,void 0,function*(){var E,m;const D=yield(E=gl.core.user.userProfile)===null||E===void 0?void 0:E.getUserProfile({userIDList:I});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(I=>{const{revoker:E}=I;g[E]&&(I.revokerInfo.nick=g[E].nick||"",I.revokerInfo.avatar=g[E].avatar||"",I.revokerInfo.userID=E)})}catch(g){console.debug(g)}})}const BD=1,qv=2,dh=20,OQ=2500,Kv=1,Ch=300;function PQ(s){return pA(this,void 0,void 0,function*(){var n,g;const{appStore:I,utils:{isEmpty:E},common:{getCurrentUserID:m},notificationCenter:D,OuterEvent:M,OuterConstant:{CONV_C2C:T}}=gl.core,{messageList:P,conversationID:W}=s,oA=I.conversationStore.getConversationMap();let EA=(n=oA.get(W))===null||n===void 0?void 0:n.peerReadTime;if(!EA){const kA=W.replace(T,""),YA=yield function(LA){return pA(this,void 0,void 0,function*(){const SA={To_Account:LA};return gl.core.common.buildAndSendPacket({servcmd:"openim.get_peer_read_time",data:SA})})}([kA]);if(YA){const{ReadTime:LA}=YA;EA=LA?.[0],oA.has(W)&&(oA.get(W).peerReadTime=EA)}}if(oA.has(W)){const kA=(g=oA.get(W))===null||g===void 0?void 0:g.lastMessage;E(kA)||kA.fromAccount===m()&&kA.lastTime<=EA&&!kA.isPeerRead&&(kA.isPeerRead=!0,I.conversationStore.updateConversation(W,{lastMessage:kA}))}const wA=[];P.forEach(kA=>{kA.time<=EA&&!kA.isPeerRead&&kA.flow==="out"&&(kA.isPeerRead=!0,wA.push(kA))}),wA.length>0&&D.emitOuterEvent(M.MESSAGE_READ_BY_PEER,{name:M.MESSAGE_READ_BY_PEER,data:wA})})}var jv=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:I,CONV_GROUP:E},InnerEvent:{HISTORY_MESSAGE_FETCHED:m},notificationCenter:D}=this._core,{conversationID:M,nextReqMessageID:T}=s,P=dh;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 oA=null;if(M.startsWith(E)?oA=yield n.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:M,sequence:Number(T),count:P,direction:g.FORWARD,shouldMarkCompleted:!0}):M.startsWith(I)&&(oA=yield n.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:M,messageID:T,count:P,direction:g.FORWARD,shouldMarkCompleted:!0})),oA){const{nextReqMessageIDFromServer:EA,hasNoMoreHistoryMessage:wA,messageList:kA}=oA,YA=n.messageDataHandler.prependLocalMessageList({messageList:kA,conversationID:M});(function(se){const{appStore:oe,message:_i,OuterConstant:Ti}=gl.core,bt=oe.conversationStore.getConversation(se),Ni=_i.messageDataHandler.getLocalMessageList(se);if(!bt||Ni.length===0||se===Ti.CONV_SYSTEM)return;const gs=[];for(let Bt=0;BtUA.isRevoked).length;De=gs.length-bt.unreadCount-Bt}else De=gs.length-bt.unreadCount;for(let Bt=0;Btse.isRevoked);yield Hv(SA),D.emitInnerEvent(m,YA);const OA={nextReqMessageID:wA?"":String(EA),messageList:LA,isCompleted:wA},HA=LA.map(se=>se.sequence);return{code:0,data:OA,successLog:{message:`conversationID: ${M} nextReqMessageID: ${T} availableLocalMessagesCount: ${W} sequenceList: ${JSON.stringify(HA)}`}}}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:I}=n||{};throw new this._core.helper.ChatError({code:g,message:I,moreMessage:`options: ${this._core.utils.safeStringify(s)}`})}})}getMessageListHopping(s){return pA(this,void 0,void 0,function*(){var n,g;const{OuterConstant:{Direction:I,CONV_C2C:E,CONV_GROUP:m},utils:{safeStringify:D}}=this._core,{conversationID:M,sequence:T,time:P,direction:W=I.FORWARD}=s,{utils:{isEmpty:oA},message:EA,notificationCenter:wA,InnerEvent:{HISTORY_MESSAGE_FETCHED:kA}}=this._core;if(![I.BACKWARD,I.FORWARD].includes(W))throw new this._core.helper.ChatError({message:"direction must be 0 or 1",moreMessage:`options: ${D(s)}`});let{count:YA=dh}=s;YA=YA>dh?dh:YA;let LA=null;if(M.startsWith(m)){if(LA=yield EA.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:M,sequence:T,count:YA,direction:W}),LA){const{nextReqMessageIDFromServer:SA,hasNoMoreHistoryMessage:OA,messageList:HA,invisibleSequenceList:se}=LA;if(this._core.message.messageDataHandler.storeSparseMessageList(HA),wA.emitInnerEvent(kA,HA),W===I.FORWARD){const oe=OA&&SA<1;return{code:0,data:{messageList:HA,isCompleted:oe,nextMessageSeq:oe?"":SA}}}if(W===I.BACKWARD){if(oA(HA)&&oA(se))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};const oe=((n=HA?.[HA.length-1])===null||n===void 0?void 0:n.sequence)||0,_i=((g=se?.[se.length-1])===null||g===void 0?void 0:g.sequence)||0;return{code:0,data:{messageList:HA.filter(Ti=>Ti.sequence>=T),isCompleted:!OA,nextMessageSeq:OA?Math.max(oe,_i)+1:""}}}return{code:0,data:LA}}}else if(M.startsWith(E)&&(LA=yield EA.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:M,count:YA+1,time:P,direction:W}),LA)){const{messageList:SA,lastMessageTime:OA,hasNoMoreHistoryMessage:HA}=LA;return wA.emitInnerEvent(kA,SA),HA||(W===I.FORWARD?SA.shift():SA.pop()),EA.messageDataHandler.storeSparseMessageList(SA),yield PQ({messageList:SA,conversationID:M}),{code:0,data:{messageList:SA,isCompleted:HA,nextMessageTime:HA?"":OA}}}})}clearHistoryMessage(s){return pA(this,void 0,void 0,function*(){var n;const{appStore:g,common:{ChatError:I,getCurrentUserID:E},OuterConstant:{CONV_C2C:m,CONV_GROUP:D},apiMap:M,message:T}=this._core,P=g.conversationStore.getConversation(s);if(!P)throw new I({code:OQ});const W={fromAccount:E()},{type:oA}=P;oA===m?(W.type=BD,W.toAccount=s.replace(m,"")):oA===D&&(W.type=qv,W.toGroupID=s.replace(D,""));try{return yield(n=M?.setMessageRead)===null||n===void 0?void 0:n.call(M,{conversationID:s}),(yield function(wA){return pA(this,void 0,void 0,function*(){const{fromAccount:kA,type:YA,toAccount:LA,toGroupID:SA}=wA,OA={From_Account:kA,Type:YA,To_Account:LA,ToGroupid:SA};return gl.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:wA}=EA;throw new this._core.helper.ChatError({functionName:"clearHistoryMessage",code:wA,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:I}}=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(I)&&(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:I}=this._core;return nn.startsWith(E)?EA.ID===g:String(EA.sequence)===g),W=oA>I?oA-I:0,T=oA):W=M>I?M-I:0,P.messageList=D.slice(W,oA),P.isCompleted=T<=I&&m.messageHistory.completedHistoryConversations.has(n),P.isCompleted?P.nextReqMessageID="":P.nextReqMessageID=this._generateNextReqMessageID({conversationID:n,targetIndex:W}),n.startsWith(E)&&(yield Jv(n),yield PQ({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}}},IB=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:I,InnerEvent:E}}=s;n.registerWorkflowStep(g.SYNC_SERVER_INFO_AFTER_RE_ONLINE,I.HISTORY_MESSAGE_RECOVER,this._syncGroupOfflineMessage,this),n.registerWorkflowStep(g.SYNC_SERVER_INFO_AFTER_RE_ONLINE,I.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:I}}=this._core;if(I(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=[],I=[];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:I})),g.push(M.replace(n.CONV_GROUP,""))}))),{recoverRevokeNoticeGroupIDList:g,groupTipList:I}})}_recoverGroupHistoryForConversation(s){return pA(this,arguments,void 0,function*({conversationID:n,localLastMessageSequence:g,serverLastMessageSequence:I,groupTipList:E}){try{const{utils:{isArray:m,isObject:D,isEmpty:M},OuterEvent:T,OuterConstant:P,notificationCenter:W,message:oA,appStore:EA,common:{getMessagePreviewText:wA,buildLastMessage:kA}}=this._core,YA=I-g,LA=Math.min(20,YA),SA={},OA=yield oA.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:n,sequence:g+LA,direction:P.Direction.FORWARD,count:LA}),{nextReqMessageIDFromServer:HA,hasNoMoreHistoryMessage:se,messageList:oe,serverGroupTipList:_i}=OA;m(_i)&&E.push(..._i);const Ti=se&&HA<0,bt=[];if(m(oe)&&(oe.forEach(Ni=>{oA.messageReceiver.groupMessageReceiver.updateMessageProfile(Ni),Ni.from===P.CONV_SYSTEM&&(Ni.isSystemMessage=!1),oA.messageDataHandler.storeConversationMessage(Ni)&&!M(Ni.payload)&&(bt.push(Ni),Ni._isExcludedFromLastMessage||(SA.lastMessage=kA(Ni)))}),bt.length>0&&W.emitOuterEvent(T.MESSAGE_RECEIVED,{name:T.MESSAGE_RECEIVED,data:bt})),!Ti&&oe.length>0){const Ni=oe[oe.length-1].sequence;yield this._recoverGroupHistoryForConversation({conversationID:n,localLastMessageSequence:Ni,serverLastMessageSequence:I,groupTipList:E})}D(SA.lastMessage)&&(SA.lastMessage.messageForShow=wA(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,I]of n){const E=Array.from(I.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),I=g[g.length-1];return I?.sequence}_shouldRecoverHistory(s){const{localLastMessageSequence:n,serverLastMessageSequence:g}=s;if(typeof n!="number"||typeof g!="number")return!1;const I=g-n;return g!==0&&n>0&&I>=Kv&&I{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:I}={}}=n,E=this._getLocalLastMessageTime(g);this._shouldRecoverC2CHistory({localLastMessageTime:E,serverLastMessageTime:I})&&(yield this._recoverHistoryForC2CConversation({conversationID:g,localLastMessageTime:E,serverLastMessageTime:I}))})))})}_shouldRecoverC2CHistory(s){const{localLastMessageTime:n,serverLastMessageTime:g}=s,I=g-n;return n>0&&I>=1&&I<=600}_recoverHistoryForC2CConversation(s){return pA(this,void 0,void 0,function*(){var n;const{conversationID:g,localLastMessageTime:I,serverLastMessageTime:E}=s,{utils:{isArray:m,isObject:D,isEmpty:M,safeStringify:T},OuterEvent:P,OuterConstant:W,notificationCenter:oA,message:EA,appStore:wA,common:{getMessagePreviewText:kA,buildLastMessage:YA}}=this._core;try{const LA={},SA=yield EA.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:g,direction:W.Direction.BACKWARD,time:I,count:20});if(M(SA))return;const{hasNoMoreHistoryMessage:OA,messageList:HA}=SA,se=[];m(HA)&&(HA.forEach(_i=>{EA.messageDataHandler.storeConversationMessage(_i)&&!M(_i.payload)&&(se.push(_i),_i._isExcludedFromLastMessage||(LA.lastMessage=YA(_i)))}),se.length>0&&oA.emitOuterEvent(P.MESSAGE_RECEIVED,{name:P.MESSAGE_RECEIVED,data:se}));const oe=(n=HA[HA.length-1])===null||n===void 0?void 0:n.time;!OA&&oe>E&&(yield this._recoverHistoryForC2CConversation({conversationID:g,localLastMessageTime:oe,serverLastMessageTime:E})),D(LA.lastMessage)&&(LA.lastMessage.messageForShow=kA(LA.lastMessage.type,LA.lastMessage.payload),wA.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),I=g[g.length-1];return I?.time}reset(){this._lastMessageSequenceMapOnDisconnect.clear(),this._lastMessageTimeMapOnDisconnect.clear()}dispose(){this.reset()}},uB=new class{constructor(){this.name="HistoryMessage"}install(s){this._core=s,gl.init(s),jv.init(s),IB.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),IB.dispose()}_reset(){IB.reset()}},QD=new class{init(s){this.core=s}},CC=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:I}}=this._core;try{if(!I(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:I}}=this._core,{atomicStoreID:E}=s;try{I(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:I,eventCode:E,eventResult:m,eventMessage:D,moreMessage:M,extensionMessage:T}=s;g.createSSOLogData({method:T,code:I,message:D,eventType:30,costTime:E,uiPlatform:m,moreMessage:M}).end(!0)}catch(I){g.debug(`reportRoomEngineEvent Report failed: ${n(I)}`)}}reset(){this._reportedAtomicStoreIDs.clear()}dispose(){this.reset()}},xQ=new class{constructor(){this.name="DataReport"}install(s){this._core=s;const{notificationCenter:n,InnerEvent:{LOGOUT:g,DESTROY:I}}=s;QD.init(s),CC.init(s),n.subscribeInnerEvent(g,this._reset,this),n.subscribeInnerEvent(I,this._dispose,this)}_reset(){CC.reset()}_dispose(){const{notificationCenter:s,InnerEvent:{LOGOUT:n,DESTROY:g}}=this._core;s.unSubscribeInnerEvent(n,this._reset,this),s.unSubscribeInnerEvent(g,this._dispose,this),CC.dispose()}};let Fm=sr.STANDARD,EB=[];Fm=sr.STANDARD,EB=[ZC,eC,tC,iC,vc,dT,uB,xQ,RE,vi,jn,rT,Tm,ED,VI];function dB(s,n){const{operationType:g,memberInfoList:I,operatorInfo:E}=s||{};let m={};if(vs(I)?vs(E)||(m=E):g!==_g.JOINED&&g!==_g.KICKED&&g!==_g.ADMIN_SET&&g!==_g.ADMIN_CANCELED||(m=Object.assign({},I[0])),!vs(m)){const{nick:D="",avatar:M=""}=m;n.nick=D,n.avatar=M}}const YQ=s=>({lastTime:s?.time||s?.lastTime||0,lastSequence:s?.sequence||s?.lastSequence||0,fromAccount:s?.from||s?.fromAccount||"",messageForShow:Wc(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 VQ=Object.freeze({__proto__:null,ChatError:as,WorkflowManager:Rs,buildAndSendPacket:ag,buildLastMessage:YQ,get builtInPlugins(){return EB},checkBusinessCapabilityBits:en,deepMerge:sd,getCurrentUserID:Ar,getErrorMessage:ss,getMessagePreviewText:Wc,isC2CConv:s=>l(s)&&s.slice(0,3)===ba.CONV_C2C,isCommunity:zr,isGroupConv:s=>l(s)&&s.slice(0,5)===ba.CONV_GROUP,isInternational:Ml,isTopic:jc,isUnlimitedAVChatRoom:function(){var s;return!!(!((s=me.store.get("instance"))===null||s===void 0)&&s.unlimitedAVChatRoom)},liteChatInstanceMap:Ea,registerInterceptor:Sc,registerValidateConfig:Kc,requireAuth:td,get sdkEdition(){return Fm},setGroupTipsUserInfo:dB,t:Su,updateGroupAtInfo:(s,n)=>{const{CONV_AT_ME:g,CONV_AT_ALL:I,CONV_AT_ALL_AT_ME:E}=ko;if(function(M,T){const{CONV_AT_ME:P,CONV_AT_ALL:W,CONV_AT_ALL_AT_ME:oA}=ko,{groupID:EA,sequence:wA}=M;let kA=!1;return zr({groupID:EA})&&T.forEach(YA=>{YA.messageSequence===wA&&(YA.atTypeArray.includes(P)&&M.groupAtType.includes(W)&&(YA.atTypeArray=[oA]),YA.atTypeArray.includes(W)&&M.groupAtType.includes(P)&&(YA.atTypeArray=[oA],YA.__random=M.__random,YA.__sequence=M.__sequence),kA=!0)}),kA}(s,n))return;let m=[...s.groupAtType];m.includes(g)&&m.includes(I)&&(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:Dr,validateParameters:nI});class $I{constructor(){this._builtInPlugins=new Set,this._externalPlugins=new Set}static getInstance(){return $I._instance||($I._instance=new $I),$I._instance}static setInstance(n){$I._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 I=[];I=p(n)?n:[n];const E=I.findIndex(D=>D?.name==="AVChatRoom"),m=E>-1?I.splice(E,1):[];I.forEach(D=>{this._isPluginInstalled(D.name)||(D&&Mg(D.install)?(g.add(D.name),Mg(D.getInstalledSubPlugins)?(m?.forEach(M=>g.add(M?.name)),D.install(dr.getInstance().exposeApiForPlugin(),m)):D.install(dr.getInstance().exposeApiForPlugin()),Mg(D.handleLoginSuccess)&&this._isLoggedIn()&&D.handleLoginSuccess()):Mg(D)?(g.add(D.name),D(dr.getInstance().exposeApiForPlugin()),Mg(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=me.store.get("login"))===null||n===void 0?void 0:n.isLoggedIn)===!0}}var CB=new class{constructor(){this._conversationMap=new Map}getConversationMap(){return this._conversationMap}getConversation(s){return this._conversationMap.get(s)}updateConversation(s,n,g){const{emit:I=!0,needSort:E=!1}=g||{},m=this._conversationMap.get(s);m&&!vs(n)&&(Object.keys(n).forEach(D=>{m[D]=n[D]}),I&&me.notificationCenter.emitInnerEvent(so.CONVERSATION_UPDATED,{needSort:E}))}deleteConversation(s){this._conversationMap.has(s)&&(this._conversationMap.delete(s),me.notificationCenter.emitInnerEvent(so.CONVERSATION_UPDATED))}},JQ=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&&!vs(n)&&Object.keys(n).forEach(I=>{g[I]=n[I]})}},HQ=new class{constructor(){this._messagesByConversation=new Map}updateMessage(s,n,g){var I;const{operation:E,updateUnreadCount:m=!0}=g,D=yo(g,["operation","updateUnreadCount"]),M=[];for(const T of n){const P=(I=this._messagesByConversation.get(s))===null||I===void 0?void 0:I.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;jc(g)?me.notificationCenter.emitInnerEvent(pu[s],n):me.notificationCenter.emitInnerEvent(s,n)}},nc=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)}},pD=Object.freeze({__proto__:null,conversationStore:CB,groupStore:JQ,messageStore:HQ,userStore:nc});class dr{static getInstance(){return dr._instance||(dr._instance=new dr),dr._instance}static setInstance(n){dr._instance=n}constructor(){this._experimentalApiMap={statTUIKeyFeatures:this.statKeyFeatureUsage.bind(this),setApplicationID:this.setApplicationID.bind(this)},this._apiHandlersMap={},this._apiMap={on:me.notificationCenter.subscribeOuterEvent.bind(me.notificationCenter),off:me.notificationCenter.unSubscribeOuterEvent.bind(me.notificationCenter),destroy:this.destroy.bind(this),callExperimentalAPI:this.callExperimentalAPI.bind(this),use:$I.getInstance().installExternalPlugin.bind($I.getInstance()),registerPlugin:this.registerPlugin.bind(this),setLogLevel:this.setLogLevel.bind(this)}}registerPlugin(n){me.ssoLog.debug("registerPlugin",n)}statKeyFeatureUsage(n){me.ssoLog.debug("statTUIKeyFeatures",n)}setLogLevel(n){me.ssoLog.debug("setLogLevel",n),me.ssoLog.setLogLevel(n)}setApplicationID(n){me.store.set("instance",{applicationID:n})}getApiMap(){return this._apiMap}setApiMap(n){this._apiMap=n}registerApi(n){const{common:{timeManager:g},utils:{safeStringify:I}}=me,{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),UI.includes(E)&&me.ssoLog.debug(E,`${E} start params: ${I(T)}`),Dr(D,T);const oA=this._apiHandlersMap[E];for(const EA of oA)if(!EA.matcher||EA.matcher(T))try{const wA=EA.context[EA.methodName].bind(EA.context)(...T);return this._isPromiseLike(wA)?this._handleAsyncResult(wA,E,W,P):(this._reportApiSuccessLog({result:wA,apiName:E,eventType:W,startTime:P}),wA)}catch(wA){throw me.ssoLog.error(E,`${E} fail ${wA?.message||wA?.errorMessage})`,{error:wA,costTime:g.getServerTimeMs()-P,eventType:W,method:E}),wA}})}registerExperimentalAPI(n,g,I){const E=I||n;this._experimentalApiMap[n]=g[E].bind(g)}destroy(){return pA(this,void 0,void 0,function*(){var n,g;try{!((n=me.store.get("login"))===null||n===void 0)&&n.isLogin&&(yield this._apiMap.logout()),me.notificationCenter.emitInnerEvent(so.DESTROY)}catch(I){console.debug("destroy error: ",I)}finally{me.notificationCenter.emitOuterEvent(yr.SDK_DESTROY,{SDKAppID:(g=me.store.get("instance"))===null||g===void 0?void 0:g.sdkAppId}),Ea.clear(),$I.getInstance().clear(),Rs.getInstance().destroy(),me.destroy()}})}exposeApiForClient(){return this._apiMap}exposeApiForPlugin(){return Object.assign(Object.assign({InnerEvent:so,InnerEventSubType:me.notificationCenter.InnerEventSubType,OuterEvent:yr,OuterConstant:ko,SignalingEvent:Jc,helper:Object.assign(Object.assign(Object.assign({},me.utils),me.common),{registerApi:this.registerApi.bind(this),registerExperimentalAPI:this.registerExperimentalAPI.bind(this),registerInterceptor:Sc,registerValidateConfig:Kc,checkBusinessCapabilityBits:en,registerWorkflowStep:Rs.getInstance().registerWorkflowStep.bind(Rs.getInstance()),ChatError:as}),apiMap:this._apiMap},me),{constants:Object.assign(Object.assign({},Wa),me.constants),common:Object.assign(Object.assign(Object.assign({},VQ),me.common),{workflowManager:Rs.getInstance()}),utils:me.utils,appStore:pD})}callExperimentalAPI(n,g){return me.ssoLog.debug(`callExperimentalAPI.${n} start params: ${me.utils.safeStringify(g)}`),this._experimentalApiMap[n]?this._experimentalApiMap[n](g):(me.ssoLog.error("callExperimentalAPI",`callExperimentalAPI.${n} not found, params: ${me.utils.safeStringify(g)}`),Promise.reject(new as({code:ua.INVALID_OPERATION})))}_isPromiseLike(n){return n!==null&&typeof n=="object"&&typeof n.then=="function"}_handleAsyncResult(n,g,I,E){return n.then(m=>(this._reportApiSuccessLog({result:m,apiName:g,eventType:I,startTime:E}),m)).catch(m=>{throw me.ssoLog.error(g,`${g} fail ${m?.message||m?.errorMessage})`,{error:m,costTime:me.common.timeManager.getServerTimeMs()-E,eventType:I,method:g,startTime:E}),m})}_reportApiSuccessLog(n){let{result:g,apiName:I,startTime:E,eventType:m}=n;const{timeManager:D}=me.common,{successLog:{message:M,moreMessage:T}={message:"",moreMessage:""}}=g||{},P=D.getServerTimeMs();I==="login"&&(E+=D.getTimeOffsetWithServer()),UI.includes(I)&&me.ssoLog.info(I,`${I} success ${M} ${T}`,{costTime:P-E,eventType:m,message:M,moreMessage:T,startTime:E}),g?.successLog&&delete g.successLog}}class Wv{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120,this._customLoginInfo=""}init(){const{notificationCenter:n,store:g}=me;g.set("login",{isReady:!1}),dr.getInstance().registerApi({apiName:"login",context:this}),dr.getInstance().registerApi({apiName:"logout",context:this}),dr.getInstance().registerApi({apiName:"getLoginUser",context:this}),dr.getInstance().registerApi({apiName:"isReady",context:this}),dr.getInstance().registerApi({apiName:"getServerTime",context:this}),dr.getInstance().registerExperimentalAPI("setCustomLoginInfo",this),n.subscribeInnerEvent(so.RECONNECTED,this._reLogin,this),me.notificationCenter.subscribeInnerEvent(so.DESTROY,this._dispose,this)}login(n){return pA(this,void 0,void 0,function*(){var g;const{sdkEdition:I}=me.store.get("instance")||{};try{if(this._isLoginIn())return this._createRepeatLoginResponse();if(this._isLoginFrequencyExceeded())throw new as({functionName:"login",code:ua.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=me.channel.getSocketAdapter())===null||g===void 0?void 0:g.getId(),{appId:D,href:M}=me.store.get("instance")||{},{instanceID:T,customStatus:P}=E||{};return{code:0,data:E,successLog:{message:I,moreMessage:`socketID:${m} instanceID:${T} customStatus:${P} href: ${M} appId: ${D}`}}}catch(E){const{errorCode:m}=E;m!==ua.REPEAT_LOGIN&&(this._latestLoginAt=0);const D=new as({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 Du(this._customLoginInfo);if(g){const{instanceID:I,customStatus:E}=g;me.store.set("login",{statusInstanceId:I}),Rs.getInstance().executeWorkflow(Pt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,{customStatus:E,statusType:uE.USER_STATUS_ONLINE});const m=(n=me.channel.getSocketAdapter())===null||n===void 0?void 0:n.getId();me.ssoLog.info("reLogin",`socketId:${m} instanceId:${I}`)}}catch(g){console.warn(g)}})}logout(){return pA(this,arguments,void 0,function*(n=sa.USER_INITIATED){const{ssoLog:g}=me;g.debug("logout",`logout start logoutReason: ${n}`);try{yield this._performLogout(n),g.info("logout","logout success"),me.ssoLog.uploadSSOLogData()}catch(I){const{errorCode:E}=I;throw new as({functionName:"logout",code:E})}finally{this.handleLogoutCompleted()}return{code:0,data:{}}})}getLoginUser(){return this._isLoginIn()?Ar():""}isReady(){var n;return(n=me.store.get("login"))===null||n===void 0?void 0:n.isReady}setCustomLoginInfo(n=""){this._customLoginInfo=n}handleLogoutCompleted(){this._updateAndEmitSDKNotReady(),this._reset(),Rs.getInstance().reset(),me.notificationCenter.emitInnerEvent("logout")}getServerTime(){const{timeManager:n}=me.common;return n.getServerTimeMs()}_updateAndEmitSDKReady(){me.store.set("login",{isReady:!0}),setTimeout(()=>{me.notificationCenter.emitOuterEvent(yr.SDK_READY,{name:yr.SDK_READY})},1)}_updateAndEmitSDKNotReady(){me.store.set("login",{isReady:!1}),me.notificationCenter.emitOuterEvent(yr.SDK_NOT_READY,{name:yr.SDK_NOT_READY})}_validateAfterLogin(n){const g="login";if(!n)throw new as({functionName:g,message:"login response is empty"});const{tinyID:I,a2Key:E}=n||{};if(!I)throw new as({functionName:g,code:ua.NO_TINYID});if(!E)throw new as({functionName:g,code:ua.NO_A2KEY})}_createRepeatLoginResponse(){var n;return{code:0,data:{actionStatus:"OK",errorCode:0,errorInfo:ss({code:"RepeatLogin",replacement1:(n=me.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:I}=n;return me.store.set("login",{userId:g,userSig:I}),this._latestLoginAt=Date.now(),Du(this._customLoginInfo)})}_ensureAsyncComplete(){return pA(this,void 0,void 0,function*(){yield new Promise(n=>{setTimeout(()=>n(null),1)})})}_handleLoginSuccess(n){const{timeManager:g}=me.common,{helloInterval:I,timeStamp:E,customStatus:m,purchaseBits:D}=n,M=1e3*E;g.calculateTimeOffsetWithServer(this._latestLoginAt,M),this._helloInterval=I||120,this._updateLoginStore(n),me.user.userStatus.setCustomStatus(m),Rs.getInstance().executeWorkflow(Pt.SYNC_SERVER_INFO_AFTER_LOGIN,{purchaseBits:D}),me.common.taskScheduler.addTask({id:Ng,intervalMs:1e3*this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this})}_performLogout(n){return function(g){return pA(this,void 0,void 0,function*(){const{logoutReason:I}=g,E="im_open_status.wslogout",m=me.common.generateProtocolData({servcmd:E,data:{wslogout_type:I,isWebUniapp:0}}),D=`${m.head.seq}${E}`;return yield me.channel.sendPacket(m,{requestId:D})})}({logoutReason:n})}_updateLoginStore(n){const{a2Key:g,tinyID:I,instanceID:E,authKey:m}=n;me.store.set("login",{a2Key:g,tinyID:I,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=me.common.generateProtocolData({servcmd:n,data:{isWebUniapp:0}}),I=`${g.head.seq}${n}`;return me.channel.sendPacket(g,{requestId:I})}()}catch(n){me.ssoLog.warn("_sendOnlinePresenceRequest",` error:${n.message}`)}})}_isLoginIn(){var n;return((n=me.store.get("login"))===null||n===void 0?void 0:n.isLoggedIn)===!0}_isLoginFrequencyExceeded(){return Date.now()-this._latestLoginAt<=15e3}_reset(){me.common.taskScheduler.removeTask(Ng),this._helloInterval=120,this._latestSendOnlinePresenceRequestTime=0,this._latestLoginAt=0,this._customLoginInfo="",me.store.clear("login"),me.store.set("login",{isReady:!1}),me.store.set("instance",{applicationID:0})}_dispose(){this._reset();const{notificationCenter:n}=me;n.unSubscribeInnerEvent(so.RECONNECTED,this._reLogin,this),n.unSubscribeInnerEvent(so.DESTROY,this._dispose,this)}}const zv={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}},CT={logout:!0};class hh{constructor(){this.loginAction=new Wv,this.kickedOutHandler=new yu,this.loginAction.init(),this.kickedOutHandler.init(),Kc({auth:CT,params:zv})}}var Jr,Vu,kE;(function(s){s.CONV_C2C="C2C",s.CONV_GROUP="GROUP",s.CONV_TOPIC="TOPIC",s.CONV_SYSTEM="@TIM#SYSTEM"})(Jr||(Jr={})),function(s){s.MSG_PRIORITY_HIGH="High",s.MSG_PRIORITY_NORMAL="Normal",s.MSG_PRIORITY_LOW="Low",s.MSG_PRIORITY_LOWEST="Lowest"}(Vu||(Vu={})),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 mD={1:Vu.MSG_PRIORITY_HIGH,2:Vu.MSG_PRIORITY_NORMAL,3:Vu.MSG_PRIORITY_LOW,4:Vu.MSG_PRIORITY_LOWEST},fD=0,Zv=1;var Ju;(function(s){s.IN="in",s.OUT="out"})(Ju||(Ju={}));const Xv=2,qQ={};function Au(s){if(!s)return 0;if(qQ[s]===void 0){const n=new Date,g=`3${n.getHours()}`.slice(-2),I=`0${n.getMinutes()}`.slice(-2),E=`0${n.getSeconds()}`.slice(-2);qQ[s]=parseInt([g,I,E,"0001"].join(""),10),console.log(`autoIncrementIndex start index:${qQ[s]}`)}else qQ[s]+=1;return qQ[s]}class LE{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=Vu.MSG_PRIORITY_NORMAL,this._relayFlag=!1;const{clientTime:g=me.common.timeManager.getServerTimeSeconds()||0,senderTinyID:I,currentUser:E,needReadReceipt:m,isSupportExtension:D,customModerationConfigurationId:M,to:T,from:P,nick:W="",avatar:oA="",time:EA,messageControlInfo:wA,tinyID:kA,cloudCustomData:YA="",messageLifeTime:LA,messageVersion:SA=0,conversationType:OA,sequence:HA,checkResult:se=0,isPlaceMessage:oe=0,messageFlagBits:_i,receiverList:Ti,isSystemMessage:bt=!1,status:Ni=Or.SUCCESS,revokeReason:gs="",conversationSubType:De,clientSequence:Bt,protocol:UA="JSON",revokerInfo:ii={userID:"",nick:"",avatar:""},readReceiptInfo:ws={readCount:void 0,unreadCount:void 0,isPeerRead:void 0,timestamp:0},random:Gi,groupProfile:Lr,atUserList:xi,flow:ar,isRead:wt=!1,priority:_t=Vu.MSG_PRIORITY_NORMAL,onlineOnlyFlag:qu=!1,nameCard:ln="",quoteInfo:ho}=n;var cl;this.clientTime=g,this.senderTinyID=I||kA,this.needReadReceipt=m===!0||m===1,this.isSupportExtension=D===!0||D===1,this._cmConfigID=M,this.to=T,this.nick=W,this.avatar=oA,this.protocol=UA,this.random=Gi===void 0?(cl=cl||99999999,Math.round(Math.random()*cl)):Gi,this.time=EA||Math.ceil(Date.now()/1e3),this._isExcludedFromLastMessage=!!wA?.excludedFromLastMessage,this._isExcludedFromUnreadCount=!!wA?.excludedFromUnreadCount,this.isModified=!!SA,this.cloudCustomData=YA,this.messageLifeTime=LA,this.from=P||null,this.sequence=HA||0,this.conversationType=OA||Jr.CONV_C2C,this.hasRiskContent=se>1,this.version=SA,this.isPlaceMessage=oe,this.isRevoked=oe===2||_i===8,this.isSystemMessage=bt,this.readReceiptInfo=ws,this.revokeReason=gs,this.revokerInfo=ii,this._receiverList=Ti,this.conversationSubType=De,this.revoker=ii?.revoker||"",this.clientSequence=Bt||HA||0,this.status=Ni,this.atUserList=xi||[],this.flow=ar,this.isRead=wt,this.priority=_t,this._onlineOnlyFlag=qu,this.nameCard=ln,this.quoteInfo=ho,this.reInitialize(E),this._initC2CReadReceiptInfo(n),this._extractGroupInfo(Lr)}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,I;return this._relayFlag?{isValid:!0}:((n=this._elements)===null||n===void 0?void 0:n.length)>0?(I=(g=this._elements[0])===null||g===void 0?void 0:g.validateBeforeSend)===null||I===void 0?void 0:I.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:I=0}=n;this.conversationType===Jr.CONV_C2C&&this.needReadReceipt===!0&&(this.readReceiptInfo.isPeerRead=g===1,this.readReceiptInfo.timestamp=I)}_extractGroupInfo(n){if(!n)return;const{From_AccountNick:g,From_AccountHeadurl:I,MsgFrom_AccountExtraInfo:E,GroupType:m}=n,{NameCard:D}=E||{};typeof g=="string"&&(this.nick=g),typeof I=="string"&&(this.avatar=I),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 I=this.conversationType;I!==Jr.CONV_SYSTEM?(g=I===Jr.CONV_C2C?n===this.from?this.to:this.from:this.to,this.conversationID=g?`${I}${g}`:null):this.conversationID=Jr.CONV_SYSTEM}_initSequence(n){this.clientSequence===0&&n&&(this.clientSequence=Au(n)),this.sequence===0&&this.conversationType===Jr.CONV_C2C&&(this.sequence=this.clientSequence)}generateMessageID(){this.from===Jr.CONV_SYSTEM&&(this.senderTinyID="144115198244471703"),this.ID=`${this.senderTinyID}-${this.clientTime}-${this.random}`}setIsRead(n){this.isRead=n}}class pd{static parseServerPushElement(n){const{MsgContent:g={}}=n,{Data:I,Ext:E,Desc:m}=g;return new pd({data:I,description:m,extension:E})}constructor(n){this.type=kE.MSG_CUSTOM;const{data:g="",description:I="",extension:E=""}=n;this.content={data:g,description:I,extension:E}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},I=g?this.payload:this.content,{data:E,description:m,extension:D}=I;return{MsgType:this.type,MsgContent:{Data:E,Ext:D,Desc:m}}}validateBeforeSend(){const{isEmpty:n}=me.utils,g=[this.content.data,this.content.description,this.content.extension].some(I=>!n(I));return{isValid:g,error:g?null:{message:"content can not be empty"}}}}class md{static parseServerPushElement(n){const{MsgContent:g={Text:""}}=n,{Text:I}=g;return new md({text:I})}constructor(n){this.type=Rg.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||{},I=g?this.payload:this.content,{text:E}=I;return{MsgType:this.type,MsgContent:{Text:E}}}}var Om=new class{constructor(){this._elementClassMap={[kE.MSG_CUSTOM]:pd,[kE.MSG_TEXT]:md}}init(){dr.getInstance().registerApi({apiName:"createCustomMessage",context:this}),dr.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=Ju.OUT}=s,{userId:I}=me.store.get("login")||{};this._isSendByCurrentInstance({from:n,flow:g,currentUser:I})?this._updateWithSenderInfo(s):this._isMultiEndpointSyncMessage({from:n,flow:g,currentUser:I})&&(s.flow=Ju.OUT);const E=Object.assign(Object.assign({},s),{currentUser:I});return new LE(E)}createCustomMessage(s){const n=Ar(),g=this.createMessage(Object.assign(Object.assign({},s),{from:n})),I=this._elementClassMap[kE.MSG_CUSTOM];if(!g)return null;if(I){const E=new I(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)||"",I=new md({text:g}),E=Ar(),m=me.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:E}));return m.setElement(I),m}_updateWithSenderInfo(s){var n,g;const{nick:I,avatar:E,conversationType:m,to:D}=s,{userId:M,tinyID:T}=me.store.get("login")||{},P=nc.getUserProfile(M);return s.nick=I||P?.nick||"",s.avatar=E||P?.avatar||"",s.tinyID=s.tinyID||T||"",s.from=M,s.status=Or.UNSENT,s.flow=Ju.OUT,m===ba.CONV_GROUP&&(s.nameCard=(g=(n=JQ.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:I}=s;return n===I&&g===Ju.IN}_isSendByCurrentInstance(s){const{from:n,flow:g,currentUser:I}=s;return n===I&&g===Ju.OUT}};const $v={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}},fd={HonorImportance:{range:["LOW","NORMAL"],defaultValue:void 0},MeizuNotifyType:{range:[0,1],defaultValue:void 0}},yD={enableIOSBackgroundNotification:{range:[!0,!1],defaultValue:!1},interruptionLevel:{range:["passive","active","time-sensitive","critical"],defaultValue:"active"}};function AR(s,n){return Object.keys(n).forEach(g=>{const{range:I,defaultValue:E}=n[g];s[g]=I.includes(s[g])?s[g]:E}),s}function KQ(s){const n=s.lastIndexOf(".");return n===-1?s:s.slice(0,n)}function eR(s){const{androidInfo:n={},androidOPPOChannelID:g=""}=s,I=n.OPPOChannelID||g,E=AR(n,fd),{sound:m="",FCMChannelID:D=""}=E,M=yo(E,["sound","FCMChannelID"]);return Object.assign(Object.assign({},M),{Sound:KQ(m),OPPOChannelID:I,GoogleChannelID:D})}function tR(s){const{apnsInfo:n={},ignoreIOSBadge:g=!1,disableVoipPush:I}=s,E=AR(n,yD),{ignoreIOSBadge:m,disableVoipPush:D,enableIOSBackgroundNotification:M}=E,T=yo(E,["ignoreIOSBadge","disableVoipPush","enableIOSBackgroundNotification"]),P=m===!0||g===!0?1:0;let W;return r(I)||(W=I===!1?1:0),r(D)||(W=D===!1?1:0),Object.assign(Object.assign({},T),{BadgeMode:P,IsVoipPush:W,ContentAvailable:M?1:0})}function DD(s){return me.utils.isPlainObject(s)?{PushFlag:s.disablePush===!0?1:0,Title:s.title||"",Desc:s.description||"",Ext:s.extension||"",ApnsInfo:tR(s),AndroidInfo:eR(s)}:$v}function Pm(s){const{From_AccountHeadurl:n,From_AccountNick:g,IsNeedReadReceipt:I,IsPeerRead:E,IsSyncMsg:m,MsgBody:D,MsgClientTime:M,MsgLifeTime:T,MsgRandom:P,MsgSeq:W,MsgTimeStamp:oA,SendMsgControl:EA,SupportMessageExtension:wA,TinyId:kA,MsgCheckResult:YA,CloudCustomData:LA,MsgVersion:SA,MsgFlagBits:OA,RevokerInfo:HA,InnerSdkCustomData:se}=s;let oe,{From_Account:_i,To_Account:Ti}=s;if(m===1){const bt=Ti;Ti=_i,_i=bt}if(HA){const{Reason:bt,Revoker_Account:Ni,Revoker_FromUin:gs}=HA;oe={reason:bt,revoker:Ni,revokerFromUin:gs,userID:Ni}}return{from:_i,avatar:n,nick:g,needReadReceipt:I===1,isSyncMessage:m,clientTime:M,messageLifeTime:T,random:P,sequence:W,time:oA,messageControlInfo:{excludedFromLastMessage:EA?.NoLastMsg===1,excludedFromUnreadCount:EA?.NoUnread===1},isSupportExtension:wA,to:Ti,tinyID:kA,checkResult:YA,cloudCustomData:LA,revokerInfo:oe,messageVersion:SA,messageFlagBits:OA,readReceiptSentByPeer:E,elements:hC(D),onlineOnlyFlag:T===0,quoteInfo:jQ(se)}}function xm(s){const{From_Account:n,MsgBody:g,MsgClientTime:I,MsgRandom:E,MsgSeq:m,MsgTimeStamp:D,To_Account:M,MsgVersion:T,CloudCustomData:P,MsgCheckResult:W}=s;return{from:n,clientTime:I,random:E,sequence:m,time:D,to:M,elements:hC(g),messageVersion:T,cloudCustomData:P,checkResult:W}}function SD(s){const{ClientSeq:n,From_Account:g,GroupInfo:I,MsgBody:E,MsgClientTime:m,MsgRandom:D,MsgSeq:M,MsgTimeStamp:T,SendMsgControl:P,SupportMessageExtension:W,TinyId:oA,CloudCustomData:EA,MsgVersion:wA,MsgCheckResult:kA,NeedReadReceipt:YA,IsPlaceMsg:LA,RevokerInfo:SA,GroupAtInfo:OA,OnlineOnlyFlag:HA,InnerSdkCustomData:se}=s;let oe,_i=Vu.MSG_PRIORITY_NORMAL;if(Object.keys(mD).includes(String(s.MsgPriority))&&(_i=mD[s.MsgPriority]),SA){const{Reason:bt,Revoker_Account:Ni,Revoker_FromUin:gs}=SA;oe={reason:bt,revoker:Ni,revokerFromUin:gs,userID:Ni}}const Ti=function(bt){const Ni=[];return Array.isArray(bt)&&bt.forEach(gs=>{gs.GroupAtAllFlag===fD?Ni.push(gs.GroupAt_Account):gs.GroupAtAllFlag===Zv&&Ni.push(ko.MSG_AT_ALL)}),Ni}(OA);return{clientSequence:n,from:g,groupProfile:I,clientTime:m,priority:_i,random:D,sequence:M,time:T,messageControlInfo:{excludedFromLastMessage:P?.NoLastMsg===1,excludedFromUnreadCount:P?.NoUnread===1},isSupportExtension:W,tinyID:oA,cloudCustomData:EA,messageVersion:wA,checkResult:kA,needReadReceipt:YA,isPlaceMessage:LA,revokerInfo:oe,atUserList:Ti,elements:hC(E),to:hT(s),onlineOnlyFlag:HA===1,quoteInfo:jQ(se)}}function hT(s){const{utils:{isEmpty:n},constants:{IS_TOPIC_MESSAGE:g}}=me,{ToGroupId:I,GroupInfo:{MillionGroupFlag:E=0,TopicId:m}={}}=s;return E!==g||n(m)?I:m}function hC(s){if(!s)return null;if(Array.isArray(s))return s.map(g=>{const I=me.message.messageFactory.getElementClass(g.MsgType);return I?.parseServerPushElement(g)});const n=me.message.messageFactory.getElementClass(s.MsgType);return n?.parseServerPushElement(s)}function MD(s){const{From_Account:n,MsgBody:g,MsgClientTime:I,MsgRandom:E,MsgSeq:m,MsgTimeStamp:D,GroupId:M,TopicId:T,MsgVersion:P,CloudCustomData:W,MsgCheckResult:oA}=s;return{from:n,clientTime:I,random:E,sequence:m,time:D,groupID:M,topicID:T,elements:hC(g),messageVersion:P,cloudCustomData:W,checkResult:oA}}function jQ(s){const{utils:{isString:n,safeStringify:g},ssoLog:I}=me;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 I.debug("_parseServerQuoteInfo",g(E)),null}}function WQ({conversationUpdateFields:s,message:n}){const{conversationID:g,conversationType:I,conversationSubType:E,flow:m,_isExcludedFromUnreadCount:D,_isExcludedFromLastMessage:M}=n,T=M?"":YQ(n),P=!D&&m===Ju.IN;s.has(g)?(s.get(g).lastMessage=T,P&&s.get(g).unreadCount++):s.set(g,{conversationID:g,type:I,subType:E,unreadCount:P?1:0,lastMessage:T})}function hB(s){return s.filter(n=>{const g=!vs(n?._elements),I=n?.isPlaceMessage===1;return g||me.ssoLog.error("emptyMessageBody",`from:${n.from} to:${n.to} sequence:${n.sequence}`),g&&!I})}function BB(s){const{messageDataHandler:n}=me.message;return!n.isInMessageList(s)&&!n.isMessageSentByCurrentInstance(s)}var iR=Object.freeze({__proto__:null,autoIncrementIndex:Au,createAndroidPushInfo:eR,createApnsPushInfo:tR,createOfflinePushInfo:DD,filterValidMessages:hB,getAndroidSoundName:KQ,parseServerGroupMessage:SD,parseServerPushC2CModifyMessage:xm,parseServerPushGroupModifyMessage:MD,parseServerPushMessage:Pm,parseServerPushMessageElement:hC,shouldStoreMessage:BB,updateConversationFields:WQ});const{isPlainObject:oR}=me.utils;function zQ(s,n={}){const{onlineUserOnly:g,messageControlInfo:I}=n;let{offlinePushInfo:E}=n;s.conversationType===Jr.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(I&&oR(I)){const{excludedFromUnreadCount:M,excludedFromLastMessage:T,excludedFromContentModeration:P}=I;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 vD(s){const{webhookInfo:{disableCloudMessagePreHook:n=!1,disableCloudMessagePostHook:g=!1}={}}=s||{};if(!n&&!g)return;const I=[];return n&&I.push("ForbidBeforeSendMsgCallback"),g&&I.push("ForbidAfterSendMsgCallback"),I}function Bh(s,n){return pA(this,void 0,void 0,function*(){const g=s.conversationType===Jr.CONV_GROUP?function(E,m){var D;const M=zQ(E,m),{onlineUserOnly:T,cloudCustomData:P,messageControlInfo:W,offlinePushInfo:oA}=M,EA=JSON.parse(JSON.stringify(E.transformElementsToServerFormat()));let wA;return p(E._receiverList)&&E._receiverList.length>0&&(wA=E._receiverList,E._receiverList.length>50&&(wA=E._receiverList.slice(0,50),console.warn("ReceiverListLimit"))),{servcmd:"group_open_http_svc.send_group_msg",data:{From_Account:(D=me.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:DD(oA),SendMsgControl:T?void 0:W,NeedReadReceipt:E.needReadReceipt===!0?1:0,To_Account:wA,SupportMessageExtension:E.isSupportExtension===!0?1:0,IsRelayMsg:E._relayFlag===!0?1:0,CustomModerationConfigID:E._cmConfigID,ForbidCallbackControl:vD(m),InnerSdkCustomData:pB(E)}}}(s,n):function(E,m){var D;const M=zQ(E,m),{onlineUserOnly:T,cloudCustomData:P,messageControlInfo:W,offlinePushInfo:oA}=M,EA=T===!0?0:void 0,wA=JSON.parse(JSON.stringify(E.transformElementsToServerFormat()));return{servcmd:"openim.sendmsg",data:{From_Account:(D=me.store.get("login"))===null||D===void 0?void 0:D.userId,To_Account:E.to,MsgBody:wA,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:DD(oA),ForbidCallbackControl:vD(m),InnerSdkCustomData:pB(E)}}}(s,n),I=yield ag(g);return I?{time:I.MsgTime,messageDropReason:I.MsgDropReason,sequence:I.MsgSeq}:null})}function Qh(s){return pA(this,void 0,void 0,function*(){const{from:n,to:g,version:I=0,sequence:E,random:m,time:D,type:M,cloudCustomData:T}=s,P={From_Account:n,To_Account:g,MsgVersion:I,MsgSeq:E,MsgRandom:m,MsgTime:D,MsgType:M,MsgBody:s.transformElementsToServerFormat(),CloudCustomData:T},W=yield ag({servcmd:"openim.modify_c2c_msg",data:P});if(W){const{MsgBody:oA,MsgVersion:EA,CloudCustomData:wA}=W;return{elements:hC(oA),messageVersion:EA,cloudCustomData:wA}}})}function QB(s){return pA(this,void 0,void 0,function*(){const{to:n,version:g=0,sequence:I,cloudCustomData:E}=s,m={GroupId:n,MsgVersion:g,MsgSeq:I,MsgBody:s.transformElementsToServerFormat(),CloudCustomData:E},D=yield ag({servcmd:"openim.modify_group_msg",data:m});if(D){const{MsgBody:M,MsgVersion:T,CloudCustomData:P}=D;return{elements:hC(M),messageVersion:T,cloudCustomData:P}}})}function ph(s){return pA(this,void 0,void 0,function*(){const{groupID:n,count:g,messageSequence:I,messageSequenceList:E,getType:m}=s,D={GroupId:n,ReqMsgNumber:g,WithRecalledMsg:1,Version:1,GetType:m};return I&&(D.ReqMsgSeq=I),p(E)&&E.length>0&&(D.ReqMsgSeqList=E),yield ag({servcmd:"group_open_http_svc.group_msg_get",data:D})})}function Ym(s){return pA(this,void 0,void 0,function*(){const{peerAccount:n,count:g,lastMessageTime:I,messageKey:E,direction:m}=s;return ag({servcmd:"openim.getroammsg",data:{Peer_Account:n,MaxCnt:g,WithRecalledMsg:1,LastMsgTime:I,MsgKey:E,GetDirection:m}})})}function pB(s){if(me.utils.isObject(s.quoteInfo)){const{msgID:n,messageSequence:g,messageTime:I}=s.quoteInfo;return JSON.stringify({businessQuote:{messageID:n,messageSequence:g,messageTime:I}})}}var RD=Object.freeze({__proto__:null,createMessagePackOptions:zQ,generateForbidCallbackControl:vD,getC2CRoamingMessagesByAnchor:Ym,getGroupRoamingMessagesByAnchor:ph,getRoamingMessages:function(s){return pA(this,void 0,void 0,function*(){const{peerAccount:n,count:g,lastMessageTime:I,messageKey:E}=s;return(yield ag({servcmd:"openim.getroammsg",data:{Peer_Account:n,MaxCnt:g||15,LastMsgTime:I||0,MsgKey:E,GetDirection:0,WithRecalledMsg:1}}))||[]})},modifyC2CMessage:Qh,modifyGroupMessage:QB,sendMessage:Bh});const{isPlainObject:BT}=me.utils,{MSG_AUDIO:wD,MSG_FILE:_D,MSG_IMAGE:sR,MSG_VIDEO:nR,MSG_MERGER:rR}=ko;class Vm{constructor(){this._sendProtocolMap=new Map}init(){dr.getInstance().registerApi({apiName:"sendMessage",context:this,matcher:n=>![wD,_D,sR,nR,rR].includes(n[0].type)})}registerSendProtocol(n,g,I){this._sendProtocolMap.set(n,g.bind(I))}sendMessage(n,g){return pA(this,void 0,void 0,function*(){const{TOTAL_COUNT:I,SEND_COST:E,SUCCESS_COUNT:m,FAILED_COUNT:D}=nr;if(!(n instanceof LE))throw new as({code:ua.MSG_INSTANCE_REQUIRED});const M=n.validateBeforeSend();if(!M.isValid){const{code:W,message:oA=""}=M.error||{};throw new as({code:W,message:oA})}this._reportMessageSendQuality({name:I,message:n});let T=!1;const{messageDataHandler:P}=me.message||{};try{const{messageControlInfo:W}=g||{};let oA=null;P.addRandomOfSentMessage(n.random);const EA=Date.now(),wA=this._getSendProtocol(n);if(n.conversationType===Jr.CONV_C2C?(T=g?.onlineUserOnly===!0,oA=yield wA(n,g)):n.conversationType===Jr.CONV_GROUP&&(yield this._validateBeforeSendGroupMessage(n),oA=yield wA(n,g)),oA){const{messageDropReason:kA,sequence:YA,time:LA}=oA;if(this._updateNickAndAvatarOfSentMessageByMe(n),kA&&this._logRateLimitInfo(n,YA,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&&(me.ssoLog.debug("sendMessage",`sendMessage resend ok. ID:${SA.ID}`),P.deleteConversationMessage(SA))}return n.status=Or.SUCCESS,n.time=LA,n.conversationType===Jr.CONV_GROUP&&(n.sequence=YA),T?n._onlineOnlyFlag=!0:(P.storeConversationMessage(n),this._applySentMessageControlInfo(n,W),this._emitOnlineMessageSent(n)),n.type===Rg.MSG_STREAM?{code:0,data:{message:n,streamMessageID:oA.streamMessageID}}:{code:0,data:{message:n}}}}catch(W){n.status=Or.FAIL,P.removeRandomOfSentMessage(n.random);let{errorCode:oA}=W||{},EA=W?.errorInfo||W?.message||"";throw this._hasRiskContent(oA)&&(n.hasRiskContent=!0),T||this._isRejectedByRestApi(oA)||P.storeConversationMessage(n),this._reportMessageSendQuality({name:D,message:n,error:W}),new as({code:oA,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:I,conversationType:E}=n,m=jc(I)?so.TOPIC_NEW_MESSAGE:so.NEW_MESSAGE;me.notificationCenter.emitInnerEvent(m,{result:{conversationUpdateFieldList:[{conversationID:I,type:E,message:n,lastMessage:g,unreadCount:0}]}})}_applySentMessageControlInfo(n,g){g&&BT(g)&&(g.excludedFromLastMessage===!0&&(n._isExcludedFromLastMessage=!0),g.excludedFromUnreadCount===!0&&(n._isExcludedFromUnreadCount=!0))}_logRateLimitInfo(n,g,I){const E=`from:${n.from} to:${n.to} sequence:${g} messageDropReason:${I}`;me.ssoLog.warn("messageDropReason",E)}_updateNickAndAvatarOfSentMessageByMe(n){const{messageDataHandler:g}=me.message||{};let I=!1;const{conversationID:E}=n,m=g.getLatestMsgSentByMe(E);if(m){const{nick:D,avatar:M}=m;D===n.nick&&M===n.avatar||(I=!0),I&&g.updateNickAndAvatarOfSentMessage({conversationID:E,latestNick:n.nick,latestAvatar:n.avatar,isSentByMe:!0})}}_validateBeforeSendGroupMessage(n){return pA(this,void 0,void 0,function*(){var g,I,E;const{to:m,from:D}=n;let M=m,T=JQ.getGroup(M);if(zr({groupID:M})&&T?.isSupportTopic)throw new as({code:ua.MSG_SEND_GRP_WITH_TOPIC_FAIL});if(jc(m)&&([M]=m.split(oa.TOPIC),T=JQ.getGroup(M)),!T&&typeof((g=dr.getInstance().getApiMap())===null||g===void 0?void 0:g.getGroupProfile)=="function"){const P=yield dr.getInstance().getApiMap().getGroupProfile({groupID:M});if(((E=(I=P?.data)===null||I===void 0?void 0:I.group)===null||E===void 0?void 0:E.type)===ko.GRP_AVCHATROOM){const W=ss({code:ua.MSG_SEND_FAIL_NOT_IN_AV,replacement1:D,replacement2:M});throw new as({code:ua.MSG_SEND_FAIL_NOT_IN_AV,message:W})}}return!0})}_reportMessageSendQuality(n){me.notificationCenter.emitInnerEvent(so.QUALITY_STAT,{label:oI.MESSAGE_SEND_SUCCESS_RATE,data:n})}_getSendProtocol(n){return this._sendProtocolMap.get(n.type)||Bh}}var QT=new class{constructor(){this._sparseMessagesByConversation=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new Set}init(){me.notificationCenter.subscribeInnerEvent(so.LOGOUT,this._reset,this),me.notificationCenter.subscribeInnerEvent(so.DESTROY,this._dispose,this)}get _messagesByConversation(){return HQ.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 I=this._getUniqueIdOfMessage(s);return this._messagesByConversation.get(g).set(I,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),I=this._messagesByConversation.get(s.conversationID);if(I?.has(g)){const E=I?.get(g);if(!n||E?.isModified===!0)return!0}return!1}deleteConversationMessage(s){var n;const{conversationID:g=""}=s,I=this._getUniqueIdOfMessage(s);this._messagesByConversation.has(g)&&((n=this._messagesByConversation.get(g))===null||n===void 0||n.delete(I))}modifyConversationMessage(s,n){var g;if(!this._messagesByConversation.has(s)&&!this._sparseMessagesByConversation.has(s))return{isUpdated:!1,message:null};const I=this._getUniqueIdOfMessage(n),E=this._getMessageFromLocalMessage(s,I);if(E){const{messageVersion:m,elements:D,cloudCustomData:M,checkResult:T=0}=n,P=T>1;if(me.ssoLog.debug("modifyConversationMessage",`conversationToMessageMap modifyConversationMessage localVersion:${E.version} remoteVersion:${m}`),E.versionE.ID===s)||null,n)break;if(!n){const I=Array.from(this._sparseMessagesByConversation.values());for(const E of I)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:I}){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 HQ.updateMessage(s,[M],{isRevoked:!0,revoker:I,operation:fc.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=I,m}}_findMessageBySequenceAndRandom({messageList:s,sequence:n,random:g}){for(let I=0;I0){const D=new Map([...E,...m.entries()]);this._messagesByConversation.set(g,D),this._updateLatestMessageSentByMe(g),this._updateLatestMessageSentByPeer(g)}return I}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 I=this._sparseMessagesByConversation.get(n);for(let E=0;E=0;I--)if(g[I].flow==="out"){this._setLatestMsgSentByMe(s,g[I]);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 I=g.length-1;I>=0;I--)if(g[I].flow==="in"){this._setLatestMsgSentByPeer(s,g[I]);break}}}_getUniqueIdOfMessage(s){const{from:n,to:g,random:I,sequence:E,time:m}=s;return`${n}-${g}-${I}-${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:I,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:oA}=T;oA===M&&(P!==I&&(T.nick=I),W!==g&&(T.avatar=g))})}isInMessageList(s){var n;const{conversationID:g}=s;if(!g||!this._messagesByConversation.has(g))return!1;const I=this._getUniqueIdOfMessage(s);return(n=this._messagesByConversation.get(g))===null||n===void 0?void 0:n.has(I)}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(),me.notificationCenter.unSubscribeInnerEvent(so.LOGOUT,this._reset,this),me.notificationCenter.unSubscribeInnerEvent(so.DESTROY,this._dispose,this)}};function Jm(s,n){const g=CB.getConversation(s);if(g?.lastMessage){const{lastMessage:I}=g,{lastTime:E,lastSequence:m,version:D}=I,{time:M,sequence:T,messageVersion:P,elements:W,cloudCustomData:oA}=n;E===M&&m===T&&D!==P&&(I.type=W[0].type,I.payload=W[0].content,I.messageForShow=Wc(I.type,I.payload),I.cloudCustomData=oA,I.version=P,CB.updateConversation(s,{lastMessage:I}))}}class aR{init(){dr.getInstance().registerApi({apiName:"modifyMessage",context:this})}modifyMessage(n){return pA(this,void 0,void 0,function*(){const{to:g,payload:I,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=I)}try{let W=null,oA=null;if(m===Jr.CONV_C2C?W=yield Qh(n):m===Jr.CONV_GROUP&&(W=yield QB(n)),W){let EA=`${m}${g}`;return g===Ar()&&m===Jr.CONV_C2C&&(EA=`${m}${T}`),oA={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(oA),{code:0,data:{message:n},successLog:{message:`to:${g}`}}}}catch(W){const{errorCode:oA}=W||{};throw new as({functionName:"modifyMessage",code:oA,moreMessage:`to:${g}`})}})}_handleModifyMessageSuccess(n){const{conversationID:g}=n,{isUpdated:I,message:E}=me.message.messageDataHandler.modifyConversationMessage(g,n);I===!0&&me.notificationCenter.emitOuterEvent(yr.MESSAGE_MODIFIED,{name:yr.MESSAGE_MODIFIED,data:[E]}),me.notificationCenter.emitInnerEvent(so.MESSAGE_MODIFIED,{conversationID:g,message:E}),Jm(g,n)}_canModifyMessageElement(n){return[kE.MSG_TEXT,kE.MSG_CUSTOM,kE.MSG_LOCATION,kE.MSG_FACE].includes(n)}}class mh{init(){const{notificationCenter:n}=me,{InnerEventSubType:g}=n;Rs.getInstance().registerWorkflowStep(Pt.RECEIVE_C2C_NEW_MESSAGE,Ht.HANDLE_C2C_NEW_MESSAGE,this._handleC2CMessagePush,this),Rs.getInstance().registerWorkflowStep(Pt.RECEIVE_C2C_NEW_MESSAGE,Ht.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterReceiveNewMessage,this),Rs.getInstance().registerWorkflowStep(Pt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Ht.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){Rs.getInstance().executeWorkflow(Pt.RECEIVE_C2C_NEW_MESSAGE,n)}_handleC2CMessagePush(n){const g=n.data||{},{messageDataHandler:I}=me.message||{},E=[],m=new Map;return g.C2cMsgArray.forEach(D=>{const M=this._generateC2CMessage(D);this._updateMessageProfile(M);let T=M.isModified===1;I.isMessageSentByCurrentInstance(M)?M.isModified=T:T=!1,M._onlineOnlyFlag?I.isMessageSentByCurrentInstance(M)||E.push(M):BB(M)&&(I.storeConversationMessage(M)&&WQ({conversationUpdateFields:m,message:M}),I.isMessageSentByCurrentInstance(M)&&!T||E.push(M))}),{conversationUpdateFieldList:[...m.values()],messages:E}}_emitMessageEventsAfterReceiveNewMessage(n){var g;const{messages:I=[]}=((g=n.result)===null||g===void 0?void 0:g[Ht.HANDLE_C2C_NEW_MESSAGE])||{};this._emitMessageEvents(I)}_emitMessageEventsAfterSyncUnreadMessage(n){var g;const{messages:I=[]}=((g=n.result)===null||g===void 0?void 0:g[Ht.UNREAD_MESSAGE_SYNC])||{};this._emitMessageEvents(I)}_emitMessageEvents(n){const g=n?.filter(E=>E?.isModified===!0)||[];g.length>0&&me.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:g});const I=n?.filter(E=>!E?.isModified);I.length>0&&me.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:I})}_generateC2CMessage(n){const g=Jr.CONV_C2C,I=Pm(n),E=me.message.messageFactory.createMessage(Object.assign(Object.assign({},I),{conversationType:g,flow:Ju.IN})),{elements:m}=I;return E.setElement(m),E}_updateMessageProfile(n){var g;const{messageDataHandler:I}=me.message||{},E=(g=me.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=I.getLatestMsgSentByPeer(T);if(P){const{nick:W,avatar:oA}=P;r(D)||r(M)?(n.nick=l(W)?W:n.nick,n.avatar=l(oA)?oA:n.avatar):D===W&&M===oA||(I.updateNickAndAvatarOfSentMessage({conversationID:T,latestNick:D,latestAvatar:M,isSentByMe:!1}),this._updateConversationUserProfile({conversationID:T,nick:D,avatar:M}))}}else{const P=I.getLatestMsgSentByMe(T);!P||D===P.nick&&M===P.avatar||I.updateNickAndAvatarOfSentMessage({conversationID:T,latestNick:D,latestAvatar:M,isSentByMe:!0})}}_updateConversationUserProfile(n){const{conversationID:g,nick:I,avatar:E}=n,m=CB.getConversation(g),{userProfile:D={}}=m||{};D.avatar===E&&D.nick===I||CB.updateConversation(g,{userProfile:Object.assign(Object.assign({},D),{nick:I,avatar:E})})}_updateMessageListDueToModify(n){const{conversationID:g}=n,{isUpdated:I,message:E}=me.message.messageDataHandler.modifyConversationMessage(g,n);I===!0&&me.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[E]}),me.notificationCenter.emitInnerEvent("ModifyMessageSuccess",n),Jm(g,n)}_handleC2CMessageModify(n){n.C2cMsgModNotifys.forEach(g=>{var I;const E=Jr.CONV_C2C;let m=xm(g);const{to:D,from:M}=m;let T=`${E}${D}`;D===((I=me.store.get("login"))===null||I===void 0?void 0:I.userId)&&(T=`${E}${M}`),m=Object.assign({conversationType:E,conversationID:T},m),this._updateMessageListDueToModify(m)})}_dispose(){const{notificationCenter:n}=me,{InnerEventSubType:g}=n;me.notificationCenter.unSubscribeInnerEvent(so.MESSAGE_PUSH,g.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),me.notificationCenter.unSubscribeInnerEvent(so.MESSAGE_PUSH,g.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),me.notificationCenter.unSubscribeInnerEvent(so.DESTROY,this._dispose,this)}}class fh{init(){const{notificationCenter:n}=me,{InnerEventSubType:g}=n;Rs.getInstance().registerWorkflowStep(Pt.RECEIVE_GROUP_NEW_MESSAGE,Ht.HANDLE_GROUP_NEW_MESSAGE,this._handleGroupMessagePush,this),Rs.getInstance().registerWorkflowStep(Pt.RECEIVE_GROUP_NEW_MESSAGE,Ht.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)&&Rs.getInstance().executeWorkflow(Pt.RECEIVE_GROUP_NEW_MESSAGE,n)}_handleGroupMessagePush(n){const g=n.data||{},{messageDataHandler:I}=me.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;I.isMessageSentByCurrentInstance(T)?T.isModified=P:P=!1,T._onlineOnlyFlag?I.isMessageSentByCurrentInstance(T)||E.push(T):BB(T)&&I.storeConversationMessage(T)&&(E.push(T),WQ({conversationUpdateFields:m,message:T}))}),{conversationUpdateFieldList:[...m.values()],messages:E}}_emitMessageEvents(n){var g;const{messages:I}=((g=n.result)===null||g===void 0?void 0:g[Ht.HANDLE_GROUP_NEW_MESSAGE])||{},E=I?.filter(D=>D?.isModified===!0)||[];E.length>0&&me.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:E});const m=I?.filter(D=>!D?.isModified)||[];m.length>0&&me.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:m})}_generateGroupMessage(n){const g=Jr.CONV_GROUP,I=SD(n),E=me.message.messageFactory.createMessage(Object.assign(Object.assign({},I),{conversationType:g,flow:Ju.IN})),{elements:m}=I;return E.setElement(m),E}updateMessageProfile(n){var g;const{messageDataHandler:I}=me.message||{},E=(g=me.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=I.getLatestMsgSentByMe(T);!W||D===W.nick&&M===W.avatar||I.updateNickAndAvatarOfSentMessage({conversationID:T,latestNick:D,latestAvatar:M,isSentByMe:!0})}else if(m===ko.CONV_SYSTEM){const{operationType:W,memberInfoList:oA,operatorInfo:EA}=P;let wA={};if(vs(oA)?vs(EA)||(wA=EA):[_g.JOINED,_g.KICKED,_g.ADMIN_SET,_g.ADMIN_CANCELED].includes(W)&&(wA=Object.assign({},oA[0])),!vs(wA)){const{nick:kA="",avatar:YA=""}=wA;n.nick=kA,n.avatar=YA}}}_updateMessageListDueToModify(n){const{conversationID:g}=n,{isUpdated:I,message:E}=me.message.messageDataHandler.modifyConversationMessage(g,n);I===!0&&me.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[E]}),Jm(g,n)}_handleGroupMessageModify(n){n.GroupMsgModNotifys.forEach(g=>{const I=Jr.CONV_GROUP;let E=MD(g);const{topicID:m,groupID:D}=E,M=m||D,T=`${I}${M}`;E=Object.assign({conversationType:I,conversationID:T,to:M},E),this._updateMessageListDueToModify(E)})}_dispose(){const{notificationCenter:n}=me,{InnerEventSubType:{GROUP_REALTIME_MESSAGE:g,GROUP_MESSAGE_MODIFIED:I}}=n;n.unSubscribeInnerEvent(so.MESSAGE_PUSH,g,this._handleGroupMessagePush,this),n.unSubscribeInnerEvent(so.MESSAGE_PUSH,I,this._handleGroupMessageModify,this),n.unSubscribeInnerEvent(so.DESTROY,this._dispose,this)}_canExecuteReceiverNewMessageWorkFlow(n){var g,I;const{GroupId:E,GroupType:m}=((I=(g=n?.GroupMsgArray)===null||g===void 0?void 0:g[0])===null||I===void 0?void 0:I.GroupInfo)||{},D=m===ka.GRP_AVCHATROOM;return!(!JQ.getGroup(E)&&D)}}var TD=new class{constructor(){this.c2cMessageReceiver=new mh,this.groupMessageReceiver=new fh}init(){this.c2cMessageReceiver.init(),this.groupMessageReceiver.init()}};const gR={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)}}},pT={createCustomMessage:!0,sendMessage:!0,modifyMessage:!0};var mT=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:I,sequence:E,messageSequenceList:m,shouldMarkCompleted:D=!1,getType:M}=s,T=n.replace(ba.CONV_GROUP,""),P=[];let W=E;if(I===Hc.BACKWARD){if(typeof E!="number")return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};W=E+g-1}const oA=yield ph({groupID:T,count:g,messageSequence:W,messageSequenceList:m,getType:M});if(oA){const{RspMsgList:EA=[],NextReqMsgSeq:wA=0,IsFinished:kA,InvisibleMsgSeq:YA}=oA,LA=`groupID:${T} sequence:${E} reqSeq:${W} direction:${I} complete:${kA} nextSequence:${wA} remoteMsgCount:${EA.length} invisibleSequenceList:${YA}`,SA=[];for(let se=0;se=E),OA&&D&&this.completedHistoryConversations.add(n);const HA=hB(SA);return me.ssoLog.info("getGroupRoamingMessagesByAnchor",LA),{messageList:HA,invisibleSequenceList:YA,nextReqMessageIDFromServer:wA,hasNoMoreHistoryMessage:OA,serverGroupTipList:P}}}catch(n){const{errorCode:g,errorInfo:I}=n||{};throw new as({code:g,message:I})}})}clearHistoryMessageListFetchAnchors(s){this._historyMessageListFetchAnchors.delete(s)}isHistoryMessageFetchCompleted(s){return this.completedHistoryConversations.has(s)}_parseMessage(s){var n;const g=ba.CONV_GROUP;s.Event===4&&(s.MsgBody.MsgType=ko.MSG_GRP_TIP);const I=SD(s),E=Om.createMessage(Object.assign(Object.assign({},I),{conversationType:g,flow:"in"}));return dB(((n=I.elements)===null||n===void 0?void 0:n.content)||{},E),E.setElement(I.elements),E}getC2CRoamingMessagesByAnchor(s){return pA(this,void 0,void 0,function*(){var n;try{const{conversationID:g,count:I,messageID:E,time:m,direction:D,shouldMarkCompleted:M=!1}=s;let T=m,P="";if(!m){const EA=E?me.message.messageDataHandler.findMessage(E):null;if(T=EA?.time||0,E&&this._historyMessageListFetchAnchors.has(g)){const wA=this._historyMessageListFetchAnchors.get(g);T=wA.lastMessageTime,P=wA.messageKey}}const W=g.replace(ba.CONV_C2C,""),oA=yield Ym({count:I,lastMessageTime:T,messageKey:P,peerAccount:W,direction:D});if(oA){const{MsgList:EA=[],Complete:wA,MsgKey:kA,LastMsgTime:YA}=oA;this._historyMessageListFetchAnchors.set(g,{messageKey:kA,lastMessageTime:YA});const LA=[];for(let se=0;se{const{tag:E,value:m}=I;E&&E.indexOf(GD)>-1?g.profileCustomField.push({key:E,value:m}):yd.has(E)&&(g[yd.get(E)]=m)}),Object.assign(Object.assign({},Hm),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!==bD&&n.push({tag:Fl[g.toUpperCase()],value:s[g]})}),s.profileCustomField&&p(s.profileCustomField)&&s.profileCustomField.forEach(g=>{n.push({tag:g.key,value:g.value})}),n}normalizeProfileFields(s){const n={},g=[];return s.forEach(I=>{const{tag:E,value:m}=I;if(E&&E.indexOf(GD)>-1&&g.push({key:E,value:m}),yd.has(E)&&m!==void 0){const D=yd.get(E);n[D]=m}}),g.length>0&&(n.profileCustomField=g),n}};const{generateProtocolData:lR}=me.common;function IR(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 I=lR({servcmd:n,data:g}),E=`${I.head.seq}${n}`,m=yield me.channel.sendPacket(I,{requestId:E});if(m)return function(D){const{ActionStatus:M,ErrorCode:T,ErrorDisplay:P,ErrorInfo:W,UserProfileItem:oA}=D,EA=[];return oA.map(wA=>{const{To_Account:kA,CustomSequence:YA,ResultCode:LA,ResultInfo:SA,StandardSequence:OA,ProfileItem:HA}=wA,se=Hu.parseProfileItem(HA);EA.push({userId:kA,customSequence:YA,resultCode:LA,resultInfo:SA,standardSequence:OA,profileItem:se})}),{actionStatus:M,errorCode:T,errorDisplay:P,errorInfo:W,userProfile:EA}}(m)})}function UE(s){return nc.getFriendMap().has(s)}const{isEmpty:kD}=me.utils;class qm{constructor(){this._strangerProfileMap=new Map}init(){dr.getInstance().registerApi({apiName:"getMyProfile",context:this}),dr.getInstance().registerApi({apiName:"getUserProfile",context:this}),dr.getInstance().registerApi({apiName:"updateMyProfile",context:this}),this.createProfile=Hu.createProfile.bind(Hu);const{notificationCenter:n}=me;Rs.getInstance().registerWorkflowStep(Pt.SYNC_SERVER_INFO_AFTER_LOGIN,Ht.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 IR([n]);if(g){const I=this._handleProfileFormResponse(g)[0];return nc.getUserProfileMap().set(n,I),{code:0,data:I}}}catch(n){const{errorCode:g,errorInfo:I}=n;throw new as({functionName:"getMyProfile",code:g,message:I})}})}getUserProfile(n){return pA(this,void 0,void 0,function*(){try{let{userIDList:g}=n;const{userIdListToRequest:I,profileFromCache:E}=this._filterRequestAndCacheUsers(g);if(I.length===0)return{code:0,data:E,successLog:{message:`userIDList.length:${g.length}`}};I.length>cR&&(me.ssoLog.warn("getUserProfile","userIdListToRequest.length > 1000"),I.length=cR);const{data:m,error:D}=yield this._batchFetchUserProfiles(I),M=I.length,T=m.length,P=M-T;if(E.length===0&&M===P&&!kD(D))throw D;if(p(m))return m.forEach(oA=>{UE(oA.userID)?nc.getUserProfileMap().set(oA.userID,oA):this._strangerProfileMap.set(oA.userID,oA)}),{code:0,data:m.concat(E),successLog:{message:`getUserProfile query:${M} success:${T} fail:${P} from cache:${E.length}`}}}catch(g){throw new as(g)}})}getMyProfileCacheThenServer(){return pA(this,void 0,void 0,function*(){const n=Ar(),g=nc.getUserProfileMap().has(n);return g?{code:0,data:g}:this.getMyProfile()})}updateMyProfile(n){return pA(this,void 0,void 0,function*(){const g=Ar(),I={};for(const m in n)n[m]!==void 0&&(I[m]=n[m]);const E=Hu.convertParamsToProfile(I);try{yield function(P){return pA(this,void 0,void 0,function*(){const W="profile.portrait_set",oA=lR({servcmd:W,data:P}),EA=`${oA.head.seq}${W}`,wA=yield me.channel.sendPacket(oA,{requestId:EA});if(wA){const{ActionStatus:kA,ErrorCode:YA,ErrorDisplay:LA,ErrorInfo:SA}=wA;return{actionStatus:kA,errorCode:YA,errorDisplay:LA,errorInfo:SA}}})}({From_Account:g,ProfileItem:E});const D=nc.getUserProfile(g);let M;M=D?Object.assign(Object.assign({},D),I):Hu.createProfile(g,E);const T=!ng(D,M,["lastUpdatedTime"]);return M.lastUpdatedTime=Date.now(),nc.getUserProfileMap().set(g,M),T&&this._emitProfileUpdated(M),{code:0,data:M,successLog:{message:`profileArray: ${me.utils.safeStringify(E)}`}}}catch(m){const{errorCode:D,errorInfo:M}=m;throw new as({functionName:"updateMyProfile",code:D,message:M,moreMessage:`params: ${me.utils.safeStringify(n)}`})}})}updateMyNickAndAvatar(n){return pA(this,void 0,void 0,function*(){const g=Ar(),I=Date.now(),E=nc.getUserProfile(g);let m={};m=E?Object.assign(E,n):Hu.createProfile(g,n),m.lastUpdatedTime=I,nc.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:Hu.parseProfileList(T)}}(n.ProfileDataMod[0]);if(kD(g))return;const{isProfileUpdated:I,profile:E}=this._handleProfileModified(g);I&&this._emitProfileUpdated(E)}_emitProfileUpdated(n){me.notificationCenter.emitInnerEvent(so.PROFILE_UPDATE,{name:so.PROFILE_UPDATE,data:[n]}),me.notificationCenter.emitOuterEvent(yr.PROFILE_UPDATED,{name:yr.PROFILE_UPDATED,data:[n]}),CB.updateConversation(`C2C${n?.userID}`,{userProfile:n})}_dispose(){const{notificationCenter:n}=me;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:I}=n,E=nc.getUserProfile(g);if(!(Ar()===g||UE(g)&&E))return{isProfileUpdated:!1,profile:null};const m=Hu.normalizeProfileFields(I),D=Object.keys(m).some(W=>W===bD?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,bD)?this._mergeProfileCustomField(E.profileCustomField,m.profileCustomField):E.profileCustomField,P=Object.assign(Object.assign(Object.assign({},E),m),{profileCustomField:T,lastUpdatedTime:M});return nc.getUserProfileMap().set(g,P),{isProfileUpdated:D,profile:P}}_filterRequestAndCacheUsers(n){const g=[],I=[];return n.forEach(E=>{const m=nc.getUserProfileMap().has(E);UE(E)&&m?I.push(nc.getUserProfile(E)):this._isStrangerAndProfileValid(E)?I.push(this._strangerProfileMap.get(E)):g.push(E)}),{userIdListToRequest:g,profileFromCache:I}}_handleProfileFormResponse(n){const{userProfile:g}=n;if(!Array.isArray(g))return[];const I=g.filter(m=>m.userId!=="@TLS#NOT_FOUND"&&m.userId!==""&&!kD(m.profileItem)),E=Date.now();return I.map(m=>{const D=Hu.createProfile(m.userId,m.profileItem);return D.lastUpdatedTime=E,D})}_isStrangerAndProfileValid(n){var g;if(!UE(n)){const{lastUpdatedTime:I=0}=this._strangerProfileMap.get(n)||{},E=((g=me.store.get("cloudConfig"))===null||g===void 0?void 0:g.stranger_profile_expiration_time)||6e5;return Date.now()-I<=E}return!1}_chunkUserIDList(n,g){return Array.from({length:Math.ceil(n.length/g)},(I,E)=>n.slice(E*g,(E+1)*g))}_batchFetchUserProfiles(n){return pA(this,void 0,void 0,function*(){const g=[],I=[];let E={};return this._chunkUserIDList(n,100).forEach(m=>{g.push(IR(m))}),(yield Promise.allSettled(g)).forEach(m=>{if(m.status==="fulfilled"){const D=m.value,M=this._handleProfileFormResponse(D);p(M)&&I.push(...M)}else if(m.status==="rejected"){const{code:D,message:M}=m.reason||{};E={errorCode:D,message:M}}}),{data:I,error:E}})}_isCustomFieldChanged(n=[],g=[]){if(!p(g)||g.length===0)return!1;if(!p(n)||n.length===0)return!0;const I=new Map(n.map(E=>[E.key,E.value]));return g.some(E=>I.get(E.key)!==E.value)}_mergeProfileCustomField(n=[],g=[]){const I=p(n)?n.map(E=>Object.assign({},E)):[];return p(g)&&g.length!==0&&g.forEach(({key:E,value:m})=>{const D=I.find(M=>M.key===E);D?D.value=m:I.push({key:E,value:m})}),I}_reset(){nc.getUserProfileMap().clear(),this._strangerProfileMap.clear()}}const Km=new Map,LD=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let s=0,n=LD.length;s>(-2*m&6)):0)E="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(E);try{return decodeURIComponent(escape(g))}catch(I){return console.warn(I),""}}const{isEmpty:yT}=me.utils,{generateProtocolData:jm}=me.common;function uR(s){return pA(this,void 0,void 0,function*(){const n="im_open_status.ws_get_user_status",g=jm({servcmd:n,data:{To_Account:s}}),I=`${g.head.seq}${n}`,E=yield me.channel.sendPacket(g,{requestId:I});if(E)return function(m){const{ErrorCode:D,ErrorInfo:M,ErrorList:T=[],UserStatusList:P=[]}=m,W=P.map(EA=>{const{To_Account:wA,Status:kA,CustomStatus:YA,Detail:LA=[]}=EA;return{userID:wA,statusType:kA,customStatus:ZQ(YA),onlineDevices:DT(LA)}}),oA=T.map(EA=>{const{To_Account:wA,Invalid_Account:kA,ErrorCode:YA,ErrorInfo:LA}=EA;return{userID:yT(kA)?wA:kA,code:YA,message:LA}});return{errorCode:D,errorInfo:M,successUserList:W,failureUserList:oA}}(E)})}function DT(s){const n=[];return s?.forEach(g=>{const{Platform:I,Status:E}=g;E==="Online"&&n.push(I)}),n}class ST{constructor(){this._customStatus=""}init(){const{notificationCenter:n}=me;dr.getInstance().registerApi({apiName:"getUserStatus",context:this}),dr.getInstance().registerApi({apiName:"setSelfStatus",context:this}),dr.getInstance().registerApi({apiName:"subscribeUserStatus",context:this}),dr.getInstance().registerApi({apiName:"unsubscribeUserStatus",context:this}),Rs.getInstance().registerWorkflowStep(Pt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Ht.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:I}=n;try{return yield function(E){return pA(this,void 0,void 0,function*(){const m="im_open_status.ws_set_custom_status",D=jm({servcmd:m,data:{CustomStatus:E}}),M=`${D.head.seq}${m}`,T=yield me.channel.sendPacket(D,{requestId:M});if(T){const{ErrorCode:P,ErrorInfo:W}=T;return{errorCode:P,errorInfo:W}}})}(I),this._customStatus=I,{code:0,data:{userID:g,statusType:yh,customStatus:I},successLog:{message:`customStatus: ${I}`}}}catch(E){const{errorCode:m,errorInfo:D}=E;throw new as({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 I=yield this._getUserStatus(g);return Object.assign(Object.assign({},I),{successLog:{message:`userIDList length: ${g.length}`}})})}setCustomStatus(n){const g=ZQ(n);this._customStatus=g}subscribeUserStatus(n){return pA(this,void 0,void 0,function*(){try{const{userIDList:g=[]}=n;this._checkBusinessCapabilityBits("subscribeUserStatus");const I=this._getMaxUserCount("subscribe"),E=this._sliceUserIDList(g,I),m=yield function(M){return pA(this,void 0,void 0,function*(){const{channel:T}=me,P="im_open_status.ws_status_subscribe",W=jm({servcmd:P,data:{To_Account:M}}),oA=`${W.head.seq}${P}`;return yield T.sendPacket(W,{requestId:oA})})}(E),D=this._parseResponse(m);return{code:0,data:{failureUserList:D},successLog:{message:`userID length:${g.length} failCount: ${D.length}`}}}catch(g){const{errorCode:I}=g;throw new as({functionName:"subscribeUserStatus",code:I})}})}unsubscribeUserStatus(n){return pA(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("unsubscribeUserStatus");const{userIDList:g=[]}=n,I=this._getMaxUserCount("unsubscribe"),E=this._sliceUserIDList(g,I),m=yield function(M){return pA(this,void 0,void 0,function*(){const{channel:T}=me,P="im_open_status.ws_status_unsubscribe";let W={};W=M.length===0?{UnsubscribeAll:1}:{To_Account:M};const oA=jm({servcmd:P,data:W}),EA=`${oA.head.seq}${P}`;return yield T.sendPacket(oA,{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:I}=g;throw new as({functionName:"unsubscribeUserStatus",code:I})}})}_onUserStatusUpdate(n){const{UserStatusList:g=[]}=n||{},I=g.map(E=>{const{To_Account:m,Status:D,CustomStatus:M,Platform:T}=E,P={userID:m,statusType:D,customStatus:ZQ(M)};return T&&(P.onlineDevices=T),P});this._emitUserStatusUpdatedEvent(I)}_onReOnline(n){const g=ZQ(n.data.customStatus);if(this._customStatus===g)return;this._customStatus=g;const I={userID:Ar(),statusType:yh,customStatus:g};this._emitUserStatusUpdatedEvent(I)}_emitUserStatusUpdatedEvent(n){me.notificationCenter.emitOuterEvent(yr.USER_STATUS_UPDATED,{name:yr.USER_STATUS_UPDATED,data:n})}_sliceUserIDList(n,g){return n.slice(0,g)}_parseResponse(n){const{ErrorList:g=[]}=n;return g.map(I=>{const{To_Account:E,Invalid_Account:m,ErrorCode:D,ErrorInfo:M}=I;return{userID:me.utils.isEmpty(m)?E:m,code:D,message:M}})}_checkBusinessCapabilityBits(n){if(!me.store.get("commercialConfig").get(fT))throw new as({functionName:n,code:ua.NO_USE,replacement1:n})}_getMaxUserCount(n){const g=me.store.get("cloudConfig")||{},I={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}=I[n],D=g[E]||m;return parseInt(D,10)}_getMyStatus(){return{code:0,data:{successUserList:[{userID:Ar(),statusType:yh,customStatus:this._customStatus}],failureUserList:[]}}}_getUserStatus(n){return pA(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("getUserStatus");const g=this._getMaxUserCount("query"),I=this._sliceUserIDList(n,g),E=yield uR(I),{successUserList:m,failureUserList:D}=E||{};return{code:0,data:{successUserList:m,failureUserList:D}}}catch(g){const{errorCode:I}=g;throw new as({functionName:"getUserStatus",code:I})}})}_isOnlyMeInArray(n){const g=Ar();return n.length===1&&n.indexOf(g)>-1}_dispose(){const{notificationCenter:n}=me;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 UD={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(GD))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}}},MT={getMyProfile:!0,getUserProfile:!0,updateMyProfile:!0,setSelfStatus:!0,getUserStatus:!0,subscribeUserStatus:!0,unsubscribeUserStatus:!0};class vT{constructor(){this.userProfile=new qm,this.userStatus=new ST,this.userProfile.init(),this.userStatus.init(),Kc({auth:MT,params:UD})}}function FD(s){const n=[];if(!l(s))return n;const g=s.length;if(g===0)return n;for(let I=g-1;I>=0;I--)s[I]==="1"&&n.push(2**(g-I-1));return n}var Dd,BC,Sd;(function(s){s.NOT_START="notStart",s.PENDING="pending",s.RESOLVED="resolved",s.REJECTED="rejected"})(Dd||(Dd={})),function(s){s[s.C2C=1]="C2C",s[s.GROUP=2]="GROUP"}(BC||(BC={})),function(s){s[s.C2C=8]="C2C",s[s.GROUP=2]="GROUP"}(Sd||(Sd={}));class OD{constructor(){this._name="SyncConversationHandler",this._pagingStatus=Dd.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}init(){const{notificationCenter:n}=me;Rs.getInstance().registerWorkflowStep(Pt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Ht.CONVERSATION_RECOVER,this._syncConversationList,this),Rs.getInstance().registerWorkflowStep(Pt.SYNC_SERVER_INFO_AFTER_LOGIN,Ht.CONVERSATION_LIST_SYNC,this._syncConversationListAfterLogin,this),n.subscribeInnerEvent(so.LOGOUT,this._reset,this),n.subscribeInnerEvent(so.DESTROY,this._dispose,this),me.ssoLog.debug(`${this._name}.init`)}isSyncCompleted(){return this._pagingStatus===Dd.RESOLVED}_syncConversationListAfterLogin(){return pA(this,void 0,void 0,function*(){return this._pagingStatus=Dd.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}}=me;n.debug("_syncConversationList","start");try{const I=yield this._pagingGetConversationList(!0);this._pagingStatus=Dd.RESOLVED;const{conversationList:E=[]}=I||{};return n.info("_syncConversationList",`success count:${E.length}`),I}catch(I){const E=new as(I);n.error("_syncConversationList",`fail ${g(I)}`,{error:E})}})}_pagingGetConversationList(n){return pA(this,void 0,void 0,function*(){try{const g=[];this._pagingStatus=Dd.PENDING;const I=yield function(oA){return pA(this,void 0,void 0,function*(){const{fromAccount:EA,pagingTimeStamp:wA,pagingStartIndex:kA,pagingPinnedTimeStamp:YA,pagingPinnedStartIndex:LA}=oA;return ag({servcmd:"recentcontact.page_get",data:{AssistFlags:31,MsgAssistFlags:15,OrderType:1,From_Account:EA,StartIndex:kA,TimeStamp:wA,TopStartIndex:LA,TopTimeStamp:YA}})})}({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}=I||{};let W=[];if(E===1&&(this._pagingStatus=Dd.RESOLVED),m.length>0&&(W=this._getConversationOptions(m),g.push(...W)),me.notificationCenter.emitInnerEvent(so.SYNC_CONVERSATION_LIST,{conversationUpdateFieldList:W}),this._pagingTimeStamp=D,this._pagingStartIndex=M,this._pagingPinnedTimeStamp=T,this._pagingPinnedStartIndex=P,E!==1){const{conversationList:oA}=yield this._pagingGetConversationList(n);g.push(...oA)}return{conversationList:g}}catch(g){throw g}})}_getConversationOptions(n){const{utils:{isUndefined:g}}=me,I=this._convertConversationKey(n);return this._filterValidConversations(I).map(E=>(g(E.lastMsg)&&(E.lastMsg={elements:[]}),E.type===BC.C2C?this._assembleC2COption(E):this._assembleGroupOption(E)))}_filterValidConversations(n){return n.filter(({type:g,userID:I})=>g===BC.C2C&&!function(E){let m;return E.startsWith(ko.CONV_C2C)&&(m=E.replace(ko.CONV_C2C,"")),m==="@TLS#ERROR"||m==="@TLS#NOT_FOUND"}(I)||g===2)}_assembleC2COption(n){var g,I,E,m,D,M,T,P;const W=this._createUserprofile(n);return{conversationID:`${ko.CONV_C2C}${n.userID}`,type:ko.CONV_C2C,lastMessage:{lastTime:n.time,lastSequence:n.sequence,fromAccount:n.lastC2CMsgFromAccount,type:!((g=n.lastMsg)===null||g===void 0)&&g.elements[0]?(I=n.lastMsg)===null||I===void 0?void 0:I.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===Sd.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:FD(n.standardMark),conversationGroupList:[],remark:n.friendRemark||"",messageRemindType:this._transMsgRemindType(n.messageRemindType)}}_createUserprofile(n){var g;const{userID:I,nick:E,peerAvatar:m}=n,D=[{tag:"Tag_Profile_IM_Nick",value:E},{tag:"Tag_Profile_IM_Image",value:m}];return(g=me.user.userProfile)===null||g===void 0?void 0:g.createProfile(I,D)}_computeIsPeerRead(n){const g=Ar(),{lastC2CMsgFromAccount:I,time:E,c2cPeerReadTime:m}=n;return I===g&&E<=m}_assembleGroupOption(n){var g,I,E,m,D;return{conversationID:`${ko.CONV_GROUP}${n.groupID}`,type:ko.CONV_GROUP,lastMessage:Object.assign(Object.assign({lastTime:n.time,lastSequence:n.sequence,fromAccount:n.msgGroupFromAccount},this._patchTypeAndPayload(n)),{cloudCustomData:((E=(I=(g=n.lastMsg)===null||g===void 0?void 0:g.elements)===null||I===void 0?void 0:I[0])===null||E===void 0?void 0:E.cloudCustomData)||"",isRevoked:n.lastMessageFlag===Sd.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:FD(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,I,E;const{utils:{isEmpty:m}}=me;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=ko.MSG_GRP_TIP,M=Object.assign(Object.assign({},this._parseContent(D,n.GroupTips.MsgBody)),{groupProfile:{from:T,groupName:P}})}return n.MsgBody&&(D=(I=n.MsgBody[0])===null||I===void 0?void 0:I.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 I;if(!g)return g;const E=me.message.messageFactory.getElementClass(n);return E?(I=E.parseServerPushElement(g))===null||I===void 0?void 0:I.content:g}_amendLayersOverLimitProp(n){const{LayersOverLimit:g}=n;return yo(n,["LayersOverLimit"]).layersOverLimit=g===1,n}_transMsgRemindType(n){let g="";return n===0?g=ko.MSG_REMIND_ACPT_AND_NOTE:n===1?g=ko.MSG_REMIND_DISCARD:n===2?g=ko.MSG_REMIND_ACPT_NOT_NOTE:n===3&&(g=ko.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),g}_patchTypeAndPayload(n){var g;const{utils:{isUndefined:I}}=me,{event:E,elements:m=[]}=n.lastMsg||{};return I(E)?{type:m[0]?m[0].type:null,payload:m[0]?this._amendLayersOverLimitProp(m[0].content):null}:{type:ko.MSG_GRP_TIP,payload:((g=m?.[0])===null||g===void 0?void 0:g.content)||{}}}_computeGroupUnreadCount(n){const{unreadCount:g=0,noUnreadCount:I=0}=n,E=g-I;return E>0?E:0}_reset(){this._pagingStatus=Dd.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}_dispose(){this._reset();const{notificationCenter:n}=me;n.unSubscribeInnerEvent(so.LOGOUT,this._reset,this),n.unSubscribeInnerEvent(so.DESTROY,this._dispose,this)}}class PD{constructor(){this.syncConversationHandler=new OD,this.syncConversationHandler.init()}}console.log(`TencentCloudLiteChat.VERSION:${Wr}`);var xD={create:function(s){var n,g;const{SDKAppID:I,testEnv:E=!1,devMode:m=!1,unlimitedAVChatRoom:D=!1,scene:M="",oversea:T=!1,instance:P,disableIndependentDomain:W=!1,proxyServer:oA=""}=s;let EA=I;if(!function(kA){if(typeof kA=="number")return!0;const YA=Number(kA);return!Number.isNaN(YA)}(EA))return console.error("Create SDK instance failed. Failed to parse the SDKAppID, please check the arguments"),null;if(EA=Number(EA),Ea.has(EA))return Ea.get(EA);let wA=null;if(P)wA=P,wA._workflowManager&&Rs.setInstance(wA._workflowManager),wA._pluginManager&&wA._pluginManager.installBuiltInPlugin(EB),P.isReady()&&((g=(n=Rs.getInstance()).executeWorkflow)===null||g===void 0||g.call(n,Pt.SYNC_SERVER_INFO_AFTER_LOGIN));else{const kA=function(){function se(){return(65536*(1+Math.random())|0).toString(16).substring(1)}return`${se()+se()}${se()}${se()}${se()}${se()}${se()}${se()}`}();me.init({sdkAppId:EA,instanceId:kA,testEnv:E,devMode:m,unlimitedAVChatRoom:D,disableIndependentDomain:W,scene:M,oversea:T,sdkEdition:Fm,version:Wr,proxyServer:oA}),Rs.getInstance().init(),me.message=new ND,me.user=new vT,me.login=new hh,me.conversation=new PD,$I.getInstance().installBuiltInPlugin(EB),wA=dr.getInstance().exposeApiForClient(),wA._workflowManager=Rs.getInstance(),wA._pluginManager=$I.getInstance();const{utils:{IS_WORKER_AVAILABLE:YA,USER_AGENT:LA,getPlatformType:SA,isIOSWebView:OA}}=me,HA=`instanceID:${kA} SDKAppID:${I} platform:${qA} host:${SA()} isIOSWebView:${OA} workerAvailable:${YA} UserAgent:${LA}`;me.ssoLog.info("sdkConstruct",HA)}return Ea.set(EA,wA),wA},TSignaling:Jc,EVENT:yr,VERSION:Wr,TYPES:ko};return xD})}(l1)),l1.exports}var _iA=wiA();const tg=B3(_iA);var I1={exports:{}},TiA=I1.exports,Z5;function NiA(){return Z5||(Z5=1,function(t,i){(function(r,l){t.exports=l()})(TiA,function(){function r(re,qe){if(!(re instanceof qe))throw new TypeError("Cannot call a class as a function")}function l(re,qe){for(var ft=0;ft"u"&&typeof uni.requireNativePlugin=="function",PA=MA&&uni.getDeviceInfo().platform.toLocaleLowerCase()==="ios",ge=(MA&&uni.getDeviceInfo().platform.toLocaleLowerCase(),lA||aA||mA||IA||tA||MA),de=F!==void 0&&(F.nativeModuleProxy!==void 0||F.ReactNative!==void 0),Ve=aA?qq:mA?tt:IA?swan:tA?my:lA?wx:MA?uni:{},Be=function(re){if(k(re)!=="object"||re===null)return!1;var qe=Object.getPrototypeOf(re);if(qe===null)return!0;for(var ft=qe;Object.getPrototypeOf(ft)!==null;)ft=Object.getPrototypeOf(ft);return qe===ft};function ct(re){if(re==null)return!0;if(typeof re=="boolean")return!1;if(typeof re=="number")return re===0;if(typeof re=="string"||typeof re=="function"||Array.isArray(re))return re.length===0;if(re instanceof Error)return re.message==="";if(Be(re)){for(var qe in re)if(Object.prototype.hasOwnProperty.call(re,qe))return!1;return!0}return!1}var mt=function(){return u(function re(){r(this,re),this._n="WebRequest"},[{key:"request",value:function(re,qe){var ft=this,si="".concat(this._n,".request"),Vt=re.downloadUrl||"",gi=(re.method||"PUT").toUpperCase(),Fi=re.url;if(console.log("%c tim-upload-plugin %c","background:#0abf5b; padding:1px; border-radius:3px; color: #fff","background:transparent","".concat(si," URL:").concat(Fi)),re.qs){var _o=function(ki){var os=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"&",Ko=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"=";return ct(ki)?"":Be(ki)?Object.keys(ki).map(function($i){var jt=encodeURIComponent($i)+Ko;return Array.isArray(ki[$i])?ki[$i].map(function(io){return jt+encodeURIComponent(io)}).join(os):jt+encodeURIComponent(ki[$i])}).filter(Boolean).join(os):void 0}(re.qs);_o&&(Fi+="".concat(Fi.indexOf("?")===-1?"?":"&").concat(_o))}var to=new XMLHttpRequest;to.open(gi,Fi,!0),to.responseType=re.dataType||"text";var uo=re.headers||{};if(re.uploadByIP&&(uo=w(w({},uo),{},{host:re.uploadIP})),!ct(uo))for(var Ys in uo)uo.hasOwnProperty(Ys)&&Ys.toLowerCase()!=="content-length"&&Ys.toLowerCase()!=="user-agent"&&Ys.toLowerCase()!=="origin"&&Ys.toLowerCase()!=="host"&&to.setRequestHeader(Ys,uo[Ys]);return to.onload=function(){if(to.status===200)qe(null,ft._xhrRes(to,ft._xhrBody(to,Vt,re.uploadByIP&&re.uploadIP),uo));else{if(re.uploadIP&&re.url.indexOf(re.uploadIP)===-1)return re.url=function(os,Ko){return os.replace(/^http(s)?:\/\/(.*?)\//,"https://".concat(Ko,"/"))}(re.url,re.uploadIP),re.uploadByIP=!0,ft.request(re,qe);var ki={code:to.status,message:JSON.stringify(to.responseText)};qe(ki,ft._xhrRes(to,ft._xhrBody(to,Vt,re.uploadByIP&&re.uploadIP),uo))}},to.onerror=function(ki){var os=ft._xhrBody(to,Vt,re.uploadByIP&&re.uploadIP),Ko={code:to.status,message:JSON.stringify(to.responseText)};os||to.statusText||to.status!==0||(ki.message="CORS blocked or network error"),qe(Ko,ft._xhrRes(to,os)),Ko=null},re.onProgress&&to.upload&&(to.upload.onprogress=function(ki){var os=ki.total,Ko=ki.loaded,$i=Math.floor(100*Ko/os);re.onProgress({total:os,loaded:Ko,percent:($i>=100?100:$i)/100})}),to.send(re.resources),to}},{key:"_xhrRes",value:function(re,qe){var ft={};return re.getAllResponseHeaders().trim().split(`
-`).forEach(function(si){if(si){var Vt=si.indexOf(":"),gi=si.substr(0,Vt).trim().toLowerCase(),Fi=si.substr(Vt+1).trim();ft[gi]=Fi}}),{statusCode:re.status,statusMessage:re.statusText,headers:ft,data:qe}}},{key:"_xhrBody",value:function(re,qe,ft){return re.status===200&&qe?{location:qe,uploadIP:ft}:{response:re.responseText,uploadIP:ft}}}])}(),Ke=["unknown","image","video","audio","log"],Dt=["name"],qt=function(){return u(function re(){r(this,re)},[{key:"request",value:function(re,qe){var ft=this,si=re.resources,Vt=si===void 0?"":si,gi=re.headers,Fi=gi===void 0?{}:gi,_o=re.url,to=re.downloadUrl,uo=to===void 0?"":to,Ys=_o,ki=null,os=uo.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/),Ko=decodeURIComponent(os[3]),$i=Ko.indexOf("?")>-1?Ko.split("?")[0]:Ko,jt={key:re.fileKey?re.fileKey:$i,success_action_status:200,"Content-Type":""},io={};if(PA){var bi=_o.split("?sign=");if(bi.length>1){var Ms=bi[1];Ys="".concat(bi[0],"?sign=").concat(encodeURIComponent("".concat(Ms))),io.sign=decodeURIComponent(Ms),io.signature=decodeURIComponent(Ms)}}var qA={url:Ys,header:Fi,name:"file",filePath:Vt,formData:w(w({},jt),io),timeout:re.timeout||3e5};if(tA){var ce=qA;ce.name,qA=w(w({},function(Pe,kt){if(Pe==null)return{};var it,gt,Xt=function(Ge,je){if(Ge==null)return{};var Mt={};for(var Rt in Ge)if({}.hasOwnProperty.call(Ge,Rt)){if(je.includes(Rt))continue;Mt[Rt]=Ge[Rt]}return Mt}(Pe,kt);if(Object.getOwnPropertySymbols){var $t=Object.getOwnPropertySymbols(Pe);for(gt=0;gt<$t.length;gt++)it=$t[gt],kt.includes(it)||{}.propertyIsEnumerable.call(Pe,it)&&(Xt[it]=Pe[it])}return Xt}(ce,Dt)),{},{fileName:"file",fileType:Ke[re.fileType]})}return(ki=Ve.uploadFile(w(w({},qA),{},{success:function(Pe){ft._handleResponse({response:Pe,downloadUrl:uo,callback:qe})},fail:function(Pe){ft._handleResponse({response:Pe,downloadUrl:uo,callback:qe})}}))).onProgressUpdate&&ki.onProgressUpdate(function(Pe){re.onProgress&&re.onProgress({total:Pe.totalBytesExpectedToSend,loaded:Pe.totalBytesSent,percent:Math.floor(Pe.progress)/100})}),ki}},{key:"_handleResponse",value:function(re){var qe=re.downloadUrl,ft=re.response,si=re.callback,Vt=ft.header,gi={};if(Vt)for(var Fi in Vt)Vt.hasOwnProperty(Fi)&&(gi[Fi.toLowerCase()]=Vt[Fi]);var _o=+ft.statusCode;_o===200?si(null,{statusCode:_o,headers:gi,data:w(w({},ft.data),{},{location:qe})}):si({code:_o,message:JSON.stringify(ft.data)},{statusCode:_o,headers:gi,data:void 0})}}])}(),It=function(){return u(function re(){r(this,re)},[{key:"request",value:function(re,qe){var ft=this,si=re.resources,Vt=si===void 0?"":si,gi=re.fileKey,Fi=gi===void 0?"":gi,_o=re.url,to=re.downloadUrl,uo=to===void 0?"":to,Ys=new FormData;Ys.append("key",Fi),Ys.append("success_action_status",200),Ys.append("file",{uri:Vt,type:"application/octet-stream",name:"uploaded_file"}),fetch(_o,{method:"POST",headers:{"Content-Type":"multipart/form-data"},body:Ys}).then(function(ki){ft._handleResponse({response:ki,downloadUrl:uo,callback:qe})}).catch(function(ki){ft._handleResponse({response:ki,downloadUrl:uo,callback:qe})})}},{key:"_handleResponse",value:function(re){var qe=re.downloadUrl,ft=re.response,si=re.callback,Vt=ft.headers,gi=ft.status,Fi=Vt&&Vt.map||{};gi===200?si(null,{statusCode:200,headers:Fi,data:{location:qe}}):si({code:gi,message:JSON.stringify(ft)},{statusCode:gi,headers:Fi,data:void 0})}}])}();return function(){return u(function re(){r(this,re),this.retry=1,this.tryCount=0,this.systemClockOffset=0,this.httpRequest=ge?new qt:de?new It:new mt,console.log("TIMUploadPlugin.VERSION: ".concat("1.4.3"))},[{key:"uploadFile",value:function(re,qe){var ft=this;return this.httpRequest.request(re,function(si,Vt){si&&ft.tryCount=3e4&&(this.systemClockOffset=_o-Fi,qe=!0)}else Math.floor(re.statusCode/100)===5&&(qe=!0)}return qe}}],[{key:"getVersion",value:function(){return"1.4.3"}}])}()})}(I1)),I1.exports}var GiA=NiA();const biA=B3(GiA);/**
+`],{type:"application/javascript"});this._worker=new Worker(URL.createObjectURL(g)),this._worker.postMessage({type:mr,url:n})}send(n){var g,I;try{(g=this._worker)===null||g===void 0||g.postMessage({type:Ls,data:n})}catch(E){(I=this._onSendFail)===null||I===void 0||I.call(this,E)}}bindSocketHandlers(n){const{onOpen:g,onMessage:I,onClose:E,onError:m,onSendFail:D}=n;if(this._worker){const M={[ms]:g,[as]:I,[mu]:E,[ja]: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 OI{}var Xo,Zi=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:I,onClose:E,onError:m,onSendFail:D}=n;this._socket&&(this._socket.onClose(E),this._socket.onOpen(g),this._socket.onMessage(M=>I(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"})(Xo||(Xo={}));class ng{constructor(n){this._url="",this._readyState=Xo.DISCONNECTED,this._url=n,this._id=F(),this._emitter=new On,gi?this._socket=new pc:It||_o||ft||qe||Fi||Vt?this._socket=new cn({onError:this._onError.bind(this)}):an?this._socket=new OI:this._canUseWebWorker()?this._socket=new sg:this._socket=new yl,this.connect()}connect(){this.doOpen(),this._bindSocketHandlers()}doOpen(){[Xo.CONNECTED,Xo.CONNECTING].includes(this._readyState)||(this._readyState=Xo.CONNECTING,this._ws=this._socket.connectSocket(this._url))}send(n){this._readyState!==Xo.CONNECTED?this.reconnect():this._socket.send(n)}reconnect(){[Xo.CONNECTED,Xo.CONNECTING].includes(this._readyState)||(this.disconnect(),this.doOpen())}getId(){return this._id}on(n,g,I){this._emitter.on(n,g,I)}off(n,g,I){this._emitter.off(n,g,I)}isConnected(){return this._readyState===Xo.CONNECTED}disconnect(){this._readyState=Xo.DISCONNECTED,this._unbindSocketHandlers(),this._socket.disconnect()}_onOpen(n){this._readyState===Xo.CONNECTING&&(this._readyState=Xo.CONNECTED,this._emitter.emit("connect",{socketId:this._id,event:n}))}_onMessage(n){this._emitter.emit("message",n)}_onClose(n){this._readyState=Xo.DISCONNECTED,this._emitter.emit("close",{socketId:this._id,event:n})}_onError(n){this._readyState=Xo.DISCONNECTED,this._emitter.emit("error",{socketId:this._id,error:n})}_onSendFail(n){this._readyState=Xo.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=Zi.get("cloudConfig")||{};return(r(n.isWorkerEnabled)||n.isWorkerEnabled==="1")&&No}}const Dg={[ct.SINGAPORE]:[[2e7,3e7],[172e7,173e7]],[ct.KOREA]:[[3e7,4e7],[173e7,174e7]],[ct.GERMANY]:[[4e7,5e7],[174e7,175e7]],[ct.IND]:[[5e7,6e7],[175e7,176e7]],[ct.JPN]:[[6e7,7e7],[176e7,177e7]],[ct.USA]:[[7e7,8e7],[177e7,178e7]],[ct.INDONESIA]:[[8e7,9e7],[178e7,179e7]],[ct.KSA]:[[9e7,1e8],[179e7,18e8]]};function la(s){var n;if(!((n=Zi.get("instance"))===null||n===void 0)&&n.oversea)return ct.OVERSEA;for(const g of Object.keys(Dg))for(const[I,E]of Dg[g])if(s>=I&&s`${iA}=${W[iA]}`).join("&"));var W;return g?`${s}/binfo?${P}&compress=gzip`:`${s}/info?${P}`}function Hs(s){const n=Zi.get("instance"),{sdkAppId:g,testEnv:I,proxyServer:E}=n,m=la(g);if(I)return Hn(mt.TEST[m].DEFAULT,{isBinary:s});if(!Rs(E))return Hn(E,{isBinary:s});const D=mt.PRODUCTION[m],M=jt&&D.ANYCAST,T=jt,P=!!D.BACKUP_CN;return Hn({[Go.INITIAL]:()=>(wo=Go.DEFAULT,D.DEFAULT),[Go.DEFAULT]:()=>(wo=Go.IPV6,D.IPV6),[Go.IPV6]:()=>(wo=Go.BACKUP,D.BACKUP),[Go.BACKUP]:()=>T?(wo=Go.BACKUP_WEB_ONLY,function(W){const iA=Math.floor(10001*Math.random())+1e4;return W.replace("*",String(iA))}(D.BACKUP_WEB_ONLY)):P?(wo=Go.BACKUP_CN,D.BACKUP_CN):M?(wo=Go.ANYCAST,D.ANYCAST):D.DEFAULT,[Go.BACKUP_WEB_ONLY]:()=>P?(wo=Go.BACKUP_CN,D.BACKUP_CN):M?(wo=Go.ANYCAST,D.ANYCAST):D.DEFAULT,[Go.BACKUP_CN]:()=>(wo=M?Go.ANYCAST:Go.DEFAULT,D[wo]),[Go.ANYCAST]:()=>(wo=Go.DEFAULT,D.ANYCAST="",D.DEFAULT)}[wo](),{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(),I=g-s;this._timeOffsetWithServer=n+I-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:I,isOnce:E=!1,intervalMs:m=mc}=s,D=Math.max(m,mc);return{id:n,nextExecuteTime:Date.now()+D,intervalMs:m,callback:g,context:I,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 Na(s){const n=[];for(let g=0;g=55296&&I<=56319){const E=s.charCodeAt(++g)-56320+(I-55296<<10)+65536;n.push(240|E>>18,128|E>>12&63,128|E>>6&63,128|63&E)}else I<=127?n.push(I):I<=2047?n.push(192|I>>6,128|63&I):n.push(224|I>>12,128|I>>6&63,128|63&I)}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(pA.includes(s))return 0;const g=Na(JSON.stringify(n));let I=4294967295;const{length:E}=g;for(let m=0;m>>=1:I=I>>>1^3988292384}return(4294967295^I)>>>0}function Ia(s){const{servcmd:n,data:g}=s,I=function(m){const D=Zi.get("login")||{},M=Zi.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:Da(),cs:0}}(n),E=In(g);return I.cs=fs(n,E),{head:I,body:E}}function yn(s){const{servcmd:n,data:g}=s,I=function(m){const D=Zi.get("login")||{},M=Zi.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:Da(),cs:0}}(n),E=In(g);return I.cs=fs(n,E),{head:I,body:E}}let Ga=F();function Da(){return Ga=Ga<2415919103?Ga+1:F(),Ga}function $(){var s;const n=Zi.get("login")||{},g=Zi.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=Zi.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,I=function(m){const D=Zi.get("login")||{},M=Zi.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:Da(),cs:0}}(n),E=In(g);return I.cs=fs(n,E),{head:I,body:E}},generateProtocolData:Ia,generateSSOLogProtocolData:yn,generateSequence:Da,getCommonHead:$,getHostSite:la,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 te{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:I=0,message:E="",costTime:m=0,error:D,uiPlatform:M,moreMessage:T="",code:P=0,startTime:W=0}=n||{};this.eventType=I,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=Zi.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 I=g;qA[I]&&(n[qA[I]]=this[I])}),n}_getUiPlatform(){var n;const g=(n=Zi.get("instance"))===null||n===void 0?void 0:n.scene;if(typeof g=="string"){const I=Number(g);return isNaN(I)?void 0:I}}_getSDKEdition(){var n;return(n=Zi.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 Oe=pe;const Fe=20,ot=6e4,ut=[4,5,6],St="report-logger";var Ot=new class{constructor(){this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._reportLevel=[4,5,6],this._minThreshold=Fe,this._maxThreshold=100,this._waitingTime=ot,this._lastReportAt=Date.now(),this._ssoLogMap=new Map,this._logLevel=lA.DEBUG,this._throttleConfig={global:{throttleTime:De,maxCount:Ce},single:{throttleTime:zA,maxCount:$A}},this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap=new Map,gn.subscribeInnerEvent(Oe.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),fn.addTask({id:St,intervalMs:1e3,callback:this._checkAndReportIfDue,context:this}),this._logQueue=[],this._savePlatFormInfo()}_handleCloudConfigUpdate(s){const{evt_rpt_threshold:n=Fe,evt_rpt_waiting:g=ot,evt_rpt_level:I=ut,evt_rpt_sdkappid_bl:E="",evt_rpt_tinyid_wl:m="",evt_rpt_global_throttle_time:D=De,evt_rpt_global_throttle_count:M=Ce,evt_rpt_single_throttle_time:T=zA,evt_rpt_single_throttle_count:P=$A}=s||{};this._sdkAppIdBlackList=E.split(",").map(W=>Number(W)),this._waitingTime=Number(g),this._minThreshold=n,this._reportLevel=I,this._tinyIdWhiteList=m.split(","),this._throttleConfig={global:{throttleTime:D,maxCount:M},single:{throttleTime:T,maxCount:P}}}createSSOLogData(s){const n=new te(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 mA(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(I){const E="imopenstat.tim_web_report_v2",m=yn({servcmd:E,data:I}),D=`${m.head.seq}${E}`;return fe.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(It){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:I,envVersion:E}=g;Zi.set("instance",{appId:I,envVersion:E})}}else jt&&Zi.set("instance",{href:window.location.href})}_filterLogs(s){const{tinyID:n}=Zi.get("login")||{},{sdkAppId:g}=Zi.get("instance")||{};return this._sdkAppIdBlackList.includes(g)&&!this._tinyIdWhiteList.includes(n)?[]:s.filter(I=>this._reportLevel.includes(I.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,I){const E=new Date,m=`${E.getHours()}:${E.getMinutes()}:${E.getSeconds()}:${E.getMilliseconds()}`,D=`<${lA[s]}>`;return Rt||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(I)}`]}_log(s,n,g,I){if(this._shouldLog(s)){const E=this._formatLog(s,n,g,I);TA[s].apply(console,E)}if(this._shouldReport(s)){const E=this._getThrottleKey(n,g,I);this._checkThrottle(E)||this.createSSOLogData(Object.assign(Object.assign({message:g},I),{method:n})).end()}}_getThrottleKey(s,n,g){const I=`${s}${n}${en(Object.assign(Object.assign({},g),{costTime:""}))}`,E=Na(JSON.stringify(I));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(St),gn.unSubscribeInnerEvent(Oe.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),this._lastReportAt=0,this.uploadSSOLogData(),this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._minThreshold=Fe,this._maxThreshold=100,this._waitingTime=ot,this._logQueue=[],this._logLevel=lA.DEBUG,this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap.clear()}};const li=15e3,nt="Channel",Ft="channel_schedule_task",Ji="channel_reconnect_task",qi="connected",qs="connecting",Mi="disconnected",Wo=1e3,Mg="network_status_change",or="activity_status_change",fr="send_fail",xn="reconnect_failed",Dl="socket_error",Ks="socket_close";function oI(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 fu,Sa={exports:{}},Sl=(fu||(fu=1,function(s){s.exports=function n(g,I,E){function m(T,P){if(!I[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=I[T]={exports:{}};g[T][0].call(iA.exports,function(EA){return m(g[T][1][EA]||EA)},iA,iA.exports,n,g,I,E)}return I[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},I.buf2binstring=function(W){return P(W,W.length)},I.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)},I.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,I){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,I){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,I){g.exports=function(E,m){var D,M,T,P,W,iA,EA,RA,kA,xA,LA,SA,OA,JA,re,ne,_i,Ti,kt,Ni,cs,Se,Bt,UA,ii;D=E.state,M=E.next_in,UA=E.input,T=M+(E.avail_in-5),P=E.next_out,ii=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,re=D.distcode,ne=(1<>>=kt=Ti>>>24,OA-=kt,(kt=Ti>>>16&255)==0)ii[P++]=65535&Ti;else{if(!(16&kt)){if(!(64&kt)){Ti=JA[(65535&Ti)+(SA&(1<>>=kt,OA-=kt),OA<15&&(SA+=UA[M++]<>>=kt=Ti>>>24,OA-=kt,!(16&(kt=Ti>>>16&255))){if(!(64&kt)){Ti=re[(65535&Ti)+(SA&(1<>>=kt,OA-=kt,(kt=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 Bt;return Se&&Se.state?(Bt=Se.state,Se.total_in=Se.total_out=Bt.total=0,Se.msg="",Bt.wrap&&(Se.adler=1&Bt.wrap),Bt.mode=RA,Bt.last=0,Bt.havedict=0,Bt.dmax=32768,Bt.head=null,Bt.hold=0,Bt.bits=0,Bt.lencode=Bt.lendyn=new E.Buf32(kA),Bt.distcode=Bt.distdyn=new E.Buf32(xA),Bt.sane=1,Bt.back=-1,iA):EA}function JA(Se){var Bt;return Se&&Se.state?((Bt=Se.state).wsize=0,Bt.whave=0,Bt.wnext=0,OA(Se)):EA}function re(Se,Bt){var UA,ii;return Se&&Se.state?(ii=Se.state,Bt<0?(UA=0,Bt=-Bt):(UA=1+(Bt>>4),Bt<48&&(Bt&=15)),Bt&&(Bt<8||15=Gi.wsize?(E.arraySet(Gi.window,Bt,UA-Gi.wsize,Gi.wsize,0),Gi.wnext=0,Gi.whave=Gi.wsize):(ii<(_s=Gi.wsize-Gi.wnext)&&(_s=ii),E.arraySet(Gi.window,Bt,UA-ii,_s,Gi.wnext),(ii-=_s)?(E.arraySet(Gi.window,Bt,UA-ii,ii,0),Gi.wnext=ii,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),_t=wt=0,UA.mode=2;break}if(UA.flags=0,UA.head&&(UA.head.done=!1),!(1&UA.wrap)||(((255&wt)<<8)+(wt>>8))%31){Se.msg="incorrect header check",UA.mode=30;break}if((15&wt)!=8){Se.msg="unknown compression method",UA.mode=30;break}if(_t-=4,Ya=8+(15&(wt>>>=4)),UA.wbits===0)UA.wbits=Ya;else if(Ya>UA.wbits){Se.msg="invalid window size",UA.mode=30;break}UA.dmax=1<>8&1),512&UA.flags&&(dg[0]=255&wt,dg[1]=wt>>>8&255,UA.check=D(UA.check,dg,2,0)),_t=wt=0,UA.mode=3;case 3:for(;_t<32;){if(xi===0)break A;xi--,wt+=ii[Gi++]<<_t,_t+=8}UA.head&&(UA.head.time=wt),512&UA.flags&&(dg[0]=255&wt,dg[1]=wt>>>8&255,dg[2]=wt>>>16&255,dg[3]=wt>>>24&255,UA.check=D(UA.check,dg,4,0)),_t=wt=0,UA.mode=4;case 4:for(;_t<16;){if(xi===0)break A;xi--,wt+=ii[Gi++]<<_t,_t+=8}UA.head&&(UA.head.xflags=255&wt,UA.head.os=wt>>8),512&UA.flags&&(dg[0]=255&wt,dg[1]=wt>>>8&255,UA.check=D(UA.check,dg,2,0)),_t=wt=0,UA.mode=5;case 5:if(1024&UA.flags){for(;_t<16;){if(xi===0)break A;xi--,wt+=ii[Gi++]<<_t,_t+=8}UA.length=wt,UA.head&&(UA.head.extra_len=wt),512&UA.flags&&(dg[0]=255&wt,dg[1]=wt>>>8&255,UA.check=D(UA.check,dg,2,0)),_t=wt=0}else UA.head&&(UA.head.extra=null);UA.mode=6;case 6:if(1024&UA.flags&&(xi<(ho=UA.length)&&(ho=xi),ho&&(UA.head&&(Ya=UA.head.extra_len-UA.length,UA.head.extra||(UA.head.extra=new Array(UA.head.extra_len)),E.arraySet(UA.head.extra,ii,Gi,ho,Ya)),512&UA.flags&&(UA.check=D(UA.check,ii,ho,Gi)),xi-=ho,Gi+=ho,UA.length-=ho),UA.length))break A;UA.length=0,UA.mode=7;case 7:if(2048&UA.flags){if(xi===0)break A;for(ho=0;Ya=ii[Gi+ho++],UA.head&&Ya&&UA.length<65536&&(UA.head.name+=String.fromCharCode(Ya)),Ya&&ho>9&1,UA.head.done=!0),Se.adler=UA.check=0,UA.mode=12;break;case 10:for(;_t<32;){if(xi===0)break A;xi--,wt+=ii[Gi++]<<_t,_t+=8}Se.adler=UA.check=LA(wt),_t=wt=0,UA.mode=11;case 11:if(UA.havedict===0)return Se.next_out=Lr,Se.avail_out=ar,Se.next_in=Gi,Se.avail_in=xi,UA.hold=wt,UA.bits=_t,2;Se.adler=UA.check=1,UA.mode=12;case 12:if(Bt===5||Bt===6)break A;case 13:if(UA.last){wt>>>=7&_t,_t-=7&_t,UA.mode=27;break}for(;_t<3;){if(xi===0)break A;xi--,wt+=ii[Gi++]<<_t,_t+=8}switch(UA.last=1&wt,_t-=1,3&(wt>>>=1)){case 0:UA.mode=14;break;case 1:if(Ni(UA),UA.mode=20,Bt!==6)break;wt>>>=2,_t-=2;break A;case 2:UA.mode=17;break;case 3:Se.msg="invalid block type",UA.mode=30}wt>>>=2,_t-=2;break;case 14:for(wt>>>=7&_t,_t-=7&_t;_t<32;){if(xi===0)break A;xi--,wt+=ii[Gi++]<<_t,_t+=8}if((65535&wt)!=(wt>>>16^65535)){Se.msg="invalid stored block lengths",UA.mode=30;break}if(UA.length=65535&wt,_t=wt=0,UA.mode=15,Bt===6)break A;case 15:UA.mode=16;case 16:if(ho=UA.length){if(xi>>=5,_t-=5,UA.ndist=1+(31&wt),wt>>>=5,_t-=5,UA.ncode=4+(15&wt),wt>>>=4,_t-=4,286>>=3,_t-=3}for(;UA.have<19;)UA.lens[WD[UA.have++]]=0;if(UA.lencode=UA.lendyn,UA.lenbits=7,MI={bits:UA.lenbits},Pl=T(0,UA.lens,0,19,UA.lencode,0,UA.work,MI),UA.lenbits=MI.bits,Pl){Se.msg="invalid code lengths set",UA.mode=30;break}UA.have=0,UA.mode=19;case 19:for(;UA.have>>16&255,SI=65535&Yg,!((Rr=Yg>>>24)<=_t);){if(xi===0)break A;xi--,wt+=ii[Gi++]<<_t,_t+=8}if(SI<16)wt>>>=Rr,_t-=Rr,UA.lens[UA.have++]=SI;else{if(SI===16){for(zu=Rr+2;_t>>=Rr,_t-=Rr,UA.have===0){Se.msg="invalid bit length repeat",UA.mode=30;break}Ya=UA.lens[UA.have-1],ho=3+(3&wt),wt>>>=2,_t-=2}else if(SI===17){for(zu=Rr+3;_t>>=Rr)),wt>>>=3,_t-=3}else{for(zu=Rr+7;_t>>=Rr)),wt>>>=7,_t-=7}if(UA.have+ho>UA.nlen+UA.ndist){Se.msg="invalid bit length repeat",UA.mode=30;break}for(;ho--;)UA.lens[UA.have++]=Ya}}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,MI={bits:UA.lenbits},Pl=T(P,UA.lens,0,UA.nlen,UA.lencode,0,UA.work,MI),UA.lenbits=MI.bits,Pl){Se.msg="invalid literal/lengths set",UA.mode=30;break}if(UA.distbits=6,UA.distcode=UA.distdyn,MI={bits:UA.distbits},Pl=T(W,UA.lens,UA.nlen,UA.ndist,UA.distcode,0,UA.work,MI),UA.distbits=MI.bits,Pl){Se.msg="invalid distances set",UA.mode=30;break}if(UA.mode=20,Bt===6)break A;case 20:UA.mode=21;case 21:if(6<=xi&&258<=ar){Se.next_out=Lr,Se.avail_out=ar,Se.next_in=Gi,Se.avail_in=xi,UA.hold=wt,UA.bits=_t,M(Se,ln),Lr=Se.next_out,_s=Se.output,ar=Se.avail_out,Gi=Se.next_in,ii=Se.input,xi=Se.avail_in,wt=UA.hold,_t=UA.bits,UA.mode===12&&(UA.back=-1);break}for(UA.back=0;xg=(Yg=UA.lencode[wt&(1<>>16&255,SI=65535&Yg,!((Rr=Yg>>>24)<=_t);){if(xi===0)break A;xi--,wt+=ii[Gi++]<<_t,_t+=8}if(xg&&!(240&xg)){for(ac=Rr,Af=xg,ip=SI;xg=(Yg=UA.lencode[ip+((wt&(1<>ac)])>>>16&255,SI=65535&Yg,!(ac+(Rr=Yg>>>24)<=_t);){if(xi===0)break A;xi--,wt+=ii[Gi++]<<_t,_t+=8}wt>>>=ac,_t-=ac,UA.back+=ac}if(wt>>>=Rr,_t-=Rr,UA.back+=Rr,UA.length=SI,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(zu=UA.extra;_t>>=UA.extra,_t-=UA.extra,UA.back+=UA.extra}UA.was=UA.length,UA.mode=23;case 23:for(;xg=(Yg=UA.distcode[wt&(1<>>16&255,SI=65535&Yg,!((Rr=Yg>>>24)<=_t);){if(xi===0)break A;xi--,wt+=ii[Gi++]<<_t,_t+=8}if(!(240&xg)){for(ac=Rr,Af=xg,ip=SI;xg=(Yg=UA.distcode[ip+((wt&(1<>ac)])>>>16&255,SI=65535&Yg,!(ac+(Rr=Yg>>>24)<=_t);){if(xi===0)break A;xi--,wt+=ii[Gi++]<<_t,_t+=8}wt>>>=ac,_t-=ac,UA.back+=ac}if(wt>>>=Rr,_t-=Rr,UA.back+=Rr,64&xg){Se.msg="invalid distance code",UA.mode=30;break}UA.offset=SI,UA.extra=15&xg,UA.mode=24;case 24:if(UA.extra){for(zu=UA.extra;_t>>=UA.extra,_t-=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(ar===0)break A;if(ho=ln-ar,UA.offset>ho){if((ho=UA.offset-ho)>UA.whave&&UA.sane){Se.msg="invalid distance too far back",UA.mode=30;break}ho>UA.wnext?(ho-=UA.wnext,ll=UA.wsize-ho):ll=UA.wnext-ho,ho>UA.length&&(ho=UA.length),DC=UA.window}else DC=_s,ll=Lr-UA.offset,ho=UA.length;for(ar_i?(kt=ll[DC+xA[Bt]],Ni=_t[Wu+xA[Bt]]):(kt=96,Ni=0),SA=1<>Lr)+(OA-=SA)]=Ti<<24|kt<<16|Ni,OA!==0;);for(SA=1<>=1;if(SA!==0?(wt&=SA-1,wt+=SA):wt=0,Bt++,--ln[Se]==0){if(Se===ii)break;Se=W[iA+xA[Bt]]}if(_s{const M=new Uint8Array(D).slice(4);let T;try{T=Sl.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 I;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?Na(E).buffer:E;(I=this._socketAdapter)===null||I===void 0||I.send(P)}else this._pendingRequests.delete(g)})}_onConnect(s){const{socketId:n,event:g={}}=s||{};this._connectionId=n,this._connectionEstablishedTime=Date.now();const I=Date.now()-this._connectionStartTime,E=`${nt}.onConnect cost:${I} ms. socketID:${n} res:${JSON.stringify(g)}`;if(this._ssoLog({method:"onConnect",message:E}),this._checkPendingRequestsAndResend(),this._sendHeartbeatIfReady(),this._isReconnecting){const m=`${nt}.reconnect success`;this._ssoLog({method:"reconnectSuccess",message:m}),gn.emitInnerEvent(Oe.RECONNECTED),this._isReconnecting=!1}this._resetReconnectDelay(),this._handleConnectStateChange({state:qi,shouldEmitEvent:!0,shouldAttemptReconnect:!1})}_sendAck(s){const n=Ia({servcmd:"openim.ws_msg_push_ack",data:{SessionData:s}});this.sendPacket(n)}_executeScheduledTaskIfReady(){return mA(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 mA(this,void 0,void 0,function*(){var s;const n=Ia({servcmd:"heartbeat.alive",data:{}});try{const g=`${n.head.seq}${n.head.servcmd}`;yield this.sendPacket(n,{requestId:g,timeout:3e3})}catch(g){const I=(s=Zi.get("netWorkMonitor"))===null||s===void 0?void 0:s.isNetworkOnline,E=`${nt}.sendHeartbeat failed. isNetWorkOnline:${I} error: ${en(g)}`;this._ssoLog({method:"sendHeartbeatError",message:E}),this._handleConnectStateChange({state:Mi,shouldEmitEvent:!0,shouldAttemptReconnect:!0})}})}_sendHeartbeatIfReady(){return mA(this,void 0,void 0,function*(){this._canSendHeartbeat()&&(this._isHeartbeatInProgress=!0,yield this._sendHeartbeat(),this._isHeartbeatInProgress=!1)})}_updateHeartbeatTime(){this._nextHeartbeatAt=_o?Date.now()+5e3:Date.now()+1e4}_handleNetworkStatusChange(s){const n=`${nt}.networkStatusChange ${JSON.stringify(s)}`;this._ssoLog({method:"networkStatusChange",message:n});const{isNetworkOnline:g,networkType:I}=s;g&&I!=="none"?this._handleConnectStateChange({state:qi,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Mg}):this._handleConnectStateChange({state:Mi,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Mg})}isPrivateNetWork(){const s=Zi.get("instance")||{};return s.proxyServer&&!s.fileDownloadProxy}_handleConnectStateChange(s){const{state:n,shouldAttemptReconnect:g,shouldEmitEvent:I,reason:E}=s,m=`${nt}._handleConnectStateChange currentConnectState: ${this._currentConnectState} shouldAttemptReconnect: ${g} shouldEmitEvent: ${I} reason: ${E}`;this._currentConnectState!==n&&(this._ssoLog({method:"handleConnectStateChange",message:m}),I&&(Ot.info("_handleConnectStateChange",` from ${this._currentConnectState} to ${n}`),gn.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:n}}),this._currentConnectState=n,n===Mi&&gn.emitInnerEvent(Oe.SOCKET_DISCONNECTED)),g&&(this._resetReconnectDelay(),fn.addTask({id:Ji,intervalMs:this._intendedDelay,callback:this._scheduleReconnectWithBackoff,context:this})))}_handleActivityStatusChange(s){var n,g;const I=(g=(n=this._socketAdapter)===null||n===void 0?void 0:n._ws)===null||g===void 0?void 0:g.readyState,E=`${nt}.activityStatusChange ${JSON.stringify(s)} readyState: ${I}`;Ot.debug("activityStatusChange",E),I===3&&this._handleConnectStateChange({state:Mi,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:or})}_resetReconnectDelay(){var s;Ot.debug(`${nt}._resetReconnectDelay`),fn.removeTask(Ji);const n=(s=Zi.get("activityMonitor"))===null||s===void 0?void 0:s.isActive;this._intendedDelay=n?Wo:1e3}_scheduleReconnectWithBackoff(){var s;const n=(s=Zi.get("activityMonitor"))===null||s===void 0?void 0:s.isActive;this._intendedDelay=n?Math.min(5e3,Math.max(Wo,1.5*this._intendedDelay)):Math.min(3e5,Math.max(1e3,1.5*this._intendedDelay));const g=new Date().toTimeString().slice(0,8),I=`${nt}.scheduleReconnectWithBackoff timeStr: ${g} intendedDelay: ${this._intendedDelay}`;Ot.debug(I),this.reconnect(),fn.updateTaskInterval(Ji,this._intendedDelay)}_ssoLog(s){const{method:n,message:g}=s;Ot.info(n,g)}_diagnose(){this.isPrivateNetWork()||(this._lastDiagnoseAt=Date.now(),function(s){mA(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(I){Ot.warn("diagnoseBySSO",`diagnoseBySSO failed. error:${I.message}`)}})}(this._url),function(s){mA(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){Ot.warn(`diagnoseByCDN', 'diagnoseByCDN failed. error:${g.message}`)}})}(this._url),this._beforeSendInterceptors=[])}_clearTimeoutRequest(){for(const[s,n]of this._pendingRequests.entries()){const{reject:g,timestamp:I,timeout:E}=n;Date.now()-I>=E&&(this._pendingRequests.delete(s),Date.now()-this._lastDiagnoseAt>=3e4&&this._diagnose(),g({errorCode:Br,errorInfo:"NETWORK_TIMEOUT",data:{requestId:s}}))}}_updateIsBinarySupported(){var s;if(!((s=Zi.get("instance"))===null||s===void 0)&&s.devMode)return void(this._isBinarySupported=!1);const n=Es();if((gi||It&&n==="windows"||Vs)&&(this._isBinarySupported=!1),_o){const{uniRuntimeVersion:g=""}=io.getSystemInfoSync();(function(I){const E=I.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 me={init:function(s){Zi.set("instance",s),fe.init()},destroy:function(){fe.dispose(),Zi.clear(),fn.dispose()},notificationCenter:gn,channel:fe,store:Zi,ssoLog:Ot,utils:yg,common:vA,constants:Dt},vg=s=>typeof s=="function";function rg(s,n,g){const I=g||[];if(!s||!n)return!1;const E=Object.keys(s).filter(D=>!I.includes(D)),m=Object.keys(n).filter(D=>!I.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,yr=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 Or;(function(s){s.UNSENT="unSend",s.SUCCESS="success",s.FAIL="fail"})(Or||(Or={}));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:Or,Direction:qc}),yu={[yc.modify]:so.TOPIC_MESSAGE_MODIFIED,[yc.delete]:so.TOPIC_MESSAGE_DELETED,[yc.revoke]:so.TOPIC_MESSAGE_REVOKED},CE={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({},CE),ba={CONV_C2C:"C2C",CONV_GROUP:"GROUP",CONV_TOPIC:"TOPIC",CONV_SYSTEM:"@TIM#SYSTEM"},Dc=Object.assign(Object.assign(Object.assign(Object.assign({},ba),{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"}),hE=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"}),ka={GRP_WORK:"Private",GRP_PUBLIC:"Public",GRP_MEETING:"ChatRoom",GRP_AVCHATROOM:"AVChatRoom",GRP_COMMUNITY:"Community",GRP_ROOM:"Room",GRP_LIVE:"Live"},oa={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},sI=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},ka),{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:oa,GROUP_TIPS_OPERATION_TYPE:Tg}),hs={IOS_OFFLINE_PUSH_NO_SOUND:"push.no_sound",IOS_OFFLINE_PUSH_DEFAULT_SOUND:"default"},ko=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},zg),ag),_g),Dc),hE),sI),hs),{NET_STATE_CONNECTING:"connecting",NET_STATE_DISCONNECTED:"disconnected",NET_STATE_CONNECTED:"connected"}),ua={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},sr={BASIC:"1",STANDARD:"2",PROFESSIONAL:"3",NODE:"4"},Pt={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"},Ht={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={[Pt.SYNC_SERVER_INFO_AFTER_RE_ONLINE]:[{stepId:Ht.USER_STATUS_UPDATE},{stepId:Ht.GROUP_ATTRIBUTE_CACHE_CLEAR},{stepId:Ht.UNREAD_MESSAGE_SYNC,dependency:Ht.C2C_HISTORY_MESSAGE_RECOVER},{stepId:Ht.CONVERSATION_RECOVER},{stepId:Ht.HISTORY_MESSAGE_RECOVER,dependency:Ht.CONVERSATION_RECOVER},{stepId:Ht.BLACKLIST_RECOVER},{stepId:Ht.FRIEND_RECOVER},{stepId:Ht.FRIEND_APPLICATION_LIST_RECOVER},{stepId:Ht.GROUP_REVOKED_NOTICE_RECOVER,dependency:Ht.HISTORY_MESSAGE_RECOVER},{stepId:Ht.GROUP_TIPS_RECOVER,dependency:Ht.HISTORY_MESSAGE_RECOVER},{stepId:Ht.TOPIC_REQUEST_INFO_RESET},{stepId:Ht.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,dependency:Ht.UNREAD_MESSAGE_SYNC},{stepId:Ht.HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD,dependency:Ht.UNREAD_MESSAGE_SYNC},{stepId:Ht.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Ht.UNREAD_MESSAGE_SYNC,Ht.CONVERSATION_RECOVER]},{stepId:Ht.EMIT_C2C_MESSAGE_EVENT,dependency:[Ht.UNREAD_MESSAGE_SYNC,Ht.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED],skipIfDependencyMissing:!1},{stepId:Ht.C2C_HISTORY_MESSAGE_RECOVER,dependency:Ht.CONVERSATION_RECOVER},{stepId:Ht.STREAM_MESSAGE_RECOVER}],[Pt.SYNC_SERVER_INFO_AFTER_LOGIN]:[{stepId:Ht.COMMERCIAL_CONFIG_UPDATE},{stepId:Ht.CLOUD_CONFIG_SYNC},{stepId:Ht.USER_PROFILE_SYNC},{stepId:Ht.UNREAD_MESSAGE_SYNC},{stepId:Ht.FRIEND_AND_BLACKLIST_SYNC},{stepId:Ht.GROUP_LIST_SYNC},{stepId:Ht.CONVERSATION_LIST_SYNC},{stepId:Ht.SIGNALING_MESSAGE_RECOVER,dependency:Ht.UNREAD_MESSAGE_SYNC},{stepId:Ht.UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED,dependency:[Ht.UNREAD_MESSAGE_SYNC]},{stepId:Ht.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Ht.UNREAD_MESSAGE_SYNC,Ht.CONVERSATION_LIST_SYNC]},{stepId:Ht.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,dependency:[Ht.GROUP_LIST_SYNC,Ht.CONVERSATION_LIST_SYNC]},{stepId:Ht.CONVERSATION_GROUP_LIST_SYNC},{stepId:Ht.CONVERSATION_GROUP_UPDATE,dependency:[Ht.CONVERSATION_LIST_SYNC,Ht.CONVERSATION_GROUP_LIST_SYNC]},{stepId:Ht.QUALITY_REPORT}],[Pt.RECEIVE_C2C_NEW_MESSAGE]:[{stepId:Ht.HANDLE_C2C_NEW_MESSAGE},{stepId:Ht.UNREAD_MESSAGE_SYNC},{stepId:Ht.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Ht.HANDLE_C2C_NEW_MESSAGE},{stepId:Ht.EMIT_C2C_MESSAGE_EVENT,dependency:[Ht.HANDLE_C2C_NEW_MESSAGE,Ht.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1},{stepId:Ht.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Ht.UNREAD_MESSAGE_SYNC]}],[Pt.RECEIVE_GROUP_NEW_MESSAGE]:[{stepId:Ht.HANDLE_GROUP_NEW_MESSAGE},{stepId:Ht.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Ht.HANDLE_GROUP_NEW_MESSAGE},{stepId:Ht.UPDATE_GROUP_NEXT_SEQUENCE,dependency:Ht.HANDLE_GROUP_NEW_MESSAGE},{stepId:Ht.UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE,dependency:Ht.HANDLE_GROUP_NEW_MESSAGE},{stepId:Ht.EMIT_GROUP_MESSAGE_EVENT,dependency:[Ht.HANDLE_GROUP_NEW_MESSAGE,Ht.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1}],[Pt.RECEIVE_GROUP_TIPS_NOTIFICATION]:[{stepId:Ht.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:Ht.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Ht.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:Ht.EMIT_GROUP_TIPS_EVENT,dependency:[Ht.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,Ht.HANDLE_GROUP_TIPS_NOTIFICATION],skipIfDependencyMissing:!1}]},nI={MESSAGE_SEND_SUCCESS_RATE:"messageSendSuccessRate"},nr={TOTAL_COUNT:"sendMessageTotalCount",SUCCESS_COUNT:"sendMessageSuccessCount",FAILED_COUNT:"sendMessageFailedCount",SEND_COST:"sendMessageCost"},PI=["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 Wa=Object.freeze({__proto__:null,ERROR_CODE:ua,InnerEvent:so,NEED_LOG_API:PI,OuterConstant:ko,OuterEvent:yr,PUSH:hs,QUALITY_METRICS:nI,SDK_EDITION:sr,SDK_INFO:{VERSION:"1.7.3",APPID:537048168},SEND_MESSAGE_STAT:nr,SignalingEvent:Hc,WEB_PUSH_ACCOUNT_TYPE:1,WORKFLOW_DEFINITIONS:Ng,WORKFLOW_NAME:Pt,WORKFLOW_STEP:Ht}),sa,un,Sn;(function(s){s[s.USER_INITIATED=0]="USER_INITIATED",s[s.KICKED_OUT=1]="KICKED_OUT"})(sa||(sa={})),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 Du={[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:La,DESTROY:Kc,FORCE_OFFLINE:xI}=so,{KICKED_OUT_MULT_ACCOUNT:BE,KICKED_OUT_MULT_DEVICE:rI,KICKED_OUT_REST_API:Su,ACCOUNT_A2KEY_EXPIRED:Ml,MSG_A2KEY_EXPIRED:Sc}=ua;class Mu{init(){const{notificationCenter:n}=me;n.subscribeInnerEvent(xI,this._handleForceOfflineFromServerPush,this),n.subscribeInnerEvent(La,Sc,this._handleForceOfflineFromResponse,this,this._isChatLoginEvent),n.subscribeInnerEvent(La,Ml,this._handleForceOfflineFromResponse,this,this._isChatLoginEvent),n.subscribeInnerEvent(La,BE,this._handleForceOfflineFromResponse,this),n.subscribeInnerEvent(La,rI,this._handleForceOfflineFromResponse,this),n.subscribeInnerEvent(La,Su,this._handleForceOfflineFromResponse,this),n.subscribeInnerEvent(Kc,this._dispose,this)}_handleForceOfflineFromServerPush(n){var g;if(((g=me.store.get("login"))===null||g===void 0?void 0:g.isLoggedIn)===!0){const{EventArray:I=[]}=n?.body||{};this._extractKickedOutMessages(I).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,I)=>[...g,...I.C2cNotifyMsgArray||[]],[]).filter(g=>{var I;return this._isKickedOut((I=g?.KickoutMsgNotify)===null||I===void 0?void 0:I.KickType)})}_handleForceOfflineFromResponse(n){const{errorCode:g}=n;this._processKickedOutReasonInfo({kickedOutReasonCode:g})}_processKickedOutReasonInfo(n){return mA(this,void 0,void 0,function*(){const{kickedOutReasonCode:g}=n,{ssoLog:I,utils:{safeStringify:E}}=me;try{this._logKickedOutEvent(n),this._shouldLogoutAfterKickedOut(g)?yield me.login.loginAction.logout(sa.KICKED_OUT):me.login.loginAction.handleLogoutCompleted()}catch(m){I.debug("_processKickedOutReasonInfo",` fail ${E(m)}`)}finally{me.notificationCenter.emitOuterEvent(yr.KICKED_OUT,{data:{type:Du[g]},name:yr.KICKED_OUT})}})}_logKickedOutEvent(n){const{kickedOutReasonCode:g,newInstanceInfo:I={}}=n,E=`type:${Du[g]} newInstanceInfo: ${JSON.stringify(I)}`;me.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:I}=me.store.get("login")||{};return g===!0&&n===I}_dispose(){const{notificationCenter:n}=me;n.unSubscribeInnerEvent(xI,this._handleForceOfflineFromServerPush,this),n.unSubscribeInnerEvent(La,Ml,this._handleForceOfflineFromResponse,this),n.unSubscribeInnerEvent(La,Sc,this._handleForceOfflineFromResponse,this),n.unSubscribeInnerEvent(La,BE,this._handleForceOfflineFromResponse,this),n.unSubscribeInnerEvent(La,rI,this._handleForceOfflineFromResponse,this),n.unSubscribeInnerEvent(La,Su,this._handleForceOfflineFromResponse,this),n.unSubscribeInnerEvent(Kc,this._dispose,this)}}function vu(s){return mA(this,void 0,void 0,function*(){const n="im_open_status.wslogin",g=me.common.generateProtocolData({servcmd:n,data:{State:"Online",is_web_uniapp:0,InstType:0,CustomInfo:s}}),I=`${g.head.seq}${n}`,E=yield me.channel.sendPacket(g,{timeout:9e4,requestId:I});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 vl(){const{store:s}=me;return la(s.get("instance").sdkAppId)!==ct.CHINA}function rs(s){var n;try{const g=Zi.getStorage("errorMessage");if(!s||!g)return"";const I=((n=JSON.parse(g))===null||n===void 0?void 0:n.errorMessage)||{},{code:E,replacement1:m="",replacement2:D=""}=s;if(!E)return"";const M=vl()?`${E}_en`:`${E}_cn`;let T=I[I[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:I,message:E="",data:m="",moreMessage:D="",errorMessage:M=""}=n;M=(I?rs(n):"")||M||E;let T=I?`${g} failed. error: {"message": ${M}, "code": ${I}}`:`${g} failed. error: {"message": ${M}}`;T=`${T} ${D}`,super(),this.code=I,this.errorCode=I,this.errorMessage=M,this.message=T,this.data=m}}function rd(s,n){var g;if(s&&((g=me.store.get("login"))===null||g===void 0?void 0:g.isLoggedIn)!==!0)throw new gs({code:ua.USER_NOT_LOGGED_IN,functionName:n})}function aI(s,n,g){if(Array.isArray(s))for(let I=0;I{return P===(W=I,Object.prototype.toString.call(W).match(/^\[object (.*)\]$/)[1].toLowerCase());var W})){for(let W=0;W{const{interceptor:E,context:m}=I;E.apply(m,[g])})}(s)}function Mc(s,n){QE.push({interceptor:s,context:n})}function jc(s){const{params:n,auth:g}=s;n&&typeof n=="object"&&Object.assign(Rl,n),g&&typeof g=="object"&&Object.assign(ad,g)}function tn(s){return me.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 I=Date.now();g?(this._stepStartTimes.set(`${n}-${g}`,I),me.ssoLog.debug("_executeWorkflowStep",`[Workflow ${n}] Step ${g} started at ${new Date(I).toISOString()}`)):(this._workflowStartTimes.set(n,I),me.ssoLog.debug("_executeWorkflowStep",`[Workflow ${n}] started at ${new Date(I).toISOString()}`))},success:(n,g)=>{const I=Date.now();if(g){const E=this._stepStartTimes.get(`${n}-${g}`),m=E?I-E:0;this._stepStartTimes.delete(`${n}-${g}`),me.ssoLog.debug("_executeWorkflowStep",`[Workflow ${n}] Step ${g} completed successfully at ${new Date(I).toISOString()} (${m}ms)`)}else{const E=this._workflowStartTimes.get(n),m=E?I-E:0;this._workflowStartTimes.delete(n),me.ssoLog.debug("_executeWorkflowStep",`[Workflow ${n}] completed successfully at ${new Date(I).toISOString()} (${m}ms)`)}},error:(n,g,I)=>{const{ssoLog:E,utils:{safeStringify:m}}=me,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(I)}`,{error:I})}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(I)}`,{error:I})}}}}static getInstance(){return ws._instance||(ws._instance=new ws),ws._instance}static setInstance(n){ws._instance=n}init(){this._initializeWorkflows()}registerWorkflowStep(n,g,I,E){if(!this._handlers.has(n))return void me.ssoLog.debug("registerWorkflowStep",`Workflow '${n}' not defined in core`);if(!Ng[n].find(D=>D.stepId===g))return void me.ssoLog.debug("registerWorkflowStep",`Step '${g}' not defined in workflow '${n}'`);const m=this._handlers.get(n);m.has(g)||m.set(g,E?I.bind(E):I)}executeWorkflow(n,g){return mA(this,void 0,void 0,function*(){if(!this._validateWorkflow(n))return;me.ssoLog.debug("executeWorkflow",`[Workflow ${n}] Started execution at ${new Date().toISOString()}`);const I=Ng[n],E={},m={cancelled:!1};this._activeWorkflows.set(n,{cancelToken:m});try{const D=new Map;I.forEach(T=>{D.set(T.stepId,T)});const M={workflowName:n,pendingSteps:new Set(I.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&&(me.ssoLog.debug("executeWorkflow",`Workflow ${n} completed with some steps skipped due to dependency failures`),T())},onError:P,onStepComplete:W})})};W()}),me.ssoLog.debug("executeWorkflow",`[Workflow ${n}] Completed execution at ${new Date().toISOString()}`)}catch(D){me.ssoLog.error("executeWorkflow",`[Workflow ${n}] Failed execution at ${new Date().toISOString()}`,{error:D})}finally{this._activeWorkflows.delete(n)}})}_executeWorkflowStep(n,g,I){return mA(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});me.ssoLog.error(W,EA,{error:RA}),this._logWorkflowExecution(E,n,"error",P),I.onError(P)}finally{m.delete(n),g.pendingSteps.delete(n),I.onStepComplete(),I.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:I}=g;I.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:I,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})?I.has(T):!P;if(B(T)){if(T.filter(W=>!this._isStepRegistered({workflowName:m,stepId:W})).length>0&&P)return!1;for(const W of T)if(!I.has(W))return!1;return!0}return!1})}_isStepRegistered(n){var g;const{workflowName:I,stepId:E}=n;return(g=this._handlers.get(I))===null||g===void 0?void 0:g.has(E)}_logWorkflowExecution(n,g,I,E){this._logHandlers[I](n,g)}}const Ea=new Map,zr=({type:s,groupID:n})=>s===ko.GRP_COMMUNITY||`${n}`.startsWith(oa.COMMUNITY)&&!`${n}`.includes(oa.TOPIC),Wc=(s="")=>{const n=s.startsWith("GROUP")?s.replace("GROUP",""):s;return n.startsWith(oa.COMMUNITY)&&`${n}`.includes(oa.TOPIC)},gd="openim",Zg="million_group_open_http_svc";function gg(s){return mA(this,void 0,void 0,function*(){const{servcmd:n,data:g}=function(m){const{data:D}=m;return pE(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(oa.TOPIC),{servcmd:qn(P),data:Object.assign(Object.assign({},W),{GroupId:iA,TopicId:EA})}}(m):(pE(M)&&(D=qn(D)),{servcmd:D,data:M})}(s):s,I=me.common.generateProtocolData({servcmd:n,data:g}),E=`${I.head.seq}${n}`;return me.channel.sendPacket(I,{requestId:E,timeout:s.timeout})})}function pE(s){const{Type:n,GroupId:g,GroupIdList:I=[]}=s,E=g||I[0]||"";return zr({type:n,groupID:E})}function Xg(s){const{GroupId:n=""}=s;return Wc(n)}function qn(s){if(s.includes(gd))return s;const n=s.split(".")[1];return`${Zg}.${n}`}function Ar(){var s;return(s=me.store.get("login"))===null||s===void 0?void 0:s.userId}const Ua=s=>B(s)||f(s),cd=(s,n,g,I)=>{if(!Ua(s)||!Ua(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===ko.MSG_TEXT)return n.text||"";const g=YI[s];return g?Ru(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}],VI="im_sdk_config_mgr.fetch_config",cI="im_sdk_config_mgr.push_configv2",Xc="cloud-config",$c=2996,Ma=new class{init(s){this.core=s}};function bg(s){return mA(this,void 0,void 0,function*(){const{sdkAppId:n}=Ma.core.store.get("instance")||{},g=Ma.core.helper.generateProtocolData({servcmd:VI,data:{uint32_sdkappid:n,uint64_version:s}}),I=`${g.head.seq}${VI}`;return Ma.core.channel.sendPacket(g,{requestId:I})})}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:I,constants:{WORKFLOW_NAME:E,WORKFLOW_STEP:m},channel:D}=s;n.subscribeInnerEvent(cI,this._handlePushedConfig,this),I.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),I.registerExperimentalAPI("getServerConfig",this),this._updateCmdFreqLimitMap(Zc),D.registerBeforeSendInterceptor(this.checkMethodCallOverLimit,this)}getServerConfig(s){return mA(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:I,methodCallCounter:E}=this._methodCallFrequencyMap.get(s);if(Date.now()-I>1e3*g)this._methodCallFrequencyMap.set(s,{startTime:Date.now(),methodCallCounter:1});else if(E+=1,this._methodCallFrequencyMap.set(s,{startTime:I,methodCallCounter:E}),E>n)throw new this._core.helper.ChatError({code:$c,replacement1:s})}_handlePushedConfig(s){return mA(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 mA(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 mA(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 mA(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:I,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(I),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 mA(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(I){console.warn(I)}})}_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(cI,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 I=8-g.length;for(;I;)g=`0${g}`,I--}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",HI="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:I,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(I.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 mA(this,void 0,void 0,function*(){const n=parseInt(s,10).toString(2),{length:g}=n;let I,E=!0;for(let m=g-1,D=0;m>=0;m--,D++)if(n.charAt(m)==="1"&&(I=D<32?new Kn(0,2**D).toString():new Kn(2**(D-32),0).toString(),!this._featureMap.get(I))){E=!1;break}return this._core.ssoLog.debug("isFeatureEnabled",`${JI}.isFeatureEnabled decimalNumber:${s} key:${I} ret:${E}`),{code:0,data:{enabled:E}}})}queryCommercialAbility(){return this._purchaseBits}_fetchAndParseCommercialConfig(){return mA(this,void 0,void 0,function*(){var s;const{ssoLog:n,utils:{safeStringify:g},common:{buildAndSendPacket:I}}=this._core;try{this._isFetching=!0;const E=yield I({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 mA(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:HI,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 mA(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:I,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:${I}`),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 I=null;for(let E=s.length-1,m=0;E>=0;E--,m++)if(I=m<32?new Kn(0,2**m).toString():new Kn(2**(m-32),0).toString(),s[E]==="1"){this._featureMap.set(I,!0);const D=this._getKeyByValue(vc,I);D&&this._methodKeyMap.set(D,!0)}else{this._featureMap.set(I,!1);const D=this._getKeyByValue(vc,I);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(([I,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(HI),this._core.store.set("commercialConfig",{}),this._expirationTime=0,this._isFetching=!1,this._featureMap.clear(),this._purchaseBits="0"}},oh=new class{constructor(){this._core=null,this._serverOverloadInfoMap=new Map}install(s){this._core=s;const{notificationCenter:n,InnerEvent:g,channel:I}=this._core;n.subscribeInnerEvent(g.OVERLOAD_PUSH,this._handleOverLoadPush,this),n.subscribeInnerEvent(g.LOGOUT,this._reset,this),n.subscribeInnerEvent(g.DESTROY,this._dispose,this),I.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)}},nC=new class{constructor(){this.name="ConfigCenter"}install(s){Ma.init(s),ys.install(s),mE.install(s),oh.install(s)}},sh=new class{constructor(){this.name="ErrorMessage",this._core=null}install(s){return mA(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 mA(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={},I=new RegExp(/'/g);for(let E=0;E{var JA,re,ne;const _i=function(Ti,kt){const{From_Account:Ni,From_AccountHeadurl:cs,From_AccountNick:Se,IsNeedReadReceipt:Bt,MsgBody:UA,MsgClientTime:ii,MsgRandom:_s,MsgSeq:Gi,MsgTimeStamp:Lr,SendMsgControl:xi,SupportMessageExtension:ar,To_Account:wt,TinyId:_t,MsgCheckResult:Wu,CloudCustomData:ln,IsPeerRead:ho,MsgFlagBits:ll,MsgVersion:DC,EventArray:Rr}=Ti;return{from:Ni,avatar:cs,nick:Se,needReadReceipt:Bt===1,readReceiptSentByPeer:ho,clientTime:ii,messageFlagBits:ll,random:_s,sequence:Gi,time:Lr,messageControlInfo:xi,isSupportExtension:ar,to:wt,tinyID:_t,checkResult:Wu,cloudCustomData:ln,messageVersion:DC,eventArray:Rr,elements:kt.message.messageHelper.parseServerPushMessageElement(UA)}}(OA,xA);if(!((ne=(re=(JA=OA?.EventArray)===null||JA===void 0?void 0:JA[0])===null||re===void 0?void 0:re.hasOwnProperty)===null||ne===void 0)&&ne.call(re,"C2cNotifyMsgArray"))SA.push(...function(Ti){var kt;const Ni=[];return(kt=Ti.EventArray)===null||kt===void 0||kt.forEach(cs=>{var Se,Bt;const{C2cNotifyMsgArray:UA}=cs,ii=(Bt=(Se=UA?.[0])===null||Se===void 0?void 0:Se.WithdrawC2cMsgNotify)===null||Bt===void 0?void 0:Bt.C2cWithdrawInfoArray;Array.isArray(ii)&&Ni.push(...ii)}),Ni}(OA));else{const Ti=xA.message.messageFactory.createMessage(Object.assign(Object.assign({},_i),{conversationType:"C2C",flow:"in"})),{elements:kt}=_i;Ti.setElement(kt),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 rC=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 mA(this,void 0,void 0,function*(){const{isAfterReOnline:n=!1,isAfterNewMessageReceived:g=!1,isAfterLogin:I=!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:!I,isUnreadC2CMessage:!0,revokedMessageList:M,unreadMessageMap:this._unreadDBMessageMap,groupTipList:D}})}_syncUnreadDBMessageAfterLogin(){return mA(this,void 0,void 0,function*(){return this._cookie="",this._syncUnreadMessage({isAfterLogin:!0})})}_syncUnreadDBMessageAfterNewMessageReceived(s){return mA(this,void 0,void 0,function*(){if(s.data.Flag===1)return this._syncUnreadMessage({isAfterNewMessageReceived:!0})})}_updateConversationUnreadOptions(s){const{unreadCountList:n,overflowUnreadCountList:g,conversationUpdateFieldList:I}=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=I.find(({conversationID:W})=>W===`${E}${M}`);P?P.unreadCount=T:I.push({conversationID:`${E}${M}`,unreadCount:T,type:E})}}),g?.forEach(D=>{const{From_Account:M,LastMsgTime:T}=D;M!==m&&(I.find(({conversationID:P})=>P===`${E}${M}`)||I.push({conversationID:`${E}${M}`,type:E,lastMsgTime:T}))})}_syncUnreadDBMessageAfterReOnline(){return mA(this,void 0,void 0,function*(){return this._syncUnreadMessage({isAfterReOnline:!0})})}_updateMessageProfile(s){var n;const{messageDataHandler:g}=this._core.message||{},I=(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!==I){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,I=[];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)||I.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||I.push(E)}}),{messages:I,conversationOptions:g}}_shouldStoreUnreadMessage(s){var n;const{conversationID:g}=s,{message:I,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!I.messageDataHandler.isInMessageList(s)&&D.includes(g)&&this._localConversationIDListBeforeDisconnect.includes(g)&&!m(M)}_fetchUnreadDBMessage(s){return mA(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(I){console.log(I)}})}_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),I=g[g.length-1];return I?.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()}},fE=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()}},yE=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,I,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})})):((I=m?.onAppShow)===null||I===void 0||I.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()}},ld=new class{init(s){const{IN_MINI_APP:n,IN_WX_MINI_PLUGIN:g}=s.helper;g||(n?yE.init(s):fE.init(s))}};const DE="none",el="online";var lI=new class{init(s){this._core=s,this._activateNetworkMonitoring(),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return mA(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:I,networkType:E}=s;(n=this._core)===null||n===void 0||n.store.set("netWorkMonitor",{isNetworkOnline:I,networkType:E}),(g=this._core)===null||g===void 0||g.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:I,networkType:E})}_onOnline(){this._onNetworkStatusChange({isConnected:!0,networkType:el})}_onOffline(){this._onNetworkStatusChange({isConnected:!1,networkType:DE})}_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()}},wu=new class{init(s){this._core=s,this._activateNetworkMonitoring(),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return mA(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:I,networkType:E}=s;(n=this._core)===null||n===void 0||n.store.set("netWorkMonitor",{isNetworkOnline:I,networkType:E}),(g=this._core)===null||g===void 0||g.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:I,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()}},_u=new class{init(s){const{IN_MINI_APP:n}=s.utils;n?wu.init(s):lI.init(s)}},aC=new class{constructor(){this.name="SystemStateMonitor"}install(s){ld.init(s),_u.init(s)}};const Mr=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=Mr}install(s){this._core=s;const{notificationCenter:n,InnerEvent:g,helper:I}=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),I.registerExperimentalAPI("sendTRTCCustomData",this,"transferBusinessCommand"),I.registerExperimentalAPI("sendRoomCustomData",this,"transferBusinessCommand")}transferBusinessCommand(s){return mA(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 mA(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:I}=s||{},{ROOM_CUSTOM_DATA_RECEIVED:E}=n;g.emitOuterEvent(E,{name:E,data:I})}_reset(){this._transferredCommands=Mr}_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 Tu=1,wl=2,Id=3,Zr=4,II=5,_n="TIMCustomElem",gC="C2C",tl="GROUP",ud="invite",uI="accept",Fa="cancel",cC="reject",Oa="modifyInvitation",Ir="signaling",Ed=8010,Nu="signaling-timeout";function ur(s){return s.filter(n=>{if(n.type===_n){const{cloudCustomData:g="",payload:{data:I=""}={}}=n,E=g.match(/"type":"tsignaling"/),m=I.match(/inviteID/),D=I.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=`${Ir}.updateSignaling`,{inviteID:g,inviter:I,inviteeList:E,groupID:m}=s;if(console.log(`${n} inviteID:${g} inviter:${I} 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:I,inviteeList:E}=g,m=I||E[0];return{signaling:this._createSignaling(g,m),signalingData:g,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createAcceptSignaling(s){const n=this._createAcceptSignalingData(s),{groupID:g,inviter:I}=n,E=g||I;return{signaling:this._createSignaling(n,E),signalingData:n,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createCancelSignaling(s){const n=this._createCancelSignalingData(s),{groupID:g,inviteeList:I}=n,E=g||I[0];return{signaling:this._createSignaling(n,E),signalingData:n,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createRejectSignaling(s){const n=this._createRejectSignalingData(s),{groupID:g,inviter:I}=n,E=g||I;return{signaling:this._createSignaling(n,E),signalingData:n,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createTimeoutSignaling(s){const{isInviter:n=!1}=s,g=this._createTimeoutSignalingData(s),{groupID:I,inviteeList:E,inviter:m}=g,D=I||(n?E[0]:m);return{signaling:this._createSignaling(g,D),signalingData:g,signalingExtensionOptions:this._createSignalingExtensionOptions(g)}}_createSignalingExtensionOptions(s){var n,g;const{data:I="",onlineUserOnly:E,inviteID:m="",offlinePushInfo:D,actionType:M}=s,T=((g=(n=Fo.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(I,M)}}_createMessageControlInfo(s,n){const g=n===II&&!!s.match(/excludeTimeoutSignalingFromHistoryMessage/),I=!!s.match(/excludeFromHistoryMessage/)||!!s.match(/excludeOriginalSignalingFromHistoryMessage/);return{excludedFromContentModeration:!0,excludedFromUnreadCount:g||I,excludedFromLastMessage:g||I}}_createInviteSignalingData(s){const n=`${Ir}._createInviteSignalingData`,{userID:g,timeout:I=0,groupID:E="",inviteeList:m=[]}=s,D=this._core.common.getCurrentUserID(),M=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:Tu,inviter:D,inviteeList:E?m:[g],timeout:I});return console.log(`${n} signalingData:`,M),M}_createAcceptSignalingData(s){const n=`${Ir}._createAcceptSignalingData`,{inviteID:g}=s,I=this._core.common.getCurrentUserID(),{inviter:E,groupID:m}=Fo.getSignaling(g),D=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:Id,groupID:m,inviter:E,inviteeList:[I]});return console.log(`${n} signalingData:`,D),D}_createCancelSignalingData(s){const n=`${Ir}._createCancelSignalingData`,{inviteID:g}=s,I=this._core.common.getCurrentUserID(),{inviteeList:E,groupID:m}=Fo.getSignaling(g),D=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:wl,groupID:m,inviter:I,inviteeList:E});return console.log(`${n} signalingData:`,D),D}_createRejectSignalingData(s){const n=`${Ir}._createRejectSignalingData`,{inviteID:g}=s,I=this._core.common.getCurrentUserID(),{inviter:E,groupID:m}=Fo.getSignaling(g),D=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:Zr,groupID:m,inviter:E,inviteeList:[I]});return console.log(`${n} signalingData:`,D),D}_createTimeoutSignalingData(s){const n=`${Ir}._createTimeoutSignalingData`,{isInviter:g=!1,inviteID:I}=s,{inviteeList:E,inviter:m}=Fo.getSignaling(I),D=this._core.common.getCurrentUserID(),M=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:II,inviter:m,inviteeList:g?E:[D]});return console.log(`${n} signalingData:`,M),M}_createSignaling(s,n){var g,I,E;const{groupID:m=""}=s,D={to:n,conversationType:m?tl:gC,priority:"High",payload:{data:JSON.stringify(s)}};return(E=(I=(g=this._core)===null||g===void 0?void 0:g.message)===null||I===void 0?void 0:I.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:I=""}=s;return{businessID:1,timeout:0,data:n,inviteID:g,groupID:I}}},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 mA(this,void 0,void 0,function*(){var n;try{this._validateBeforeInvite(s);const{signaling:g,signalingData:I,signalingExtensionOptions:E}=$g.createInviteSignaling(s),m=yield this._sendSignaling(g,E);if(m?.code===0){const{inviteID:D,timeout:M}=I;return Fo.saveSignaling(D,Object.assign(Object.assign({},I),{signaling:g})),M>0&&((n=this._core)===null||n===void 0||n.helper.taskScheduler.addOnceTask({id:`${Nu}-${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 mA(this,void 0,void 0,function*(){try{const{inviteID:n}=s;this._validateBeforeAccept(n),this._isProcessingSignaling=!0;const{signaling:g,signalingData:I,signalingExtensionOptions:E}=$g.createAcceptSignaling(s),m=yield this._sendSignaling(g,E);return m?.code===0?(Fo.updateSignaling(I),Object.assign(Object.assign({},m),{inviteID:n})):m}catch(n){throw n}finally{this._isProcessingSignaling=!1}})}cancel(s){return mA(this,void 0,void 0,function*(){try{const{inviteID:n}=s;this._validateBeforeCancel(n),this._isProcessingSignaling=!0;const{signaling:g,signalingExtensionOptions:I}=$g.createCancelSignaling(s),E=yield this._sendSignaling(g,I);return E?.code===0?(Fo.removeSignaling(n),Object.assign(Object.assign({},E),{inviteID:n})):E}catch(n){throw n}finally{this._isProcessingSignaling=!1}})}reject(s){return mA(this,void 0,void 0,function*(){try{const{inviteID:n}=s;this._validateBeforeReject(n),this._isProcessingSignaling=!0;const{signaling:g,signalingExtensionOptions:I}=$g.createRejectSignaling(s),E=yield this._sendSignaling(g,I);return E?.code===0?(Fo.removeSignaling(n),Object.assign(Object.assign({},E),{inviteID:n})):E}catch(n){throw n}finally{this._isProcessingSignaling=!1}})}modifyInvitation(s){return mA(this,void 0,void 0,function*(){var n,g;const{inviteID:I,data:E}=s;let m="";try{this._validateBeforeModifyInvitation(I);const D=Fo.getSignaling(I),{signaling:M}=D,T=yo(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 Fo.hasSignaling(I)&&Fo.saveSignaling(I,Object.assign(Object.assign({},T),{signaling:M})),P}catch(D){if(m){const{signaling:M}=Fo.getSignaling(I);M.payload.data=m}throw D}})}getSignalingInfo(s){const{ssoLog:n,utils:{safeStringify:g}}=this._core;if(ur([s]).length===0)return;const I=wc(s),E={businessID:I.businessID||1,inviteID:I.inviteID,groupID:I.groupID||"",inviter:I.inviter||"",inviteeList:I.inviteeList||[],data:I.data||"",actionType:I.actionType||Tu,timeout:I.timeout||0};return n.debug(`${Ir} getSignalingInfo ${g(E)}`),E}addSignalingListener(s,n,g){var I,E;s===((I=this._core)===null||I===void 0?void 0:I.SignalingEvent.NEW_INVITATION_RECEIVED)&&Fo.setSignalingListenStatus(!0),(E=this._core)===null||E===void 0||E.notificationCenter.subscribeOuterEvent(s,n,g)}removeSignalingListener(s,n,g){var I,E;s===((I=this._core)===null||I===void 0?void 0:I.SignalingEvent.NEW_INVITATION_RECEIVED)&&Fo.setSignalingListenStatus(!1),(E=this._core)===null||E===void 0||E.notificationCenter.unSubscribeOuterEvent(s,n,g)}handleInvitationExpiryTimer(s){const n=Fo.getOnlineSignalingMap(),g=this._core.common.getCurrentUserID();if(!n.has(s))return;const I=n.get(s).inviter===g;this._sendTimeoutNotice({inviteID:s,isInviter:I})}_sendSignaling(s,n){return mA(this,void 0,void 0,function*(){var g,I,E;return(E=(I=(g=this._core)===null||g===void 0?void 0:g.message)===null||I===void 0?void 0:I.messageSender)===null||E===void 0?void 0:E.sendMessage(s,n)})}_sendTimeoutNotice(s){return mA(this,void 0,void 0,function*(){var n,g,I;this._core.ssoLog.debug("_sendTimeoutNotice",`${Ir}._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:(I=this._core)===null||I===void 0?void 0:I.SignalingEvent.INVITATION_TIMEOUT,data:{data:W,groupID:iA,inviteID:m,inviteeList:EA,inviter:RA,isSelfTimeout:!0,message:D}}),E?Fo.removeSignaling(m):Fo.updateSignaling(M)}})}_validateInviteId(s,n){if(!Fo.hasSignaling(n))throw new this._core.helper.ChatError({functionName:s,code:Ed})}_validateProcessStatus(s){if(this._isProcessingSignaling)throw new this._core.helper.ChatError({functionName:s,message:"processing other signaling operations"})}_validateBeforeInvite(s){const n=ud,{userID:g}=s,I=this._core.common.getCurrentUserID();if(g===I)throw new this._core.helper.ChatError({functionName:n,message:`cannot invite yourself, currentUserId:${I}, inviteeId:${g}`})}_validateBeforeAccept(s){const n=uI;this._validateInviteId(n,s),this._validateProcessStatus(n);const g=this._core.common.getCurrentUserID(),{inviteeList:I}=Fo.getSignaling(s);if(!I.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=Fa;this._validateInviteId(n,s),this._validateProcessStatus(n);const g=this._core.common.getCurrentUserID(),{inviter:I}=Fo.getSignaling(s);if(I!==g){const E=`unmatched inviter:${I} 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:I}=Fo.getSignaling(s);if(!I.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=Oa;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}},_l=new class{constructor(){this._actionProcessor=new Map([[Tu,this._onNewInvitationReceived.bind(this)],[Zr,this._onInviteeRejected.bind(this)],[Id,this._onInviteeAccepted.bind(this)],[wl,this._onInvitationCancelled.bind(this)],[II,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 I=this._actionProcessor.get(g.actionType);I?.(g,n)}})}_handleMessageReceived(s){if(!Fo.getSignalingListenStatus())return;const n=ur(s.data);n.length!==0&&this.handleActionSignaling(n)}_handleMessageModified(s){if(!Fo.getSignalingListenStatus())return;const n=ur(s.data);n.length>0&&n.forEach(g=>{const I=wc(g);I&&this._onInvitationModified(I,g)})}_onNewInvitationReceived(s,n){var g,I;const E=`${Ir}._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=Fo.getSignaling(m);iA!==s&&(iA||Fo.saveSignaling(m,Object.assign(Object.assign({},s),{signaling:n})),P>0&&((g=this._core)===null||g===void 0||g.helper.taskScheduler.addOnceTask({id:`${Nu}-${m}`,intervalMs:1e3*P,callback:za.handleInvitationExpiryTimer.bind(za,m)})),this._emitEvent({name:(I=this._core)===null||I===void 0?void 0:I.SignalingEvent.NEW_INVITATION_RECEIVED,data:Object.assign(Object.assign({},this._generateBaseEmitData(s)),{inviteeList:D})}))}_onInviteeRejected(s){var n;const g=`${Ir}._onInviteeRejected`,{inviteID:I,inviter:E,groupID:m,inviteeList:D}=s,M=Fo.hasSignaling(I);this._core.ssoLog.debug("_onInviteeRejected",`${g} inviteID:${I} hasInviteID:${M} inviter:${E} groupID:${m}`),M&&(Fo.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=`${Ir}._onInviteeAccepted`,{inviteID:I,inviter:E,groupID:m,inviteeList:D}=s,M=Fo.hasSignaling(I);this._core.ssoLog.debug("_onInviteeAccepted",`${g} inviteID:${I} hasInviteID:${M} inviter:${E} groupID:${m}`),M&&(Fo.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=`${Ir}._onInvitationCancelled`,{inviteID:I,inviter:E,groupID:m}=s,D=Fo.hasSignaling(I);this._core.ssoLog.debug("_onInvitationCancelled",`${g} inviteID:${I} hasInviteID:${D} inviter:${E} groupID:${m}`),D&&(Fo.removeSignaling(I),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=`${Ir}._onInvitationTimeout`,{inviteID:I,inviteeList:E}=s,m=Fo.hasSignaling(I);this._core.ssoLog.debug("_onInvitationTimeout",`${g} inviteID:${I} hasInviteID:${m} data:${s.data}`),m&&(Fo.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 I=`${Ir}._onInvitationModified`,{inviteID:E,data:m}=s,D=Fo.hasSignaling(E);this._core.ssoLog.debug("_onInvitationModified",`${I} inviteID:${E} data:${m}`),D&&(Fo.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:I,data:E}=s;return{inviteID:n,inviter:g,groupID:I,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)}},Xr=new class{constructor(){this._offlineSignalingMap=new Map}init(s){this._core=s;const{notificationCenter:n,helper:g,constants:{InnerEvent:I,WORKFLOW_STEP:E,WORKFLOW_NAME:m}}=s;n.subscribeInnerEvent(I.DESTROY,this._dispose,this),n.subscribeInnerEvent(I.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&&Fo.getSignalingListenStatus()))return;const g=ur([...n.values()]);if(g.length!==0&&(g.forEach(I=>{this._handleC2CActionType(I)}),this._offlineSignalingMap.size>0)){const I=this._sortOfflineSignalingByTime();_l.handleActionSignaling(I)}}_handleC2CActionType(s){const n=wc(s);if(!n)return;const{actionType:g}=n;g===Tu?this._saveValidOfflineInvite(n,s):this._removeOfflineInvite(n)}_saveValidOfflineInvite(s,n){const{inviteID:g,inviteeList:I=[],timeout:E=0}=s,m=this._core.common.getCurrentUserID();if(!I.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 nh={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 qI=new class{constructor(){this.name="Signaling"}install(s){za.init(s),_l.init(s),$g.init(s),Fo.init(s),Xr.init(s),s.helper.registerValidateConfig({auth:js,params:nh})}};const Us=new class{init(s){this.core=s}};function _c(s){let n;const{message:g}=Us.core,{conversationID:I,messageID:E}=s;return n=g.messageDataHandler.getLocalMessageList(I).find(m=>m.ID===E),!n&&(n=g.messageDataHandler.getSparseMessageList(I).find(m=>m.ID===E)),n}function Ac(s){return s.map(n=>{const{from:g,to:I,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:I,SenderId:g,To_Account:I}})}function Er(s){var n;const{From_Account:g,From_AccountHeadurl:I,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:I,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 Pr,Za;(function(s){s.MSG_TEXT="TIMTextElem",s.MSG_CUSTOM="TIMCustomElem",s.MSG_LOCATION="TIMLocationElem",s.MSG_FACE="TIMFaceElem",s.MSG_STREAM="TIMStreamElem"})(Pr||(Pr={})),function(s){s[s.FORWARD=0]="FORWARD",s[s.BACKWARD=1]="BACKWARD"}(Za||(Za={}));const SE="MSG_REACTION",lC="MSG_EXT",rh=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"},Tl="16k_zh",IC="16k_en",uC="16k_yue",Nl="16k_ja",KI="16k_zh-PY",EI={[Tc.ZH_CN]:Tl,[Tc.EN_US]:IC,[Tc.YUE_HK]:uC,[Tc.JA_JP]:Nl,[Tc.ZH_PY]:KI},dI=/\.(wav|pcm|ogg-opus|speex|silk|mp3|m4a|aac|amr)/,ME={READ:0,UNREAD:1},Gl=1,bl=2,Ug=3;var ec;(function(s){s.IN="in",s.OUT="out"})(ec||(ec={}));const dd=16,vE=17;var Nc;(function(s){s[s.DATA=0]="DATA",s[s.REVOKED=1]="REVOKED"})(Nc||(Nc={}));var jI;(function(s){s[s.NORMAL=0]="NORMAL",s[s.TIMEOUT=1]="TIMEOUT"})(jI||(jI={}));const co="StreamMsg.PushStreamHttp";var RE=new class{constructor(){this._reactionsMap=new Map}init(s){this._core=s;const{helper:n,notificationCenter:g,InnerEvent:{MESSAGE_PUSH:I},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(I,E,this._handleReactionUpdated,this),g.subscribeInnerEvent(I,m,this._handleReactionSync,this)}addMessageReaction(s,n){return mA(this,void 0,void 0,function*(){const{OuterConstant:g,ssoLog:I,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 mA(this,void 0,void 0,function*(){var SA;const{from:OA,to:JA,clientSequence:re,random:ne,time:_i,reactionID:Ti}=xA,kt={From_Account:OA,To_Account:JA,MsgKey:`${re}_${ne}_${_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:kt})})}({from:T,to:P,clientSequence:W,random:iA,time:EA,reactionID:n},this._core):M===g.CONV_GROUP&&(yield function(xA,LA){return mA(this,void 0,void 0,function*(){var SA;const{to:OA,reactionID:JA,sequence:re}=xA,ne={GroupId:OA,MsgSeq:re,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:ne})})}({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 mA(this,void 0,void 0,function*(){const{OuterConstant:g,helper:I}=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 mA(this,void 0,void 0,function*(){var LA;const{from:SA,to:OA,clientSequence:JA,random:re,time:ne,reactionID:_i}=kA,Ti={From_Account:SA,To_Account:OA,MsgKey:`${JA}_${re}_${ne}`,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 mA(this,void 0,void 0,function*(){var LA;const{to:SA,reactionID:OA,sequence:JA}=kA,re={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:re},xA)})}({to:T,reactionID:n,sequence:EA},this._core)),{code:0,successLog:{message:RA}}}catch(kA){const{errorCode:xA}=kA||{};throw new I.ChatError({functionName:"removeMessageReaction",code:xA,moreMessage:RA})}})}getAllUserListOfMessageReaction(s){return mA(this,void 0,void 0,function*(){this._validateMessageReactionBusinessCapability();const{message:n,reactionID:g,nextSeq:I=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 mA(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,re={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:re})})}({message:n,reactionID:g,nextSeq:I,count:E}):yield function(W){return mA(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:I,count:E}),P){const{Reaction_Account:W,NextSeq:iA}=P,EA=yield this._getUserProfileList(W);return{code:0,data:{nextSeq:iA,isCompleted:I===0,userList:EA}}}}catch(P){const{errorCode:W}=P||{};throw new M.ChatError({functionName:"getAllUserListOfMessageReaction",code:W})}})}getMessageReactions(s){return mA(this,void 0,void 0,function*(){const{constants:n}=this._core;this._validateMessageReactionBusinessCapability();const{messageList:g,maxUserCountPerReaction:I=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 mA(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:I}):P===n.OuterConstant.CONV_GROUP&&(m=yield function(kA){return mA(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:I}));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:re,Reaction_Account:ne,ReactedByMe:_i}=OA;return{reactionID:JA,totalUserCount:re,partialUserList:this._generatePartialUserInfo({userIDList:ne,userProfileMap:RA}),reactedByMyself:_i===1}})}})}}})}dispose(){this._reactionsMap.clear()}_extractUserIDsFromReactionResults(s){const n=[];return s?.forEach(g=>{const{ReactionList:I=[]}=g;I.forEach(E=>{E.Reaction_Account&&n.push(...E.Reaction_Account)})}),n}_getUserProfileList(s){return mA(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 mA(this,void 0,void 0,function*(){const n=new Map;return(yield this._getUserProfileList(s)).forEach(g=>{const{nick:I,avatar:E,userID:m}=g;n.set(m,{nick:I,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:I}=s,E=`${n}-${g}`,m=this._reactionsMap.get(E)||{};this._reactionsMap.set(E,Object.assign(Object.assign({},m),I))}_validateMessageReactionBusinessCapability(){const{helper:s,constants:n}=this._core;if(!s.checkBusinessCapabilityBits(SE))throw new s.ChatError({functionName:"addMessageReaction",code:n.ERROR_CODE.NO_USE,replacement1:"addMessageReaction"})}_handleReactionUpdated(s){const{MsgReactionNotifyList:n}=s,{notificationCenter:g,constants:I}=this._core;n.forEach(E=>mA(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}),re=OA?xA.Count:0,ne=((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:re,partialUserList:JA}}),{reactionID:SA,totalUserCount:re,partialUserList:JA,reactedByMyself:ne}});g.emitOuterEvent(I.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:I.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:iA,reactionList:kA}})}))}_handleReactionSync(s){var n;const{notificationCenter:g,constants:I}=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(I.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:I.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:iA,reactionList:[RA]}})}}_generatePartialUserInfo({userIDList:s,userProfileMap:n}){const g=[];return s?.forEach(I=>{n.has(I)&&g.push(n.get(I))}),g}_generateMessageID(s){const{messageSequence:n,messageKey:g,messageIDMap:I}=s;return g?I.get(g):I.get(n)}_generateMessageKeyList(s,n){const{constants:g}=this._core,I=s[0],{conversationType:E}=I;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}},Xa=new class{init(s){this._core=s;const{helper:n,InnerEvent:{MESSAGE_PUSH:g},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:I,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,I,this._handleC2CMessageReadReceipt,this),m.subscribeInnerEvent(g,E,this._handleGroupMessageReadReceipt,this)}sendMessageReadReceipt(s){return mA(this,void 0,void 0,function*(){var n;const{common:g,constants:I}=this._core,E=this._filterValidMessageSendByOther(s);if(E.length===0)throw new g.ChatError({code:I.ERROR_CODE.READ_RECEIPT_MSG_LIST_EMPTY});try{const{conversationType:m}=E[0];return m===I.OuterConstant.CONV_C2C?yield function(D){return mA(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 mA(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 mA(this,void 0,void 0,function*(){const{common:n,constants:g}=this._core;try{const{conversationType:I}=s[0];if(I===g.OuterConstant.CONV_GROUP){const E=this._filterValidMessageSendByMe(s);if(E?.length>0){const m=yield function(M){return mA(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(I){const{errorCode:E,errorInfo:m}=I;throw new n.ChatError({code:E,message:m})}})}getGroupMessageReadMemberList(s){return mA(this,void 0,void 0,function*(){const{constants:n,common:g}=this._core,{message:I,filter:E=ME.READ,cursor:m=""}=s,{conversationID:D,sequence:M,ID:T}=I,P=D.replace(n.OuterConstant.CONV_GROUP,""),W=s.count>=100?100:s.count;try{const iA=yield function(EA){return mA(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===ME.READ?LA.readUserIDList=xA.map(SA=>SA.Read_Account):E===ME.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:I}=this._core,{C2cMsgInfo:E,PeerReadTime:m,Peer_Account:D}=s;if(I.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,I=new Map;n.forEach(E=>{I.set(E.sequence,E)}),g?.forEach(E=>{if(E.Code===0){const{MsgSeq:m,ReadNum:D,UnreadNum:M}=E,T=I.get(m);T&&(T.readReceiptInfo.readCount=D,T.readReceiptInfo.unreadCount=M)}})}_handleGroupMessageReadReceipt(s){const n=[],{constants:g}=this._core,{GroupTips:I}=s;I.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:I,status:E}=g;return I===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:I}=this._core;I.unSubscribeInnerEvent(s,n,this._handleC2CMessageReadReceipt,this),I.unSubscribeInnerEvent(s,g,this._handleGroupMessageReadReceipt,this)}};function WI(s,n,g){return mA(this,void 0,void 0,function*(){const{common:{buildAndSendPacket:I}}=Us.core,{from:E,to:m,clientSequence:D,random:M,time:T}=s;return I({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 Gu(s,n,g){return mA(this,void 0,void 0,function*(){const{common:{buildAndSendPacket:I}}=Us.core,{to:E,sequence:m}=s;return I({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:I,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(I,m,this._handleMessageExtensionsNotify,this),n.subscribeInnerEvent(E,this.reset,this)}setMessageExtensions(s,n){return mA(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("setMessageExtensions");const{constants:{OuterConstant:g},ssoLog:I}=this._core,{ID:E,conversationID:m,sequence:D,time:M,conversationType:T}=s;let P=n;n.length>20&&(P=n.slice(0,20),I.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 WI(s,W,Gl):T===g.CONV_GROUP&&(EA=yield Gu(s,W,Gl)),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 mA(this,void 0,void 0,function*(){const{utils:{isUndefined:n}}=this._core;this._validateMessageExtensionBusinessCapability("getMessageExtensions");const{conversationID:g,ID:I,sequence:E,time:m}=s,D=`convID:${g} messageID:${I} sequence:${E} time:${m}`;try{let M;this._completedFetchExtensions.has(I)&&(M=this._extensionsLatestSequenceMap.get(I));const T=yield this._fetchMessageExtensions(s,M);return n(M)&&T.length>1&&this._completedFetchExtensions.add(I),{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 mA(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("deleteMessageExtensions");const{utils:{isEmpty:g},constants:{OuterConstant:I}}=this._core,{conversationType:E,conversationID:m,sequence:D,ID:M,time:T}=s;let P=Ug;const W=[];g(n)||(P=bl,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===I.CONV_C2C?RA=yield WI(s,EA,P):E===I.CONV_GROUP&&(RA=yield Gu(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:I}}=this._core;s.unSubscribeInnerEvent(n,I,this._handleMessageExtensionsNotify,this),s.subscribeInnerEvent(g,this.reset,this)}_handleModifyMessageExtensions(s,n){const{ID:g}=s,{Seq:I}=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,I),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(I=>{const{key:E,seq:m,value:D=""}=I;g?.set(E,{value:D,seq:m})})}_fetchMessageExtensions(s,n){return mA(this,void 0,void 0,function*(){const{constants:{OuterConstant:g},utils:{isEmpty:I}}=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;I(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((I,E)=>{I.seq<=n&&g.delete(E)})}}_generateServerExtensions(s,n){const{ID:g}=s;if(this._messageExtensionsMap.has(g)){const I=this._messageExtensionsMap.get(g);return n.map(E=>{var m;const{key:D,value:M}=E;let T=0;return I?.has(D)&&(T=(m=I.get(D))===null||m===void 0?void 0:m.seq),{Key:D,Value:M,Seq:T}})}return n.map(I=>({Key:I.key,Value:I.value,Seq:0}))}_validateMessageExtensionBusinessCapability(s){const{helper:n,constants:g}=this._core;if(!n.checkBusinessCapabilityBits(lC))throw new n.ChatError({functionName:s,code:g.ERROR_CODE.NO_USE,replacement1:s})}_handleMessageExtensionsNotify(s){const{SetKVInfo:n,DeleteKVInfo:g,ClearKVInfo:I,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===Gl?this._handleMessageExtensionsUpdated({messageID:EA,updateMessageExtensionsInfo:n}):E===bl?this._handleMessageExtensionsDeleted({messageID:EA,deleteMessageExtensionsInfo:g}):E===Ug&&this._handleMessageExtensionsCleared({messageID:EA,clearMessageExtensionsInfo:I})}_handleMessageExtensionsUpdated(s){const{notificationCenter:n,OuterEvent:g}=this._core,{messageID:I,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(I,T)}),n.emitOuterEvent(g.MESSAGE_EXTENSIONS_UPDATED,{name:g.MESSAGE_EXTENSIONS_UPDATED,data:{messageID:I,extensions:m}})}_handleMessageExtensionsDeleted(s){const{notificationCenter:n,OuterEvent:g}=this._core,{messageID:I,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(I,T)}),n.emitOuterEvent(g.MESSAGE_EXTENSIONS_DELETED,{name:g.MESSAGE_EXTENSIONS_DELETED,data:{messageID:I,keyList:m}})}_handleMessageExtensionsCleared(s){const{notificationCenter:n,OuterEvent:{MESSAGE_EXTENSIONS_DELETED:g},utils:{isEmpty:I}}=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&&!I(P.value)&&D.push(W)}),this._clearLocationExtensions(E,T)}),n.emitOuterEvent(g,{name:g,data:{messageID:E,keyList:D}})}};const CI={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:[CI,{key:"extensions",required:!0,rules:["array"],allowEmpty:!1}],getMessageExtensions:[CI],deleteMessageExtensions:[CI]},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 I;return typeof g?.text!="string"||typeof g.text=="string"&&((I=g?.text)===null||I===void 0?void 0:I.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}]}),Pa=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 wE{constructor(n){this._core=n}deleteMessage(n){return mA(this,void 0,void 0,function*(){const{to:g,messageIdentifiers:I}=n,E={From_Account:this._core.common.getCurrentUserID(),To_Account:g,MsgKeyList:I};return this._core.common.buildAndSendPacket({servcmd:"openim.delete_c2c_msg_ramble",data:E})})}revokeMessage(n){return mA(this,void 0,void 0,function*(){const{to:g,from:I,sequence:E,time:m,random:D}=n,M={MsgInfo:{From_Account:I,To_Account:g,MsgSeq:E,MsgRandom:D,MsgTimeStamp:m}};return this._core.common.buildAndSendPacket({servcmd:"openim.msgwithdraw",data:M})})}}class na{constructor(n){this._core=n}deleteMessage(n){return mA(this,void 0,void 0,function*(){const{to:g,messageIdentifiers:I}=n,E={GroupId:g,Deleter_Account:this._core.common.getCurrentUserID(),Seqs:I};return this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_ramble_msg_by_seq",data:E})})}revokeMessage(n){return mA(this,void 0,void 0,function*(){const{to:g,sequence:I}=n,E={GroupId:g,MsgSeqList:[{MsgSeq:I}]};return this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_recall",data:E})})}}const Mn=2116;class Nr{constructor(n){this._core=n}generateRevokeMessage(n){const{conversationID:g,sequence:I,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:I,random:E,revoker:T}),P||(P={conversationID:g,sequence:I},m&&D&&E&&(P.ID=`${m}-${D}-${E}`)),P.revoker=T,P.revokeReason=M,P.revokerInfo={userID:T,nick:"",avatar:""},P}updateRevokerInfo(n){return mA(this,void 0,void 0,function*(){const g=n.map(I=>I.revoker);try{const I=yield this._fetchUserInfos(g);I&&n.forEach(E=>{const{revoker:m}=E;I[m]&&(E.revokerInfo.nick=I[m].nick||"",E.revokerInfo.avatar=I[m].avatar||"",E.revokerInfo.userID=m)})}catch(I){console.debug(I)}})}_fetchUserInfos(n){return mA(this,void 0,void 0,function*(){var g,I;const E=yield(g=this._core.user.userProfile)===null||g===void 0?void 0:g.getUserProfile({userIDList:n});return E?.data?(I=E.data)===null||I===void 0?void 0:I.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 na(s),this._c2cMessageAction=new wE(s),this._messageHelper=new Nr(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 mA(this,void 0,void 0,function*(){let n=[],g=[];const{conversationID:I,conversationType:E}=s[0],m=I.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===I&&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 mA(this,void 0,void 0,function*(){var n;const{conversationType:g,isRevoked:I,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(I)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 mA(this,void 0,void 0,function*(){var g,I;return s.isResend=!0,s.status="unSend",(I=(g=this._core)===null||g===void 0?void 0:g.apiMap)===null||I===void 0?void 0:I.sendMessage(s,n)})}findMessage(s){return this._core.message.messageDataHandler.findMessage(s)}createQuoteMessage(s,n){const{ID:g,time:I,sequence:E}=n;return s.quoteInfo={msgID:g,messageTime:I,messageSequence:E},s}_handleDeleteMessageSuccess(s){if(s.length===0)return;const{message:{messageDataHandler:n},common:{isTopic:g},notificationCenter:I,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)?I.emitInnerEvent(E.TOPIC_MESSAGE_DELETED,m):I.emitInnerEvent(E.MESSAGE_DELETED,m)}_handleRevokeMessageSuccess(s){return mA(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:I,sequence:E,random:m}=s;this._core.message.messageDataHandler.revokeMessage({conversationID:I,sequence:E,random:m,revoker:g}),yield this._messageHelper.updateRevokerInfo([s])})}};class kl{static parseServerPushElement(n){const{MsgContent:g={}}=n,{Index:I,Data:E}=g;return new kl({index:I,data:E})}constructor(n){this.type=Pr.MSG_FACE;const{index:g,data:I}=n;this.content={index:g,data:I}}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||{},I=g?this.payload:this.content,{index:E,data:m}=I;return{MsgType:this.type,MsgContent:{Index:E,Data:m}}}}class bc{static parseServerPushElement(n){const{MsgContent:g={}}=n,{Desc:I,Longitude:E,Latitude:m}=g;return new bc({description:I,longitude:E,latitude:m})}constructor(n){this.type=Pr.MSG_LOCATION;const{description:g,longitude:I,latitude:E}=n;this.content={description:g,longitude:I,latitude:E}}validateBeforeSend(){return{isValid:!0}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},I=g?this.payload:this.content,{description:E,longitude:m,latitude:D}=I;return{MsgType:this.type,MsgContent:{Desc:E,Longitude:m,Latitude:D}}}}class _E{static parseServerPushElement(n){const{MsgContent:g={}}=n,{StreamMsgID:I,CompatibleText:E,Markdown:m,BinaryData:D,ErrorCode:M,ErrorMsg:T}=g;return new _E({streamMessageID:I,compatibleText:E,markdown:m,binaryData:D,errorCode:M,errorMessage:T})}constructor(n){this.type=Pr.MSG_STREAM,this.content={streamMessageID:"",compatibleText:"",errorCode:0,errorMessage:"",isStreamEnded:!1},this._chunks=[],this._latestIndex=0;const{streamMessageID:g,compatibleText:I,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=I,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),I=this._getMaxRevokedChunkIndex(g);I>=0&&(this._chunks=[],this._latestIndex=I,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||{},I=g?this.payload:this.content,{streamMessageID:E,chunks:m}=I,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 I=[];let E=g;for(const m of n){if(m.index>E)break;m.index===E&&(I.push(m),E++)}return I}_mergeAndSortChunks(n){const g=new Map;this._chunks.forEach(I=>{g.set(I.index,I)}),n.forEach(I=>{g.set(I.index,I)}),this._chunks=Array.from(g.values()).sort((I,E)=>I.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),I=new Uint8Array(g);let E=0;for(const m of n)I.set(m,E),E+=m.length;this.content.binaryData=I}}_getMaxRevokedChunkIndex(n){let g=-1;for(let I=0;Ig&&(g=E.index)}return g}_getValidChunks(n){const g=n.filter(I=>I.eventType===Nc.DATA&&I.index>this._latestIndex);return this._filterContinuousChunks(g,this._latestIndex+1)}}var kc=new class{init(s){this._core=s,s.message.messageFactory.registerElementClass(Pr.MSG_FACE,kl),s.message.messageFactory.registerElementClass(Pr.MSG_LOCATION,bc),s.message.messageFactory.registerElementClass(Pr.MSG_STREAM,_E),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||{},I=new kl({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(I),m}createTextAtMessage(s){const{atUserList:n}=s?.payload||{},g=this._core.apiMap.createTextMessage(s),{OuterConstant:I}=this._core;if(!g)return null;if(Array.isArray(n)){const E=[],m=[];n.forEach(D=>{D!==I.MSG_AT_ALL?(E.push({GroupAtAllFlag:rh,GroupAt_Account:D}),m.push(D)):(E.push({GroupAtAllFlag:ro}),m.push(I.MSG_AT_ALL))}),g._groupAtInfoList=E,g.atUserList=m}return g}createForwardMessage(s){const{helper:n,OuterConstant:g}=this._core,{to:I,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:I,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:I}=s?.payload||{},E=new bc({description:n,longitude:g,latitude:I}),m=this._core.common.getCurrentUserID(),D=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:m}));return D.setElement(E),D}};let bu=class{init(s){this._messageHelper=new Nr(s),this._core=s;const{notificationCenter:n,InnerEvent:{MESSAGE_PUSH:g},InnerEventSubType:{C2C_REVOKED_MESSAGE:I},helper:{registerWorkflowStep:E},constants:{WORKFLOW_NAME:m,WORKFLOW_STEP:D}}=s;n.subscribeInnerEvent(g,I,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 mA(this,void 0,void 0,function*(){try{const{WithdrawC2cMsgNotify:{C2cWithdrawInfoArray:n}}=s;yield this._parseAndEmitC2CRevokedMessages(n)}catch(n){console.debug(n)}})}_parseAndEmitC2CRevokedMessages(s){return mA(this,void 0,void 0,function*(){const n=[],{notificationCenter:g,OuterEvent:I,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(I.MESSAGE_REVOKED,{name:I.MESSAGE_REVOKED,data:n}))})}_handleC2CRevokeMessagesFromUnreadMessageSync(s){return mA(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)}},EC=class{init(s){this._messageHelper=new Nr(s),this._core=s;const{notificationCenter:n,InnerEvent:{MESSAGE_PUSH:g},InnerEventSubType:{GROUP_MESSAGE_REVOKED:I}}=s;n.subscribeInnerEvent(g,I,this._handleGroupNotifyMessage,this)}_handleGroupNotifyMessage(s){const{GroupTips:n}=s;n?.forEach(g=>{var I;Array.isArray((I=g?.MsgBody)===null||I===void 0?void 0:I.GroupWithdrawInfoArray)&&this._handleGroupRevokeMessage(g)})}_handleGroupRevokeMessage(s){return mA(this,void 0,void 0,function*(){try{const{RevokerInfo:n,MsgBody:{GroupWithdrawInfoArray:g},GroupInfo:I}=s,E=[],m=[],{notificationCenter:D,OuterEvent:M,utils:{isEmpty:T},common:{isCommunity:P}}=this._core;let W=!1;I&&(W=P({groupID:I.GroupId})||!T(I.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,re=SA?`GROUP${SA}`:`GROUP${kA}`,ne=this._messageHelper.generateRevokeMessage({conversationID:re,sequence:RA,random:EA,tinyID:LA,clientTime:xA,revoker:OA,revokeReason:JA});W?(ne.revokerInfo.nick=I.From_AccountNick,ne.revokerInfo.avatar=I.From_AccountHeadurl,E.push(ne)):m.push(ne)}),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 zI=new class{constructor(){this._c2cMessageReceiver=new bu,this._groupMessageReceiver=new EC}init(s){this._c2cMessageReceiver.init(s),this._groupMessageReceiver.init(s)}dispose(){this._c2cMessageReceiver.dispose(),this._groupMessageReceiver.dispose()}},ah=new class{constructor(){this._core=null}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"translateText",context:this})}translateText(s){return mA(this,void 0,void 0,function*(){try{const{sourceLanguage:n,sourceTextList:g,targetLanguage:I}=s,E=yield function(m,D){return mA(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:I},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:I}=n||{};throw new this._core.helper.ChatError({functionName:"translateText",code:g,message:I})}})}},ku=new class{init(s){this._core=s,s.helper.registerApi({apiName:"convertVoiceToText",context:this})}convertVoiceToText(s){return mA(this,void 0,void 0,function*(){var n;const{message:g,language:I=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=dI.exec(E))===null||n===void 0?void 0:n[1])||"mp3",M=EI[I]||KI;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(!dI.test(s))throw new this._core.common.ChatError({code:2119})}};class hI{constructor(n){const{constants:g,common:I,utils:E}=Us.core,{CONV_C2C:m,CONV_GROUP:D}=g.OuterConstant,{ID:M,tinyID:T,from:P,to:W,clientTime:iA=I.timeManager.getServerTimeSeconds()||0,random:EA,sequence:RA,cloudCustomData:kA="",nick:xA="",avatar:LA="",clientSequence:SA,conversationType:OA,groupID:JA,_elements:re,time:ne}=n;this.ID=M||`${T}-${iA}-${EA}`,this.messageRandom=EA,this.from=P,this.messageSender=P,this.time=ne,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(re);_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:I=[],CompatibleText:E,AbstractList:m,Title:D,PbMsgKey:M,JsonMsgKey:T}=g||{},P=I.map(W=>Er(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:I,abstractList:E,compatibleText:m,pbDownloadKey:D="",downloadKey:M="",version:T=0,layersOverLimit:P=!1}=n,W=[];g.forEach(iA=>{if(iA){const EA=new hI(iA);W.push(EA)}}),this.content={messageList:W,title:I,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||{},I=g?this.payload:this.content,{abstractList:E,compatibleText:m,downloadKey:D,layersOverLimit:M,pbDownloadKey:T,title:P,version:W,messageList:iA}=I;return{MsgType:this.type,MsgContent:{AbstractList:E,CompatibleText:m,JsonMsgKey:D,LayersOverLimit:M,PbMsgKey:T,Title:P,Version:W,MsgList:Ac(iA)}}}}var dC=new class{init(s){this._core=s;const{message:n,helper:g,constants:{OuterConstant:I}}=s;n.messageFactory.registerElementClass(I.MSG_MERGER,rl),g.registerApi({apiName:"createMergerMessage",context:this}),g.registerApi({apiName:"sendMessage",context:this,matcher:E=>E[0].type===I.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),I=n.getCurrentUserID(),E=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:I}));return E.setRelayFlag(!0),E.setElement(g),E}sendMessage(s,n){return mA(this,void 0,void 0,function*(){var g,I,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 mA(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=(I=(g=this._core)===null||g===void 0?void 0:g.message)===null||I===void 0?void 0:I.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 mA(this,void 0,void 0,function*(){const{ssoLog:n}=this._core,g=s.payload,{downloadKey:I,pbDownload:E,type:m,messageList:D}=g,M=yo(g,["downloadKey","pbDownload","type","messageList"]);try{const T=yield function(iA){return mA(this,void 0,void 0,function*(){return Us.core.common.buildAndSendPacket({servcmd:"im_long_msg.get_relay_json_msg",data:{JsonMsgKey:iA}})})}(I),{MsgList:P}=T||{},W=P?.map(iA=>{const EA=Er(iA);return new hI(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:${I}`),s}catch(T){const{errorCode:P}=T;throw new this._core.helper.ChatError({functionName:"downloadMergerMessage",code:P,moreMessage:I})}})}},ra=new class{init(s){this._core=s,this._core.helper.registerExperimentalAPI("sendComboMessage",this)}sendComboMessage(s){return mA(this,void 0,void 0,function*(){const{appStore:n,message:g,common:{getCurrentUserID:I},utils:{isArray:E}}=this._core,{GroupId:m,To_Account:D}=s;s.From_Account=s.From_Account||I();let M=null;if(m){M=this._generateGroupMessage(Object.assign(Object.assign({},s),{ToGroupId:m}));const T=n.userStore.getUserProfile(I());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,I=g,E=n.messageHelper.parseServerPushMessage(s),m=n.messageFactory.createMessage(Object.assign(Object.assign({},E),{conversationType:I,flow:ec.OUT})),{elements:D}=E;return m.setElement(D),m}_generateGroupMessage(s){const{message:n,OuterConstant:{CONV_GROUP:g}}=this._core,I=g,E=n.messageHelper.parseServerGroupMessage(s),m=n.messageFactory.createMessage(Object.assign(Object.assign({},E),{conversationType:I,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:I},InnerEventSubType:{GROUP_MESSAGE_PINNED:E}}=s;g.subscribeInnerEvent(I,E,this._handleGroupMessagePinned,this),n.registerApi({apiName:"pinGroupMessage",context:this}),n.registerApi({apiName:"getPinnedGroupMessageList",context:this})}pinGroupMessage(s){return mA(this,void 0,void 0,function*(){const{ssoLog:n,common:{isTopic:g},OuterConstant:{GROUP_ID_PREFIX:I},helper:{ChatError:E}}=this._core;let{groupID:m,message:D,isPinned:M}=s;const{sequence:T}=D;try{return yield function(P){return mA(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 mA(this,void 0,void 0,function*(){let n=[];try{const g=yield function(I){return mA(this,void 0,void 0,function*(){const{groupID:E}=I,{common:{buildAndSendPacket:m}}=Us.core;return m({servcmd:"group_open_http_svc.get_pinned_messages",data:{GroupId:E}})})}({groupID:s});if(g){const{PinnedMsgList:I=[]}=g;n=yield this._updatePinnedMessageInfo({serverPinnedMessageList:I,groupID:s})}return{code:0,data:{messageList:n}}}catch(g){throw g}})}_handleGroupMessagePinned(s){const{message:{messageHelper:n,messageFactory:g},notificationCenter:I,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===dd){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===vE){const{ClientTime:SA,Random:OA,SenderTinyId:JA,ServerTime:re,MsgSeq:ne}=iA;xA={ID:`${JA}-${SA}-${OA}`,sequence:ne,random:OA,time:re,clientTime:SA}}xA&&I.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(I=>I.sequence===n)}_updatePinnedMessageInfo(s){return mA(this,arguments,void 0,function*({serverPinnedMessageList:n,groupID:g}){const{OuterConstant:{CONV_GROUP:I},utils:{isEmpty:E}}=this._core,m=[],D=[],M=[],T=new Map,P=`${I}${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 mA(this,void 0,void 0,function*(){var n,g;const{message:{messageHistory:I},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 mA(this,void 0,void 0,function*(){const{utils:{isEmpty:n},message:{messageHistory:g}}=this._core,{conversationID:I,messageSequenceList:E}=s;return n(E)?[]:g.getGroupRoamingMessagesByAnchor({conversationID:I,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:I,Markdown:E,IsLast:m,BinaryData:D}=n;this.eventType=g,this.index=I,this.markdown=E,this.isLast=m,this.binaryData=D}}var BI=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:I},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(I,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:I}=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){I.error("processHistoryMessage.error",g(E))}}_handleMessageReceived(s){const n=s.data;n?.forEach(g=>{var I,E;if(this._isValidStreamMessage(g)){const{streamMessageID:m}=((E=(I=g?._elements)===null||I===void 0?void 0:I[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:I}}=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===Pr.MSG_STREAM&&!I(E)}_fetchStreamMessageChunks(s){return mA(this,void 0,void 0,function*(){var n,g;const{constants:{ERROR_CODE:I},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 mA(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===I.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:I}=this._core;g.content.isStreamEnded=!0,g.stopReason=n,this._messageMap.delete(s),I.debug("_onStreamEnded",`streamMessage end, StopReason: ${n}`)}_handleStreamMessageChunkPush(s){var n;const{ssoLog:g}=this._core,{StopReason:I,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){mA(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,I,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 I=!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 I=Math.max(0,g.length-300);I{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(I=>{if(I){const[E,m]=I.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 I;const{isEmpty:E,isPlainObject:m}=(I=this._core)===null||I===void 0?void 0:I.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 Uu=["unknown","image","video","audio","log"];var QI=new class{init(s){this._core=s}request(s,n){var g;const{MINI_APP_NAMESPACE:I,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=yo(SA,["name"]);SA=Object.assign(Object.assign({},JA),{fileName:"file",fileType:s.fileType?Uu[s.fileType]:"image"})}return iA=I.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:I}=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?I(null,{statusCode:m,headers:E,data:Object.assign(Object.assign({},g.data),{location:n})}):I({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 Gr(s){const n=s||99999999;return Math.round(Math.random()*n)}function br(s,n=!0,g=!0){const I=Date.now();return n?g?I-s+" ms":`${Math.round((I-s)/1e3)} s`:g?I-s:Math.round((I-s)/1e3)}function Ig(s){return`${Array.from({length:8},()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1)).join("")}-${s}`}function rr(s,n){return Math.round(Number(s)*10**n)/10**n}function vr(s){return s<=1048576?`${rr(s/1024,1)}KB/s`:`${rr(s/1048576,1)}MB/s`}const ic="TIMImageElem",Fg="TIMSoundElem",xa="TIMFileElem",Ll="TIMVideoFileElem",da="RichMediaMessagePlugin",pI=["rich.my-imcloud.com","imrich.qcloud.com"],ZI=1,Ca=2,gl=3,NE=255;var XI;(function(s){s.UNSENT="unSend",s.SUCCESS="success",s.FAIL="fail"})(XI||(XI={}));const GE={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\/)/},xr=Symbol("isCustomUpload");var $I,Ut=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[I,E]=n.split("?");if(!E)return I;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?`${I}?${D}`:I}(s,"authKey")}_isMiniProgramTempFile(s){return!!this.getPlatformFlags().IN_MINI_APP&&Object.values(GE).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 I=Object.getPrototypeOf(g);if(I===null)return!0;let E=I;for(;Object.getPrototypeOf(E)!==null;)E=Object.getPrototypeOf(E);return I===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 mA(this,void 0,void 0,function*(){var n;const{IN_MINI_APP:g,IN_BROWSER:I}=((n=this._core)===null||n===void 0?void 0:n.utils)||{};return this._shouldSkipProbing()?{width:0,height:0}:I?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=pI;const g=((s=this._core)===null||s===void 0?void 0:s.store.get("cloudConfig"))||{},{file_dn_list:I}=g;if(I===void 0)return n;try{JSON.parse(I).forEach(E=>{n.includes(E)||n.push(E)})}catch(E){console.warn(E),n=pI}return n}getPlatform(){var s;return(s=this._core)===null||s===void 0?void 0:s.utils.platform}generateUUID(s,n){var g;let I=`${this.getSDKAppID()}-${this.getCurrentUserID()}-${(g=this._core)===null||g===void 0?void 0:g.utils.randomString()}`;if(n)return`${I}.${n}`;const E=s.name||s.value||s.url||s.tempFilePath,m=E&&E.slice(E.lastIndexOf(".")+1);return m&&(I=`${I}.${m}`),I}processResourceUrl(s){if(!s)return"";let n=s;const g=this.getFileDownloadProxy(),I=this.getAuthKey(),E=this.getFileDNList();return g&&(s.startsWith("http://")?n=s.replace(/^http:\/\/[^/]+/,g):s.startsWith("https://")&&(n=s.replace(/^https:\/\/[^/]+/,g))),I&&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=${I}`:`${n}?authKey=${I}`),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:I,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:I,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(I=>{g.getImageInfo({src:s,success:E=>I({width:E.width,height:E.height}),fail:()=>I({width:0,height:0})})})}_shouldSkipProbing(){var s;const{IN_RN_APP:n,IS_IE:g,IE_VERSION:I,IN_WX_MINI_GAME:E}=((s=this._core)===null||s===void 0?void 0:s.utils)||{};return n||g&&I===9||E}_probeImageDimensionsWeb(s){return new Promise(n=>{const g=new Image,I=()=>{g.onload=null,g.onerror=null,g.src=""};g.onload=()=>{n({width:g.width,height:g.height}),I()},g.onerror=()=>{n({width:0,height:0}),I()},g.src=s})}},Fu={exports:{}},Ou=($I||($I=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 I(LA,SA){var OA=LA[0],JA=LA[1],re=LA[2],ne=LA[3];JA=((JA+=((re=((re+=((ne=((ne+=((OA=((OA+=(JA&re|~JA&ne)+SA[0]-680876936|0)<<7|OA>>>25)+JA|0)&JA|~OA&re)+SA[1]-389564586|0)<<12|ne>>>20)+OA|0)&OA|~ne&JA)+SA[2]+606105819|0)<<17|re>>>15)+ne|0)&ne|~re&OA)+SA[3]-1044525330|0)<<22|JA>>>10)+re|0,JA=((JA+=((re=((re+=((ne=((ne+=((OA=((OA+=(JA&re|~JA&ne)+SA[4]-176418897|0)<<7|OA>>>25)+JA|0)&JA|~OA&re)+SA[5]+1200080426|0)<<12|ne>>>20)+OA|0)&OA|~ne&JA)+SA[6]-1473231341|0)<<17|re>>>15)+ne|0)&ne|~re&OA)+SA[7]-45705983|0)<<22|JA>>>10)+re|0,JA=((JA+=((re=((re+=((ne=((ne+=((OA=((OA+=(JA&re|~JA&ne)+SA[8]+1770035416|0)<<7|OA>>>25)+JA|0)&JA|~OA&re)+SA[9]-1958414417|0)<<12|ne>>>20)+OA|0)&OA|~ne&JA)+SA[10]-42063|0)<<17|re>>>15)+ne|0)&ne|~re&OA)+SA[11]-1990404162|0)<<22|JA>>>10)+re|0,JA=((JA+=((re=((re+=((ne=((ne+=((OA=((OA+=(JA&re|~JA&ne)+SA[12]+1804603682|0)<<7|OA>>>25)+JA|0)&JA|~OA&re)+SA[13]-40341101|0)<<12|ne>>>20)+OA|0)&OA|~ne&JA)+SA[14]-1502002290|0)<<17|re>>>15)+ne|0)&ne|~re&OA)+SA[15]+1236535329|0)<<22|JA>>>10)+re|0,JA=((JA+=((re=((re+=((ne=((ne+=((OA=((OA+=(JA&ne|re&~ne)+SA[1]-165796510|0)<<5|OA>>>27)+JA|0)&re|JA&~re)+SA[6]-1069501632|0)<<9|ne>>>23)+OA|0)&JA|OA&~JA)+SA[11]+643717713|0)<<14|re>>>18)+ne|0)&OA|ne&~OA)+SA[0]-373897302|0)<<20|JA>>>12)+re|0,JA=((JA+=((re=((re+=((ne=((ne+=((OA=((OA+=(JA&ne|re&~ne)+SA[5]-701558691|0)<<5|OA>>>27)+JA|0)&re|JA&~re)+SA[10]+38016083|0)<<9|ne>>>23)+OA|0)&JA|OA&~JA)+SA[15]-660478335|0)<<14|re>>>18)+ne|0)&OA|ne&~OA)+SA[4]-405537848|0)<<20|JA>>>12)+re|0,JA=((JA+=((re=((re+=((ne=((ne+=((OA=((OA+=(JA&ne|re&~ne)+SA[9]+568446438|0)<<5|OA>>>27)+JA|0)&re|JA&~re)+SA[14]-1019803690|0)<<9|ne>>>23)+OA|0)&JA|OA&~JA)+SA[3]-187363961|0)<<14|re>>>18)+ne|0)&OA|ne&~OA)+SA[8]+1163531501|0)<<20|JA>>>12)+re|0,JA=((JA+=((re=((re+=((ne=((ne+=((OA=((OA+=(JA&ne|re&~ne)+SA[13]-1444681467|0)<<5|OA>>>27)+JA|0)&re|JA&~re)+SA[2]-51403784|0)<<9|ne>>>23)+OA|0)&JA|OA&~JA)+SA[7]+1735328473|0)<<14|re>>>18)+ne|0)&OA|ne&~OA)+SA[12]-1926607734|0)<<20|JA>>>12)+re|0,JA=((JA+=((re=((re+=((ne=((ne+=((OA=((OA+=(JA^re^ne)+SA[5]-378558|0)<<4|OA>>>28)+JA|0)^JA^re)+SA[8]-2022574463|0)<<11|ne>>>21)+OA|0)^OA^JA)+SA[11]+1839030562|0)<<16|re>>>16)+ne|0)^ne^OA)+SA[14]-35309556|0)<<23|JA>>>9)+re|0,JA=((JA+=((re=((re+=((ne=((ne+=((OA=((OA+=(JA^re^ne)+SA[1]-1530992060|0)<<4|OA>>>28)+JA|0)^JA^re)+SA[4]+1272893353|0)<<11|ne>>>21)+OA|0)^OA^JA)+SA[7]-155497632|0)<<16|re>>>16)+ne|0)^ne^OA)+SA[10]-1094730640|0)<<23|JA>>>9)+re|0,JA=((JA+=((re=((re+=((ne=((ne+=((OA=((OA+=(JA^re^ne)+SA[13]+681279174|0)<<4|OA>>>28)+JA|0)^JA^re)+SA[0]-358537222|0)<<11|ne>>>21)+OA|0)^OA^JA)+SA[3]-722521979|0)<<16|re>>>16)+ne|0)^ne^OA)+SA[6]+76029189|0)<<23|JA>>>9)+re|0,JA=((JA+=((re=((re+=((ne=((ne+=((OA=((OA+=(JA^re^ne)+SA[9]-640364487|0)<<4|OA>>>28)+JA|0)^JA^re)+SA[12]-421815835|0)<<11|ne>>>21)+OA|0)^OA^JA)+SA[15]+530742520|0)<<16|re>>>16)+ne|0)^ne^OA)+SA[2]-995338651|0)<<23|JA>>>9)+re|0,JA=((JA+=((ne=((ne+=(JA^((OA=((OA+=(re^(JA|~ne))+SA[0]-198630844|0)<<6|OA>>>26)+JA|0)|~re))+SA[7]+1126891415|0)<<10|ne>>>22)+OA|0)^((re=((re+=(OA^(ne|~JA))+SA[14]-1416354905|0)<<15|re>>>17)+ne|0)|~OA))+SA[5]-57434055|0)<<21|JA>>>11)+re|0,JA=((JA+=((ne=((ne+=(JA^((OA=((OA+=(re^(JA|~ne))+SA[12]+1700485571|0)<<6|OA>>>26)+JA|0)|~re))+SA[3]-1894986606|0)<<10|ne>>>22)+OA|0)^((re=((re+=(OA^(ne|~JA))+SA[10]-1051523|0)<<15|re>>>17)+ne|0)|~OA))+SA[1]-2054922799|0)<<21|JA>>>11)+re|0,JA=((JA+=((ne=((ne+=(JA^((OA=((OA+=(re^(JA|~ne))+SA[8]+1873313359|0)<<6|OA>>>26)+JA|0)|~re))+SA[15]-30611744|0)<<10|ne>>>22)+OA|0)^((re=((re+=(OA^(ne|~JA))+SA[6]-1560198380|0)<<15|re>>>17)+ne|0)|~OA))+SA[13]+1309151649|0)<<21|JA>>>11)+re|0,JA=((JA+=((ne=((ne+=(JA^((OA=((OA+=(re^(JA|~ne))+SA[4]-145523070|0)<<6|OA>>>26)+JA|0)|~re))+SA[11]-1120210379|0)<<10|ne>>>22)+OA|0)^((re=((re+=(OA^(ne|~JA))+SA[2]+718787259|0)<<15|re>>>17)+ne|0)|~OA))+SA[9]-343485551|0)<<21|JA>>>11)+re|0,LA[0]=OA+LA[0]|0,LA[1]=JA+LA[1]|0,LA[2]=re+LA[2]|0,LA[3]=ne+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,re,ne,_i,Ti=LA.length,kt=[1732584193,-271733879,-1732584194,271733878];for(SA=64;SA<=Ti;SA+=64)I(kt,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(I(kt,JA),SA=0;SA<16;SA+=1)JA[SA]=0;return re=(re=8*Ti).toString(16).match(/(.*?)(.{0,8})$/),ne=parseInt(re[2],16),_i=parseInt(re[1],16)||0,JA[14]=ne,JA[15]=_i,I(kt,JA),kt}function M(LA){var SA,OA,JA,re,ne,_i,Ti=LA.length,kt=[1732584193,-271733879,-1732584194,271733878];for(SA=64;SA<=Ti;SA+=64)I(kt,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(I(kt,JA),SA=0;SA<16;SA+=1)JA[SA]=0;return re=(re=8*Ti).toString(16).match(/(.*?)(.{0,8})$/),ne=parseInt(re[2],16),_i=parseInt(re[1],16)||0,JA[14]=ne,JA[15]=_i,I(kt,JA),kt}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,re,ne,_i,Ti=this.byteLength,kt=LA(SA,Ti),Ni=Ti;return OA!==n&&(Ni=LA(OA,Ti)),kt>Ni?new ArrayBuffer(0):(JA=Ni-kt,re=new ArrayBuffer(JA),ne=new Uint8Array(re),_i=new Uint8Array(this,kt,JA),ne.set(_i),re)}}(),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)I(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,re=JA.length,ne=[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(ne,re),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,re,ne=SA;if(LA[ne>>2]|=128<<(ne%4<<3),ne>55)for(I(this._hash,LA),ne=0;ne<16;ne+=1)LA[ne]=0;OA=(OA=8*this._length).toString(16).match(/(.*?)(.{0,8})$/),JA=parseInt(OA[2],16),re=parseInt(OA[1],16)||0,LA[14]=JA,LA[15]=re,I(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)I(this._hash,m(OA.subarray(SA-64,SA)));return this._buff=SA-64>2]|=JA[SA]<<(SA%4<<3);return this._finish(ne,re),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}()}(Fu)),Fu.exports),CC=oI(Ou),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?QI:Lu,(n=this.httpRequest)===null||n===void 0||n.init(s)}uploadToCOS(s){return mA(this,void 0,void 0,function*(){const n=`${da} uploadToCOS`,{ssoLog:g,utils:{safeStringify:I}}=this._core,{file:E}=s;this.uploadFileType=s.uploadFileType,g.debug("uploadToCOS",`${n} options:${I(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:${vr(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:${I(m)}`),m}})}_handleUploadError(s,n){var g,I;const{ChatError:E}=(g=this._core)===null||g===void 0?void 0:g.helper;if(s.statusCode===403)throw n.url,!((I=s?.data)===null||I===void 0)&&I.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:br(Date.now(),!1),uploadSpeed:vr(1e3*s.size/br(Date.now(),!1))}}_createCosOptions(s){return mA(this,void 0,void 0,function*(){const{fileName:n,resources:g,uploadMethod:I}=yield this._prepareUploadParams(s),E=this._isC2CConversation(s.message.conversationID)?1:2;try{const m=yield this._fetchCosSignatureUrl({fileType:this.uploadFileType,fileName:n,uploadMethod:I,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=!Ut.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 mA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g,isEmpty:I}}=this._core;n.debug("_prepareUploadParams",` prepareUploadParams:${g(s)}`);const{file:E}=s,{IN_MINI_APP:m,IN_RN_APP:D}=Ut.getPlatformFlags(),M=m||D,T=M&&s.message.type!==xa,{name:P}=E,W=P.slice(P.lastIndexOf(".")),iA=`${Gr(999999)}${W}`,EA=T?E.name:iA,RA=yield this._generateHashFileName(E);return{fileName:I(RA)?Ig(EA):`${RA}${W}`,resources:M?E.url:E,uploadMethod:M?1:0}})}_generateHashFileName(s){return mA(this,void 0,void 0,function*(){const{utils:{IN_MINI_APP:n,IN_BROWSER:g,IN_UNI_NATIVE_APP:I,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]),I||(M=yield this._generateFileNameInMiniProgram(s)),I&&(M=yield this._generateFileNameInUNINativeApp(s))),m.info("_generateHashFileName",`hashFileName:${M} costTime:${Date.now()-D}`),M})}_generateHashFileNameInWeb(s){return mA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g}}=this._core;let I="";try{I=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 CC.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 I})}_generateFileNameInMiniProgram(s){return mA(this,void 0,void 0,function*(){const{utils:{MINI_APP_NAMESPACE:n,safeStringify:g,isEmpty:I},ssoLog:E}=this._core;let m="";if(I(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 mA(this,void 0,void 0,function*(){var n;const{utils:{safeStringify:g,isEmpty:I},ssoLog:E}=this._core;let m="";if(I(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 mA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g}}=this._core,I=Ut.isSimpleCos(),E=this._prepareCosRequestData(s),m=I?"im_cos_msg.simple_sig":"im_cos_msg.pre_sig";try{const D=yield function(T,P,W){return mA(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:${I} 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=Ut.isSimpleCos(),I=g?(n=s?.rpt_pre_sig)===null||n===void 0?void 0:n[0]:s;if(!I)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}=I;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}=I;return{uploadUrl:E,downloadUrl:m,requestSnapshotUrl:D,thumbUrl:M,largeUrl:T,fileKey:P}}_prepareCosRequestData(s){return Ut.isSimpleCos()?{uint32_upload_method:s.uploadMethod,uint32_platform:Ut.getPlatform(),uint32_sdkappid:Ut.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 mA(this,void 0,void 0,function*(){return new Promise((n,g)=>{this.httpRequest.request(s,(I,E)=>{I&&this.uploadFileTryCount=3e4}_syncSystemClock(s){var n,g,I;const E=((n=s.headers)===null||n===void 0?void 0:n.date)||((g=s.headers)===null||g===void 0?void 0:g.Date)||((I=s.error)===null||I===void 0?void 0:I.ServerTime);if(E){const m=Date.now(),D=Date.parse(E);this.systemClockOffset=D-m}}_getRawOrUploadProxyUrl(s){const n=Ut.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,Ae=2;class Qe{constructor(n,g){this.instanceID=Gr(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=Ut.addAuthToUrl(n.imageUrl||n.url||""),this.url=Ut.addAuthToUrl(n.url||g)}setSizeType(n){this.sizeType=n}setType(n){this.type=n}setImageUrl(n){n&&(this.imageUrl=Ut.addAuthToUrl(n))}getImageUrl(){return this.imageUrl}}function p(s){const{originUrl:n,originWidth:g,originHeight:I,min:E=198}=s,m=parseInt(g)||0,D=parseInt(I)||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 yo(M,["url"])}return M}class h{constructor(n){this._imageMemoryURL="",this._percent=0,this.type=ic;const{uuid:g,file:I,imageFormat:E,imageInfoArray:m=[],isCustomUpload:D=!1}=n;this._imageMemoryURL=this.createImageDataAsURL(I),this.content={imageFormat:E,uuid:g,imageInfoArray:[]},this[xr]=D,this.initImageInfoArray(m),this.autoFixUrl()}static parseServerPushElement(n){const{MsgContent:g}=n,{ImageFormat:I,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 h({imageFormat:I,imageInfoArray:D,uuid:m})}createImageDataAsURL(n){let g="";const{IN_MINI_APP:I,IN_RN_APP:E,IN_BROWSER:m}=Ut.getPlatformFlags();return n&&((I||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 I=0;I<3;I++){const E=n[I]||Object.assign({},g),m=new Qe(E,this._imageMemoryURL);m.setSizeType(I+1),m.setType(I),this.addImageInfo(m)}this.updateAccessSideImageInfoArray()}autoFixUrl(){const n=["http","https"];this.content.imageInfoArray.forEach(g=>{if(!g.url||g.imageUrl==="")return;const[I,...E]=g.imageUrl.split("://"),m=E.join("://");n.includes(I)||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 I;for(let E=0;E({InstanceId:g.instanceID,Type:g.sizeType,MsgType:g.type,Size:g.size,Width:g.width,Height:g.height,URL:Ut.removeAuthToUrl(g.imageUrl)}))}}const v=new class{init(s){this.core=s}},N={[ZI]:"i",[gl]:"a",[Ca]:"v",[NE]:"f"};let O=null,z=null;function X(s){var n;const{store:g,utils:{isNumber:I,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(I(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:I,InnerEvent:E,message:m}=s;I.registerApi({apiName:"createImageMessage",context:this}),I.registerExperimentalAPI("createImageMessage",this,"createCustomUploadImageMessage"),(n=m?.messageFactory)===null||n===void 0||n.registerElementClass(ic,h),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createImageMessage(s){var n,g,I;try{const E=(n=this._core.store.get("login"))===null||n===void 0?void 0:n.userId,m=(I=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||I===void 0?void 0:I.createMessage(Object.assign(Object.assign({},s),{from:E})),D=this._processImage(s);s.payload.file=D;const M={imageFormat:uA.UNKNOWN,uuid:Ut.generateUUID(D),file:D,imageInfoArray:[]},T=new h(M);return m.setElement(T),this._messageOptionsMap.set(m.clientSequence,s),m}catch(E){throw E}}createCustomUploadImageMessage(s){var n,g,I,E;const{store:m,utils:{isEmpty:D}}=this._core,M=(n=m.get("login"))===null||n===void 0?void 0:n.userId,T=(I=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||I===void 0?void 0:I.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:re,thumbImageWidth:ne,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 kt=new h({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:re,width:ne,height:_i,imageUrl:Ti,url:Ti}],isCustomUpload:!0});return T.setElement(kt),this._messageOptionsMap.set(T.clientSequence,s),T._skipUpload=!0,T}upload(s){return mA(this,void 0,void 0,function*(){const n=s.getElements()[0],{file:g}=this._messageOptionsMap.get(s.clientSequence).payload;this._validateBeforeUploadImage(g);const I=yield this._performImageUpload(n,s,g),E=this._generateImageInfo(I);return n.updateImageFormat(I?.fileType),n.updateImageInfoArray(E),this._updateImageType(n.content.imageInfoArray),s})}_performImageUpload(s,n,g){return mA(this,void 0,void 0,function*(){const{to:I}=n,E={uploadFileType:ZI,file:g,to:I,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:I,height:E,smallImageUrl:m,smallImageWidth:D,smallImageHeight:M,largeImageUrl:T,largeImageWidth:P,largeImageHeight:W,imageInfoArray:iA}=s,EA=Ut.addAuthToUrl(n),RA={size:g,url:EA,width:I,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,I,E,720),this._generateThumbInfo(EA,I,E,198)]}_generateThumbInfo(s,n,g,I){return p({originUrl:s,originWidth:n,originHeight:g,min:I})}_processImageInfoArray(s,n){let g,I,E;for(const m of s)m.type===1?(I=m,I.size=n):m.type===2?(E=m,E.size=n):(g=m,g.size=n);return[Object.assign({},g),Object.assign({},E),Object.assign({},I)]}_parseResponse(s,n){return mA(this,void 0,void 0,function*(){try{const{thumbUrl:g,largeUrl:I,downloadUrl:E}=s;if(g&&I&&(yield this._getImageInfoByUrl(g,n,"thumb"),yield this._getImageInfoByUrl(I,n,"large")),Ut.isSimpleCos()&&!Ut.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 mA(this,void 0,void 0,function*(){var I;try{const E=Ut.addAuthToUrl(s),{width:m=0,height:D=0}=yield Ut.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){(I=this._core)===null||I===void 0||I.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:I}=s.payload;return I=g?this._processMiniAppImageFile(I):this._processWebImageFile(I),I}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,I=Ut.extractFileFromInput(s);if(!I)throw new g({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return I}_getDownloadIP(s,n){return mA(this,void 0,void 0,function*(){const g=`${da} getDownloadIP domainName: ${s}`;try{const I=yield function(m,D){return mA(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(!I||!I.str_final_ip)return;console.log(`${g} ok. downloadIP:${I}`);const E=n.location.split("/");E[0]=I.str_final_ip,n.location=E.join("/")}catch(I){console.warn(I)}})}_getImageInfoArray(s,n){return mA(this,void 0,void 0,function*(){try{const g=yield function(I,E){return mA(this,void 0,void 0,function*(){try{const{helper:m,channel:D}=E,M="im_cos_msg.get_imageinfo",T={str_image_url:I},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 I="";if(n.IN_MINI_APP&&(I=s.url.slice(s.url.lastIndexOf(".")+1)),n.IN_BROWSER&&(I=s.name.slice(s.name.lastIndexOf(".")+1)),tA.indexOf(I.toLowerCase())<0)throw new g.ChatError({code:G})}_checkImageSize(s){const{utils:n,helper:g,store:I}=this._core;let E=0;if(E=(n.IN_MINI_APP,s.size),E===0)throw new g.ChatError({code:L});if(E>=(X(ZI)||20971520))throw new g.ChatError({code:x})}_updateImageType(s){s[1].type=Ae,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,ie="2.5.0",Ee="1.18.0";function He(s,n){const g=s.split("."),I=n.split("."),E=Math.max(g.length,I.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||{},I=g?this.payload:this.content,{uuid:E,downloadFlag:m,fileUrl:D,fileName:M,fileSize:T}=I;return{MsgType:this.type,MsgContent:{Download_Flag:m,Url:Ut.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:I}=n;return I?(g&&this._processNativeAppFile(I),{size:I.size,name:I.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=`${Gr(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)}}At=xr;var bt=new class{constructor(){this._messageOptionsMap=new Map}init(s){var n;this._core=s;const{notificationCenter:g,helper:I,InnerEvent:E,message:m}=s;I.registerApi({apiName:"createFileMessage",context:this}),I.registerExperimentalAPI("createFileMessage",this,"createCustomUploadFileMessage"),(n=m?.messageFactory)===null||n===void 0||n.registerElementClass(xa,st),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createFileMessage(s){var n,g,I;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=(I=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||I===void 0?void 0:I.createMessage(Object.assign(Object.assign({},s),{from:m})),M={uuid:Ut.generateUUID(E),file:E},T=new st(M);return D.setElement(T),this._messageOptionsMap.set(D.clientSequence,s),D}catch(E){throw E}}createCustomUploadFileMessage(s){var n,g,I;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=(I=m.messageFactory)===null||I===void 0?void 0:I.createMessage(Object.assign(Object.assign({},s),{from:M})),RA=new st({url:T,uuid:P,file:{size:W,name:iA},isCustomUpload:!0});return EA.setElement(RA),EA}catch(E){throw E}}upload(s){return mA(this,void 0,void 0,function*(){const{file:n}=this._messageOptionsMap.get(s.clientSequence).payload;this._validateBeforeUploadFile(n);const g=s.getElements()[0],I=yield this._performFileUpload(g,s,n),E=Ut.addAuthToUrl(I?.location);return g.updateFileUrl(E),s})}_validateBeforeUploadFile(s){const{helper:{ChatError:n}}=this._core;if(!s)throw new n({code:GA});const g=X(NE)||104857600;if(s.size>g)throw new n({code:VA});if(s.size===0)throw new n({code:DA})}_performFileUpload(s,n,g){return mA(this,void 0,void 0,function*(){const{to:I}=n,E={uploadFileType:NE,file:g,to:I,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:I,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(I||M){const P=Ut.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:I,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(I){if(!(E||m||D))throw new M({message:"Unsupported mini app environment"});const T=g.getSystemInfoSync().SDKVersion;if(E&&He(T,ie)<0)throw new M({message:`WXChooseMessageFile requires SDK version ${ie} or higher`});if(m&&He(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 xt=2108,Ui=2351,ao=2352,zi=["mp4","quicktime","mov","video"];var ui;class Oo{constructor(n){this.type=Ll,this.uploadProgress=0,this[ui]=!1;const g=typeof n?.videoSecond=="number"?n?.videoSecond:0;this[xr]=n.isCustomUpload||!1,this.content={remoteVideoUrl:Ut.addAuthToUrl(n.remoteVideoUrl||n.videoUrl||""),videoFormat:n.videoFormat,videoSecond:parseInt(g?.toString(),10),videoSize:n.videoSize,videoUrl:Ut.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:Ut.addAuthToUrl(n.thumbUrl),snapshotUrl:Ut.addAuthToUrl(n.thumbUrl)}}static parseServerPushElement(n){const{MsgContent:g}=n,{VideoUrl:I,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 Oo({videoUrl:I,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:I,snapshotHeight:E}=n;Ut.isEmpty(g)||(this.content.thumbUrl=this.content.snapshotUrl=g),Ut.isEmpty(I)||(this.content.thumbWidth=this.content.snapshotWidth=Number(I)),Ut.isEmpty(E)||(this.content.thumbHeight=this.content.snapshotHeight=Number(E))}validateBeforeSend(){if(this[xr])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||{},I=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:re}=I;return{MsgType:this.type,MsgContent:{VideoUrl:Ut.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:Ut.removeAuthToUrl(JA),SnapshotUrl:Ut.removeAuthToUrl(re)}}}}ui=xr;var $o,Qi=new class{constructor(){this._messageOptionsMap=new Map}init(s){var n;this._core=s;const{notificationCenter:g,helper:I,InnerEvent:E,message:m}=s;I.registerApi({apiName:"createVideoMessage",context:this}),I.registerExperimentalAPI("createVideoMessage",this,"createCustomUploadVideoMessage"),(n=m?.messageFactory)===null||n===void 0||n.registerElementClass(Ll,Oo),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createVideoMessage(s){var n,g,I;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=(I=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||I===void 0?void 0:I.createMessage(Object.assign(Object.assign({},s),{from:m})),M={videoFormat:E.videoFile.type,videoSecond:rr(E.videoFile.second,0),videoSize:E.videoFile.size,remoteVideoUrl:"",videoUrl:E.videoFile.url,videoUUID:Ut.generateUUID(E.videoFile),thumbUUID:Ut.generateUUID(E.videoFile,"jpg"),thumbWidth:E.width||200,thumbHeight:E.height||200,thumbUrl:E.thumbUrl,thumbSize:E.thumbSize,thumbFormat:"jpg"},T=new Oo(M);return D.setElement(T),this._messageOptionsMap.set(D.clientSequence,s),D}catch(E){throw E}}createCustomUploadVideoMessage(s){var n,g,I;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=(I=m.messageFactory)===null||I===void 0?void 0:I.createMessage(Object.assign(Object.assign({},s),{from:D})),JA=new Oo({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 mA(this,void 0,void 0,function*(){const n=s.getElements()[0],{file:g}=this._messageOptionsMap.get(s.clientSequence).payload;this._validateBeforeUploadVideo(g);const I=yield this._performVideoUpload(n,s,g),{location:E,snapshotInfo:m}=I,D=Ut.addAuthToUrl(E);return n.updateVideoUrl(D),Ut.isEmpty(m)||n.updateSnapshotInfo(m),s})}_validateBeforeUploadVideo(s){const{helper:{ChatError:n}}=this._core,g=X(Ca)||104857600;if(s.videoFile.size>g)throw new n({code:Ui});if(s.videoFile.size===0)throw new n({code:xt});if(zi.indexOf(s.videoFile.type)===-1)throw new n({code:ao})}_validateCustomUploadVideoMessage(s){var n;const{utils:{isEmpty:g,isNumber:I}}=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)||!I(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 mA(this,void 0,void 0,function*(){const{to:I}=n,E={uploadFileType:Ca,file:g,to:I,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:I}=(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=Ut.extractFileFromInput(D);if(!T)throw new I({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(I){throw console.warn(`${da} _processFile error:`,I),I}}_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 I=s.tempFilePath.slice(s.tempFilePath.lastIndexOf(".")+1).toLowerCase();return n&&(I=s.fileType||I),{url:s.tempFilePath,name:s.tempFilePath.slice(s.tempFilePath.lastIndexOf("/")+1),size:s.size||1,second:s.duration||0,type:I}}_processWebVideoFile(s){const{name:n,size:g=1,duration:I=0,type:E}=s,m=E.split("/")[1];return{url:window.URL.createObjectURL(s),name:n,size:g,second:I,type:m}}_getSnapshotInfoByUrl(s){return mA(this,void 0,void 0,function*(){const{ssoLog:n}=this._core;try{n.debug("_getSnapshotInfoByUrl",`${da} _getSnapshotInfoByUrl url:${s}`);const g={version:1,platform:Ut.getPlatform(),cover_name:Ig(Gr(99999)),snapshot_url:s},I=yield function(T,P){return mA(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}=I||{};if(n.debug("_getSnapshotInfoByUrl",`${da} _getSnapshotInfoByUrl OK snapshotUrl:${E}`),Ut.isEmpty(E))return{};const m=Ut.addAuthToUrl(E),{width:D=0,height:M=0}=yield Ut.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[$o]=!1,this[xr]=n.isCustomUpload||!1,this.content={downloadFlag:2,second:n.second,size:n.size,url:Ut.generateURL(n.url,{needAddAuthToUrl:!this[xr]}),remoteAudioUrl:Ut.addAuthToUrl(n.url||""),uuid:n.uuid}}static parseServerPushElement(n){const{MsgContent:g}=n,{Url:I,Download_Flag:E,Second:m,Size:D,UUID:M}=g;return new Ki({url:I,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[xr])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||{},I=g?this.payload:this.content,{uuid:E,downloadFlag:m,remoteAudioUrl:D,size:M,second:T}=I;return{MsgType:this.type,MsgContent:{Url:Ut.removeAuthToUrl(D),Download_Flag:m,Second:T,Size:M,UUID:E}}}}$o=xr;const Ws=2108,_e=2300,vt=2301;var FA=new class{constructor(){this._messageOptionsMap=new Map}init(s){var n;this._core=s;const{notificationCenter:g,helper:I,InnerEvent:E,message:m}=s;I.registerApi({apiName:"createAudioMessage",context:this}),I.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,I;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=(I=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||I===void 0?void 0:I.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:Ut.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,I;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=(I=m.messageFactory)===null||I===void 0?void 0:I.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 mA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g}}=this._core;n.debug("upload",`${da} uploadAudio message:${g(s)}`);const{file:I}=this._messageOptionsMap.get(s.clientSequence).payload;this._validateBeforeUploadAudio(I);const E=s.getElements()[0],m=yield this._performAudioUpload(E,s,I),D=Ut.addAuthToUrl(m?.location);return E.updateAudioUrl(D),s})}_validateBeforeUploadAudio(s){const{helper:{ChatError:n},store:g}=this._core;if(!s)throw new n({code:_e});const I=X(gl)||20971520;if(s.size>I)throw new n({code:vt});if(s.size===0)throw new n({code:Ws})}_performAudioUpload(s,n,g){return mA(this,void 0,void 0,function*(){const{to:I}=n,E={uploadFileType:gl,file:g,to:I,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:I}=(n=this._core)===null||n===void 0?void 0:n.utils;return g?this._processMiniFile(s):I?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:I,uuid:E,duration:m}=((n=s?.payload)===null||n===void 0?void 0:n.file)||{};if(g(I)||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,[xa]:bt,[Ll]:Qi,[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:I,MSG_VIDEO:E}}}=s;v.init(s),nA.init(s),bt.init(s),Qi.init(s),FA.init(s),q.init(s),Ut.init(s),s.helper.registerApi({apiName:"sendMessage",context:this,matcher:m=>[n,g,I,E].includes(m[0].type)}),s.helper.registerValidateConfig({auth:Zt,params:En})}sendMessage(s,n){return mA(this,void 0,void 0,function*(){var g,I,E;try{return this._isCustomUpload(s)||(yield this._upload(s)),yield(E=(I=(g=this._core)===null||g===void 0?void 0:g.message)===null||I===void 0?void 0:I.messageSender)===null||E===void 0?void 0:E.sendMessage(s,n)}catch(m){throw m}})}_upload(s){return mA(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 I=us[s.type];I&&(yield I.upload(s),n.info("_upload",` type:${s.type}`))}catch(I){throw s.status=XI.FAIL,I instanceof Error&&(I.data={message:s}),this._core.message.messageDataHandler.storeConversationMessage(s),I}})}_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[xr])===!0}};const Co=new class{init(s){this.core=s}};class Et{constructor(n){this.conversationID=n.conversationID||"",this.unreadCount=n.unreadCount||0,this.type=n.type||"",this.lastMessage=Co.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:I}}}=Co;I(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),I(this.groupProfile)&&(this.groupProfile={groupID:this.conversationID.replace(g.CONV_GROUP,""),selfInfo:{},lastMessage:{},type:this.subType}))}updateUnreadCount(n){var g;const{core:{OuterConstant:I,utils:{isUndefined:E},store:m}}=Co,{nextUnreadCount:D,isFromGetConversations:M,isUnreadC2CMessage:T}=n;if(E(D))return;if(this.subType===I.GRP_AVCHATROOM)return void(this.unreadCount=0);if(M&&this.type===I.CONV_GROUP)return void(this.unreadCount=D);if(T&&this.type===I.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!==I.GRP_MEETING||P?this.unreadCount+=D:this.unreadCount=0}updateLastMessage(n){this.lastMessage=Co.core.common.buildLastMessage(n)}reduceUnreadCount(){return this.unreadCount>=1&&(this.unreadCount-=1,!0)}isLastMessageRevoked(n){const{core:{OuterConstant:g}}=Co,{sequence:I,time:E}=n;return this.type===g.CONV_C2C&&I===this.lastMessage.lastSequence&&E===this.lastMessage.lastTime||this.type===g.CONV_GROUP&&I===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}}}=Co;g(n,this.groupAtInfoList)}clearGroupAtInfoList(){this.groupAtInfoList.length=0}getProfileCompleted(){return this._isInfoCompleted}setProfileCompleted(){this._isInfoCompleted=!0}}const Ct=s=>{const{core:{OuterConstant:n,utils:{isString:g}}}=Co;return g(s)&&s.slice(0,3)===n.CONV_C2C},ug=s=>{const{core:{OuterConstant:n,utils:{isString:g}}}=Co;return g(s)&&s.slice(0,5)===n.CONV_GROUP},ks=s=>{const{core:{OuterConstant:n,utils:{isString:g}}}=Co;return g(s)&&s===n.CONV_SYSTEM};function ji(s){const{OuterConstant:n}=Co.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 Yr(s){const{OuterConstant:n}=Co.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}=Co.core,I=new g.ChatError({functionName:s,code:n?.errorCode||n?.code,message:n?.errorInfo||n?.message});throw console.error(`${s} fail:`,I),I}var ts,aa;(function(s){s[s.OFF=0]="OFF",s[s.ON=1]="ON"})(ts||(ts={})),function(s){s[s.ONLY_CONVERSATIONID=1]="ONLY_CONVERSATIONID"}(aa||(aa={}));var ha;(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"})(ha||(ha={}));const $r=0,H=1;var BA=new class{constructor(){this._name="GetC2CMessageRemindType"}init(s){this._core=s}get(s){return mA(this,void 0,void 0,function*(){try{const{common:n}=this._core,g=yield function(E,m){return mA(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:I=[]}=g||{};I.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 mA(this,void 0,void 0,function*(){if(s.length!==0)try{const n=yield function(I,E){return mA(this,void 0,void 0,function*(){const{groupIDList:m,responseFilter:D}=I,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(I=>{var E;const{GroupId:m,MemberList:D}=I,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:I},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=I,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:I=[],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(I)}_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:I=!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:I,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:I,MsgBody:E,MsgRandom:m,ClientSeq:D}=g;let M={};I?M=this._convertGroupAtTipsKey(I):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:I,GroupAtType:E}=s;return{from:n,groupID:g,sequence:I,groupAtType:E}}_updateGroupAtInfoList(){if(this._groupAtTipsList.length===0)return;const{common:s,OuterConstant:n}=this._core,g=s.getCurrentUserID();let I=!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),I=!0)}}),I&&this.emitConversationListUpdate(),this._groupAtTipsList.length=0}_handleMessageDeleted(s){var n,g;console.log(`${this._name}._handleMessageDeleted, conversationID:`,s);const{message:{messageDataHandler:I},OuterConstant:E}=this._core,m=I?.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 I=null,E=!1;n.forEach(m=>{I=this.getLocalConversation(m.conversationID),I&&(g&&I.reduceUnreadCount()&&(E=!0),I.isLastMessageRevoked({sequence:m.sequence,time:m.time})&&(I.setLastMessageRevoked(!0),I.setLastMessageRevoker(m.revoker),E=!0))}),E&&this.emitConversationListUpdate()}_handleMessageModified(s){const{utils:{isEmpty:n},common:{getMessagePreviewText:g},ssoLog:I}=this._core;I.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:I,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)?I.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(I).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:I,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===I){const T=D.replace(I,"");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:I},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=I.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 mA(this,void 0,void 0,function*(){const{OuterConstant:{CONV_GROUP:n},appStore:{groupStore:g},utils:{safeStringify:I},ssoLog:E,apiMap:{getGroupProfile:m}}=this._core;let D=!1;try{yield Promise.all(s.map(M=>mA(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",I(M))}})}_handleMessageRead(s){const{OuterConstant:{CONV_C2C:n}}=this._core,{C2cNotifyMsgArray:g=[]}=s||{};g.forEach(I=>{const{To_Account:E,UinPairReadArray:m=[]}=I?.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:I}}=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===I()&&T.lastTime<=m&&!T.isPeerRead&&(T.isPeerRead=!0,n.conversationStore.updateConversation(E,{lastMessage:T}))}}_updateMessageListPeerRead(s){const{notificationCenter:n,OuterEvent:g,message:I}=this._core,{conversationID:E,peerReadTime:m}=s,D=I.messageDataHandler.getLocalMessageList(E),M=I.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:I,GRP_ROOM:E,GRP_LIVE:m},utils:{isUndefined:D}}=this._core,M=this.getLocalConversation(s);if(D(M))return!0;const T=M.type===I&&((n=M.groupProfile)===null||n===void 0?void 0:n.type)===E,P=M.type===I&&((g=M.groupProfile)===null||g===void 0?void 0:g.type)===m;return!(T||P)}updateUnreadCount(s,n=!0){var g,I;let E=!1;const m=this.getLocalConversation(s),D=(I=(g=this._core)===null||g===void 0?void 0:g.message.messageDataHandler)===null||I===void 0?void 0:I.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:I},conversation:E}=this._core,m=this.getLocalConversationList();this._emitEvent({name:I,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 I=0;return g.forEach(E=>{E.type!==s.CONV_SYSTEM&&(n(E.messageRemindType)||E.messageRemindType===s.MSG_REMIND_ACPT_AND_NOTE)&&(I+=E.unreadCount)}),I}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(I=>{const E=this.getLocalConversation(I);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:I=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=I&&T.time>I,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(I=>I[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:I,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(I,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 mA(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:I}}=this._core;if(n(s))return NA.getLocalConversationList();if(g(s))return s.length===0?[]:NA.getLocalConversationList().filter(E=>s.includes(E.conversationID));if(I(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 mA(this,void 0,void 0,function*(){const{OuterConstant:{CONV_C2C:n,CONV_GROUP:g,GRP_AVCHATROOM:I},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=Ct(s)?n:g;if(m(M)&&(T=!0,M=new Et({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!==I&&(yield yA.get([W]))}return D})}_handleC2CConversation(s,n){return mA(this,void 0,void 0,function*(){var g,I;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:ha.USER_OR_GRP_NOT_FOUND});s.userProfile=W?.data[0];const iA=(I=T.getFriend(n))===null||I===void 0?void 0:I.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 mA(this,void 0,void 0,function*(){const{apiMap:{getGroupProfile:g},appStore:{conversationStore:I}}=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?I.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()}},Ne=new class{constructor(){this._serverGroupConversationLastReadSeqMap=new Map,this._name="SetMessageRead"}init(s){this._core=s;const{helper:n,common:{isTopic:g},notificationCenter:I,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}),I.subscribeInnerEvent(E,m,this._handleAllMessageRead,this)}handleC2CMessageReadSync(s){const{helper:{isEmpty:n},OuterConstant:g}=this._core;s.forEach(I=>{const{ReadC2cMsgNotify:E}=I;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(I=>{const{GroupReadInfoArray:E}=I.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 mA(this,void 0,void 0,function*(){var n,g;const{OuterConstant:I}=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===I.CONV_GROUP&&T&&this._deleteGroupAtTips(E),D.unreadCount===0)return m;const{helper:{ChatError:P}}=this._core;try{if(D.type===I.CONV_C2C){const W=this._getLocalMessageMaxTime(D);M+=`lastMessageTime:${W}`,yield this._setC2CMessageRead(E,W)}if(D.type===I.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===I.CONV_SYSTEM&&(D.unreadCount=0),NA.emitConversationListUpdate(),Object.assign(Object.assign({},m),{successLog:{message:M}})})}setAllMessageRead(){return mA(this,arguments,void 0,function*(s={}){const{OuterConstant:{READ_ALL_MSG:n},utils:{safeStringify:g}}=this._core;let I=`scope:${s.scope}`;s.scope||(s.scope=n);const{scope:E}=s,m=this._generateSetAllMessageReadRequestData(E);if(m.allC2CMessageReadStatus===$r&&m.groupMessageReadInfoList.length===0)return{code:0};try{const D=yield function(M){return mA(this,void 0,void 0,function*(){const{allC2CMessageReadStatus:T,groupMessageReadInfoList:P}=M,W={C2CReadAllMsg:T,GroupReadInfo:P};return Co.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(),I+=`failureGroupInfoList:${g(P)}`}return{code:0,successLog:{message:I}}}catch(D){const{errorCode:M}=D;throw new this._core.helper.ChatError({functionName:"setAllMessageRead",code:M,moreMessage:I})}})}_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:I}=this._core,E=I.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:I},appStore:E}=this._core,m={allC2CMessageReadStatus:$r,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===$r){if(m.allC2CMessageReadStatus=H,s===I)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(I=>{const{GroupId:E,MsgSeq:m,RetCode:D,LastReadMsgSeq:M}=I;n(D)?this._serverGroupConversationLastReadSeqMap.set(E,M):(this._serverGroupConversationLastReadSeqMap.set(E,m),D!==0&&g.push(`${E}-${m}-${D}`))}),g}_deleteGroupAtTips(s){return mA(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:I,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:I(),MsgSeq:P.__sequence,MsgRandom:P.__random,GroupId:P.groupID}));yield function(P,W){return mA(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(I){console.error(`${this._name}._deleteGroupAtTips fail:`,I)}})}_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,I=this._core.message.messageDataHandler.getLocalMessageList(g),E=Math.max(...I.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,I=this._core.message.messageDataHandler.getLocalMessageList(g),E=Math.max(...I.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 mA(this,void 0,void 0,function*(){try{yield function(g,I){return mA(this,void 0,void 0,function*(){return I.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 mA(this,void 0,void 0,function*(){try{yield function(g,I){return mA(this,void 0,void 0,function*(){const{groupID:E,lastMessageSequence:m}=g,D={GroupId:E,MsgReadedSeq:m};return I.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:I,READ_ALL_C2C_MSG:E,READ_ALL_GROUP_MSG:m}}=this._core,{type:D,scope:M,unreadCount:T}=s;return!(T<=0)&&(!(D!==n||![I,E].includes(M))||!(D!==g||![I,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:I}=this._core;let E=!1;s.forEach(m=>{const{Type:D,Peer_Account:M,GroupId:T}=m;let P;D===1?P=NA.getLocalConversation(`${I.CONV_C2C}${M}`):D===2&&(P=NA.getLocalConversation(`${I.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 mA(this,void 0,void 0,function*(){const{OuterConstant:n,common:g,helper:{ChatError:I}}=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(Ct(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 mA(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 Et({conversationID:E,type:Ct(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 I({functionName:"pinConversation",code:W,message:iA,moreMessage:T})}})}},Ue=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,I=[];s.forEach(E=>{const{Type:m,Peer_Account:D,GroupId:M}=E;m===1&&I.push(`${g.CONV_C2C}${D}`),m===2&&I.push(`${g.CONV_GROUP}${M}`)}),console.log(`${this._name}.handleConversationDeleted conversationIDList:${I}`),this._deleteLocalConversationList(I)}deleteConversation(s){return mA(this,void 0,void 0,function*(){const{utils:{isString:n}}=this._core;if(n(s))return this._deleteConversation({conversationIDList:[s],flag:aa.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 mA(this,void 0,void 0,function*(){const{conversationIDList:n,clearHistoryMessage:g=!0,flag:I=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:ha.CONV_NOT_FOUND});return{code:0,data:I===aa.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 I;if(!NA.hasLocalConversation(g))return!1;const E=(I=NA.getLocalConversation(g))===null||I===void 0?void 0:I.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 mA(this,void 0,void 0,function*(){const{OuterConstant:g,common:I}=this._core,E={fromAccount:I.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 mA(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,I=s.replace(n,"");return!!g.getGroup(I)}_deleteConversationLocalMessage(s){console.log(`${this._name}._deleteConversationLocalMessage conversationID:${s}`),this._core.message.messageDataHandler.deleteConversationMessageList(s),this._core.message.messageHistory.completedHistoryConversations.delete(s)}},yt=new class{constructor(){this._name="SetConversationDraft"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"setConversationDraft",context:this})}setConversationDraft(s){return mA(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:ha.CONV_NOT_FOUND});const I=NA.getLocalConversation(n);return I?.setDraftText(g),NA.emitConversationListUpdate(),{code:0,data:{conversation:I}}})}},Kt=new class{constructor(){this._name="SetC2CMessageRemindType"}init(s){this._core=s}set(s,n){return mA(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}=Co.core.OuterConstant;return{[P]:0,[W]:1,[iA]:2}}()[n],I=yield function(P,W){return mA(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=[]}=I||{},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 mA(this,void 0,void 0,function*(){const{common:{getCurrentUserID:g,isTopic:I},OuterConstant:E}=this._core;if(yield function(m,D){return mA(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),!I(s)){const m=`${E.CONV_GROUP}${s}`;NA.patchMessageRemindType([m],n)}return{code:0,data:{groupID:s,messageRemindType:n}}})}},Qt=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:I}=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);I.debug(`${this._name}.handleC2CMessageRemindTypeSync conversationIDList:${T} messageRemindType:${P}`),NA.patchMessageRemindType(T,P)}})}setMessageRemindType(s){return mA(this,void 0,void 0,function*(){const n="setMessageRemindType",{groupID:g,userIDList:I,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(I))return M.debug(`${this._name}.${n} userIDList:${I} messageRemindType:${E}`),yield Kt.set(I,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:${I} messageRemindType:${E}`})}})}},hi=new class{init(s){s.ssoLog.debug("ConversationAction.init"),this._core=s,ZA.init(s),Re.init(s),Ie.init(s),Ne.init(s),ae.init(s),Ue.init(s),yt.init(s),Qt.init(s);const{notificationCenter:n,InnerEvent:{MESSAGE_PUSH:g,DESTROY:I}}=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(I,this._dispose,this)}_onConversationModified(s){const{constants:{ConvModifyPushType:n}}=this._core,{RecentContactMod:g=[]}=s;g.forEach(I=>{const{PushType:E}=I;if(E===n.CONV_DELETED){const{RecentContactList:m}=I.RecentContactDeleteItem;Ue.handleConversationDeleted(m)}if(E===n.CONV_PINED){const{RecentContactList:m}=I.RecentContactTopItem;ae.handleConversationPinned(m,!0)}if(E===n.CONV_UNPINED){const{RecentContactList:m}=I.RecentContactTopItem;ae.handleConversationPinned(m,!1)}})}_onC2CMessageReadSync(s){const{C2cNotifyMsgArray:n=[]}=s;Ne.handleC2CMessageReadSync(n)}_onC2CMessageRemindTypeSync(s){const{C2cNotifyMsgArray:n=[]}=s;Qt.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:I,C2C_MESSAGE_READ_SYNC:E,GROUP_MESSAGE_READ_SYNC:m,C2C_REMIND_TYPE_SYNC:D}}=s;s.unSubscribeInnerEvent(n,I,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 mA(this,void 0,void 0,function*(){try{const{OuterConstant:{MSG_REMIND_ACPT_NOT_NOTE:n}}=this._core,{messageRemindType:g=n,isRepeated:I=!0}=s,{startTime:E=0,endTime:m=0}=this._calcStartAndEndTime(s),D=yield function(M){return mA(this,void 0,void 0,function*(){const{common:T}=Co.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:I?ts.ON:ts.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:I=0,duration:E=0,isRepeated:m=!0}=s,D=new Date,M=new Date(D.getFullYear(),D.getMonth(),D.getDate(),n,g,I),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:I}=s;n.registerApi({apiName:"getAllReceiveMessageOpt",context:this}),g.subscribeInnerEvent(I.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:I}}=this._core;g.emitOuterEvent(I,{name:I,data:n})}getAllReceiveMessageOpt(){return mA(this,void 0,void 0,function*(){try{const s=yield function(){return mA(this,void 0,void 0,function*(){const{common:n}=Co.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:I,MSG_REMIND_ACPT_NOT_NOTE:E}=n,m={0:g,1:I,2:E},{Level:D,StartTime:M,EndTime:T,IsRepeated:P}=s;return{messageRemindType:m[D]||g,startTime:M,endTime:T,isRepeated:P===ts.ON}}},Lo=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 ei=s=>!Ct(s)&&!ug(s)&&!ks(s),kr={getConversationProfile:[{key:"conversationID",required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!ei(s)||"conversationID is invalid."}],setMessageRead:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!ei(s)||"conversationID is invalid."}},pinConversation:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!ei(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:I}}}=Co;if(!I(s)&&!g(s))return"options is String or Object.";if(I(s)&&ei(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(ei(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=>!(!Ct(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){Co.init(s),hi.init(s),Lo.init(s),NA.init(s),s.helper.registerValidateConfig({auth:zo,params:kr})}};const Wn=new class{init(s){this.core=s}},Aa="AVChatRoom",Vr="AV_HISTORY_MSG",sc="GRP_COUNTER",Pu="Set",Cm="Increase",Ri="Decrease",ti=0,fo=1,on=2,is=["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"],Ul=["Role","JoinTime","MsgFlag","MsgSeq"],Cd=["Role","JoinTime","MsgSeq","MsgFlag","NameCard"],Lc=0,Sr=1,mI="notStart",Au="resolved",Og="rejected",eu=10018,fI=11e3,Uc=2,xu=["Owner","Admin","Member"],hm=["Role","JoinTime","NameCard","ShutUpUntil","OnlineStatus"],Bm=0,Qm=1,pm=2,Xy=4,$y=1,Dv=2,AD=3,eD=4,Sv=5,X_=1,hd=0,$_=4,tD=6,AT=400,iD=300,eT={from:!0,groupID:!0,groupName:!0,to:!0},Mv={from:!0,groupID:!0,groupName:!0,to:!0,type:!0},tT=2,vv=4,iT=5,oT=7,oD=8,sD=15,MQ=20,mm=21,fm=2600,Bd=2602,sT=2603,nT=2620,ym=2621,nD=2623,gh=2660,rT=2661,aT=2681,Dm=2683,Rv=2684,rD=2685,Sm=2687,wv=3122,gT=10018,cT={0:"DisableInvite",1:"NeedPermission",2:"FreeAccess"},_v=s=>s===Wn.core.OuterConstant.GRP_PUBLIC,Qd=s=>s===Wn.core.OuterConstant.GRP_AVCHATROOM,Mm=(s,n)=>{const{isArray:g}=Wn.core.utils;if(!g(s)||!g(n))return!1;let I=!1;return n.forEach(({key:E,value:m})=>{const D=s.find(M=>M.key===E);D?D.value!==m&&(D.value=m,I=!0):(s.push({key:E,value:m}),I=!0)}),I},pd=s=>{const n=[];if(!s)return n;for(let g=0,I=s.length;g{const n=[];for(let g=0,I=s.length;g0&&M.members.forEach(T=>{T.userID===this.selfInfo.userID&&D(this.selfInfo,T,["sequence"])})}updateSelfInfo(n){const{nameCard:g,joinTime:I,role:E,messageRemindType:m,readedSequence:D,excludedUnreadSequenceList:M}=n,{common:{deepMerge:T}}=Wn.core;T(this.selfInfo,{nameCard:g,joinTime:I,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 Yu(E)),this._clearGroupLocalMessage(g))});const I=n();for(const[,E]of this._groupMap)E.selfInfo.userID=I,E.selfInfo.role==="Owner"&&(E.ownerID=I)}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:I}=g;return I!==s&&I!==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,I=`${g}${s}`,E=n.getConversation(I);if(E){const m=this.getLocalGroup(s);E.setProfileCompleted(),n.updateConversation(I,{groupProfile:m})}}reset(){this.clearLocalGroup()}_clearGroupLocalMessage(s){const{message:{messageHistory:n,messageDataHandler:g},OuterConstant:{CONV_GROUP:I},ssoLog:E}=this._core;E.debug("_clearGroupLocalMessage",`groupID:${s}`);const m=`${I}${s}`;n.completedHistoryConversations.delete(m),g.deleteConversationMessageList(m)}};function Rm(s,n){return mA(this,void 0,void 0,function*(){const{type:g,limit:I,offset:E,supportTopic:m=0,memberAccount:D,responseFilter:M}=s,T={Type:g,Limit:I,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 Tv=new class{constructor(){this._name="GetGroupList",this._pagingStatus=mI,this.PAGING_GRP_COUNT_LIMIT=200}init(s){this._core=s;const{helper:n,constants:{WORKFLOW_NAME:g,WORKFLOW_STEP:I}}=s;n.registerApi({apiName:"getGroupList",context:this}),n.registerWorkflowStep(g.SYNC_SERVER_INFO_AFTER_LOGIN,I.GROUP_LIST_SYNC,this._syncGroupList,this)}getGroupList(){return mA(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===mI)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 mA(this,void 0,void 0,function*(){this._pagingStatus===mI&&Yi.clearLocalGroup();const s=this.PAGING_GRP_COUNT_LIMIT,n=[];try{yield this._pagingGetGroupList({limit:s,offset:0,groupList:n}),this._pagingStatus=Au,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 mA(this,void 0,void 0,function*(){const{ssoLog:n}=this._core,{isCommunityRelay:g=!1,groupList:I}=s;let E,{limit:m,offset:D}=s;const M=[...is];g&&(E=this._core.OuterConstant.GRP_COMMUNITY,M.push("AtInfoList"));try{const T=yield Rm({type:E,limit:m,offset:D,memberAccount:this._core.store.get("login").userId,responseFilter:{GroupBaseInfoFilter:M,SelfInfoFilter:[...Ul]}},this._core),{GroupIdList:P=[],TotalCount:W=0}=T||{},iA=this._convertGroupKey(P);I.push(...iA);const EA=D+m,RA=!(W>EA),kA=`offset:${D} limit:${m} total:${W} isCompleted:${RA} current:${I.length} isCommunityRelay:${g}`;return n.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList ok. ${kA}`),g?RA?I:(D=EA,this._pagingGetGroupList({isCommunityRelay:!0,limit:m,offset:D,groupList:I})):RA?(n.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList start to get community list`),D=0,this._pagingGetGroupList({isCommunityRelay:!0,limit:m,offset:D,groupList:I})):(D=EA,this._pagingGetGroupList({limit:m,offset:D,groupList:I}))}catch(T){if(T.ErrorCode===eu)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:I});if(g)return T.code===fI&&n.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList ok. community unavailable`),I;throw T}})}_pagingGetJoinedCommunityList(s){return mA(this,void 0,void 0,function*(){const{common:{getCurrentUserID:n},OuterConstant:g,ssoLog:I}=this._core,{groupList:E}=s;let{limit:m,offset:D}=s;try{const M=yield Rm({limit:m,offset:D,type:g.GRP_COMMUNITY,memberAccount:n(),supportTopic:1,responseFilter:{GroupBaseInfoFilter:[...is],SelfInfoFilter:[...Ul]}},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 I.debug("_pagingGetJoinedCommunityList",`${this._name}._pagingGetJoinedCommunityList ok. ${RA}`),EA?E:(D=iA,this._pagingGetJoinedCommunityList({limit:m,offset:D,groupList:E}))}catch(M){if(M.code===gT)return I.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 I=0,E=s.length;I{const{AtFlagList:E,AtMsgSeq:m,From_Account:D}=I;g.push({groupID:s,groupAtType:E,sequence:m,from:D})}),g}},Vu=new class{constructor(){this._name="CreateGroup"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"createGroup",context:this})}createGroup(s){return mA(this,void 0,void 0,function*(){var n;this._preCheckParams(s);const{helper:{ChatError:g}}=this._core;try{const{utils:{isEmpty:I},common:{getCurrentUserID:E},OuterConstant:{GRP_AVCHATROOM:m}}=this._core,D=yield function(iA,EA){return mA(this,void 0,void 0,function*(){const{name:RA,type:kA,groupID:xA,introduction:LA,notification:SA,avatar:OA,maxMemberNum:JA,joinOption:re,inviteOption:ne,memberList:_i,groupCustomField:Ti,isSupportTopic:kt}=iA;let Ni,cs;_i&&(Ni=_i.map(Bt=>{const{userID:UA,memberCustomField:ii}=Bt;return{Member_Account:UA,AppMemberDefinedData:ii?bE(ii):void 0}})),Ti&&(cs=bE(Ti));const Se={Name:RA,Type:kA,GroupId:xA,Introduction:LA,Notification:SA,FaceUrl:OA,MaxMemberCount:JA,ApplyJoinOption:re,InviteJoinOption:ne,MemberList:Ni,AppDefinedData:cs,SupportTopic:kt,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(I(s.memberList)||I(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 Yu(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(I){const{errorCode:E,errorInfo:m}=I;throw new g({functionName:"createGroup",code:E,message:m,moreMessage:` groupID:${s.groupID}`})}})}_preCheckParams(s){const{type:n,groupID:g}=s,{utils:{isEmpty:I,isUndefined:E},common:{isCommunity:m}}=this._core,D=!I(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:fm});if(!m({type:n})){if(D&&m({groupID:g}))throw new this._core.helper.ChatError({code:Bd});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:Bd});s.isSupportTopic=this._canIUseTopic(s)?1:0}}_canIUseMemberList(s){return!Qd(s)}_canIUseJoinOption(s){return _v(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:I,GRP_COMMUNITY:E}}=this._core;return n===I||n===E&&g===1}_sendCustomMessage(s,n){var g,I,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=Sr);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=(I=(g=this._core)===null||g===void 0?void 0:g.message)===null||I===void 0?void 0:I.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:I}}=this._core;return!I(n)&&!g(n.groupAttributeOption)}handleGroupAttributesUpdated(s){const{groupID:n,groupAttributeOption:g}=s,{serverMainSequence:I,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:I,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:I,operation:E}=s;if(this.hasGroupAttributesCache(n)){const m=this.getGroupAttributesCache(n),{localMainSequence:D}=m;E!==Sv&&g-D!==1||(m.serverMainSequence=g,m.localMainSequence=g,m.lastUpdateTime=Date.now(),this._updateGroupAttributesCacheValues({groupAttributes:m,groupAttributeList:I,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:I}=s;I!==AD?I!==eD?(I===$y&&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:I=[]}=s,E={};if(this.hasGroupAttributesCache(g)){const{values:m}=this.getGroupAttributesCache(g);if(I.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 I.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:I,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||([I,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=[],I=[];return Object.keys(s).forEach(E=>{s[E]!==this._groupAttributesCacheValuesCopy[E]&&g.push(E)}),Object.keys(this._groupAttributesCacheValuesCopy).forEach(E=>{n(s[E])&&I.push(E)}),this._groupAttributesCacheValuesCopy={},{updatedKeyList:g,deletedKeyList:I}}_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={}}},lh=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(Aa)})}dismissGroup(s){return mA(this,void 0,void 0,function*(){const{helper:{ChatError:n}}=this._core;try{yield function(I,E){return mA(this,void 0,void 0,function*(){const m={GroupId:I};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:I,errorInfo:E}=g;throw new n({functionName:"dismissGroup",code:I,message:E})}})}},Fl=new class{constructor(){this._name="GetGroupProfile"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"getGroupProfile",context:this})}getGroupProfile(s){return mA(this,void 0,void 0,function*(){const{groupID:n,groupCustomFieldFilter:g}=s,I={groupIDList:[n],responseFilter:{GroupBaseInfoFilter:[...is],AppDefinedDataFilter_Group:g,MemberInfoFilter:[...Cd]}},{helper:{ChatError:E}}=this._core;try{const m=yield this.getGroupProfileAdvance(I),{successGroupList:D,failureGroupList:M}=m;if(M.length>0)throw M[0];let T;return!Yi.hasLocalGroup(n)&&Qd(D[0].type)?T=new Yu(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 mA(this,void 0,void 0,function*(){const{groupIDList:n}=s,{common:{isCommunity:g}}=this._core,I=n.filter(T=>!g({groupID:T})),E=n.filter(T=>g({groupID:T}));I.length>50&&(I.length=50),E.length>50&&(E.length=50);const m=yield Promise.all([this._getGroupProfileAdvance(Object.assign(Object.assign({},s),{groupIDList:I})),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 mA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{isUndefined:g}}=this._core,{isCommunityProfile:I=!1}=s,E=yo(s,["isCommunityProfile"]);if(E.groupIDList.length===0)return{successGroupList:[],failureGroupList:[]};try{const m=yield function(W,iA){return mA(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(I)return{successGroupList:[],failureGroupList:[]};throw m}})}_convertGroupProfileKey(s){const n=[];for(let g=0,I=s.length;g0&&I{const{Key:T,Value:P=0}=M;E.set(T,P)}),this._groupCountersMap.set(n,{lastUpdateTime:Date.now(),groupCounterSeq:I,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:I}=this.getLocalGroupCounters(s);if(n.length>0)n.forEach(E=>{I.has(E)&&(g[E]=I.get(E))});else for(const E of I.keys())g[E]=I.get(E);return g}deleteLocalGroupCounters(s){const{groupID:n,counterList:g=[],groupCounterSeq:I}=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:I,counters:E,avChatRoomKey:m})}}setGroupCounters(s,n){if(!this._hasLocalGroupCounters(s))return;const g=this.getLocalGroupCounters(s),{counters:I}=g;let E=!1;Object.entries(n).forEach(([m,D])=>{I.has(m)&&I.get(m)!==D&&(I.set(m,D),E=!0)}),E&&this._groupCountersMap.set(s,Object.assign(Object.assign({},g),{lastUpdateTime:Date.now(),counters:I}))}_hasLocalGroupCounters(s){return this._groupCountersMap.has(s)}reset(){this._groupCountersMap.clear()}},kE=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(Aa)})}joinGroup(s){return mA(this,void 0,void 0,function*(){const{groupID:n}=s,{helper:{ChatError:g},OuterConstant:I,ssoLog:E}=this._core;try{if(Yi.hasLocalGroup(n))try{return yield Fl.getGroupProfile({groupID:n}),dn({status:I.JOIN_STATUS_ALREADY_IN_GROUP,group:Yi.getLocalGroup(n)},{message:`groupID:${n} joinedStatus:${I.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 mA(this,void 0,void 0,function*(){const{OuterConstant:n,helper:g,ssoLog:I}=this._core,{groupID:E}=s,m=Object.assign({},s),D=g.checkBusinessCapabilityBits(Vr);D&&(m.historyMessageFlag=1);const M=yield function(SA,OA){return mA(this,void 0,void 0,function*(){const{groupID:JA,applyMessage:re,historyMessageFlag:ne}=SA,_i={GroupId:JA,ApplyMsg:re,HugeGroupHistoryMsgFlag:ne};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}`;I.debug("_applyJoinGroup",`${this._name}._applyJoinGroup ok, ${xA}`);let LA=new Yu({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 Fl.getGroupProfile({groupID:E})).data.group}catch(SA){I.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:gh})})}_handleJoinResult(s){const{group:n,avChatRoomFlag:g,avChatRoomKey:I}=s;return g===1?(zs.initGroupAttributesCache({groupID:n.groupID,avChatRoomKey:I}),nc.initGroupCountersCache({groupID:n.groupID,avChatRoomKey:I}),dn(s)):(Yi.updateLocalGroup([n]),Yi.emitGroupListUpdate(),dn({status:this._core.OuterConstant.JOIN_STATUS_SUCCESS,group:n},{message:`groupID:${n.groupID}`}))}},vQ=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(Aa)})}quitGroup(s){return mA(this,void 0,void 0,function*(){if(!Yi.hasLocalGroup(s))throw new this._core.helper.ChatError({code:nD});const{helper:{ChatError:n}}=this._core;try{yield function(I,E){return mA(this,void 0,void 0,function*(){const m={GroupId:I};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:I,errorInfo:E}=g;throw new n({functionName:"quitGroup",code:I,message:E,moreMessage:`groupID:${s}`})}})}},rB=new class{constructor(){this._name="SearchGroup"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"searchGroupByID",context:this})}searchGroupByID(s){return mA(this,void 0,void 0,function*(){try{const n=yield function(OA,JA){return mA(this,void 0,void 0,function*(){const re={GroupIdList:[OA],GroupBasePublicInfoFilter:[...Eg]};return JA.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_public_info",data:re})})}(s,this._core),{GroupInfo:g=[]}=n||{},{AppDefinedData:I=[],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=pd(I),SA=new Yu({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:I}=n;throw new this._core.helper.ChatError({functionName:"searchGroupByID",code:g,message:I})}})}},lT=new class{constructor(){this._name="UpdateGroupProfile"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"updateGroupProfile",context:this})}updateGroupProfile(s){return mA(this,void 0,void 0,function*(){const{groupID:n}=s,{utils:{isUndefined:g,safeStringify:I},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 mA(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?bE(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 Yu(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:${I(s)}`})}})}_canIUseJoinOption(s){return _v(s)||this._core.common.isCommunity({type:s})}},IT=new class{constructor(){this._name="ChangeGroupOwner"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"changeGroupOwner",context:this})}changeGroupOwner(s){return mA(this,void 0,void 0,function*(){const n="changeGroupOwner",{groupID:g,newOwnerID:I}=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:nT});if(I===M())throw new m.ChatError({functionName:n,code:ym});try{return yield function(T,P){return mA(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=I,Yi.emitGroupListUpdate(),dn({group:E})}catch(T){throw new m.ChatError({functionName:n,code:T?.errorCode,message:T?.errorInfo})}})}},RQ=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(Aa)})}getGroupOnlineMemberCount(s){return mA(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 I=this._onlineMemberCountMap.get(s),{lastReqTime:E=0,memberCount:m=0}=I||{};if(g-E<=6e4)return dn({memberCount:m})}try{const I=yield function(D,M){return mA(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}=I||{};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(I){throw new this._core.helper.ChatError({functionName:n,code:I?.errorCode,message:I?.errorInfo})}})}},wQ=new class{init(s,n){s.ssoLog.debug("GroupAction.init"),Tv.init(s),Vu.init(s),lh.init(s,n),kE.init(s,n),vQ.init(s,n),rB.init(s),Fl.init(s),lT.init(s),IT.init(s),RQ.init(s,n)}dismissGroup(s){return lh.dismissGroup(s)}joinGroup(s){return kE.joinGroup(s)}quitGroup(s){return vQ.quitGroup(s)}getGroupOnlineMemberCount(s){return RQ.getGroupOnlineMemberCount(s)}},Nv=new class{constructor(){this._name="GetGroupApplicationList"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"getGroupApplicationList",context:this})}getGroupApplicationList(){return mA(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 mA(this,void 0,void 0,function*(){const{type:n,startTime:g=0,limit:I=20}=s||{},{common:E}=this._core;let m;try{m=yield function(P,W){return mA(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:I,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 I=this._convertApplicationData(g),{handled:E}=I,m=yo(I,["handled"]);E===0&&n.push(m)}),n}_convertApplicationData(s){const{Handled:n,AddTime:g,ApplyInviteMsg:I,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:I,addTime:g}}},Gv=new class{constructor(){this._name="HandleGroupApplication"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"handleGroupApplication",context:this})}handleGroupApplication(s){return mA(this,void 0,void 0,function*(){const{application:n}=s,g=this._handleParams(s);try{n?.applicationType===Uc?yield function(E,m){return mA(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 mA(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 I=Yi.getLocalGroup(g.groupID);return dn({group:I})}catch(I){throw new this._core.helper.ChatError({functionName:"handleGroupApplication",code:I?.errorCode,message:I?.errorInfo})}})}_handleParams(s){var n;const{handleAction:g,handleMessage:I,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:I,applicant:D,invitee:W,groupID:M,authentication:T,messageKey:P}}},aD=new class{init(s){s.ssoLog.debug("GroupApplication.init"),Nv.init(s),Gv.init(s)}};let BC=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 I=[null,void 0,"",0,NaN];s.memberCustomField&&Mm(this.memberCustomField,s.memberCustomField),g(this,s,["memberCustomField","marks","onlineStatus","muteTime"],I)}};function aB(s,n){return mA(this,void 0,void 0,function*(){const{groupID:g,userID:I,muteTime:E,role:m,nameCard:D,memberCustomField:M}=s;let T;M&&(T=bE(M));const P={GroupId:g,Member_Account:I,ShutUpTime:E,Role:m,NameCard:D,AppMemberDefinedData:T};return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:P})})}var gD=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(Aa)})}getGroupMemberList(s){return mA(this,void 0,void 0,function*(){const n="getGroupMemberList",{groupID:g,offset:I=0,count:E=100,role:m="",filter:D=""}=s,M=Yi.getLocalGroup(g),T=E>100?100:E,P={groupID:g,offset:I,limit:T,memberRoleFilter:xu.includes(m)?[m]:void 0,memberInfoFilter:hm};try{const W=yield function(ne,_i){return mA(this,void 0,void 0,function*(){const{isCommunity:Ti}=_i.common,{groupID:kt,offset:Ni,limit:cs,memberRoleFilter:Se,memberInfoFilter:Bt}=ne,UA={GroupId:kt,Limit:cs,MemberRoleFilter:Se,MemberInfoFilter:Bt};return Ti({groupID:kt})?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=I+T;SA({groupID:g})&&(OA=LA(RA)?0:RA),iA.lengthD.userID),I=yield(n=this._core.user.userProfile)===null||n===void 0?void 0:n.getUserProfile({userIDList:g}),E=I?.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,I=s.length;g50&&(T.warn("getGroupMemberProfile",`${this._name}.${n} userIDList length:${I.length} exceeds limit 50`),I.splice(50));const P=`userIDList length:${I.length} groupID:${g}`;try{const W=yield function(kA,xA){return mA(this,void 0,void 0,function*(){const{groupID:LA,userIDList:SA,memberInfoFilter:OA,memberCustomFieldFilter:JA}=kA,re={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:re})})}({groupID:g,userIDList:I,memberCustomFieldFilter:E,memberInfoFilter:[...hm]},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,I=s.length;gD.userID),I=yield(n=this._core.user.userProfile)===null||n===void 0?void 0:n.getUserProfile({userIDList:g}),E=I?.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,I=s.length;g({Member_Account:M}));try{const M=yield function(RA,kA){return mA(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=[],I=[],E=[];return s.forEach(m=>{const{Result:D,Member_Account:M}=m;D===Bm?n.push(M):D===Qm?g.push(M):D===pm?I.push(M):D===Xy&&E.push(M)}),{failureUserIDList:n,successUserIDList:g,existedUserIDList:I,overLimitUserIDList:E}}},fd=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(Aa)})}deleteGroupMember(s){return mA(this,void 0,void 0,function*(){const n="deleteGroupMember",{groupID:g,userIDList:I}=s,E=Yi.getLocalGroup(g),{helper:m,utils:{isUndefined:D},ssoLog:M}=this._core;if(D(E))throw new m.ChatError({functionName:n,code:sT});I.length>20&&(M.warn("deleteGroupMember",`${this._name}.${n} userIDList length:${I.length} exceeds limit 20`),I.splice(20));try{return yield function(T,P){return mA(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:I},this._core),dn({group:E,userIDList:I},{message:`groupID:${g} userIDList length:${I.length}`})}catch(T){throw new m.ChatError({functionName:n,code:T?.errorCode,message:T?.errorInfo})}})}},bv=new class{constructor(){this._name="SetGroupMemberMuteTime"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"setGroupMemberMuteTime",context:this})}setGroupMemberMuteTime(s){return mA(this,void 0,void 0,function*(){const{helper:n}=this._core,{groupID:g,userID:I,muteTime:E}=s,m=` groupID:${g} userID:${I} muteTime:${E}`;this._preCheckSettingMuteParams(s);try{yield aB(s,this._core);const D=Yi.getLocalGroup(g),M=new BC({userID:I,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:I}=this._core;if(n===g.get("login").userId)throw new I.ChatError({functionName:"setGroupMemberMuteTime",code:rD})}},TQ=new class{constructor(){this._name="SetGroupMemberRole"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"setGroupMemberRole",context:this})}setGroupMemberRole(s){return mA(this,void 0,void 0,function*(){const n="setGroupMemberRole",{helper:g}=this._core,{groupID:I,userID:E,role:m}=s,D=`${this._name}.${n} ok, groupID:${I} userID:${E} role:${m}`;this._preCheckSettingRoleParams(s);try{yield aB(s,this._core);const M=Yi.getLocalGroup(I),T=new BC({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:I,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:aT});if(I===m.get("login").userId)throw new D.ChatError({functionName:"setGroupMemberRole",code:Rv});const W=[...xu];if(T({groupID:g})&&W.push(M.GRP_MBR_ROLE_CUSTOM),!W.includes(E))throw new D.ChatError({functionName:"setGroupMemberRole",code:Dm})}},cD=new class{constructor(){this._name="SetGroupMemberNameCard"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"setGroupMemberNameCard",context:this})}setGroupMemberNameCard(s){return mA(this,void 0,void 0,function*(){var n;const g="setGroupMemberNameCard",{helper:I,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 aB({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 BC({userID:D,nameCard:M});return dn({group:W,member:iA},{message:T})}catch(P){throw new I.ChatError({functionName:g,code:P?.errorCode,message:P?.errorInfo,moreMessage:T})}})}_preCheckSettingNameCardParams(s){const{groupID:n}=s,{helper:g}=this._core,I=Yi.getLocalGroup(n);if(Qd(I?.type))throw new g.ChatError({functionName:"setGroupMemberNameCard",code:Sm})}},wm=new class{constructor(){this._name="SetGroupMemberCustomField"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"setGroupMemberCustomField",context:this})}setGroupMemberCustomField(s){return mA(this,void 0,void 0,function*(){const n="setGroupMemberCustomField",{helper:g,common:{getCurrentUserID:I}}=this._core;this._preCheckSettingCustomFiledParams(s);const{groupID:E,userID:m=I(),memberCustomField:D}=s,M=`${this._name}.${n} ok, groupID:${E}userID:${m} memberCustomField:${JSON.stringify(D)}`;try{yield aB({groupID:E,userID:m,memberCustomField:D},this._core);const P=Yi.getLocalGroup(E),W=new BC({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,I=Yi.getLocalGroup(n);if(Qd(I?.type))throw new g.ChatError({functionName:"setGroupMemberCustomField",code:Sm})}},kv=new class{init(s,n){s.ssoLog.debug("GroupMember.init"),gD.init(s,n),_Q.init(s),md.init(s),fd.init(s,n),bv.init(s),TQ.init(s),cD.init(s),wm.init(s)}getGroupMemberList(s){return gD.getGroupMemberList(s)}deleteGroupMember(s){return fd.deleteGroupMember(s)}},uT=new class{init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"getGroupCounters",context:this})}getGroupCounters(s){return mA(this,void 0,void 0,function*(){const n="getGroupCounters";try{vm(n,sc);const{groupID:g,keyList:I=[]}=s,{avChatRoomKey:E,lastUpdateTime:m}=nc.getLocalGroupCounters(g);if(!(Date.now()-m>=this._getExpireTime()))return{code:0,data:{counters:nc.getLocalCounters(g,I)}};const D=yield function(P){return mA(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:I,avChatRoomKey:E}),{GroupCounter:M=[],GroupCounterSeq:T}=D;return nc.updateLocalGroupCounters({groupID:g,counterList:M,groupCounterSeq:T}),{code:0,data:{counters:nc.getLocalCounters(g,I)}}}catch(g){hC(n,g)}})}_getExpireTime(){const{store:s,utils:{isUndefined:n}}=this._core,g=s.get("cloudConfig")||{},{grp_counter_expire_time:I}=g;return n(I)?3e4:Number(I)}},_m=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 mA(this,void 0,void 0,function*(){return this._handleCounterOperation(Pu,s)})}increaseGroupCounter(s){return mA(this,void 0,void 0,function*(){return this._handleCounterOperation(Cm,s)})}decreaseGroupCounter(s){return mA(this,void 0,void 0,function*(){return this._handleCounterOperation(Ri,s)})}_handleCounterOperation(s,n){return mA(this,void 0,void 0,function*(){const g=`${s}GroupCounter`;try{vm(g,sc);const{groupID:I,key:E,value:m=0}=n,{avChatRoomKey:D}=nc.getLocalGroupCounters(I),M=s===Pu?this._convertObjectToList(n.counters):[{Key:E,Value:m}],T=yield this._updateGroupCounters({groupID:I,counterList:M,avChatRoomKey:D,mode:s});return nc.setGroupCounters(I,T),{code:0,data:{counters:T}}}catch(I){hC(g,I)}})}_updateGroupCounters(s){return mA(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,I={};return g.forEach(E=>{const{Key:m,Value:D=0}=E;I[m]=D}),I})}_convertObjectToList(s){return Object.entries(s).map(([n,g])=>({Key:n,Value:g||0}))}},gB=new class{init(s){this._core=s,uT.init(s),_m.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(I=>{const{type:E,groupCounterSeq:m,counterList:D=[]}=I;E!==ti&&E!==on||this._processAndNotifyCounterUpdate(n,m,D),E===fo&&nc.deleteLocalGroupCounters({groupID:n,groupCounterSeq:m,counterList:D})})}_processAndNotifyCounterUpdate(s,n,g){const{OuterEvent:I,notificationCenter:E}=this._core;nc.updateLocalGroupCounters({groupID:s,groupCounterSeq:n,counterList:g}),g.forEach(({Key:m,Value:D=0})=>{E.emitOuterEvent(I.GROUP_COUNTER_UPDATED,{name:I.GROUP_COUNTER_UPDATED,data:{groupID:s,key:m,value:D}})})}reset(){nc.reset()}},Tm=new class{constructor(){this._name="InitGroupAttributes"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"initGroupAttributes",context:this})}initGroupAttributes(s){return mA(this,void 0,void 0,function*(){const{groupID:n,groupAttributes:g}=s,{serverMainSequence:I,avChatRoomKey:E}=zs.getGroupAttributesCache(n),m=zs.convertKeyValueMapToList(g);try{const D=yield function(W,iA){return mA(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:I},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:$y}),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})}})}},ET=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 mA(this,void 0,void 0,function*(){const{groupID:n,groupAttributes:g,richStatusMode:I}=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 mA(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:I},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:Dv}),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 mA(this,void 0,void 0,function*(){const{groupID:n,richStatus:g}=s;return this.setGroupAttributes({groupID:n,groupAttributes:g,richStatusMode:!0})})}},lD=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 mA(this,void 0,void 0,function*(){const n="deleteGroupAttributes",{groupID:g,keyList:I=[],richStatusMode:E}=s;try{let m;m=I.length===0?yield this._clearGroupAttributes(g,{richStatusMode:E}):yield this._deleteGroupAttributes(g,{keyList:I,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 mA(this,void 0,void 0,function*(){return this.deleteGroupAttributes(Object.assign(Object.assign({},s),{richStatusMode:!0}))})}_deleteGroupAttributes(s,n){return mA(this,void 0,void 0,function*(){const{serverMainSequence:g,avChatRoomKey:I,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 mA(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:I,groupAttributeList:T,mainSequence:g,richStatusMode:D},this._core),{AttrMainSeq:W}=P||{};return{resultList:M,serverMainSequence:W,groupAttributeList:T,operation:eD}})}_clearGroupAttributes(s,n){return mA(this,void 0,void 0,function*(){const{serverMainSequence:g,avChatRoomKey:I,values:E}=zs.getGroupAttributesCache(s),{richStatusMode:m}=n||{},D=[...E.keys()],M=yield function(P,W){return mA(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:I,mainSequence:g,richStatusMode:m},this._core),{AttrMainSeq:T}=M||{};return{resultList:D,serverMainSequence:T,operation:AD}})}},ID=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 mA(this,void 0,void 0,function*(){const{groupID:n}=s,{avChatRoomKey:g,lastUpdateTime:I,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()-I>=3e4||E{const{key:iA,value:EA,seq:RA}=W;return{key:iA,value:EA,sequence:RA}});return zs.refreshGroupAttributesCache({groupID:I,serverMainSequence:M,groupAttributeList:P,operation:Sv}),{serverGroupAttributeList:T}})}},NQ=new class{init(s){s.ssoLog.debug("GroupAttribute.init"),Tm.init(s),ET.init(s),lD.init(s),ID.init(s),zs.init(s)}isGroupAttributesUpdated(s){return zs.isGroupAttributesUpdated(s)}handleGroupAttributesUpdated(s){const{to:n,elements:{newGroupProfile:g}}=s,{groupAttributeOption:I}=g,{serverMainSequence:E,withChangedAttributeInfo:m}=I,{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);ID.getGroupAttributesFromServer({groupID:n,avChatRoomKey:T}).then(()=>{zs.emitGroupAttributesUpdated(n)}).catch(()=>{})}}else zs.handleGroupAttributesUpdated({groupID:n,groupAttributeOption:I})}reset(){zs.reset()}};function LE(s,n="tips"){const{ClientSeq:g,From_Account:I,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:re,To_Account:ne}=kA;return{groupCode:xA,groupID:LA,groupName:SA,type:OA,messageFromAccountExtraInformation:JA,from:re,to:ne}}(iA);return{clientSequence:g,from:I,clientTime:E,priority:m,random:D,sequence:M,time:T,tinyID:P,to:W,groupProfile:RA,elements:n==="tips"?Ju(EA):Ih(EA)}}function Ju(s){const n={};return Object.keys(s).forEach(g=>{var I,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=(I=s[g])===null||I===void 0?void 0:I.map(m=>uD(m));break;case"MsgOperatorMemberExtraInfo":n.operatorInfo=uD(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=cT[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 uD(s){const{ImageUrl:n,NickName:g,Role:I,UserId:E}=s;return{avatar:n,nick:g,role:I,userID:E}}function Ih(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=(I=s[g]||[])==null?void 0:I.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 I}),n}class Nm{constructor(n){this.type=Wn.core.OuterConstant.MSG_GRP_TIP,this.content={},this._initContent(n)}static parseServerPushElement(n){const g=Ju(n);return new Nm(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 I=0;I{n.forEach(I=>{g.userID===I.userID&&Object.assign(g,I)})}):this.content.memberList=n}_initNewGroupProfile(n){this.content.newGroupProfile={};const g=Object.keys(n);for(let I=0;I0&&this._handleGroupTipMessage(g),{conversationUpdateFieldList:I,messageList:g}}_emitGroupTipsEvent(s){var n;const{constants:{WORKFLOW_STEP:g}}=this._core,{messageList:I=[]}=((n=s?.result)===null||n===void 0?void 0:n[g.HANDLE_GROUP_TIPS_NOTIFICATION])||{};if(I.length>0){const{notificationCenter:E,OuterEvent:m}=this._core;E.emitOuterEvent(m.MESSAGE_RECEIVED,{name:m.MESSAGE_RECEIVED,data:I})}}_handleGroupTips(s,n=!0){const{Event:g,GroupTips:I}=s,E=new Map,m=[],D=[];for(let M=0,T=I.length;M{const{operationType:I}=g.payload;switch(I){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:I,operatorInfo:E}=s.payload,{groupID:m}=I,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])?Mm(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:I}=this._core,E=Yi.getLocalGroup(s),m=g.getCurrentUserID(),{ownerID:D}=n;m===D&&E.updateGroup({ownerID:D,selfInfo:{role:I.GRP_MBR_ROLE_OWNER}})}_updateSelfRole(s,n){const{OuterConstant:g}=this._core;let I=g.GRP_MBR_ROLE_MEMBER;n===AT?I=g.GRP_MBR_ROLE_OWNER:n===iD&&(I=g.GRP_MBR_ROLE_ADMIN),s.updateSelfInfo({role:I})}_handleGroupMemberCountUpdated(s){const{memberCount:n,groupProfile:{groupID:g}}=s.payload,I=Yi.getLocalGroup(g),{utils:{isNumber:E}}=this._core;I&&E(n)&&I.memberCount!==n&&(I.memberCount=n,Yi.emitGroupListUpdate(),Yi.updateConversationGroupProfile(g))}_handleGroupTipsRecover(s){const{utils:{isArray:n}}=this._core,{groupTipList:g}=s?.result||{};n(g)&&g.forEach(I=>{const{messageList:E}=this._handleGroupTips({Event:I.Event,GroupTips:[I]},!1);this._handleGroupTipMessage(E)})}_handleMemberGrantAdmin(s){const{OuterConstant:n}=this._core,{groupProfile:g,userIDList:I}=s.payload,E=this._core.common.getCurrentUserID(),{groupID:m}=g,D=Yi.getLocalGroup(m);D&&I.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:I}=s.payload,E=this._core.common.getCurrentUserID(),{groupID:m}=g,D=Yi.getLocalGroup(m);D&&I.includes(E)&&(D.updateSelfInfo({role:n.GRP_MBR_ROLE_MEMBER}),Yi.emitGroupListUpdate(),Yi.updateConversationGroupProfile(m))}};class GQ{constructor(n){this.type=Wn.core.OuterConstant.MSG_GRP_SYS_NOTICE,this.content={},this._initContent(n)}static parseServerPushElement(n){const g=Ih(n);return new GQ(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 I=0;I0&&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 I={};for(let E=0;E0?[I]:[],messageList:g}}_assembleMessage(s){const{message:{messageFactory:n},OuterConstant:g,utils:{randomInt:I}}=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 GQ(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=I(),E.random=I(),E.generateMessageID()),E}_handleConversationOptions(s,n){const{OuterConstant:g}=this._core,I={conversationID:g.CONV_SYSTEM,unreadCount:0,type:g.CONV_SYSTEM,subType:s.conversationSubType,lastMessage:null};return n&&I.unreadCount++,I}_handleGroupSysTemMessage(s,n){s&&n.forEach(g=>{const{operationType:I}=g.payload;switch(I){case tT:this._handleGroupJoinResult(g);break;case vv:this._handleMemberKicked(g);break;case iT:this._handleGroupDismissed(g);break;case oT:this._handleGroupInvitedResult(g);break;case oD:this._handleGroupQuitResult(g);break;case MQ:this._handleMessageRemindTypeSynced(g);break;case mm:this._handleAVChatRoomMemberBanned(g)}})}_handleGroupJoinResult(s){const{groupProfile:n}=s.payload,{groupID:g,type:I}=n,E=Yi.hasLocalGroup(g);this._core.ssoLog.debug("_handleGroupJoinResult",` groupID:${g} type:${I} hasLocalGroup:${E}`),E||Qd(I)||(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,I=Yi.hasLocalGroup(g);this._core.ssoLog.debug("_handleGroupInvitedResult",` groupID:${g} hasLocalGroup:${I}`),I||Fl.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,I=Yi.hasLocalGroup(n);this._core.ssoLog.debug("_handleGroupQuitResult",` groupID:${n} type:${g} hasLocalGroup:${I}`),I&&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(Qd(n)){const{appStore:{conversationStore:g},OuterConstant:{CONV_GROUP:I}}=this._core;g.deleteConversation(`${I}${s}`)}Yi.deleteLocalGroup(s),Yi.emitGroupListUpdate()}_updateConversationProfile(s,n){const{appStore:{conversationStore:g},OuterConstant:{CONV_GROUP:I}}=this._core,E=`${I}${s}`;g.getConversation(E)&&g.updateConversation(E,n)}},ED=new class{init(s){this._core=s,s.ssoLog.debug("GroupNotificationHandler.init"),Lv.init(s),Uv.init(s);const{notificationCenter:n,InnerEvent:g}=s,{InnerEventSubType:I}=n;n.subscribeInnerEvent(g.MESSAGE_PUSH,I.GROUP_TIPS_NOTIFICATION,this._onNewGroupTipsNotification,this),n.subscribeInnerEvent(g.MESSAGE_PUSH,I.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){Uv.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},bQ={required:!0,rules:["number"],allowEmpty:!1},yd={required:!0,rules:["array"],allowEmpty:!1},dD={required:!0,rules:["object"],allowEmpty:!1},dT={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:yd,memberCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},addGroupMember:{groupID:vn,userIDList:yd},deleteGroupMember:{groupID:vn,userIDList:yd},setGroupMemberMuteTime:{groupID:vn,userID:vn,muteTime:Object.assign(Object.assign({},bQ),{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:yd},markGroupMemberList:{groupID:vn,markType:Object.assign(Object.assign({},bQ),{customValidator:s=>!(s<1e3)||"markType must be greater than or equal to 1000."}),enableMark:{required:!0,rules:["boolean"],allowEmpty:!1},userIDList:yd},initGroupAttributes:{groupID:vn,groupAttributes:dD},setGroupAttributes:{groupID:vn,groupAttributes:dD},deleteGroupAttributes:{groupID:vn,keyList:Object.assign(Object.assign({},yd),{allowEmpty:!0})},getGroupAttributes:{groupID:vn,keyList:Object.assign(Object.assign({},yd),{allowEmpty:!0})},getGroupCounters:{groupID:vn,keyList:{required:!1,rules:["array"],allowEmpty:!0}},setGroupCounters:{groupID:vn,counters:dD},increaseGroupCounter:{groupID:vn,key:vn,value:bQ},decreaseGroupCounter:{groupID:vn,key:vn,value:bQ}},CT={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 hT=new class{constructor(){this._installedSubPlugins=[],this.groupDataHandler=Yi,this.groupAction=wQ,this.groupAttribute=NQ,this.groupMember=kv,this.groupCounter=gB,this.name="Group"}install(s,n=[]){this._core=s,Wn.init(s),Yi.init(s),wQ.init(s,this),kv.init(s,this),aD.init(s),gB.init(s),NQ.init(s),ED.init(s),s.helper.registerValidateConfig({auth:CT,params:dT}),this._installSubPlugins(n);const{notificationCenter:g,InnerEvent:I}=s;g.subscribeInnerEvent(I.LOGOUT,this._reset,this),g.subscribeInnerEvent(I.DESTROY,this._dispose,this)}getInstalledSubPlugins(){return this._installedSubPlugins}_installSubPlugins(s){const{utils:{isArray:n}}=this._core;s&&n(s)&&s.forEach(g=>{var I;this._installedSubPlugins.includes(g.name)||((I=g.install)===null||I===void 0||I.call(g,this._core,this),this._installedSubPlugins.push(g.name))})}_reset(){Yi.reset(),NQ.reset(),gB.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 cB=new class{init(s){this.core=s}},Fv="AV_MBR_LIST",BT="AV_BAN_MBR",UE={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},uh={GROUP_DISMISSED:5,QUIT_GROUP:8,AVCHATROOM_MEMBER_BANNED:21},CD=60,hD=2603,QT=2686,pT=2688,kQ=3122;class Ov{constructor(n){const{core:g,manager:I,groupID:E,getRequestParams:m,onSuccess:D,onFail:M}=n;this._name="Polling",this._core=g,this._manager=I,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 mA(this,void 0,void 0,function*(){try{const n=this._getRequestParams(this._groupID),g=yield function(E,m){return mA(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 I=this._manager.getCurrentPollingInterval(this._groupID);this._runNextPolling(I)}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 Eh{constructor(n){this._maxLength=n,this._map=new Map}set(n){var g;if(this._map.size>=this._maxLength){const I=((g=this._map.entries().next().value)===null||g===void 0?void 0:g[0])||"";this._map.delete(I)}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 Hu=s=>s===UE.GROUP_TIPS_HAS_NO_ROAMING||s===UE.GROUP_TIPS_HAS_ROAMING,LQ=s=>s===UE.GROUP_SYSTEM_MESSAGE;function Gm(s){const n=function(g){const{E:I,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=yo(g,["E","MCT","MR","MP","MTS","GId","MS","CCD","F_Account","IsSys","GInf","MsgBody"]);return Object.assign({Event:I,MsgClientTime:E,MsgRandom:m,MsgPriority:D,MsgTimeStamp:M,ToGroupId:T,MsgSeq:P,CloudCustomData:W,From_Account:iA,IsSystemMsg:EA,GroupInfo:BD(RA),MsgBody:mT(kA)},xA)}(s);return function(g){const{Event:I}=g;(Hu(I)||LQ(I))&&(g.From_Account=g.From_Account||"@TIM#SYSTEM"),E=I,(E===UE.BROADCAST_MESSAGE||(m=>m===UE.NORMAL_MESSAGE)(I))&&function(m){const{core:{OuterConstant:D}}=cB;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;Hu(I)&&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),LQ(I)&&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 BD(s){const n=s||{},{GN:g,GT:I,F_Hd:E,F_NN:m,F_Ll:D}=n,M=yo(n,["GN","GT","F_Hd","F_NN","F_Ll"]),T=Object.assign({GroupName:g,GroupType:I},M);return E&&(T.From_AccountHeadurl=E),m&&(T.From_AccountNick=m),D&&(T.From_AccountLevel=D),T}function mT(s){let n=s;Array.isArray(s)||(n=[s]);const g=n.map(I=>{const{O_Account:E,Opt:m,L_Account:D,RT:M,UDF:T,OpInf:P,OnlineInf:W,MsgMemberExtraInfo:iA}=I,EA=yo(I,["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=yo(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=yo(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 dh=new class{constructor(){this._name="MessageParser",this._sequenceList=new Eh(200),this._messageIDList=new Eh(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 I=this._handleMessageList(s,n);if(I.length===0)return;if(!g){const{appStore:{conversationStore:T},OuterConstant:{CONV_GROUP:P},common:{buildLastMessage:W}}=this._core,iA=W(I[I.length-1]);T.updateConversation(`${P}${s}`,{lastMessage:iA})}this._checkMessageStacked(I);const E=I.filter(T=>T.isModified===!0),m=I.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:I}=s;let E=[];this._avChatRoomHandler.isPollingSimplifiedMessage()&&!I?(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:I,messageHelper:E}}=this._core,m=this._avChatRoomHandler.isPollingSimplifiedMessage(),D=[],M=n.length;for(let T=0;Tg===UE.MESSAGE_REVOKED)(n)?(this._handleMessageRevoked(s),null):(g=>g===UE.LIVE_CUSTOM_DATA)(n)?(this._onLiveCustomData(s),null):(g=>g===UE.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 I=g.CONV_GROUP;s.elements.type===g.MSG_GRP_SYS_NOTICE&&(I=g.CONV_SYSTEM);const E=!!s.isSystemMessage,m=n.createMessage(Object.assign(Object.assign({},s),{conversationType:I,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:I,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}${I}`,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:I,MsgTimeStamp:E,MsgBody:m}=s,D=m?.Content||m?.MsgContent||"";this._emitEvent({name:n,data:D}),console.log(`${this._name}._onLiveCustomData groupID:${g} sequence:${I} 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,I=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:I}}=s;if(n(I))return;const{OnlineMemberNum:E=0,ExpireTime:m=CD}=I,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 lB=s=>{const{core:{store:n}}=cB;return(n.get("cloudConfig")||{})[s]},Ch=s=>{const{core:{utils:{isUndefined:n}}}=cB;return!n(s)},UQ=()=>{const s=lB("polling_interval");return Ch(s)?parseInt(s,10):300},IB=()=>{const s=lB("polling_simplified_msg");return Ch(s)?parseInt(s,10):0};var Pv=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 mA(this,void 0,void 0,function*(){const{appStore:{groupStore:n},OuterConstant:g}=this._core,I=n.getGroup(s);return I?I.type===g.GRP_AVCHATROOM?this._getOnlineMemberCount(s):this._parentPlugin.groupAction.getGroupOnlineMemberCount(s):{code:0,data:{memberCount:0}}})}_getOnlineMemberCount(s){return mA(this,void 0,void 0,function*(){const n="_getOnlineMemberCount",{utils:{isEmpty:g}}=this._core,I=Pg.getLocalOnlineMemberCount(s);if(g(I)||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:${I.memberCount} from local.`),{code:0,data:{memberCount:I.memberCount}}})}_isExpired(s){const n=Pg.getLocalOnlineMemberCount(s),g=Date.now(),I=g-n.lastSyncTime>1e3*n.expireTime,E=g-n.latestUpdateTime>1e4,m=g-n.lastReqTime>3e3;return I&&E&&m}_getOnlineMemberCountFromServer(s){return mA(this,void 0,void 0,function*(){const n="_getOnlineMemberCountFromServer";try{const g=yield function(M,T){return mA(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:I=0,ExpireTime:E=CD}=g||{},m=Date.now(),D={lastSyncTime:m,latestUpdateTime:m,lastReqTime:m,memberCount:I,expireTime:E};return Pg.updateLocalOnlineMemberCount(s,D),{memberCount:I}}catch(g){const I=new this._core.helper.ChatError({functionName:n,code:g?.errorCode,message:g?.errorInfo});throw console.error(`${this._name}.${n} fail:`,I),I}})}},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,dh.init(s,this),s.ssoLog.debug("AVChatRoomHandler.init")}onAVChatRoomSystemNotification(s){const{OuterConstant:{GRP_AVCHATROOM:n}}=this._core,{GroupTips:g=[]}=s;for(let I=0;I0&&(n=[...this._joinedGroupMap.values()].filter(g=>g.type===s)),n}handleJoinGroupResult(s){return mA(this,void 0,void 0,function*(){const{utils:{isUndefined:n},OuterConstant:{CONV_GROUP:g},apiMap:{getConversationProfile:I},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(),I(`${g}${T}`),Pv.getGroupOnlineMemberCount(T),M.length>0&&dh.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 mA(this,void 0,void 0,function*(){const{common:n,OuterConstant:g,helper:I,apiMap:{quitGroup:E},ssoLog:m}=this._core;if(n.isUnlimitedAVChatRoom()){if(this._pollingInstanceMap.size>(()=>{const T=lB("polling_count_limit");return Ch(T)&&T>0?parseInt(T,10):20})())throw new I.ChatError({code:pT,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:I=1,group:E}=s,{groupID:m}=E;return this._pollingRequestInfoMap.set(m,{longPollingKey:g,startSequence:I}),this._pollingIntervalMap.set(m,UQ()),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 Ov({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:IB()}:{longPollingKey:n,startSequence:g,simplifiedMessage:IB()}}_handleSuccess(s,n){const{ErrorCode:g}=n;if(g!==0){const{longPollingKey:I,startSequence:E}=this._pollingRequestInfoMap.get(s)||{};return void console.warn(`${this._name}._handleSuccess groupID:${s} key:${I} startSeq:${E} errorCode:${g}`)}this._hasJoinedAVChatRoom(s)&&this._handleResponseData(s,n)}_handleResponseData(s,n){const{Key:g,NextSeq:I,NextBroadcastSeq:E,RspMsgList:m=[],RspBroadcastMsgList:D=[]}=n;if(g&&I&&this._pollingRequestInfoMap.set(s,{longPollingKey:g,startSequence:I}),E&&E>this._startBroadcastSequence&&(this._startBroadcastSequence=E),m.length>0)this._getPollingNoMessageCount(s)!==0&&(this._updatePollingNoMessageCount(s,0),this._pollingIntervalMap.set(s,UQ())),dh.onMessageReceived(s,m);else{let M=this._getPollingNoMessageCount(s);if(M+=1,this._updatePollingNoMessageCount(s,M),M===(()=>{const T=lB("polling_no_msg_count");return Ch(T)?parseInt(T,10):20})()){const T=UQ()+(()=>{const P=lB("polling_interval_plus");return Ch(P)?parseInt(P,10):2e3})();this._pollingIntervalMap.set(s,T)}}D.length>0&&dh.onBroadcastMessageReceived(D)}_handleFailure(s,n){const{ssoLog:g,utils:{safeStringify:I}}=this._core;g.warn("polling",`${this._name}._handleFailure groupID:${s} error: ${I(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){dh.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:I,count:E}=(()=>{const m=lB("av_members_freq_limit");if(Ch(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*I?(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 I=this._pollingInstanceMap.get(s);return I?.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:I}=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)}),I.info("longPollingCount",String(s),{moreMessage:`av:${m.join(",")} live:${D.join(",")} code: ${E}`,eventType:29})}}reset(s){this._stopPolling(s),this._startBroadcastSequence=1,dh.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 mA(this,void 0,void 0,function*(){const{OuterConstant:n}=this._core,g=yield this._parentPlugin.groupAction.joinGroup(s),{data:{status:I,group:{type:E}}}=g;return E===n.GRP_AVCHATROOM?I===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 mA(this,void 0,void 0,function*(){const{OuterConstant:n}=this._core,g=yield this._parentPlugin.groupAction.quitGroup(s),{data:{type:I}}=g;return I===n.GRP_AVCHATROOM&&Pg.reset(s),g})}},Yv=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 mA(this,void 0,void 0,function*(){const{OuterConstant:n}=this._core,g=yield this._parentPlugin.groupAction.dismissGroup(s),{data:{type:I}}=g;return I===n.GRP_AVCHATROOM&&Pg.reset(s),g})}},bm=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 mA(this,void 0,void 0,function*(){const{appStore:{groupStore:n},helper:g,OuterConstant:I}=this._core,{groupID:E}=s,m=n.getGroup(E);if(m?.type===I.GRP_AVCHATROOM&&g.checkBusinessCapabilityBits(Fv)){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 mA(this,void 0,void 0,function*(){const n="_getGroupMemberList",{helper:g}=this._core;try{const I=yield function(M,T){return mA(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}=I||{},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(I){const E=new g.ChatError({functionName:n,code:I?.errorCode,message:I?.errorInfo});throw console.error(`${this._name}.${n} fail:`,E),E}})}_handleMemberList(s){return s.map(n=>{const{Member_Account:g,NickName:I="",Avatar:E="",Remark:m="",JoinTime:D=0,Marks:M=[]}=n;return{userID:g,nick:I,avatar:E,remark:m,joinTime:D,marks:M,isOnline:!0}})}},km=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 mA(this,void 0,void 0,function*(){const n="deleteGroupMember",{appStore:{groupStore:g},utils:{isUndefined:I},helper:E,OuterConstant:m}=this._core,{groupID:D}=s,M=g.getGroup(D);if(I(M))throw new E.ChatError({functionName:n,code:hD});if(M.type===m.GRP_AVCHATROOM){if(E.checkBusinessCapabilityBits(BT))return this._deleteGroupMember(s);throw new E.ChatError({functionName:n,code:kQ})}return this._parentPlugin.groupMember.deleteGroupMember(s)})}_deleteGroupMember(s){return mA(this,void 0,void 0,function*(){const n="_deleteGroupMember",{appStore:{groupStore:g},helper:I,ssoLog:E}=this._core,{groupID:m,duration:D=0,userIDList:M}=s;if(D===0)throw new I.ChatError({functionName:n,code:QT});try{return yield function(T,P){return mA(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 I.ChatError({functionName:n,code:T?.errorCode,message:T?.errorInfo})}})}},Dd=new class{constructor(){this._name="MarkAVChatRoomMember"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"markGroupMemberList",context:this})}markGroupMemberList(s){return mA(this,void 0,void 0,function*(){const n="markGroupMemberList",{groupID:g,markType:I,enableMark:E,userIDList:m=[]}=s,D=this._generateRequestData(s);try{const M=yield function(iA,EA){return mA(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:${I} 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:I,userIDList:E=[]}=s,m=I===!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=[],I=[];return s.length===n.length?(g.push(...n),{successUserIDList:g,failureUserIDList:I}):(n.forEach(E=>{s.find(m=>m.Member_Account===E)?g.push(E):I.push(E)}),{successUserIDList:g,failureUserIDList:I})}},Vv=new class{init(s,n){s.ssoLog.debug("AVChatRoomAction.init"),xv.init(s,n),fT.init(s,n),Yv.init(s,n),bm.init(s,n),Pv.init(s,n),km.init(s,n),Dd.init(s)}},Jv=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:I,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:I.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 mA(this,void 0,void 0,function*(){const{ssoLog:n}=this._core,{groupID:g}=s;try{const I=yield function(m,D){return mA(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=[]}=I||{};n.debug("_getLiveHistoryMessages",`${this._name}._getLiveHistoryMessages ok, groupID:${g} count:${E.length}`),E.length>0&&Pg.handleLiveHistoryMessages(g,E)}catch(I){n.debug("_getLiveHistoryMessages",`${this._name}._getLiveHistoryMessages failed, groupID:${g} info:${I.message}`)}})}},Lm=new class{constructor(){this.name="AVChatRoom"}install(s,n){this._core=s,cB.init(s),Pg.init(s,n),Vv.init(s,n),Jv.init(s);const{notificationCenter:g,InnerEvent:I}=s,{InnerEventSubType:E}=g;g.subscribeInnerEvent(I.MESSAGE_PUSH,E.GROUP_SYSTEM_NOTIFICATION,this._onAVChatRoomSystemNotification,this),g.subscribeInnerEvent(I.LOGOUT,this._reset,this),g.subscribeInnerEvent(I.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 $a=new class{init(s){this.core=s}},Um="message",uB="user",EB={OR:"or",AND:"and"},yI=20,yT=20,Hv=20,hh={required:!1,rules:["array"],allowEmpty:!0,customValidator:s=>!s||!!(Array.isArray(s)&&s.length<=5)||"keywordList should be an array and length <= 5"},Fm={required:!1,rules:["string"],allowEmpty:!0,customValidator:s=>!s||!![EB.OR,EB.AND].includes(s)||"keywordListMatchType should be OR or AND"},QC={required:!1,rules:["number"],allowEmpty:!0,customValidator:s=>typeof s=="number"&&s>=1&&s<=100||"count must be a number between 1 and 100"},FQ={required:!1,rules:["string"],allowEmpty:!0},qv={required:!1,rules:["array"],allowEmpty:!0,customValidator:s=>{const{OuterConstant:n}=$a.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 I=!1;for(let E=0;E{const{OuterConstant:n}=$a.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 I=!1;for(let E=0;E{const{OuterConstant:n}=$a.core;return!(!s?.startsWith(n.CONV_C2C)&&!s?.startsWith(n.CONV_GROUP)&&s!==n.CONV_SYSTEM)||"conversationID is invalid"}},Om=s=>({required:!1,rules:["number"],allowEmpty:!0,customValidator:n=>typeof n=="number"&&n>=0||`${s} should be a number >= 0';`}),QD={required:!1,rules:["string"],allowEmpty:!0,customValidator:s=>{const{OuterConstant:n}=$a.core;return!![n.GENDER_FEMALE,n.GENDER_MALE].includes(s)||"gender is invalid"}},Pm={searchCloudMessages:{keywordList:hh,keywordListMatchType:Fm,cursor:FQ,senderUserIDList:{required:!1,rules:["array"],allowEmpty:!0,customValidator:s=>!!(Array.isArray(s)&&s.length<=5)||"senderUserIDList should be an array and length <= 5"},messageTypeList:Kv,conversationID:jv,timePosition:Om("timePosition"),timePeriod:Om("timePeriod")},searchCloudUsers:{keywordList:hh,keywordListMatchType:Fm,cursor:FQ,count:QC,miniBirthday:Om("miniBirthday"),maxBirthday:Om("maxBirthday"),gender:QD},searchCloudGroupMembers:{keywordList:hh,keywordListMatchType:Fm,cursor:FQ,count:QC,groupTypeList:qv,groupIDList:{required:!1,rules:["array"],allowEmpty:!0}},searchCloudGroups:{keywordList:hh,keywordListMatchType:Fm,cursor:FQ,count:QC,groupTypeList:qv}},pD={searchCloudMessages:!0,searchCloudUsers:!0,searchCloudGroupMembers:!0,searchCloudGroups:!0};var mD=new class{constructor(){this.name="CloudSearch"}install(s){this._core=s,$a.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:pD,params:Pm})}searchCloudMessages(s){return mA(this,void 0,void 0,function*(){try{const{OuterConstant:n,helper:g}=this._core,{conversationID:I,timePeriod:E,timePosition:m}=s,D=yo(s,["conversationID","timePeriod","timePosition"]),M=Object.assign({count:100},D);I&&(I.startsWith(n.CONV_C2C)?M.account=I.replace(n.CONV_C2C,""):I.startsWith(n.CONV_GROUP)&&(M.groupID=I.replace(n.CONV_GROUP,""))),this._setTimeRangeParams(M,{timePeriod:E,timePosition:m});const T=yield function(LA){return mA(this,void 0,void 0,function*(){const{count:SA,keywordList:OA,keywordListMatchType:JA,senderUserIDList:re,messageTypeList:ne,endTime:_i,startTime:Ti,cursor:kt,account:Ni,groupID:cs}=LA,Se={Count:SA,KeywordList:OA,MatchType:JA,SendUserIDList:re,MsgTypeList:ne,EndTime:_i,StartTime:Ti,Cursor:kt,PeerAccount:Ni,GroupID:cs};return $a.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:re}=LA,ne=JA?`${n.CONV_GROUP}${JA}`:`${n.CONV_C2C}${re}`;if(this._isSearchingAllConversations(s)&&OA>1)return{conversationID:ne,messageCount:OA,messageList:[]};const _i=SA.map(Ti=>g.isEmpty(JA)?function(kt,Ni){const cs=Ni.OuterConstant.CONV_C2C,Se=Ni.message.messageHelper.parseServerPushMessage(kt),Bt=Ni.message.messageFactory.createMessage(Object.assign(Object.assign({},Se),{conversationType:cs,flow:"in"}));return Bt.setElement(Se.elements),Bt}(Ti,this._core):function(kt,Ni){const cs=Ni.OuterConstant.CONV_GROUP,Se=Ni.message.messageHelper.parseServerGroupMessage(kt),Bt=Ni.message.messageFactory.createMessage(Object.assign(Object.assign({},Se),{conversationType:cs,flow:"in"}));return Bt.setElement(Se.elements),Bt}(Ti,this._core));return{conversationID:ne,messageCount:OA,messageList:_i}}),cursor:EA,totalCount:iA},successLog:{message:kA}}}catch(n){const{errorCode:g,errorInfo:I}=n||{};this._handleError({errorCode:g,errorInfo:I,searchType:Um,functionName:"searchCloudMessages"})}})}searchCloudUsers(s){return mA(this,void 0,void 0,function*(){var n;try{const{keywordListMatchType:g,count:I=yT}=s,E=yo(s,["keywordListMatchType","count"]),m=Object.assign({count:I,keywordListMatchType:g===EB.AND?1:0},E);this._setBirthdayRangeParams(m,s);const D=yield function(kA){return mA(this,void 0,void 0,function*(){const{count:xA,keywordList:LA,keywordListMatchType:SA,miniBirthday:OA,maxBirthday:JA,cursor:re,gender:ne}=kA,_i={Count:xA,Keywords:LA,KeywordMatchType:SA,Cursor:re,UserBirthStart:OA,UserBirthEnd:JA,Gender:ne};return $a.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:re.Tag,value:re.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:I,errorInfo:E}=g||{};this._handleError({errorCode:I,errorInfo:E,searchType:uB,functionName:"searchCloudUsers"})}})}searchCloudGroupMembers(s){return mA(this,void 0,void 0,function*(){try{const{count:n=Hv,keywordListMatchType:g}=s,I=yo(s,["count","keywordListMatchType"]),E=Object.assign({count:n,keywordListMatchType:g===EB.AND?1:0},I),m=yield function(RA){return mA(this,void 0,void 0,function*(){const{count:kA,keywordList:xA,keywordListMatchType:LA,groupTypeList:SA,cursor:OA,groupIDList:JA}=RA,re={Count:kA,Keywords:xA,KeywordMatchType:LA,Cursor:OA,GroupType:SA,GroupIdList:JA};return $a.core.common.buildAndSendPacket({servcmd:"group_member_search.query",data:re})})}(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:re,GroupMemberAvatar:ne=""}=RA,_i={groupID:kA,name:xA,type:LA,avatar:SA},Ti={userID:JA,nick:OA,nameCard:re,avatar:ne};if(EA.has(kA)){const kt=EA.get(kA);kt.memberList.push(Ti),EA.set(kA,kt)}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:I}=n||{};this._handleError({errorCode:g,errorInfo:I,searchType:uB,functionName:"searchCloudGroupMembers"})}})}searchCloudGroups(s){return mA(this,void 0,void 0,function*(){try{const{count:n=yI,keywordListMatchType:g}=s,I=yo(s,["count","keywordListMatchType"]),E=Object.assign({count:n,keywordListMatchType:g===EB.AND?1:0},I),m=yield function(EA){return mA(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 $a.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:re,GroupOwnerUserName:ne,GroupType:_i,GroupAddOption:Ti,GroupInviteOption:kt}=RA;return{avatar:kA,groupID:xA,introduction:LA,memberCount:SA,name:OA,ownerTinyID:JA,ownerID:re,ownerNick:ne,type:_i,joinOption:Ti,inviteOption:kt}}(EA))||[],cursor:P,totalCount:W},successLog:{message:iA}}}catch(n){const{errorCode:g,errorInfo:I}=n||{};this._handleError({errorCode:g,errorInfo:I,searchType:uB,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:I}=this._core;let E=s;throw s===60020?E="SearchUnable":g!==Um&&s===27003?E="SearchParamsError":g!==Um&&s===60018&&(E="SearchOverLimit"),new I.ChatError({code:E,message:n})}_isSearchingAllConversations(s){return this._core.helper.isEmpty(s.conversationID)}_setBirthdayRangeParams(s,n){const{miniBirthday:g,maxBirthday:I}=n;g!==void 0&&(s.miniBirthday=g,I===void 0&&(s.maxBirthday=4294967295)),I!==void 0&&(s.maxBirthday=I)}};function Bh(s,n){return Math.round(Number(s)*Math.pow(10,n))/Math.pow(10,n)}const Wv="qualityStat",fD="im-ssolog-quality-stat";var yD;(function(s){s[s.ONLINE=8]="ONLINE"})(yD||(yD={}));const xm="networkRTT",Qh="messageE2EDelay",dB="sendMessageC2C",ph="sendMessageGroup",mh="sendMessageGroupAV",CB="sendMessageRichMedia",hB="cosUpload",pC="messageReceivedGroup",OQ="messageReceivedGroupAVPush",PQ="messageReceivedGroupAVPull",DT={[xm]:2,[Qh]:3,[dB]:4,[ph]:5,[mh]:6,[CB]:7,[pC]:8,[OQ]:9,[PQ]:10,[hB]:11},zv=[dB,ph,mh,CB,hB],fh=[pC,OQ,PQ],BB=[xm,Qh,dB,ph,mh,CB,hB,pC,OQ,PQ],DD={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},Ym="quality_stat";var xQ=new class{constructor(){this._messageStatsMap=new Map,this._userSideErrorCodes=new Set(Object.values(DD))}init(s){this._core=s,Object.values(zv).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:I,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,I);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:I,failedCountOfUserSide:E}=n,m=Bh(I/g*100,2),D=I+E,M=Bh(D/g*100,2),T=this._calcAverageValue(n,s);return this._resetStat(s),{total_count:g,success_count_business:I,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 I=(g=n?.code)!==null&&g!==void 0?g:n?.errorCode;if(this._isUserSideError(I)){const E=this._getSendMessageSpecifiedKey(s),m=E&&this._messageStatsMap.get(E);m&&m.failedCountOfUserSide++}}_handleSendCost(s,n){const g=this._getSendMessageSpecifiedKey(s),I=g&&this._messageStatsMap.get(g);I&&(I.costSum+=Date.now()-n,I.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:I,MSG_FILE:E,CONV_C2C:m,CONV_GROUP:D,GRP_AVCHATROOM:M}=this._core.OuterConstant;if([n,g,I,E].includes(s.type))return CB;if(s.conversationType===m)return dB;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?mh:ph}}_calcAverageValue(s,n){return s.costCount===0?0:Math.round(n===hB?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)}},YQ=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:I},ssoLog:E}=this._core;if(g(n)||!this._currentCycleStats.has(n))return void E.debug("addMessageSequence",`${Wv}.addMessageSequence invalid key:${n}`);const{conversationID:m,sequence:D}=s,M=m.replace(I,""),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&&(I+=m.length,g+=M-D+1)}),g===0?null:(this._transferCycleDataOptimized(s),{total_count:g,success_count_business:I,percent_business:Bh(I/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(fh).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((I,E)=>{const m=I.dirty?[...I.sortedSequences].sort((D,M)=>D-M):I.sortedSequences;g.set(E,{sortedSequences:m,minSeq:I.minSeq,maxSeq:I.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:I}=this._core.appStore,E=I.getGroup(s.to);if(!E)return null;const{type:m}=E;return m===g?PQ:pC}}_insertToLastCycle(s,n){n.dirty&&(n.sortedSequences.sort((I,E)=>I-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,I=s.length-1;for(;g<=I;){const E=Math.floor((g+I)/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:I}}=this._core,E=[g,I];n.forEach(m=>{!E.includes(m.type)&&m.clientTime>0&&this.addMessageDelay(m.clientTime)})}_calculateAverageDelay(s){return s===0?0:Bh(this._totalDelay/s,1)}_calculatePercentage(s,n){return Bh(s/n*100,2)}},Zv=new class{init(s){this.core=s}},ST=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:I,LOGOUT:E,DESTROY:m},constants:{WORKFLOW_NAME:D,WORKFLOW_STEP:M}}=s;Zv.init(s),xQ.init(s),YQ.init(s),VQ.init(s),n.registerWorkflowStep(D.SYNC_SERVER_INFO_AFTER_LOGIN,M.QUALITY_REPORT,this.handleLoginSuccess,this),g.subscribeInnerEvent(I,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,I=s.get("cloudConfig")||{},{q_rpt_interval:E}=I,m=g(E)?12e4:Number(E);n.taskScheduler.addTask({id:Ym,intervalMs:m,callback:this.report,context:this})}report(){this._wholePeriod=!0;const s=[...BB.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:I}=s;g===n.MESSAGE_SEND_SUCCESS_RATE&&xQ.dispatchSendStats(I)}_needSkipReport(){return this._isSDKAppIDInBlacklist()&&!this._isTinyIDInWhitelist()}_isSDKAppIDInBlacklist(){const{store:s,utils:n}=this._core,g=s.get("cloudConfig")||{},I=s.get("instance")||{},{sdkAppId:E}=I,{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")||{},I=s.get("login")||{},E=Number(I.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:DT[s],timestamp:Date.now(),network_type:yD.ONLINE,extension:""};return Object.assign(Object.assign({},g),n)}_getStatResultByKey(s){switch(s){case Qh:return VQ.getStatResult();case dB:case ph:case mh:case CB:case hB:return xQ.getStatResult(s);case pC:case OQ:case PQ:return YQ.getStatResult(s);default:return null}}_uploadQualityReports(s){return mA(this,void 0,void 0,function*(){try{const n={header:this._core.common.getCommonHead(),quality:s};yield function(g){const{common:I,channel:E}=Zv.core,m="imopenstat.tim_web_report_v2",D=I.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=`${Wv}._cacheFailedLogs`;let g=[...this._failedLogsCache.get(fD)||[],...s];g.length>10&&(g=g.slice(g.length-10),console.log(`${n} logs overflow, keeping last 10 items`)),this._failedLogsCache.set(fD,g),console.log(`${n} count: ${g.length}`),this._pendingReports=[]}_reset(){const{helper:s}=this._core;s.taskScheduler.removeTask(Ym)}_dispose(){const{notificationCenter:s,InnerEvent:{QUALITY_STAT:n,LOGOUT:g,DESTROY:I}}=this._core;s.unSubscribeInnerEvent(n,this._handleQualityStat,this),s.unSubscribeInnerEvent(g,this._reset,this),s.unSubscribeInnerEvent(I,this._dispose,this),this._reset(),VQ.dispose(),YQ.dispose()}};const cl=new class{init(s){this.core=s}};function Xv(s){return mA(this,void 0,void 0,function*(){var n;const{message:g,user:I,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 I.userProfile.getMyProfile())||{};if(M){const{avatar:T,nick:P}=M;g.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:s,latestAvatar:T,latestNick:P,isSentByMe:!0})}})}function $v(s){return mA(this,void 0,void 0,function*(){const n=s.map(g=>g.revoker);try{const g=yield function(I){return mA(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:I});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(I=>{const{revoker:E}=I;g[E]&&(I.revokerInfo.nick=g[E].nick||"",I.revokerInfo.avatar=g[E].avatar||"",I.revokerInfo.userID=E)})}catch(g){console.debug(g)}})}const SD=1,AR=2,yh=20,JQ=2500,eR=1,Dh=300;function HQ(s){return mA(this,void 0,void 0,function*(){var n,g;const{appStore:I,utils:{isEmpty:E},common:{getCurrentUserID:m},notificationCenter:D,OuterEvent:M,OuterConstant:{CONV_C2C:T}}=cl.core,{messageList:P,conversationID:W}=s,iA=I.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 mA(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,I.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 tR=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 mA(this,void 0,void 0,function*(){try{const{message:n,OuterConstant:{Direction:g,CONV_C2C:I,CONV_GROUP:E},InnerEvent:{HISTORY_MESSAGE_FETCHED:m},notificationCenter:D}=this._core,{conversationID:M,nextReqMessageID:T}=s,P=yh;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(I)&&(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(re){const{appStore:ne,message:_i,OuterConstant:Ti}=cl.core,kt=ne.conversationStore.getConversation(re),Ni=_i.messageDataHandler.getLocalMessageList(re);if(!kt||Ni.length===0||re===Ti.CONV_SYSTEM)return;const cs=[];for(let Bt=0;BtUA.isRevoked).length;Se=cs.length-kt.unreadCount-Bt}else Se=cs.length-kt.unreadCount;for(let Bt=0;Btre.isRevoked);yield $v(SA),D.emitInnerEvent(m,xA);const OA={nextReqMessageID:RA?"":String(EA),messageList:LA,isCompleted:RA},JA=LA.map(re=>re.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:I}=n||{};throw new this._core.helper.ChatError({code:g,message:I,moreMessage:`options: ${this._core.utils.safeStringify(s)}`})}})}getMessageListHopping(s){return mA(this,void 0,void 0,function*(){var n,g;const{OuterConstant:{Direction:I,CONV_C2C:E,CONV_GROUP:m},utils:{safeStringify:D}}=this._core,{conversationID:M,sequence:T,time:P,direction:W=I.FORWARD}=s,{utils:{isEmpty:iA},message:EA,notificationCenter:RA,InnerEvent:{HISTORY_MESSAGE_FETCHED:kA}}=this._core;if(![I.BACKWARD,I.FORWARD].includes(W))throw new this._core.helper.ChatError({message:"direction must be 0 or 1",moreMessage:`options: ${D(s)}`});let{count:xA=yh}=s;xA=xA>yh?yh: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:re}=LA;if(this._core.message.messageDataHandler.storeSparseMessageList(JA),RA.emitInnerEvent(kA,JA),W===I.FORWARD){const ne=OA&&SA<1;return{code:0,data:{messageList:JA,isCompleted:ne,nextMessageSeq:ne?"":SA}}}if(W===I.BACKWARD){if(iA(JA)&&iA(re))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};const ne=((n=JA?.[JA.length-1])===null||n===void 0?void 0:n.sequence)||0,_i=((g=re?.[re.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(ne,_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===I.FORWARD?SA.shift():SA.pop()),EA.messageDataHandler.storeSparseMessageList(SA),yield HQ({messageList:SA,conversationID:M}),{code:0,data:{messageList:SA,isCompleted:JA,nextMessageTime:JA?"":OA}}}})}clearHistoryMessage(s){return mA(this,void 0,void 0,function*(){var n;const{appStore:g,common:{ChatError:I,getCurrentUserID:E},OuterConstant:{CONV_C2C:m,CONV_GROUP:D},apiMap:M,message:T}=this._core,P=g.conversationStore.getConversation(s);if(!P)throw new I({code:JQ});const W={fromAccount:E()},{type:iA}=P;iA===m?(W.type=SD,W.toAccount=s.replace(m,"")):iA===D&&(W.type=AR,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 mA(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:I}}=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(I)&&(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:I}=this._core;return nn.startsWith(E)?EA.ID===g:String(EA.sequence)===g),W=iA>I?iA-I:0,T=iA):W=M>I?M-I:0,P.messageList=D.slice(W,iA),P.isCompleted=T<=I&&m.messageHistory.completedHistoryConversations.has(n),P.isCompleted?P.nextReqMessageID="":P.nextReqMessageID=this._generateNextReqMessageID({conversationID:n,targetIndex:W}),n.startsWith(E)&&(yield Xv(n),yield HQ({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}}},QB=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:I,InnerEvent:E}}=s;n.registerWorkflowStep(g.SYNC_SERVER_INFO_AFTER_RE_ONLINE,I.HISTORY_MESSAGE_RECOVER,this._syncGroupOfflineMessage,this),n.registerWorkflowStep(g.SYNC_SERVER_INFO_AFTER_RE_ONLINE,I.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:I}}=this._core;if(I(n)){const E=n.filter(m=>m.type===g.CONV_GROUP&&m.groupProfile.type!==g.GRP_AVCHATROOM);return this._recoverGroupHistoryMessage(E)}}_recoverGroupHistoryMessage(s){return mA(this,void 0,void 0,function*(){const{OuterConstant:n}=this._core,g=[],I=[];return yield Promise.all(s?.map(E=>mA(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:I})),g.push(M.replace(n.CONV_GROUP,""))}))),{recoverRevokeNoticeGroupIDList:g,groupTipList:I}})}_recoverGroupHistoryForConversation(s){return mA(this,arguments,void 0,function*({conversationID:n,localLastMessageSequence:g,serverLastMessageSequence:I,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=I-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:re,messageList:ne,serverGroupTipList:_i}=OA;m(_i)&&E.push(..._i);const Ti=re&&JA<0,kt=[];if(m(ne)&&(ne.forEach(Ni=>{iA.messageReceiver.groupMessageReceiver.updateMessageProfile(Ni),Ni.from===P.CONV_SYSTEM&&(Ni.isSystemMessage=!1),iA.messageDataHandler.storeConversationMessage(Ni)&&!M(Ni.payload)&&(kt.push(Ni),Ni._isExcludedFromLastMessage||(SA.lastMessage=kA(Ni)))}),kt.length>0&&W.emitOuterEvent(T.MESSAGE_RECEIVED,{name:T.MESSAGE_RECEIVED,data:kt})),!Ti&&ne.length>0){const Ni=ne[ne.length-1].sequence;yield this._recoverGroupHistoryForConversation({conversationID:n,localLastMessageSequence:Ni,serverLastMessageSequence:I,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,I]of n){const E=Array.from(I.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),I=g[g.length-1];return I?.sequence}_shouldRecoverHistory(s){const{localLastMessageSequence:n,serverLastMessageSequence:g}=s;if(typeof n!="number"||typeof g!="number")return!1;const I=g-n;return g!==0&&n>0&&I>=eR&&I{m.type===g.CONV_C2C&&E.push(m)}),this._recoverC2CHistoryMessage(E)}}_recoverC2CHistoryMessage(s){return mA(this,void 0,void 0,function*(){yield Promise.all(s?.map(n=>mA(this,void 0,void 0,function*(){const{conversationID:g,lastMessage:{lastTime:I}={}}=n,E=this._getLocalLastMessageTime(g);this._shouldRecoverC2CHistory({localLastMessageTime:E,serverLastMessageTime:I})&&(yield this._recoverHistoryForC2CConversation({conversationID:g,localLastMessageTime:E,serverLastMessageTime:I}))})))})}_shouldRecoverC2CHistory(s){const{localLastMessageTime:n,serverLastMessageTime:g}=s,I=g-n;return n>0&&I>=1&&I<=600}_recoverHistoryForC2CConversation(s){return mA(this,void 0,void 0,function*(){var n;const{conversationID:g,localLastMessageTime:I,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:I,count:20});if(M(SA))return;const{hasNoMoreHistoryMessage:OA,messageList:JA}=SA,re=[];m(JA)&&(JA.forEach(_i=>{EA.messageDataHandler.storeConversationMessage(_i)&&!M(_i.payload)&&(re.push(_i),_i._isExcludedFromLastMessage||(LA.lastMessage=xA(_i)))}),re.length>0&&iA.emitOuterEvent(P.MESSAGE_RECEIVED,{name:P.MESSAGE_RECEIVED,data:re}));const ne=(n=JA[JA.length-1])===null||n===void 0?void 0:n.time;!OA&&ne>E&&(yield this._recoverHistoryForC2CConversation({conversationID:g,localLastMessageTime:ne,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),I=g[g.length-1];return I?.time}reset(){this._lastMessageSequenceMapOnDisconnect.clear(),this._lastMessageTimeMapOnDisconnect.clear()}dispose(){this.reset()}},pB=new class{constructor(){this.name="HistoryMessage"}install(s){this._core=s,cl.init(s),tR.init(s),QB.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),QB.dispose()}_reset(){QB.reset()}},MD=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:I}}=this._core;try{if(!I(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:I}}=this._core,{atomicStoreID:E}=s;try{I(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:I,eventCode:E,eventResult:m,eventMessage:D,moreMessage:M,extensionMessage:T}=s;g.createSSOLogData({method:T,code:I,message:D,eventType:30,costTime:E,uiPlatform:m,moreMessage:M}).end(!0)}catch(I){g.debug(`reportRoomEngineEvent Report failed: ${n(I)}`)}}reset(){this._reportedAtomicStoreIDs.clear()}dispose(){this.reset()}},qQ=new class{constructor(){this.name="DataReport"}install(s){this._core=s;const{notificationCenter:n,InnerEvent:{LOGOUT:g,DESTROY:I}}=s;MD.init(s),mC.init(s),n.subscribeInnerEvent(g,this._reset,this),n.subscribeInnerEvent(I,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 Vm=sr.STANDARD,mB=[];Vm=sr.STANDARD,mB=[sh,nC,rC,aC,Rc,ST,pB,qQ,TE,vi,jn,hT,Lm,mD,qI];function fB(s,n){const{operationType:g,memberInfoList:I,operatorInfo:E}=s||{};let m={};if(Rs(I)?Rs(E)||(m=E):g!==Tg.JOINED&&g!==Tg.KICKED&&g!==Tg.ADMIN_SET&&g!==Tg.ADMIN_CANCELED||(m=Object.assign({},I[0])),!Rs(m)){const{nick:D="",avatar:M=""}=m;n.nick=D,n.avatar=M}}const KQ=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 jQ=Object.freeze({__proto__:null,ChatError:gs,WorkflowManager:ws,buildAndSendPacket:gg,buildLastMessage:KQ,get builtInPlugins(){return mB},checkBusinessCapabilityBits:tn,deepMerge:cd,getCurrentUserID:Ar,getErrorMessage:rs,getMessagePreviewText:zc,isC2CConv:s=>l(s)&&s.slice(0,3)===ba.CONV_C2C,isCommunity:zr,isGroupConv:s=>l(s)&&s.slice(0,5)===ba.CONV_GROUP,isInternational:vl,isTopic:Wc,isUnlimitedAVChatRoom:function(){var s;return!!(!((s=me.store.get("instance"))===null||s===void 0)&&s.unlimitedAVChatRoom)},liteChatInstanceMap:Ea,registerInterceptor:Mc,registerValidateConfig:jc,requireAuth:rd,get sdkEdition(){return Vm},setGroupTipsUserInfo:fB,t:Ru,updateGroupAtInfo:(s,n)=>{const{CONV_AT_ME:g,CONV_AT_ALL:I,CONV_AT_ALL_AT_ME:E}=ko;if(function(M,T){const{CONV_AT_ME:P,CONV_AT_ALL:W,CONV_AT_ALL_AT_ME:iA}=ko,{groupID:EA,sequence:RA}=M;let kA=!1;return zr({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(I)&&(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:Dr,validateParameters:aI});class tu{constructor(){this._builtInPlugins=new Set,this._externalPlugins=new Set}static getInstance(){return tu._instance||(tu._instance=new tu),tu._instance}static setInstance(n){tu._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 I=[];I=B(n)?n:[n];const E=I.findIndex(D=>D?.name==="AVChatRoom"),m=E>-1?I.splice(E,1):[];I.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(dr.getInstance().exposeApiForPlugin(),m)):D.install(dr.getInstance().exposeApiForPlugin()),vg(D.handleLoginSuccess)&&this._isLoggedIn()&&D.handleLoginSuccess()):vg(D)?(g.add(D.name),D(dr.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=me.store.get("login"))===null||n===void 0?void 0:n.isLoggedIn)===!0}}var yB=new class{constructor(){this._conversationMap=new Map}getConversationMap(){return this._conversationMap}getConversation(s){return this._conversationMap.get(s)}updateConversation(s,n,g){const{emit:I=!0,needSort:E=!1}=g||{},m=this._conversationMap.get(s);m&&!Rs(n)&&(Object.keys(n).forEach(D=>{m[D]=n[D]}),I&&me.notificationCenter.emitInnerEvent(so.CONVERSATION_UPDATED,{needSort:E}))}deleteConversation(s){this._conversationMap.has(s)&&(this._conversationMap.delete(s),me.notificationCenter.emitInnerEvent(so.CONVERSATION_UPDATED))}},WQ=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(I=>{g[I]=n[I]})}},zQ=new class{constructor(){this._messagesByConversation=new Map}updateMessage(s,n,g){var I;const{operation:E,updateUnreadCount:m=!0}=g,D=yo(g,["operation","updateUnreadCount"]),M=[];for(const T of n){const P=(I=this._messagesByConversation.get(s))===null||I===void 0?void 0:I.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)?me.notificationCenter.emitInnerEvent(yu[s],n):me.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)}},vD=Object.freeze({__proto__:null,conversationStore:yB,groupStore:WQ,messageStore:zQ,userStore:rc});class dr{static getInstance(){return dr._instance||(dr._instance=new dr),dr._instance}static setInstance(n){dr._instance=n}constructor(){this._experimentalApiMap={statTUIKeyFeatures:this.statKeyFeatureUsage.bind(this),setApplicationID:this.setApplicationID.bind(this)},this._apiHandlersMap={},this._apiMap={on:me.notificationCenter.subscribeOuterEvent.bind(me.notificationCenter),off:me.notificationCenter.unSubscribeOuterEvent.bind(me.notificationCenter),destroy:this.destroy.bind(this),callExperimentalAPI:this.callExperimentalAPI.bind(this),use:tu.getInstance().installExternalPlugin.bind(tu.getInstance()),registerPlugin:this.registerPlugin.bind(this),setLogLevel:this.setLogLevel.bind(this)}}registerPlugin(n){me.ssoLog.debug("registerPlugin",n)}statKeyFeatureUsage(n){me.ssoLog.debug("statTUIKeyFeatures",n)}setLogLevel(n){me.ssoLog.debug("setLogLevel",n),me.ssoLog.setLogLevel(n)}setApplicationID(n){me.store.set("instance",{applicationID:n})}getApiMap(){return this._apiMap}setApiMap(n){this._apiMap=n}registerApi(n){const{common:{timeManager:g},utils:{safeStringify:I}}=me,{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),PI.includes(E)&&me.ssoLog.debug(E,`${E} start params: ${I(T)}`),Dr(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 me.ssoLog.error(E,`${E} fail ${RA?.message||RA?.errorMessage})`,{error:RA,costTime:g.getServerTimeMs()-P,eventType:W,method:E}),RA}})}registerExperimentalAPI(n,g,I){const E=I||n;this._experimentalApiMap[n]=g[E].bind(g)}destroy(){return mA(this,void 0,void 0,function*(){var n,g;try{!((n=me.store.get("login"))===null||n===void 0)&&n.isLogin&&(yield this._apiMap.logout()),me.notificationCenter.emitInnerEvent(so.DESTROY)}catch(I){console.debug("destroy error: ",I)}finally{me.notificationCenter.emitOuterEvent(yr.SDK_DESTROY,{SDKAppID:(g=me.store.get("instance"))===null||g===void 0?void 0:g.sdkAppId}),Ea.clear(),tu.getInstance().clear(),ws.getInstance().destroy(),me.destroy()}})}exposeApiForClient(){return this._apiMap}exposeApiForPlugin(){return Object.assign(Object.assign({InnerEvent:so,InnerEventSubType:me.notificationCenter.InnerEventSubType,OuterEvent:yr,OuterConstant:ko,SignalingEvent:Hc,helper:Object.assign(Object.assign(Object.assign({},me.utils),me.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},me),{constants:Object.assign(Object.assign({},Wa),me.constants),common:Object.assign(Object.assign(Object.assign({},jQ),me.common),{workflowManager:ws.getInstance()}),utils:me.utils,appStore:vD})}callExperimentalAPI(n,g){return me.ssoLog.debug(`callExperimentalAPI.${n} start params: ${me.utils.safeStringify(g)}`),this._experimentalApiMap[n]?this._experimentalApiMap[n](g):(me.ssoLog.error("callExperimentalAPI",`callExperimentalAPI.${n} not found, params: ${me.utils.safeStringify(g)}`),Promise.reject(new gs({code:ua.INVALID_OPERATION})))}_isPromiseLike(n){return n!==null&&typeof n=="object"&&typeof n.then=="function"}_handleAsyncResult(n,g,I,E){return n.then(m=>(this._reportApiSuccessLog({result:m,apiName:g,eventType:I,startTime:E}),m)).catch(m=>{throw me.ssoLog.error(g,`${g} fail ${m?.message||m?.errorMessage})`,{error:m,costTime:me.common.timeManager.getServerTimeMs()-E,eventType:I,method:g,startTime:E}),m})}_reportApiSuccessLog(n){let{result:g,apiName:I,startTime:E,eventType:m}=n;const{timeManager:D}=me.common,{successLog:{message:M,moreMessage:T}={message:"",moreMessage:""}}=g||{},P=D.getServerTimeMs();I==="login"&&(E+=D.getTimeOffsetWithServer()),PI.includes(I)&&me.ssoLog.info(I,`${I} success ${M} ${T}`,{costTime:P-E,eventType:m,message:M,moreMessage:T,startTime:E}),g?.successLog&&delete g.successLog}}class iR{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120,this._customLoginInfo=""}init(){const{notificationCenter:n,store:g}=me;g.set("login",{isReady:!1}),dr.getInstance().registerApi({apiName:"login",context:this}),dr.getInstance().registerApi({apiName:"logout",context:this}),dr.getInstance().registerApi({apiName:"getLoginUser",context:this}),dr.getInstance().registerApi({apiName:"isReady",context:this}),dr.getInstance().registerApi({apiName:"getServerTime",context:this}),dr.getInstance().registerExperimentalAPI("setCustomLoginInfo",this),n.subscribeInnerEvent(so.RECONNECTED,this._reLogin,this),me.notificationCenter.subscribeInnerEvent(so.DESTROY,this._dispose,this)}login(n){return mA(this,void 0,void 0,function*(){var g;const{sdkEdition:I}=me.store.get("instance")||{};try{if(this._isLoginIn())return this._createRepeatLoginResponse();if(this._isLoginFrequencyExceeded())throw new gs({functionName:"login",code:ua.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=me.channel.getSocketAdapter())===null||g===void 0?void 0:g.getId(),{appId:D,href:M}=me.store.get("instance")||{},{instanceID:T,customStatus:P}=E||{};return{code:0,data:E,successLog:{message:I,moreMessage:`socketID:${m} instanceID:${T} customStatus:${P} href: ${M} appId: ${D}`}}}catch(E){const{errorCode:m}=E;m!==ua.REPEAT_LOGIN&&(this._latestLoginAt=0);const D=new gs({functionName:"login",code:m});throw console.error(D),D}})}_reLogin(){return mA(this,void 0,void 0,function*(){var n;try{if(!this._isLoginIn())return;const g=yield vu(this._customLoginInfo);if(g){const{instanceID:I,customStatus:E}=g;me.store.set("login",{statusInstanceId:I}),ws.getInstance().executeWorkflow(Pt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,{customStatus:E,statusType:CE.USER_STATUS_ONLINE});const m=(n=me.channel.getSocketAdapter())===null||n===void 0?void 0:n.getId();me.ssoLog.info("reLogin",`socketId:${m} instanceId:${I}`)}}catch(g){console.warn(g)}})}logout(){return mA(this,arguments,void 0,function*(n=sa.USER_INITIATED){const{ssoLog:g}=me;g.debug("logout",`logout start logoutReason: ${n}`);try{yield this._performLogout(n),g.info("logout","logout success"),me.ssoLog.uploadSSOLogData()}catch(I){const{errorCode:E}=I;throw new gs({functionName:"logout",code:E})}finally{this.handleLogoutCompleted()}return{code:0,data:{}}})}getLoginUser(){return this._isLoginIn()?Ar():""}isReady(){var n;return(n=me.store.get("login"))===null||n===void 0?void 0:n.isReady}setCustomLoginInfo(n=""){this._customLoginInfo=n}handleLogoutCompleted(){this._updateAndEmitSDKNotReady(),this._reset(),ws.getInstance().reset(),me.notificationCenter.emitInnerEvent("logout")}getServerTime(){const{timeManager:n}=me.common;return n.getServerTimeMs()}_updateAndEmitSDKReady(){me.store.set("login",{isReady:!0}),setTimeout(()=>{me.notificationCenter.emitOuterEvent(yr.SDK_READY,{name:yr.SDK_READY})},1)}_updateAndEmitSDKNotReady(){me.store.set("login",{isReady:!1}),me.notificationCenter.emitOuterEvent(yr.SDK_NOT_READY,{name:yr.SDK_NOT_READY})}_validateAfterLogin(n){const g="login";if(!n)throw new gs({functionName:g,message:"login response is empty"});const{tinyID:I,a2Key:E}=n||{};if(!I)throw new gs({functionName:g,code:ua.NO_TINYID});if(!E)throw new gs({functionName:g,code:ua.NO_A2KEY})}_createRepeatLoginResponse(){var n;return{code:0,data:{actionStatus:"OK",errorCode:0,errorInfo:rs({code:"RepeatLogin",replacement1:(n=me.store.get("login"))===null||n===void 0?void 0:n.userId}),repeatLogin:!0}}}_performLogin(n){return mA(this,void 0,void 0,function*(){const{userID:g,userSig:I}=n;return me.store.set("login",{userId:g,userSig:I}),this._latestLoginAt=Date.now(),vu(this._customLoginInfo)})}_ensureAsyncComplete(){return mA(this,void 0,void 0,function*(){yield new Promise(n=>{setTimeout(()=>n(null),1)})})}_handleLoginSuccess(n){const{timeManager:g}=me.common,{helloInterval:I,timeStamp:E,customStatus:m,purchaseBits:D}=n,M=1e3*E;g.calculateTimeOffsetWithServer(this._latestLoginAt,M),this._helloInterval=I||120,this._updateLoginStore(n),me.user.userStatus.setCustomStatus(m),ws.getInstance().executeWorkflow(Pt.SYNC_SERVER_INFO_AFTER_LOGIN,{purchaseBits:D}),me.common.taskScheduler.addTask({id:Gg,intervalMs:1e3*this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this})}_performLogout(n){return function(g){return mA(this,void 0,void 0,function*(){const{logoutReason:I}=g,E="im_open_status.wslogout",m=me.common.generateProtocolData({servcmd:E,data:{wslogout_type:I,isWebUniapp:0}}),D=`${m.head.seq}${E}`;return yield me.channel.sendPacket(m,{requestId:D})})}({logoutReason:n})}_updateLoginStore(n){const{a2Key:g,tinyID:I,instanceID:E,authKey:m}=n;me.store.set("login",{a2Key:g,tinyID:I,statusInstanceId:E,authKey:m,isLoggedIn:!0})}_sendOnlinePresenceRequest(){return mA(this,void 0,void 0,function*(){this._latestSendOnlinePresenceRequestTime=Date.now();try{yield function(){const n="im_open_status.wshello",g=me.common.generateProtocolData({servcmd:n,data:{isWebUniapp:0}}),I=`${g.head.seq}${n}`;return me.channel.sendPacket(g,{requestId:I})}()}catch(n){me.ssoLog.warn("_sendOnlinePresenceRequest",` error:${n.message}`)}})}_isLoginIn(){var n;return((n=me.store.get("login"))===null||n===void 0?void 0:n.isLoggedIn)===!0}_isLoginFrequencyExceeded(){return Date.now()-this._latestLoginAt<=15e3}_reset(){me.common.taskScheduler.removeTask(Gg),this._helloInterval=120,this._latestSendOnlinePresenceRequestTime=0,this._latestLoginAt=0,this._customLoginInfo="",me.store.clear("login"),me.store.set("login",{isReady:!1}),me.store.set("instance",{applicationID:0})}_dispose(){this._reset();const{notificationCenter:n}=me;n.unSubscribeInnerEvent(so.RECONNECTED,this._reLogin,this),n.unSubscribeInnerEvent(so.DESTROY,this._dispose,this)}}const oR={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}},MT={logout:!0};class Sh{constructor(){this.loginAction=new iR,this.kickedOutHandler=new Mu,this.loginAction.init(),this.kickedOutHandler.init(),jc({auth:MT,params:oR})}}var Jr,qu,FE;(function(s){s.CONV_C2C="C2C",s.CONV_GROUP="GROUP",s.CONV_TOPIC="TOPIC",s.CONV_SYSTEM="@TIM#SYSTEM"})(Jr||(Jr={})),function(s){s.MSG_PRIORITY_HIGH="High",s.MSG_PRIORITY_NORMAL="Normal",s.MSG_PRIORITY_LOW="Low",s.MSG_PRIORITY_LOWEST="Lowest"}(qu||(qu={})),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"}(FE||(FE={}));const RD={1:qu.MSG_PRIORITY_HIGH,2:qu.MSG_PRIORITY_NORMAL,3:qu.MSG_PRIORITY_LOW,4:qu.MSG_PRIORITY_LOWEST},wD=0,sR=1;var Ku;(function(s){s.IN="in",s.OUT="out"})(Ku||(Ku={}));const nR=2,ZQ={};function iu(s){if(!s)return 0;if(ZQ[s]===void 0){const n=new Date,g=`3${n.getHours()}`.slice(-2),I=`0${n.getMinutes()}`.slice(-2),E=`0${n.getSeconds()}`.slice(-2);ZQ[s]=parseInt([g,I,E,"0001"].join(""),10),console.log(`autoIncrementIndex start index:${ZQ[s]}`)}else ZQ[s]+=1;return ZQ[s]}class OE{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=qu.MSG_PRIORITY_NORMAL,this._relayFlag=!1;const{clientTime:g=me.common.timeManager.getServerTimeSeconds()||0,senderTinyID:I,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:re=0,isPlaceMessage:ne=0,messageFlagBits:_i,receiverList:Ti,isSystemMessage:kt=!1,status:Ni=Or.SUCCESS,revokeReason:cs="",conversationSubType:Se,clientSequence:Bt,protocol:UA="JSON",revokerInfo:ii={userID:"",nick:"",avatar:""},readReceiptInfo:_s={readCount:void 0,unreadCount:void 0,isPeerRead:void 0,timestamp:0},random:Gi,groupProfile:Lr,atUserList:xi,flow:ar,isRead:wt=!1,priority:_t=qu.MSG_PRIORITY_NORMAL,onlineOnlyFlag:Wu=!1,nameCard:ln="",quoteInfo:ho}=n;var ll;this.clientTime=g,this.senderTinyID=I||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||Jr.CONV_C2C,this.hasRiskContent=re>1,this.version=SA,this.isPlaceMessage=ne,this.isRevoked=ne===2||_i===8,this.isSystemMessage=kt,this.readReceiptInfo=_s,this.revokeReason=cs,this.revokerInfo=ii,this._receiverList=Ti,this.conversationSubType=Se,this.revoker=ii?.revoker||"",this.clientSequence=Bt||JA||0,this.status=Ni,this.atUserList=xi||[],this.flow=ar,this.isRead=wt,this.priority=_t,this._onlineOnlyFlag=Wu,this.nameCard=ln,this.quoteInfo=ho,this.reInitialize(E),this._initC2CReadReceiptInfo(n),this._extractGroupInfo(Lr)}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,I;return this._relayFlag?{isValid:!0}:((n=this._elements)===null||n===void 0?void 0:n.length)>0?(I=(g=this._elements[0])===null||g===void 0?void 0:g.validateBeforeSend)===null||I===void 0?void 0:I.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:I=0}=n;this.conversationType===Jr.CONV_C2C&&this.needReadReceipt===!0&&(this.readReceiptInfo.isPeerRead=g===1,this.readReceiptInfo.timestamp=I)}_extractGroupInfo(n){if(!n)return;const{From_AccountNick:g,From_AccountHeadurl:I,MsgFrom_AccountExtraInfo:E,GroupType:m}=n,{NameCard:D}=E||{};typeof g=="string"&&(this.nick=g),typeof I=="string"&&(this.avatar=I),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 I=this.conversationType;I!==Jr.CONV_SYSTEM?(g=I===Jr.CONV_C2C?n===this.from?this.to:this.from:this.to,this.conversationID=g?`${I}${g}`:null):this.conversationID=Jr.CONV_SYSTEM}_initSequence(n){this.clientSequence===0&&n&&(this.clientSequence=iu(n)),this.sequence===0&&this.conversationType===Jr.CONV_C2C&&(this.sequence=this.clientSequence)}generateMessageID(){this.from===Jr.CONV_SYSTEM&&(this.senderTinyID="144115198244471703"),this.ID=`${this.senderTinyID}-${this.clientTime}-${this.random}`}setIsRead(n){this.isRead=n}}class Sd{static parseServerPushElement(n){const{MsgContent:g={}}=n,{Data:I,Ext:E,Desc:m}=g;return new Sd({data:I,description:m,extension:E})}constructor(n){this.type=FE.MSG_CUSTOM;const{data:g="",description:I="",extension:E=""}=n;this.content={data:g,description:I,extension:E}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},I=g?this.payload:this.content,{data:E,description:m,extension:D}=I;return{MsgType:this.type,MsgContent:{Data:E,Ext:D,Desc:m}}}validateBeforeSend(){const{isEmpty:n}=me.utils,g=[this.content.data,this.content.description,this.content.extension].some(I=>!n(I));return{isValid:g,error:g?null:{message:"content can not be empty"}}}}class Md{static parseServerPushElement(n){const{MsgContent:g={Text:""}}=n,{Text:I}=g;return new Md({text:I})}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||{},I=g?this.payload:this.content,{text:E}=I;return{MsgType:this.type,MsgContent:{Text:E}}}}var Jm=new class{constructor(){this._elementClassMap={[FE.MSG_CUSTOM]:Sd,[FE.MSG_TEXT]:Md}}init(){dr.getInstance().registerApi({apiName:"createCustomMessage",context:this}),dr.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=Ku.OUT}=s,{userId:I}=me.store.get("login")||{};this._isSendByCurrentInstance({from:n,flow:g,currentUser:I})?this._updateWithSenderInfo(s):this._isMultiEndpointSyncMessage({from:n,flow:g,currentUser:I})&&(s.flow=Ku.OUT);const E=Object.assign(Object.assign({},s),{currentUser:I});return new OE(E)}createCustomMessage(s){const n=Ar(),g=this.createMessage(Object.assign(Object.assign({},s),{from:n})),I=this._elementClassMap[FE.MSG_CUSTOM];if(!g)return null;if(I){const E=new I(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)||"",I=new Md({text:g}),E=Ar(),m=me.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:E}));return m.setElement(I),m}_updateWithSenderInfo(s){var n,g;const{nick:I,avatar:E,conversationType:m,to:D}=s,{userId:M,tinyID:T}=me.store.get("login")||{},P=rc.getUserProfile(M);return s.nick=I||P?.nick||"",s.avatar=E||P?.avatar||"",s.tinyID=s.tinyID||T||"",s.from=M,s.status=Or.UNSENT,s.flow=Ku.OUT,m===ba.CONV_GROUP&&(s.nameCard=(g=(n=WQ.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:I}=s;return n===I&&g===Ku.IN}_isSendByCurrentInstance(s){const{from:n,flow:g,currentUser:I}=s;return n===I&&g===Ku.OUT}};const rR={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}},vd={HonorImportance:{range:["LOW","NORMAL"],defaultValue:void 0},MeizuNotifyType:{range:[0,1],defaultValue:void 0}},_D={enableIOSBackgroundNotification:{range:[!0,!1],defaultValue:!1},interruptionLevel:{range:["passive","active","time-sensitive","critical"],defaultValue:"active"}};function aR(s,n){return Object.keys(n).forEach(g=>{const{range:I,defaultValue:E}=n[g];s[g]=I.includes(s[g])?s[g]:E}),s}function XQ(s){const n=s.lastIndexOf(".");return n===-1?s:s.slice(0,n)}function gR(s){const{androidInfo:n={},androidOPPOChannelID:g=""}=s,I=n.OPPOChannelID||g,E=aR(n,vd),{sound:m="",FCMChannelID:D=""}=E,M=yo(E,["sound","FCMChannelID"]);return Object.assign(Object.assign({},M),{Sound:XQ(m),OPPOChannelID:I,GoogleChannelID:D})}function cR(s){const{apnsInfo:n={},ignoreIOSBadge:g=!1,disableVoipPush:I}=s,E=aR(n,_D),{ignoreIOSBadge:m,disableVoipPush:D,enableIOSBackgroundNotification:M}=E,T=yo(E,["ignoreIOSBadge","disableVoipPush","enableIOSBackgroundNotification"]),P=m===!0||g===!0?1:0;let W;return r(I)||(W=I===!1?1:0),r(D)||(W=D===!1?1:0),Object.assign(Object.assign({},T),{BadgeMode:P,IsVoipPush:W,ContentAvailable:M?1:0})}function TD(s){return me.utils.isPlainObject(s)?{PushFlag:s.disablePush===!0?1:0,Title:s.title||"",Desc:s.description||"",Ext:s.extension||"",ApnsInfo:cR(s),AndroidInfo:gR(s)}:rR}function Hm(s){const{From_AccountHeadurl:n,From_AccountNick:g,IsNeedReadReceipt:I,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:re}=s;let ne,{From_Account:_i,To_Account:Ti}=s;if(m===1){const kt=Ti;Ti=_i,_i=kt}if(JA){const{Reason:kt,Revoker_Account:Ni,Revoker_FromUin:cs}=JA;ne={reason:kt,revoker:Ni,revokerFromUin:cs,userID:Ni}}return{from:_i,avatar:n,nick:g,needReadReceipt:I===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:ne,messageVersion:SA,messageFlagBits:OA,readReceiptSentByPeer:E,elements:fC(D),onlineOnlyFlag:T===0,quoteInfo:$Q(re)}}function qm(s){const{From_Account:n,MsgBody:g,MsgClientTime:I,MsgRandom:E,MsgSeq:m,MsgTimeStamp:D,To_Account:M,MsgVersion:T,CloudCustomData:P,MsgCheckResult:W}=s;return{from:n,clientTime:I,random:E,sequence:m,time:D,to:M,elements:fC(g),messageVersion:T,cloudCustomData:P,checkResult:W}}function ND(s){const{ClientSeq:n,From_Account:g,GroupInfo:I,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:re}=s;let ne,_i=qu.MSG_PRIORITY_NORMAL;if(Object.keys(RD).includes(String(s.MsgPriority))&&(_i=RD[s.MsgPriority]),SA){const{Reason:kt,Revoker_Account:Ni,Revoker_FromUin:cs}=SA;ne={reason:kt,revoker:Ni,revokerFromUin:cs,userID:Ni}}const Ti=function(kt){const Ni=[];return Array.isArray(kt)&&kt.forEach(cs=>{cs.GroupAtAllFlag===wD?Ni.push(cs.GroupAt_Account):cs.GroupAtAllFlag===sR&&Ni.push(ko.MSG_AT_ALL)}),Ni}(OA);return{clientSequence:n,from:g,groupProfile:I,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:ne,atUserList:Ti,elements:fC(E),to:vT(s),onlineOnlyFlag:JA===1,quoteInfo:$Q(re)}}function vT(s){const{utils:{isEmpty:n},constants:{IS_TOPIC_MESSAGE:g}}=me,{ToGroupId:I,GroupInfo:{MillionGroupFlag:E=0,TopicId:m}={}}=s;return E!==g||n(m)?I:m}function fC(s){if(!s)return null;if(Array.isArray(s))return s.map(g=>{const I=me.message.messageFactory.getElementClass(g.MsgType);return I?.parseServerPushElement(g)});const n=me.message.messageFactory.getElementClass(s.MsgType);return n?.parseServerPushElement(s)}function GD(s){const{From_Account:n,MsgBody:g,MsgClientTime:I,MsgRandom:E,MsgSeq:m,MsgTimeStamp:D,GroupId:M,TopicId:T,MsgVersion:P,CloudCustomData:W,MsgCheckResult:iA}=s;return{from:n,clientTime:I,random:E,sequence:m,time:D,groupID:M,topicID:T,elements:fC(g),messageVersion:P,cloudCustomData:W,checkResult:iA}}function $Q(s){const{utils:{isString:n,safeStringify:g},ssoLog:I}=me;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 I.debug("_parseServerQuoteInfo",g(E)),null}}function Ap({conversationUpdateFields:s,message:n}){const{conversationID:g,conversationType:I,conversationSubType:E,flow:m,_isExcludedFromUnreadCount:D,_isExcludedFromLastMessage:M}=n,T=M?"":KQ(n),P=!D&&m===Ku.IN;s.has(g)?(s.get(g).lastMessage=T,P&&s.get(g).unreadCount++):s.set(g,{conversationID:g,type:I,subType:E,unreadCount:P?1:0,lastMessage:T})}function DB(s){return s.filter(n=>{const g=!Rs(n?._elements),I=n?.isPlaceMessage===1;return g||me.ssoLog.error("emptyMessageBody",`from:${n.from} to:${n.to} sequence:${n.sequence}`),g&&!I})}function SB(s){const{messageDataHandler:n}=me.message;return!n.isInMessageList(s)&&!n.isMessageSentByCurrentInstance(s)}var lR=Object.freeze({__proto__:null,autoIncrementIndex:iu,createAndroidPushInfo:gR,createApnsPushInfo:cR,createOfflinePushInfo:TD,filterValidMessages:DB,getAndroidSoundName:XQ,parseServerGroupMessage:ND,parseServerPushC2CModifyMessage:qm,parseServerPushGroupModifyMessage:GD,parseServerPushMessage:Hm,parseServerPushMessageElement:fC,shouldStoreMessage:SB,updateConversationFields:Ap});const{isPlainObject:IR}=me.utils;function ep(s,n={}){const{onlineUserOnly:g,messageControlInfo:I}=n;let{offlinePushInfo:E}=n;s.conversationType===Jr.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(I&&IR(I)){const{excludedFromUnreadCount:M,excludedFromLastMessage:T,excludedFromContentModeration:P}=I;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 bD(s){const{webhookInfo:{disableCloudMessagePreHook:n=!1,disableCloudMessagePostHook:g=!1}={}}=s||{};if(!n&&!g)return;const I=[];return n&&I.push("ForbidBeforeSendMsgCallback"),g&&I.push("ForbidAfterSendMsgCallback"),I}function Mh(s,n){return mA(this,void 0,void 0,function*(){const g=s.conversationType===Jr.CONV_GROUP?function(E,m){var D;const M=ep(E,m),{onlineUserOnly:T,cloudCustomData:P,messageControlInfo:W,offlinePushInfo:iA}=M,EA=JSON.parse(JSON.stringify(E.transformElementsToServerFormat()));let RA;return B(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=me.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:TD(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:bD(m),InnerSdkCustomData:vB(E)}}}(s,n):function(E,m){var D;const M=ep(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=me.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:TD(iA),ForbidCallbackControl:bD(m),InnerSdkCustomData:vB(E)}}}(s,n),I=yield gg(g);return I?{time:I.MsgTime,messageDropReason:I.MsgDropReason,sequence:I.MsgSeq}:null})}function vh(s){return mA(this,void 0,void 0,function*(){const{from:n,to:g,version:I=0,sequence:E,random:m,time:D,type:M,cloudCustomData:T}=s,P={From_Account:n,To_Account:g,MsgVersion:I,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:fC(iA),messageVersion:EA,cloudCustomData:RA}}})}function MB(s){return mA(this,void 0,void 0,function*(){const{to:n,version:g=0,sequence:I,cloudCustomData:E}=s,m={GroupId:n,MsgVersion:g,MsgSeq:I,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:fC(M),messageVersion:T,cloudCustomData:P}}})}function Rh(s){return mA(this,void 0,void 0,function*(){const{groupID:n,count:g,messageSequence:I,messageSequenceList:E,getType:m}=s,D={GroupId:n,ReqMsgNumber:g,WithRecalledMsg:1,Version:1,GetType:m};return I&&(D.ReqMsgSeq=I),B(E)&&E.length>0&&(D.ReqMsgSeqList=E),yield gg({servcmd:"group_open_http_svc.group_msg_get",data:D})})}function Km(s){return mA(this,void 0,void 0,function*(){const{peerAccount:n,count:g,lastMessageTime:I,messageKey:E,direction:m}=s;return gg({servcmd:"openim.getroammsg",data:{Peer_Account:n,MaxCnt:g,WithRecalledMsg:1,LastMsgTime:I,MsgKey:E,GetDirection:m}})})}function vB(s){if(me.utils.isObject(s.quoteInfo)){const{msgID:n,messageSequence:g,messageTime:I}=s.quoteInfo;return JSON.stringify({businessQuote:{messageID:n,messageSequence:g,messageTime:I}})}}var kD=Object.freeze({__proto__:null,createMessagePackOptions:ep,generateForbidCallbackControl:bD,getC2CRoamingMessagesByAnchor:Km,getGroupRoamingMessagesByAnchor:Rh,getRoamingMessages:function(s){return mA(this,void 0,void 0,function*(){const{peerAccount:n,count:g,lastMessageTime:I,messageKey:E}=s;return(yield gg({servcmd:"openim.getroammsg",data:{Peer_Account:n,MaxCnt:g||15,LastMsgTime:I||0,MsgKey:E,GetDirection:0,WithRecalledMsg:1}}))||[]})},modifyC2CMessage:vh,modifyGroupMessage:MB,sendMessage:Mh});const{isPlainObject:RT}=me.utils,{MSG_AUDIO:LD,MSG_FILE:UD,MSG_IMAGE:uR,MSG_VIDEO:ER,MSG_MERGER:dR}=ko;class jm{constructor(){this._sendProtocolMap=new Map}init(){dr.getInstance().registerApi({apiName:"sendMessage",context:this,matcher:n=>![LD,UD,uR,ER,dR].includes(n[0].type)})}registerSendProtocol(n,g,I){this._sendProtocolMap.set(n,g.bind(I))}sendMessage(n,g){return mA(this,void 0,void 0,function*(){const{TOTAL_COUNT:I,SEND_COST:E,SUCCESS_COUNT:m,FAILED_COUNT:D}=nr;if(!(n instanceof OE))throw new gs({code:ua.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:I,message:n});let T=!1;const{messageDataHandler:P}=me.message||{};try{const{messageControlInfo:W}=g||{};let iA=null;P.addRandomOfSentMessage(n.random);const EA=Date.now(),RA=this._getSendProtocol(n);if(n.conversationType===Jr.CONV_C2C?(T=g?.onlineUserOnly===!0,iA=yield RA(n,g)):n.conversationType===Jr.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&&(me.ssoLog.debug("sendMessage",`sendMessage resend ok. ID:${SA.ID}`),P.deleteConversationMessage(SA))}return n.status=Or.SUCCESS,n.time=LA,n.conversationType===Jr.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=Or.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:I,conversationType:E}=n,m=Wc(I)?so.TOPIC_NEW_MESSAGE:so.NEW_MESSAGE;me.notificationCenter.emitInnerEvent(m,{result:{conversationUpdateFieldList:[{conversationID:I,type:E,message:n,lastMessage:g,unreadCount:0}]}})}_applySentMessageControlInfo(n,g){g&&RT(g)&&(g.excludedFromLastMessage===!0&&(n._isExcludedFromLastMessage=!0),g.excludedFromUnreadCount===!0&&(n._isExcludedFromUnreadCount=!0))}_logRateLimitInfo(n,g,I){const E=`from:${n.from} to:${n.to} sequence:${g} messageDropReason:${I}`;me.ssoLog.warn("messageDropReason",E)}_updateNickAndAvatarOfSentMessageByMe(n){const{messageDataHandler:g}=me.message||{};let I=!1;const{conversationID:E}=n,m=g.getLatestMsgSentByMe(E);if(m){const{nick:D,avatar:M}=m;D===n.nick&&M===n.avatar||(I=!0),I&&g.updateNickAndAvatarOfSentMessage({conversationID:E,latestNick:n.nick,latestAvatar:n.avatar,isSentByMe:!0})}}_validateBeforeSendGroupMessage(n){return mA(this,void 0,void 0,function*(){var g,I,E;const{to:m,from:D}=n;let M=m,T=WQ.getGroup(M);if(zr({groupID:M})&&T?.isSupportTopic)throw new gs({code:ua.MSG_SEND_GRP_WITH_TOPIC_FAIL});if(Wc(m)&&([M]=m.split(oa.TOPIC),T=WQ.getGroup(M)),!T&&typeof((g=dr.getInstance().getApiMap())===null||g===void 0?void 0:g.getGroupProfile)=="function"){const P=yield dr.getInstance().getApiMap().getGroupProfile({groupID:M});if(((E=(I=P?.data)===null||I===void 0?void 0:I.group)===null||E===void 0?void 0:E.type)===ko.GRP_AVCHATROOM){const W=rs({code:ua.MSG_SEND_FAIL_NOT_IN_AV,replacement1:D,replacement2:M});throw new gs({code:ua.MSG_SEND_FAIL_NOT_IN_AV,message:W})}}return!0})}_reportMessageSendQuality(n){me.notificationCenter.emitInnerEvent(so.QUALITY_STAT,{label:nI.MESSAGE_SEND_SUCCESS_RATE,data:n})}_getSendProtocol(n){return this._sendProtocolMap.get(n.type)||Mh}}var wT=new class{constructor(){this._sparseMessagesByConversation=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new Set}init(){me.notificationCenter.subscribeInnerEvent(so.LOGOUT,this._reset,this),me.notificationCenter.subscribeInnerEvent(so.DESTROY,this._dispose,this)}get _messagesByConversation(){return zQ.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 I=this._getUniqueIdOfMessage(s);return this._messagesByConversation.get(g).set(I,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),I=this._messagesByConversation.get(s.conversationID);if(I?.has(g)){const E=I?.get(g);if(!n||E?.isModified===!0)return!0}return!1}deleteConversationMessage(s){var n;const{conversationID:g=""}=s,I=this._getUniqueIdOfMessage(s);this._messagesByConversation.has(g)&&((n=this._messagesByConversation.get(g))===null||n===void 0||n.delete(I))}modifyConversationMessage(s,n){var g;if(!this._messagesByConversation.has(s)&&!this._sparseMessagesByConversation.has(s))return{isUpdated:!1,message:null};const I=this._getUniqueIdOfMessage(n),E=this._getMessageFromLocalMessage(s,I);if(E){const{messageVersion:m,elements:D,cloudCustomData:M,checkResult:T=0}=n,P=T>1;if(me.ssoLog.debug("modifyConversationMessage",`conversationToMessageMap modifyConversationMessage localVersion:${E.version} remoteVersion:${m}`),E.versionE.ID===s)||null,n)break;if(!n){const I=Array.from(this._sparseMessagesByConversation.values());for(const E of I)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:I}){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 zQ.updateMessage(s,[M],{isRevoked:!0,revoker:I,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=I,m}}_findMessageBySequenceAndRandom({messageList:s,sequence:n,random:g}){for(let I=0;I0){const D=new Map([...E,...m.entries()]);this._messagesByConversation.set(g,D),this._updateLatestMessageSentByMe(g),this._updateLatestMessageSentByPeer(g)}return I}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 I=this._sparseMessagesByConversation.get(n);for(let E=0;E=0;I--)if(g[I].flow==="out"){this._setLatestMsgSentByMe(s,g[I]);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 I=g.length-1;I>=0;I--)if(g[I].flow==="in"){this._setLatestMsgSentByPeer(s,g[I]);break}}}_getUniqueIdOfMessage(s){const{from:n,to:g,random:I,sequence:E,time:m}=s;return`${n}-${g}-${I}-${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:I,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!==I&&(T.nick=I),W!==g&&(T.avatar=g))})}isInMessageList(s){var n;const{conversationID:g}=s;if(!g||!this._messagesByConversation.has(g))return!1;const I=this._getUniqueIdOfMessage(s);return(n=this._messagesByConversation.get(g))===null||n===void 0?void 0:n.has(I)}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(),me.notificationCenter.unSubscribeInnerEvent(so.LOGOUT,this._reset,this),me.notificationCenter.unSubscribeInnerEvent(so.DESTROY,this._dispose,this)}};function Wm(s,n){const g=yB.getConversation(s);if(g?.lastMessage){const{lastMessage:I}=g,{lastTime:E,lastSequence:m,version:D}=I,{time:M,sequence:T,messageVersion:P,elements:W,cloudCustomData:iA}=n;E===M&&m===T&&D!==P&&(I.type=W[0].type,I.payload=W[0].content,I.messageForShow=zc(I.type,I.payload),I.cloudCustomData=iA,I.version=P,yB.updateConversation(s,{lastMessage:I}))}}class CR{init(){dr.getInstance().registerApi({apiName:"modifyMessage",context:this})}modifyMessage(n){return mA(this,void 0,void 0,function*(){const{to:g,payload:I,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=I)}try{let W=null,iA=null;if(m===Jr.CONV_C2C?W=yield vh(n):m===Jr.CONV_GROUP&&(W=yield MB(n)),W){let EA=`${m}${g}`;return g===Ar()&&m===Jr.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:I,message:E}=me.message.messageDataHandler.modifyConversationMessage(g,n);I===!0&&me.notificationCenter.emitOuterEvent(yr.MESSAGE_MODIFIED,{name:yr.MESSAGE_MODIFIED,data:[E]}),me.notificationCenter.emitInnerEvent(so.MESSAGE_MODIFIED,{conversationID:g,message:E}),Wm(g,n)}_canModifyMessageElement(n){return[FE.MSG_TEXT,FE.MSG_CUSTOM,FE.MSG_LOCATION,FE.MSG_FACE].includes(n)}}class wh{init(){const{notificationCenter:n}=me,{InnerEventSubType:g}=n;ws.getInstance().registerWorkflowStep(Pt.RECEIVE_C2C_NEW_MESSAGE,Ht.HANDLE_C2C_NEW_MESSAGE,this._handleC2CMessagePush,this),ws.getInstance().registerWorkflowStep(Pt.RECEIVE_C2C_NEW_MESSAGE,Ht.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterReceiveNewMessage,this),ws.getInstance().registerWorkflowStep(Pt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Ht.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(Pt.RECEIVE_C2C_NEW_MESSAGE,n)}_handleC2CMessagePush(n){const g=n.data||{},{messageDataHandler:I}=me.message||{},E=[],m=new Map;return g.C2cMsgArray.forEach(D=>{const M=this._generateC2CMessage(D);this._updateMessageProfile(M);let T=M.isModified===1;I.isMessageSentByCurrentInstance(M)?M.isModified=T:T=!1,M._onlineOnlyFlag?I.isMessageSentByCurrentInstance(M)||E.push(M):SB(M)&&(I.storeConversationMessage(M)&&Ap({conversationUpdateFields:m,message:M}),I.isMessageSentByCurrentInstance(M)&&!T||E.push(M))}),{conversationUpdateFieldList:[...m.values()],messages:E}}_emitMessageEventsAfterReceiveNewMessage(n){var g;const{messages:I=[]}=((g=n.result)===null||g===void 0?void 0:g[Ht.HANDLE_C2C_NEW_MESSAGE])||{};this._emitMessageEvents(I)}_emitMessageEventsAfterSyncUnreadMessage(n){var g;const{messages:I=[]}=((g=n.result)===null||g===void 0?void 0:g[Ht.UNREAD_MESSAGE_SYNC])||{};this._emitMessageEvents(I)}_emitMessageEvents(n){const g=n?.filter(E=>E?.isModified===!0)||[];g.length>0&&me.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:g});const I=n?.filter(E=>!E?.isModified);I.length>0&&me.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:I})}_generateC2CMessage(n){const g=Jr.CONV_C2C,I=Hm(n),E=me.message.messageFactory.createMessage(Object.assign(Object.assign({},I),{conversationType:g,flow:Ku.IN})),{elements:m}=I;return E.setElement(m),E}_updateMessageProfile(n){var g;const{messageDataHandler:I}=me.message||{},E=(g=me.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=I.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||(I.updateNickAndAvatarOfSentMessage({conversationID:T,latestNick:D,latestAvatar:M,isSentByMe:!1}),this._updateConversationUserProfile({conversationID:T,nick:D,avatar:M}))}}else{const P=I.getLatestMsgSentByMe(T);!P||D===P.nick&&M===P.avatar||I.updateNickAndAvatarOfSentMessage({conversationID:T,latestNick:D,latestAvatar:M,isSentByMe:!0})}}_updateConversationUserProfile(n){const{conversationID:g,nick:I,avatar:E}=n,m=yB.getConversation(g),{userProfile:D={}}=m||{};D.avatar===E&&D.nick===I||yB.updateConversation(g,{userProfile:Object.assign(Object.assign({},D),{nick:I,avatar:E})})}_updateMessageListDueToModify(n){const{conversationID:g}=n,{isUpdated:I,message:E}=me.message.messageDataHandler.modifyConversationMessage(g,n);I===!0&&me.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[E]}),me.notificationCenter.emitInnerEvent("ModifyMessageSuccess",n),Wm(g,n)}_handleC2CMessageModify(n){n.C2cMsgModNotifys.forEach(g=>{var I;const E=Jr.CONV_C2C;let m=qm(g);const{to:D,from:M}=m;let T=`${E}${D}`;D===((I=me.store.get("login"))===null||I===void 0?void 0:I.userId)&&(T=`${E}${M}`),m=Object.assign({conversationType:E,conversationID:T},m),this._updateMessageListDueToModify(m)})}_dispose(){const{notificationCenter:n}=me,{InnerEventSubType:g}=n;me.notificationCenter.unSubscribeInnerEvent(so.MESSAGE_PUSH,g.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),me.notificationCenter.unSubscribeInnerEvent(so.MESSAGE_PUSH,g.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),me.notificationCenter.unSubscribeInnerEvent(so.DESTROY,this._dispose,this)}}class _h{init(){const{notificationCenter:n}=me,{InnerEventSubType:g}=n;ws.getInstance().registerWorkflowStep(Pt.RECEIVE_GROUP_NEW_MESSAGE,Ht.HANDLE_GROUP_NEW_MESSAGE,this._handleGroupMessagePush,this),ws.getInstance().registerWorkflowStep(Pt.RECEIVE_GROUP_NEW_MESSAGE,Ht.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(Pt.RECEIVE_GROUP_NEW_MESSAGE,n)}_handleGroupMessagePush(n){const g=n.data||{},{messageDataHandler:I}=me.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;I.isMessageSentByCurrentInstance(T)?T.isModified=P:P=!1,T._onlineOnlyFlag?I.isMessageSentByCurrentInstance(T)||E.push(T):SB(T)&&I.storeConversationMessage(T)&&(E.push(T),Ap({conversationUpdateFields:m,message:T}))}),{conversationUpdateFieldList:[...m.values()],messages:E}}_emitMessageEvents(n){var g;const{messages:I}=((g=n.result)===null||g===void 0?void 0:g[Ht.HANDLE_GROUP_NEW_MESSAGE])||{},E=I?.filter(D=>D?.isModified===!0)||[];E.length>0&&me.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:E});const m=I?.filter(D=>!D?.isModified)||[];m.length>0&&me.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:m})}_generateGroupMessage(n){const g=Jr.CONV_GROUP,I=ND(n),E=me.message.messageFactory.createMessage(Object.assign(Object.assign({},I),{conversationType:g,flow:Ku.IN})),{elements:m}=I;return E.setElement(m),E}updateMessageProfile(n){var g;const{messageDataHandler:I}=me.message||{},E=(g=me.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=I.getLatestMsgSentByMe(T);!W||D===W.nick&&M===W.avatar||I.updateNickAndAvatarOfSentMessage({conversationID:T,latestNick:D,latestAvatar:M,isSentByMe:!0})}else if(m===ko.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:I,message:E}=me.message.messageDataHandler.modifyConversationMessage(g,n);I===!0&&me.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[E]}),Wm(g,n)}_handleGroupMessageModify(n){n.GroupMsgModNotifys.forEach(g=>{const I=Jr.CONV_GROUP;let E=GD(g);const{topicID:m,groupID:D}=E,M=m||D,T=`${I}${M}`;E=Object.assign({conversationType:I,conversationID:T,to:M},E),this._updateMessageListDueToModify(E)})}_dispose(){const{notificationCenter:n}=me,{InnerEventSubType:{GROUP_REALTIME_MESSAGE:g,GROUP_MESSAGE_MODIFIED:I}}=n;n.unSubscribeInnerEvent(so.MESSAGE_PUSH,g,this._handleGroupMessagePush,this),n.unSubscribeInnerEvent(so.MESSAGE_PUSH,I,this._handleGroupMessageModify,this),n.unSubscribeInnerEvent(so.DESTROY,this._dispose,this)}_canExecuteReceiverNewMessageWorkFlow(n){var g,I;const{GroupId:E,GroupType:m}=((I=(g=n?.GroupMsgArray)===null||g===void 0?void 0:g[0])===null||I===void 0?void 0:I.GroupInfo)||{},D=m===ka.GRP_AVCHATROOM;return!(!WQ.getGroup(E)&&D)}}var FD=new class{constructor(){this.c2cMessageReceiver=new wh,this.groupMessageReceiver=new _h}init(){this.c2cMessageReceiver.init(),this.groupMessageReceiver.init()}};const hR={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)}}},_T={createCustomMessage:!0,sendMessage:!0,modifyMessage:!0};var TT=new class{constructor(){this._historyMessageListFetchAnchors=new Map,this.completedHistoryConversations=new Set}getGroupRoamingMessagesByAnchor(s){return mA(this,void 0,void 0,function*(){try{const{conversationID:n,count:g,direction:I,sequence:E,messageSequenceList:m,shouldMarkCompleted:D=!1,getType:M}=s,T=n.replace(ba.CONV_GROUP,""),P=[];let W=E;if(I===qc.BACKWARD){if(typeof E!="number")return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};W=E+g-1}const iA=yield Rh({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:${I} complete:${kA} nextSequence:${RA} remoteMsgCount:${EA.length} invisibleSequenceList:${xA}`,SA=[];for(let re=0;re=E),OA&&D&&this.completedHistoryConversations.add(n);const JA=DB(SA);return me.ssoLog.info("getGroupRoamingMessagesByAnchor",LA),{messageList:JA,invisibleSequenceList:xA,nextReqMessageIDFromServer:RA,hasNoMoreHistoryMessage:OA,serverGroupTipList:P}}}catch(n){const{errorCode:g,errorInfo:I}=n||{};throw new gs({code:g,message:I})}})}clearHistoryMessageListFetchAnchors(s){this._historyMessageListFetchAnchors.delete(s)}isHistoryMessageFetchCompleted(s){return this.completedHistoryConversations.has(s)}_parseMessage(s){var n;const g=ba.CONV_GROUP;s.Event===4&&(s.MsgBody.MsgType=ko.MSG_GRP_TIP);const I=ND(s),E=Jm.createMessage(Object.assign(Object.assign({},I),{conversationType:g,flow:"in"}));return fB(((n=I.elements)===null||n===void 0?void 0:n.content)||{},E),E.setElement(I.elements),E}getC2CRoamingMessagesByAnchor(s){return mA(this,void 0,void 0,function*(){var n;try{const{conversationID:g,count:I,messageID:E,time:m,direction:D,shouldMarkCompleted:M=!1}=s;let T=m,P="";if(!m){const EA=E?me.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(ba.CONV_C2C,""),iA=yield Km({count:I,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 re=0;re{const{tag:E,value:m}=I;E&&E.indexOf(PD)>-1?g.profileCustomField.push({key:E,value:m}):Rd.has(E)&&(g[Rd.get(E)]=m)}),Object.assign(Object.assign({},zm),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:Ol[g.toUpperCase()],value:s[g]})}),s.profileCustomField&&B(s.profileCustomField)&&s.profileCustomField.forEach(g=>{n.push({tag:g.key,value:g.value})}),n}normalizeProfileFields(s){const n={},g=[];return s.forEach(I=>{const{tag:E,value:m}=I;if(E&&E.indexOf(PD)>-1&&g.push({key:E,value:m}),Rd.has(E)&&m!==void 0){const D=Rd.get(E);n[D]=m}}),g.length>0&&(n.profileCustomField=g),n}};const{generateProtocolData:QR}=me.common;function pR(s){return mA(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 I=QR({servcmd:n,data:g}),E=`${I.head.seq}${n}`,m=yield me.channel.sendPacket(I,{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,re=ju.parseProfileItem(JA);EA.push({userId:kA,customSequence:xA,resultCode:LA,resultInfo:SA,standardSequence:OA,profileItem:re})}),{actionStatus:M,errorCode:T,errorDisplay:P,errorInfo:W,userProfile:EA}}(m)})}function PE(s){return rc.getFriendMap().has(s)}const{isEmpty:YD}=me.utils;class Zm{constructor(){this._strangerProfileMap=new Map}init(){dr.getInstance().registerApi({apiName:"getMyProfile",context:this}),dr.getInstance().registerApi({apiName:"getUserProfile",context:this}),dr.getInstance().registerApi({apiName:"updateMyProfile",context:this}),this.createProfile=ju.createProfile.bind(ju);const{notificationCenter:n}=me;ws.getInstance().registerWorkflowStep(Pt.SYNC_SERVER_INFO_AFTER_LOGIN,Ht.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 mA(this,void 0,void 0,function*(){try{const n=Ar(),g=yield pR([n]);if(g){const I=this._handleProfileFormResponse(g)[0];return rc.getUserProfileMap().set(n,I),{code:0,data:I}}}catch(n){const{errorCode:g,errorInfo:I}=n;throw new gs({functionName:"getMyProfile",code:g,message:I})}})}getUserProfile(n){return mA(this,void 0,void 0,function*(){try{let{userIDList:g}=n;const{userIdListToRequest:I,profileFromCache:E}=this._filterRequestAndCacheUsers(g);if(I.length===0)return{code:0,data:E,successLog:{message:`userIDList.length:${g.length}`}};I.length>BR&&(me.ssoLog.warn("getUserProfile","userIdListToRequest.length > 1000"),I.length=BR);const{data:m,error:D}=yield this._batchFetchUserProfiles(I),M=I.length,T=m.length,P=M-T;if(E.length===0&&M===P&&!YD(D))throw D;if(B(m))return m.forEach(iA=>{PE(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 mA(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 mA(this,void 0,void 0,function*(){const g=Ar(),I={};for(const m in n)n[m]!==void 0&&(I[m]=n[m]);const E=ju.convertParamsToProfile(I);try{yield function(P){return mA(this,void 0,void 0,function*(){const W="profile.portrait_set",iA=QR({servcmd:W,data:P}),EA=`${iA.head.seq}${W}`,RA=yield me.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),I):ju.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: ${me.utils.safeStringify(E)}`}}}catch(m){const{errorCode:D,errorInfo:M}=m;throw new gs({functionName:"updateMyProfile",code:D,message:M,moreMessage:`params: ${me.utils.safeStringify(n)}`})}})}updateMyNickAndAvatar(n){return mA(this,void 0,void 0,function*(){const g=Ar(),I=Date.now(),E=rc.getUserProfile(g);let m={};m=E?Object.assign(E,n):ju.createProfile(g,n),m.lastUpdatedTime=I,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:ju.parseProfileList(T)}}(n.ProfileDataMod[0]);if(YD(g))return;const{isProfileUpdated:I,profile:E}=this._handleProfileModified(g);I&&this._emitProfileUpdated(E)}_emitProfileUpdated(n){me.notificationCenter.emitInnerEvent(so.PROFILE_UPDATE,{name:so.PROFILE_UPDATE,data:[n]}),me.notificationCenter.emitOuterEvent(yr.PROFILE_UPDATED,{name:yr.PROFILE_UPDATED,data:[n]}),yB.updateConversation(`C2C${n?.userID}`,{userProfile:n})}_dispose(){const{notificationCenter:n}=me;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:I}=n,E=rc.getUserProfile(g);if(!(Ar()===g||PE(g)&&E))return{isProfileUpdated:!1,profile:null};const m=ju.normalizeProfileFields(I),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=[],I=[];return n.forEach(E=>{const m=rc.getUserProfileMap().has(E);PE(E)&&m?I.push(rc.getUserProfile(E)):this._isStrangerAndProfileValid(E)?I.push(this._strangerProfileMap.get(E)):g.push(E)}),{userIdListToRequest:g,profileFromCache:I}}_handleProfileFormResponse(n){const{userProfile:g}=n;if(!Array.isArray(g))return[];const I=g.filter(m=>m.userId!=="@TLS#NOT_FOUND"&&m.userId!==""&&!YD(m.profileItem)),E=Date.now();return I.map(m=>{const D=ju.createProfile(m.userId,m.profileItem);return D.lastUpdatedTime=E,D})}_isStrangerAndProfileValid(n){var g;if(!PE(n)){const{lastUpdatedTime:I=0}=this._strangerProfileMap.get(n)||{},E=((g=me.store.get("cloudConfig"))===null||g===void 0?void 0:g.stranger_profile_expiration_time)||6e5;return Date.now()-I<=E}return!1}_chunkUserIDList(n,g){return Array.from({length:Math.ceil(n.length/g)},(I,E)=>n.slice(E*g,(E+1)*g))}_batchFetchUserProfiles(n){return mA(this,void 0,void 0,function*(){const g=[],I=[];let E={};return this._chunkUserIDList(n,100).forEach(m=>{g.push(pR(m))}),(yield Promise.allSettled(g)).forEach(m=>{if(m.status==="fulfilled"){const D=m.value,M=this._handleProfileFormResponse(D);B(M)&&I.push(...M)}else if(m.status==="rejected"){const{code:D,message:M}=m.reason||{};E={errorCode:D,message:M}}}),{data:I,error:E}})}_isCustomFieldChanged(n=[],g=[]){if(!B(g)||g.length===0)return!1;if(!B(n)||n.length===0)return!0;const I=new Map(n.map(E=>[E.key,E.value]));return g.some(E=>I.get(E.key)!==E.value)}_mergeProfileCustomField(n=[],g=[]){const I=B(n)?n.map(E=>Object.assign({},E)):[];return B(g)&&g.length!==0&&g.forEach(({key:E,value:m})=>{const D=I.find(M=>M.key===E);D?D.value=m:I.push({key:E,value:m})}),I}_reset(){rc.getUserProfileMap().clear(),this._strangerProfileMap.clear()}}const Xm=new Map,VD=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let s=0,n=VD.length;s>(-2*m&6)):0)E="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(E);try{return decodeURIComponent(escape(g))}catch(I){return console.warn(I),""}}const{isEmpty:GT}=me.utils,{generateProtocolData:$m}=me.common;function mR(s){return mA(this,void 0,void 0,function*(){const n="im_open_status.ws_get_user_status",g=$m({servcmd:n,data:{To_Account:s}}),I=`${g.head.seq}${n}`,E=yield me.channel.sendPacket(g,{requestId:I});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:tp(xA),onlineDevices:bT(LA)}}),iA=T.map(EA=>{const{To_Account:RA,Invalid_Account:kA,ErrorCode:xA,ErrorInfo:LA}=EA;return{userID:GT(kA)?RA:kA,code:xA,message:LA}});return{errorCode:D,errorInfo:M,successUserList:W,failureUserList:iA}}(E)})}function bT(s){const n=[];return s?.forEach(g=>{const{Platform:I,Status:E}=g;E==="Online"&&n.push(I)}),n}class kT{constructor(){this._customStatus=""}init(){const{notificationCenter:n}=me;dr.getInstance().registerApi({apiName:"getUserStatus",context:this}),dr.getInstance().registerApi({apiName:"setSelfStatus",context:this}),dr.getInstance().registerApi({apiName:"subscribeUserStatus",context:this}),dr.getInstance().registerApi({apiName:"unsubscribeUserStatus",context:this}),ws.getInstance().registerWorkflowStep(Pt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Ht.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 mA(this,void 0,void 0,function*(){const g=Ar(),{customStatus:I}=n;try{return yield function(E){return mA(this,void 0,void 0,function*(){const m="im_open_status.ws_set_custom_status",D=$m({servcmd:m,data:{CustomStatus:E}}),M=`${D.head.seq}${m}`,T=yield me.channel.sendPacket(D,{requestId:M});if(T){const{ErrorCode:P,ErrorInfo:W}=T;return{errorCode:P,errorInfo:W}}})}(I),this._customStatus=I,{code:0,data:{userID:g,statusType:Th,customStatus:I},successLog:{message:`customStatus: ${I}`}}}catch(E){const{errorCode:m,errorInfo:D}=E;throw new gs({functionName:"setSelfStatus",code:m,message:D})}})}getUserStatus(n){return mA(this,void 0,void 0,function*(){const{userIDList:g=[]}=n;if(this._isOnlyMeInArray(g))return this._getMyStatus();const I=yield this._getUserStatus(g);return Object.assign(Object.assign({},I),{successLog:{message:`userIDList length: ${g.length}`}})})}setCustomStatus(n){const g=tp(n);this._customStatus=g}subscribeUserStatus(n){return mA(this,void 0,void 0,function*(){try{const{userIDList:g=[]}=n;this._checkBusinessCapabilityBits("subscribeUserStatus");const I=this._getMaxUserCount("subscribe"),E=this._sliceUserIDList(g,I),m=yield function(M){return mA(this,void 0,void 0,function*(){const{channel:T}=me,P="im_open_status.ws_status_subscribe",W=$m({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:I}=g;throw new gs({functionName:"subscribeUserStatus",code:I})}})}unsubscribeUserStatus(n){return mA(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("unsubscribeUserStatus");const{userIDList:g=[]}=n,I=this._getMaxUserCount("unsubscribe"),E=this._sliceUserIDList(g,I),m=yield function(M){return mA(this,void 0,void 0,function*(){const{channel:T}=me,P="im_open_status.ws_status_unsubscribe";let W={};W=M.length===0?{UnsubscribeAll:1}:{To_Account:M};const iA=$m({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:I}=g;throw new gs({functionName:"unsubscribeUserStatus",code:I})}})}_onUserStatusUpdate(n){const{UserStatusList:g=[]}=n||{},I=g.map(E=>{const{To_Account:m,Status:D,CustomStatus:M,Platform:T}=E,P={userID:m,statusType:D,customStatus:tp(M)};return T&&(P.onlineDevices=T),P});this._emitUserStatusUpdatedEvent(I)}_onReOnline(n){const g=tp(n.data.customStatus);if(this._customStatus===g)return;this._customStatus=g;const I={userID:Ar(),statusType:Th,customStatus:g};this._emitUserStatusUpdatedEvent(I)}_emitUserStatusUpdatedEvent(n){me.notificationCenter.emitOuterEvent(yr.USER_STATUS_UPDATED,{name:yr.USER_STATUS_UPDATED,data:n})}_sliceUserIDList(n,g){return n.slice(0,g)}_parseResponse(n){const{ErrorList:g=[]}=n;return g.map(I=>{const{To_Account:E,Invalid_Account:m,ErrorCode:D,ErrorInfo:M}=I;return{userID:me.utils.isEmpty(m)?E:m,code:D,message:M}})}_checkBusinessCapabilityBits(n){if(!me.store.get("commercialConfig").get(NT))throw new gs({functionName:n,code:ua.NO_USE,replacement1:n})}_getMaxUserCount(n){const g=me.store.get("cloudConfig")||{},I={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}=I[n],D=g[E]||m;return parseInt(D,10)}_getMyStatus(){return{code:0,data:{successUserList:[{userID:Ar(),statusType:Th,customStatus:this._customStatus}],failureUserList:[]}}}_getUserStatus(n){return mA(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("getUserStatus");const g=this._getMaxUserCount("query"),I=this._sliceUserIDList(n,g),E=yield mR(I),{successUserList:m,failureUserList:D}=E||{};return{code:0,data:{successUserList:m,failureUserList:D}}}catch(g){const{errorCode:I}=g;throw new gs({functionName:"getUserStatus",code:I})}})}_isOnlyMeInArray(n){const g=Ar();return n.length===1&&n.indexOf(g)>-1}_dispose(){const{notificationCenter:n}=me;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 JD={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(PD))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}}},LT={getMyProfile:!0,getUserProfile:!0,updateMyProfile:!0,setSelfStatus:!0,getUserStatus:!0,subscribeUserStatus:!0,unsubscribeUserStatus:!0};class UT{constructor(){this.userProfile=new Zm,this.userStatus=new kT,this.userProfile.init(),this.userStatus.init(),jc({auth:LT,params:JD})}}function HD(s){const n=[];if(!l(s))return n;const g=s.length;if(g===0)return n;for(let I=g-1;I>=0;I--)s[I]==="1"&&n.push(2**(g-I-1));return n}var wd,yC,_d;(function(s){s.NOT_START="notStart",s.PENDING="pending",s.RESOLVED="resolved",s.REJECTED="rejected"})(wd||(wd={})),function(s){s[s.C2C=1]="C2C",s[s.GROUP=2]="GROUP"}(yC||(yC={})),function(s){s[s.C2C=8]="C2C",s[s.GROUP=2]="GROUP"}(_d||(_d={}));class qD{constructor(){this._name="SyncConversationHandler",this._pagingStatus=wd.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}init(){const{notificationCenter:n}=me;ws.getInstance().registerWorkflowStep(Pt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Ht.CONVERSATION_RECOVER,this._syncConversationList,this),ws.getInstance().registerWorkflowStep(Pt.SYNC_SERVER_INFO_AFTER_LOGIN,Ht.CONVERSATION_LIST_SYNC,this._syncConversationListAfterLogin,this),n.subscribeInnerEvent(so.LOGOUT,this._reset,this),n.subscribeInnerEvent(so.DESTROY,this._dispose,this),me.ssoLog.debug(`${this._name}.init`)}isSyncCompleted(){return this._pagingStatus===wd.RESOLVED}_syncConversationListAfterLogin(){return mA(this,void 0,void 0,function*(){return this._pagingStatus=wd.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0,this._syncConversationList()})}_syncConversationList(){return mA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g}}=me;n.debug("_syncConversationList","start");try{const I=yield this._pagingGetConversationList(!0);this._pagingStatus=wd.RESOLVED;const{conversationList:E=[]}=I||{};return n.info("_syncConversationList",`success count:${E.length}`),I}catch(I){const E=new gs(I);n.error("_syncConversationList",`fail ${g(I)}`,{error:E})}})}_pagingGetConversationList(n){return mA(this,void 0,void 0,function*(){try{const g=[];this._pagingStatus=wd.PENDING;const I=yield function(iA){return mA(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}=I||{};let W=[];if(E===1&&(this._pagingStatus=wd.RESOLVED),m.length>0&&(W=this._getConversationOptions(m),g.push(...W)),me.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}}=me,I=this._convertConversationKey(n);return this._filterValidConversations(I).map(E=>(g(E.lastMsg)&&(E.lastMsg={elements:[]}),E.type===yC.C2C?this._assembleC2COption(E):this._assembleGroupOption(E)))}_filterValidConversations(n){return n.filter(({type:g,userID:I})=>g===yC.C2C&&!function(E){let m;return E.startsWith(ko.CONV_C2C)&&(m=E.replace(ko.CONV_C2C,"")),m==="@TLS#ERROR"||m==="@TLS#NOT_FOUND"}(I)||g===2)}_assembleC2COption(n){var g,I,E,m,D,M,T,P;const W=this._createUserprofile(n);return{conversationID:`${ko.CONV_C2C}${n.userID}`,type:ko.CONV_C2C,lastMessage:{lastTime:n.time,lastSequence:n.sequence,fromAccount:n.lastC2CMsgFromAccount,type:!((g=n.lastMsg)===null||g===void 0)&&g.elements[0]?(I=n.lastMsg)===null||I===void 0?void 0:I.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===_d.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:HD(n.standardMark),conversationGroupList:[],remark:n.friendRemark||"",messageRemindType:this._transMsgRemindType(n.messageRemindType)}}_createUserprofile(n){var g;const{userID:I,nick:E,peerAvatar:m}=n,D=[{tag:"Tag_Profile_IM_Nick",value:E},{tag:"Tag_Profile_IM_Image",value:m}];return(g=me.user.userProfile)===null||g===void 0?void 0:g.createProfile(I,D)}_computeIsPeerRead(n){const g=Ar(),{lastC2CMsgFromAccount:I,time:E,c2cPeerReadTime:m}=n;return I===g&&E<=m}_assembleGroupOption(n){var g,I,E,m,D;return{conversationID:`${ko.CONV_GROUP}${n.groupID}`,type:ko.CONV_GROUP,lastMessage:Object.assign(Object.assign({lastTime:n.time,lastSequence:n.sequence,fromAccount:n.msgGroupFromAccount},this._patchTypeAndPayload(n)),{cloudCustomData:((E=(I=(g=n.lastMsg)===null||g===void 0?void 0:g.elements)===null||I===void 0?void 0:I[0])===null||E===void 0?void 0:E.cloudCustomData)||"",isRevoked:n.lastMessageFlag===_d.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:HD(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,I,E;const{utils:{isEmpty:m}}=me;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=ko.MSG_GRP_TIP,M=Object.assign(Object.assign({},this._parseContent(D,n.GroupTips.MsgBody)),{groupProfile:{from:T,groupName:P}})}return n.MsgBody&&(D=(I=n.MsgBody[0])===null||I===void 0?void 0:I.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 I;if(!g)return g;const E=me.message.messageFactory.getElementClass(n);return E?(I=E.parseServerPushElement(g))===null||I===void 0?void 0:I.content:g}_amendLayersOverLimitProp(n){const{LayersOverLimit:g}=n;return yo(n,["LayersOverLimit"]).layersOverLimit=g===1,n}_transMsgRemindType(n){let g="";return n===0?g=ko.MSG_REMIND_ACPT_AND_NOTE:n===1?g=ko.MSG_REMIND_DISCARD:n===2?g=ko.MSG_REMIND_ACPT_NOT_NOTE:n===3&&(g=ko.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),g}_patchTypeAndPayload(n){var g;const{utils:{isUndefined:I}}=me,{event:E,elements:m=[]}=n.lastMsg||{};return I(E)?{type:m[0]?m[0].type:null,payload:m[0]?this._amendLayersOverLimitProp(m[0].content):null}:{type:ko.MSG_GRP_TIP,payload:((g=m?.[0])===null||g===void 0?void 0:g.content)||{}}}_computeGroupUnreadCount(n){const{unreadCount:g=0,noUnreadCount:I=0}=n,E=g-I;return E>0?E:0}_reset(){this._pagingStatus=wd.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}_dispose(){this._reset();const{notificationCenter:n}=me;n.unSubscribeInnerEvent(so.LOGOUT,this._reset,this),n.unSubscribeInnerEvent(so.DESTROY,this._dispose,this)}}class KD{constructor(){this.syncConversationHandler=new qD,this.syncConversationHandler.init()}}console.log(`TencentCloudLiteChat.VERSION:${Wr}`);var jD={create:function(s){var n,g;const{SDKAppID:I,testEnv:E=!1,devMode:m=!1,unlimitedAVChatRoom:D=!1,scene:M="",oversea:T=!1,instance:P,disableIndependentDomain:W=!1,proxyServer:iA=""}=s;let EA=I;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),Ea.has(EA))return Ea.get(EA);let RA=null;if(P)RA=P,RA._workflowManager&&ws.setInstance(RA._workflowManager),RA._pluginManager&&RA._pluginManager.installBuiltInPlugin(mB),P.isReady()&&((g=(n=ws.getInstance()).executeWorkflow)===null||g===void 0||g.call(n,Pt.SYNC_SERVER_INFO_AFTER_LOGIN));else{const kA=function(){function re(){return(65536*(1+Math.random())|0).toString(16).substring(1)}return`${re()+re()}${re()}${re()}${re()}${re()}${re()}${re()}`}();me.init({sdkAppId:EA,instanceId:kA,testEnv:E,devMode:m,unlimitedAVChatRoom:D,disableIndependentDomain:W,scene:M,oversea:T,sdkEdition:Vm,version:Wr,proxyServer:iA}),ws.getInstance().init(),me.message=new OD,me.user=new UT,me.login=new Sh,me.conversation=new KD,tu.getInstance().installBuiltInPlugin(mB),RA=dr.getInstance().exposeApiForClient(),RA._workflowManager=ws.getInstance(),RA._pluginManager=tu.getInstance();const{utils:{IS_WORKER_AVAILABLE:xA,USER_AGENT:LA,getPlatformType:SA,isIOSWebView:OA}}=me,JA=`instanceID:${kA} SDKAppID:${I} platform:${HA} host:${SA()} isIOSWebView:${OA} workerAvailable:${xA} UserAgent:${LA}`;me.ssoLog.info("sdkConstruct",JA)}return Ea.set(EA,RA),RA},TSignaling:Hc,EVENT:yr,VERSION:Wr,TYPES:ko};return jD})}(S1)),S1.exports}var XiA=ZiA();const tg=F3(XiA);var M1={exports:{}},$iA=M1.exports,Qz;function AoA(){return Qz||(Qz=1,function(t,i){(function(r,l){t.exports=l()})($iA,function(){function r(ge,qe){if(!(ge instanceof qe))throw new TypeError("Cannot call a class as a function")}function l(ge,qe){for(var ft=0;ft"u"&&typeof uni.requireNativePlugin=="function",WA=TA&&uni.getDeviceInfo().platform.toLocaleLowerCase()==="ios",zA=(TA&&uni.getDeviceInfo().platform.toLocaleLowerCase(),IA||rA||pA||lA||cA||TA),$A=F!==void 0&&(F.nativeModuleProxy!==void 0||F.ReactNative!==void 0),De=rA?qq:pA?tt:lA?swan:cA?my:IA?wx:TA?uni:{},Ce=function(ge){if(k(ge)!=="object"||ge===null)return!1;var qe=Object.getPrototypeOf(ge);if(qe===null)return!0;for(var ft=qe;Object.getPrototypeOf(ft)!==null;)ft=Object.getPrototypeOf(ft);return qe===ft};function ct(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(Ce(ge)){for(var qe in ge)if(Object.prototype.hasOwnProperty.call(ge,qe))return!1;return!0}return!1}var mt=function(){return u(function ge(){r(this,ge),this._n="WebRequest"},[{key:"request",value:function(ge,qe){var ft=this,ni="".concat(this._n,".request"),Vt=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(ni," URL:").concat(Fi)),ge.qs){var _o=function(ki){var ns=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"&",Ko=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"=";return ct(ki)?"":Ce(ki)?Object.keys(ki).map(function($i){var jt=encodeURIComponent($i)+Ko;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}(ge.qs);_o&&(Fi+="".concat(Fi.indexOf("?")===-1?"?":"&").concat(_o))}var to=new XMLHttpRequest;to.open(gi,Fi,!0),to.responseType=ge.dataType||"text";var uo=ge.headers||{};if(ge.uploadByIP&&(uo=w(w({},uo),{},{host:ge.uploadIP})),!ct(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)qe(null,ft._xhrRes(to,ft._xhrBody(to,Vt,ge.uploadByIP&&ge.uploadIP),uo));else{if(ge.uploadIP&&ge.url.indexOf(ge.uploadIP)===-1)return ge.url=function(ns,Ko){return ns.replace(/^http(s)?:\/\/(.*?)\//,"https://".concat(Ko,"/"))}(ge.url,ge.uploadIP),ge.uploadByIP=!0,ft.request(ge,qe);var ki={code:to.status,message:JSON.stringify(to.responseText)};qe(ki,ft._xhrRes(to,ft._xhrBody(to,Vt,ge.uploadByIP&&ge.uploadIP),uo))}},to.onerror=function(ki){var ns=ft._xhrBody(to,Vt,ge.uploadByIP&&ge.uploadIP),Ko={code:to.status,message:JSON.stringify(to.responseText)};ns||to.statusText||to.status!==0||(ki.message="CORS blocked or network error"),qe(Ko,ft._xhrRes(to,ns)),Ko=null},ge.onProgress&&to.upload&&(to.upload.onprogress=function(ki){var ns=ki.total,Ko=ki.loaded,$i=Math.floor(100*Ko/ns);ge.onProgress({total:ns,loaded:Ko,percent:($i>=100?100:$i)/100})}),to.send(ge.resources),to}},{key:"_xhrRes",value:function(ge,qe){var ft={};return ge.getAllResponseHeaders().trim().split(`
+`).forEach(function(ni){if(ni){var Vt=ni.indexOf(":"),gi=ni.substr(0,Vt).trim().toLowerCase(),Fi=ni.substr(Vt+1).trim();ft[gi]=Fi}}),{statusCode:ge.status,statusMessage:ge.statusText,headers:ft,data:qe}}},{key:"_xhrBody",value:function(ge,qe,ft){return ge.status===200&&qe?{location:qe,uploadIP:ft}:{response:ge.responseText,uploadIP:ft}}}])}(),Ke=["unknown","image","video","audio","log"],Dt=["name"],qt=function(){return u(function ge(){r(this,ge)},[{key:"request",value:function(ge,qe){var ft=this,ni=ge.resources,Vt=ni===void 0?"":ni,gi=ge.headers,Fi=gi===void 0?{}:gi,_o=ge.url,to=ge.downloadUrl,uo=to===void 0?"":to,Vs=_o,ki=null,ns=uo.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/),Ko=decodeURIComponent(ns[3]),$i=Ko.indexOf("?")>-1?Ko.split("?")[0]:Ko,jt={key:ge.fileKey?ge.fileKey:$i,success_action_status:200,"Content-Type":""},io={};if(WA){var bi=_o.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:Vt,formData:w(w({},jt),io),timeout:ge.timeout||3e5};if(cA){var le=HA;le.name,HA=w(w({},function(xe,Lt){if(xe==null)return{};var it,gt,Xt=function(be,je){if(be==null)return{};var Mt={};for(var Rt in be)if({}.hasOwnProperty.call(be,Rt)){if(je.includes(Rt))continue;Mt[Rt]=be[Rt]}return Mt}(xe,Lt);if(Object.getOwnPropertySymbols){var $t=Object.getOwnPropertySymbols(xe);for(gt=0;gt<$t.length;gt++)it=$t[gt],Lt.includes(it)||{}.propertyIsEnumerable.call(xe,it)&&(Xt[it]=xe[it])}return Xt}(le,Dt)),{},{fileName:"file",fileType:Ke[ge.fileType]})}return(ki=De.uploadFile(w(w({},HA),{},{success:function(xe){ft._handleResponse({response:xe,downloadUrl:uo,callback:qe})},fail:function(xe){ft._handleResponse({response:xe,downloadUrl:uo,callback:qe})}}))).onProgressUpdate&&ki.onProgressUpdate(function(xe){ge.onProgress&&ge.onProgress({total:xe.totalBytesExpectedToSend,loaded:xe.totalBytesSent,percent:Math.floor(xe.progress)/100})}),ki}},{key:"_handleResponse",value:function(ge){var qe=ge.downloadUrl,ft=ge.response,ni=ge.callback,Vt=ft.header,gi={};if(Vt)for(var Fi in Vt)Vt.hasOwnProperty(Fi)&&(gi[Fi.toLowerCase()]=Vt[Fi]);var _o=+ft.statusCode;_o===200?ni(null,{statusCode:_o,headers:gi,data:w(w({},ft.data),{},{location:qe})}):ni({code:_o,message:JSON.stringify(ft.data)},{statusCode:_o,headers:gi,data:void 0})}}])}(),It=function(){return u(function ge(){r(this,ge)},[{key:"request",value:function(ge,qe){var ft=this,ni=ge.resources,Vt=ni===void 0?"":ni,gi=ge.fileKey,Fi=gi===void 0?"":gi,_o=ge.url,to=ge.downloadUrl,uo=to===void 0?"":to,Vs=new FormData;Vs.append("key",Fi),Vs.append("success_action_status",200),Vs.append("file",{uri:Vt,type:"application/octet-stream",name:"uploaded_file"}),fetch(_o,{method:"POST",headers:{"Content-Type":"multipart/form-data"},body:Vs}).then(function(ki){ft._handleResponse({response:ki,downloadUrl:uo,callback:qe})}).catch(function(ki){ft._handleResponse({response:ki,downloadUrl:uo,callback:qe})})}},{key:"_handleResponse",value:function(ge){var qe=ge.downloadUrl,ft=ge.response,ni=ge.callback,Vt=ft.headers,gi=ft.status,Fi=Vt&&Vt.map||{};gi===200?ni(null,{statusCode:200,headers:Fi,data:{location:qe}}):ni({code:gi,message:JSON.stringify(ft)},{statusCode:gi,headers:Fi,data:void 0})}}])}();return function(){return u(function ge(){r(this,ge),this.retry=1,this.tryCount=0,this.systemClockOffset=0,this.httpRequest=zA?new qt:$A?new It:new mt,console.log("TIMUploadPlugin.VERSION: ".concat("1.4.3"))},[{key:"uploadFile",value:function(ge,qe){var ft=this;return this.httpRequest.request(ge,function(ni,Vt){ni&&ft.tryCount=3e4&&(this.systemClockOffset=_o-Fi,qe=!0)}else Math.floor(ge.statusCode/100)===5&&(qe=!0)}return qe}}],[{key:"getVersion",value:function(){return"1.4.3"}}])}()})}(M1)),M1.exports}var eoA=AoA();const toA=F3(eoA);/**
* @vue/shared v3.5.13
* (c) 2018-present Yuxi (Evan) You and Vue contributors
* @license MIT
-**//*! #__NO_SIDE_EFFECTS__ */function Q3(t){const i=Object.create(null);for(const r of t.split(","))i[r]=1;return r=>r in i}const fa={},f_=[],CQ=()=>{},kiA=()=>!1,rY=t=>t.charCodeAt(0)===111&&t.charCodeAt(1)===110&&(t.charCodeAt(2)>122||t.charCodeAt(2)<97),p3=t=>t.startsWith("onUpdate:"),$l=Object.assign,m3=(t,i)=>{const r=t.indexOf(i);r>-1&&t.splice(r,1)},LiA=Object.prototype.hasOwnProperty,qr=(t,i)=>LiA.call(t,i),Ss=Array.isArray,y_=t=>aY(t)==="[object Map]",rZ=t=>aY(t)==="[object Set]",Xs=t=>typeof t=="function",mg=t=>typeof t=="string",nm=t=>typeof t=="symbol",Ta=t=>t!==null&&typeof t=="object",aZ=t=>(Ta(t)||Xs(t))&&Xs(t.then)&&Xs(t.catch),gZ=Object.prototype.toString,aY=t=>gZ.call(t),UiA=t=>aY(t).slice(8,-1),cZ=t=>aY(t)==="[object Object]",f3=t=>mg(t)&&t!=="NaN"&&t[0]!=="-"&&""+parseInt(t,10)===t,dL=Q3(",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"),gY=t=>{const i=Object.create(null);return r=>i[r]||(i[r]=t(r))},FiA=/-(\w)/g,KC=gY(t=>t.replace(FiA,(i,r)=>r?r.toUpperCase():"")),OiA=/\B([A-Z])/g,Yy=gY(t=>t.replace(OiA,"-$1").toLowerCase()),cY=gY(t=>t.charAt(0).toUpperCase()+t.slice(1)),_K=gY(t=>t?`on${cY(t)}`:""),Ny=(t,i)=>!Object.is(t,i),u1=(t,...i)=>{for(let r=0;r{Object.defineProperty(t,i,{configurable:!0,enumerable:!1,writable:l,value:r})},Sj=t=>{const i=parseFloat(t);return isNaN(i)?t:i},PiA=t=>{const i=mg(t)?Number(t):NaN;return isNaN(i)?t:i};let X5;const lY=()=>X5||(X5=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{});function hr(t){if(Ss(t)){const i={};for(let r=0;r{if(r){const l=r.split(YiA);l.length>1&&(i[l[0].trim()]=l[1].trim())}}),i}function Xi(t){let i="";if(mg(t))i=t;else if(Ss(t))for(let r=0;r!!(t&&t.__v_isRef===!0),Si=t=>mg(t)?t:t==null?"":Ss(t)||Ta(t)&&(t.toString===gZ||!Xs(t.toString))?uZ(t)?Si(t.value):JSON.stringify(t,EZ,2):String(t),EZ=(t,i)=>uZ(i)?EZ(t,i.value):y_(i)?{[`Map(${i.size})`]:[...i.entries()].reduce((r,[l,u],p)=>(r[TK(l,p)+" =>"]=u,r),{})}:rZ(i)?{[`Set(${i.size})`]:[...i.values()].map(r=>TK(r))}:nm(i)?TK(i):Ta(i)&&!Ss(i)&&!cZ(i)?String(i):i,TK=(t,i="")=>{var r;return nm(t)?`Symbol(${(r=t.description)!=null?r:i})`:t};/**
+**//*! #__NO_SIDE_EFFECTS__ */function O3(t){const i=Object.create(null);for(const r of t.split(","))i[r]=1;return r=>r in i}const fa={},__=[],yQ=()=>{},ioA=()=>!1,yY=t=>t.charCodeAt(0)===111&&t.charCodeAt(1)===110&&(t.charCodeAt(2)>122||t.charCodeAt(2)<97),P3=t=>t.startsWith("onUpdate:"),eI=Object.assign,x3=(t,i)=>{const r=t.indexOf(i);r>-1&&t.splice(r,1)},ooA=Object.prototype.hasOwnProperty,qr=(t,i)=>ooA.call(t,i),Ms=Array.isArray,T_=t=>DY(t)==="[object Map]",wZ=t=>DY(t)==="[object Set]",$s=t=>typeof t=="function",fg=t=>typeof t=="string",lm=t=>typeof t=="symbol",Ta=t=>t!==null&&typeof t=="object",_Z=t=>(Ta(t)||$s(t))&&$s(t.then)&&$s(t.catch),TZ=Object.prototype.toString,DY=t=>TZ.call(t),soA=t=>DY(t).slice(8,-1),NZ=t=>DY(t)==="[object Object]",Y3=t=>fg(t)&&t!=="NaN"&&t[0]!=="-"&&""+parseInt(t,10)===t,ML=O3(",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"),SY=t=>{const i=Object.create(null);return r=>i[r]||(i[r]=t(r))},noA=/-(\w)/g,eh=SY(t=>t.replace(noA,(i,r)=>r?r.toUpperCase():"")),roA=/\B([A-Z])/g,Wy=SY(t=>t.replace(roA,"-$1").toLowerCase()),MY=SY(t=>t.charAt(0).toUpperCase()+t.slice(1)),qK=SY(t=>t?`on${MY(t)}`:""),Oy=(t,i)=>!Object.is(t,i),v1=(t,...i)=>{for(let r=0;r{Object.defineProperty(t,i,{configurable:!0,enumerable:!1,writable:l,value:r})},Yj=t=>{const i=parseFloat(t);return isNaN(i)?t:i},aoA=t=>{const i=fg(t)?Number(t):NaN;return isNaN(i)?t:i};let pz;const vY=()=>pz||(pz=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{});function hr(t){if(Ms(t)){const i={};for(let r=0;r{if(r){const l=r.split(coA);l.length>1&&(i[l[0].trim()]=l[1].trim())}}),i}function Xi(t){let i="";if(fg(t))i=t;else if(Ms(t))for(let r=0;r!!(t&&t.__v_isRef===!0),Di=t=>fg(t)?t:t==null?"":Ms(t)||Ta(t)&&(t.toString===TZ||!$s(t.toString))?kZ(t)?Di(t.value):JSON.stringify(t,LZ,2):String(t),LZ=(t,i)=>kZ(i)?LZ(t,i.value):T_(i)?{[`Map(${i.size})`]:[...i.entries()].reduce((r,[l,u],B)=>(r[KK(l,B)+" =>"]=u,r),{})}:wZ(i)?{[`Set(${i.size})`]:[...i.values()].map(r=>KK(r))}:lm(i)?KK(i):Ta(i)&&!Ms(i)&&!NZ(i)?String(i):i,KK=(t,i="")=>{var r;return lm(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 Hd;class jiA{constructor(i=!1){this.detached=i,this._active=!0,this.effects=[],this.cleanups=[],this._isPaused=!1,this.parent=Hd,!i&&Hd&&(this.index=(Hd.scopes||(Hd.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(hL){let i=hL;for(hL=void 0;i;){const r=i.next;i.next=void 0,i.flags&=-9,i=r}}let t;for(;CL;){let i=CL;for(CL=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 BZ(t){for(let i=t.deps;i;i=i.nextDep)i.version=-1,i.prevActiveLink=i.dep.activeLink,i.dep.activeLink=i}function QZ(t){let i,r=t.depsTail,l=r;for(;l;){const u=l.prevDep;l.version===-1?(l===r&&(r=u),S3(l),ziA(l)):i=l,l.dep.activeLink=l.prevActiveLink,l.prevActiveLink=void 0,l=u}t.deps=i,t.depsTail=r}function Mj(t){for(let i=t.deps;i;i=i.nextDep)if(i.dep.version!==i.version||i.dep.computed&&(pZ(i.dep.computed)||i.dep.version!==i.version))return!0;return!!t._dirty}function pZ(t){if(t.flags&4&&!(t.flags&16)||(t.flags&=-17,t.globalVersion===kL))return;t.globalVersion=kL;const i=t.dep;if(t.flags|=2,i.version>0&&!t.isSSR&&t.deps&&!Mj(t)){t.flags&=-3;return}const r=Ra,l=Wh;Ra=t,Wh=!0;try{BZ(t);const u=t.fn(t._value);(i.version===0||Ny(u,t._value))&&(t._value=u,i.version++)}catch(u){throw i.version++,u}finally{Ra=r,Wh=l,QZ(t),t.flags&=-3}}function S3(t,i=!1){const{dep:r,prevSub:l,nextSub:u}=t;if(l&&(l.nextSub=u,t.prevSub=void 0),u&&(u.prevSub=l,t.nextSub=void 0),r.subs===t&&(r.subs=l,!l&&r.computed)){r.computed.flags&=-5;for(let p=r.computed.deps;p;p=p.nextDep)S3(p,!0)}!i&&!--r.sc&&r.map&&r.map.delete(r.key)}function ziA(t){const{prevDep:i,nextDep:r}=t;i&&(i.nextDep=r,t.prevDep=void 0),r&&(r.prevDep=i,t.nextDep=void 0)}let Wh=!0;const mZ=[];function Vy(){mZ.push(Wh),Wh=!1}function Jy(){const t=mZ.pop();Wh=t===void 0?!0:t}function $5(t){const{cleanup:i}=t;if(t.cleanup=void 0,i){const r=Ra;Ra=void 0;try{i()}finally{Ra=r}}}let kL=0;class ZiA{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 M3{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(!Ra||!Wh||Ra===this.computed)return;let r=this.activeLink;if(r===void 0||r.sub!==Ra)r=this.activeLink=new ZiA(Ra,this),Ra.deps?(r.prevDep=Ra.depsTail,Ra.depsTail.nextDep=r,Ra.depsTail=r):Ra.deps=Ra.depsTail=r,fZ(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=Ra.depsTail,r.nextDep=void 0,Ra.depsTail.nextDep=r,Ra.depsTail=r,Ra.deps===r&&(Ra.deps=l)}return r}trigger(i){this.version++,kL++,this.notify(i)}notify(i){y3();try{for(let r=this.subs;r;r=r.prevSub)r.sub.notify()&&r.sub.dep.notify()}finally{D3()}}}function fZ(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)fZ(l)}const r=t.dep.subs;r!==t&&(t.prevSub=r,r&&(r.nextSub=t)),t.dep.subs=t}}const T1=new WeakMap,$M=Symbol(""),vj=Symbol(""),LL=Symbol("");function lu(t,i,r){if(Wh&&Ra){let l=T1.get(t);l||T1.set(t,l=new Map);let u=l.get(r);u||(l.set(r,u=new M3),u.map=l,u.key=r),u.track()}}function em(t,i,r,l,u,p){const y=T1.get(t);if(!y){kL++;return}const w=_=>{_&&_.trigger()};if(y3(),i==="clear")y.forEach(w);else{const _=Ss(t),k=_&&f3(r);if(_&&r==="length"){const F=Number(l);y.forEach((j,lA)=>{(lA==="length"||lA===LL||!nm(lA)&&lA>=F)&&w(j)})}else switch((r!==void 0||y.has(void 0))&&w(y.get(r)),k&&w(y.get(LL)),i){case"add":_?k&&w(y.get("length")):(w(y.get($M)),y_(t)&&w(y.get(vj)));break;case"delete":_||(w(y.get($M)),y_(t)&&w(y.get(vj)));break;case"set":y_(t)&&w(y.get($M));break}}D3()}function XiA(t,i){const r=T1.get(t);return r&&r.get(i)}function A_(t){const i=Tr(t);return i===t?i:(lu(i,"iterate",LL),JC(t)?i:i.map(Iu))}function IY(t){return lu(t=Tr(t),"iterate",LL),t}const $iA={__proto__:null,[Symbol.iterator](){return GK(this,Symbol.iterator,Iu)},concat(...t){return A_(this).concat(...t.map(i=>Ss(i)?A_(i):i))},entries(){return GK(this,"entries",t=>(t[1]=Iu(t[1]),t))},every(t,i){return Kp(this,"every",t,i,void 0,arguments)},filter(t,i){return Kp(this,"filter",t,i,r=>r.map(Iu),arguments)},find(t,i){return Kp(this,"find",t,i,Iu,arguments)},findIndex(t,i){return Kp(this,"findIndex",t,i,void 0,arguments)},findLast(t,i){return Kp(this,"findLast",t,i,Iu,arguments)},findLastIndex(t,i){return Kp(this,"findLastIndex",t,i,void 0,arguments)},forEach(t,i){return Kp(this,"forEach",t,i,void 0,arguments)},includes(...t){return bK(this,"includes",t)},indexOf(...t){return bK(this,"indexOf",t)},join(t){return A_(this).join(t)},lastIndexOf(...t){return bK(this,"lastIndexOf",t)},map(t,i){return Kp(this,"map",t,i,void 0,arguments)},pop(){return Vk(this,"pop")},push(...t){return Vk(this,"push",t)},reduce(t,...i){return Az(this,"reduce",t,i)},reduceRight(t,...i){return Az(this,"reduceRight",t,i)},shift(){return Vk(this,"shift")},some(t,i){return Kp(this,"some",t,i,void 0,arguments)},splice(...t){return Vk(this,"splice",t)},toReversed(){return A_(this).toReversed()},toSorted(t){return A_(this).toSorted(t)},toSpliced(...t){return A_(this).toSpliced(...t)},unshift(...t){return Vk(this,"unshift",t)},values(){return GK(this,"values",Iu)}};function GK(t,i,r){const l=IY(t),u=l[i]();return l!==t&&!JC(t)&&(u._next=u.next,u.next=()=>{const p=u._next();return p.value&&(p.value=r(p.value)),p}),u}const AoA=Array.prototype;function Kp(t,i,r,l,u,p){const y=IY(t),w=y!==t&&!JC(t),_=y[i];if(_!==AoA[i]){const j=_.apply(t,p);return w?Iu(j):j}let k=r;y!==t&&(w?k=function(j,lA){return r.call(this,Iu(j),lA,t)}:r.length>2&&(k=function(j,lA){return r.call(this,j,lA,t)}));const F=_.call(y,k,l);return w&&u?u(F):F}function Az(t,i,r,l){const u=IY(t);let p=r;return u!==t&&(JC(t)?r.length>3&&(p=function(y,w,_){return r.call(this,y,w,_,t)}):p=function(y,w,_){return r.call(this,y,Iu(w),_,t)}),u[i](p,...l)}function bK(t,i,r){const l=Tr(t);lu(l,"iterate",LL);const u=l[i](...r);return(u===-1||u===!1)&&w3(r[0])?(r[0]=Tr(r[0]),l[i](...r)):u}function Vk(t,i,r=[]){Vy(),y3();const l=Tr(t)[i].apply(t,r);return D3(),Jy(),l}const eoA=Q3("__proto__,__v_isRef,__isVue"),yZ=new Set(Object.getOwnPropertyNames(Symbol).filter(t=>t!=="arguments"&&t!=="caller").map(t=>Symbol[t]).filter(nm));function toA(t){nm(t)||(t=String(t));const i=Tr(this);return lu(i,"has",t),i.hasOwnProperty(t)}class DZ{constructor(i=!1,r=!1){this._isReadonly=i,this._isShallow=r}get(i,r,l){if(r==="__v_skip")return i.__v_skip;const u=this._isReadonly,p=this._isShallow;if(r==="__v_isReactive")return!u;if(r==="__v_isReadonly")return u;if(r==="__v_isShallow")return p;if(r==="__v_raw")return l===(u?p?IoA:RZ:p?vZ:MZ).get(i)||Object.getPrototypeOf(i)===Object.getPrototypeOf(l)?i:void 0;const y=Ss(i);if(!u){let _;if(y&&(_=$iA[r]))return _;if(r==="hasOwnProperty")return toA}const w=Reflect.get(i,r,Xl(i)?i:l);return(nm(r)?yZ.has(r):eoA(r))||(u||lu(i,"get",r),p)?w:Xl(w)?y&&f3(r)?w:w.value:Ta(w)?u?qh(w):WM(w):w}}class SZ extends DZ{constructor(i=!1){super(!1,i)}set(i,r,l,u){let p=i[r];if(!this._isShallow){const _=av(p);if(!JC(l)&&!av(l)&&(p=Tr(p),l=Tr(l)),!Ss(i)&&Xl(p)&&!Xl(l))return _?!1:(p.value=l,!0)}const y=Ss(i)&&f3(r)?Number(r)t,H2=t=>Reflect.getPrototypeOf(t);function roA(t,i,r){return function(...l){const u=this.__v_raw,p=Tr(u),y=y_(p),w=t==="entries"||t===Symbol.iterator&&y,_=t==="keys"&&y,k=u[t](...l),F=r?Rj:i?wj:Iu;return!i&&lu(p,"iterate",_?vj:$M),{next(){const{value:j,done:lA}=k.next();return lA?{value:j,done:lA}:{value:w?[F(j[0]),F(j[1])]:F(j),done:lA}},[Symbol.iterator](){return this}}}}function q2(t){return function(...i){return t==="delete"?!1:t==="clear"?void 0:this}}function aoA(t,i){const r={get(u){const p=this.__v_raw,y=Tr(p),w=Tr(u);t||(Ny(u,w)&&lu(y,"get",u),lu(y,"get",w));const{has:_}=H2(y),k=i?Rj:t?wj:Iu;if(_.call(y,u))return k(p.get(u));if(_.call(y,w))return k(p.get(w));p!==y&&p.get(u)},get size(){const u=this.__v_raw;return!t&&lu(Tr(u),"iterate",$M),Reflect.get(u,"size",u)},has(u){const p=this.__v_raw,y=Tr(p),w=Tr(u);return t||(Ny(u,w)&&lu(y,"has",u),lu(y,"has",w)),u===w?p.has(u):p.has(u)||p.has(w)},forEach(u,p){const y=this,w=y.__v_raw,_=Tr(w),k=i?Rj:t?wj:Iu;return!t&&lu(_,"iterate",$M),w.forEach((F,j)=>u.call(p,k(F),k(j),y))}};return $l(r,t?{add:q2("add"),set:q2("set"),delete:q2("delete"),clear:q2("clear")}:{add(u){!i&&!JC(u)&&!av(u)&&(u=Tr(u));const p=Tr(this);return H2(p).has.call(p,u)||(p.add(u),em(p,"add",u,u)),this},set(u,p){!i&&!JC(p)&&!av(p)&&(p=Tr(p));const y=Tr(this),{has:w,get:_}=H2(y);let k=w.call(y,u);k||(u=Tr(u),k=w.call(y,u));const F=_.call(y,u);return y.set(u,p),k?Ny(p,F)&&em(y,"set",u,p):em(y,"add",u,p),this},delete(u){const p=Tr(this),{has:y,get:w}=H2(p);let _=y.call(p,u);_||(u=Tr(u),_=y.call(p,u)),w&&w.call(p,u);const k=p.delete(u);return _&&em(p,"delete",u,void 0),k},clear(){const u=Tr(this),p=u.size!==0,y=u.clear();return p&&em(u,"clear",void 0,void 0),y}}),["keys","values","entries",Symbol.iterator].forEach(u=>{r[u]=roA(u,t,i)}),r}function v3(t,i){const r=aoA(t,i);return(l,u,p)=>u==="__v_isReactive"?!t:u==="__v_isReadonly"?t:u==="__v_raw"?l:Reflect.get(qr(r,u)&&u in l?r:l,u,p)}const goA={get:v3(!1,!1)},coA={get:v3(!1,!0)},loA={get:v3(!0,!1)};const MZ=new WeakMap,vZ=new WeakMap,RZ=new WeakMap,IoA=new WeakMap;function uoA(t){switch(t){case"Object":case"Array":return 1;case"Map":case"Set":case"WeakMap":case"WeakSet":return 2;default:return 0}}function EoA(t){return t.__v_skip||!Object.isExtensible(t)?0:uoA(UiA(t))}function WM(t){return av(t)?t:R3(t,!1,ooA,goA,MZ)}function doA(t){return R3(t,!1,noA,coA,vZ)}function qh(t){return R3(t,!0,soA,loA,RZ)}function R3(t,i,r,l,u){if(!Ta(t)||t.__v_raw&&!(i&&t.__v_isReactive))return t;const p=u.get(t);if(p)return p;const y=EoA(t);if(y===0)return t;const w=new Proxy(t,y===2?l:r);return u.set(t,w),w}function D_(t){return av(t)?D_(t.__v_raw):!!(t&&t.__v_isReactive)}function av(t){return!!(t&&t.__v_isReadonly)}function JC(t){return!!(t&&t.__v_isShallow)}function w3(t){return t?!!t.__v_raw:!1}function Tr(t){const i=t&&t.__v_raw;return i?Tr(i):t}function CoA(t){return!qr(t,"__v_skip")&&Object.isExtensible(t)&&lZ(t,"__v_skip",!0),t}const Iu=t=>Ta(t)?WM(t):t,wj=t=>Ta(t)?qh(t):t;function Xl(t){return t?t.__v_isRef===!0:!1}function $e(t){return hoA(t,!1)}function hoA(t,i){return Xl(t)?t:new BoA(t,i)}class BoA{constructor(i,r){this.dep=new M3,this.__v_isRef=!0,this.__v_isShallow=!1,this._rawValue=r?i:Tr(i),this._value=r?i:Iu(i),this.__v_isShallow=r}get value(){return this.dep.track(),this._value}set value(i){const r=this._rawValue,l=this.__v_isShallow||JC(i)||av(i);i=l?i:Tr(i),Ny(i,r)&&(this._rawValue=i,this._value=l?i:Iu(i),this.dep.trigger())}}function gA(t){return Xl(t)?t.value:t}const QoA={get:(t,i,r)=>i==="__v_raw"?t:gA(Reflect.get(t,i,r)),set:(t,i,r,l)=>{const u=t[i];return Xl(u)&&!Xl(r)?(u.value=r,!0):Reflect.set(t,i,r,l)}};function wZ(t){return D_(t)?t:new Proxy(t,QoA)}function Ns(t){const i=Ss(t)?new Array(t.length):{};for(const r in t)i[r]=_Z(t,r);return i}class poA{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 XiA(Tr(this._object),this._key)}}class moA{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 kK(t,i,r){return Xl(t)?t:Xs(t)?new moA(t):Ta(t)&&arguments.length>1?_Z(t,i,r):$e(t)}function _Z(t,i,r){const l=t[i];return Xl(l)?l:new poA(t,i,r)}class foA{constructor(i,r,l){this.fn=i,this.setter=r,this._value=void 0,this.dep=new M3(this),this.__v_isRef=!0,this.deps=void 0,this.depsTail=void 0,this.flags=16,this.globalVersion=kL-1,this.next=void 0,this.effect=this,this.__v_isReadonly=!r,this.isSSR=l}notify(){if(this.flags|=16,!(this.flags&8)&&Ra!==this)return hZ(this,!0),!0}get value(){const i=this.dep.track();return pZ(this),i&&(i.version=this.dep.version),this._value}set value(i){this.setter&&this.setter(i)}}function yoA(t,i,r=!1){let l,u;return Xs(t)?l=t:(l=t.get,u=t.set),new foA(l,u,r)}const K2={},N1=new WeakMap;let VM;function DoA(t,i=!1,r=VM){if(r){let l=N1.get(r);l||N1.set(r,l=[]),l.push(t)}}function SoA(t,i,r=fa){const{immediate:l,deep:u,once:p,scheduler:y,augmentJob:w,call:_}=r,k=de=>u?de:JC(de)||u===!1||u===0?tm(de,1):tm(de);let F,j,lA,aA,mA=!1,IA=!1;if(Xl(t)?(j=()=>t.value,mA=JC(t)):D_(t)?(j=()=>k(t),mA=!0):Ss(t)?(IA=!0,mA=t.some(de=>D_(de)||JC(de)),j=()=>t.map(de=>{if(Xl(de))return de.value;if(D_(de))return k(de);if(Xs(de))return _?_(de,2):de()})):Xs(t)?i?j=_?()=>_(t,2):t:j=()=>{if(lA){Vy();try{lA()}finally{Jy()}}const de=VM;VM=F;try{return _?_(t,3,[aA]):t(aA)}finally{VM=de}}:j=CQ,i&&u){const de=j,Ve=u===!0?1/0:u;j=()=>tm(de(),Ve)}const tA=WiA(),MA=()=>{F.stop(),tA&&tA.active&&m3(tA.effects,F)};if(p&&i){const de=i;i=(...Ve)=>{de(...Ve),MA()}}let PA=IA?new Array(t.length).fill(K2):K2;const ge=de=>{if(!(!(F.flags&1)||!F.dirty&&!de))if(i){const Ve=F.run();if(u||mA||(IA?Ve.some((Be,ct)=>Ny(Be,PA[ct])):Ny(Ve,PA))){lA&&lA();const Be=VM;VM=F;try{const ct=[Ve,PA===K2?void 0:IA&&PA[0]===K2?[]:PA,aA];_?_(i,3,ct):i(...ct),PA=Ve}finally{VM=Be}}}else F.run()};return w&&w(ge),F=new dZ(j),F.scheduler=y?()=>y(ge,!1):ge,aA=de=>DoA(de,!1,F),lA=F.onStop=()=>{const de=N1.get(F);if(de){if(_)_(de,4);else for(const Ve of de)Ve();N1.delete(F)}},i?l?ge(!0):PA=F.run():y?y(ge.bind(null,!0),!0):F.run(),MA.pause=F.pause.bind(F),MA.resume=F.resume.bind(F),MA.stop=MA,MA}function tm(t,i=1/0,r){if(i<=0||!Ta(t)||t.__v_skip||(r=r||new Set,r.has(t)))return t;if(r.add(t),i--,Xl(t))tm(t.value,i,r);else if(Ss(t))for(let l=0;l{tm(l,i,r)});else if(cZ(t)){for(const l in t)tm(t[l],i,r);for(const l of Object.getOwnPropertySymbols(t))Object.prototype.propertyIsEnumerable.call(t,l)&&tm(t[l],i,r)}return t}/**
+**/let Zd;class CoA{constructor(i=!1){this.detached=i,this._active=!0,this.effects=[],this.cleanups=[],this._isPaused=!1,this.parent=Zd,!i&&Zd&&(this.index=(Zd.scopes||(Zd.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(RL){let i=RL;for(RL=void 0;i;){const r=i.next;i.next=void 0,i.flags&=-9,i=r}}let t;for(;vL;){let i=vL;for(vL=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 PZ(t){for(let i=t.deps;i;i=i.nextDep)i.version=-1,i.prevActiveLink=i.dep.activeLink,i.dep.activeLink=i}function xZ(t){let i,r=t.depsTail,l=r;for(;l;){const u=l.prevDep;l.version===-1?(l===r&&(r=u),H3(l),BoA(l)):i=l,l.dep.activeLink=l.prevActiveLink,l.prevActiveLink=void 0,l=u}t.deps=i,t.depsTail=r}function Vj(t){for(let i=t.deps;i;i=i.nextDep)if(i.dep.version!==i.version||i.dep.computed&&(YZ(i.dep.computed)||i.dep.version!==i.version))return!0;return!!t._dirty}function YZ(t){if(t.flags&4&&!(t.flags&16)||(t.flags&=-17,t.globalVersion===qL))return;t.globalVersion=qL;const i=t.dep;if(t.flags|=2,i.version>0&&!t.isSSR&&t.deps&&!Vj(t)){t.flags&=-3;return}const r=wa,l=tB;wa=t,tB=!0;try{PZ(t);const u=t.fn(t._value);(i.version===0||Oy(u,t._value))&&(t._value=u,i.version++)}catch(u){throw i.version++,u}finally{wa=r,tB=l,xZ(t),t.flags&=-3}}function H3(t,i=!1){const{dep:r,prevSub:l,nextSub:u}=t;if(l&&(l.nextSub=u,t.prevSub=void 0),u&&(u.prevSub=l,t.nextSub=void 0),r.subs===t&&(r.subs=l,!l&&r.computed)){r.computed.flags&=-5;for(let B=r.computed.deps;B;B=B.nextDep)H3(B,!0)}!i&&!--r.sc&&r.map&&r.map.delete(r.key)}function BoA(t){const{prevDep:i,nextDep:r}=t;i&&(i.nextDep=r,t.prevDep=void 0),r&&(r.prevDep=i,t.nextDep=void 0)}let tB=!0;const VZ=[];function zy(){VZ.push(tB),tB=!1}function Zy(){const t=VZ.pop();tB=t===void 0?!0:t}function mz(t){const{cleanup:i}=t;if(t.cleanup=void 0,i){const r=wa;wa=void 0;try{i()}finally{wa=r}}}let qL=0;class QoA{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 q3{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(!wa||!tB||wa===this.computed)return;let r=this.activeLink;if(r===void 0||r.sub!==wa)r=this.activeLink=new QoA(wa,this),wa.deps?(r.prevDep=wa.depsTail,wa.depsTail.nextDep=r,wa.depsTail=r):wa.deps=wa.depsTail=r,JZ(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=wa.depsTail,r.nextDep=void 0,wa.depsTail.nextDep=r,wa.depsTail=r,wa.deps===r&&(wa.deps=l)}return r}trigger(i){this.version++,qL++,this.notify(i)}notify(i){V3();try{for(let r=this.subs;r;r=r.prevSub)r.sub.notify()&&r.sub.dep.notify()}finally{J3()}}}function JZ(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)JZ(l)}const r=t.dep.subs;r!==t&&(t.prevSub=r,r&&(r.nextSub=t)),t.dep.subs=t}}const H1=new WeakMap,rv=Symbol(""),Jj=Symbol(""),KL=Symbol("");function Eu(t,i,r){if(tB&&wa){let l=H1.get(t);l||H1.set(t,l=new Map);let u=l.get(r);u||(l.set(r,u=new q3),u.map=l,u.key=r),u.track()}}function nm(t,i,r,l,u,B){const f=H1.get(t);if(!f){qL++;return}const w=_=>{_&&_.trigger()};if(V3(),i==="clear")f.forEach(w);else{const _=Ms(t),k=_&&Y3(r);if(_&&r==="length"){const F=Number(l);f.forEach((j,IA)=>{(IA==="length"||IA===KL||!lm(IA)&&IA>=F)&&w(j)})}else switch((r!==void 0||f.has(void 0))&&w(f.get(r)),k&&w(f.get(KL)),i){case"add":_?k&&w(f.get("length")):(w(f.get(rv)),T_(t)&&w(f.get(Jj)));break;case"delete":_||(w(f.get(rv)),T_(t)&&w(f.get(Jj)));break;case"set":T_(t)&&w(f.get(rv));break}}J3()}function poA(t,i){const r=H1.get(t);return r&&r.get(i)}function a_(t){const i=Tr(t);return i===t?i:(Eu(i,"iterate",KL),ZC(t)?i:i.map(du))}function RY(t){return Eu(t=Tr(t),"iterate",KL),t}const moA={__proto__:null,[Symbol.iterator](){return WK(this,Symbol.iterator,du)},concat(...t){return a_(this).concat(...t.map(i=>Ms(i)?a_(i):i))},entries(){return WK(this,"entries",t=>(t[1]=du(t[1]),t))},every(t,i){return Xp(this,"every",t,i,void 0,arguments)},filter(t,i){return Xp(this,"filter",t,i,r=>r.map(du),arguments)},find(t,i){return Xp(this,"find",t,i,du,arguments)},findIndex(t,i){return Xp(this,"findIndex",t,i,void 0,arguments)},findLast(t,i){return Xp(this,"findLast",t,i,du,arguments)},findLastIndex(t,i){return Xp(this,"findLastIndex",t,i,void 0,arguments)},forEach(t,i){return Xp(this,"forEach",t,i,void 0,arguments)},includes(...t){return zK(this,"includes",t)},indexOf(...t){return zK(this,"indexOf",t)},join(t){return a_(this).join(t)},lastIndexOf(...t){return zK(this,"lastIndexOf",t)},map(t,i){return Xp(this,"map",t,i,void 0,arguments)},pop(){return $k(this,"pop")},push(...t){return $k(this,"push",t)},reduce(t,...i){return fz(this,"reduce",t,i)},reduceRight(t,...i){return fz(this,"reduceRight",t,i)},shift(){return $k(this,"shift")},some(t,i){return Xp(this,"some",t,i,void 0,arguments)},splice(...t){return $k(this,"splice",t)},toReversed(){return a_(this).toReversed()},toSorted(t){return a_(this).toSorted(t)},toSpliced(...t){return a_(this).toSpliced(...t)},unshift(...t){return $k(this,"unshift",t)},values(){return WK(this,"values",du)}};function WK(t,i,r){const l=RY(t),u=l[i]();return l!==t&&!ZC(t)&&(u._next=u.next,u.next=()=>{const B=u._next();return B.value&&(B.value=r(B.value)),B}),u}const foA=Array.prototype;function Xp(t,i,r,l,u,B){const f=RY(t),w=f!==t&&!ZC(t),_=f[i];if(_!==foA[i]){const j=_.apply(t,B);return w?du(j):j}let k=r;f!==t&&(w?k=function(j,IA){return r.call(this,du(j),IA,t)}:r.length>2&&(k=function(j,IA){return r.call(this,j,IA,t)}));const F=_.call(f,k,l);return w&&u?u(F):F}function fz(t,i,r,l){const u=RY(t);let B=r;return u!==t&&(ZC(t)?r.length>3&&(B=function(f,w,_){return r.call(this,f,w,_,t)}):B=function(f,w,_){return r.call(this,f,du(w),_,t)}),u[i](B,...l)}function zK(t,i,r){const l=Tr(t);Eu(l,"iterate",KL);const u=l[i](...r);return(u===-1||u===!1)&&W3(r[0])?(r[0]=Tr(r[0]),l[i](...r)):u}function $k(t,i,r=[]){zy(),V3();const l=Tr(t)[i].apply(t,r);return J3(),Zy(),l}const yoA=O3("__proto__,__v_isRef,__isVue"),HZ=new Set(Object.getOwnPropertyNames(Symbol).filter(t=>t!=="arguments"&&t!=="caller").map(t=>Symbol[t]).filter(lm));function DoA(t){lm(t)||(t=String(t));const i=Tr(this);return Eu(i,"has",t),i.hasOwnProperty(t)}class qZ{constructor(i=!1,r=!1){this._isReadonly=i,this._isShallow=r}get(i,r,l){if(r==="__v_skip")return i.__v_skip;const u=this._isReadonly,B=this._isShallow;if(r==="__v_isReactive")return!u;if(r==="__v_isReadonly")return u;if(r==="__v_isShallow")return B;if(r==="__v_raw")return l===(u?B?boA:zZ:B?WZ:jZ).get(i)||Object.getPrototypeOf(i)===Object.getPrototypeOf(l)?i:void 0;const f=Ms(i);if(!u){let _;if(f&&(_=moA[r]))return _;if(r==="hasOwnProperty")return DoA}const w=Reflect.get(i,r,AI(i)?i:l);return(lm(r)?HZ.has(r):yoA(r))||(u||Eu(i,"get",r),B)?w:AI(w)?f&&Y3(r)?w:w.value:Ta(w)?u?JC(w):iv(w):w}}class KZ extends qZ{constructor(i=!1){super(!1,i)}set(i,r,l,u){let B=i[r];if(!this._isShallow){const _=hv(B);if(!ZC(l)&&!hv(l)&&(B=Tr(B),l=Tr(l)),!Ms(i)&&AI(B)&&!AI(l))return _?!1:(B.value=l,!0)}const f=Ms(i)&&Y3(r)?Number(r)t,s1=t=>Reflect.getPrototypeOf(t);function woA(t,i,r){return function(...l){const u=this.__v_raw,B=Tr(u),f=T_(B),w=t==="entries"||t===Symbol.iterator&&f,_=t==="keys"&&f,k=u[t](...l),F=r?Hj:i?qj:du;return!i&&Eu(B,"iterate",_?Jj:rv),{next(){const{value:j,done:IA}=k.next();return IA?{value:j,done:IA}:{value:w?[F(j[0]),F(j[1])]:F(j),done:IA}},[Symbol.iterator](){return this}}}}function n1(t){return function(...i){return t==="delete"?!1:t==="clear"?void 0:this}}function _oA(t,i){const r={get(u){const B=this.__v_raw,f=Tr(B),w=Tr(u);t||(Oy(u,w)&&Eu(f,"get",u),Eu(f,"get",w));const{has:_}=s1(f),k=i?Hj:t?qj:du;if(_.call(f,u))return k(B.get(u));if(_.call(f,w))return k(B.get(w));B!==f&&B.get(u)},get size(){const u=this.__v_raw;return!t&&Eu(Tr(u),"iterate",rv),Reflect.get(u,"size",u)},has(u){const B=this.__v_raw,f=Tr(B),w=Tr(u);return t||(Oy(u,w)&&Eu(f,"has",u),Eu(f,"has",w)),u===w?B.has(u):B.has(u)||B.has(w)},forEach(u,B){const f=this,w=f.__v_raw,_=Tr(w),k=i?Hj:t?qj:du;return!t&&Eu(_,"iterate",rv),w.forEach((F,j)=>u.call(B,k(F),k(j),f))}};return eI(r,t?{add:n1("add"),set:n1("set"),delete:n1("delete"),clear:n1("clear")}:{add(u){!i&&!ZC(u)&&!hv(u)&&(u=Tr(u));const B=Tr(this);return s1(B).has.call(B,u)||(B.add(u),nm(B,"add",u,u)),this},set(u,B){!i&&!ZC(B)&&!hv(B)&&(B=Tr(B));const f=Tr(this),{has:w,get:_}=s1(f);let k=w.call(f,u);k||(u=Tr(u),k=w.call(f,u));const F=_.call(f,u);return f.set(u,B),k?Oy(B,F)&&nm(f,"set",u,B):nm(f,"add",u,B),this},delete(u){const B=Tr(this),{has:f,get:w}=s1(B);let _=f.call(B,u);_||(u=Tr(u),_=f.call(B,u)),w&&w.call(B,u);const k=B.delete(u);return _&&nm(B,"delete",u,void 0),k},clear(){const u=Tr(this),B=u.size!==0,f=u.clear();return B&&nm(u,"clear",void 0,void 0),f}}),["keys","values","entries",Symbol.iterator].forEach(u=>{r[u]=woA(u,t,i)}),r}function K3(t,i){const r=_oA(t,i);return(l,u,B)=>u==="__v_isReactive"?!t:u==="__v_isReadonly"?t:u==="__v_raw"?l:Reflect.get(qr(r,u)&&u in l?r:l,u,B)}const ToA={get:K3(!1,!1)},NoA={get:K3(!1,!0)},GoA={get:K3(!0,!1)};const jZ=new WeakMap,WZ=new WeakMap,zZ=new WeakMap,boA=new WeakMap;function koA(t){switch(t){case"Object":case"Array":return 1;case"Map":case"Set":case"WeakMap":case"WeakSet":return 2;default:return 0}}function LoA(t){return t.__v_skip||!Object.isExtensible(t)?0:koA(soA(t))}function iv(t){return hv(t)?t:j3(t,!1,MoA,ToA,jZ)}function UoA(t){return j3(t,!1,RoA,NoA,WZ)}function JC(t){return j3(t,!0,voA,GoA,zZ)}function j3(t,i,r,l,u){if(!Ta(t)||t.__v_raw&&!(i&&t.__v_isReactive))return t;const B=u.get(t);if(B)return B;const f=LoA(t);if(f===0)return t;const w=new Proxy(t,f===2?l:r);return u.set(t,w),w}function N_(t){return hv(t)?N_(t.__v_raw):!!(t&&t.__v_isReactive)}function hv(t){return!!(t&&t.__v_isReadonly)}function ZC(t){return!!(t&&t.__v_isShallow)}function W3(t){return t?!!t.__v_raw:!1}function Tr(t){const i=t&&t.__v_raw;return i?Tr(i):t}function FoA(t){return!qr(t,"__v_skip")&&Object.isExtensible(t)&&GZ(t,"__v_skip",!0),t}const du=t=>Ta(t)?iv(t):t,qj=t=>Ta(t)?JC(t):t;function AI(t){return t?t.__v_isRef===!0:!1}function Xe(t){return OoA(t,!1)}function OoA(t,i){return AI(t)?t:new PoA(t,i)}class PoA{constructor(i,r){this.dep=new q3,this.__v_isRef=!0,this.__v_isShallow=!1,this._rawValue=r?i:Tr(i),this._value=r?i:du(i),this.__v_isShallow=r}get value(){return this.dep.track(),this._value}set value(i){const r=this._rawValue,l=this.__v_isShallow||ZC(i)||hv(i);i=l?i:Tr(i),Oy(i,r)&&(this._rawValue=i,this._value=l?i:du(i),this.dep.trigger())}}function aA(t){return AI(t)?t.value:t}const xoA={get:(t,i,r)=>i==="__v_raw"?t:aA(Reflect.get(t,i,r)),set:(t,i,r,l)=>{const u=t[i];return AI(u)&&!AI(r)?(u.value=r,!0):Reflect.set(t,i,r,l)}};function ZZ(t){return N_(t)?t:new Proxy(t,xoA)}function Gs(t){const i=Ms(t)?new Array(t.length):{};for(const r in t)i[r]=XZ(t,r);return i}class YoA{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 poA(Tr(this._object),this._key)}}class VoA{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 ZK(t,i,r){return AI(t)?t:$s(t)?new VoA(t):Ta(t)&&arguments.length>1?XZ(t,i,r):Xe(t)}function XZ(t,i,r){const l=t[i];return AI(l)?l:new YoA(t,i,r)}class JoA{constructor(i,r,l){this.fn=i,this.setter=r,this._value=void 0,this.dep=new q3(this),this.__v_isRef=!0,this.deps=void 0,this.depsTail=void 0,this.flags=16,this.globalVersion=qL-1,this.next=void 0,this.effect=this,this.__v_isReadonly=!r,this.isSSR=l}notify(){if(this.flags|=16,!(this.flags&8)&&wa!==this)return OZ(this,!0),!0}get value(){const i=this.dep.track();return YZ(this),i&&(i.version=this.dep.version),this._value}set value(i){this.setter&&this.setter(i)}}function HoA(t,i,r=!1){let l,u;return $s(t)?l=t:(l=t.get,u=t.set),new JoA(l,u,r)}const r1={},q1=new WeakMap;let zM;function qoA(t,i=!1,r=zM){if(r){let l=q1.get(r);l||q1.set(r,l=[]),l.push(t)}}function KoA(t,i,r=fa){const{immediate:l,deep:u,once:B,scheduler:f,augmentJob:w,call:_}=r,k=$A=>u?$A:ZC($A)||u===!1||u===0?rm($A,1):rm($A);let F,j,IA,rA,pA=!1,lA=!1;if(AI(t)?(j=()=>t.value,pA=ZC(t)):N_(t)?(j=()=>k(t),pA=!0):Ms(t)?(lA=!0,pA=t.some($A=>N_($A)||ZC($A)),j=()=>t.map($A=>{if(AI($A))return $A.value;if(N_($A))return k($A);if($s($A))return _?_($A,2):$A()})):$s(t)?i?j=_?()=>_(t,2):t:j=()=>{if(IA){zy();try{IA()}finally{Zy()}}const $A=zM;zM=F;try{return _?_(t,3,[rA]):t(rA)}finally{zM=$A}}:j=yQ,i&&u){const $A=j,De=u===!0?1/0:u;j=()=>rm($A(),De)}const cA=hoA(),TA=()=>{F.stop(),cA&&cA.active&&x3(cA.effects,F)};if(B&&i){const $A=i;i=(...De)=>{$A(...De),TA()}}let WA=lA?new Array(t.length).fill(r1):r1;const zA=$A=>{if(!(!(F.flags&1)||!F.dirty&&!$A))if(i){const De=F.run();if(u||pA||(lA?De.some((Ce,ct)=>Oy(Ce,WA[ct])):Oy(De,WA))){IA&&IA();const Ce=zM;zM=F;try{const ct=[De,WA===r1?void 0:lA&&WA[0]===r1?[]:WA,rA];_?_(i,3,ct):i(...ct),WA=De}finally{zM=Ce}}}else F.run()};return w&&w(zA),F=new UZ(j),F.scheduler=f?()=>f(zA,!1):zA,rA=$A=>qoA($A,!1,F),IA=F.onStop=()=>{const $A=q1.get(F);if($A){if(_)_($A,4);else for(const De of $A)De();q1.delete(F)}},i?l?zA(!0):WA=F.run():f?f(zA.bind(null,!0),!0):F.run(),TA.pause=F.pause.bind(F),TA.resume=F.resume.bind(F),TA.stop=TA,TA}function rm(t,i=1/0,r){if(i<=0||!Ta(t)||t.__v_skip||(r=r||new Set,r.has(t)))return t;if(r.add(t),i--,AI(t))rm(t.value,i,r);else if(Ms(t))for(let l=0;l{rm(l,i,r)});else if(NZ(t)){for(const l in t)rm(t[l],i,r);for(const l of Object.getOwnPropertySymbols(t))Object.prototype.propertyIsEnumerable.call(t,l)&&rm(t[l],i,r)}return t}/**
* @vue/runtime-core v3.5.13
* (c) 2018-present Yuxi (Evan) You and Vue contributors
* @license MIT
-**/function XL(t,i,r,l){try{return l?t(...l):t()}catch(u){uY(u,i,r)}}function Zh(t,i,r,l){if(Xs(t)){const u=XL(t,i,r,l);return u&&aZ(u)&&u.catch(p=>{uY(p,i,r)}),u}if(Ss(t)){const u=[];for(let p=0;p>>1,u=cE[l],p=UL(u);p=UL(r)?cE.push(t):cE.splice(voA(i),0,t),t.flags|=1,NZ()}}function NZ(){G1||(G1=TZ.then(bZ))}function RoA(t){Ss(t)?S_.push(...t):Sy&&t.id===-1?Sy.splice(s_+1,0,t):t.flags&1||(S_.push(t),t.flags|=1),NZ()}function ez(t,i,r=gQ+1){for(;rUL(r)-UL(l));if(S_.length=0,Sy){Sy.push(...i);return}for(Sy=i,s_=0;s_t.id==null?t.flags&2?-1:1/0:t.id;function bZ(t){try{for(gQ=0;gQ{l._d&&dz(-1);const p=b1(i);let y;try{y=t(...u)}finally{b1(p),l._d&&dz(1)}return y};return l._n=!0,l._c=!0,l._d=!0,l}function wa(t,i){if(Zl===null)return t;const r=QY(Zl),l=t.dirs||(t.dirs=[]);for(let u=0;ut.__isTeleport,BL=t=>t&&(t.disabled||t.disabled===""),tz=t=>t&&(t.defer||t.defer===""),iz=t=>typeof SVGElement<"u"&&t instanceof SVGElement,oz=t=>typeof MathMLElement=="function"&&t instanceof MathMLElement,_j=(t,i)=>{const r=t&&t.to;return mg(r)?i?i(r):null:r},UZ={name:"Teleport",__isTeleport:!0,process(t,i,r,l,u,p,y,w,_,k){const{mc:F,pc:j,pbc:lA,o:{insert:aA,querySelector:mA,createText:IA,createComment:tA}}=k,MA=BL(i.props);let{shapeFlag:PA,children:ge,dynamicChildren:de}=i;if(t==null){const Ve=i.el=IA(""),Be=i.anchor=IA("");aA(Ve,r,l),aA(Be,r,l);const ct=(Ke,Dt)=>{PA&16&&(u&&u.isCE&&(u.ce._teleportTarget=Ke),F(ge,Ke,Dt,u,p,y,w,_))},mt=()=>{const Ke=i.target=_j(i.props,mA),Dt=FZ(Ke,i,IA,aA);Ke&&(y!=="svg"&&iz(Ke)?y="svg":y!=="mathml"&&oz(Ke)&&(y="mathml"),MA||(ct(Ke,Dt),E1(i,!1)))};MA&&(ct(r,Be),E1(i,!0)),tz(i.props)?aE(()=>{mt(),i.el.__isMounted=!0},p):mt()}else{if(tz(i.props)&&!t.el.__isMounted){aE(()=>{UZ.process(t,i,r,l,u,p,y,w,_,k),delete t.el.__isMounted},p);return}i.el=t.el,i.targetStart=t.targetStart;const Ve=i.anchor=t.anchor,Be=i.target=t.target,ct=i.targetAnchor=t.targetAnchor,mt=BL(t.props),Ke=mt?r:Be,Dt=mt?Ve:ct;if(y==="svg"||iz(Be)?y="svg":(y==="mathml"||oz(Be))&&(y="mathml"),de?(lA(t.dynamicChildren,de,Ke,u,p,y,w),N3(t,i,!0)):_||j(t,i,Ke,Dt,u,p,y,w,!1),MA)mt?i.props&&t.props&&i.props.to!==t.props.to&&(i.props.to=t.props.to):j2(i,r,Ve,k,1);else if((i.props&&i.props.to)!==(t.props&&t.props.to)){const qt=i.target=_j(i.props,mA);qt&&j2(i,qt,null,k,0)}else mt&&j2(i,Be,ct,k,1);E1(i,MA)}},remove(t,i,r,{um:l,o:{remove:u}},p){const{shapeFlag:y,children:w,anchor:_,targetStart:k,targetAnchor:F,target:j,props:lA}=t;if(j&&(u(k),u(F)),p&&u(_),y&16){const aA=p||!BL(lA);for(let mA=0;mA{t.isMounted=!0}),qZ(()=>{t.isUnmounting=!0}),t}const GC=[Function,Array],OZ={mode:String,appear:Boolean,persisted:Boolean,onBeforeEnter:GC,onEnter:GC,onAfterEnter:GC,onEnterCancelled:GC,onBeforeLeave:GC,onLeave:GC,onAfterLeave:GC,onLeaveCancelled:GC,onBeforeAppear:GC,onAppear:GC,onAfterAppear:GC,onAppearCancelled:GC},PZ=t=>{const i=t.subTree;return i.component?PZ(i.component):i},NoA={name:"BaseTransition",props:OZ,setup(t,{slots:i}){const r=RsA(),l=ToA();return()=>{const u=i.default&&VZ(i.default(),!0);if(!u||!u.length)return;const p=xZ(u),y=Tr(t),{mode:w}=y;if(l.isLeaving)return LK(p);const _=sz(p);if(!_)return LK(p);let k=Tj(_,y,l,r,j=>k=j);_.type!==lE&&FL(_,k);let F=r.subTree&&sz(r.subTree);if(F&&F.type!==lE&&!JM(_,F)&&PZ(r).type!==lE){let j=Tj(F,y,l,r);if(FL(F,j),w==="out-in"&&_.type!==lE)return l.isLeaving=!0,j.afterLeave=()=>{l.isLeaving=!1,r.job.flags&8||r.update(),delete j.afterLeave,F=void 0},LK(p);w==="in-out"&&_.type!==lE?j.delayLeave=(lA,aA,mA)=>{const IA=YZ(l,F);IA[String(F.key)]=F,lA[My]=()=>{aA(),lA[My]=void 0,delete k.delayedLeave,F=void 0},k.delayedLeave=()=>{mA(),delete k.delayedLeave,F=void 0}}:F=void 0}else F&&(F=void 0);return p}}};function xZ(t){let i=t[0];if(t.length>1){for(const r of t)if(r.type!==lE){i=r;break}}return i}const GoA=NoA;function YZ(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 Tj(t,i,r,l,u){const{appear:p,mode:y,persisted:w=!1,onBeforeEnter:_,onEnter:k,onAfterEnter:F,onEnterCancelled:j,onBeforeLeave:lA,onLeave:aA,onAfterLeave:mA,onLeaveCancelled:IA,onBeforeAppear:tA,onAppear:MA,onAfterAppear:PA,onAppearCancelled:ge}=i,de=String(t.key),Ve=YZ(r,t),Be=(Ke,Dt)=>{Ke&&Zh(Ke,l,9,Dt)},ct=(Ke,Dt)=>{const qt=Dt[1];Be(Ke,Dt),Ss(Ke)?Ke.every(It=>It.length<=1)&&qt():Ke.length<=1&&qt()},mt={mode:y,persisted:w,beforeEnter(Ke){let Dt=_;if(!r.isMounted)if(p)Dt=tA||_;else return;Ke[My]&&Ke[My](!0);const qt=Ve[de];qt&&JM(t,qt)&&qt.el[My]&&qt.el[My](),Be(Dt,[Ke])},enter(Ke){let Dt=k,qt=F,It=j;if(!r.isMounted)if(p)Dt=MA||k,qt=PA||F,It=ge||j;else return;let re=!1;const qe=Ke[W2]=ft=>{re||(re=!0,ft?Be(It,[Ke]):Be(qt,[Ke]),mt.delayedLeave&&mt.delayedLeave(),Ke[W2]=void 0)};Dt?ct(Dt,[Ke,qe]):qe()},leave(Ke,Dt){const qt=String(t.key);if(Ke[W2]&&Ke[W2](!0),r.isUnmounting)return Dt();Be(lA,[Ke]);let It=!1;const re=Ke[My]=qe=>{It||(It=!0,Dt(),qe?Be(IA,[Ke]):Be(mA,[Ke]),Ke[My]=void 0,Ve[qt]===t&&delete Ve[qt])};Ve[qt]=t,aA?ct(aA,[Ke,re]):re()},clone(Ke){const Dt=Tj(Ke,i,r,l,u);return u&&u(Dt),Dt}};return mt}function LK(t){if(dY(t))return t=Uy(t),t.children=null,t}function sz(t){if(!dY(t))return LZ(t.type)&&t.children?xZ(t.children):t;const{shapeFlag:i,children:r}=t;if(r){if(i&16)return r[0];if(i&32&&Xs(r.default))return r.default()}}function FL(t,i){t.shapeFlag&6&&t.component?(t.transition=i,FL(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 VZ(t,i=!1,r){let l=[],u=0;for(let p=0;p1)for(let p=0;pk1(mA,i&&(Ss(i)?i[IA]:i),r,l,u));return}if(M_(l)&&!u){l.shapeFlag&512&&l.type.__asyncResolved&&l.component.subTree.component&&k1(t,i,r,l.component.subTree);return}const p=l.shapeFlag&4?QY(l.component):l.el,y=u?null:p,{i:w,r:_}=t,k=i&&i.r,F=w.refs===fa?w.refs={}:w.refs,j=w.setupState,lA=Tr(j),aA=j===fa?()=>!1:mA=>qr(lA,mA);if(k!=null&&k!==_&&(mg(k)?(F[k]=null,aA(k)&&(j[k]=null)):Xl(k)&&(k.value=null)),Xs(_))XL(_,w,12,[y,F]);else{const mA=mg(_),IA=Xl(_);if(mA||IA){const tA=()=>{if(t.f){const MA=mA?aA(_)?j[_]:F[_]:_.value;u?Ss(MA)&&m3(MA,p):Ss(MA)?MA.includes(p)||MA.push(p):mA?(F[_]=[p],aA(_)&&(j[_]=F[_])):(_.value=[p],t.k&&(F[t.k]=_.value))}else mA?(F[_]=y,aA(_)&&(j[_]=y)):IA&&(_.value=y,t.k&&(F[t.k]=y))};y?(tA.id=-1,aE(tA,r)):tA()}}}lY().requestIdleCallback;lY().cancelIdleCallback;const M_=t=>!!t.type.__asyncLoader,dY=t=>t.type.__isKeepAlive;function boA(t,i){HZ(t,"a",i)}function koA(t,i){HZ(t,"da",i)}function HZ(t,i,r=bI){const l=t.__wdc||(t.__wdc=()=>{let u=r;for(;u;){if(u.isDeactivated)return;u=u.parent}return t()});if(CY(i,l,r),r){let u=r.parent;for(;u&&u.parent;)dY(u.parent.vnode)&&LoA(l,i,r,u),u=u.parent}}function LoA(t,i,r,l){const u=CY(i,t,l,!0);qg(()=>{m3(l[i],u)},r)}function CY(t,i,r=bI,l=!1){if(r){const u=r[t]||(r[t]=[]),p=i.__weh||(i.__weh=(...y)=>{Vy();const w=AU(r),_=Zh(i,r,t,y);return w(),Jy(),_});return l?u.unshift(p):u.push(p),p}}const rm=t=>(i,r=bI)=>{(!xL||t==="sp")&&CY(t,(...l)=>i(...l),r)},UoA=rm("bm"),Cc=rm("m"),FoA=rm("bu"),OoA=rm("u"),qZ=rm("bum"),qg=rm("um"),PoA=rm("sp"),xoA=rm("rtg"),YoA=rm("rtc");function VoA(t,i=bI){CY("ec",t,i)}const JoA="components";function HoA(t,i){return KoA(JoA,t,!0,i)||t}const qoA=Symbol.for("v-ndc");function KoA(t,i,r=!0,l=!1){const u=Zl||bI;if(u){const p=u.type;{const w=GsA(p,!1);if(w&&(w===i||w===KC(i)||w===cY(KC(i))))return p}const y=nz(u[t]||p[t],i)||nz(u.appContext[t],i);return!y&&l?p:y}}function nz(t,i){return t&&(t[i]||t[KC(i)]||t[cY(KC(i))])}function zd(t,i,r,l){let u;const p=r,y=Ss(t);if(y||mg(t)){const w=y&&D_(t);let _=!1;w&&(_=!JC(t),t=IY(t)),u=new Array(t.length);for(let k=0,F=t.length;ki(w,_,void 0,p));else{const w=Object.keys(t);u=new Array(w.length);for(let _=0,k=w.length;_PL(i)?!(i.type===lE||i.type===Kr&&!KZ(i.children)):!0)?t:null}const Nj=t=>t?I6(t)?QY(t):Nj(t.parent):null,QL=$l(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=>Nj(t.parent),$root:t=>Nj(t.root),$host:t=>t.ce,$emit:t=>t.emit,$options:t=>WZ(t),$forceUpdate:t=>t.f||(t.f=()=>{_3(t.update)}),$nextTick:t=>t.n||(t.n=$L.bind(t.proxy)),$watch:t=>EsA.bind(t)}),UK=(t,i)=>t!==fa&&!t.__isScriptSetup&&qr(t,i),joA={get({_:t},i){if(i==="__v_skip")return!0;const{ctx:r,setupState:l,data:u,props:p,accessCache:y,type:w,appContext:_}=t;let k;if(i[0]!=="$"){const aA=y[i];if(aA!==void 0)switch(aA){case 1:return l[i];case 2:return u[i];case 4:return r[i];case 3:return p[i]}else{if(UK(l,i))return y[i]=1,l[i];if(u!==fa&&qr(u,i))return y[i]=2,u[i];if((k=t.propsOptions[0])&&qr(k,i))return y[i]=3,p[i];if(r!==fa&&qr(r,i))return y[i]=4,r[i];Gj&&(y[i]=0)}}const F=QL[i];let j,lA;if(F)return i==="$attrs"&&lu(t.attrs,"get",""),F(t);if((j=w.__cssModules)&&(j=j[i]))return j;if(r!==fa&&qr(r,i))return y[i]=4,r[i];if(lA=_.config.globalProperties,qr(lA,i))return lA[i]},set({_:t},i,r){const{data:l,setupState:u,ctx:p}=t;return UK(u,i)?(u[i]=r,!0):l!==fa&&qr(l,i)?(l[i]=r,!0):qr(t.props,i)||i[0]==="$"&&i.slice(1)in t?!1:(p[i]=r,!0)},has({_:{data:t,setupState:i,accessCache:r,ctx:l,appContext:u,propsOptions:p}},y){let w;return!!r[y]||t!==fa&&qr(t,y)||UK(i,y)||(w=p[0])&&qr(w,y)||qr(l,y)||qr(QL,y)||qr(u.config.globalProperties,y)},defineProperty(t,i,r){return r.get!=null?t._.accessCache[i]=0:qr(r,"value")&&this.set(t,i,r.value,null),Reflect.defineProperty(t,i,r)}};function rz(t){return Ss(t)?t.reduce((i,r)=>(i[r]=null,i),{}):t}let Gj=!0;function WoA(t){const i=WZ(t),r=t.proxy,l=t.ctx;Gj=!1,i.beforeCreate&&az(i.beforeCreate,t,"bc");const{data:u,computed:p,methods:y,watch:w,provide:_,inject:k,created:F,beforeMount:j,mounted:lA,beforeUpdate:aA,updated:mA,activated:IA,deactivated:tA,beforeDestroy:MA,beforeUnmount:PA,destroyed:ge,unmounted:de,render:Ve,renderTracked:Be,renderTriggered:ct,errorCaptured:mt,serverPrefetch:Ke,expose:Dt,inheritAttrs:qt,components:It,directives:re,filters:qe}=i;if(k&&zoA(k,l,null),y)for(const Vt in y){const gi=y[Vt];Xs(gi)&&(l[Vt]=gi.bind(r))}if(u){const Vt=u.call(r,r);Ta(Vt)&&(t.data=WM(Vt))}if(Gj=!0,p)for(const Vt in p){const gi=p[Vt],Fi=Xs(gi)?gi.bind(r,r):Xs(gi.get)?gi.get.bind(r,r):CQ,_o=!Xs(gi)&&Xs(gi.set)?gi.set.bind(r):CQ,to=Lt({get:Fi,set:_o});Object.defineProperty(l,Vt,{enumerable:!0,configurable:!0,get:()=>to.value,set:uo=>to.value=uo})}if(w)for(const Vt in w)jZ(w[Vt],l,r,Vt);if(_){const Vt=Xs(_)?_.call(r):_;Reflect.ownKeys(Vt).forEach(gi=>{XE(gi,Vt[gi])})}F&&az(F,t,"c");function si(Vt,gi){Ss(gi)?gi.forEach(Fi=>Vt(Fi.bind(r))):gi&&Vt(gi.bind(r))}if(si(UoA,j),si(Cc,lA),si(FoA,aA),si(OoA,mA),si(boA,IA),si(koA,tA),si(VoA,mt),si(YoA,Be),si(xoA,ct),si(qZ,PA),si(qg,de),si(PoA,Ke),Ss(Dt))if(Dt.length){const Vt=t.exposed||(t.exposed={});Dt.forEach(gi=>{Object.defineProperty(Vt,gi,{get:()=>r[gi],set:Fi=>r[gi]=Fi})})}else t.exposed||(t.exposed={});Ve&&t.render===CQ&&(t.render=Ve),qt!=null&&(t.inheritAttrs=qt),It&&(t.components=It),re&&(t.directives=re),Ke&&JZ(t)}function zoA(t,i,r=CQ){Ss(t)&&(t=bj(t));for(const l in t){const u=t[l];let p;Ta(u)?"default"in u?p=kI(u.from||l,u.default,!0):p=kI(u.from||l):p=kI(u),Xl(p)?Object.defineProperty(i,l,{enumerable:!0,configurable:!0,get:()=>p.value,set:y=>p.value=y}):i[l]=p}}function az(t,i,r){Zh(Ss(t)?t.map(l=>l.bind(i.proxy)):t.bind(i.proxy),i,r)}function jZ(t,i,r,l){let u=l.includes(".")?r6(r,l):()=>r[l];if(mg(t)){const p=i[t];Xs(p)&&ia(u,p)}else if(Xs(t))ia(u,t.bind(r));else if(Ta(t))if(Ss(t))t.forEach(p=>jZ(p,i,r,l));else{const p=Xs(t.handler)?t.handler.bind(r):i[t.handler];Xs(p)&&ia(u,p,t)}}function WZ(t){const i=t.type,{mixins:r,extends:l}=i,{mixins:u,optionsCache:p,config:{optionMergeStrategies:y}}=t.appContext,w=p.get(i);let _;return w?_=w:!u.length&&!r&&!l?_=i:(_={},u.length&&u.forEach(k=>L1(_,k,y,!0)),L1(_,i,y)),Ta(i)&&p.set(i,_),_}function L1(t,i,r,l=!1){const{mixins:u,extends:p}=i;p&&L1(t,p,r,!0),u&&u.forEach(y=>L1(t,y,r,!0));for(const y in i)if(!(l&&y==="expose")){const w=ZoA[y]||r&&r[y];t[y]=w?w(t[y],i[y]):i[y]}return t}const ZoA={data:gz,props:cz,emits:cz,methods:Zk,computed:Zk,beforeCreate:sE,created:sE,beforeMount:sE,mounted:sE,beforeUpdate:sE,updated:sE,beforeDestroy:sE,beforeUnmount:sE,destroyed:sE,unmounted:sE,activated:sE,deactivated:sE,errorCaptured:sE,serverPrefetch:sE,components:Zk,directives:Zk,watch:$oA,provide:gz,inject:XoA};function gz(t,i){return i?t?function(){return $l(Xs(t)?t.call(this,this):t,Xs(i)?i.call(this,this):i)}:i:t}function XoA(t,i){return Zk(bj(t),bj(i))}function bj(t){if(Ss(t)){const i={};for(let r=0;r1)return r&&Xs(i)?i.call(l&&l.proxy):i}}const ZZ={},XZ=()=>Object.create(ZZ),$Z=t=>Object.getPrototypeOf(t)===ZZ;function tsA(t,i,r,l=!1){const u={},p=XZ();t.propsDefaults=Object.create(null),A6(t,i,u,p);for(const y in t.propsOptions[0])y in u||(u[y]=void 0);r?t.props=l?u:doA(u):t.type.props?t.props=u:t.props=p,t.attrs=p}function isA(t,i,r,l){const{props:u,attrs:p,vnode:{patchFlag:y}}=t,w=Tr(u),[_]=t.propsOptions;let k=!1;if((l||y>0)&&!(y&16)){if(y&8){const F=t.vnode.dynamicProps;for(let j=0;j{_=!0;const[lA,aA]=e6(j,i,!0);$l(y,lA),aA&&w.push(...aA)};!r&&i.mixins.length&&i.mixins.forEach(F),t.extends&&F(t.extends),t.mixins&&t.mixins.forEach(F)}if(!p&&!_)return Ta(t)&&l.set(t,f_),f_;if(Ss(p))for(let F=0;Ft[0]==="_"||t==="$stable",T3=t=>Ss(t)?t.map(IQ):[IQ(t)],ssA=(t,i,r)=>{if(i._n)return i;const l=Li((...u)=>T3(i(...u)),r);return l._c=!1,l},i6=(t,i,r)=>{const l=t._ctx;for(const u in t){if(t6(u))continue;const p=t[u];if(Xs(p))i[u]=ssA(u,p,l);else if(p!=null){const y=T3(p);i[u]=()=>y}}},o6=(t,i)=>{const r=T3(i);t.slots.default=()=>r},s6=(t,i,r)=>{for(const l in i)(r||l!=="_")&&(t[l]=i[l])},nsA=(t,i,r)=>{const l=t.slots=XZ();if(t.vnode.shapeFlag&32){const u=i._;u?(s6(l,i,r),r&&lZ(l,"_",u,!0)):i6(i,l)}else i&&o6(t,i)},rsA=(t,i,r)=>{const{vnode:l,slots:u}=t;let p=!0,y=fa;if(l.shapeFlag&32){const w=i._;w?r&&w===1?p=!1:s6(u,i,r):(p=!i.$stable,i6(i,u)),y=i}else i&&(o6(t,i),y={default:1});if(p)for(const w in u)!t6(w)&&y[w]==null&&delete u[w]},aE=msA;function asA(t){return gsA(t)}function gsA(t,i){const r=lY();r.__VUE__=!0;const{insert:l,remove:u,patchProp:p,createElement:y,createText:w,createComment:_,setText:k,setElementText:F,parentNode:j,nextSibling:lA,setScopeId:aA=CQ,insertStaticContent:mA}=t,IA=(qA,ce,Pe,kt=null,it=null,gt=null,Xt=void 0,$t=null,Ge=!!ce.dynamicChildren)=>{if(qA===ce)return;qA&&!JM(qA,ce)&&(kt=$i(qA),uo(qA,it,gt,!0),qA=null),ce.patchFlag===-2&&(Ge=!1,ce.dynamicChildren=null);const{type:je,ref:Mt,shapeFlag:Rt}=ce;switch(je){case BY:tA(qA,ce,Pe,kt);break;case lE:MA(qA,ce,Pe,kt);break;case OK:qA==null&&PA(ce,Pe,kt,Xt);break;case Kr:It(qA,ce,Pe,kt,it,gt,Xt,$t,Ge);break;default:Rt&1?Ve(qA,ce,Pe,kt,it,gt,Xt,$t,Ge):Rt&6?re(qA,ce,Pe,kt,it,gt,Xt,$t,Ge):(Rt&64||Rt&128)&&je.process(qA,ce,Pe,kt,it,gt,Xt,$t,Ge,bi)}Mt!=null&&it&&k1(Mt,qA&&qA.ref,gt,ce||qA,!ce)},tA=(qA,ce,Pe,kt)=>{if(qA==null)l(ce.el=w(ce.children),Pe,kt);else{const it=ce.el=qA.el;ce.children!==qA.children&&k(it,ce.children)}},MA=(qA,ce,Pe,kt)=>{qA==null?l(ce.el=_(ce.children||""),Pe,kt):ce.el=qA.el},PA=(qA,ce,Pe,kt)=>{[qA.el,qA.anchor]=mA(qA.children,ce,Pe,kt,qA.el,qA.anchor)},ge=({el:qA,anchor:ce},Pe,kt)=>{let it;for(;qA&&qA!==ce;)it=lA(qA),l(qA,Pe,kt),qA=it;l(ce,Pe,kt)},de=({el:qA,anchor:ce})=>{let Pe;for(;qA&&qA!==ce;)Pe=lA(qA),u(qA),qA=Pe;u(ce)},Ve=(qA,ce,Pe,kt,it,gt,Xt,$t,Ge)=>{ce.type==="svg"?Xt="svg":ce.type==="math"&&(Xt="mathml"),qA==null?Be(ce,Pe,kt,it,gt,Xt,$t,Ge):Ke(qA,ce,it,gt,Xt,$t,Ge)},Be=(qA,ce,Pe,kt,it,gt,Xt,$t)=>{let Ge,je;const{props:Mt,shapeFlag:Rt,transition:Oi,dirs:Qo}=qA;if(Ge=qA.el=y(qA.type,gt,Mt&&Mt.is,Mt),Rt&8?F(Ge,qA.children):Rt&16&&mt(qA.children,Ge,null,kt,it,FK(qA,gt),Xt,$t),Qo&&LM(qA,null,kt,"created"),ct(Ge,qA,qA.scopeId,Xt,kt),Mt){for(const oo in Mt)oo!=="value"&&!dL(oo)&&p(Ge,oo,null,Mt[oo],gt,kt);"value"in Mt&&p(Ge,"value",null,Mt.value,gt),(je=Mt.onVnodeBeforeMount)&&aQ(je,kt,qA)}Qo&&LM(qA,null,kt,"beforeMount");const To=csA(it,Oi);To&&Oi.beforeEnter(Ge),l(Ge,ce,Pe),((je=Mt&&Mt.onVnodeMounted)||To||Qo)&&aE(()=>{je&&aQ(je,kt,qA),To&&Oi.enter(Ge),Qo&&LM(qA,null,kt,"mounted")},it)},ct=(qA,ce,Pe,kt,it)=>{if(Pe&&aA(qA,Pe),kt)for(let gt=0;gt{for(let je=Ge;je{const $t=ce.el=qA.el;let{patchFlag:Ge,dynamicChildren:je,dirs:Mt}=ce;Ge|=qA.patchFlag&16;const Rt=qA.props||fa,Oi=ce.props||fa;let Qo;if(Pe&&UM(Pe,!1),(Qo=Oi.onVnodeBeforeUpdate)&&aQ(Qo,Pe,ce,qA),Mt&&LM(ce,qA,Pe,"beforeUpdate"),Pe&&UM(Pe,!0),(Rt.innerHTML&&Oi.innerHTML==null||Rt.textContent&&Oi.textContent==null)&&F($t,""),je?Dt(qA.dynamicChildren,je,$t,Pe,kt,FK(ce,it),gt):Xt||gi(qA,ce,$t,null,Pe,kt,FK(ce,it),gt,!1),Ge>0){if(Ge&16)qt($t,Rt,Oi,Pe,it);else if(Ge&2&&Rt.class!==Oi.class&&p($t,"class",null,Oi.class,it),Ge&4&&p($t,"style",Rt.style,Oi.style,it),Ge&8){const To=ce.dynamicProps;for(let oo=0;oo{Qo&&aQ(Qo,Pe,ce,qA),Mt&&LM(ce,qA,Pe,"updated")},kt)},Dt=(qA,ce,Pe,kt,it,gt,Xt)=>{for(let $t=0;$t{if(ce!==Pe){if(ce!==fa)for(const gt in ce)!dL(gt)&&!(gt in Pe)&&p(qA,gt,ce[gt],null,it,kt);for(const gt in Pe){if(dL(gt))continue;const Xt=Pe[gt],$t=ce[gt];Xt!==$t&>!=="value"&&p(qA,gt,$t,Xt,it,kt)}"value"in Pe&&p(qA,"value",ce.value,Pe.value,it)}},It=(qA,ce,Pe,kt,it,gt,Xt,$t,Ge)=>{const je=ce.el=qA?qA.el:w(""),Mt=ce.anchor=qA?qA.anchor:w("");let{patchFlag:Rt,dynamicChildren:Oi,slotScopeIds:Qo}=ce;Qo&&($t=$t?$t.concat(Qo):Qo),qA==null?(l(je,Pe,kt),l(Mt,Pe,kt),mt(ce.children||[],Pe,Mt,it,gt,Xt,$t,Ge)):Rt>0&&Rt&64&&Oi&&qA.dynamicChildren?(Dt(qA.dynamicChildren,Oi,Pe,it,gt,Xt,$t),(ce.key!=null||it&&ce===it.subTree)&&N3(qA,ce,!0)):gi(qA,ce,Pe,Mt,it,gt,Xt,$t,Ge)},re=(qA,ce,Pe,kt,it,gt,Xt,$t,Ge)=>{ce.slotScopeIds=$t,qA==null?ce.shapeFlag&512?it.ctx.activate(ce,Pe,kt,Xt,Ge):qe(ce,Pe,kt,it,gt,Xt,Ge):ft(qA,ce,Ge)},qe=(qA,ce,Pe,kt,it,gt,Xt)=>{const $t=qA.component=vsA(qA,kt,it);if(dY(qA)&&($t.ctx.renderer=bi),wsA($t,!1,Xt),$t.asyncDep){if(it&&it.registerDep($t,si,Xt),!qA.el){const Ge=$t.subTree=Nt(lE);MA(null,Ge,ce,Pe)}}else si($t,qA,ce,Pe,it,gt,Xt)},ft=(qA,ce,Pe)=>{const kt=ce.component=qA.component;if(QsA(qA,ce,Pe))if(kt.asyncDep&&!kt.asyncResolved){Vt(kt,ce,Pe);return}else kt.next=ce,kt.update();else ce.el=qA.el,kt.vnode=ce},si=(qA,ce,Pe,kt,it,gt,Xt)=>{const $t=()=>{if(qA.isMounted){let{next:Rt,bu:Oi,u:Qo,parent:To,vnode:oo}=qA;{const an=n6(qA);if(an){Rt&&(Rt.el=oo.el,Vt(qA,Rt,Xt)),an.asyncDep.then(()=>{qA.isUnmounted||$t()});return}}let No=Rt,$s;UM(qA,!1),Rt?(Rt.el=oo.el,Vt(qA,Rt,Xt)):Rt=oo,Oi&&u1(Oi),($s=Rt.props&&Rt.props.onVnodeBeforeUpdate)&&aQ($s,To,Rt,oo),UM(qA,!0);const rn=uz(qA),us=qA.subTree;qA.subTree=rn,IA(us,rn,j(us.el),$i(us),qA,it,gt),Rt.el=rn.el,No===null&&psA(qA,rn.el),Qo&&aE(Qo,it),($s=Rt.props&&Rt.props.onVnodeUpdated)&&aE(()=>aQ($s,To,Rt,oo),it)}else{let Rt;const{el:Oi,props:Qo}=ce,{bm:To,m:oo,parent:No,root:$s,type:rn}=qA,us=M_(ce);UM(qA,!1),To&&u1(To),!us&&(Rt=Qo&&Qo.onVnodeBeforeMount)&&aQ(Rt,No,ce),UM(qA,!0);{$s.ce&&$s.ce._injectChildStyle(rn);const an=qA.subTree=uz(qA);IA(null,an,Pe,kt,qA,it,gt),ce.el=an.el}if(oo&&aE(oo,it),!us&&(Rt=Qo&&Qo.onVnodeMounted)){const an=ce;aE(()=>aQ(Rt,No,an),it)}(ce.shapeFlag&256||No&&M_(No.vnode)&&No.vnode.shapeFlag&256)&&qA.a&&aE(qA.a,it),qA.isMounted=!0,ce=Pe=kt=null}};qA.scope.on();const Ge=qA.effect=new dZ($t);qA.scope.off();const je=qA.update=Ge.run.bind(Ge),Mt=qA.job=Ge.runIfDirty.bind(Ge);Mt.i=qA,Mt.id=qA.uid,Ge.scheduler=()=>_3(Mt),UM(qA,!0),je()},Vt=(qA,ce,Pe)=>{ce.component=qA;const kt=qA.vnode.props;qA.vnode=ce,qA.next=null,isA(qA,ce.props,kt,Pe),rsA(qA,ce.children,Pe),Vy(),ez(qA),Jy()},gi=(qA,ce,Pe,kt,it,gt,Xt,$t,Ge=!1)=>{const je=qA&&qA.children,Mt=qA?qA.shapeFlag:0,Rt=ce.children,{patchFlag:Oi,shapeFlag:Qo}=ce;if(Oi>0){if(Oi&128){_o(je,Rt,Pe,kt,it,gt,Xt,$t,Ge);return}else if(Oi&256){Fi(je,Rt,Pe,kt,it,gt,Xt,$t,Ge);return}}Qo&8?(Mt&16&&Ko(je,it,gt),Rt!==je&&F(Pe,Rt)):Mt&16?Qo&16?_o(je,Rt,Pe,kt,it,gt,Xt,$t,Ge):Ko(je,it,gt,!0):(Mt&8&&F(Pe,""),Qo&16&&mt(Rt,Pe,kt,it,gt,Xt,$t,Ge))},Fi=(qA,ce,Pe,kt,it,gt,Xt,$t,Ge)=>{qA=qA||f_,ce=ce||f_;const je=qA.length,Mt=ce.length,Rt=Math.min(je,Mt);let Oi;for(Oi=0;Oi