diff --git a/app/artifacts/patient_appointment_density/appointments_1024x640.png b/app/artifacts/patient_appointment_density/appointments_1024x640.png
index 83cfc4cee..64ef0aa17 100644
Binary files a/app/artifacts/patient_appointment_density/appointments_1024x640.png and b/app/artifacts/patient_appointment_density/appointments_1024x640.png differ
diff --git a/app/artifacts/patient_appointment_density/appointments_1366x768.png b/app/artifacts/patient_appointment_density/appointments_1366x768.png
index f927c4fa3..1a435e4c8 100644
Binary files a/app/artifacts/patient_appointment_density/appointments_1366x768.png and b/app/artifacts/patient_appointment_density/appointments_1366x768.png differ
diff --git a/app/artifacts/patient_appointment_density/patients_1024x640.png b/app/artifacts/patient_appointment_density/patients_1024x640.png
index bec10d926..a2e433bdb 100644
Binary files a/app/artifacts/patient_appointment_density/patients_1024x640.png and b/app/artifacts/patient_appointment_density/patients_1024x640.png differ
diff --git a/app/artifacts/patient_appointment_density/patients_1366x768.png b/app/artifacts/patient_appointment_density/patients_1366x768.png
index 9a8e0100d..d74ac6456 100644
Binary files a/app/artifacts/patient_appointment_density/patients_1366x768.png and b/app/artifacts/patient_appointment_density/patients_1366x768.png differ
diff --git a/app/artifacts/prescription_list_density/prescriptions_1366x768.png b/app/artifacts/prescription_list_density/prescriptions_1366x768.png
index 76ab87598..ff03f3f63 100644
Binary files a/app/artifacts/prescription_list_density/prescriptions_1366x768.png and b/app/artifacts/prescription_list_density/prescriptions_1366x768.png differ
diff --git a/app/artifacts/reception_ai_exact/reception.png b/app/artifacts/reception_ai_exact/reception.png
index dbd6c3b85..b1b47b8b9 100644
Binary files a/app/artifacts/reception_ai_exact/reception.png and b/app/artifacts/reception_ai_exact/reception.png differ
diff --git a/app/artifacts/subwindow_exact/prescription_ai_report_920x760.png b/app/artifacts/subwindow_exact/prescription_ai_report_920x760.png
index a16214673..1dc7109a1 100644
Binary files a/app/artifacts/subwindow_exact/prescription_ai_report_920x760.png and b/app/artifacts/subwindow_exact/prescription_ai_report_920x760.png differ
diff --git a/app/artifacts/subwindow_exact/prescription_detail_920x780.png b/app/artifacts/subwindow_exact/prescription_detail_920x780.png
index c0143bd85..029dd3ca9 100644
Binary files a/app/artifacts/subwindow_exact/prescription_detail_920x780.png and b/app/artifacts/subwindow_exact/prescription_detail_920x780.png differ
diff --git a/app/artifacts/subwindow_exact/prescription_editor_860x900.png b/app/artifacts/subwindow_exact/prescription_editor_860x900.png
index faac679bd..750cac325 100644
Binary files a/app/artifacts/subwindow_exact/prescription_editor_860x900.png and b/app/artifacts/subwindow_exact/prescription_editor_860x900.png differ
diff --git a/app/research/client-ui-design.md b/app/research/client-ui-design.md
new file mode 100644
index 000000000..0a780bbb3
--- /dev/null
+++ b/app/research/client-ui-design.md
@@ -0,0 +1,72 @@
+# 医生工作站客户端设计规范
+
+本轮覆盖现有 PySide6 客户端与 Vue 视频伴随窗口。按 `redesign-existing-projects` 审查现有页面,结合 `minimalist-ui` 的扁平化原则实施;医疗工作台保留信息密度,不套用营销页面的大留白、装饰动效或布局模板。
+
+## 审查结论
+
+- 主框架与业务页面原先并存科技蓝、紫蓝及多套中性色;登录、AI、诊单的控件也各自定义配色。
+- 页面内圆角、边框和层级不统一,部分阴影、悬浮位移和过渡使操作显得跳动。
+- 小窗口的表格、诊单与视频操作需要分别验证,不能依靠整体缩小解决。
+- 键盘焦点、禁用与选择状态应始终可识别,不通过改变控件几何位置表达状态。
+
+## 视觉系统
+
+设计变量以 `src/doctor_workstation/ui/design_system.py` 为准。旧页面通过 `clinical_stylesheet` 迁移已知的浅色主题颜色,新样式使用命名变量。医学数据曲线、模型标识色和深色主题不进行全局替色。
+
+| 角色 | 值 | 使用场景 |
+| --- | --- | --- |
+| 主色 | `#4267B2` | 主操作、选中项、重要链接 |
+| 主色浅底 | `#EAF0FB` | 选中背景、轻量状态 |
+| 画布 | `#F5F7FA` | 主窗口背景 |
+| 表面 | `#FFFFFF` | 内容区、对话框 |
+| 次级表面 | `#F7F9FC` | 筛选栏、分组、只读区域 |
+| 侧栏 | `#F0F3F8` | 导航区域 |
+| 标题 / 正文 | `#223047` / `#344258` | 文字层级 |
+| 次级文字 | `#647287` | 说明、辅助信息 |
+| 边框 / 强边框 | `#E6EAF0` / `#D4DCE8` | 低对比结构线、输入边界 |
+| 成功 / 警示 / 危险 | `#287B65` / `#96601D` / `#B54A59` | 保留明确语义,不只依赖颜色 |
+
+- 圆角:标签 6 px、输入与按钮 10 px、内容面板 16 px、独立窗口 20 px。
+- 间距:8 / 12 / 16 / 24 px,根据现有表格密度调整,不整体放大行高。
+- 字体:继续使用打包的中文字体与现有可读字号;标题层级通过字重、字号和间距体现。
+- 表面:纯色为主,轻边框划分区域,减少嵌套卡片与装饰阴影。
+- 按钮:每个操作组主次清晰;次要操作使用浅底或边框;终止、删除等危险操作保留语义色。
+
+## 交互规范
+
+- 悬浮、按下和焦点反馈不移动布局、不改变控件尺寸。
+- 动画短而克制;滚动可被键盘、拖动、程序定位与反向滚动即时打断;尊重减少动画设置。
+- 切换页面保留原有路由、权限和数据加载机制。
+- 登录表单保留密码存储、服务器设置与提交保护;组合密码框使用实际 Qt 焦点状态。
+- 大小窗口都必须能找到主要操作,优先局部滚动而非把全部内容压小。
+- 视频保留原有截图捕获、确认上传、大预览和小窗关闭返回大窗逻辑;视觉样式不改变媒体内容或尺寸计算。
+
+## 覆盖范围
+
+1. 登录与品牌区:扁平品牌面板、简洁功能说明、清晰表单与焦点。
+2. 主框架:导航、顶部搜索、工具按钮、标签与 AI 入口。
+3. 列表:挂号、接诊记录、患者、处方库、已开处方、业务订单及患者进度。
+4. 诊疗:接诊台、预约抽屉、诊单编辑与只读、指标和保存状态。
+5. 辅助窗口:AI 问诊、处方编辑、处方解读与报告控制台。
+6. 视频:通话控制、聊天、录制提示与截图确认。
+
+## 验收方式
+
+`scripts/render_client_design.py` 使用演示仓库生成 1440 × 900、1024 × 640 的真实页面,以及 1280 × 800、860 × 640 的登录页;输出 `artifacts/client-design/index.html` 与原尺寸 PNG。诊疗和 AI 弹窗使用现有专用渲染脚本验证。
+
+检查重点:小窗操作可达、中文可读、表格信息密度、长文本换行、键盘焦点、布局稳定、登录与页面路由契约、视频截图与窗口状态回归。生产服务与真实患者资料不用于视觉验收。
+
+本轮共享组件还覆盖筛选展开按钮、列表加载状态、聊天通知、更新提示、本机录音队列、媒体预览和上传进度。860 × 640 登录表单完整显示,不需要为纯留白滚动。
+
+## 验证记录与边界
+
+- 主框架、登录、遮罩与动效首轮 100 项通过;新增组合密码框键盘焦点检查通过。
+- 小窗登录与焦点补测 2 项、最终登录及主框架复查 68 项通过。
+- 筛选、无限列表、通知、更新窗口与本机录音队列 37 项通过。
+- 原生视频截图、截图预览尺寸、小窗关闭与视频契约 199 项通过。
+- 视频前端 26 项检查通过,生产 dist 已重新构建。
+- 当前视频 dist 在 1120 × 760、540 × 356、440 × 300 的合成画面中完成 27 项布局检查,截图与关闭事件正常,未访问外部服务。
+- 临床页面、AI、处方及图表分别完成专项测试和真实控件渲染,详细记录位于 `artifacts/client-design/*-report.md`。
+- 最终修改文件的 Ruff 与 `git diff --check` 均通过;AI 工作区及快捷操作权限最后复查 24 项通过。
+
+此记录不表示整仓所有历史测试全部通过。扩展测试中存在已用原始 HEAD 复现的 AI 流式/延迟生命周期失败、共享 QApplication 样式引发的图表测试顺序依赖,以及 Windows Qt 网络模块异常;本轮没有改变相关业务行为。未连接真实面诊服务,也未重新打包或安装 Windows 客户端。
diff --git a/app/research/im-ai-assistance.md b/app/research/im-ai-assistance.md
new file mode 100644
index 000000000..19774606a
--- /dev/null
+++ b/app/research/im-ai-assistance.md
@@ -0,0 +1,75 @@
+# IM 问诊 AI 辅助
+
+用户确认范围:在现有 IM 问诊窗口内增加「总结病情」「建议追问」「起草回复」。结果供医生审阅,医生主动填入输入框后编辑并手动发送。
+
+## 集成契约
+
+- 复用 `stream_diagnosis_ai`:总结使用 `summary`,追问和回复使用 `custom`。不新增模型配置、不把凭据传到浏览器、不新增服务端路由。
+- 每次生成前,通过 `sync_im_chat_messages(scope="current", sync_token=...)` 完成当前账号对话归档;响应 `completed=true` 且没有错误后才能调用 AI。准备失败明确报错,不静默降级为旧聊天。服务器按授权诊单聚合临床资料与归档 IM,提示词限定本次医生账号的近期对话。
+- 三项提示词保持 500 字以内;不在提示词中挤入、截断完整聊天或未发送草稿。
+- AI 独立后台 worker,不占用通话、录音和消息发送的队列。
+
+原生配置 `DoctorCallConfig.imAi`:`{version:1, enabled:boolean, sessionId:string, reason?:string}`。宿主生成 sessionId,每个新窗口独立。上层将 AI 权限布尔值贯穿 launcher;默认拒绝。
+
+浏览器到原生:
+
+```json
+{"source":"doctor-call","event":"im-ai-request","sessionId":"host-uuid","requestId":"uuid","contextKey":"frontend-context","diagnosisId":"501","appointmentId":101,"action":"summary"}
+```
+
+取消使用同一组身份字段及 `event="im-ai-cancel"`。只允许 `summary | followup | reply`。宿主核验可信文档、窗口未关闭、AI 权限、会话、诊单、挂号和请求格式;实际 repository 调用始终使用宿主绑定诊单。
+
+原生通过 `window.doctorConsultation.imAiResult(payload)` 返回相同身份字段与:
+
+```text
+status: loading | streaming | success | error | cancelled
+text?: 累积正文(流式及最终)
+message?: 简短进度或错误
+modelLabel?: 服务端模型标签
+warnings?: string[]
+```
+
+所有数据使用 JSON 序列化,桥接正文仍为原始文本。页面通过受限 Markdown 渲染器显示标题、重点、列表和表格;原始 HTML 被转义,链接和图片只保留文字,不执行内容或加载外部资源。客户端截止时间 180 秒,超时发送取消;原生聊天同步有独立有界预算,AI 沿用现有 105 秒传输预算。取消请求由独立线程发送,GUI 不等待网络。停止只是停止本次接收,不冒称上游工作已确认停止。
+
+## 界面与状态
+
+- 宽屏右侧约 330 px 辅助区;窄屏可收起抽屉,独立滚动,操作和关闭可达。沿用现有蓝色、圆角和轻边框。
+- AI loading 不阻塞 IM 输入、发送、加载更多和视频控制。
+- 只有完整成功结果允许填入;追问与回复可填入,病情总结默认只读。非空草稿明确追加,超过 3000 字拒绝追加而不截断原文。
+- 切换会话清空 AI 状态和草稿;迟到、重复、身份不匹配结果全部忽略。
+- 异步手动发送成功仅清空当时提交且没有继续修改的草稿。
+- 结果注明医生复核,展示服务端临床复核提示;不会自动发送、写病历或开处方。
+
+## 验证要求
+
+离线 fake repository 验证同步续拉、失败不生成、取消、终态、身份隔离、权限与关闭;Node 测试验证桥接状态/计时器、草稿追加和发送隔离;使用真实构建产物和合成消息验证宽屏与紧凑窗口。回归截图、录音收尾、通话权限与 IM 流程。验证不得访问真实患者、IM 或 AI 服务。
+
+## 交付与验证结果(2026-10-29)
+
+- `app.py` 在实际打开窗口时读取当前账号的 `tcm.diagnosis/aiAssistant` 权限,经 launcher 传入原生窗口;未配置权限时默认关闭,不采用聊天载荷中的权限标记。
+- 三项功能已接入真实 Qt bridge 和现有流式服务;宽屏常驻侧栏,980 px 及以下窗口使用可收起抽屉。中文输入法选词时按 Enter 不发送,异步发送不会清除医生随后编辑的草稿。
+- 合并后 Python 回归 **364 项通过**:包括新增 AI 服务/仓库/窗口、权限入口、IM、视频契约、截图、小窗关闭及大预览等。运行使用独立 `artifacts/im-ai/final-integration-tmp`,未访问外部服务。
+- 前端 **45 项 Node 行为测试通过**,`vue-tsc` 与 Vite 构建通过;实际 dist 在 1120×760、980×640、540×356、440×300 下 **42 项界面检查通过**。离线夹具只使用合成消息和结果,外部请求尝试为 0。
+- Ruff 与 `git diff --check` 通过。首次交付构建入口:`index-CnqWQu6O.js`、`index-BwArpbVK.css`。
+- 截图、可复现夹具和详细报告存放在 `app/artifacts/im-ai/`。未验证真实账号的模型响应;未生成 Windows 安装包。源码运行需重启客户端,已安装版本需重新打包后安装。
+
+停止接收后,原生端会独立请求取消;在旧请求实际退出前重试会提示稍后再试,避免重复模型请求。聊天同步失败时不使用旧归档静默生成,助手显示错误并允许重试。
+
+## 结果排版与切换改进(2026-10-29)
+
+- 模型输出的 Markdown 标题、加粗、列表、引用、代码和简单表格转换为安全的结构化展示;重点以加粗和浅蓝底色标记,结构标题使用蓝色引导线。不依据医学关键词自行推断重点。未闭合的流式片段保持可读原文。
+- 三项操作在当前窗口会话内分别保留状态、正文、模型标签和复核提示。顶部按钮首次点击生成,之后只切换查看;底部“重新生成/重试”才会再发请求。生成中可以阅读其他已完成结果,后台更新不能覆盖当前阅读页。
+- 每项保留独立滚动位置,换患者、关闭或重开会话时清空。结果仅保存在内存中,不增加本地患者内容持久化。
+- 填入草稿前去除 Markdown 排版符号,保留原文、数值和列表含义,再执行 3000 字长度检查;仍不覆盖原稿、不自动发送。
+- 本次前端 **61 项行为测试通过**,包含安全渲染、草稿转换、缓存、显式重生成、后台流式隔离及现有截图/通话守卫;TypeScript 与 Vite 构建通过。
+- 真实 dist 配合生产 AI controller 源码和离线宿主替身,在四种窗口尺寸完成 **20 项可点击/布局检查**,以及切换不发请求、显式刷新、后台生成、独立阅读位置、原稿追加及注入防护断言。外部请求为 0。
+- 证据:`artifacts/im-ai/refinements-visual-checks.json`、`render_im_ai_refinements.py` 与 `im-ai-styled-cached-*.png`。未打包安装程序。
+
+## 可调宽度、首次总结与指标强调(2026-10-29)
+
+- 聊天与助手之间增加可左右拖动的分隔线,宽屏保留至少 480 px 聊天区域;窄屏抽屉也可调整,最大宽度仍留出可操作的边缘。支持方向键、Home/End、Enter 或双击恢复默认,Escape 取消本次拖动。窗口变更、失焦与关闭释放指针捕获。宽屏和抽屉宽度分别记忆在当前窗口内。
+- 进入有权限的 IM 会话后,首次总结等待当前登录、聊天、Qt 通道及原生 `imAiReady(sessionId)` 确认;准备等待最多 30 秒。每个会话只自动尝试一次,不因重连、标签切换、展开面板或失败自动重试。医生提前手动操作会取消待启动的自动总结。关闭和换会话清理计时器及旧结果。
+- 普通文本中的血糖、血压、糖化血红蛋白、体重等指标名称及带单位的数值自动强调,支持范围、小数和血压组合。名称加深,数值加粗并显示浅蓝底色,不依赖模型输出 Markdown。原始数值、单位、否定和不确定表述保持不变;没有新增医学阈值判断或自动风险分级。
+- **97 项前端测试、318 项客户端回归通过**,TypeScript、Vite 和 Ruff 检查通过,`git diff --check` 无问题。当前构建:`index-C_tMrPfb.js`、`index-CMN1CXTr.css`。
+- 实际构建页面在 1634×1008、1120×760、980×640、540×356、440×300 下完成真实 Qt 鼠标拖动、键盘调整、取消、跨断点释放及指标样式检查,**15 项布局/点击检查通过**,自动选择与请求次数断言通过,外部请求为 0。
+- 证据:`artifacts/im-ai/render_im_ai_resizing.py`、`resizing-visual-checks.json`、`im-ai-metrics-resizable-*.png`。本轮未生成安装包;原生就绪握手需重启使用最新源码的客户端。
diff --git a/app/scripts/render_client_design.py b/app/scripts/render_client_design.py
new file mode 100644
index 000000000..4414ce522
--- /dev/null
+++ b/app/scripts/render_client_design.py
@@ -0,0 +1,143 @@
+"""Render the real native client with synthetic data for UI design review."""
+
+from __future__ import annotations
+
+import argparse
+import html
+import json
+import os
+from pathlib import Path
+
+os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
+os.environ.setdefault("DOCTOR_MOTION", "off")
+
+from PySide6.QtCore import QSettings, QThreadPool
+from PySide6.QtGui import QImage
+from PySide6.QtTest import QTest
+from PySide6.QtWidgets import QApplication
+
+from doctor_workstation.services import DemoDoctorRepository
+from doctor_workstation.ui import ShellWindow, apply_theme
+from doctor_workstation.ui.login import LoginWindow
+
+ROUTES = {
+ "appointments": "挂号列表",
+ "consultations": "问诊列表",
+ "patients": "我的患者",
+ "prescription_library": "我的处方库",
+ "prescriptions": "已开处方",
+ "reception": "接诊台",
+}
+
+
+def settle(app: QApplication) -> None:
+ for _ in range(4):
+ QThreadPool.globalInstance().waitForDone(3000)
+ app.processEvents()
+ QTest.qWait(75)
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--output", type=Path, default=Path("artifacts/client-design"))
+ args = parser.parse_args()
+ output = args.output.resolve()
+ output.mkdir(parents=True, exist_ok=True)
+ app = QApplication.instance() or QApplication([])
+ apply_theme(app)
+ repo = DemoDoctorRepository()
+ records = []
+
+ def capture(window, name: str, title: str) -> None:
+ settle(app)
+ filename = f"{name}.png"
+ if not window.grab().save(str(output / filename)):
+ raise RuntimeError(f"Could not save {filename}")
+ records.append({
+ "title": title, "file": filename,
+ "width": window.width(), "height": window.height(),
+ })
+
+ # Isolate preview settings from the user's saved account and credentials.
+ settings = QSettings(str(output / "preview-login.ini"), QSettings.Format.IniFormat)
+ settings.clear()
+ login = LoginWindow(repo, settings=settings)
+ login.show()
+ for width, height in ((1280, 800), (860, 640)):
+ login.resize(width, height)
+ capture(login, f"login-{width}", "登录工作站")
+ login.close()
+
+ session = repo.login(repo.DEMO_ACCOUNT, repo.DEMO_PASSWORD)
+ shell = ShellWindow(
+ repo, {"session": session, "demo_mode": True}, permissions=session.permissions,
+ )
+ shell.show()
+ try:
+ for width, height in ((1440, 900), (1024, 640)):
+ shell.resize(width, height)
+ for route, title in ROUTES.items():
+ shell.navigate(route)
+ capture(shell, f"{route}-{width}", title)
+ finally:
+ settle(app)
+ shell.close()
+
+ # Include independently rendered dialog/media fixtures when available.
+ supplementary = [
+ ("patient_orders_1366x768.png", "患者业务订单"),
+ ("patient_progress_1366x768.png", "患者进度"),
+ ("clinical-after/appointment_drawer_1440x900.png", "预约编辑"),
+ ("clinical-after/diagnosis_edit_1440x900.png", "诊单编辑"),
+ ("clinical-after/diagnosis_edit_1024x640.png", "诊单编辑 · 紧凑窗口"),
+ ("clinical-after/diagnosis_index_1440x900.png", "诊单列表"),
+ ("assistant-1440.png", "AI 问诊"),
+ ("assistant-1080.png", "AI 问诊 · 紧凑窗口"),
+ ("../subwindow_exact/prescription_editor_860x900.png", "处方编辑"),
+ ("../subwindow_exact/prescription_ai_report_920x760.png", "处方报告"),
+ ("video-call-1120x760.png", "视频面诊"),
+ ("video-call-440x300.png", "视频面诊 · 小窗"),
+ ("video-chat-440x300.png", "视频聊天 · 小窗"),
+ ("video-preview-1120x760.png", "视频截图确认"),
+ ]
+ for filename, title in supplementary:
+ preview = QImage(str(output / filename))
+ if not preview.isNull():
+ records.append({
+ "title": title, "file": filename,
+ "width": preview.width(), "height": preview.height(),
+ })
+
+ (output / "gallery.json").write_text(
+ json.dumps(records, ensure_ascii=False, indent=2), encoding="utf-8",
+ )
+ cards = []
+ for record in records:
+ filename = html.escape(record["file"])
+ title = html.escape(record["title"])
+ cards.append(
+ f'{title} {record["width"]} × {record["height"]}'
+ f'
'
+ ''
+ )
+ (output / "index.html").write_text(
+ ''
+ ''
+ '
医生工作站 · 客户端设计验收医生工作站 · 客户端设计验收
'
+ '使用演示数据渲染的真实客户端。点击图片查看原始尺寸。
'
+ + "".join(cards)
+ + '',
+ encoding="utf-8",
+ )
+ print(output / "index.html")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/app/src/doctor_workstation/app.py b/app/src/doctor_workstation/app.py
index fdc81e084..af97365f5 100644
--- a/app/src/doctor_workstation/app.py
+++ b/app/src/doctor_workstation/app.py
@@ -41,6 +41,7 @@ from doctor_workstation.ui.widgets import (
friendly_error,
gender_text,
get_value,
+ has_permission,
run_async,
set_authentication_expired_handler,
show_toast,
@@ -939,6 +940,11 @@ class ApplicationController(QObject):
open_im=open_im,
patient_name=patient_name,
patient_case=patient_case,
+ can_ai_assistant=has_permission(
+ getattr(self.shell_window, "permissions", None),
+ "tcm.diagnosis/aiAssistant",
+ default=False,
+ ),
on_open_diagnosis=lambda current_id=diagnosis_id, current_key=call_key: (
self._open_video_diagnosis(current_id, call_key=current_key)
),
diff --git a/app/src/doctor_workstation/services/mock_repository.py b/app/src/doctor_workstation/services/mock_repository.py
index 023fd9a73..3c40de4ad 100644
--- a/app/src/doctor_workstation/services/mock_repository.py
+++ b/app/src/doctor_workstation/services/mock_repository.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import hashlib
import json
+import re
import struct
import zlib
from collections.abc import Callable, Mapping, Sequence
@@ -2846,11 +2847,22 @@ class DemoDoctorRepository:
}
)
- def sync_im_chat_messages(self, diagnosis_id: int) -> dict[str, Any]:
- """Acknowledge the same asynchronous sync contract in demo mode."""
+ def sync_im_chat_messages(
+ self, diagnosis_id: int, *, scope: str = "", sync_token: str = ""
+ ) -> dict[str, Any]:
+ """Complete synthetic archive sync while retaining the legacy receipt."""
self._find_consultation(diagnosis_id)
- return {"queued": True, "diagnosis_id": diagnosis_id}
+ if scope not in {"", "current"}:
+ raise ValueError("IM sync scope must be empty or current")
+ if not isinstance(sync_token, str) or (
+ sync_token and re.fullmatch(r"[a-f0-9]{48}", sync_token) is None
+ ):
+ raise ValueError("IM sync token is invalid")
+ return {
+ "queued": True, "diagnosis_id": diagnosis_id,
+ "completed": True, "phase": "completed", "errors": [],
+ }
def list_diagnosis_appointment_logs(self, diagnosis_id: int) -> list[dict[str, Any]]:
"""Build demo audit rows from the diagnosis appointments."""
diff --git a/app/src/doctor_workstation/services/repository.py b/app/src/doctor_workstation/services/repository.py
index aa3e01765..ec10c3109 100644
--- a/app/src/doctor_workstation/services/repository.py
+++ b/app/src/doctor_workstation/services/repository.py
@@ -692,8 +692,10 @@ class DoctorRepository(Protocol):
) -> dict[str, Any]:
"""Return diagnosis IM messages, defaulting to the fast archive-only path."""
- def sync_im_chat_messages(self, diagnosis_id: int) -> Any:
- """Queue the server-side IM archive synchronisation job."""
+ def sync_im_chat_messages(
+ self, diagnosis_id: int, *, scope: str = "", sync_token: str = ""
+ ) -> Any:
+ """Advance one server-side archive page; inspect completed before using it."""
def list_diagnosis_appointment_logs(self, diagnosis_id: int) -> list[dict[str, Any]]:
"""Return per-diagnosis registration / cancellation audit rows."""
@@ -2602,12 +2604,27 @@ class RemoteDoctorRepository:
)
return dict(_require_mapping(payload, "tcm.diagnosis/getImChatMessages"))
- def sync_im_chat_messages(self, diagnosis_id: int) -> Any:
- """Queue the confirmed shutdown-function archive sync endpoint."""
+ def sync_im_chat_messages(
+ self, diagnosis_id: int, *, scope: str = "", sync_token: str = ""
+ ) -> Any:
+ """Advance a bounded archive page, preserving legacy no-option callers."""
if diagnosis_id <= 0:
raise ValueError("diagnosis_id must be positive")
- return self.client.post("tcm.diagnosis/triggerImChatSync", {"diagnosis_id": diagnosis_id})
+ if scope not in {"", "current"}:
+ raise ValueError("IM sync scope must be empty or current")
+ if not isinstance(sync_token, str) or (
+ sync_token and re.fullmatch(r"[a-f0-9]{48}", sync_token) is None
+ ):
+ raise ValueError("IM sync token is invalid")
+ payload: dict[str, Any] = {"diagnosis_id": diagnosis_id}
+ if scope:
+ payload["scope"] = scope
+ if sync_token:
+ payload["sync_token"] = sync_token
+ return _client_request(
+ self.client, "post", "tcm.diagnosis/triggerImChatSync", payload, timeout=15.0
+ )
def list_diagnosis_appointment_logs(self, diagnosis_id: int) -> list[dict[str, Any]]:
"""Return registration/cancellation logs from ``guahaoLogList``."""
diff --git a/app/src/doctor_workstation/ui/appointment_drawer.py b/app/src/doctor_workstation/ui/appointment_drawer.py
index 19bcadfe1..aba2a6b9b 100644
--- a/app/src/doctor_workstation/ui/appointment_drawer.py
+++ b/app/src/doctor_workstation/ui/appointment_drawer.py
@@ -23,7 +23,6 @@ from PySide6.QtWidgets import (
QComboBox,
QDialog,
QFrame,
- QGraphicsDropShadowEffect,
QGraphicsOpacityEffect,
QHBoxLayout,
QLabel,
@@ -43,6 +42,7 @@ from PySide6.QtWidgets import (
)
from ..core.appointment_modes import APPOINTMENT_MODES
+from .design_system import clinical_stylesheet
from .theme import main_window_target_rect
from .widgets import (
display_text,
@@ -84,8 +84,8 @@ QDialog#AppointmentDrawerOverlay QToolButton#AppointmentDrawerClose {
min-height: 32px;
max-height: 32px;
padding: 0;
- border: 0;
- border-radius: 4px;
+ border: 1px solid transparent;
+ border-radius: $ds_radius_control;
background-color: transparent;
color: #606163;
font-size: 22px;
@@ -95,6 +95,10 @@ QDialog#AppointmentDrawerOverlay QToolButton#AppointmentDrawerClose {
QDialog#AppointmentDrawerOverlay QToolButton#AppointmentDrawerClose:hover {
color: #1A1C1F;
background-color: #F0F0F0;
+}
+QDialog#AppointmentDrawerOverlay QToolButton#AppointmentDrawerClose:focus {
+ border-color: $ds_focus;
+ background-color: $ds_accent_soft;
}
QDialog#AppointmentDrawerOverlay QScrollArea#AppointmentDrawerBody,
@@ -110,7 +114,7 @@ QDialog#AppointmentDrawerOverlay QWidget#AppointmentDrawerBodyContent {
}
QDialog#AppointmentDrawerOverlay QLabel[appointmentLabel="true"] {
- color: #1A1C1F;
+ color: $ds_muted;
font-size: 14px;
font-weight: 500;
}
@@ -125,7 +129,7 @@ QDialog#AppointmentDrawerOverlay QPlainTextEdit {
min-height: 30px;
padding: 0 11px;
border: 1px solid #EDEDEE;
- border-radius: 9px;
+ border-radius: 10px;
background-color: #FFFFFF;
color: #1A1C1F;
selection-background-color: #EEF1FA;
@@ -145,7 +149,14 @@ QDialog#AppointmentDrawerOverlay QPlainTextEdit:hover {
QDialog#AppointmentDrawerOverlay QComboBox:focus,
QDialog#AppointmentDrawerOverlay QLineEdit:focus,
QDialog#AppointmentDrawerOverlay QPlainTextEdit:focus {
- border: 2px solid #8B9AD9;
+ border: 1px solid #8B9AD9;
+}
+QDialog#AppointmentDrawerOverlay QComboBox:disabled,
+QDialog#AppointmentDrawerOverlay QLineEdit:disabled,
+QDialog#AppointmentDrawerOverlay QPlainTextEdit:disabled {
+ color: $ds_disabled;
+ background-color: $ds_disabled_surface;
+ border-color: $ds_line;
}
QDialog#AppointmentDrawerOverlay QComboBox::drop-down {
@@ -197,7 +208,7 @@ QDialog#AppointmentDrawerOverlay QPushButton[appointmentDate="true"] {
max-height: 38px;
padding: 0;
border: 1px solid #EDEDEE;
- border-radius: 8px;
+ border-radius: 10px;
background-color: #FFFFFF;
color: #1A1C1F;
font-size: 14px;
@@ -221,15 +232,15 @@ QDialog#AppointmentDrawerOverlay QPushButton[appointmentDate="true"]:checked {
}
QDialog#AppointmentDrawerOverlay QFrame#AppointmentSlotsPanel {
- background-color: #F7F7F7;
+ background-color: $ds_surface_alt;
border: 0;
- border-radius: 8px;
+ border-radius: $ds_radius_panel;
}
QDialog#AppointmentDrawerOverlay QLabel#AppointmentSlotsTitle {
color: #1A1C1F;
font-size: 15px;
- font-weight: 500;
+ font-weight: 600;
}
QDialog#AppointmentDrawerOverlay QPushButton#AppointmentRefreshSlots {
@@ -247,13 +258,17 @@ QDialog#AppointmentDrawerOverlay QPushButton#AppointmentRefreshSlots {
QDialog#AppointmentDrawerOverlay QPushButton#AppointmentRefreshSlots:hover {
background-color: #EEF1FA;
}
+QDialog#AppointmentDrawerOverlay QPushButton#AppointmentRefreshSlots:focus {
+ background-color: $ds_accent_soft;
+ border: 1px solid $ds_focus;
+}
QDialog#AppointmentDrawerOverlay QPushButton[appointmentSlot="true"] {
min-width: 110px;
min-height: 70px;
padding: 0 8px;
border: 2px solid #EDEDEE;
- border-radius: 8px;
+ border-radius: 10px;
background-color: #FFFFFF;
color: #1A1C1F;
}
@@ -330,25 +345,25 @@ QDialog#AppointmentDrawerOverlay QLabel#AppointmentEmptyText {
QDialog#AppointmentDrawerOverlay QFrame#AppointmentAlert[kind="info"] {
background-color: #EEF1FA;
border: 1px solid #EDEDEE;
- border-radius: 9px;
+ border-radius: 10px;
}
QDialog#AppointmentDrawerOverlay QFrame#AppointmentAlert[kind="warning"] {
background-color: #FFF5E6;
border: 1px solid #F6E3C4;
- border-radius: 9px;
+ border-radius: 10px;
}
QDialog#AppointmentDrawerOverlay QFrame#AppointmentAlert[kind="danger"] {
background-color: #FFF1F3;
border: 1px solid #F7D7DC;
- border-radius: 9px;
+ border-radius: 10px;
}
QDialog#AppointmentDrawerOverlay QFrame#AppointmentAlert[kind="success"] {
background-color: #EAF9F3;
border: 1px solid #D4F0E5;
- border-radius: 9px;
+ border-radius: 10px;
}
QDialog#AppointmentDrawerOverlay QFrame#AppointmentAlert[kind="info"] QLabel {
@@ -378,7 +393,7 @@ QDialog#AppointmentDrawerOverlay QFrame#AppointmentDrawerFooter QPushButton {
max-height: 30px;
padding: 0 15px;
border: 1px solid #EDEDEE;
- border-radius: 9px;
+ border-radius: 10px;
background-color: #FFFFFF;
color: #1A1C1F;
font-size: 13px;
@@ -408,9 +423,14 @@ QDialog#AppointmentDrawerOverlay QFrame#AppointmentDrawerFooter QPushButton[prim
}
QDialog#AppointmentDrawerOverlay QFrame#AppointmentDrawerFooter QPushButton:disabled {
- color: #FFFFFF;
- border-color: #EDEDEE;
- background-color: #8E8F90;
+ color: $ds_disabled;
+ border-color: $ds_line;
+ background-color: $ds_disabled_surface;
+}
+QDialog#AppointmentDrawerOverlay QFrame#AppointmentDrawerFooter QPushButton[primary="true"]:pressed {
+ color: $ds_surface;
+ background-color: $ds_accent_pressed;
+ border-color: $ds_accent_pressed;
}
QDialog#AppointmentDrawerOverlay QFrame#AppointmentLoadingOverlay {
@@ -487,6 +507,7 @@ _APPOINTMENT_DARK_REPLACEMENTS = (
)
# Light is the default application theme. Keep the replacement table available
# for a future explicit dark-mode switch, but do not mutate the light source QSS.
+APPOINTMENT_DRAWER_QSS = clinical_stylesheet(APPOINTMENT_DRAWER_QSS)
def _as_int(value: Any, default: int = 0) -> int:
@@ -733,35 +754,7 @@ class _EmptyIllustration(QWidget):
painter.end()
-class _HoverLiftButton(QPushButton):
- """Button with a subtle two-pixel lift and blue-tinted shadow on hover."""
-
- def __init__(self, text: str = "", parent: QWidget | None = None) -> None:
- super().__init__(text, parent)
- self._lifted = False
- self._base_position = QPoint()
-
- def enterEvent(self, event: QEvent) -> None: # noqa: N802 - Qt API
- if self.isEnabled() and not self._lifted:
- self._base_position = self.pos()
- self.move(self.x(), self.y() - 2)
- shadow = QGraphicsDropShadowEffect(self)
- shadow.setBlurRadius(12)
- shadow.setOffset(0, 4)
- shadow.setColor(QColor(26, 28, 31, 72))
- self.setGraphicsEffect(shadow)
- self._lifted = True
- super().enterEvent(event)
-
- def leaveEvent(self, event: QEvent) -> None: # noqa: N802 - Qt API
- if self._lifted:
- self.move(self._base_position)
- self.setGraphicsEffect(None)
- self._lifted = False
- super().leaveEvent(event)
-
-
-class _SlotCard(_HoverLiftButton):
+class _SlotCard(QPushButton):
"""Two-line time card matching Element's independent time/status typography."""
def __init__(self, time_text: str, status_text: str) -> None:
@@ -819,8 +812,8 @@ class AppointmentDrawer(QDialog):
self._today_blocking = False
self._channel_names: dict[str, str] = {}
self._doctor_buttons: dict[int, QRadioButton] = {}
- self._date_buttons: dict[str, _HoverLiftButton] = {}
- self._slot_buttons: dict[str, _HoverLiftButton] = {}
+ self._date_buttons: dict[str, QPushButton] = {}
+ self._slot_buttons: dict[str, QPushButton] = {}
self._slot_available: dict[str, bool] = {}
self._slot_restore_selection = ""
self._active_loading = ""
@@ -1426,7 +1419,7 @@ class AppointmentDrawer(QDialog):
continue
label = f"{parsed.toString('MM月dd日')} ({week_days[parsed.dayOfWeek() % 7]})"
self.date_combo.addItem(label, value)
- button = _HoverLiftButton(label)
+ button = QPushButton(label)
button.setProperty("appointmentDate", True)
button.setCheckable(True)
button.setFixedSize(130, 40)
diff --git a/app/src/doctor_workstation/ui/appointments_style.py b/app/src/doctor_workstation/ui/appointments_style.py
index 194fd7bdc..134f8e343 100644
--- a/app/src/doctor_workstation/ui/appointments_style.py
+++ b/app/src/doctor_workstation/ui/appointments_style.py
@@ -2,143 +2,155 @@
from string import Template
+from .design_system import clinical_stylesheet
from .reception_style import body_family, heading_family
def appointments_stylesheet() -> str:
- return Template(_QSS).substitute(body=body_family(), heading=heading_family())
+ return clinical_stylesheet(Template(_QSS).safe_substitute(body=body_family(), heading=heading_family()))
_QSS = """
-#AppointmentsPage { background: #F3F7FD; color: #273244; }
+#AppointmentsPage { background: $ds_canvas; color: $ds_text; }
#AppointmentsPage QLabel, #AppointmentsPage QPushButton,
#AppointmentsPage QLineEdit, #AppointmentsPage QComboBox,
#AppointmentsPage QTabBar, #AppointmentsPage QTableWidget {
- font-family: "$body"; font-size: 14px; font-weight: 400; color: #273244;
+ font-family: "$body"; font-size: 14px; font-weight: 400; color: $ds_text;
}
#AppointmentsPage QWidget#PageHeader QLabel[role="pageTitle"] {
- font-family: "$heading"; font-size: 20px; font-weight: 600; color: #202C3F;
+ font-family: "$heading"; font-size: 20px; font-weight: 600; color: $ds_heading;
}
#AppointmentsPage QWidget#PageHeader QLabel[role="muted"],
#AppointmentsPage QWidget#PageHeader QLabel[role="breadcrumb"],
#AppointmentsPage QWidget#PageHeader QLabel[role="breadcrumbSeparator"],
#AppointmentsPage QWidget#PageHeader QLabel[role="breadcrumbCurrent"] {
- color: #5D6B80; font-size: 13px; font-weight: 400;
+ color: $ds_muted; font-size: 13px; font-weight: 400;
}
#AppointmentsPage QFrame#AppointmentFilterPanel,
#AppointmentsPage QFrame#AppointmentMainCard {
- background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 8px;
+ background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_panel;
}
#AppointmentsPage QPushButton {
- min-height: 30px; padding: 0 12px; border: 1px solid #DBE5F2;
- border-radius: 6px; background: #FFFFFF;
+ min-height: 30px; padding: 0 12px; border: 1px solid transparent;
+ border-radius: $ds_radius_control; background: $ds_surface_alt;
}
-#AppointmentsPage QPushButton:hover { color: #1555B6; background: #F2F7FF; border-color: #B6CDEE; }
-#AppointmentsPage QPushButton:pressed { background: #DCEAFF; }
-#AppointmentsPage QPushButton:focus { border-color: #75A5F0; }
+#AppointmentsPage QPushButton:hover { color: $ds_accent; background: $ds_surface_alt; border-color: $ds_line_strong; }
+#AppointmentsPage QPushButton:pressed { background: $ds_accent_soft; }
+#AppointmentsPage QPushButton:focus { border-color: $ds_focus; }
#AppointmentsPage QPushButton[variant="primary"] {
- background: #1769E8; color: #FFFFFF; border-color: #1769E8;
+ background: $ds_accent; color: $ds_surface; border-color: $ds_accent;
}
-#AppointmentsPage QPushButton[variant="primary"]:hover { background: #155BCC; }
-#AppointmentsPage QPushButton[variant="primary"]:pressed { background: #124EA9; }
+#AppointmentsPage QPushButton[variant="primary"]:hover { background: $ds_accent_hover; }
+#AppointmentsPage QPushButton[variant="primary"]:pressed { background: $ds_accent_pressed; }
+#AppointmentsPage QPushButton[variant="primary"]:focus { border-color: $ds_focus; }
#AppointmentsPage QPushButton[variant="danger"] {
- color: #B84652; background: #FFFFFF; border-color: #EFC8CE;
+ color: $ds_danger; background: $ds_danger_soft; border-color: transparent;
}
-#AppointmentsPage QPushButton[variant="danger"]:hover { background: #FFF0F2; }
+#AppointmentsPage QPushButton[variant="danger"]:hover { background: $ds_danger_soft; }
+#AppointmentsPage QPushButton[variant="danger"]:pressed { border-color: $ds_danger; }
#AppointmentsPage QPushButton[variant="ghost"] { background: transparent; border-color: transparent; }
-#AppointmentsPage QPushButton:disabled {
- color: #8A97A9; background: #F6F8FC; border-color: #E2E9F2;
+#AppointmentsPage QPushButton[variant="ghost"]:hover { background: $ds_accent_soft; }
+#AppointmentsPage QPushButton[variant="ghost"]:focus { border-color: $ds_focus; }
+#AppointmentsPage QPushButton:disabled, #AppointmentsPage QPushButton[variant="primary"]:disabled,
+#AppointmentsPage QPushButton[variant="danger"]:disabled {
+ color: $ds_disabled; background: $ds_disabled_surface; border-color: $ds_line;
}
#AppointmentsPage QLineEdit, #AppointmentsPage QComboBox {
- min-height: 32px; padding: 0 10px; color: #273244; background: #FFFFFF;
- border: 1px solid #DBE5F2; border-radius: 6px; selection-background-color: #DCEAFF;
+ min-height: 32px; padding: 0 10px; color: $ds_text; background: $ds_surface;
+ border: 1px solid $ds_line; border-radius: $ds_radius_control; selection-background-color: $ds_accent_soft;
}
-#AppointmentsPage QLineEdit:focus, #AppointmentsPage QComboBox:focus { border-color: #75A5F0; }
+#AppointmentsPage QLineEdit:focus, #AppointmentsPage QComboBox:focus { border-color: $ds_focus; }
#AppointmentsPage QLineEdit QToolButton {
min-width: 0; min-height: 0; padding: 0; border: 0; background: transparent;
}
-#AppointmentsPage QLineEdit QToolButton:focus { background: #EAF2FF; }
+#AppointmentsPage QLineEdit QToolButton:focus { background: $ds_accent_soft; }
#AppointmentsPage QPushButton#AppointmentSearchButton {
min-height: 39px; max-height: 39px; min-width: 52px;
}
#AppointmentsPage QLineEdit#AppointmentPatientSearch { min-height: 39px; max-height: 39px; }
#AppointmentsPage QPushButton[appointmentStat="true"] {
- min-height: 34px; max-height: 34px; padding: 0 10px; background: #F4F7FC;
- border-color: transparent; color: #5D6B80; font-size: 13px;
+ min-height: 34px; max-height: 34px; padding: 0 10px; background: $ds_canvas;
+ border-color: transparent; color: $ds_muted; font-size: 13px;
}
-#AppointmentsPage QPushButton[appointmentStat="true"]:hover { color: #1555B6; background: #EAF2FF; }
+#AppointmentsPage QPushButton[appointmentStat="true"]:hover { color: $ds_accent; background: $ds_accent_soft; }
#AppointmentsPage QPushButton[appointmentStat="true"]:checked {
- color: #FFFFFF; background: #1769E8; border-color: #1769E8;
+ color: $ds_accent; background: $ds_accent_soft; border-color: transparent; font-weight: 600;
}
#AppointmentsPage QPushButton[appointmentStatKind="warning"][hasPending="true"]:!checked {
- color: #9C681F; background: #FFF6E7; border-color: #EEDCBF;
+ color: $ds_warning; background: $ds_warning_soft; border-color: $ds_warning_soft;
}
-#AppointmentsPage QLabel#FilterRowLabel { color: #5D6B80; font-size: 13px; }
-#AppointmentsPage QLabel#FilterDivider { color: #DBE5F2; padding: 0 10px; }
+#AppointmentsPage QLabel#FilterRowLabel { color: $ds_muted; font-size: 13px; }
+#AppointmentsPage QLabel#FilterDivider { color: $ds_line; padding: 0 10px; }
#AppointmentsPage QTabBar#AppointmentStatusTabs::tab {
- min-width: 52px; min-height: 32px; padding: 0 12px; color: #5D6B80;
+ min-width: 52px; min-height: 32px; padding: 0 12px; color: $ds_muted;
background: transparent; border: 0; border-bottom: 2px solid transparent; font-size: 13px;
}
-#AppointmentsPage QTabBar#AppointmentStatusTabs::tab:hover { color: #1555B6; background: #F7FAFE; }
+#AppointmentsPage QTabBar#AppointmentStatusTabs::tab:hover { color: $ds_accent; background: $ds_surface_alt; }
#AppointmentsPage QTabBar#AppointmentStatusTabs::tab:selected {
- color: #1769E8; background: transparent; border-bottom-color: #1769E8;
+ color: $ds_accent; background: transparent; border-bottom-color: $ds_accent;
}
#AppointmentsPage QPushButton[filterChoice="true"] {
- min-height: 30px; max-height: 30px; padding: 0 12px; color: #5D6B80;
+ min-height: 30px; max-height: 30px; padding: 0 12px; color: $ds_muted;
background: transparent; border-color: transparent; font-size: 13px;
}
-#AppointmentsPage QPushButton[filterChoice="true"]:checked { color: #1555B6; background: #EAF2FF; }
+#AppointmentsPage QPushButton[filterChoice="true"]:checked { color: $ds_accent; background: $ds_accent_soft; }
+#AppointmentsPage QPushButton[filterChoice="true"]:focus,
+#AppointmentsPage QPushButton[appointmentStat="true"]:focus { border-color: $ds_focus; }
#AppointmentsPage QFrame#AppointmentToolbar { background: transparent; border: 0; }
#AppointmentsPage QPushButton[compactAction="true"] {
min-height: 36px; max-height: 36px; padding: 0 17px; font-size: 13px;
}
#AppointmentsPage QFrame#AppointmentToolbar QPushButton[variant="secondary"]:enabled {
- color: #1769E8; border-color: #ADC8F0;
+ color: $ds_text; border-color: transparent;
}
+#AppointmentsPage QFrame#AppointmentToolbar QPushButton[variant="secondary"]:hover { color: $ds_accent; background: $ds_accent_soft; }
+#AppointmentsPage QFrame#AppointmentToolbar QPushButton[variant="secondary"]:focus { border-color: $ds_focus; }
#AppointmentsPage QTableWidget#AppointmentTable {
- background: #FFFFFF; alternate-background-color: #FFFFFF; border: 0; border-radius: 0;
- gridline-color: #E6EDF6; selection-background-color: #EAF2FF; selection-color: #273244;
+ background: $ds_surface; alternate-background-color: $ds_surface; border: 0; border-radius: 0;
+ gridline-color: $ds_line; selection-background-color: $ds_accent_soft; selection-color: $ds_text;
}
-#AppointmentsPage QTableWidget#AppointmentTable::item { padding: 0; border: 0; border-bottom: 1px solid #E6EDF6; }
-#AppointmentsPage QTableWidget#AppointmentTable::item:selected { background: #EAF2FF; color: #273244; }
+#AppointmentsPage QTableWidget#AppointmentTable::item { padding: 0; border: 0; border-bottom: 1px solid $ds_line; }
+#AppointmentsPage QTableWidget#AppointmentTable::item:selected { background: $ds_accent_soft; color: $ds_text; }
#AppointmentsPage QTableWidget#AppointmentTable QHeaderView::section {
- min-height: 40px; padding: 0; background: #F5F8FD; color: #5D6B80;
- border: 0; border-top: 1px solid #E1E9F4; border-bottom: 1px solid #E1E9F4;
+ min-height: 40px; padding: 0; background: $ds_surface_alt; color: $ds_muted;
+ border: 0; border-top: 1px solid $ds_line; border-bottom: 1px solid $ds_line;
font-family: "$body"; font-size: 13px; font-weight: 400;
}
#AppointmentsPage QWidget[appointmentSelectionHost="true"] {
background: transparent; border-left: 3px solid transparent;
}
-#AppointmentsPage QWidget[appointmentSelectionHost="true"][selected="true"] { border-left-color: #1769E8; }
+#AppointmentsPage QWidget[appointmentSelectionHost="true"][selected="true"] { border-left-color: $ds_accent; }
#AppointmentsPage QCheckBox[appointmentSelector="true"]::indicator {
- width: 16px; height: 16px; background: #FFFFFF; border: 1px solid #C8D5E6; border-radius: 3px;
+ width: 16px; height: 16px; background: $ds_surface; border: 1px solid $ds_line_strong; border-radius: 3px;
}
-#AppointmentsPage QCheckBox[appointmentSelector="true"]::indicator:checked { background: #1769E8; border-color: #1769E8; }
+#AppointmentsPage QCheckBox[appointmentSelector="true"]::indicator:checked { background: $ds_accent; border-color: $ds_accent; }
#AppointmentsPage QWidget[appointmentInfoHost="true"],
#AppointmentsPage QWidget[appointmentImHost="true"] { background: transparent; }
#AppointmentsPage QLabel[tableAppointmentStatus="true"] {
- min-height: 20px; max-height: 20px; padding: 0 6px; color: #1555B6;
- background: #EAF2FF; border-radius: 4px; font-size: 13px;
+ min-height: 20px; max-height: 20px; padding: 0 6px; color: $ds_accent;
+ background: $ds_accent_soft; border-radius: $ds_radius_small; font-size: 13px;
}
-#AppointmentsPage QLabel[tableAppointmentStatusKind="warning"] { color: #9C681F; background: #FFF3DD; }
-#AppointmentsPage QLabel[tableAppointmentStatusKind="muted"] { color: #66758A; background: #EEF2F7; }
-#AppointmentsPage QLabel[tableAppointmentMeta="true"] { color: #5D6B80; font-size: 13px; }
+#AppointmentsPage QLabel[tableAppointmentStatusKind="warning"] { color: $ds_warning; background: $ds_warning_soft; }
+#AppointmentsPage QLabel[tableAppointmentStatusKind="muted"] { color: $ds_muted; background: $ds_disabled_surface; }
+#AppointmentsPage QLabel[tableAppointmentMeta="true"] { color: $ds_muted; font-size: 13px; }
#AppointmentsPage QPushButton[tableCancelAction="true"] {
- min-height: 20px; max-height: 20px; padding: 0 5px; color: #B84652;
- background: #FFF0F2; border: 0; border-radius: 4px; font-size: 13px;
+ min-height: 20px; max-height: 20px; padding: 0 5px; color: $ds_danger;
+ background: $ds_danger_soft; border: 0; border-radius: $ds_radius_small; font-size: 13px;
}
#AppointmentsPage QPushButton[appointmentImAction="true"] {
min-width: 62px; min-height: 32px; max-height: 32px; padding: 0 10px;
- color: #1555B6; background: #EAF2FF; border-color: #C9DCF7; font-size: 13px;
+ color: $ds_accent; background: $ds_accent_soft; border-color: transparent; font-size: 13px;
}
-#AppointmentsPage QPushButton[appointmentImAction="true"]:hover { color: #FFFFFF; background: #1769E8; }
-#AppointmentsPage QPushButton[appointmentImAction="true"]:disabled { color: #8A97A9; background: #F3F6FB; border-color: #DFE7F2; }
-#AppointmentsPage QWidget#Pager { background: #FFFFFF; border: 0; border-top: 1px solid #E1E9F4; }
-#AppointmentsPage QWidget#Pager QLabel { color: #5D6B80; font-size: 13px; border: 0; }
+#AppointmentsPage QPushButton[appointmentImAction="true"]:hover { color: $ds_accent_hover; border-color: $ds_line_strong; }
+#AppointmentsPage QPushButton[appointmentImAction="true"]:focus { border-color: $ds_focus; }
+#AppointmentsPage QPushButton[appointmentImAction="true"]:disabled { color: $ds_disabled; background: $ds_disabled_surface; border-color: $ds_line; }
+#AppointmentsPage QWidget#Pager { background: $ds_surface; border: 0; border-top: 1px solid $ds_line; }
+#AppointmentsPage QWidget#Pager QLabel { color: $ds_muted; font-size: 13px; border: 0; }
#AppointmentsPage QWidget#Pager QPushButton {
min-width: 30px; max-width: 30px; min-height: 32px; max-height: 32px;
- padding: 0; border: 1px solid #DBE5F2; background: #FFFFFF; color: #5D6B80; font-size: 13px;
+ padding: 0; border: 1px solid $ds_line; background: $ds_surface; color: $ds_muted; font-size: 13px;
}
-#AppointmentsPage QWidget#Pager QPushButton[active="true"] { color: #FFFFFF; background: #1769E8; border-color: #1769E8; }
-#AppointmentsPage QWidget#Pager QPushButton:disabled { color: #9AA6B7; background: #F7F9FC; }
+#AppointmentsPage QWidget#Pager QPushButton[active="true"] { color: $ds_accent; background: $ds_accent_soft; border-color: transparent; font-weight: 600; }
+#AppointmentsPage QWidget#Pager QPushButton:focus { border-color: $ds_focus; }
+#AppointmentsPage QWidget#Pager QPushButton:disabled { color: $ds_disabled; background: $ds_surface_alt; }
"""
diff --git a/app/src/doctor_workstation/ui/chat_notifications.py b/app/src/doctor_workstation/ui/chat_notifications.py
index c5f2526fa..a29f21717 100644
--- a/app/src/doctor_workstation/ui/chat_notifications.py
+++ b/app/src/doctor_workstation/ui/chat_notifications.py
@@ -24,6 +24,7 @@ from PySide6.QtWidgets import (
QWidget,
)
+from .design_system import clinical_stylesheet
from .widgets import display_text, first_value, run_async
# 后台 ChatNotifyLogic 写入的三种 type。
@@ -260,7 +261,7 @@ class ChatNotificationCenter(QWidget):
super().__init__(host)
self.repository = repository
self.setObjectName("ChatNotifyLayer")
- self.setStyleSheet(CHAT_NOTIFICATION_QSS)
+ self.setStyleSheet(clinical_stylesheet(CHAT_NOTIFICATION_QSS))
self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, False)
self._cards: dict[str, _NotificationCard] = {}
self._pending: list[ChatNotification] = []
diff --git a/app/src/doctor_workstation/ui/consultations_style.py b/app/src/doctor_workstation/ui/consultations_style.py
index 92359094d..286713d09 100644
--- a/app/src/doctor_workstation/ui/consultations_style.py
+++ b/app/src/doctor_workstation/ui/consultations_style.py
@@ -2,59 +2,67 @@
from string import Template
+from .design_system import clinical_stylesheet
from .reception_style import body_family, heading_family
def consultations_stylesheet() -> str:
- return Template(_QSS).substitute(body=body_family(), heading=heading_family())
+ return clinical_stylesheet(Template(_QSS).safe_substitute(body=body_family(), heading=heading_family()))
_QSS = """
#DiagnosisIndex, #DiagnosisIndexContent, #DiagnosisPageScroll {
- background: #F3F7FD; color: #273244; border: 0;
+ background: $ds_canvas; color: $ds_text; border: 0;
}
#DiagnosisIndex QLabel, #DiagnosisIndex QPushButton, #DiagnosisIndex QToolButton,
#DiagnosisIndex QLineEdit, #DiagnosisIndex QComboBox, #DiagnosisIndex QDateEdit,
#DiagnosisIndex QSpinBox, #DiagnosisIndex QTableView {
- font-family: "$body"; font-size: 14px; font-weight: 400; color: #273244;
+ font-family: "$body"; font-size: 14px; font-weight: 400; color: $ds_text;
}
#DiagnosisIndex QWidget#PageHeader QLabel[role="pageTitle"] {
- font-family: "$heading"; font-size: 20px; font-weight: 600; color: #202C3F;
+ font-family: "$heading"; font-size: 20px; font-weight: 600; color: $ds_heading;
}
#DiagnosisIndex QLabel[role="muted"], #DiagnosisIndex QLabel[role="breadcrumb"],
#DiagnosisIndex QLabel[role="breadcrumbCurrent"], #DiagnosisIndex QLabel[role="breadcrumbSeparator"],
#DiagnosisIndex QLabel[filterGroup="true"], #DiagnosisIndex QLabel[pagerMuted="true"] {
- color: #5D6B80; font-size: 13px;
+ color: $ds_muted; font-size: 13px;
}
#DiagnosisIndex QFrame#DiagnosisFilterCard, #DiagnosisIndex QFrame#DiagnosisListCard {
- background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 8px;
+ background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_panel;
}
#DiagnosisIndex QFrame#DiagnosisStatusCard, #DiagnosisIndex QFrame#DiagnosisQuickFilters,
#DiagnosisIndex QFrame#DiagnosisListToolbar { background: transparent; border: 0; }
#DiagnosisIndex QFrame#DiagnosisAdvancedFilters {
- background: transparent; border: 0; border-top: 1px solid #E6EDF6; border-radius: 0;
+ background: transparent; border: 0; border-top: 1px solid $ds_line; border-radius: 0;
}
#DiagnosisIndex QPushButton {
- min-height: 34px; padding: 0 13px; border: 1px solid #DBE5F2;
- border-radius: 6px; background: #FFFFFF;
+ min-height: 34px; padding: 0 13px; border: 1px solid transparent;
+ border-radius: $ds_radius_control; background: $ds_surface_alt;
}
-#DiagnosisIndex QPushButton:hover { color: #1555B6; background: #F2F7FF; border-color: #B6CDEE; }
-#DiagnosisIndex QPushButton:pressed { background: #DCEAFF; }
-#DiagnosisIndex QPushButton:focus { border-color: #75A5F0; }
-#DiagnosisIndex QPushButton[variant="primary"] { color: #FFFFFF; background: #1769E8; border-color: #1769E8; }
-#DiagnosisIndex QPushButton[variant="primary"]:hover { background: #155BCC; }
-#DiagnosisIndex QPushButton[consultationTool="true"] { color: #1555B6; border-color: #C2D5EF; }
-#DiagnosisIndex QPushButton[consultationDanger="true"] { color: #BE4B58; border-color: #EBCDD2; }
-#DiagnosisIndex QPushButton:disabled, #DiagnosisIndex QPushButton[consultationDanger="true"]:disabled {
- color: #8A97A9; background: #F6F8FC; border-color: #E2E9F2;
+#DiagnosisIndex QPushButton:hover { color: $ds_accent; background: $ds_surface_alt; border-color: $ds_line_strong; }
+#DiagnosisIndex QPushButton:pressed { background: $ds_accent_soft; }
+#DiagnosisIndex QPushButton:focus { border-color: $ds_focus; }
+#DiagnosisIndex QPushButton[variant="primary"] { color: $ds_surface; background: $ds_accent; border-color: $ds_accent; }
+#DiagnosisIndex QPushButton[variant="primary"]:hover { background: $ds_accent_hover; }
+#DiagnosisIndex QPushButton[variant="primary"]:pressed { background: $ds_accent_pressed; }
+#DiagnosisIndex QPushButton[variant="primary"]:focus { border-color: $ds_focus; }
+#DiagnosisIndex QPushButton[consultationTool="true"] { color: $ds_text; border-color: transparent; }
+#DiagnosisIndex QPushButton[consultationTool="true"]:hover { color: $ds_accent; background: $ds_accent_soft; }
+#DiagnosisIndex QPushButton[consultationDanger="true"] { color: $ds_danger; background: $ds_danger_soft; border-color: transparent; }
+#DiagnosisIndex QPushButton[consultationDanger="true"]:hover { border-color: $ds_danger; }
+#DiagnosisIndex QPushButton[consultationTool="true"]:focus,
+#DiagnosisIndex QPushButton[consultationDanger="true"]:focus { border-color: $ds_focus; }
+#DiagnosisIndex QPushButton:disabled, #DiagnosisIndex QPushButton[consultationDanger="true"]:disabled,
+#DiagnosisIndex QPushButton[variant="primary"]:disabled, #DiagnosisIndex QPushButton[consultationTool="true"]:disabled {
+ color: $ds_disabled; background: $ds_disabled_surface; border-color: $ds_line;
}
#DiagnosisIndex QLineEdit, #DiagnosisIndex QComboBox, #DiagnosisIndex QDateEdit, #DiagnosisIndex QSpinBox {
- min-height: 32px; padding: 0 10px; color: #273244; background: #FFFFFF;
- border: 1px solid #DBE5F2; border-radius: 6px; selection-background-color: #DCEAFF;
+ min-height: 32px; padding: 0 10px; color: $ds_text; background: $ds_surface;
+ border: 1px solid $ds_line; border-radius: $ds_radius_control; selection-background-color: $ds_accent_soft;
font-size: 13px;
}
#DiagnosisIndex QLineEdit:focus, #DiagnosisIndex QComboBox:focus,
-#DiagnosisIndex QDateEdit:focus, #DiagnosisIndex QSpinBox:focus { border-color: #75A5F0; }
+#DiagnosisIndex QDateEdit:focus, #DiagnosisIndex QSpinBox:focus { border-color: $ds_focus; }
#DiagnosisIndex QLineEdit QToolButton {
min-width: 0; min-height: 0; padding: 0; border: 0; background: transparent;
}
@@ -62,70 +70,77 @@ _QSS = """
width: 22px; border: 0; background: transparent;
}
#DiagnosisIndex QComboBox QAbstractItemView {
- color: #273244; background: #FFFFFF; border: 1px solid #DBE5F2;
- selection-background-color: #EAF2FF; selection-color: #1555B6; outline: 0;
+ color: $ds_text; background: $ds_surface; border: 1px solid $ds_line;
+ selection-background-color: $ds_accent_soft; selection-color: $ds_accent; outline: 0;
}
#DiagnosisIndex QWidget#DiagnosisStatusSearch QLineEdit,
#DiagnosisIndex QWidget#DiagnosisStatusSearch QPushButton { min-height: 39px; max-height: 39px; }
#DiagnosisIndex QToolButton { min-width: 0; min-height: 0; border: 0; padding: 0; background: transparent; }
#DiagnosisIndex QToolButton[diagnosisChip="true"] {
min-height: 32px; max-height: 32px; padding: 0 14px; border: 1px solid transparent;
- border-radius: 5px; color: #5D6B80; background: transparent; font-size: 13px;
+ border-radius: $ds_radius_control; color: $ds_muted; background: transparent; font-size: 13px;
}
-#DiagnosisIndex QToolButton[diagnosisChip="true"]:hover { background: #F2F7FF; color: #1555B6; }
-#DiagnosisIndex QToolButton[diagnosisChip="true"]:checked { background: #1769E8; color: #FFFFFF; }
-#DiagnosisIndex QToolButton[dateChoice="true"] { padding: 0 17px; border-color: #E1E9F4; }
-#DiagnosisIndex QToolButton[dateChoice="true"]:checked { border-color: #1769E8; }
+#DiagnosisIndex QToolButton[diagnosisChip="true"]:hover { background: $ds_surface_alt; color: $ds_accent; }
+#DiagnosisIndex QToolButton[diagnosisChip="true"]:checked { background: $ds_accent_soft; color: $ds_accent; font-weight: 600; }
+#DiagnosisIndex QToolButton[dateChoice="true"] { padding: 0 17px; background: $ds_surface_alt; border-color: transparent; }
+#DiagnosisIndex QToolButton[dateChoice="true"]:checked { background: $ds_accent_soft; border-color: transparent; }
+#DiagnosisIndex QToolButton[diagnosisChip="true"]:focus { border-color: $ds_focus; }
#DiagnosisIndex QToolButton[statusTab="true"] {
min-height: 44px; max-height: 44px; padding: 0 20px; border: 0;
border-bottom: 2px solid transparent; border-radius: 0; background: transparent;
}
#DiagnosisIndex QToolButton[statusTab="true"]:checked {
- color: #1769E8; background: transparent; border-bottom-color: #1769E8;
+ color: $ds_accent; background: transparent; border-bottom-color: $ds_accent;
}
+#DiagnosisIndex QToolButton[statusTab="true"]:focus { background: $ds_accent_soft; }
#DiagnosisIndex QToolButton#DiagnosisMoreFilter {
- min-height: 32px; padding: 0 6px; color: #5D6B80; font-size: 13px;
+ min-height: 32px; padding: 0 6px; color: $ds_muted; font-size: 13px;
}
-#DiagnosisIndex QToolButton#DiagnosisMoreFilter:hover { color: #1769E8; background: #F2F7FF; }
-#DiagnosisIndex QFrame#DiagnosisFilterDivider { min-width: 1px; max-width: 1px; min-height: 20px; background: #E1E9F4; border: 0; }
+#DiagnosisIndex QToolButton#DiagnosisMoreFilter:hover { color: $ds_accent; background: $ds_surface_alt; }
+#DiagnosisIndex QFrame#DiagnosisFilterDivider { min-width: 1px; max-width: 1px; min-height: 20px; background: $ds_line; border: 0; }
#DiagnosisIndex QFrame#DiagnosisDateRange {
- background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 6px;
+ background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_control;
}
#DiagnosisIndex QDateEdit[diagnosisRangePart="true"] { min-height: 30px; padding: 0 4px; border: 0; }
#DiagnosisIndex QTableView {
- background: #FFFFFF; alternate-background-color: #FFFFFF; border: 0; border-radius: 0;
- gridline-color: #E6EDF6; selection-background-color: #EAF2FF; selection-color: #273244;
+ background: $ds_surface; alternate-background-color: $ds_surface; border: 0; border-radius: 0;
+ gridline-color: $ds_line; selection-background-color: $ds_accent_soft; selection-color: $ds_text;
}
#DiagnosisIndex QTableView QHeaderView::section {
- min-height: 41px; padding: 0; background: #F5F8FD; color: #5D6B80;
- border: 0; border-bottom: 1px solid #E1E9F4;
+ min-height: 41px; padding: 0; background: $ds_surface_alt; color: $ds_muted;
+ border: 0; border-bottom: 1px solid $ds_line;
font-family: "$body"; font-size: 13px; font-weight: 400;
}
#DiagnosisIndex QToolButton[rowLink], #DiagnosisIndex QToolButton[appointmentCancel="true"] {
- color: #1769E8; min-height: 26px; padding: 0 4px; border: 0; background: transparent; font-size: 13px;
+ color: $ds_accent; min-height: 26px; padding: 0 4px; border: 1px solid transparent;
+ border-radius: $ds_radius_small; background: transparent; font-size: 13px;
}
-#DiagnosisIndex QToolButton[appointmentCancel="true"] { color: #BE4B58; }
-#DiagnosisIndex QToolButton[rowLink]:hover { color: #1555B6; background: #DCEAFF; border-radius: 4px; }
+#DiagnosisIndex QToolButton[appointmentCancel="true"] { color: $ds_danger; }
+#DiagnosisIndex QToolButton[appointmentCancel="true"]:hover { background: $ds_danger_soft; }
+#DiagnosisIndex QToolButton[rowLink]:hover { color: $ds_accent; background: $ds_accent_soft; border-radius: $ds_radius_small; }
+#DiagnosisIndex QToolButton[rowLink]:focus,
+#DiagnosisIndex QToolButton[appointmentCancel="true"]:focus { border-color: $ds_focus; }
#DiagnosisIndex QToolButton[rowLink="muted"], #DiagnosisIndex QLabel[fixedMuted="true"] {
- color: #5D6B80; font-size: 13px;
+ color: $ds_muted; font-size: 13px;
}
#DiagnosisIndex QToolButton#DiagnosisRowMore { padding-right: 18px; }
#DiagnosisIndex QWidget#DiagnosisFixedCell { background: transparent; }
-#DiagnosisIndex QLabel#DiagnosisTableEmpty { color: #5D6B80; background: #FFFFFF; }
-#DiagnosisIndex QLabel#DiagnosisTableEmpty[stateKind="error"] { color: #BE4B58; }
-#DiagnosisIndex QTableView#DiagnosisFixedTable { border-left: 1px solid #E1E9F4; }
-#DiagnosisIndex QWidget#DiagnosisPager { background: #FFFFFF; border-top: 1px solid #E6EDF6; }
+#DiagnosisIndex QLabel#DiagnosisTableEmpty { color: $ds_muted; background: $ds_surface; }
+#DiagnosisIndex QLabel#DiagnosisTableEmpty[stateKind="error"] { color: $ds_danger; }
+#DiagnosisIndex QTableView#DiagnosisFixedTable { border-left: 1px solid $ds_line; }
+#DiagnosisIndex QWidget#DiagnosisPager { background: $ds_surface; border-top: 1px solid $ds_line; }
#DiagnosisIndex QToolButton[pagerButton="true"] {
min-width: 30px; max-width: 30px; min-height: 30px; max-height: 30px;
- border: 1px solid #DBE5F2; border-radius: 5px; color: #5D6B80; background: #FFFFFF;
+ border: 1px solid $ds_line; border-radius: $ds_radius_control; color: $ds_muted; background: $ds_surface;
}
-#DiagnosisIndex QToolButton[pagerButton="true"][active="true"] { color: #FFFFFF; background: #1769E8; border-color: #1769E8; }
-#DiagnosisIndex QToolButton[pagerButton="true"]:disabled { color: #A4B0C0; background: #F6F8FC; }
+#DiagnosisIndex QToolButton[pagerButton="true"][active="true"] { color: $ds_accent; background: $ds_accent_soft; border-color: transparent; font-weight: 600; }
+#DiagnosisIndex QToolButton[pagerButton="true"]:focus { border-color: $ds_focus; }
+#DiagnosisIndex QToolButton[pagerButton="true"]:disabled { color: $ds_disabled; background: $ds_disabled_surface; }
#DiagnosisIndex QComboBox#DiagnosisPageSize { min-width: 95px; min-height: 30px; }
#DiagnosisIndex QSpinBox#DiagnosisPageJumper { min-height: 30px; padding: 0 8px; }
-#DiagnosisIndex QScrollBar:vertical { background: #F4F7FC; width: 7px; margin: 0; }
-#DiagnosisIndex QScrollBar:horizontal { background: #F4F7FC; height: 7px; margin: 0; }
-#DiagnosisIndex QScrollBar::handle { background: #C8D5E6; border-radius: 3px; min-width: 24px; min-height: 24px; }
+#DiagnosisIndex QScrollBar:vertical { background: $ds_canvas; width: 7px; margin: 0; }
+#DiagnosisIndex QScrollBar:horizontal { background: $ds_canvas; height: 7px; margin: 0; }
+#DiagnosisIndex QScrollBar::handle { background: $ds_line_strong; border-radius: 3px; min-width: 24px; min-height: 24px; }
#DiagnosisIndex QScrollBar::add-line, #DiagnosisIndex QScrollBar::sub-line { width: 0; height: 0; }
#DiagnosisIndex QScrollBar::add-page, #DiagnosisIndex QScrollBar::sub-page { background: transparent; }
"""
diff --git a/app/src/doctor_workstation/ui/design_system.py b/app/src/doctor_workstation/ui/design_system.py
new file mode 100644
index 000000000..0319c8a9e
--- /dev/null
+++ b/app/src/doctor_workstation/ui/design_system.py
@@ -0,0 +1,76 @@
+"""Clinical desktop design tokens, shared by native pages and dialog chrome.
+
+Keep data-series colours and video pixels outside this palette. Existing scoped
+QSS can adopt the system without changing selectors, layout or permissions.
+New rules should use the named ``$ds_*`` tokens rather than legacy colours.
+"""
+
+from __future__ import annotations
+
+import re
+from string import Template
+
+PALETTE = {
+ "canvas": "#F5F7FA",
+ "surface": "#FFFFFF",
+ "surface_alt": "#F7F9FC",
+ "sidebar": "#F0F3F8",
+ "line": "#E6EAF0",
+ "line_strong": "#D4DCE8",
+ "heading": "#223047",
+ "text": "#344258",
+ "muted": "#647287",
+ "disabled": "#8B96A6",
+ "disabled_surface": "#F0F2F5",
+ "accent": "#4267B2",
+ "accent_hover": "#355995",
+ "accent_pressed": "#2C4C82",
+ "accent_soft": "#EAF0FB",
+ "focus": "#6D8CCB",
+ "success": "#287B65",
+ "success_soft": "#EDF7F2",
+ "warning": "#96601D",
+ "warning_soft": "#FBF4E8",
+ "danger": "#B54A59",
+ "danger_soft": "#FCF0F2",
+}
+
+RADII = {"small": 6, "control": 10, "panel": 16, "window": 20}
+SPACING = {"small": 8, "control": 12, "group": 16, "section": 24}
+
+TOKENS = {f"ds_{name}": value for name, value in PALETTE.items()}
+TOKENS.update({f"ds_radius_{name}": f"{value}px" for name, value in RADII.items()})
+TOKENS.update({f"ds_space_{name}": f"{value}px" for name, value in SPACING.items()})
+
+# Explicit migration of the two existing native palettes. This adapter only
+# touches six-digit colour literals; selectors and metrics stay page-owned.
+_LEGACY_ROLES = {
+ "accent": ("1769E8", "4F63D9", "5761F4", "5267DF"),
+ "accent_hover": ("155BCC", "1555B6", "4156C4", "4356C4", "4055CA"),
+ "accent_pressed": ("124EA9", "354BB4"),
+ "accent_soft": ("EAF2FF", "EEF1FA", "EEF0FF", "F0F2FF", "DCEAFF", "EDF0FC"),
+ "focus": ("75A5F0", "8B9AD9"),
+ "canvas": ("F3F7FD", "F4F6FA", "F6F6F6"),
+ "surface_alt": ("F7F7F7", "F7FAFE", "F5F8FD", "F7F9FE", "F2F7FF"),
+ "sidebar": ("EDF4FF",),
+ "line": ("DBE5F2", "EDEDEE", "E5ECF6", "E6EDF6", "E7EDF7", "EDF0F5", "E7EBF2", "E6EAF5"),
+ "line_strong": ("E4E4E5", "C8D5E6", "C9DCF7", "ADC8F0", "B6CDEE"),
+ "heading": ("1A1C1F", "202C3F", "111F46"),
+ "text": ("273244", "263551", "24334A", "233149", "3F4E75"),
+ "muted": ("606163", "6A6B6D", "5D6B80", "7886AA", "708097"),
+ "disabled": ("8E8F90", "8A97A9", "9AA6B7"),
+ "disabled_surface": ("F2F2F2", "F0F0F0"),
+ "success_soft": ("EEF7F3", "EAF9F3"),
+ "warning": ("A9691D", "9C681F"),
+ "warning_soft": ("FCF5E9", "FFF5E6", "FFF6E7"),
+ "danger": ("BE4B58", "B84652"),
+ "danger_soft": ("FFF0F2", "FFF1F3"),
+}
+_LEGACY = {colour.lower(): PALETTE[role] for role, colours in _LEGACY_ROLES.items() for colour in colours}
+_HEX = re.compile(r"#([0-9a-fA-F]{6})(?![0-9a-fA-F])")
+
+
+def clinical_stylesheet(source: str) -> str:
+ """Resolve clinical tokens and migrate known legacy light-theme colours."""
+ resolved = Template(source).safe_substitute(TOKENS)
+ return _HEX.sub(lambda match: _LEGACY.get(match[1].lower(), match[0]), resolved)
diff --git a/app/src/doctor_workstation/ui/diagnosis_drawer.py b/app/src/doctor_workstation/ui/diagnosis_drawer.py
index 231731f30..38dae4767 100644
--- a/app/src/doctor_workstation/ui/diagnosis_drawer.py
+++ b/app/src/doctor_workstation/ui/diagnosis_drawer.py
@@ -64,6 +64,7 @@ from PySide6.QtWidgets import (
)
from .chat_items import ChatItem, parse_chat_item
+from .design_system import PALETTE, clinical_stylesheet
from .diagnosis_editors import FlowLayout
from .diagnosis_media import shared_image_manager
from .diagnosis_terms import FIELD_DICTIONARIES, format_timestamp, shared_terms
@@ -80,10 +81,7 @@ QFrame#DiagnosisDrawer {
border-left: 1px solid #EDEDEE;
}
QFrame#DiagnosisDrawerHeader {
- background-color: qlineargradient(
- x1:0, y1:0, x2:0, y2:1,
- stop:0 #FFFFFF, stop:1 #F7F7F7
- );
+ background-color: #FFFFFF;
border-bottom: 1px solid #EDEDEE;
}
QFrame#DiagnosisDrawerFooter {
@@ -105,7 +103,7 @@ QLabel#DiagnosisDrawerModeBadge,
QLabel#DiagnosisReadonlyStatus,
QLabel[diagnosisTag="true"] {
padding: 4px 9px;
- border-radius: 9px;
+ border-radius: $ds_radius_small;
font-size: 12px;
font-weight: 500;
}
@@ -159,8 +157,8 @@ QDialog QPushButton:pressed {
border-color: #354BB4;
}
QDialog QPushButton:disabled {
- color: #E4E4E5;
- background-color: #FFFFFF;
+ color: $ds_disabled;
+ background-color: $ds_disabled_surface;
border-color: #EDEDEE;
}
QDialog QPushButton[variant="primary"] {
@@ -176,9 +174,9 @@ QDialog QPushButton[variant="primary"]:focus {
border-color: #4156C4;
}
QDialog QPushButton[variant="primary"]:disabled {
- color: #FFFFFF;
- background-color: #F0F0F0;
- border-color: #F0F0F0;
+ color: $ds_disabled;
+ background-color: $ds_disabled_surface;
+ border-color: $ds_line;
}
QDialog QPushButton[variant="secondary"] {
color: #4F63D9;
@@ -267,9 +265,9 @@ QDialog#DiagnosisDialogRoot QPushButton#DiagnosisSaveButton:focus {
border-color: #4156C4;
}
QDialog#DiagnosisDialogRoot QPushButton#DiagnosisSaveButton:disabled {
- color: #FFFFFF;
- background-color: #F0F0F0;
- border-color: #F0F0F0;
+ color: $ds_disabled;
+ background-color: $ds_disabled_surface;
+ border-color: $ds_line;
}
QDialog#DiagnosisDialogRoot QPushButton#DiagnosisFooterCloseButton {
color: #606163;
@@ -383,10 +381,10 @@ QFrame#DiagnosisFormHost {
QFrame[diagnosisSection="true"] {
background-color: #FFFFFF;
border: 1px solid #EDEDEE;
- border-radius: 12px;
+ border-radius: 16px;
}
QLabel[diagnosisFieldLabel="true"] {
- color: #1A1C1F;
+ color: $ds_muted;
font-size: 12px;
font-weight: 500;
}
@@ -426,7 +424,7 @@ QDoubleSpinBox[diagnosisField="true"]:focus,
QSpinBox[diagnosisField="true"]:focus,
QTimeEdit[diagnosisField="true"]:focus {
border: 1px solid #8B9AD9;
- background-color: #F7F7F7;
+ background-color: $ds_surface;
}
QLineEdit[diagnosisField="true"][invalid="true"],
QComboBox[diagnosisField="true"][invalid="true"],
@@ -452,8 +450,8 @@ QLabel#DiagnosisSectionTitle {
background-color: transparent;
border: 0;
padding: 0;
- font-size: 13px;
- font-weight: 500;
+ font-size: 14px;
+ font-weight: 600;
letter-spacing: 0.02em;
}
QFrame#DiagnosisSectionAccent {
@@ -470,9 +468,9 @@ QFrame#DiagnosisReadonlyPage {
background-color: #F6F6F6;
}
QFrame#DiagnosisReadonlyHero {
- background-color: #F7F7F7;
- border: 1px solid #F0F0F0;
- border-radius: 12px;
+ background-color: $ds_surface;
+ border: 1px solid $ds_line;
+ border-radius: $ds_radius_panel;
}
QLabel#DiagnosisReadonlyTitle {
color: #1A1C1F;
@@ -542,7 +540,7 @@ QFrame#DiagnosisReadonlyCaseCard,
QFrame[diagnosisReadonlyCard="true"] {
background-color: #FFFFFF;
border: 1px solid #EDEDEE;
- border-radius: 14px;
+ border-radius: 16px;
}
QLabel#DiagnosisReadonlyCardTitle {
color: #1A1C1F;
@@ -771,7 +769,7 @@ QWidget[diagnosisChoiceHost="true"] QPushButton {
color: #1A1C1F;
background-color: #FFFFFF;
border: 1px solid #EDEDEE;
- border-radius: 999px;
+ border-radius: 10px;
font-size: 12px;
}
QWidget[diagnosisChoiceHost="true"] QPushButton:hover,
@@ -1068,6 +1066,7 @@ _DIAGNOSIS_BLUE_REPLACEMENTS = (
)
for _source_color, _theme_color in _DIAGNOSIS_BLUE_REPLACEMENTS:
DIAGNOSIS_QSS = DIAGNOSIS_QSS.replace(_source_color, _theme_color)
+DIAGNOSIS_QSS = clinical_stylesheet(DIAGNOSIS_QSS)
def _text(value: Any, default: str = "—") -> str:
@@ -1147,12 +1146,19 @@ class DiagnosisSwitch(QAbstractButton):
track = QRectF(1, 3, self.width() - 2, self.height() - 6)
checked = self.isChecked()
painter.setPen(Qt.PenStyle.NoPen)
- painter.setBrush(QColor("#4F63D9" if checked else "#E4E4E5"))
+ painter.setBrush(QColor(PALETTE["accent"] if checked else PALETTE["line_strong"]))
+ if not self.isEnabled():
+ painter.setOpacity(0.6)
painter.drawRoundedRect(track, track.height() / 2, track.height() / 2)
diameter = track.height() - 4
x = track.right() - diameter - 2 if checked else track.left() + 2
painter.setBrush(QColor("#FFFFFF"))
painter.drawEllipse(QRectF(x, track.top() + 2, diameter, diameter))
+ if self.hasFocus():
+ painter.setOpacity(1)
+ painter.setPen(QPen(QColor(PALETTE["focus"]), 1))
+ painter.setBrush(Qt.BrushStyle.NoBrush)
+ painter.drawRoundedRect(QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5), 11, 11)
painter.end()
@@ -1190,13 +1196,19 @@ class SaveStateButton(QPushButton):
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
enabled = self.isEnabled()
+ idle_color = PALETTE["accent_pressed"] if self.isDown() else PALETTE["accent"]
color = {
- "success": "#287B65",
- "error": "#BE4B58",
- }.get(self._state, "#4F63D9" if enabled else "#8E8F90")
+ "success": PALETTE["success"],
+ "error": PALETTE["danger"],
+ "loading": PALETTE["accent"],
+ }.get(self._state, idle_color if enabled else PALETTE["disabled_surface"])
painter.setPen(Qt.PenStyle.NoPen)
painter.setBrush(QColor(color))
painter.drawRoundedRect(QRectF(self.rect()).adjusted(1, 1, -1, -1), 10, 10)
+ if self.hasFocus():
+ painter.setPen(QPen(QColor(PALETTE["focus"]), 1))
+ painter.setBrush(Qt.BrushStyle.NoBrush)
+ painter.drawRoundedRect(QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5), 10, 10)
label = {
"loading": "正在保存",
"success": "保存成功",
@@ -1220,7 +1232,9 @@ class SaveStateButton(QPushButton):
else:
painter.drawLine(x + 3, center_y - 5, x + 12, center_y + 5)
painter.drawLine(x + 12, center_y - 5, x + 3, center_y + 5)
- painter.setPen(QColor("#FFFFFF"))
+ painter.setPen(QColor(
+ PALETTE["disabled"] if not enabled and self._state == "idle" else PALETTE["surface"]
+ ))
painter.drawText(
QRect(x + icon_width, 0, metrics.horizontalAdvance(label), self.height()),
Qt.AlignmentFlag.AlignCenter,
@@ -1815,10 +1829,10 @@ class MessageStrip(QFrame):
self.glyph = QLabel("i")
self.glyph.setFixedWidth(18)
self.glyph.setAlignment(Qt.AlignmentFlag.AlignCenter)
- self.glyph.setStyleSheet("font-weight:700; color:#4F63D9;")
+ self.glyph.setStyleSheet(clinical_stylesheet("font-weight:700; color:$ds_accent;"))
self.label = QLabel()
self.label.setWordWrap(True)
- self.label.setStyleSheet("color:#1A1C1F; font-size:13px;")
+ self.label.setStyleSheet(clinical_stylesheet("color:$ds_text; font-size:13px;"))
layout.addWidget(self.glyph)
layout.addWidget(self.label, 1)
self.action_button = QPushButton()
@@ -1894,7 +1908,7 @@ class LoadingOverlay(QFrame):
layout.setSpacing(8)
self.glyph = _LoadingSpinner(self)
label = QLabel(text)
- label.setStyleSheet("color:#606163; font-size:13px;")
+ label.setStyleSheet(clinical_stylesheet("color:$ds_muted; font-size:13px;"))
layout.addWidget(self.glyph)
layout.addWidget(label)
self.hide()
@@ -1985,15 +1999,15 @@ class RecordTable(QTableWidget):
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter
)
if column_index in danger_columns:
- item.setForeground(QColor("#BE4B58"))
+ item.setForeground(QColor(PALETTE["danger"]))
kind = semantic.get(column_index)
if kind:
palette = {
- "success": ("#287B65", "#EAF9F3"),
- "warning": ("#A9691D", "#FFF5E6"),
- "danger": ("#BE4B58", "#FFF1F3"),
- "info": ("#4F63D9", "#EEF1FA"),
- "neutral": ("#6A6B6D", "#F7F7F7"),
+ "success": (PALETTE["success"], PALETTE["success_soft"]),
+ "warning": (PALETTE["warning"], PALETTE["warning_soft"]),
+ "danger": (PALETTE["danger"], PALETTE["danger_soft"]),
+ "info": (PALETTE["accent"], PALETTE["accent_soft"]),
+ "neutral": (PALETTE["muted"], PALETTE["surface_alt"]),
}
foreground, background = palette.get(kind, palette["neutral"])
item.setForeground(QColor(foreground))
@@ -2033,20 +2047,20 @@ class BloodTrendChart(QWidget):
plot = self.rect().adjusted(48, 24, -22, -38)
values = [value for value in (*self._fasting, *self._postprandial) if value is not None]
if not values or plot.width() <= 0 or plot.height() <= 0:
- painter.setPen(QColor("#606163"))
+ painter.setPen(QColor(PALETTE["muted"]))
painter.drawText(self.rect(), Qt.AlignmentFlag.AlignCenter, "当前时间范围暂无血糖数据")
painter.end()
return
upper = max(12.0, max(values) * 1.15)
- painter.setPen(QPen(QColor("#EDEDEE"), 1))
+ painter.setPen(QPen(QColor(PALETTE["line"]), 1))
for step in range(5):
y = plot.bottom() - round(plot.height() * step / 4)
painter.drawLine(plot.left(), y, plot.right(), y)
- painter.setPen(QColor("#606163"))
+ painter.setPen(QColor(PALETTE["muted"]))
painter.drawText(
4, y - 8, 40, 16, Qt.AlignmentFlag.AlignRight, f"{upper * step / 4:.0f}"
)
- painter.setPen(QPen(QColor("#EDEDEE"), 1))
+ painter.setPen(QPen(QColor(PALETTE["line"]), 1))
count = max(1, len(self._dates) - 1)
def point(index: int, value: float) -> QPointF:
@@ -2076,7 +2090,7 @@ class BloodTrendChart(QWidget):
painter.setPen(QColor("#A9691D"))
painter.drawText(plot.left() + 100, 4, 110, 18, Qt.AlignmentFlag.AlignLeft, "● 餐后血糖")
if self._dates:
- painter.setPen(QColor("#606163"))
+ painter.setPen(QColor(PALETTE["muted"]))
painter.drawText(
plot.left(),
plot.bottom() + 8,
@@ -2279,7 +2293,7 @@ class DailyRecordPanel(QFrame):
self.todo_table.setMinimumHeight(180)
todo_layout.addWidget(self.todo_table)
self.todo_summary = QLabel("共 0 条")
- self.todo_summary.setStyleSheet("color:#606163; font-size:13px;")
+ self.todo_summary.setStyleSheet(clinical_stylesheet("color:$ds_muted; font-size:13px;"))
todo_layout.addWidget(self.todo_summary, 0, Qt.AlignmentFlag.AlignRight)
root.addWidget(todo_card)
self.clear()
@@ -2437,8 +2451,8 @@ class DailyRecordPanel(QFrame):
for row_index, (metric, label) in enumerate(self.METRICS):
label_item = QTableWidgetItem(label)
label_item.setFont(label_font)
- label_item.setForeground(QColor("#606163"))
- label_item.setBackground(QColor("#F7F7F7"))
+ label_item.setForeground(QColor(PALETTE["muted"]))
+ label_item.setBackground(QColor(PALETTE["surface_alt"]))
self.matrix.setItem(row_index, 0, label_item)
for date_index, date in enumerate(dates, 1):
b = blood.get(date)
@@ -2491,11 +2505,11 @@ class DailyRecordPanel(QFrame):
item = QTableWidgetItem(value)
item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
if high:
- item.setForeground(QColor("#BE4B58"))
- item.setBackground(QColor("#FFF1F3"))
+ item.setForeground(QColor(PALETTE["danger"]))
+ item.setBackground(QColor(PALETTE["danger_soft"]))
elif value.endswith("· 自录"):
- item.setForeground(QColor("#1A1C1F"))
- item.setBackground(QColor("#F7F7F7"))
+ item.setForeground(QColor(PALETTE["text"]))
+ item.setBackground(QColor(PALETTE["surface_alt"]))
edit_kind = ""
edit_source: Any = None
if metric in {"fasting", "postprandial", "other", "bp", "western", "insulin"}:
@@ -3022,7 +3036,7 @@ class ChatPanel(QWidget):
toolbar_layout.setContentsMargins(0, 0, 0, 0)
toolbar_layout.setSpacing(8)
archive = QLabel("仅展示服务端已归档消息(only_archived=1)")
- archive.setStyleSheet("color:#606163;font-size:12px;")
+ archive.setStyleSheet(clinical_stylesheet("color:$ds_muted;font-size:12px;"))
toolbar_layout.addWidget(archive)
toolbar_layout.addStretch(1)
self.sync_button = QPushButton("同步最新(后台异步)")
@@ -3298,7 +3312,7 @@ class CaseGrid(QFrame):
if group_index:
divider = QFrame()
divider.setFrameShape(QFrame.Shape.HLine)
- divider.setStyleSheet("border:0; border-top:1px dashed #E4E4E5;")
+ divider.setStyleSheet(clinical_stylesheet("border:0; border-top:1px solid $ds_line;"))
self.root.addWidget(divider)
group_title = QLabel(f"● {group_name}")
group_title.setProperty("diagnosisCaseGroup", True)
@@ -3456,11 +3470,11 @@ def readonly_card(title: str, object_name: str, body: QWidget) -> QFrame:
def set_tag_item(item: QTableWidgetItem, kind: str) -> None:
palette = {
- "success": ("#287B65", "#EAF9F3"),
- "warning": ("#A9691D", "#FFF5E6"),
- "danger": ("#BE4B58", "#FFF1F3"),
- "info": ("#4F63D9", "#EEF1FA"),
- "neutral": ("#6A6B6D", "#F7F7F7"),
+ "success": (PALETTE["success"], PALETTE["success_soft"]),
+ "warning": (PALETTE["warning"], PALETTE["warning_soft"]),
+ "danger": (PALETTE["danger"], PALETTE["danger_soft"]),
+ "info": (PALETTE["accent"], PALETTE["accent_soft"]),
+ "neutral": (PALETTE["muted"], PALETTE["surface_alt"]),
}
foreground, background = palette.get(kind, palette["neutral"])
item.setForeground(QColor(foreground))
diff --git a/app/src/doctor_workstation/ui/diagnosis_index_widgets.py b/app/src/doctor_workstation/ui/diagnosis_index_widgets.py
index a2ecb96be..9a420b56d 100644
--- a/app/src/doctor_workstation/ui/diagnosis_index_widgets.py
+++ b/app/src/doctor_workstation/ui/diagnosis_index_widgets.py
@@ -67,21 +67,22 @@ from ..core.appointment_modes import (
can_appointment_video,
)
from . import icons
+from .design_system import PALETTE, clinical_stylesheet
from .reception_style import TECH_BLUE, body_family, heading_family
from .widgets import display_text, first_value, gender_text, get_value
-PRIMARY = QColor("#4F63D9")
-TEXT = QColor("#1A1C1F")
-SECONDARY = QColor("#606163")
-PLACEHOLDER = QColor("#8E8F90")
+PRIMARY = QColor(PALETTE["accent"])
+TEXT = QColor(PALETTE["text"])
+SECONDARY = QColor(PALETTE["muted"])
+PLACEHOLDER = QColor(PALETTE["disabled"])
_INVALID_INDEX = QModelIndex()
# The last two columns form the compact frozen pane. Video status and ending
# time occupy separate lines; actions keep two inline links plus 更多, with
# the remaining actions in its menu so clinical columns retain more space.
_TABLE_COLUMN_WIDTHS = (48, 70, 60, 100, 175, 88, 120, 100, 72, 110, 96, 160)
_BLUE_COLUMN_WIDTHS = (48, 70, 82, 102, 244, 90, 84, 90, 88, 122, 92, 158)
-_BLUE_WARNING = QColor("#A9691D")
-_BLUE_DANGER = QColor("#BE4B58")
+_BLUE_WARNING = QColor(PALETTE["warning"])
+_BLUE_DANGER = QColor(PALETTE["danger"])
def _blue_font(pixels: int = 13, *, medium: bool = False) -> QFont:
@@ -248,14 +249,14 @@ class _DiagnosisActionMenu(QMenu):
return
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
- painter.fillRect(rect, QColor("#FFFFFF"))
+ painter.fillRect(rect, QColor(PALETTE["surface"]))
item_rect = rect
painter.setPen(Qt.PenStyle.NoPen)
- painter.setBrush(QColor("#F7F7F7") if self.activeAction() is action else QColor("#FFFFFF"))
+ painter.setBrush(QColor(PALETTE["surface_alt"]) if self.activeAction() is action else QColor(PALETTE["surface"]))
painter.drawRoundedRect(item_rect, 3, 3)
icon_rect = QRect(item_rect.left() + 8, item_rect.center().y() - 9, 18, 18)
action.icon().paint(painter, icon_rect)
- painter.setPen(QColor("#BE4B58" if action.isEnabled() else "#8E8F90"))
+ painter.setPen(QColor(PALETTE["danger"] if action.isEnabled() else PALETTE["disabled"]))
painter.drawText(
item_rect.adjusted(34, 0, -10, 0),
Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft,
@@ -823,6 +824,8 @@ class DiagnosisTableModel(QAbstractTableModel):
default="",
)
return f"最近渠道:{channel}" if channel else ""
+ if column == 6:
+ return DiagnosisTableModel._display(row, column)
if column == 7:
return display_text(first_value(row, "assistant_name"), "")
if column == 9:
@@ -849,7 +852,7 @@ class DiagnosisHeader(QHeaderView):
def paintSection(self, painter: QPainter, rect: QRect, logical_index: int) -> None: # noqa: N802
if self.tech_blue:
painter.save()
- painter.fillRect(rect, QColor("#F5F8FD"))
+ painter.fillRect(rect, QColor(PALETTE["surface_alt"]))
painter.setPen(QPen(QColor(TECH_BLUE["line"]), 1))
painter.drawLine(rect.bottomLeft(), rect.bottomRight())
painter.setFont(_blue_font())
@@ -870,7 +873,7 @@ class DiagnosisHeader(QHeaderView):
painter.save()
painter.setPen(Qt.PenStyle.NoPen)
primary = QColor(TECH_BLUE["accent"]) if self.tech_blue else PRIMARY
- secondary = QColor(TECH_BLUE["muted"]) if self.tech_blue else QColor("#606163")
+ secondary = QColor(TECH_BLUE["muted"]) if self.tech_blue else QColor(PALETTE["muted"])
painter.setBrush(primary if direction == "asc" else secondary)
painter.drawPolygon(
QPolygon(
@@ -953,7 +956,7 @@ class DiagnosisItemDelegate(QStyledItemDelegate):
painter,
option.rect,
"已确认" if _confirmed(record) else "未确认",
- QColor("#287B65") if _confirmed(record) else QColor("#A9691D"),
+ QColor(PALETTE["success"]) if _confirmed(record) else QColor(PALETTE["warning"]),
)
elif index.column() == 6:
self._paint_followup(painter, option.rect, record)
@@ -1023,16 +1026,16 @@ class DiagnosisItemDelegate(QStyledItemDelegate):
) -> None:
hovered = model.hover_row == row
base = (
- QColor("#EEF1FA")
+ QColor(PALETTE["accent_soft"])
if selected
- else QColor("#F7F7F7" if hovered else "#F7F7F7" if row % 2 else "#FFFFFF")
+ else QColor(PALETTE["surface_alt"] if hovered or row % 2 else PALETTE["surface"])
)
special = not _confirmed(record) or not _has_appointment(record)
painter.fillRect(rect, base)
if special and column == 0:
- stripe = QColor("#A9691D") if not _confirmed(record) else QColor("#4F63D9")
+ stripe = QColor(PALETTE["warning"]) if not _confirmed(record) else QColor(PALETTE["accent"])
painter.fillRect(QRect(rect.left(), rect.top(), 3, rect.height()), stripe)
- painter.setPen(QPen(QColor("#EDEDEE"), 1))
+ painter.setPen(QPen(QColor(PALETTE["line"]), 1))
painter.drawLine(QLine(rect.bottomLeft(), rect.bottomRight()))
@staticmethod
@@ -1070,8 +1073,8 @@ class DiagnosisItemDelegate(QStyledItemDelegate):
painter,
QRect(left, content.center().y() - 10, 31, 20),
"NEW",
- QColor("#BE4B58"),
- QColor("#FFFFFF"),
+ QColor(PALETTE["danger"]),
+ QColor(PALETTE["surface"]),
10,
)
@@ -1081,17 +1084,17 @@ class DiagnosisItemDelegate(QStyledItemDelegate):
self._draw_text(painter, content, "未挂号", PLACEHOLDER, 13)
return
rows = _appointments(record)
- painter.setPen(QPen(QColor("#EDEDEE"), 1))
- painter.setBrush(QColor("#FFFFFF"))
+ painter.setPen(QPen(QColor(PALETTE["line"]), 1))
+ painter.setBrush(QColor(PALETTE["surface"]))
painter.drawRoundedRect(content, 6, 6)
y = content.top() + 4
for position, appointment in enumerate(rows or [{}]):
status = _as_int(first_value(appointment, "status", "appointment_status"), -1)
label, fg, bg = {
- 1: ("已预约", QColor("#4F63D9"), QColor("#EEF1FA")),
- 3: ("已完成", QColor("#287B65"), QColor("#E8F6F1")),
- 4: ("已过号", QColor("#A9691D"), QColor("#FFF4D8")),
- }.get(status, ("未知", SECONDARY, QColor("#F7F7F7")))
+ 1: ("已预约", QColor(PALETTE["accent"]), QColor(PALETTE["accent_soft"])),
+ 3: ("已完成", QColor(PALETTE["success"]), QColor(PALETTE["success_soft"])),
+ 4: ("已过号", QColor(PALETTE["warning"]), QColor(PALETTE["warning_soft"])),
+ }.get(status, ("未知", SECONDARY, QColor(PALETTE["surface_alt"])))
self._draw_tag(painter, QRect(content.left() + 6, y, 46, 20), label, bg, fg, 12)
doctor = display_text(first_value(appointment, "doctor_name"), "-")
time_text = display_text(first_value(appointment, "time_text", "appointment_time"), "-")
@@ -1106,12 +1109,12 @@ class DiagnosisItemDelegate(QStyledItemDelegate):
painter,
QRect(content.left() + 6, y + 19, max(20, content.width() - 12), 17),
time_text,
- QColor("#A9691D") if status == 4 else SECONDARY,
+ QColor(PALETTE["warning"]) if status == 4 else SECONDARY,
13,
)
y += 42
if position < len(rows) - 1:
- painter.setPen(QPen(QColor("#EDEDEE"), 1, Qt.PenStyle.DashLine))
+ painter.setPen(QPen(QColor(PALETTE["line"]), 1, Qt.PenStyle.DashLine))
painter.drawLine(content.left() + 6, y - 2, content.right() - 6, y - 2)
channel = first_value(
record,
@@ -1153,7 +1156,7 @@ class DiagnosisItemDelegate(QStyledItemDelegate):
painter,
QRect(content.left(), content.top() + 38, 72, 18),
"处方已作废",
- QColor("#F7F7F7"),
+ QColor(PALETTE["surface_alt"]),
SECONDARY,
11,
outlined=True,
@@ -1166,11 +1169,11 @@ class DiagnosisItemDelegate(QStyledItemDelegate):
else:
days = _as_int(value)
color = (
- QColor("#287B65")
+ QColor(PALETTE["success"])
if days <= 2
- else QColor("#A9691D")
+ else QColor(PALETTE["warning"])
if days <= 6
- else QColor("#BE4B58")
+ else QColor(PALETTE["danger"])
)
text, bold = str(days), days > 6
self._draw_text(
@@ -1320,6 +1323,8 @@ class _TechBlueDiagnosisDelegate(DiagnosisItemDelegate):
painter, content, "已确认" if _confirmed(record) else "未确认", pixels=13,
color="text" if _confirmed(record) else _BLUE_WARNING.name(),
)
+ elif column == 6:
+ self._followup(painter, content, display_text(index.data(), "—"))
elif column == 8:
prescribed = _as_bool(first_value(record, "has_prescription"))
self._text(painter, content, "已开方" if prescribed else "未开方",
@@ -1348,6 +1353,28 @@ class _TechBlueDiagnosisDelegate(DiagnosisItemDelegate):
medium=column == 2)
painter.restore()
+ @staticmethod
+ def _followup(painter: QPainter, rect: QRect, text: str) -> None:
+ """Break at the date/time boundary, never in the middle of a number.
+
+ Keep the established row metrics. Long time ranges or doctor names
+ elide within their line; the model tooltip retains the complete text.
+ """
+ painter.setFont(_blue_font(13))
+ painter.setPen(QColor(TECH_BLUE["muted"]))
+ metrics = painter.fontMetrics()
+ lines = text.splitlines()
+ if lines and metrics.horizontalAdvance(lines[0]) > rect.width():
+ lines[:1] = lines[0].split(maxsplit=1)
+ line_height = metrics.height()
+ top = rect.top() + max(0, (rect.height() - line_height * len(lines)) // 2)
+ for offset, line in enumerate(lines):
+ painter.drawText(
+ QRect(rect.left(), top + offset * line_height, rect.width(), line_height),
+ int(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter | Qt.TextFlag.TextSingleLine),
+ metrics.elidedText(line, Qt.TextElideMode.ElideRight, rect.width()),
+ )
+
def _appointments(self, painter: QPainter, rect: QRect, record: Any) -> None:
content = rect.adjusted(8, 0, -8, 0)
if not _has_appointment(record):
@@ -1688,7 +1715,9 @@ class DiagnosisTableHost(QFrame):
self.main.horizontalHeader().sectionResized.connect(self._columns_resized)
self._fixed_render_signature: tuple[Any, ...] | None = None
if tech_blue:
- self.setStyleSheet(_TECH_BLUE_TABLE_QSS.replace("BODY_FAMILY", body_family()))
+ self.setStyleSheet(clinical_stylesheet(
+ _TECH_BLUE_TABLE_QSS.replace("BODY_FAMILY", body_family())
+ ))
def set_rows(self, rows: Iterable[Any]) -> None:
previous_id = DiagnosisTableModel.record_id(self.main.current_data())
@@ -1904,6 +1933,7 @@ class DiagnosisTableHost(QFrame):
.replace("#8E8F90", TECH_BLUE["muted"])
+ f'QMenu {{ font-family: "{body_family()}"; font-weight: 400; }}'
)
+ menu.setStyleSheet(clinical_stylesheet(menu.styleSheet()))
for label, action, _semantic in demoted_actions:
_add_menu_action(
menu,
@@ -2630,19 +2660,19 @@ DIAGNOSIS_INDEX_QSS += """
#DiagnosisIndex QFrame#DiagnosisFilterCard,
#DiagnosisIndex QFrame#DiagnosisListCard {
border: 1px solid #EDEDEE;
- border-radius: 13px;
+ border-radius: $ds_radius_panel;
}
#DiagnosisIndex QLineEdit,
#DiagnosisIndex QComboBox,
#DiagnosisIndex QDateEdit,
#DiagnosisIndex QSpinBox,
#DiagnosisIndex QPushButton {
- border-radius: 8px;
+ border-radius: $ds_radius_control;
}
-#DiagnosisIndex QToolButton[diagnosisChip="true"] { border-radius: 8px; }
+#DiagnosisIndex QToolButton[diagnosisChip="true"] { border-radius: $ds_radius_small; }
#DiagnosisIndex QFrame#DiagnosisListToolbar {
- border-top-left-radius: 13px;
- border-top-right-radius: 13px;
+ border-top-left-radius: $ds_radius_panel;
+ border-top-right-radius: $ds_radius_panel;
}
#DiagnosisIndex QToolButton[diagnosisChip="true"]:checked[semantic="primary"],
#DiagnosisIndex QToolButton[diagnosisChip="true"]:checked[semantic="info"],
@@ -2650,7 +2680,27 @@ DIAGNOSIS_INDEX_QSS += """
#DiagnosisIndex QPushButton[variant="success"] {
color: #FFFFFF;
}
+#DiagnosisIndex QLineEdit:focus,
+#DiagnosisIndex QComboBox:focus,
+#DiagnosisIndex QDateEdit:focus,
+#DiagnosisIndex QSpinBox:focus,
+#DiagnosisIndex QPushButton:focus {
+ border-color: $ds_focus;
+}
+#DiagnosisIndex QPushButton[variant="primary"]:pressed {
+ color: $ds_surface;
+ background-color: $ds_accent_pressed;
+ border-color: $ds_accent_pressed;
+}
+#DiagnosisIndex QPushButton:disabled,
+#DiagnosisIndex QPushButton[variant="primary"]:disabled,
+#DiagnosisIndex QPushButton[variant="success"]:disabled {
+ color: $ds_disabled;
+ background-color: $ds_disabled_surface;
+ border-color: $ds_line;
+}
"""
+DIAGNOSIS_INDEX_QSS = clinical_stylesheet(DIAGNOSIS_INDEX_QSS)
__all__ = [
diff --git a/app/src/doctor_workstation/ui/diagnosis_media.py b/app/src/doctor_workstation/ui/diagnosis_media.py
index d072dd38a..ebbe39ddc 100644
--- a/app/src/doctor_workstation/ui/diagnosis_media.py
+++ b/app/src/doctor_workstation/ui/diagnosis_media.py
@@ -32,6 +32,8 @@ from PySide6.QtWidgets import (
QWidget,
)
+from .design_system import clinical_stylesheet
+
try:
from PySide6.QtMultimedia import QAudioOutput, QMediaPlayer
from PySide6.QtMultimediaWidgets import QVideoWidget
@@ -223,7 +225,7 @@ class InlineRecordingPlayer(QWidget):
self.setMinimumHeight(158)
self.setMaximumHeight(180)
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
- self.setStyleSheet(_INLINE_PLAYER_QSS)
+ self.setStyleSheet(clinical_stylesheet(_INLINE_PLAYER_QSS))
root = QVBoxLayout(self)
root.setContentsMargins(1, 1, 1, 5)
@@ -466,11 +468,11 @@ class RecordingPlaybackCell(QWidget):
separator = QFrame()
separator.setObjectName("DiagnosisRecordingAlternateSeparator")
separator.setFrameShape(QFrame.Shape.HLine)
- separator.setStyleSheet("color:#EDEDEE;")
+ separator.setStyleSheet(clinical_stylesheet("color:$ds_line;"))
layout.addWidget(separator)
label = QLabel("备用地址")
label.setObjectName("DiagnosisRecordingAlternateLabel")
- label.setStyleSheet("color:#606163; font-size:12px;")
+ label.setStyleSheet(clinical_stylesheet("color:$ds_muted; font-size:12px;"))
layout.addWidget(label)
links = QHBoxLayout()
links.setContentsMargins(0, 0, 0, 0)
@@ -490,7 +492,7 @@ class RecordingPlaybackCell(QWidget):
layout.addLayout(links)
self.link_status = QLabel("")
self.link_status.setObjectName("DiagnosisRecordingLinkStatus")
- self.link_status.setStyleSheet("color:#BE4B58; font-size:11px;")
+ self.link_status.setStyleSheet(clinical_stylesheet("color:$ds_danger; font-size:11px;"))
self.link_status.setWordWrap(True)
self.link_status.hide()
layout.addWidget(self.link_status)
@@ -807,7 +809,7 @@ class ImagePreviewDialog(QDialog):
self.setObjectName("DiagnosisImagePreview")
self.setWindowTitle(title)
self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose)
- self.setStyleSheet(_IMAGE_PREVIEW_QSS)
+ self.setStyleSheet(clinical_stylesheet(_IMAGE_PREVIEW_QSS))
self.resize(880, 660)
root = QVBoxLayout(self)
diff --git a/app/src/doctor_workstation/ui/dialogs/ai_consult.py b/app/src/doctor_workstation/ui/dialogs/ai_consult.py
index 9ad112149..3119a475d 100644
--- a/app/src/doctor_workstation/ui/dialogs/ai_consult.py
+++ b/app/src/doctor_workstation/ui/dialogs/ai_consult.py
@@ -62,6 +62,7 @@ from shiboken6 import isValid
from .. import icons
from ..chat_items import parse_chat_item as _parse_chat_item
+from ..design_system import clinical_stylesheet
from ..diagnosis_drawer import CaseGrid, _RemoteImageButton
from ..diagnosis_index_widgets import FlowWidget
from ..diagnosis_media import (
@@ -94,6 +95,9 @@ from ..widgets import (
show_toast,
)
from .ai_consult_charts import GlucoseChartData
+from .ai_consult_drug_names import TCM as DRUG_TCM
+from .ai_consult_drug_names import WESTERN as DRUG_WESTERN
+from .ai_consult_drug_names import summarize_drugs
from .ai_consult_metric_state import (
ABNORMAL_COLOR,
NORMAL_COLOR,
@@ -101,7 +105,6 @@ from .ai_consult_metric_state import (
combined_metric_state,
risk_color,
)
-from .ai_consult_drug_names import TCM as DRUG_TCM, WESTERN as DRUG_WESTERN, summarize_drugs
from .ai_consult_metric_text import MetricTextState, metric_text_context, metric_text_html
from .ai_consult_report_visuals import (
ReportVisual,
@@ -114,10 +117,10 @@ from .prescription_ai import (
diagnosis_ai_task,
)
-AI_CONSULT_QSS = """
+AI_CONSULT_QSS = clinical_stylesheet("""
QDialog#AiConsultDialog {
- color: #1A1C1F;
- background-color: #F7F7F7; font-size: 14px;
+ color: $ds_text;
+ background-color: $ds_canvas; font-size: 14px;
}
QDialog#AiConsultDialog QScrollArea,
QDialog#AiConsultDialog QScrollArea > QWidget,
@@ -149,7 +152,7 @@ QDialog#AiConsultDialog QScrollBar::sub-page:vertical {
background-color: transparent;
}
QDialog#AiConsultDialog QFrame#AiConsultShell {
- background-color: #F7F7F7;
+ background-color: $ds_canvas;
border: 0;
}
QDialog#AiConsultDialog QLabel#AiConsultCrumb {
@@ -171,7 +174,7 @@ QDialog#AiConsultDialog QPushButton#AiConsultBack {
color: #1A1C1F;
background-color: #F0F0F0;
border: 0;
- border-radius: 8px;
+ border-radius: $ds_radius_control;
font-weight: 500;
}
QDialog#AiConsultDialog QPushButton#AiConsultBack:hover { background-color: #EEF1FA; }
@@ -183,7 +186,7 @@ QDialog#AiConsultDialog QFrame#AiConsultHero {
QDialog#AiConsultDialog QLabel#AiConsultAvatar {
color: #FFFFFF;
background-color: #4F63D9;
- border-radius: 22px;
+ border-radius: $ds_radius_control;
font-size: 16px;
font-weight: 600;
}
@@ -201,7 +204,7 @@ QDialog#AiConsultDialog QLabel#AiConsultMeta {
QDialog#AiConsultDialog QLabel#AiConsultChip {
color: #6A6B6D;
background-color: #F7F7F7;
- border-radius: 8px;
+ border-radius: $ds_radius_small;
padding: 4px 8px;
font-size: 13px;
}
@@ -240,7 +243,7 @@ QDialog#AiConsultDialog QPushButton#AiConsultChatFilter {
color: #4F63D9;
background-color: #FFFFFF;
border: 1px solid #E1E5F4;
- border-radius: 8px;
+ border-radius: $ds_radius_control;
font-size: 13px;
}
QDialog#AiConsultDialog QPushButton#AiConsultChatFilter:hover {
@@ -275,7 +278,7 @@ QDialog#AiConsultDialog QLabel#AiConsultRole {
max-width: 30px;
min-height: 30px;
max-height: 30px;
- border-radius: 15px;
+ border-radius: $ds_radius_small;
color: #FFFFFF;
font-size: 13px;
font-weight: 500;
@@ -331,7 +334,7 @@ QDialog#AiConsultDialog QLabel#AiConsultClinicalMeta {
QDialog#AiConsultDialog QLabel#AiConsultClinicalBadge {
color: #4F63D9;
background-color: #EEF1FA;
- border-radius: 7px;
+ border-radius: $ds_radius_small;
padding: 4px 8px;
font-size: 13px;
font-weight: 500;
@@ -346,10 +349,10 @@ QDialog#AiConsultDialog QLabel#AiConsultClinicalSectionTitle {
color: #1A1C1F;
background-color: transparent;
font-size: 14px;
- font-weight: 500;
+ font-weight: 600;
}
QDialog#AiConsultDialog QLabel#AiConsultClinicalSummaryBody {
- color: #1A1C1F;
+ color: $ds_text;
background-color: transparent;
font-size: 14px;
font-weight: 400;
@@ -411,7 +414,7 @@ QDialog#AiConsultDialog QLabel#AiConsultHypothesisTag {
QDialog#AiConsultDialog QLabel#AiConsultClinicalBody,
QDialog#AiConsultDialog QLabel#AiConsultWorkflowBody,
QDialog#AiConsultDialog QLabel#AiConsultRiskBody {
- color: #1A1C1F;
+ color: $ds_text;
background-color: transparent;
font-size: 14px;
font-weight: 400;
@@ -456,23 +459,23 @@ QDialog#AiConsultDialog QLabel#AiConsultRiskTitle {
font-weight: 600;
}
QDialog#AiConsultDialog QLabel#AiConsultRiskBody {
- color: #1A1C1F; font-size: 14px;
+ color: $ds_text; font-size: 14px;
}
QDialog#AiConsultDialog QLabel#AiConsultRiskTitle {
color: #BE4B58;
}
QDialog#AiConsultDialog QLabel#AiConsultRiskBody {
- color: #1A1C1F; font-size: 14px;
+ color: $ds_text; font-size: 14px;
}
/* 结构化报告:正文按阅读节奏排版,不再每句话套一个方框。 */
QDialog#AiConsultDialog QFrame#AiConsultReportIntro {
- background-color: #F7F7F7;
+ background-color: $ds_accent_soft;
border: 1px solid #EDEDEE;
border-left: 3px solid #4F63D9;
- border-radius: 9px;
+ border-radius: $ds_radius_control;
}
QDialog#AiConsultDialog QLabel#AiConsultReportIntroBody {
- color: #1A1C1F;
+ color: $ds_text;
background-color: transparent;
font-size: 14px;
font-weight: 400;
@@ -497,7 +500,7 @@ QDialog#AiConsultDialog QLabel#AiConsultReportSectionTitle {
color: #1A1C1F;
background-color: transparent;
font-size: 15px;
- font-weight: 500;
+ font-weight: 600;
}
QDialog#AiConsultDialog QFrame#AiConsultReportRule {
background-color: #EDEDEE;
@@ -518,7 +521,7 @@ QDialog#AiConsultDialog QLabel#AiConsultReportBullet {
font-weight: 500;
}
QDialog#AiConsultDialog QLabel#AiConsultReportBody {
- color: #1A1C1F;
+ color: $ds_text;
background-color: transparent;
font-size: 14px;
font-weight: 400;
@@ -541,18 +544,18 @@ QDialog#AiConsultDialog QLabel#AiConsultClinicalDisclaimer {
font-weight: 400;
}
QDialog#AiConsultDialog QFrame#AiConsultReportProvenance {
- background-color: #F7F8FC;
- border: 1px solid #E4E8F2;
- border-radius: 9px;
+ background-color: $ds_surface_alt;
+ border: 1px solid $ds_line;
+ border-radius: $ds_radius_control;
}
QDialog#AiConsultDialog QLabel#AiConsultReportProvenanceTitle {
- color: #27336B;
+ color: $ds_heading;
background-color: transparent;
font-size: 12px;
font-weight: 600;
}
QDialog#AiConsultDialog QLabel#AiConsultReportProvenanceLine {
- color: #555B68;
+ color: $ds_muted;
background-color: transparent;
font-size: 12px;
}
@@ -647,7 +650,7 @@ QDialog#AiConsultDialog QLabel#AiConsultSection {
font-weight: 500;
}
QDialog#AiConsultDialog QLabel#AiConsultBody {
- color: #1A1C1F;
+ color: $ds_text;
background-color: transparent;
font-size: 14px;
line-height: 1.6;
@@ -681,7 +684,7 @@ QDialog#AiConsultDialog QLabel#AiConsultInsightPlaceholder {
QDialog#AiConsultDialog QLabel#AiConsultTag[level="high"] {
color: #BE4B58;
background-color: #FFF1F3;
- border-radius: 8px;
+ border-radius: $ds_radius_small;
padding: 2px 8px;
font-size: 13px;
font-weight: 600;
@@ -689,7 +692,7 @@ QDialog#AiConsultDialog QLabel#AiConsultTag[level="high"] {
QDialog#AiConsultDialog QLabel#AiConsultTag[level="medium"] {
color: #A9691D;
background-color: #FFF5E6;
- border-radius: 8px;
+ border-radius: $ds_radius_small;
padding: 2px 8px;
font-size: 13px;
font-weight: 500;
@@ -697,7 +700,7 @@ QDialog#AiConsultDialog QLabel#AiConsultTag[level="medium"] {
QDialog#AiConsultDialog QLabel#AiConsultTag[level="low"] {
color: #287B65;
background-color: #EAF9F3;
- border-radius: 8px;
+ border-radius: $ds_radius_small;
padding: 2px 8px;
font-size: 13px;
font-weight: 500;
@@ -705,7 +708,7 @@ QDialog#AiConsultDialog QLabel#AiConsultTag[level="low"] {
QDialog#AiConsultDialog QLabel#AiConsultTag[level="warn"] {
color: #BE4B58;
background-color: #FFF1F3;
- border-radius: 8px;
+ border-radius: $ds_radius_small;
padding: 2px 8px;
font-size: 13px;
font-weight: 600;
@@ -713,7 +716,7 @@ QDialog#AiConsultDialog QLabel#AiConsultTag[level="warn"] {
QDialog#AiConsultDialog QLabel#AiConsultTag[level="unknown"] {
color: #6A6B6D;
background-color: #F0F0F0;
- border-radius: 8px;
+ border-radius: $ds_radius_small;
padding: 2px 8px;
font-size: 13px;
}
@@ -739,7 +742,7 @@ QDialog#AiConsultDialog QLineEdit#AiConsultInput {
color: #1A1C1F;
background-color: #FFFFFF;
border: 1px solid #EDEDEE;
- border-radius: 12px;
+ border-radius: $ds_radius_control;
font-size: 14px;
}
QDialog#AiConsultDialog QLineEdit#AiConsultInput:focus {
@@ -763,7 +766,7 @@ QDialog#AiConsultDialog QPushButton#AiConsultIconButton {
max-height: 36px;
padding: 0;
border: 0;
- border-radius: 18px;
+ border-radius: $ds_radius_control;
background-color: #F7F7F7;
}
QDialog#AiConsultDialog QPushButton#AiConsultIconButton:hover { background-color: #EEF1FA; }
@@ -774,7 +777,7 @@ QDialog#AiConsultDialog QPushButton#AiConsultSend {
max-height: 40px;
padding: 0;
border: 0;
- border-radius: 20px;
+ border-radius: $ds_radius_control;
background-color: #4F63D9;
}
QDialog#AiConsultDialog QPushButton#AiConsultSend:hover { background-color: #4156C4; }
@@ -783,7 +786,7 @@ QDialog#AiConsultDialog QLabel#AiConsultSideTitle {
color: #1A1C1F;
background-color: transparent;
font-size: 16px;
- font-weight: 500;
+ font-weight: 600;
}
QDialog#AiConsultDialog QLabel#AiConsultSideSubtitle {
color: #6A6B6D;
@@ -871,7 +874,7 @@ QDialog#AiConsultDialog QPushButton#AiConsultSideClose {
max-height: 28px;
padding: 0;
border: 0;
- border-radius: 8px;
+ border-radius: $ds_radius_control;
color: #606163;
background-color: transparent;
font-size: 16px;
@@ -917,10 +920,10 @@ QDialog#AiConsultDialog QLabel#AiConsultRecordTitle {
color: #1A1C1F;
background-color: transparent;
font-size: 13px;
- font-weight: 500;
+ font-weight: 600;
}
QDialog#AiConsultDialog QLabel#AiConsultRecordBody {
- color: #1A1C1F;
+ color: $ds_text;
background-color: transparent;
font-size: 14px;
}
@@ -951,7 +954,7 @@ QDialog#AiConsultDialog QPushButton#AiConsultMediaOpen {
color: #4F63D9;
background-color: #EEF1FA;
border: 0;
- border-radius: 8px;
+ border-radius: $ds_radius_control;
font-weight: 500;
}
QDialog#AiConsultDialog QPushButton#AiConsultRecordRetry:hover,
@@ -1000,10 +1003,11 @@ QDialog#AiConsultDialog QLabel#AiConsultDataLabel {
font-size: 13px;
}
QDialog#AiConsultDialog QLabel#AiConsultDataValue {
- color: #1A1C1F;
+ color: $ds_text;
font-size: 13px;
}
-"""
+QDialog#AiConsultDialog QPushButton:focus { border-color: $ds_focus; }
+""")
QUICK_PROMPTS: tuple[tuple[str, str], ...] = (
("总结当前病情", "请根据当前病历总结患者病情、证候与风险。"),
@@ -1053,8 +1057,8 @@ _DOCTOR_DOCUMENT_CSS = (
# 模型回复几乎都是“分节标题 + 两层要点”的长文。早期样式里标题只比正文大 1px、
# 段落与列表项的间距也几乎相同,整段读起来就是一堵字墙。这里把层级、行距和分节
# 留白拉开:标题明显更大更重,顶层小节之间留出整行空白,嵌套要点单独收紧缩进。
-_AI_DOCUMENT_CSS = (
- "body { color:#1A1C1F; font-size:14px; line-height:200%; } "
+_AI_DOCUMENT_CSS = clinical_stylesheet(
+ "body { color:$ds_text; font-size:14px; line-height:200%; } "
"h1,h2 { color:#1A1C1F; font-size:17px; margin:22px 0 10px; line-height:160%; } "
"h3,h4 { color:#1A1C1F; font-size:15px; margin:18px 0 8px; line-height:160%; } "
"p { margin:10px 0; line-height:200%; } "
@@ -2219,15 +2223,12 @@ def _escape_html(value: str) -> str:
)
-class _FlowRow(QWidget):
+class _FlowRow(FlowWidget):
+ """Keep patient metadata readable when the details pane is narrow."""
+
def __init__(self, parent: QWidget | None = None) -> None:
- super().__init__(parent)
- self._layout = QHBoxLayout(self)
- self._layout.setContentsMargins(0, 0, 0, 0)
- self._layout.setSpacing(8)
- self._layout.setAlignment(
- Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter
- )
+ super().__init__(parent, horizontal_spacing=8, vertical_spacing=6)
+ self._layout = self.flow
def add(self, widget: QWidget) -> None:
self._layout.addWidget(widget)
@@ -2810,7 +2811,7 @@ class _DrugSummaryStrip(QFrame):
layout.addLayout(row)
@staticmethod
- def for_text(text: str, parent: QWidget | None = None) -> "_DrugSummaryStrip | None":
+ def for_text(text: str, parent: QWidget | None = None) -> _DrugSummaryStrip | None:
summary = summarize_drugs(text)
return _DrugSummaryStrip(summary, parent) if any(summary.values()) else None
@@ -3454,11 +3455,11 @@ class _ChatBubble(QWidget):
avatar.setAlignment(Qt.AlignmentFlag.AlignCenter)
_style_surface(avatar)
if role == "doctor":
- avatar.setStyleSheet("background-color:#4F63D9; color:#FFFFFF; border-radius:15px;")
+ avatar.setStyleSheet(clinical_stylesheet("background-color:#4F63D9; color:#FFFFFF; border-radius:6px;"))
elif role == "ai":
- avatar.setStyleSheet("background-color:#EEF1FA; color:#4F63D9; border-radius:15px;")
+ avatar.setStyleSheet(clinical_stylesheet("background-color:#EEF1FA; color:#4F63D9; border-radius:6px;"))
else:
- avatar.setStyleSheet("background-color:#6A6B6D; color:#FFFFFF; border-radius:15px;")
+ avatar.setStyleSheet(clinical_stylesheet("background-color:#6A6B6D; color:#FFFFFF; border-radius:6px;"))
bubble = QFrame()
_style_surface(bubble)
if role == "doctor":
@@ -3629,10 +3630,10 @@ class _ChatBubble(QWidget):
toggle.setCursor(Qt.CursorShape.PointingHandCursor)
toggle.setAccessibleName("展开资料提交回执")
toggle.setStyleSheet(
- "QPushButton {color:#65718A;font-size:12px;text-align:left;"
+ clinical_stylesheet("QPushButton {color:$ds_muted;font-size:12px;text-align:left;"
"background:transparent;border:0;padding:4px 0;}"
"QPushButton:hover {color:#4F63D9;}"
- "QPushButton:focus {border-bottom:1px solid #4F63D9;}"
+ "QPushButton:focus {border-bottom:1px solid #4F63D9;}")
)
layout.addWidget(toggle)
label = QLabel(receipt)
@@ -3643,7 +3644,7 @@ class _ChatBubble(QWidget):
Qt.TextInteractionFlag.TextSelectableByMouse
| Qt.TextInteractionFlag.TextSelectableByKeyboard
)
- label.setStyleSheet("color:#65718A;font-size:12px;")
+ label.setStyleSheet(clinical_stylesheet("color:$ds_muted;font-size:12px;"))
label.hide()
layout.addWidget(label)
self._inner.insertWidget(0, receipt)
@@ -3688,7 +3689,7 @@ class _ChatBubble(QWidget):
label.setTextFormat(Qt.TextFormat.PlainText)
label.setWordWrap(True)
label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
- label.setStyleSheet("color:#BE4B58;background:#FEF3F2;border-radius:6px;padding:8px;")
+ label.setStyleSheet(clinical_stylesheet("color:#BE4B58;background:#FEF3F2;border-radius:6px;padding:8px;"))
self._inner.insertWidget(self._inner.indexOf(self.body), label)
self._stream_failure_label = label
label.setText(f"本次回复未完成\n{text}")
@@ -4949,8 +4950,9 @@ class AiConsultDialog(QDialog):
button.setObjectName("AiConsultChipButton")
button.setCursor(Qt.CursorShape.PointingHandCursor)
button.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
+ task_key = QUICK_PROMPT_TASKS.get(label, "")
button.clicked.connect(
- lambda _checked=False, text=prompt, task=QUICK_PROMPT_TASKS.get(label, ""):
+ lambda _checked=False, text=prompt, task=task_key:
self._ask(text, replace_active=True, task=task)
)
chips.addWidget(button, 1)
diff --git a/app/src/doctor_workstation/ui/dialogs/app_update.py b/app/src/doctor_workstation/ui/dialogs/app_update.py
index 485032d64..4d2fd6a67 100644
--- a/app/src/doctor_workstation/ui/dialogs/app_update.py
+++ b/app/src/doctor_workstation/ui/dialogs/app_update.py
@@ -43,6 +43,7 @@ from doctor_workstation.services.app_update import (
validate_installer_download_policy,
validate_windows_installer,
)
+from doctor_workstation.ui.design_system import clinical_stylesheet
from doctor_workstation.ui.widgets import friendly_error, show_toast
LOGGER = logging.getLogger(__name__)
@@ -129,11 +130,11 @@ class AppUpdateDialog(QDialog):
self.badge = QLabel("必须更新后才能继续使用" if offer.force else "发现新版本")
self.badge.setObjectName("UpdateBadge")
- self.badge.setStyleSheet(
+ self.badge.setStyleSheet(clinical_stylesheet(
"color:#A9691D;background:#FFF5E6;border-radius:8px;padding:4px 10px;font-weight:600;"
if offer.force
else "color:#4F63D9;background:#EEF1FA;border-radius:8px;padding:4px 10px;font-weight:600;"
- )
+ ))
root.addWidget(self.badge, 0, Qt.AlignmentFlag.AlignLeft)
self.headline = QLabel(title or "医生工作站有新版本")
@@ -146,7 +147,7 @@ class AppUpdateDialog(QDialog):
latest = offer.latest_version or "新版本"
self.version_label = QLabel(f"当前版本 {current} → 最新版本 {latest}")
self.version_label.setObjectName("UpdateVersionLabel")
- self.version_label.setStyleSheet("color:#606163;")
+ self.version_label.setStyleSheet(clinical_stylesheet("color:$ds_muted;"))
root.addWidget(self.version_label)
self.notes = QTextEdit()
@@ -160,7 +161,7 @@ class AppUpdateDialog(QDialog):
self.status_label = QLabel("")
self.status_label.setObjectName("UpdateStatus")
self.status_label.setWordWrap(True)
- self.status_label.setStyleSheet("color:#1A1C1F;")
+ self.status_label.setStyleSheet(clinical_stylesheet("color:$ds_heading;"))
self.status_label.hide()
root.addWidget(self.status_label)
@@ -175,7 +176,7 @@ class AppUpdateDialog(QDialog):
self.progress_text = QLabel("")
self.progress_text.setObjectName("UpdateProgressText")
- self.progress_text.setStyleSheet("color:#606163;font-size:12px;")
+ self.progress_text.setStyleSheet(clinical_stylesheet("color:$ds_muted;font-size:12px;"))
self.progress_text.hide()
root.addWidget(self.progress_text)
@@ -225,7 +226,7 @@ class AppUpdateDialog(QDialog):
def show_download_progress(self, received: int, total: int) -> None:
self.progress.show()
self.progress_text.show()
- self.status_label.setStyleSheet("color:#1A1C1F;")
+ self.status_label.setStyleSheet(clinical_stylesheet("color:$ds_heading;"))
self.status_label.setText("正在下载安装包…")
self.status_label.show()
if total > 0:
@@ -237,7 +238,7 @@ class AppUpdateDialog(QDialog):
self.progress_text.setText(_format_bytes(received))
def show_status(self, message: str, *, determinate: bool = False) -> None:
- self.status_label.setStyleSheet("color:#1A1C1F;")
+ self.status_label.setStyleSheet(clinical_stylesheet("color:$ds_heading;"))
self.status_label.setText(message)
self.status_label.show()
self.progress.show()
@@ -251,7 +252,7 @@ class AppUpdateDialog(QDialog):
def show_error(self, message: str) -> None:
self._busy = False
self.status_label.setText(message)
- self.status_label.setStyleSheet("color:#BE4B58;")
+ self.status_label.setStyleSheet(clinical_stylesheet("color:$ds_danger;"))
self.status_label.show()
self.progress.hide()
self.progress_text.hide()
diff --git a/app/src/doctor_workstation/ui/dialogs/diagnosis.py b/app/src/doctor_workstation/ui/dialogs/diagnosis.py
index d5e3f50b9..98b6413d6 100644
--- a/app/src/doctor_workstation/ui/dialogs/diagnosis.py
+++ b/app/src/doctor_workstation/ui/dialogs/diagnosis.py
@@ -48,6 +48,7 @@ from PySide6.QtWidgets import (
)
from ...core.appointment_modes import appointment_type_description, appointment_type_value
+from ..design_system import clinical_stylesheet
from ..diagnosis_drawer import (
DIAGNOSIS_QSS,
CaseGrid,
@@ -97,6 +98,7 @@ from .issued_prescription_ai import can_open_issued_ai, present_issued_prescript
from .local_audio_queue import LocalAudioQueueDialog
from .prescription_ai import can_open_diagnosis_ai_report, present_diagnosis_ai_report
+
class _UploadProgressRelay(QObject):
"""把后台线程中的分片上传进度转回界面线程(信号跨线程自动排队)。"""
@@ -1541,16 +1543,16 @@ class DiagnosisDialog(QDialog):
"""上传本地回放时的进度条:按分片实时更新,医生能看到上传在进行、进行到哪。"""
frame = QFrame()
frame.setObjectName("DiagnosisVideoUploadProgress")
- frame.setStyleSheet(
+ frame.setStyleSheet(clinical_stylesheet(
"QFrame#DiagnosisVideoUploadProgress { background-color: #EEF1FA;"
- " border: 1px solid #C9D1F3; border-radius: 8px; }"
- "QFrame#DiagnosisVideoUploadProgress QLabel { color: #3347B8; background: transparent;"
+ " border: 1px solid $ds_line_strong; border-radius: $ds_radius_control; }"
+ "QFrame#DiagnosisVideoUploadProgress QLabel { color: $ds_accent_hover; background: transparent;"
" font-size: 13px; font-weight: 500; }"
"QFrame#DiagnosisVideoUploadProgress QProgressBar { background-color: #FFFFFF;"
" border: 0; border-radius: 4px; min-height: 8px; max-height: 8px; }"
"QFrame#DiagnosisVideoUploadProgress QProgressBar::chunk { background-color: #4F63D9;"
" border-radius: 4px; }"
- )
+ ))
row = QVBoxLayout(frame)
row.setContentsMargins(12, 8, 12, 10)
row.setSpacing(6)
diff --git a/app/src/doctor_workstation/ui/dialogs/issued_prescription_ai_theme.py b/app/src/doctor_workstation/ui/dialogs/issued_prescription_ai_theme.py
index f003977b1..bbdb46f1e 100644
--- a/app/src/doctor_workstation/ui/dialogs/issued_prescription_ai_theme.py
+++ b/app/src/doctor_workstation/ui/dialogs/issued_prescription_ai_theme.py
@@ -21,6 +21,8 @@ from typing import Any
from PySide6.QtGui import QFont
+from ..design_system import PALETTE
+
DARK: dict[str, str] = {
# ground and cards
"canvas": "#080D18",
@@ -62,23 +64,23 @@ DARK: dict[str, str] = {
}
LIGHT: dict[str, str] = {
- "canvas": "#F1F5FC",
- "canvas_soft": "#E7EEFA",
- "surface": "#FFFFFF",
- "surface_2": "#F5F8FE",
- "raised": "#E8EFFA",
- "line": "#D5E1F2",
- "line_soft": "#E3EBF8",
- "heading": "#0A182E",
- "text": "#2A3C56",
- "muted": "#54697F",
- "faint": "#7A8DA3",
- "selected_text": "#0A182E",
- "accent": "#1A5FD0",
- "accent_text": "#124DAE",
- "accent_pressed": "#0E3F90",
- "selection": "#E8EFFA",
- "selection_line": "#AEC7EE",
+ "canvas": PALETTE["canvas"],
+ "canvas_soft": PALETTE["surface_alt"],
+ "surface": PALETTE["surface"],
+ "surface_2": PALETTE["surface_alt"],
+ "raised": PALETTE["sidebar"],
+ "line": PALETTE["line_strong"],
+ "line_soft": PALETTE["line"],
+ "heading": PALETTE["heading"],
+ "text": PALETTE["text"],
+ "muted": PALETTE["muted"],
+ "faint": PALETTE["disabled"],
+ "selected_text": PALETTE["heading"],
+ "accent": PALETTE["accent"],
+ "accent_text": PALETTE["accent_hover"],
+ "accent_pressed": PALETTE["accent_pressed"],
+ "selection": PALETTE["accent_soft"],
+ "selection_line": PALETTE["focus"],
"qwen": "#0C89AC",
"qwen_text": "#086C88",
"qwen_dim": "#E2F5FA",
diff --git a/app/src/doctor_workstation/ui/dialogs/local_audio_queue.py b/app/src/doctor_workstation/ui/dialogs/local_audio_queue.py
index 4af364d26..0f21c06ee 100644
--- a/app/src/doctor_workstation/ui/dialogs/local_audio_queue.py
+++ b/app/src/doctor_workstation/ui/dialogs/local_audio_queue.py
@@ -29,6 +29,7 @@ from ...services.local_audio_queue import (
LocalAudioUploadManager,
get_local_audio_upload_manager,
)
+from ..design_system import clinical_stylesheet
from ..widgets import run_async
_STATUS_LABELS = {
@@ -174,7 +175,7 @@ class LocalAudioQueueDialog(QDialog):
self.setModal(True)
self.setMinimumSize(760, 480)
self.resize(1160, 620)
- self.setStyleSheet(_LOCAL_AUDIO_QSS)
+ self.setStyleSheet(clinical_stylesheet(_LOCAL_AUDIO_QSS))
self._build_ui()
self.poll_timer = QTimer(self)
diff --git a/app/src/doctor_workstation/ui/dialogs/prescription.py b/app/src/doctor_workstation/ui/dialogs/prescription.py
index 77b5fdad2..bd69d795a 100644
--- a/app/src/doctor_workstation/ui/dialogs/prescription.py
+++ b/app/src/doctor_workstation/ui/dialogs/prescription.py
@@ -28,8 +28,8 @@ from PySide6.QtCore import (
QDate,
QEvent,
QIODevice,
- QModelIndex,
QMarginsF,
+ QModelIndex,
QObject,
QPoint,
QRectF,
@@ -98,6 +98,7 @@ from PySide6.QtWidgets import (
)
from .. import icons
+from ..design_system import clinical_stylesheet
from ..diagnosis_terms import shared_terms
from ..infinite_list import InfiniteList
from ..theme import main_window_target_rect
@@ -116,9 +117,9 @@ from ..widgets import (
)
from .diagnosis import DiagnosisDialog as _StructuredDiagnosisDialog
-PRESCRIPTION_DRAWER_QSS = r"""
+PRESCRIPTION_DRAWER_QSS = clinical_stylesheet(r"""
QFrame#PrescriptionDrawerSurface {
- color: #1A1C1F;
+ color: $ds_text;
background-color: #FFFFFF;
border-left: 1px solid #EDEDEE;
font-size: 14px;
@@ -145,7 +146,7 @@ QLabel#PrescriptionLockTag {
color: #BE4B58;
background-color: #FEF0F0;
border: 1px solid #FDE2E2;
- border-radius: 4px;
+ border-radius: $ds_radius_small;
padding: 2px 8px;
font-size: 13px;
}
@@ -175,7 +176,7 @@ QLabel#PrescriptionDrawerMode {
color: #4F63D9;
background-color: #EEF1FA;
border: 1px solid #EDEDEE;
- border-radius: 5px;
+ border-radius: $ds_radius_small;
padding: 4px 9px;
font-size: 13px;
font-weight: 500;
@@ -189,7 +190,7 @@ QPushButton#PrescriptionDrawerClose {
color: #606163;
background-color: transparent;
border: 0;
- border-radius: 7px;
+ border-radius: $ds_radius_control;
font-size: 22px;
font-weight: 400;
}
@@ -208,12 +209,12 @@ QWidget#PrescriptionDrawerContent {
QFrame#PrescriptionFormSection {
background-color: #F7F7F7;
border: 1px solid #EDEDEE;
- border-radius: 10px;
+ border-radius: $ds_radius_panel;
}
QLabel#PrescriptionSectionTitle {
color: #1A1C1F;
font-size: 15px;
- font-weight: 500;
+ font-weight: 600;
}
QLabel#PrescriptionSectionHint {
color: #6A6B6D;
@@ -242,7 +243,7 @@ QLabel#PrescriptionUsageAux {
QFrame#PrescriptionRpToolbar {
background-color: #FFFFFF;
border: 1px solid #EDEDEE;
- border-radius: 10px;
+ border-radius: $ds_radius_panel;
}
QFrame#PrescriptionRpMarker {
background-color: #4F63D9;
@@ -262,12 +263,12 @@ QLabel#PrescriptionRpLock {
color: #BE4B58;
background-color: #FEF3F2;
border: 1px solid #FECDCA;
- border-radius: 5px;
+ border-radius: $ds_radius_small;
padding: 5px 8px;
font-size: 13px;
}
QLabel#PrescriptionFormulaTag {
- border-radius: 4px;
+ border-radius: $ds_radius_small;
padding: 3px 8px;
font-size: 13px;
font-weight: 500;
@@ -328,7 +329,7 @@ QFrame#PrescriptionDrawerSurface QDoubleSpinBox {
color: #1A1C1F;
background-color: #FFFFFF;
border: 1px solid #EDEDEE;
- border-radius: 7px;
+ border-radius: $ds_radius_control;
padding: 0 11px;
selection-background-color: #C9D1F3;
selection-color: #1A1C1F; font-size: 14px;
@@ -338,7 +339,7 @@ QFrame#PrescriptionDrawerSurface QComboBox {
color: #1A1C1F;
background-color: #FFFFFF;
border: 1px solid #EDEDEE;
- border-radius: 7px;
+ border-radius: $ds_radius_control;
padding-left: 11px;
padding-right: 28px;
selection-background-color: #C9D1F3;
@@ -379,7 +380,7 @@ QFrame#PrescriptionDatePicker {
min-height: 32px;
background-color: #FFFFFF;
border: 1px solid #EDEDEE;
- border-radius: 7px;
+ border-radius: $ds_radius_control;
}
QFrame#PrescriptionDatePicker:hover {
border-color: #8B9AD9;
@@ -446,7 +447,7 @@ QFrame#PrescriptionDrawerSurface QPushButton {
color: #1A1C1F;
background-color: #FFFFFF;
border: 1px solid #EDEDEE;
- border-radius: 7px;
+ border-radius: $ds_radius_control;
font-weight: 500;
}
QFrame#PrescriptionDrawerSurface QPushButton:hover {
@@ -468,7 +469,7 @@ QFrame#PrescriptionDrawerSurface QPushButton#PrescriptionDrawerClose {
color: #606163;
background-color: transparent;
border: 0;
- border-radius: 7px;
+ border-radius: $ds_radius_control;
font-size: 22px;
font-weight: 400;
}
@@ -496,23 +497,23 @@ QFrame#PrescriptionDrawerSurface QPushButton[variant="primary"]:hover {
border-color: #4156C4;
}
QFrame#PrescriptionDrawerSurface QPushButton[variant="success"] {
- color: #FFFFFF;
- background-color: #287B65;
- border-color: #287B65;
+ color: $ds_accent;
+ background-color: $ds_accent_soft;
+ border-color: $ds_line;
}
QFrame#PrescriptionDrawerSurface QPushButton[variant="success"]:hover {
- background-color: #287B65;
- border-color: #287B65;
+ background-color: $ds_accent_soft;
+ border-color: $ds_focus;
}
QFrame#PrescriptionDrawerSurface QPushButton[variant="warning"] {
- color: #A9691D;
+ color: $ds_accent;
background-color: #FFFFFF;
- border-color: #A9691D;
+ border-color: $ds_accent;
}
QFrame#PrescriptionDrawerSurface QPushButton[variant="warning"]:hover {
- color: #FFFFFF;
- background-color: #A9691D;
- border-color: #A9691D;
+ color: $ds_accent_hover;
+ background-color: $ds_accent_soft;
+ border-color: $ds_focus;
}
QFrame#PrescriptionDrawerSurface QPushButton[variant="secondary"] {
color: #4F63D9;
@@ -615,7 +616,8 @@ QFrame#PrescriptionDrawerSurface QFrame#MessageBanner[kind="danger"] {
QFrame#PrescriptionDrawerSurface QFrame#MessageBanner[kind="danger"] QLabel {
color: #BE4B58;
}
-"""
+QFrame#PrescriptionDrawerSurface QPushButton:focus { border: 1px solid $ds_focus; }
+""")
_CHEVRON_PATH: Path | None = None
@@ -647,7 +649,7 @@ def _prescription_drawer_qss() -> str:
def _prescription_calendar_qss() -> str:
- return """
+ return clinical_stylesheet("""
QCalendarWidget {
background-color: #FFFFFF;
border: 1px solid #EDEDEE;
@@ -672,13 +674,13 @@ QCalendarWidget QAbstractItemView:enabled {
selection-color: #1A1C1F;
outline: 0;
}
-"""
+""")
-PRESCRIPTION_DIALOG_QSS = """
+PRESCRIPTION_DIALOG_QSS = clinical_stylesheet("""
QDialog#PrescriptionDialogSurface {
color: #1A1C1F;
- background-color: #F7F7F7;
+ background-color: $ds_canvas;
font-size: 14px;
}
QDialog#PrescriptionDialogSurface QLabel {
@@ -740,7 +742,7 @@ QDialog#PrescriptionDialogSurface QTextBrowser {
color: #1A1C1F;
background-color: #FFFFFF;
border: 1px solid #EDEDEE;
- border-radius: 7px;
+ border-radius: $ds_radius_control;
selection-background-color: #EEF1FA;
selection-color: #1A1C1F; font-size: 14px;
}
@@ -768,7 +770,7 @@ QDialog#PrescriptionDialogSurface QPushButton {
color: #1A1C1F;
background-color: #FFFFFF;
border: 1px solid #EDEDEE;
- border-radius: 7px;
+ border-radius: $ds_radius_control;
font-weight: 500;
}
QDialog#PrescriptionDialogSurface QPushButton:hover {
@@ -798,7 +800,7 @@ QDialog#PrescriptionDialogSurface QPushButton:disabled {
QDialog#PrescriptionDialogSurface QTabWidget::pane {
background-color: #FFFFFF;
border: 1px solid #EDEDEE;
- border-radius: 9px;
+ border-radius: $ds_radius_panel;
top: -1px;
}
QDialog#PrescriptionDialogSurface QTabBar::tab {
@@ -852,7 +854,8 @@ QDialog#PrescriptionDialogSurface QScrollBar::add-line:vertical,
QDialog#PrescriptionDialogSurface QScrollBar::sub-line:vertical {
height: 0;
}
-"""
+QDialog#PrescriptionDialogSurface QPushButton:focus { border: 1px solid $ds_focus; }
+""")
def _apply_prescription_dialog_style(dialog: QDialog) -> None:
@@ -1531,9 +1534,9 @@ class RemoteMedicineComboBox(QComboBox):
popup = self._completer.popup()
popup.setItemDelegate(_MedicineSuggestionDelegate(popup))
popup.setStyleSheet(
- "QListView { background-color: #FFFFFF; border: 1px solid #E4E7ED; border-radius: 6px;"
+ clinical_stylesheet("QListView { background-color: #FFFFFF; border: 1px solid #E4E7ED; border-radius: 6px;"
" padding: 4px 0; font-size: 14px; outline: 0; }"
- "QListView::item:selected, QListView::item:hover { background-color: #F5F7FA; }"
+ "QListView::item:selected, QListView::item:hover { background-color: #F5F7FA; }")
)
self.lineEdit().setCompleter(self._completer)
self.lineEdit().installEventFilter(self)
@@ -5292,8 +5295,8 @@ class PrescriptionDetailDialog(QDialog):
self.preview.setObjectName("PrescriptionPaperPreview")
self.preview.setOpenExternalLinks(False)
self.preview.setStyleSheet(
- "QTextBrowser#PrescriptionPaperPreview {"
- "background-color:#F7F7F7; border:1px solid #E4E4E5; padding:0;}"
+ clinical_stylesheet("QTextBrowser#PrescriptionPaperPreview {"
+ "background-color:#F7F7F7; border:1px solid #E4E4E5; padding:0;}")
)
self.preview.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
self.preview.setDocument(self.document)
@@ -5301,8 +5304,8 @@ class PrescriptionDetailDialog(QDialog):
self.user_preview.setObjectName("PrescriptionUserPaperPreview")
self.user_preview.setOpenExternalLinks(False)
self.user_preview.setStyleSheet(
- "QTextBrowser#PrescriptionUserPaperPreview {"
- "background-color:#F7F7F7; border:1px solid #E4E4E5; padding:0;}"
+ clinical_stylesheet("QTextBrowser#PrescriptionUserPaperPreview {"
+ "background-color:#F7F7F7; border:1px solid #E4E4E5; padding:0;}")
)
self.user_preview.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
self.user_preview.setDocument(self.user_document)
@@ -5320,8 +5323,8 @@ class PrescriptionDetailDialog(QDialog):
self.case_preview.setObjectName("CaseRecordPaperPreview")
self.case_preview.setOpenExternalLinks(False)
self.case_preview.setStyleSheet(
- "QTextBrowser#CaseRecordPaperPreview {"
- "background-color:#F7F7F7; border:1px solid #E4E4E5; padding:0;}"
+ clinical_stylesheet("QTextBrowser#CaseRecordPaperPreview {"
+ "background-color:#F7F7F7; border:1px solid #E4E4E5; padding:0;}")
)
self.case_preview.setDocument(self.case_document)
case_index = self.tabs.addTab(self.case_preview, "详细病历")
diff --git a/app/src/doctor_workstation/ui/dialogs/prescription_ai.py b/app/src/doctor_workstation/ui/dialogs/prescription_ai.py
index 16201b000..db3d98638 100644
--- a/app/src/doctor_workstation/ui/dialogs/prescription_ai.py
+++ b/app/src/doctor_workstation/ui/dialogs/prescription_ai.py
@@ -26,6 +26,7 @@ from PySide6.QtWidgets import (
QWidget,
)
+from ..design_system import clinical_stylesheet
from ..report_provenance import report_provenance_lines
from ..theme import apply_reading_rhythm
from ..widgets import (
@@ -169,10 +170,10 @@ def diagnosis_ai_task(prompt: str) -> str:
return "custom"
-PRESCRIPTION_AI_QSS = """
+PRESCRIPTION_AI_QSS = clinical_stylesheet("""
QDialog#PrescriptionAiDialog {
- color: #1A1C1F;
- background-color: #F7F7F7;
+ color: $ds_text;
+ background-color: $ds_canvas;
font-size: 13px;
}
@@ -182,7 +183,7 @@ QDialog#PrescriptionAiDialog QPushButton {
color: #1A1C1F;
background-color: #FFFFFF;
border: 1px solid #EDEDEE;
- border-radius: 7px;
+ border-radius: $ds_radius_control;
font-weight: 500;
}
QDialog#PrescriptionAiDialog QPushButton:hover {
@@ -224,7 +225,7 @@ QLabel#PrescriptionAiSubtitle {
QFrame#PrescriptionAiSnapshot {
background-color: #FFFFFF;
border: 1px solid #EDEDEE;
- border-radius: 10px;
+ border-radius: $ds_radius_panel;
}
QLabel#PrescriptionAiSnapshotLabel {
color: #1A1C1F;
@@ -232,20 +233,20 @@ QLabel#PrescriptionAiSnapshotLabel {
font-weight: 600;
}
QLabel#PrescriptionAiSnapshotBody {
- color: #1A1C1F;
- font-size: 13px;
+ color: $ds_text;
+ font-size: 14px;
line-height: 1.65;
}
QFrame#PrescriptionAiSummary {
- background-color: #F0F0F0;
+ background-color: $ds_accent_soft;
border: 0;
border-left: 3px solid #4F63D9;
- border-radius: 0 9px 9px 0;
+ border-radius: $ds_radius_control;
}
QFrame#PrescriptionAiCaution {
background-color: #FFF9EE;
border: 1px solid #F3DFB5;
- border-radius: 9px;
+ border-radius: $ds_radius_control;
}
QLabel#PrescriptionAiSectionTitle {
color: #1A1C1F;
@@ -253,17 +254,17 @@ QLabel#PrescriptionAiSectionTitle {
font-weight: 600;
}
QLabel#PrescriptionAiBody {
- color: #1A1C1F;
- font-size: 13px;
+ color: $ds_text;
+ font-size: 14px;
line-height: 1.75;
}
QTextBrowser#PrescriptionAiAnswer {
- color: #1A1C1F;
+ color: $ds_text;
background-color: #FFFFFF;
border: 1px solid #EDEDEE;
- border-radius: 10px;
- padding: 12px 14px;
- selection-color: #1A1C1F;
+ border-radius: $ds_radius_panel;
+ padding: 16px 18px;
+ selection-color: $ds_text;
selection-background-color: #EEF1FA;
}
QLabel#PrescriptionAiMuted {
@@ -279,7 +280,7 @@ QFrame#PrescriptionAiMeta {
QDialog#PrescriptionAiDialog QTabWidget::pane {
background-color: #FFFFFF;
border: 1px solid #EDEDEE;
- border-radius: 10px;
+ border-radius: $ds_radius_panel;
top: -1px;
}
QDialog#PrescriptionAiDialog QTabBar::tab {
@@ -309,7 +310,7 @@ QDialog#PrescriptionAiDialog QTextEdit {
color: #1A1C1F;
background-color: #FFFFFF;
border: 1px solid #EDEDEE;
- border-radius: 8px;
+ border-radius: $ds_radius_control;
padding: 10px;
selection-background-color: #EEF1FA;
}
@@ -330,10 +331,12 @@ QDialog#PrescriptionAiDialog QScrollBar::add-line:vertical,
QDialog#PrescriptionAiDialog QScrollBar::sub-line:vertical {
height: 0;
}
-"""
+QDialog#PrescriptionAiDialog QPushButton:focus { border: 1px solid $ds_focus; }
+QDialog#PrescriptionAiDialog QPushButton:disabled { color: $ds_disabled; background-color: $ds_disabled_surface; border-color: $ds_line; }
+""")
-_AI_ANSWER_DOCUMENT_CSS = (
- "body { color:#1A1C1F; font-size:14px; line-height:1.72; } "
+_AI_ANSWER_DOCUMENT_CSS = clinical_stylesheet(
+ "body { color:$ds_text; font-size:14px; line-height:1.72; } "
"h1 { color:#1A1C1F; font-size:20px; margin:14px 0 8px; line-height:1.4; } "
"h2 { color:#1A1C1F; font-size:17px; margin:14px 0 7px; line-height:1.42; } "
"h3,h4 { color:#1A1C1F; font-size:15px; margin:12px 0 6px; line-height:1.45; } "
@@ -801,7 +804,7 @@ class PrescriptionAiReportDialog(QDialog):
self.report_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
self.host = QWidget()
self.host_layout = QVBoxLayout(self.host)
- self.host_layout.setContentsMargins(4, 4, 12, 8)
+ self.host_layout.setContentsMargins(18, 14, 20, 16)
self.host_layout.setSpacing(12)
self.report_scroll.setWidget(self.host)
self.tabs.widget(0).layout().addWidget(self.report_scroll)
@@ -1455,7 +1458,7 @@ class PrescriptionAiReportDialog(QDialog):
label.setTextFormat(Qt.TextFormat.PlainText)
label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
label.setWordWrap(True)
- label.setStyleSheet("color: #555B68; font-size: 12px; padding: 10px 14px; background: #F7F8FC; border: 1px solid #E4E8F2; border-radius: 8px;")
+ label.setStyleSheet(clinical_stylesheet("color: $ds_muted; font-size: 12px; padding: 10px 14px; background: $ds_surface_alt; border: 1px solid $ds_line; border-radius: $ds_radius_control;"))
self.host_layout.addWidget(label)
def reject(self) -> None:
diff --git a/app/src/doctor_workstation/ui/filter_disclosure.py b/app/src/doctor_workstation/ui/filter_disclosure.py
index 0346c76ae..753fc4486 100644
--- a/app/src/doctor_workstation/ui/filter_disclosure.py
+++ b/app/src/doctor_workstation/ui/filter_disclosure.py
@@ -8,6 +8,7 @@ from PySide6.QtCore import QObject, QSize, Qt, Signal
from PySide6.QtWidgets import QApplication, QPushButton, QWidget
from . import icons
+from .design_system import PALETTE, clinical_stylesheet
class FilterDisclosure(QObject):
@@ -35,17 +36,17 @@ class FilterDisclosure(QObject):
self.button.setCursor(Qt.CursorShape.PointingHandCursor)
self.button.setFixedHeight(32)
self.button.setIconSize(QSize(14, 14))
- self.button.setStyleSheet("""
+ self.button.setStyleSheet(clinical_stylesheet("""
QPushButton#FilterDisclosureButton {
color: #1769E8; background: #FFFFFF; border: 1px solid #DBE5F2;
- border-radius: 6px; padding: 0 11px; min-height: 30px; max-height: 30px;
+ border-radius: $ds_radius_control; padding: 0 11px; min-height: 30px; max-height: 30px;
min-width: 92px; font-size: 13px; font-weight: 400;
}
- QPushButton#FilterDisclosureButton:hover { background: #F3F7FD; border-color: #ADC8F2; }
- QPushButton#FilterDisclosureButton:checked { background: #EAF2FF; border-color: #ADC8F2; }
- QPushButton#FilterDisclosureButton:focus { border-color: #1769E8; }
- QPushButton#FilterDisclosureButton:disabled { color: #8B97A8; border-color: #E3E9F1; }
- """)
+ QPushButton#FilterDisclosureButton:hover { background: $ds_canvas; border-color: $ds_line_strong; }
+ QPushButton#FilterDisclosureButton:checked { background: $ds_accent_soft; border-color: $ds_line_strong; }
+ QPushButton#FilterDisclosureButton:focus { border-color: $ds_focus; }
+ QPushButton#FilterDisclosureButton:disabled { color: $ds_disabled; border-color: $ds_line; }
+ """))
self.button.toggled.connect(self.set_expanded)
self._apply()
@@ -78,4 +79,4 @@ class FilterDisclosure(QObject):
self.button.setAccessibleName(label)
self.button.setAccessibleDescription("显示或收起检索条件和统计信息;收起保留当前筛选条件")
self.button.setToolTip("收起保留当前筛选条件" if self._expanded else "展开检索条件和统计信息,当前筛选条件保持不变")
- self.button.setIcon(icons.icon("chevron_up" if self._expanded else "chevron_down", "#1769E8", 14))
+ self.button.setIcon(icons.icon("chevron_up" if self._expanded else "chevron_down", PALETTE["accent"], 14))
diff --git a/app/src/doctor_workstation/ui/infinite_list.py b/app/src/doctor_workstation/ui/infinite_list.py
index 2b6082e36..19f9297e2 100644
--- a/app/src/doctor_workstation/ui/infinite_list.py
+++ b/app/src/doctor_workstation/ui/infinite_list.py
@@ -16,6 +16,7 @@ from PySide6.QtWidgets import (
QWidget,
)
+from .design_system import clinical_stylesheet
from .widgets import first_value, get_value, page_items, page_total, run_async
@@ -54,16 +55,16 @@ class InfiniteList(QWidget):
layout = QHBoxLayout(self)
layout.setContentsMargins(12, 0, 12, 0)
self.summary_label = QLabel("", self)
- self.summary_label.setStyleSheet(
+ self.summary_label.setStyleSheet(clinical_stylesheet(
"color: #5D6B80; font-size: 12px; background: transparent;"
- )
+ ))
layout.addWidget(self.summary_label)
layout.addStretch(1)
self.retry_button = QPushButton("加载失败,点击重试", self)
self.retry_button.setFlat(True)
- self.retry_button.setStyleSheet(
+ self.retry_button.setStyleSheet(clinical_stylesheet(
"color: #1769E8; font-size: 12px; padding: 0 4px; border: none; background: transparent; min-height: 20px; max-height: 20px; min-width: 0;"
- )
+ ))
self.retry_button.hide()
self.retry_button.clicked.connect(self.retry)
layout.addWidget(self.retry_button)
diff --git a/app/src/doctor_workstation/ui/login.py b/app/src/doctor_workstation/ui/login.py
index 24aa407cc..691cc9000 100644
--- a/app/src/doctor_workstation/ui/login.py
+++ b/app/src/doctor_workstation/ui/login.py
@@ -5,26 +5,21 @@ from __future__ import annotations
from contextlib import suppress
from typing import Any
-from PySide6.QtCore import QPoint, QPointF, QRectF, QSettings, Qt, QTimer, Signal
+from PySide6.QtCore import QEvent, QPoint, QPointF, QRectF, QSettings, Qt, QTimer, Signal
from PySide6.QtGui import (
- QBrush,
QColor,
QFont,
QIcon,
- QLinearGradient,
QPainter,
QPainterPath,
QPen,
QPixmap,
- QPolygonF,
- QRadialGradient,
QResizeEvent,
)
from PySide6.QtWidgets import (
QApplication,
QCheckBox,
QFrame,
- QGraphicsDropShadowEffect,
QHBoxLayout,
QLabel,
QLayout,
@@ -45,6 +40,7 @@ from doctor_workstation import __version__
from doctor_workstation.resources import app_icon_path, brand_lockup_path
from . import icons
+from .design_system import PALETTE, clinical_stylesheet
from .widgets import BusyOverlay, MessageBanner, friendly_error, invoke, run_async
@@ -127,7 +123,7 @@ def _round_pen(color: QColor | str, width: float) -> QPen:
class _BrandPanel(QWidget):
- """The quiet medical illustration and copy from the supplied login artwork."""
+ """A flat, readable introduction to the clinician's daily workflow."""
def __init__(self, parent: QWidget | None = None) -> None:
super().__init__(parent)
@@ -137,228 +133,76 @@ class _BrandPanel(QWidget):
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
self._brand_lockup = QPixmap(str(brand_lockup_path()))
- @staticmethod
- def _draw_cube(painter: QPainter, center: QPointF, size: float, kind: str) -> None:
- x, y = center.x(), center.y()
- top = QPolygonF(
- [
- QPointF(x, y - size * 0.58),
- QPointF(x + size * 0.48, y - size * 0.34),
- QPointF(x, y - size * 0.10),
- QPointF(x - size * 0.48, y - size * 0.34),
- ]
- )
- left = QPolygonF(
- [
- QPointF(x - size * 0.48, y - size * 0.34),
- QPointF(x, y - size * 0.10),
- QPointF(x, y + size * 0.48),
- QPointF(x - size * 0.48, y + size * 0.24),
- ]
- )
- right = QPolygonF(
- [
- QPointF(x, y - size * 0.10),
- QPointF(x + size * 0.48, y - size * 0.34),
- QPointF(x + size * 0.48, y + size * 0.24),
- QPointF(x, y + size * 0.48),
- ]
- )
- painter.setPen(QPen(QColor(185, 196, 247, 205), 1.2))
- painter.setBrush(QColor(235, 239, 255, 218))
- painter.drawPolygon(top)
- painter.setBrush(QColor(210, 218, 255, 205))
- painter.drawPolygon(left)
- painter.setBrush(QColor(224, 230, 255, 220))
- painter.drawPolygon(right)
- painter.setPen(_round_pen(QColor(137, 154, 248, 135), 2.2))
- if kind == "plus":
- painter.drawLine(
- QPointF(x - size * 0.12, y + size * 0.05),
- QPointF(x + size * 0.15, y - size * 0.02),
- )
- painter.drawLine(
- QPointF(x + size * 0.02, y - size * 0.13),
- QPointF(x + size * 0.02, y + size * 0.17),
- )
- else:
- shield = QPainterPath(QPointF(x, y - size * 0.16))
- shield.lineTo(x + size * 0.15, y - size * 0.08)
- shield.lineTo(x + size * 0.10, y + size * 0.17)
- shield.lineTo(x, y + size * 0.26)
- shield.lineTo(x - size * 0.10, y + size * 0.17)
- shield.lineTo(x - size * 0.15, y - size * 0.08)
- shield.closeSubpath()
- painter.drawPath(shield)
-
- def _draw_illustration(
- self, painter: QPainter, width: float, height: float
- ) -> None:
- ox = max(250.0, width - 500.0)
- oy = max(365.0, height - 500.0)
-
- glow = QRadialGradient(QPointF(width - 170, oy + 230), 280)
- glow.setColorAt(0.0, QColor(102, 120, 255, 62))
- glow.setColorAt(1.0, QColor(102, 120, 255, 0))
- painter.setPen(Qt.PenStyle.NoPen)
- painter.setBrush(glow)
- painter.drawEllipse(QPointF(width - 170, oy + 230), 280, 280)
-
- painter.setPen(QPen(QColor(166, 180, 241, 78), 1))
- for offset in (0, 72, 144):
- painter.drawLine(
- QPointF(ox - 80, oy + 280 + offset),
- QPointF(width + 20, oy + 170 + offset),
- )
- painter.drawLine(QPointF(ox + 10, oy + 400), QPointF(ox + 10, oy + 80))
- painter.drawLine(QPointF(ox + 170, oy + 430), QPointF(ox + 170, oy + 35))
-
- base = QRectF(ox + 80, oy + 365, 430, 88)
- base_gradient = QLinearGradient(base.topLeft(), base.bottomRight())
- base_gradient.setColorAt(0.0, QColor(246, 248, 255, 228))
- base_gradient.setColorAt(1.0, QColor(186, 199, 255, 184))
- painter.setBrush(base_gradient)
- painter.setPen(QPen(QColor(166, 181, 248, 158), 1))
- painter.drawEllipse(base)
- painter.setBrush(QColor(249, 250, 255, 225))
- painter.drawEllipse(QRectF(base.x() + 42, base.y() - 12, base.width() - 84, 70))
-
- painter.save()
- painter.translate(35, 40)
- screen = QPolygonF(
- [
- QPointF(ox + 130, oy + 60),
- QPointF(ox + 435, oy + 100),
- QPointF(ox + 435, oy + 365),
- QPointF(ox + 130, oy + 310),
- ]
- )
- painter.setBrush(QColor(218, 225, 255, 205))
- painter.setPen(QPen(QColor(145, 163, 242, 170), 1.3))
- painter.drawPolygon(screen)
- inner = QPolygonF(
- [
- QPointF(ox + 141, oy + 80),
- QPointF(ox + 425, oy + 117),
- QPointF(ox + 425, oy + 345),
- QPointF(ox + 141, oy + 295),
- ]
- )
- painter.setBrush(QColor(255, 255, 255, 225))
- painter.drawPolygon(inner)
-
- painter.setPen(Qt.PenStyle.NoPen)
- painter.setBrush(QColor(174, 189, 252, 180))
- painter.drawRoundedRect(QRectF(ox + 148, oy + 89, 270, 15), 7, 7)
- for dot_x in (156, 173, 190):
- painter.setBrush(QColor(255, 255, 255, 200))
- painter.drawEllipse(QPointF(ox + dot_x, oy + 96.5), 3.5, 3.5)
-
- cards = (
- QRectF(ox + 150, oy + 135, 82, 80),
- QRectF(ox + 241, oy + 142, 72, 73),
- QRectF(ox + 322, oy + 151, 95, 72),
- QRectF(ox + 151, oy + 232, 264, 50),
- QRectF(ox + 151, oy + 291, 264, 42),
- )
- painter.setPen(QPen(QColor(188, 199, 246, 160), 1))
- painter.setBrush(QColor(249, 250, 255, 228))
- for card in cards:
- painter.drawRoundedRect(card, 7, 7)
- painter.setPen(_round_pen(QColor(117, 137, 236, 165), 4))
- for idx, bar_height in enumerate((20, 36, 51)):
- x = ox + 164 + idx * 17
- painter.drawLine(QPointF(x, oy + 200), QPointF(x, oy + 200 - bar_height))
- painter.setBrush(QColor(112, 132, 235, 160))
- painter.setPen(Qt.PenStyle.NoPen)
- painter.drawEllipse(QPointF(ox + 277, oy + 167), 10, 10)
- painter.drawRoundedRect(QRectF(ox + 259, oy + 180, 36, 20), 10, 10)
- painter.setPen(_round_pen(QColor(137, 153, 235, 150), 5))
- for y, length in ((170, 54), (186, 42), (249, 89), (307, 72)):
- painter.drawLine(
- QPointF(ox + 340, oy + y), QPointF(ox + 340 + length, oy + y + 5)
- )
-
- self._draw_cube(painter, QPointF(ox + 352, oy - 25), 76, "plus")
- self._draw_cube(painter, QPointF(ox - 8, oy + 210), 76, "shield")
- painter.restore()
-
def paintEvent(self, event: Any) -> None: # noqa: N802 - Qt API
del event
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
- painter.setRenderHint(QPainter.RenderHint.TextAntialiasing)
- bounds = QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5)
- background = QLinearGradient(bounds.topLeft(), bounds.bottomRight())
- background.setColorAt(0.0, QColor("#FFFFFF"))
- background.setColorAt(0.7, QColor("#FFFFFF"))
- background.setColorAt(1.0, QColor("#F7F7F7"))
- painter.setBrush(background)
- painter.setPen(QPen(QColor("#EDEDEE"), 1))
- painter.drawRoundedRect(bounds, 24, 24)
-
- width, height = float(self.width()), float(self.height())
- self._draw_illustration(painter, width, height)
-
- left = 64.0 if width >= 620 else 38.0
- if not self._brand_lockup.isNull():
- logo_width = 180.0
- logo_height = logo_width * (
- self._brand_lockup.height() / self._brand_lockup.width()
- )
- painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform)
- painter.drawPixmap(
- QRectF(left, 24, logo_width, logo_height),
- self._brand_lockup,
- QRectF(self._brand_lockup.rect()),
- )
-
- tag_rect = QRectF(left, 238, 119, 40)
+ bounds = QRectF(self.rect()).adjusted(1, 1, -1, -1)
painter.setPen(Qt.PenStyle.NoPen)
- painter.setBrush(QColor("#EEF1FA"))
- painter.drawRoundedRect(tag_rect, 11, 11)
- painter.setFont(_font(17, QFont.Weight.Medium))
- painter.setPen(QColor("#4F63D9"))
- painter.drawText(tag_rect, Qt.AlignmentFlag.AlignCenter, "医生工作站")
+ painter.setBrush(QColor(PALETTE["sidebar"]))
+ painter.drawRoundedRect(bounds, 20, 20)
+ left = 36.0
+ width = max(240.0, self.width() - 72.0)
+ if not self._brand_lockup.isNull():
+ brand = self._brand_lockup.scaled(
+ 226, 58, Qt.AspectRatioMode.KeepAspectRatio,
+ Qt.TransformationMode.SmoothTransformation,
+ )
+ painter.drawPixmap(QPointF(left, 36), brand)
+ else:
+ painter.setFont(_font(22, QFont.Weight.DemiBold))
+ painter.setPen(QColor(PALETTE["heading"]))
+ painter.drawText(QPointF(left, 70), "甄养堂 · 医生工作站")
- copy_left = left + 4
- painter.setFont(_font(48, QFont.Weight.Medium))
- painter.setPen(QColor("#1A1C1F"))
- painter.drawText(QPointF(copy_left, 354), "把诊间工作,")
- painter.drawText(QPointF(copy_left, 424), "留在一个")
- prefix_width = painter.fontMetrics().horizontalAdvance("留在一个")
- highlight = QLinearGradient(
- copy_left + prefix_width,
- 0,
- copy_left + prefix_width + 264,
- 0,
- )
- highlight.setColorAt(0.0, QColor("#4F63D9"))
- highlight.setColorAt(1.0, QColor("#4F63D9"))
- painter.setPen(QPen(QBrush(highlight), 1))
- painter.drawText(QPointF(copy_left + prefix_width, 424), "安静的界面里")
- suffix_x = (
- copy_left
- + prefix_width
- + painter.fontMetrics().horizontalAdvance("安静的界面里")
- )
- painter.setPen(QColor("#1A1C1F"))
- painter.drawText(QPointF(suffix_x, 424), "。")
+ heading_y = max(158.0, min(218.0, self.height() * .27))
+ painter.setPen(QColor(PALETTE["muted"]))
+ painter.setFont(_font(13, QFont.Weight.Medium))
+ painter.drawText(QPointF(left, heading_y - 36), "医 生 工 作 台")
+ painter.setPen(QColor(PALETTE["heading"]))
+ painter.setFont(_font(30, QFont.Weight.DemiBold))
+ painter.drawText(QPointF(left, heading_y), "让诊疗有序,")
+ painter.drawText(QPointF(left, heading_y + 44), "让沟通更专注。")
+ painter.setFont(_font(14))
+ painter.setPen(QColor(PALETTE["muted"]))
+ painter.drawText(QPointF(left, heading_y + 82), "从接诊、病历到处方,在一个工作台完成。")
- body_left = left + 6
- painter.setFont(_font(20))
- painter.setPen(QColor("#606163"))
- painter.drawText(
- QPointF(body_left, 492), "接诊、问诊、患者与处方信息统一呈现,"
- )
- painter.drawText(QPointF(body_left, 525), "帮助医生专注于每一次沟通。")
+ row_y = heading_y + 122
+ for index, (title, detail) in enumerate((
+ ("今日接诊", "快速找到待接诊患者与预约安排"),
+ ("诊疗记录", "病历、随访与面诊资料集中查看"),
+ ("处方协作", "开方与审核流程清晰衔接"),
+ ), start=1):
+ row = QRectF(left, row_y, width, 66)
+ painter.setPen(Qt.PenStyle.NoPen)
+ painter.setBrush(QColor(PALETTE["surface"]))
+ painter.drawRoundedRect(row, 12, 12)
+ painter.setFont(_font(13, QFont.Weight.DemiBold))
+ painter.setPen(QColor(PALETTE["accent"]))
+ painter.drawText(QRectF(left + 16, row_y, 28, 66), Qt.AlignmentFlag.AlignCenter, f"0{index}")
+ painter.setFont(_font(15, QFont.Weight.Medium))
+ painter.setPen(QColor(PALETTE["heading"]))
+ painter.drawText(QPointF(left + 58, row_y + 27), title)
+ painter.setFont(_font(12))
+ painter.setPen(QColor(PALETTE["muted"]))
+ painter.drawText(QPointF(left + 58, row_y + 47), detail)
+ row_y += 78
+ if self.height() > row_y + 50:
+ painter.setFont(_font(12))
+ painter.setPen(QColor(PALETTE["muted"]))
+ painter.drawText(QPointF(left, self.height() - 28), "仅供获授权的医疗人员使用")
+ painter.end()
- painter.setFont(_font(16))
- painter.setPen(QColor("#6A6B6D"))
- painter.drawText(
- QPointF(body_left, height - 85), "本工作站仅供获授权的医疗人员使用"
- )
- painter.drawText(QPointF(body_left, height - 59), "请勿在公共设备保存账号信息")
+
+class _PasswordField(QFrame):
+ """Keep the grouped password control visibly focused for keyboard users."""
+
+ def eventFilter(self, watched: Any, event: QEvent) -> bool: # noqa: N802
+ if event.type() in (QEvent.Type.FocusIn, QEvent.Type.FocusOut):
+ self.setProperty("focused", event.type() == QEvent.Type.FocusIn)
+ self.style().unpolish(self)
+ self.style().polish(self)
+ self.update()
+ return super().eventFilter(watched, event)
class _RevealButton(QToolButton):
@@ -392,8 +236,8 @@ class _ServerButton(QPushButton):
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
rect = QRectF(self.rect()).adjusted(0.75, 0.75, -0.75, -0.75)
- painter.setBrush(QColor("#FFFFFF") if self.underMouse() else QColor("#FFFFFF"))
- painter.setPen(QPen(QColor("#E4E4E5"), 1.5))
+ painter.setBrush(QColor(PALETTE["accent_soft"] if self.underMouse() else PALETTE["surface"]))
+ painter.setPen(QPen(QColor(PALETTE["focus"] if self.hasFocus() else PALETTE["line_strong"]), 1))
painter.drawRoundedRect(rect, 12, 12)
color = QColor("#1A1C1F" if self.isEnabled() else "#8E8F90")
painter.setPen(_round_pen("#6A6B6D", 1.8))
@@ -536,7 +380,7 @@ class LoginWindow(QMainWindow):
border: 1px solid #E4E4E5;
border-radius: 12px;
}
- QFrame#PasswordField:focus-within { border-color: #8B9AD9; }
+ QFrame#PasswordField[focused="true"] { border-color: #8B9AD9; }
QFrame#LoginCard QCheckBox {
color: #606163;
spacing: 13px;
@@ -606,6 +450,9 @@ class LoginWindow(QMainWindow):
self.login_root.addWidget(self.brand_panel, 60)
self.login_root.addWidget(self._build_login_area(), 40)
self._restore_settings()
+ for widget in (canvas, *canvas.findChildren(QWidget)):
+ if widget.styleSheet():
+ widget.setStyleSheet(clinical_stylesheet(widget.styleSheet()))
def resizeEvent(self, event: QResizeEvent) -> None: # noqa: N802 - Qt API
"""Preserve the reference composition while remaining usable on small screens."""
@@ -625,18 +472,15 @@ class LoginWindow(QMainWindow):
# Keep the form fully visible when the 60/40 desktop split would
# otherwise crop its fixed-width card. Small windows focus on login.
self.brand_panel.setVisible(width >= 1120)
+ compact_height = event.size().height() < 720
+ self.card.setMinimumHeight(580 if compact_height else 620)
self.login_area_layout.setContentsMargins(
- 0, min(104, max(24, (event.size().height() - 694) // 2)), 0, 12
+ 0, 12 if compact_height else min(104, max(24, (event.size().height() - 694) // 2)), 0, 12
)
super().resizeEvent(event)
def _build_brand_panel(self) -> QWidget:
panel = _BrandPanel()
- shadow = QGraphicsDropShadowEffect(panel)
- shadow.setBlurRadius(32)
- shadow.setOffset(0, 10)
- shadow.setColor(QColor(67, 82, 154, 18))
- panel.setGraphicsEffect(shadow)
return panel
def _build_login_area(self) -> QWidget:
@@ -660,11 +504,6 @@ class LoginWindow(QMainWindow):
self.card.setFixedWidth(480)
self.card.setMinimumHeight(620)
self.card.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Minimum)
- card_shadow = QGraphicsDropShadowEffect(self.card)
- card_shadow.setBlurRadius(38)
- card_shadow.setOffset(0, 16)
- card_shadow.setColor(QColor(59, 77, 139, 24))
- self.card.setGraphicsEffect(card_shadow)
card_layout = QVBoxLayout(self.card)
card_layout.setSizeConstraint(QLayout.SizeConstraint.SetDefaultConstraint)
card_layout.setContentsMargins(47, 42, 47, 26)
@@ -673,13 +512,13 @@ class LoginWindow(QMainWindow):
title = QLabel("欢迎回来")
title.setObjectName("LoginTitle")
- title.setStyleSheet("color:#1A1C1F; font-size:30px; font-weight:500;")
+ title.setStyleSheet("color:#1A1C1F; font-size:26px; font-weight:600;")
title.setContentsMargins(1, -3, 0, 3)
title.setFixedHeight(46)
card_layout.addWidget(title)
subtitle = QLabel("使用医生账号登录工作站")
subtitle.setProperty("role", "muted")
- subtitle.setStyleSheet("color:#606163; font-size:18px;")
+ subtitle.setStyleSheet("color:#606163; font-size:15px;")
subtitle.setContentsMargins(1, 8, 0, 0)
subtitle.setFixedHeight(27)
card_layout.addWidget(subtitle)
@@ -710,7 +549,7 @@ class LoginWindow(QMainWindow):
password_label.setFixedHeight(24)
card_layout.addWidget(password_label)
card_layout.addSpacing(11)
- password_field = QFrame()
+ password_field = _PasswordField()
password_field.setObjectName("PasswordField")
password_field.setFixedHeight(54)
password_row = QHBoxLayout(password_field)
@@ -721,6 +560,7 @@ class LoginWindow(QMainWindow):
self.password_edit.setEchoMode(QLineEdit.EchoMode.Password)
self.password_edit.setPlaceholderText("请输入密码")
self.password_edit.setAccessibleName("登录密码")
+ self.password_edit.installEventFilter(password_field)
self.password_edit.setTextMargins(0, -2, 0, 2)
self.password_edit.returnPressed.connect(self.submit)
password_row.addWidget(self.password_edit, 1)
@@ -730,6 +570,7 @@ class LoginWindow(QMainWindow):
self.reveal_button.setCheckable(True)
self.reveal_button.setFixedSize(87, 52)
self.reveal_button.setToolTip("显示或隐藏密码")
+ self.reveal_button.installEventFilter(password_field)
self.reveal_button.toggled.connect(self._toggle_password)
password_row.addWidget(self.reveal_button)
card_layout.addWidget(password_field)
@@ -758,11 +599,6 @@ class LoginWindow(QMainWindow):
self.login_button = QPushButton("登录工作站")
self.login_button.setProperty("variant", "primary")
self.login_button.setFixedHeight(58)
- login_shadow = QGraphicsDropShadowEffect(self.login_button)
- login_shadow.setBlurRadius(20)
- login_shadow.setOffset(0, 7)
- login_shadow.setColor(QColor(82, 101, 246, 45))
- self.login_button.setGraphicsEffect(login_shadow)
self.login_button.clicked.connect(self.submit)
card_layout.addWidget(self.login_button)
self.debug_settings_section = QWidget()
diff --git a/app/src/doctor_workstation/ui/motion.py b/app/src/doctor_workstation/ui/motion.py
index 6236d8b14..9a4e41ce6 100644
--- a/app/src/doctor_workstation/ui/motion.py
+++ b/app/src/doctor_workstation/ui/motion.py
@@ -37,8 +37,10 @@ from PySide6.QtCore import (
QTimer,
)
from PySide6.QtWidgets import (
+ QAbstractItemView,
QAbstractScrollArea,
QGraphicsOpacityEffect,
+ QPlainTextEdit,
QStackedWidget,
QWidget,
)
@@ -75,15 +77,35 @@ def reduced_motion() -> bool:
return os.getenv("QT_QPA_PLATFORM", "").strip().lower() == "offscreen"
-def _own(target: QWidget, key: str, animation: QPropertyAnimation) -> QPropertyAnimation:
- """Park an animation on its target so Python does not collect it early."""
+def _stop(target: QObject, key: str) -> None:
+ """Retire a replaced animation without firing its completion callback."""
- running: dict[str, QPropertyAnimation] = getattr(target, "_doctor_motion", None) or {}
- previous = running.get(key)
+ running = getattr(target, "_doctor_motion", {})
+ previous = running.pop(key, None)
if previous is not None:
previous.stop()
+ previous.setParent(None)
+ previous.deleteLater()
+
+
+def _own(target: QObject, key: str, animation: QPropertyAnimation) -> QPropertyAnimation:
+ """Park an animation on its target so Python does not collect it early."""
+
+ _stop(target, key)
+ running: dict[str, QPropertyAnimation] = getattr(target, "_doctor_motion", {})
running[key] = animation
target._doctor_motion = running
+
+ def release() -> None:
+ if running.get(key) is animation:
+ running.pop(key)
+ # A callback can hold the last Python reference to the owner. Detach
+ # first so releasing that callback during deferred deletion cannot
+ # recursively delete this animation through its former parent.
+ animation.setParent(None)
+ animation.deleteLater()
+
+ animation.finished.connect(release)
return animation
@@ -107,7 +129,10 @@ def animate(
from inside its own ``finished`` emission.
"""
+ animation_owner = owner if owner is not None else target
+ animation_key = key or prop.decode()
if reduced_motion():
+ _stop(animation_owner, animation_key)
target.setProperty(prop.decode() if isinstance(prop, bytes) else prop, end)
if on_finished is not None:
on_finished()
@@ -117,18 +142,24 @@ def animate(
animation.setEasingCurve(easing)
animation.setStartValue(start)
animation.setEndValue(end)
+ _own(animation_owner, animation_key, animation)
if on_finished is not None:
animation.finished.connect(on_finished)
- _own(owner if owner is not None else target, key or prop.decode(), animation)
animation.start(QAbstractAnimation.DeletionPolicy.KeepWhenStopped)
return animation
-def _opacity_effect(widget: QWidget) -> QGraphicsOpacityEffect:
+def _opacity_effect(widget: QWidget) -> QGraphicsOpacityEffect | None:
effect = widget.graphicsEffect()
- if not isinstance(effect, QGraphicsOpacityEffect):
+ # Do not replace a caller's shadow or opacity effect: Qt deletes it when
+ # another effect is attached. Only effects created here belong to a fade.
+ if effect is not None and effect is not getattr(widget, "_doctor_opacity_effect", None):
+ return None
+ if effect is None:
effect = QGraphicsOpacityEffect(widget)
+ effect.setOpacity(1.0)
widget.setGraphicsEffect(effect)
+ widget._doctor_opacity_effect = effect
effect.setEnabled(True)
return effect
@@ -146,9 +177,17 @@ def _drop_effect(widget: QWidget) -> None:
signal that is still being delivered.
"""
+ effect = getattr(widget, "_doctor_opacity_effect", None)
+ revision = getattr(widget, "_doctor_fade_revision", 0)
+
def detach() -> None:
try:
- if isinstance(widget.graphicsEffect(), QGraphicsOpacityEffect):
+ if (
+ effect is not None
+ and widget.graphicsEffect() is effect
+ and getattr(widget, "_doctor_fade_revision", 0) == revision
+ ):
+ widget._doctor_opacity_effect = None
widget.setGraphicsEffect(None)
except RuntimeError: # the widget went away while the fade was running
pass
@@ -156,6 +195,13 @@ def _drop_effect(widget: QWidget) -> None:
QTimer.singleShot(0, detach)
+def _restart_fade(widget: QWidget) -> None:
+ _stop(widget, "fade")
+ # A completed fade may still have deferred cleanup waiting in the queue.
+ # It must not remove an effect now being used by a subsequent fade.
+ widget._doctor_fade_revision = getattr(widget, "_doctor_fade_revision", 0) + 1
+
+
def fade_in(
widget: QWidget,
*,
@@ -165,10 +211,20 @@ def fade_in(
) -> None:
"""Fade a widget up to full opacity, showing it first if needed."""
+ existing = widget.graphicsEffect()
+ if existing is not None and existing is getattr(widget, "_doctor_opacity_effect", None):
+ start = float(existing.opacity())
+ _restart_fade(widget)
if reduced_motion():
+ if existing is not None and existing is getattr(widget, "_doctor_opacity_effect", None):
+ existing.setOpacity(1.0)
+ _drop_effect(widget)
widget.show()
return
effect = _opacity_effect(widget)
+ if effect is None:
+ widget.show()
+ return
effect.setOpacity(start)
widget.show()
animate(
@@ -193,9 +249,11 @@ def fade_out(
) -> None:
"""Fade a widget down, optionally hiding it when the fade completes."""
+ _restart_fade(widget)
if reduced_motion():
if hide:
widget.hide()
+ _drop_effect(widget)
if on_finished is not None:
on_finished()
return
@@ -208,6 +266,9 @@ def fade_out(
if on_finished is not None:
on_finished()
+ if effect is None:
+ done()
+ return
animate(
effect,
b"opacity",
@@ -229,13 +290,17 @@ def enter(widget: QWidget, *, duration: int = BASE, rise: int = RISE) -> None:
the user has to wait out.
"""
+ previous = getattr(widget, "_doctor_motion", {}).get("enter")
+ origin = previous.endValue() if previous is not None else widget.pos()
if reduced_motion():
- widget.show()
+ _stop(widget, "enter")
+ widget.move(origin)
+ fade_in(widget, duration=duration)
return
fade_in(widget, duration=duration)
if rise:
- origin = widget.pos()
- widget.move(origin + QPoint(0, rise))
+ if previous is None:
+ widget.move(origin + QPoint(0, rise))
animate(
widget,
b"pos",
@@ -260,7 +325,7 @@ def switch_stack(stack: QStackedWidget, index: int, *, rise: int = RISE) -> None
return
stack.setCurrentIndex(index)
page = stack.currentWidget()
- if page is None or reduced_motion():
+ if page is None:
return
enter(page, rise=rise)
@@ -274,50 +339,121 @@ SCROLL_STEP = 120
SCROLL_MS = 190
+class _ScrollAnimation(QPropertyAnimation):
+ """Identify animation writes so direct scrollbar changes can interrupt us."""
+
+ writing = False
+
+ def updateCurrentValue(self, value: Any) -> None: # noqa: N802 - Qt API
+ self.writing = True
+ try:
+ super().updateCurrentValue(value)
+ finally:
+ self.writing = False
+
+
class _SmoothScroller(QObject):
"""Animate a scroll area's wheel movement instead of jumping to it."""
+ _INTERRUPT_EVENTS = frozenset(
+ {
+ QEvent.Type.KeyPress,
+ QEvent.Type.MouseButtonPress,
+ QEvent.Type.TouchBegin,
+ QEvent.Type.Hide,
+ }
+ )
+
def __init__(self, area: QAbstractScrollArea, *, orientation: Qt.Orientation) -> None:
super().__init__(area)
+ self._area = area
+ self._orientation = orientation
self._bar = (
area.verticalScrollBar()
if orientation is Qt.Orientation.Vertical
else area.horizontalScrollBar()
)
self._target = self._bar.value()
- self._animation = QPropertyAnimation(self._bar, b"value", self)
+ self._animation = _ScrollAnimation(self._bar, b"value", self)
self._animation.setEasingCurve(EASE_ENTER)
self._animation.setDuration(SCROLL_MS)
- # Keyboard, programmatic and drag movements must not be fought over: when
- # nothing is animating, the wheel target follows wherever the bar went.
self._bar.valueChanged.connect(self._sync_target)
+ self._bar.sliderPressed.connect(self._cancel)
+ self._bar.actionTriggered.connect(self._cancel)
+ self._bar.rangeChanged.connect(self._cancel)
+ self._bar.installEventFilter(self)
+ area.installEventFilter(self)
area.viewport().installEventFilter(self)
+ def _cancel(self, *_: Any) -> None:
+ self._animation.stop()
+ self._target = self._bar.value()
+
def _sync_target(self, value: int) -> None:
- if self._animation.state() != QAbstractAnimation.State.Running:
+ if not self._animation.writing:
+ self._animation.stop()
self._target = value
+ def _uses_pixels(self) -> bool:
+ if isinstance(self._area, QAbstractItemView):
+ mode = (
+ self._area.verticalScrollMode()
+ if self._orientation == Qt.Orientation.Vertical
+ else self._area.horizontalScrollMode()
+ )
+ return mode == QAbstractItemView.ScrollMode.ScrollPerPixel
+ # QPlainTextEdit's vertical scrollbar counts text blocks, not pixels.
+ return not (
+ isinstance(self._area, QPlainTextEdit) and self._orientation == Qt.Orientation.Vertical
+ )
+
def eventFilter(self, watched: QObject, event: QEvent) -> bool: # noqa: N802 - Qt API
- del watched
- if event.type() is not QEvent.Type.Wheel or reduced_motion():
+ event_type = event.type()
+ if event_type in self._INTERRUPT_EVENTS:
+ self._cancel()
return False
- delta = event.angleDelta().y() or event.angleDelta().x()
- if not delta or event.modifiers() & Qt.KeyboardModifier.ControlModifier:
+ if event_type != QEvent.Type.Wheel:
return False
+ horizontal = self._orientation == Qt.Orientation.Horizontal
+ shifted = bool(event.modifiers() & Qt.KeyboardModifier.ShiftModifier)
+ delta = event.angleDelta().x() if horizontal else event.angleDelta().y()
+ if horizontal and shifted and not delta:
+ delta = event.angleDelta().y()
+ if (
+ watched is not self._area.viewport()
+ or reduced_motion()
+ or not self._uses_pixels()
+ or not event.pixelDelta().isNull()
+ or event.phase() != Qt.ScrollPhase.NoScrollPhase
+ or event.modifiers()
+ & (Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.AltModifier)
+ or (shifted and not horizontal)
+ or not delta
+ ):
+ # Trackpads already provide continuous motion and native momentum.
+ # Mixing another easing curve into it adds lag and fights gestures.
+ self._cancel()
+ return False
+
lower, upper = self._bar.minimum(), self._bar.maximum()
# Re-clamp first: the range can shrink underneath a running animation
# when the content behind it reloads, which would otherwise leave the
# pending target past the end of the new content.
self._target = max(lower, min(upper, self._target))
- target = self._target - round(delta / 120.0 * SCROLL_STEP)
+ current = self._bar.value()
+ step = -round(delta / 120.0 * SCROLL_STEP)
+ # Reverse immediately from the visible position, not the end of a
+ # backlog of wheel notches still travelling in the opposite direction.
+ origin = current if (self._target - current) * step < 0 else self._target
+ target = origin + step
target = max(lower, min(upper, target))
# At either end, hand the wheel back so an enclosing scroll area still
# gets it - swallowing it there is what makes nested panes feel stuck.
if target == self._target:
- return False
+ return target != current
self._target = target
self._animation.stop()
- self._animation.setStartValue(self._bar.value())
+ self._animation.setStartValue(current)
self._animation.setEndValue(target)
self._animation.start()
return True
@@ -328,7 +464,7 @@ def install_smooth_scroll(
*,
orientation: Qt.Orientation = Qt.Orientation.Vertical,
) -> None:
- """Give a scroll area eased wheel scrolling."""
+ """Ease discrete wheels on pixel-based areas; preserve native gestures."""
if getattr(area, "_doctor_smooth_scroll", None) is not None:
return
diff --git a/app/src/doctor_workstation/ui/pages/patients.py b/app/src/doctor_workstation/ui/pages/patients.py
index a83e2893f..d56f34338 100644
--- a/app/src/doctor_workstation/ui/pages/patients.py
+++ b/app/src/doctor_workstation/ui/pages/patients.py
@@ -50,6 +50,7 @@ from ...core.appointment_modes import (
)
from .. import icons
from ..appointment_drawer import AppointmentDrawer
+from ..design_system import PALETTE, clinical_stylesheet
from ..dialogs import DiagnosisDialog, present_ai_consult, present_order_detail
from ..dialogs.ai_consult import can_open_ai_consult
from ..dialogs.prescription import PrescriptionOrderListDialog
@@ -110,97 +111,97 @@ FULFILLMENT_TEXT = {
}
_SEMANTIC_COLORS = {
- "primary": "#4F63D9",
- "success": "#287B65",
- "warning": "#A9691D",
- "danger": "#BE4B58",
- "info": "#4F63D9",
- "muted": "#606163",
+ "primary": PALETTE["accent"],
+ "success": PALETTE["success"],
+ "warning": PALETTE["warning"],
+ "danger": PALETTE["danger"],
+ "info": PALETTE["accent"],
+ "muted": PALETTE["muted"],
}
-PATIENTS_LIGHT_QSS = """
+PATIENTS_LIGHT_QSS = clinical_stylesheet("""
#PatientsPage QWidget#PageHeader QLabel[role="pageTitle"] {
- color: #1A1C1F;
+ color: $ds_heading;
font-size: 20px;
font-weight: 600;
}
#PatientsPage QWidget#PageHeader QLabel[role="muted"] {
- color: #606163;
+ color: $ds_muted;
font-size: 13px;
}
#PatientsPage QPushButton[patientSearchAction="true"] {
min-height: 32px;
max-height: 32px;
- color: #FFFFFF;
- background-color: #4F63D9;
- border: 1px solid #4F63D9;
+ color: $ds_surface;
+ background-color: $ds_accent;
+ border: 1px solid $ds_accent;
border-radius: 7px;
font-weight: 500;
}
#PatientsPage QPushButton[patientSearchAction="true"]:hover {
- background-color: #4156C4;
- border-color: #4156C4;
+ background-color: $ds_accent_hover;
+ border-color: $ds_accent_hover;
}
#PatientsPage QFrame[patientListFilter="true"] {
min-height: 88px;
max-height: 88px;
- background-color: #FFFFFF;
- border: 1px solid #EDEDEE;
+ background-color: $ds_surface;
+ border: 1px solid $ds_line;
border-radius: 12px;
}
#PatientsPage QFrame[patientListFilter="true"] QLineEdit,
#PatientsPage QFrame[patientListFilter="true"] QDateEdit {
min-height: 32px;
max-height: 32px;
- background-color: #FFFFFF;
- border: 1px solid #EDEDEE;
+ background-color: $ds_surface;
+ border: 1px solid $ds_line;
border-radius: 7px; font-size: 14px;
}
#PatientsPage QFrame[patientListFilter="true"] QPushButton {
min-height: 32px; max-height: 32px;
}
#PatientsPage QFrame[patientListFilter="true"] QDateEdit:disabled {
- color: #8E8F90; background-color: #F7F7F7;
+ color: $ds_disabled; background-color: $ds_surface_alt;
}
#PatientsPage QPushButton[patientStatusChip="true"] {
min-height: 32px;
max-height: 32px;
padding: 0 10px;
- color: #606163;
- background-color: #F7F7F7;
+ color: $ds_muted;
+ background-color: $ds_surface_alt;
border: 1px solid transparent;
border-radius: 5px;
}
#PatientsPage QPushButton[patientStatusChip="true"]:hover {
- color: #4F63D9;
- background-color: #EEF1FA;
+ color: $ds_accent;
+ background-color: $ds_accent_soft;
}
#PatientsPage QPushButton[patientStatusChip="true"]:checked {
- color: #4F63D9;
- background-color: #EEF1FA;
- border: 1px solid #8B9AD9;
+ color: $ds_accent;
+ background-color: $ds_accent_soft;
+ border: 1px solid $ds_focus;
}
#PatientsPage QPushButton[patientQuickDate="true"] {
min-height: 32px;
max-height: 32px;
padding: 0 9px;
- color: #1A1C1F;
+ color: $ds_heading;
background-color: transparent;
border: 1px solid transparent;
border-radius: 7px;
}
#PatientsPage QPushButton[patientQuickDate="true"]:hover {
- color: #4F63D9;
- background-color: #EEF1FA;
+ color: $ds_accent;
+ background-color: $ds_accent_soft;
}
#PatientsPage QPushButton[patientQuickDate="true"]:checked {
- color: #4F63D9;
- background-color: #EEF1FA;
- border-color: #8B9AD9;
+ color: $ds_accent;
+ background-color: $ds_accent_soft;
+ border-color: $ds_focus;
}
#PatientsPage QTabWidget#PatientWorkspaceTabs::pane {
border: 0;
- border-top: 1px solid #EDEDEE;
+ border-top: 1px solid $ds_line;
background-color: transparent;
}
#PatientsPage QTabWidget#PatientWorkspaceTabs QTabBar::tab {
@@ -208,124 +209,124 @@ PATIENTS_LIGHT_QSS = """
min-height: 34px;
padding: 0 6px;
margin-right: 8px;
- color: #606163;
+ color: $ds_muted;
background: transparent;
border: 0;
border-bottom: 2px solid transparent;
font-weight: 400;
}
#PatientsPage QTabWidget#PatientWorkspaceTabs QTabBar::tab:selected {
- color: #4F63D9;
- border-bottom-color: #4F63D9;
+ color: $ds_accent;
+ border-bottom-color: $ds_accent;
font-weight: 500;
}
#PatientsPage QPushButton[summaryCard="true"] {
min-height: 42px;
max-height: 42px;
padding: 0 11px;
- color: #1A1C1F;
- background-color: #F7F7F7;
- border: 1px solid #EDEDEE;
+ color: $ds_heading;
+ background-color: $ds_surface_alt;
+ border: 1px solid $ds_line;
border-radius: 9px;
text-align: left;
font-weight: 500;
}
#PatientsPage QPushButton[summaryCard="true"]:hover {
- color: #4F63D9;
- background-color: #EEF1FA;
- border-color: #8B9AD9;
+ color: $ds_accent;
+ background-color: $ds_accent_soft;
+ border-color: $ds_focus;
}
#PatientsPage QPushButton[rowAction="true"] {
min-height: 26px;
max-height: 26px;
padding: 0 7px;
- color: #4F63D9;
- background-color: #FFFFFF;
- border: 1px solid #EDEDEE;
+ color: $ds_accent;
+ background-color: $ds_surface;
+ border: 1px solid $ds_line;
border-radius: 6px;
font-size: 13px;
font-weight: 400;
}
#PatientsPage QPushButton[rowAction="true"]:hover {
- background-color: #EEF1FA;
- border-color: #8B9AD9;
+ background-color: $ds_accent_soft;
+ border-color: $ds_focus;
}
#PatientsPage QPushButton[rowAction="true"][variant="danger"] {
- color: #BE4B58;
- background-color: #FFF7F8;
- border-color: #F4C4CC;
+ color: $ds_danger;
+ background-color: $ds_danger_soft;
+ border-color: $ds_danger_soft;
}
#PatientsPage QTableWidget#PatientTable QHeaderView::section {
min-height: 34px;
- background-color: #F7F7F7; font-size: 13px;
+ background-color: $ds_surface_alt; font-size: 13px;
}
#PatientsPage QTableWidget#PatientTable::item { padding: 5px 7px; }
#PatientsPage QTableWidget#PatientTable {
- gridline-color: #EDEDEE;
- selection-background-color: #EEF1FA;
- selection-color: #1A1C1F; font-size: 14px;
+ gridline-color: $ds_line;
+ selection-background-color: $ds_accent_soft;
+ selection-color: $ds_heading; font-size: 14px;
}
#PatientsPage QCheckBox[patientSelector="true"]::indicator {
width: 13px;
height: 13px;
- background-color: #FFFFFF;
- border: 1px solid #EDEDEE;
+ background-color: $ds_surface;
+ border: 1px solid $ds_line;
border-radius: 2px;
}
#PatientsPage QCheckBox[patientSelector="true"]::indicator:checked {
- background-color: #4F63D9;
- border-color: #4F63D9;
+ background-color: $ds_accent;
+ border-color: $ds_accent;
}
#PatientsPage QPushButton[variant="ghost"]:checked {
- color: #4F63D9;
- background-color: #EEF1FA;
- border: 1px solid #4F63D9;
+ color: $ds_accent;
+ background-color: $ds_accent_soft;
+ border: 1px solid $ds_accent;
}
-#PatientsPage QPushButton[variant="ghost"]:checked:hover { background-color: #EEF1FA; }
+#PatientsPage QPushButton[variant="ghost"]:checked:hover { background-color: $ds_accent_soft; }
#PatientsPage QPushButton[statusKind="info"]:checked {
- color: #4F63D9;
- border-color: #4F63D9;
+ color: $ds_accent;
+ border-color: $ds_accent;
}
#PatientsPage QPushButton[statusKind="warning"]:checked {
- color: #A9691D;
- border-color: #A9691D;
+ color: $ds_warning;
+ border-color: $ds_warning;
}
#PatientsPage QPushButton[statusKind="success"]:checked {
- color: #287B65;
- border-color: #287B65;
+ color: $ds_success;
+ border-color: $ds_success;
}
#PatientsPage QPushButton[statusKind="danger"]:checked {
- color: #BE4B58;
- border-color: #BE4B58;
+ color: $ds_danger;
+ border-color: $ds_danger;
}
-#PatientsPage QLabel[metricKind="primary"] { color: #4F63D9; }
-#PatientsPage QLabel[metricKind="info"] { color: #4F63D9; }
-#PatientsPage QLabel[metricKind="success"] { color: #287B65; }
-#PatientsPage QLabel[metricKind="warning"] { color: #A9691D; }
-#PatientsPage QLabel[metricKind="danger"] { color: #BE4B58; }
+#PatientsPage QLabel[metricKind="primary"] { color: $ds_accent; }
+#PatientsPage QLabel[metricKind="info"] { color: $ds_accent; }
+#PatientsPage QLabel[metricKind="success"] { color: $ds_success; }
+#PatientsPage QLabel[metricKind="warning"] { color: $ds_warning; }
+#PatientsPage QLabel[metricKind="danger"] { color: $ds_danger; }
#PatientsPage QTabWidget#PatientWorkspaceTabs::pane {
background-color: transparent;
border: 0;
top: -1px;
}
#PatientsPage QTabWidget#PatientWorkspaceTabs QTabBar::tab {
- color: #606163;
+ color: $ds_muted;
background-color: transparent;
border: 0;
border-bottom: 2px solid transparent;
font-weight: 400;
}
#PatientsPage QTabWidget#PatientWorkspaceTabs QTabBar::tab:hover {
- color: #4F63D9;
- background-color: #EEF1FA;
+ color: $ds_accent;
+ background-color: $ds_accent_soft;
}
#PatientsPage QTabWidget#PatientWorkspaceTabs QTabBar::tab:selected {
- color: #4F63D9;
+ color: $ds_accent;
background-color: transparent;
- border-bottom-color: #4F63D9;
+ border-bottom-color: $ds_accent;
font-weight: 500;
}
-"""
+""")
def _style_table_cell(table: SortableTable, row: int, column: int, kind: str) -> None:
@@ -1282,7 +1283,7 @@ class _PatientDateEdit(QDateEdit):
def paintEvent(self, event: Any) -> None:
super().paintEvent(event)
painter = QPainter(self)
- glyph = icons.pixmap("calendar", "#5D6B80" if self.isEnabled() else "#8A97A9", 15)
+ glyph = icons.pixmap("calendar", PALETTE["muted"] if self.isEnabled() else PALETTE["disabled"], 15)
painter.drawPixmap(QRectF(self.width() - 24, (self.height() - 15) / 2, 15, 15), glyph, QRectF(glyph.rect()))
painter.end()
@@ -1300,18 +1301,18 @@ class _PatientSummaryButton(QPushButton):
label, _, count = self.text().partition("\n")
left = max(18, (self.width() - 204) // 2)
icon_rect = QRectF(left, (self.height() - 36) / 2, 36, 36)
- glyph = icons.pixmap("calendar", "#1769E8", 36)
+ glyph = icons.pixmap("calendar", PALETTE["accent"], 36)
painter.drawPixmap(icon_rect, glyph, QRectF(glyph.rect()))
font = QFont(body_family())
font.setPixelSize(13)
painter.setFont(font)
- painter.setPen(QColor("#5D6B80"))
+ painter.setPen(QColor(PALETTE["muted"]))
text_rect = self.rect().adjusted(left + 46, 10, -12, -32)
painter.drawText(text_rect, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
painter.fontMetrics().elidedText(label, Qt.TextElideMode.ElideRight, text_rect.width()))
font.setPixelSize(16)
painter.setFont(font)
- painter.setPen(QColor("#273244"))
+ painter.setPen(QColor(PALETTE["text"]))
painter.drawText(self.rect().adjusted(left + 46, 31, -12, -9),
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, count)
painter.end()
@@ -1324,11 +1325,11 @@ class _PatientInfoDelegate(QStyledItemDelegate):
painter.save()
selected = bool(option.state & QStyle.StateFlag.State_Selected)
hovered = bool(option.state & QStyle.StateFlag.State_MouseOver)
- painter.fillRect(option.rect, QColor("#EAF2FF" if selected else "#F6F9FE" if hovered else "#FFFFFF"))
- painter.setPen(QColor("#E6EDF6"))
+ painter.fillRect(option.rect, QColor(PALETTE["accent_soft"] if selected else PALETTE["surface_alt"] if hovered else PALETTE["surface"]))
+ painter.setPen(QColor(PALETTE["line"]))
painter.drawLine(option.rect.bottomLeft(), option.rect.bottomRight())
if selected and index.column() == 0:
- painter.fillRect(option.rect.adjusted(0, 0, -option.rect.width() + 3, 0), QColor("#1769E8"))
+ painter.fillRect(option.rect.adjusted(0, 0, -option.rect.width() + 3, 0), QColor(PALETTE["accent"]))
if index.column() in (0, 9):
painter.restore()
return
@@ -1337,9 +1338,9 @@ class _PatientInfoDelegate(QStyledItemDelegate):
font = QFont(body_family())
font.setPixelSize(14)
painter.setFont(font)
- painter.setPen(QColor("#273244"))
+ painter.setPen(QColor(PALETTE["text"]))
- def draw(text: str, target: Any, color: str = "#273244", centered: bool = False) -> None:
+ def draw(text: str, target: Any, color: str = PALETTE["text"], centered: bool = False) -> None:
painter.setPen(QColor(color))
text = painter.fontMetrics().elidedText(text, Qt.TextElideMode.ElideRight, target.width())
alignment = Qt.AlignmentFlag.AlignVCenter | (Qt.AlignmentFlag.AlignHCenter if centered else Qt.AlignmentFlag.AlignLeft)
@@ -1359,17 +1360,17 @@ class _PatientInfoDelegate(QStyledItemDelegate):
doctor = display_text(first_value(row, "appointment_doctor_name"), "")
status, _kind = _patient_status(row)
if not doctor:
- draw(status, rect, "#5D6B80")
+ draw(status, rect, PALETTE["muted"])
else:
draw(doctor, top)
font.setPixelSize(13)
painter.setFont(font)
- color, fill = ("#A9691D", "#FFF7EA") if status == "已过号" else ("#1769E8", "#F0F6FF")
+ color, fill = (PALETTE["warning"], PALETTE["warning_soft"]) if status == "已过号" else (PALETTE["accent"], PALETTE["accent_soft"])
if status == "已取消":
- color, fill = "#5D6B80", "#F5F7FA"
+ color, fill = PALETTE["muted"], PALETTE["canvas"]
badge = QRectF(bottom.x(), bottom.y() + 1, min(bottom.width(), painter.fontMetrics().horizontalAdvance(status) + 10), 20)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
- painter.setPen(QColor("#E7CDA8" if status == "已过号" else "#C7DAF7"))
+ painter.setPen(QColor(PALETTE["warning_soft"] if status == "已过号" else PALETTE["line_strong"]))
painter.setBrush(QColor(fill))
painter.drawRoundedRect(badge, 3, 3)
draw(status, badge.toRect(), color, True)
@@ -1385,7 +1386,7 @@ class _PatientInfoDelegate(QStyledItemDelegate):
draw(value, rect)
else:
text = str(index.data(Qt.ItemDataRole.DisplayRole) or "")
- draw(text, rect, "#A9691D" if index.column() == 6 and text == "待确认" else "#273244", index.column() == 5)
+ draw(text, rect, PALETTE["warning"] if index.column() == 6 and text == "待确认" else PALETTE["text"], index.column() == 5)
painter.restore()
@@ -1493,7 +1494,7 @@ class PatientListWorkspace(QWidget):
self.keyword_edit.setMaximumWidth(360)
self.keyword_edit.setPlaceholderText("患者姓名 / 手机号 / 助理 / 医生")
self.keyword_edit.setClearButtonEnabled(True)
- self.keyword_edit.addAction(icons.icon("search", "#5D6B80", 16), QLineEdit.ActionPosition.LeadingPosition)
+ self.keyword_edit.addAction(icons.icon("search", PALETTE["muted"], 16), QLineEdit.ActionPosition.LeadingPosition)
self.keyword_edit.returnPressed.connect(self.search)
search_row.addWidget(self.keyword_edit, 1)
self.status_label = QLabel("患者状态:")
@@ -1846,7 +1847,7 @@ class PatientListWorkspace(QWidget):
)
host = RowActions(row_actions, self.table)
if host.more_button is not None:
- host.more_button.setIcon(icons.icon("chevron_down", "#5D6B80", 12))
+ host.more_button.setIcon(icons.icon("chevron_down", PALETTE["muted"], 12))
host.more_button.setIconSize(QSize(12, 12))
host.more_button.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon)
host.more_button.setLayoutDirection(Qt.LayoutDirection.RightToLeft)
@@ -2079,7 +2080,7 @@ class _OrderComboBox(QComboBox):
def paintEvent(self, event: Any) -> None:
super().paintEvent(event)
painter = QPainter(self)
- glyph = icons.pixmap("chevron_down", "#5D6B80", 14)
+ glyph = icons.pixmap("chevron_down", PALETTE["muted"], 14)
painter.drawPixmap(QRectF(self.width() - 24, (self.height() - 14) / 2, 14, 14), glyph, QRectF(glyph.rect()))
painter.end()
@@ -2088,7 +2089,7 @@ class _OrderActionButton(QToolButton):
def paintEvent(self, event: Any) -> None:
super().paintEvent(event)
painter = QPainter(self)
- glyph = icons.pixmap("chevron_down", "#5D6B80" if self.isEnabled() else "#97A4B6", 14)
+ glyph = icons.pixmap("chevron_down", PALETTE["muted"] if self.isEnabled() else PALETTE["disabled"], 14)
painter.drawPixmap(QRectF(self.width() - 23, (self.height() - 14) / 2, 14, 14), glyph, QRectF(glyph.rect()))
painter.end()
@@ -2107,18 +2108,18 @@ class _OrderInfoDelegate(QStyledItemDelegate):
painter.setClipRect(option.rect)
selected = bool(option.state & QStyle.StateFlag.State_Selected)
hovered = bool(option.state & QStyle.StateFlag.State_MouseOver)
- painter.fillRect(option.rect, QColor("#F5F8FF" if selected else "#F8FAFE" if hovered else "#FFFFFF"))
- painter.setPen(QColor("#E6EDF6"))
+ painter.fillRect(option.rect, QColor(PALETTE["accent_soft"] if selected else PALETTE["surface_alt"] if hovered else PALETTE["surface"]))
+ painter.setPen(QColor(PALETTE["line"]))
painter.drawLine(option.rect.bottomLeft(), option.rect.bottomRight())
if selected and index.column() == 0:
- painter.fillRect(option.rect.adjusted(0, 0, -option.rect.width() + 3, 0), QColor("#1769E8"))
+ painter.fillRect(option.rect.adjusted(0, 0, -option.rect.width() + 3, 0), QColor(PALETTE["accent"]))
rect = option.rect.adjusted(16, 0, -12, -1)
font = QFont(body_family())
font.setPixelSize(14)
painter.setFont(font)
text = str(index.data(Qt.ItemDataRole.DisplayRole) or "—")
- def draw(value: str, target: Any, color: str = "#273244", right: bool = False) -> None:
+ def draw(value: str, target: Any, color: str = PALETTE["text"], right: bool = False) -> None:
painter.setPen(QColor(color))
value = painter.fontMetrics().elidedText(value, Qt.TextElideMode.ElideRight, target.width())
painter.drawText(target, Qt.AlignmentFlag.AlignVCenter | (Qt.AlignmentFlag.AlignRight if right else Qt.AlignmentFlag.AlignLeft), value)
@@ -2138,7 +2139,7 @@ class _OrderInfoDelegate(QStyledItemDelegate):
font.setWeight(QFont.Weight.Normal)
font.setPixelSize(13)
painter.setFont(font)
- draw(secondary, bottom, "#5D6B80")
+ draw(secondary, bottom, PALETTE["muted"])
else:
draw(text, rect)
elif column in (9, 11):
@@ -2147,7 +2148,7 @@ class _OrderInfoDelegate(QStyledItemDelegate):
draw(primary, top)
font.setPixelSize(13)
painter.setFont(font)
- draw(("(" if column == 9 else "") + secondary, bottom, "#5D6B80")
+ draw(("(" if column == 9 else "") + secondary, bottom, PALETTE["muted"])
else:
draw(text, rect)
elif column in (4, 5, 6):
@@ -2158,10 +2159,10 @@ class _OrderInfoDelegate(QStyledItemDelegate):
else:
kind = "blue" if raw in {3, 5, 6, 7, 8, 11} else "danger" if raw in {4, 9, 10} else "warning" if raw in {1, 2, 12} else "neutral"
foreground, background, border = {
- "blue": ("#1769E8", "#F2F7FF", "#CEE0FA"),
- "warning": ("#AD640C", "#FFFAF2", "#F2DABD"),
- "danger": ("#BE4657", "#FFF5F6", "#F0D0D7"),
- "neutral": ("#5D6B80", "#F6F8FC", "#E2E9F2"),
+ "blue": (PALETTE["accent"], PALETTE["accent_soft"], PALETTE["line_strong"]),
+ "warning": (PALETTE["warning"], PALETTE["warning_soft"], PALETTE["warning_soft"]),
+ "danger": (PALETTE["danger"], PALETTE["danger_soft"], PALETTE["danger_soft"]),
+ "neutral": (PALETTE["muted"], PALETTE["disabled_surface"], PALETTE["line"]),
}[kind]
font.setPixelSize(13)
painter.setFont(font)
@@ -2275,7 +2276,7 @@ class PatientOrdersWorkspace(QWidget):
self.keyword_edit.setMinimumWidth(240)
self.keyword_edit.setPlaceholderText("订单号 / 患者 / 手机号 / 处方ID / 诊单ID")
self.keyword_edit.setClearButtonEnabled(True)
- self.keyword_edit.addAction(icons.icon("search", "#5D6B80", 16), QLineEdit.ActionPosition.LeadingPosition)
+ self.keyword_edit.addAction(icons.icon("search", PALETTE["muted"], 16), QLineEdit.ActionPosition.LeadingPosition)
self.keyword_edit.returnPressed.connect(self.search)
self.filter_top_row.addWidget(self.keyword_edit, 1)
self.audit_host = QWidget()
@@ -2747,11 +2748,11 @@ class _ProgressInfoDelegate(QStyledItemDelegate):
painter.setClipRect(option.rect)
selected = bool(option.state & QStyle.StateFlag.State_Selected)
hovered = bool(option.state & QStyle.StateFlag.State_MouseOver)
- painter.fillRect(option.rect, QColor("#F2F7FF" if selected else "#F8FAFE" if hovered else "#FFFFFF"))
- painter.setPen(QColor("#E6EDF6"))
+ painter.fillRect(option.rect, QColor(PALETTE["accent_soft"] if selected else PALETTE["surface_alt"] if hovered else PALETTE["surface"]))
+ painter.setPen(QColor(PALETTE["line"]))
painter.drawLine(option.rect.bottomLeft(), option.rect.bottomRight())
if selected and index.column() == 0:
- painter.fillRect(option.rect.adjusted(0, 0, -option.rect.width() + 3, 0), QColor("#1769E8"))
+ painter.fillRect(option.rect.adjusted(0, 0, -option.rect.width() + 3, 0), QColor(PALETTE["accent"]))
rect = option.rect.adjusted(16, 0, -16, -1)
font = QFont(body_family())
font.setPixelSize(14)
@@ -2762,20 +2763,20 @@ class _ProgressInfoDelegate(QStyledItemDelegate):
painter.setFont(font)
raw_text = index.data(Qt.ItemDataRole.DisplayRole)
text = "" if raw_text is None else str(raw_text)
- color = "#273244"
+ color = PALETTE["text"]
if not self.schedule and index.column() == 5 and text and text != "—":
row = index.data(Qt.ItemDataRole.UserRole)
status = str(first_value(row, "queue_status", default="") or "").lower()
color = {
- "consulting": "#1769E8", "next": "#1555B6",
- "waiting": "#AD640C", "missed": "#BE4657",
- }.get(status, "#5D6B80")
+ "consulting": PALETTE["accent"], "next": PALETTE["accent_hover"],
+ "waiting": PALETTE["warning"], "missed": PALETTE["danger"],
+ }.get(status, PALETTE["muted"])
painter.setPen(QColor(color))
alignment = Qt.AlignmentFlag.AlignVCenter
alignment |= Qt.AlignmentFlag.AlignHCenter if self.schedule and 1 <= index.column() <= 5 else Qt.AlignmentFlag.AlignLeft
painter.drawText(rect, alignment, painter.fontMetrics().elidedText(text, Qt.TextElideMode.ElideRight, rect.width()))
if option.state & QStyle.StateFlag.State_HasFocus:
- painter.setPen(QColor("#75A5F0"))
+ painter.setPen(QColor(PALETTE["focus"]))
painter.setBrush(Qt.BrushStyle.NoBrush)
painter.drawRect(option.rect.adjusted(1, 1, -2, -2))
painter.restore()
@@ -2875,7 +2876,7 @@ class PatientProgressWorkspace(QWidget):
row = QHBoxLayout(frame)
row.setContentsMargins(0, 0, 0, 0)
row.setSpacing(0)
- divider = QFrame()
+ divider = QFrame(frame)
divider.setObjectName("ProgressMetricDivider")
divider.setFixedSize(1, 60)
divider.setVisible(key != "total")
diff --git a/app/src/doctor_workstation/ui/pages/prescription_library.py b/app/src/doctor_workstation/ui/pages/prescription_library.py
index e555800ab..3a6480cdb 100644
--- a/app/src/doctor_workstation/ui/pages/prescription_library.py
+++ b/app/src/doctor_workstation/ui/pages/prescription_library.py
@@ -24,6 +24,7 @@ from PySide6.QtWidgets import (
)
from .. import motion
+from ..design_system import PALETTE
from ..dialogs.prescription import PrescriptionTemplateDialog
from ..dialogs.prescription_ai import PrescriptionAiReportDialog, can_open_ai_explain
from ..filter_disclosure import FilterDisclosure
@@ -119,7 +120,7 @@ def _metric_card(title: str, kind: str = "accent", glyph: str = "layers") -> Met
icon.setProperty("metricIcon", True)
icon.setAlignment(Qt.AlignmentFlag.AlignCenter)
icon.setFixedSize(32, 32)
- color = "#1769E8" if kind == "accent" else "#60789F"
+ color = PALETTE["accent"] if kind == "accent" else PALETTE["muted"]
icon.setPixmap(_painted_icon(glyph, color, 25).pixmap(25, 25))
card.layout().addWidget(icon)
return card
@@ -543,7 +544,7 @@ class PrescriptionLibraryPage(QWidget):
name_item = self.table.item(row_index, 1)
if name_item is not None:
- name_item.setForeground(QColor("#1A1C1F"))
+ name_item.setForeground(QColor(PALETTE["heading"]))
font = name_item.font()
font.setWeight(QFont.Weight.Medium)
name_item.setFont(font)
diff --git a/app/src/doctor_workstation/ui/pages/prescriptions.py b/app/src/doctor_workstation/ui/pages/prescriptions.py
index 4bf9ba9dd..5a0a65f83 100644
--- a/app/src/doctor_workstation/ui/pages/prescriptions.py
+++ b/app/src/doctor_workstation/ui/pages/prescriptions.py
@@ -50,6 +50,7 @@ from PySide6.QtWidgets import (
)
from .. import icons, motion
+from ..design_system import PALETTE, clinical_stylesheet
from ..dialogs.issued_prescription_ai import (
PrescriptionAiStatisticsDialog,
agreement_safe_batch,
@@ -229,11 +230,11 @@ _ROLE_AVATAR = Qt.ItemDataRole.UserRole + 11
_ROLE_LEAD_ICON = Qt.ItemDataRole.UserRole + 12
_TAG_PALETTE = {
- "accent": ("#4F63D9", "#EEF1FA"),
- "success": ("#287B65", "#E7F8F1"),
- "warning": ("#A9691D", "#FFF5DF"),
- "danger": ("#BE4B58", "#FFF0F2"),
- "neutral": ("#606163", "#F7F7F7"),
+ "accent": (PALETTE["accent"], PALETTE["accent_soft"]),
+ "success": (PALETTE["success"], PALETTE["success_soft"]),
+ "warning": (PALETTE["warning"], PALETTE["warning_soft"]),
+ "danger": (PALETTE["danger"], PALETTE["danger_soft"]),
+ "neutral": (PALETTE["muted"], PALETTE["surface_alt"]),
}
@@ -293,7 +294,7 @@ class _RowDecorationDelegate(QStyledItemDelegate):
glyph,
QRectF(glyph.rect()),
)
- painter.setPen(QColor("#1A1C1F"))
+ painter.setPen(QColor(PALETTE["heading"]))
painter.setFont(style_option.font)
text_rect = rect.adjusted(28, 0, -8, 0)
painter.drawText(
@@ -306,17 +307,17 @@ class _RowDecorationDelegate(QStyledItemDelegate):
else:
initial = str(avatar)[:1] or "医"
circle = QRectF(rect.left() + 8, rect.center().y() - 10, 20, 20)
- painter.setPen(QPen(QColor("#EDEDEE"), 1.0))
- painter.setBrush(QColor("#F7F7F7"))
+ painter.setPen(QPen(QColor(PALETTE["line"]), 1.0))
+ painter.setBrush(QColor(PALETTE["surface_alt"]))
painter.drawEllipse(circle.adjusted(0.5, 0.5, -0.5, -0.5))
initial_font = QFont(style_option.font)
initial_font.setPixelSize(10)
initial_font.setWeight(QFont.Weight.Medium)
painter.setFont(initial_font)
- painter.setPen(QColor("#6A6B6D"))
+ painter.setPen(QColor(PALETTE["muted"]))
painter.drawText(circle, Qt.AlignmentFlag.AlignCenter, initial)
painter.setFont(style_option.font)
- painter.setPen(QColor("#1A1C1F"))
+ painter.setPen(QColor(PALETTE["heading"]))
name_rect = rect.adjusted(35, 0, -8, 0)
painter.drawText(
name_rect,
@@ -509,11 +510,11 @@ class _PrescriptionNumberDelegate(QStyledItemDelegate):
text_option.setWrapMode(QTextOption.WrapMode.WrapAtWordBoundaryOrAnywhere)
document.setDefaultTextOption(text_option)
paragraphs = [
- f'{escape(number)}
',
- f'ID: {escape(record_id)}
',
+ f'{escape(number)}
',
+ f'ID: {escape(record_id)}
',
]
paragraphs.extend(
- ''
+ f'
'
+ escape(warning)
+ "
"
for warning in _order_warnings(row)
@@ -603,14 +604,14 @@ class _DoctorOptionDelegate(QStyledItemDelegate):
rect = option.rect.adjusted(2, 1, -2, -1)
hovered = bool(option.state & QStyle.StateFlag.State_MouseOver)
painter.setPen(Qt.PenStyle.NoPen)
- painter.setBrush(QColor("#EAF2FF" if checked else "#F3F7FD" if hovered else "#FFFFFF"))
+ painter.setBrush(QColor(PALETTE["accent_soft"] if checked else PALETTE["canvas"] if hovered else PALETTE["surface"]))
painter.drawRoundedRect(rect, 5, 5)
box = QRectF(rect.left() + 10, rect.center().y() - 8, 16, 16)
- painter.setPen(QPen(QColor("#1769E8" if checked else "#B8C7DA"), 1))
- painter.setBrush(QColor("#1769E8" if checked else "#FFFFFF"))
+ painter.setPen(QPen(QColor(PALETTE["accent"] if checked else PALETTE["line_strong"]), 1))
+ painter.setBrush(QColor(PALETTE["accent"] if checked else PALETTE["surface"]))
painter.drawRoundedRect(box, 3, 3)
if checked:
- pen = QPen(QColor("#FFFFFF"), 2)
+ pen = QPen(QColor(PALETTE["surface"]), 2)
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
painter.setPen(pen)
x, y = int(box.x()), int(box.y())
@@ -619,16 +620,16 @@ class _DoctorOptionDelegate(QStyledItemDelegate):
font = QFont(body_family())
font.setPixelSize(13)
painter.setFont(font)
- painter.setPen(QColor("#273244"))
+ painter.setPen(QColor(PALETTE["text"]))
text_rect = rect.adjusted(38, 0, -54, 0)
label = painter.fontMetrics().elidedText(str(index.data() or ""), Qt.TextElideMode.ElideRight, text_rect.width())
painter.drawText(text_rect, Qt.AlignmentFlag.AlignVCenter, label)
if checked:
- painter.setPen(QColor("#1769E8"))
+ painter.setPen(QColor(PALETTE["accent"]))
painter.drawText(rect.adjusted(0, 0, -12, 0), Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter, "已选")
if option.state & QStyle.StateFlag.State_HasFocus:
painter.setBrush(Qt.BrushStyle.NoBrush)
- painter.setPen(QPen(QColor("#ADC8F2"), 1))
+ painter.setPen(QPen(QColor(PALETTE["line_strong"]), 1))
painter.drawRoundedRect(rect, 5, 5)
painter.restore()
@@ -674,18 +675,18 @@ class _DoctorSelectionDialog(QDialog):
self.setObjectName("DoctorSelectionDialog")
self.setWindowTitle("选择医生")
self.resize(420, 500)
- self.setStyleSheet("""
- QDialog#DoctorSelectionDialog { background: #FFFFFF; color: #273244; }
- QListWidget#DoctorOptionsList { background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 6px; padding: 3px; }
- QLabel#DoctorSelectionCount { color: #1769E8; font-size: 13px; }
- QDialog#DoctorSelectionDialog QLineEdit { border: 1px solid #DBE5F2; border-radius: 6px; }
- QDialog#DoctorSelectionDialog QLineEdit:focus { border-color: #1769E8; }
- QDialog#DoctorSelectionDialog QPushButton { background: #FFFFFF; color: #273244; border: 1px solid #DBE5F2; border-radius: 6px; }
- QDialog#DoctorSelectionDialog QPushButton:hover { background: #F3F7FD; border-color: #ADC8F2; }
- QDialog#DoctorSelectionDialog QPushButton:disabled { color: #8A97A9; }
- QDialog#DoctorSelectionDialog QPushButton#ConfirmDoctorSelection { background: #1769E8; color: #FFFFFF; border-color: #1769E8; }
- QDialog#DoctorSelectionDialog QPushButton#ConfirmDoctorSelection:hover { background: #125DCE; border-color: #125DCE; }
- """)
+ self.setStyleSheet(clinical_stylesheet("""
+ QDialog#DoctorSelectionDialog { background: $ds_surface; color: $ds_text; }
+ QListWidget#DoctorOptionsList { background: $ds_surface; border: 1px solid $ds_line; border-radius: 6px; padding: 3px; }
+ QLabel#DoctorSelectionCount { color: $ds_accent; font-size: 13px; }
+ QDialog#DoctorSelectionDialog QLineEdit { border: 1px solid $ds_line; border-radius: 6px; }
+ QDialog#DoctorSelectionDialog QLineEdit:focus { border-color: $ds_accent; }
+ QDialog#DoctorSelectionDialog QPushButton { background: $ds_surface; color: $ds_text; border: 1px solid $ds_line; border-radius: 6px; }
+ QDialog#DoctorSelectionDialog QPushButton:hover { background: $ds_canvas; border-color: $ds_line_strong; }
+ QDialog#DoctorSelectionDialog QPushButton:disabled { color: $ds_disabled; }
+ QDialog#DoctorSelectionDialog QPushButton#ConfirmDoctorSelection { background: $ds_accent; color: $ds_surface; border-color: $ds_accent; }
+ QDialog#DoctorSelectionDialog QPushButton#ConfirmDoctorSelection:hover { background: $ds_accent_hover; border-color: $ds_accent_hover; }
+ """))
layout = QVBoxLayout(self)
layout.setContentsMargins(16, 16, 16, 16)
layout.setSpacing(10)
@@ -793,9 +794,9 @@ class DoctorMultiSelect(QWidget):
self.button.setText("、".join(names[:2]) + (f" 等{len(names)}人" if len(names) > 2 else ""))
-def _blue_prescription_icon(kind: str, color: str = "#1769E8", size: int = 15) -> QIcon:
+def _blue_prescription_icon(kind: str, color: str = PALETTE["accent"], size: int = 15) -> QIcon:
result = QIcon(icons.icon(kind, color, size))
- result.addPixmap(icons.pixmap(kind, "#A4ADBA", size), QIcon.Mode.Disabled)
+ result.addPixmap(icons.pixmap(kind, PALETTE["disabled"], size), QIcon.Mode.Disabled)
return result
@@ -803,7 +804,7 @@ class _PrescriptionCombo(QComboBox):
def paintEvent(self, event: Any) -> None:
super().paintEvent(event)
painter = QPainter(self)
- glyph = icons.pixmap("chevron_down", "#5D6B80", 14)
+ glyph = icons.pixmap("chevron_down", PALETTE["muted"], 14)
painter.drawPixmap(QRectF(self.width() - 25, (self.height() - 14) / 2, 14, 14), glyph, QRectF(glyph.rect()))
painter.end()
@@ -812,7 +813,7 @@ class _PrescriptionDateTime(QDateTimeEdit):
def paintEvent(self, event: Any) -> None:
super().paintEvent(event)
painter = QPainter(self)
- glyph = icons.pixmap("calendar", "#5D6B80" if self.isEnabled() else "#8A97A9", 14)
+ glyph = icons.pixmap("calendar", PALETTE["muted"] if self.isEnabled() else PALETTE["disabled"], 14)
painter.drawPixmap(QRectF(self.width() - 25, (self.height() - 14) / 2, 14, 14), glyph, QRectF(glyph.rect()))
painter.end()
@@ -825,7 +826,7 @@ class _PrescriptionDoctorButton(QPushButton):
option.text = self.fontMetrics().elidedText(self.text(), Qt.TextElideMode.ElideRight, max(1, self.width() - 48))
painter = QPainter(self)
self.style().drawControl(QStyle.ControlElement.CE_PushButton, option, painter, self)
- glyph = icons.pixmap("chevron_down", "#5D6B80", 14)
+ glyph = icons.pixmap("chevron_down", PALETTE["muted"], 14)
painter.drawPixmap(QRectF(self.width() - 25, (self.height() - 14) / 2, 14, 14), glyph, QRectF(glyph.rect()))
painter.end()
@@ -837,13 +838,13 @@ class _PrescriptionDoctorButton(QPushButton):
def _prescription_cell_background(painter: QPainter, option: Any, index: QModelIndex) -> None:
selected = bool(option.state & QStyle.StateFlag.State_Selected)
hovered = bool(option.state & QStyle.StateFlag.State_MouseOver)
- painter.fillRect(option.rect, QColor("#F2F7FF" if selected else "#F8FAFE" if hovered else "#FFFFFF"))
- painter.setPen(QColor("#E6EDF6"))
+ painter.fillRect(option.rect, QColor(PALETTE["accent_soft"] if selected else PALETTE["surface_alt"] if hovered else PALETTE["surface"]))
+ painter.setPen(QColor(PALETTE["line"]))
painter.drawLine(option.rect.bottomLeft(), option.rect.bottomRight())
if selected and index.column() == 0:
- painter.fillRect(option.rect.adjusted(0, 0, -option.rect.width() + 3, 0), QColor("#1769E8"))
+ painter.fillRect(option.rect.adjusted(0, 0, -option.rect.width() + 3, 0), QColor(PALETTE["accent"]))
if option.state & QStyle.StateFlag.State_HasFocus:
- painter.setPen(QColor("#75A5F0"))
+ painter.setPen(QColor(PALETTE["focus"]))
painter.setBrush(Qt.BrushStyle.NoBrush)
painter.drawRect(option.rect.adjusted(1, 1, -2, -2))
@@ -875,7 +876,7 @@ class _PrescriptionInfoDelegate(QStyledItemDelegate):
font = QFont(body_family())
font.setPixelSize(14)
painter.setFont(font)
- painter.setPen(QColor("#273244"))
+ painter.setPen(QColor(PALETTE["text"]))
text = str(index.data(Qt.ItemDataRole.DisplayRole) or "")
column = index.column()
if column == 0:
@@ -888,9 +889,9 @@ class _PrescriptionInfoDelegate(QStyledItemDelegate):
elif column in (3, 6):
kind = index.data(_ROLE_TAG_KIND)
foreground, background = {
- "accent": ("#1769E8", "#EDF4FF"), "success": ("#1769E8", "#EDF4FF"),
- "warning": ("#AD640C", "#FFF5E5"), "danger": ("#BE4657", "#FFF0F2"),
- }.get(kind, ("#5D6B80", "#F5F8FD"))
+ "accent": (PALETTE["accent"], PALETTE["accent_soft"]), "success": (PALETTE["accent"], PALETTE["accent_soft"]),
+ "warning": (PALETTE["warning"], PALETTE["warning_soft"]), "danger": (PALETTE["danger"], PALETTE["danger_soft"]),
+ }.get(kind, (PALETTE["muted"], PALETTE["surface_alt"]))
font.setPixelSize(13)
painter.setFont(font)
label = painter.fontMetrics().elidedText(text, Qt.TextElideMode.ElideRight, max(1, rect.width() - 12))
@@ -918,7 +919,7 @@ class _PrescriptionInfoDelegate(QStyledItemDelegate):
font = QFont(body_family())
font.setPixelSize(13)
painter.setFont(font)
- painter.setPen(QColor("#5D6B80"))
+ painter.setPen(QColor(PALETTE["muted"]))
second_rect = first_rect.translated(0, 26)
painter.drawText(second_rect, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, painter.fontMetrics().elidedText(secondary, Qt.TextElideMode.ElideRight, rect.width()))
else:
@@ -942,11 +943,11 @@ class _PrescriptionNumberBlueDelegate(_PrescriptionNumberDelegate):
text_option.setWrapMode(QTextOption.WrapMode.WrapAtWordBoundaryOrAnywhere)
document.setDefaultTextOption(text_option)
paragraphs = [
- f'{escape(number)}
',
- f'ID: {escape(record_id)}
',
+ f'{escape(number)}
',
+ f'ID: {escape(record_id)}
',
]
paragraphs.extend(
- '' + escape(warning) + "
"
+ f'' + escape(warning) + "
"
for warning in _order_warnings(row)
)
document.setHtml("".join(paragraphs))
@@ -976,7 +977,7 @@ class _PrescriptionBlueTable(SortableTable):
for button in widget.findChildren(QPushButton):
kind = {"查看处方": "eye", "编辑处方": "pencil", "删除处方": "trash"}.get(button.accessibleName())
if kind:
- button.setIcon(_blue_prescription_icon(kind, "#BE4657" if kind == "trash" else "#1769E8"))
+ button.setIcon(_blue_prescription_icon(kind, PALETTE["danger"] if kind == "trash" else PALETTE["accent"]))
class PrescriptionsPage(QWidget):
@@ -1060,7 +1061,7 @@ class PrescriptionsPage(QWidget):
self.add_button.setObjectName("PrescriptionAddButton")
self.add_button.setMinimumWidth(122)
self.add_button.setProperty("variant", "primary")
- self.add_button.setIcon(_blue_prescription_icon("plus", "#FFFFFF"))
+ self.add_button.setIcon(_blue_prescription_icon("plus", PALETTE["surface"]))
self.add_button.setIconSize(QSize(15, 15))
self.add_button.setCursor(Qt.CursorShape.PointingHandCursor)
self.add_button.setVisible(has_permission(permissions, "cf.prescription/add"))
@@ -1079,7 +1080,7 @@ class PrescriptionsPage(QWidget):
self.table_card = table_card
root.addWidget(table_card, 1)
for button, kind in ((self.view_button, "eye"), (self.edit_button, "pencil"), (self.delete_button, "trash")):
- button.setIcon(_blue_prescription_icon(kind, "#BE4657" if kind == "trash" else "#1769E8"))
+ button.setIcon(_blue_prescription_icon(kind, PALETTE["danger"] if kind == "trash" else PALETTE["accent"]))
self._load_doctor_options()
def _build_filters(self) -> QWidget:
@@ -1226,7 +1227,7 @@ class PrescriptionsPage(QWidget):
refresh = QPushButton("刷新")
refresh.setProperty("variant", "ghost")
refresh.setCursor(Qt.CursorShape.PointingHandCursor)
- refresh.setIcon(_blue_prescription_icon("refresh", "#5D6B80"))
+ refresh.setIcon(_blue_prescription_icon("refresh", PALETTE["muted"]))
refresh.setIconSize(QSize(15, 15))
refresh.clicked.connect(self.refresh)
toolbar.addWidget(refresh)
@@ -1287,7 +1288,7 @@ class PrescriptionsPage(QWidget):
self.table.setItemDelegate(_PrescriptionInfoDelegate(self.table))
self.table.setItemDelegateForColumn(1, _PrescriptionNumberBlueDelegate(self.table))
self.table.horizontalHeader().sectionResized.connect(self._number_column_resized)
- self.table.horizontalHeaderItem(0).setIcon(_blue_prescription_icon("checkbox", "#8A97A9", 14))
+ self.table.horizontalHeaderItem(0).setIcon(_blue_prescription_icon("checkbox", PALETTE["disabled"], 14))
self.table.horizontalHeaderItem(0).setTextAlignment(Qt.AlignmentFlag.AlignCenter)
self.table.itemSelectionChanged.connect(self._selection_changed)
self.table.itemDoubleClicked.connect(lambda _item: self._view_selected())
@@ -1537,7 +1538,7 @@ class PrescriptionsPage(QWidget):
sn_item = self.table.item(row_index, 1)
if sn_item is not None:
- sn_item.setForeground(QColor("#1A1C1F"))
+ sn_item.setForeground(QColor(PALETTE["heading"]))
font = sn_item.font()
font.setWeight(QFont.Weight.Normal)
sn_item.setFont(font)
diff --git a/app/src/doctor_workstation/ui/pages/reception.py b/app/src/doctor_workstation/ui/pages/reception.py
index cb13eaae5..ea58bc6c2 100644
--- a/app/src/doctor_workstation/ui/pages/reception.py
+++ b/app/src/doctor_workstation/ui/pages/reception.py
@@ -75,6 +75,7 @@ from PySide6.QtWidgets import (
from ...core.appointment_modes import appointment_type_description, appointment_type_value
from .. import icons
+from ..design_system import PALETTE, clinical_stylesheet
from ..diagnosis_drawer import DailyRecordPanel
from ..diagnosis_editors import FlowLayout
from ..dialogs import DiagnosisDialog
@@ -2020,7 +2021,7 @@ def _painted_reception_tab_icon(kind: str, size: int = 16) -> QIcon:
outline (bubble / chart page / capsule / clipboard / calendar-clock).
"""
- return icons.icon(kind, "#5D6B80", size)
+ return icons.icon(kind, PALETTE["muted"], size)
def _painted_reception_action_icon(kind: str, color: str, size: int = 14) -> QIcon:
@@ -2882,7 +2883,7 @@ class _ReceptionSparkIcon(QWidget):
del event
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
- glyph = icons.pixmap("ai", "#1769E8", 18)
+ glyph = icons.pixmap("ai", PALETTE["accent"], 18)
painter.drawPixmap(QRectF(0, 0, 18, 18), glyph, QRectF(glyph.rect()))
painter.end()
@@ -2896,9 +2897,9 @@ class _ReceptionAiSectionIcon(QWidget):
#: Section tone -> (plate, glyph tint, shared glyph name).
_TONES = {
- "diagnosis": ("#EAF2FF", "#1769E8", "report"),
- "risk": ("#EAF2FF", "#1769E8", "alert"),
- "treatment": ("#EAF2FF", "#1769E8", "meds"),
+ "diagnosis": (PALETTE["accent_soft"], PALETTE["accent"], "report"),
+ "risk": (PALETTE["accent_soft"], PALETTE["accent"], "alert"),
+ "treatment": (PALETTE["accent_soft"], PALETTE["accent"], "meds"),
}
def __init__(self, tone: str, parent: QWidget | None = None) -> None:
@@ -2949,9 +2950,9 @@ class _ReceptionAssistantIcon(QWidget):
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
painter.setPen(Qt.PenStyle.NoPen)
- painter.setBrush(QColor("#1769E8"))
+ painter.setBrush(QColor(PALETTE["accent"]))
painter.drawRoundedRect(QRectF(1, 1, 22, 22), 4, 4)
- painter.setPen(QColor("#FFFFFF"))
+ painter.setPen(QColor(PALETTE["surface"]))
font = painter.font()
font.setPixelSize(11)
font.setBold(True)
@@ -2975,7 +2976,7 @@ class _ReceptionSendButton(QPushButton):
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
painter.setPen(
QPen(
- QColor("#FFFFFF"),
+ QColor(PALETTE["surface"]),
1.8,
Qt.PenStyle.SolidLine,
Qt.PenCapStyle.RoundCap,
@@ -3053,7 +3054,7 @@ class _ReceptionDateButton(QPushButton):
super().paintEvent(event)
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
- color = QColor("#5D6B80")
+ color = QColor(PALETTE["muted"])
painter.setPen(
QPen(
color,
@@ -3087,7 +3088,7 @@ class _ReceptionAiExpandButton(QPushButton):
del event
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
- color = QColor("#1769E8" if self.isEnabled() else "#8E8F90")
+ color = QColor(PALETTE["accent"] if self.isEnabled() else PALETTE["disabled"])
painter.setPen(
QPen(
color,
@@ -3120,7 +3121,7 @@ class _ReceptionAiModelCombo(QComboBox):
super().paintEvent(event)
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
- color = QColor("#273244" if self.isEnabled() else "#8E8F90")
+ color = QColor(PALETTE["text"] if self.isEnabled() else PALETTE["disabled"])
painter.setPen(
QPen(
color,
@@ -3162,7 +3163,7 @@ class _ReceptionAiAnalysisDialog(QDialog):
self.resize(920, 760)
self.setMinimumSize(720, 560)
self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose)
- self.setStyleSheet(RECEPTION_AI_DIALOG_QSS)
+ self.setStyleSheet(clinical_stylesheet(RECEPTION_AI_DIALOG_QSS))
root = QVBoxLayout(self)
root.setContentsMargins(18, 18, 18, 18)
@@ -3365,7 +3366,11 @@ class _ReceptionAiAnalysisDialog(QDialog):
source_label.setTextFormat(Qt.TextFormat.PlainText)
source_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
source_label.setWordWrap(True)
- source_label.setStyleSheet("color: #555B68; font-size: 12px; padding: 10px 14px; background: #F7F8FC; border: 1px solid #E4E8F2; border-radius: 8px;")
+ source_label.setStyleSheet(clinical_stylesheet(
+ "color: $ds_muted; font-size: 12px; padding: 10px 14px; "
+ "background: $ds_surface_alt; border: 1px solid $ds_line; "
+ "border-radius: $ds_radius_control;"
+ ))
body_layout.addWidget(source_label)
self.source_label = source_label
body_layout.addStretch(1)
@@ -3614,9 +3619,9 @@ class _VitalMetricIcon(QWidget):
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
painter.setPen(Qt.PenStyle.NoPen)
- painter.setBrush(QColor("#EAF2FF"))
+ painter.setBrush(QColor(PALETTE["accent_soft"]))
painter.drawRoundedRect(QRectF(0, 0, 22, 22), 6, 6)
- glyph = icons.pixmap(self._GLYPHS.get(self._kind, "pulse"), "#1769E8", 15)
+ glyph = icons.pixmap(self._GLYPHS.get(self._kind, "pulse"), PALETTE["accent"], 15)
painter.drawPixmap(QRectF(3.5, 3.5, 15, 15), glyph, QRectF(glyph.rect()))
painter.end()
@@ -3636,7 +3641,7 @@ class _LifestyleIcon(QWidget):
del event
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
- glyph = icons.pixmap(self._GLYPHS.get(self._kind, "exercise"), "#5D6B80", 16)
+ glyph = icons.pixmap(self._GLYPHS.get(self._kind, "exercise"), PALETTE["muted"], 16)
painter.drawPixmap(QRectF(0, 0, 16, 16), glyph, QRectF(glyph.rect()))
painter.end()
@@ -3672,7 +3677,7 @@ class _GenderMark(QWidget):
return
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
- pen = QPen(QColor("#5D6B80"), 1.35)
+ pen = QPen(QColor(PALETTE["muted"]), 1.35)
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
pen.setJoinStyle(Qt.PenJoinStyle.RoundJoin)
painter.setPen(pen)
@@ -3737,7 +3742,7 @@ class _ReceptionQueueSpinner(QWidget):
del event
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
- pen = QPen(QColor("#1769E8"), 2.2)
+ pen = QPen(QColor(PALETTE["accent"]), 2.2)
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
painter.setPen(pen)
painter.drawArc(QRectF(2, 2, 14, 14), self._angle * 16, 250 * 16)
@@ -3873,15 +3878,15 @@ class QueueRow(QWidget):
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
rect = QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5)
if self._selected:
- painter.setBrush(QColor("#EAF2FF"))
- painter.setPen(QPen(QColor("#E5ECF6"), 1))
+ painter.setBrush(QColor(PALETTE["accent_soft"]))
+ painter.setPen(QPen(QColor(PALETTE["line"]), 1))
else:
- painter.setBrush(QColor("#FFFFFF"))
- painter.setPen(QPen(QColor("#E5ECF6"), 1))
- painter.drawRoundedRect(rect, 6, 6)
+ painter.setBrush(QColor(PALETTE["surface"]))
+ painter.setPen(QPen(QColor(PALETTE["line"]), 1))
+ painter.drawRoundedRect(rect, 10, 10)
if self._selected:
painter.setPen(Qt.PenStyle.NoPen)
- painter.setBrush(QColor("#1769E8"))
+ painter.setBrush(QColor(PALETTE["accent"]))
painter.drawRoundedRect(QRectF(1.2, 1, 3.2, self.height() - 2), 1.6, 1.6)
@@ -4074,7 +4079,7 @@ class ReceptionDailyRecordsPanel(DailyRecordPanel):
font = item.font()
font.setWeight(QFont.Weight.DemiBold if high else QFont.Weight.Normal)
item.setFont(font)
- item.setForeground(QBrush(QColor("#BE4B58" if high else "#273244")))
+ item.setForeground(QBrush(QColor(PALETTE["danger"] if high else PALETTE["text"])))
item.setBackground(
QBrush(
QColor(
@@ -4103,9 +4108,11 @@ class ReceptionPage(QWidget):
super().__init__(parent)
self.setObjectName("ReceptionPage")
self.setStyleSheet(
- (RECEPTION_QSS + RECEPTION_WORKSPACE_QSS).replace("$body_family", body_family())
- .replace("$heading_family", heading_family())
- .replace("$number_family", number_family())
+ clinical_stylesheet(
+ (RECEPTION_QSS + RECEPTION_WORKSPACE_QSS).replace("$body_family", body_family())
+ .replace("$heading_family", heading_family())
+ .replace("$number_family", number_family())
+ )
)
self.repository = repository
self.permissions = permissions
@@ -4262,7 +4269,7 @@ class ReceptionPage(QWidget):
header_layout.addWidget(title)
header_layout.addStretch(1)
self.refresh_button = QPushButton("", header)
- self.refresh_button.setIcon(icons.icon("refresh", "#5D6B80", 18))
+ self.refresh_button.setIcon(icons.icon("refresh", PALETTE["muted"], 18))
self.refresh_button.setObjectName("ReceptionRefreshButton")
self.refresh_button.setFixedSize(34, 32)
self.refresh_button.setAccessibleName("刷新接诊台")
@@ -4454,7 +4461,7 @@ class ReceptionPage(QWidget):
self.video_button.clicked.connect(self._request_video)
actions.addWidget(self.video_button)
self.more_button = QPushButton(hero)
- self.more_button.setIcon(icons.icon("more", "#5D6B80", 16))
+ self.more_button.setIcon(icons.icon("more", PALETTE["muted"], 16))
self.more_button.setIconSize(QSize(16, 16))
self.more_button.setToolTip("更多操作")
self.more_button.setAccessibleName("更多操作")
@@ -5286,7 +5293,9 @@ class ReceptionPage(QWidget):
self.ai_source_label.setTextFormat(Qt.TextFormat.PlainText)
self.ai_source_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
self.ai_source_label.setWordWrap(True)
- self.ai_source_label.setStyleSheet("color: #5B6474; font-size: 11px;")
+ self.ai_source_label.setStyleSheet(clinical_stylesheet(
+ "color: $ds_muted; font-size: 12px;"
+ ))
analysis_layout.addWidget(self.ai_source_label)
self.ai_detail_actions_host = QWidget(analysis_card)
diff --git a/app/src/doctor_workstation/ui/patient_orders_style.py b/app/src/doctor_workstation/ui/patient_orders_style.py
index 925e55d43..89d11ce25 100644
--- a/app/src/doctor_workstation/ui/patient_orders_style.py
+++ b/app/src/doctor_workstation/ui/patient_orders_style.py
@@ -1,119 +1,126 @@
-"""Scoped surfaces for the approved patient order-management workspace."""
-
-from string import Template
-
-from .reception_style import body_family
-
-
-def patient_orders_stylesheet() -> str:
- return Template(_ORDERS).substitute(body=body_family())
-
-
-_ORDERS = """
-#PatientOrdersWorkspace { background: transparent; color: #273244; }
-#OrderWorkspaceContent, #OrderWorkspaceScroll { background: transparent; border: 0; }
-#PatientOrdersWorkspace QLabel, #PatientOrdersWorkspace QPushButton,
-#PatientOrdersWorkspace QToolButton, #PatientOrdersWorkspace QLineEdit,
-#PatientOrdersWorkspace QComboBox, #PatientOrdersWorkspace QDateEdit,
-#PatientOrdersWorkspace QCheckBox, #PatientOrdersWorkspace QTableWidget {
- font-family: "$body"; font-size: 14px; font-weight: 400; color: #273244;
-}
-#PatientOrdersWorkspace QLabel[role="muted"] { font-size: 13px; color: #5D6B80; }
-#PatientOrdersWorkspace QFrame#OrderFilterCard,
-#PatientOrdersWorkspace QFrame#OrderSummaryStrip,
-#PatientOrdersWorkspace QFrame#OrderTableCard {
- background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 8px;
-}
-#PatientOrdersWorkspace QPushButton, #PatientOrdersWorkspace QToolButton {
- min-height: 38px; max-height: 38px; padding: 0 16px; border: 1px solid #DBE5F2;
- border-radius: 5px; background: #FFFFFF; color: #273244;
-}
-#PatientOrdersWorkspace QPushButton:hover, #PatientOrdersWorkspace QToolButton:hover {
- background: #F2F7FF; border-color: #B6CDEE; color: #1555B6;
-}
-#PatientOrdersWorkspace QPushButton:pressed, #PatientOrdersWorkspace QToolButton:pressed { background: #DCEAFF; }
-#PatientOrdersWorkspace QPushButton:focus, #PatientOrdersWorkspace QToolButton:focus { border-color: #75A5F0; }
-#PatientOrdersWorkspace QPushButton#OrderSearchButton,
-#PatientOrdersWorkspace QPushButton#OrderDetailButton {
- color: #FFFFFF; background: #1769E8; border-color: #1769E8;
-}
-#PatientOrdersWorkspace QPushButton#OrderSearchButton:hover,
-#PatientOrdersWorkspace QPushButton#OrderDetailButton:hover { background: #155BCC; border-color: #155BCC; }
-#PatientOrdersWorkspace QPushButton:disabled, #PatientOrdersWorkspace QToolButton:disabled {
- color: #97A4B6; background: #F6F8FC; border-color: #E2E9F2;
-}
-#PatientOrdersWorkspace QLineEdit, #PatientOrdersWorkspace QComboBox,
-#PatientOrdersWorkspace QDateEdit {
- min-height: 38px; max-height: 38px; padding: 0 10px; font-size: 13px;
- background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 5px;
- selection-background-color: #DCEAFF; selection-color: #273244;
-}
-#PatientOrdersWorkspace QLineEdit:focus, #PatientOrdersWorkspace QComboBox:focus,
-#PatientOrdersWorkspace QDateEdit:focus { border-color: #75A5F0; }
-#PatientOrdersWorkspace QLineEdit QToolButton {
- min-height: 0; max-height: 24px; min-width: 0; border: 0; padding: 0; background: transparent;
-}
-#PatientOrdersWorkspace QComboBox { padding-right: 30px; }
-#PatientOrdersWorkspace QComboBox::drop-down { border: 0; width: 28px; background: transparent; }
-#PatientOrdersWorkspace QComboBox::down-arrow { image: none; width: 0; height: 0; }
-#PatientOrdersWorkspace QComboBox QAbstractItemView {
- font-family: "$body"; font-size: 13px; color: #273244; background: #FFFFFF;
- border: 1px solid #DBE5F2; outline: 0; selection-background-color: #EAF2FF; selection-color: #1555B6;
-}
-#PatientOrdersWorkspace QComboBox QAbstractItemView::item { min-height: 30px; padding: 3px 10px; }
-#PatientOrdersWorkspace QDateEdit { padding-right: 26px; }
-#PatientOrdersWorkspace QDateEdit::drop-down { border: 0; width: 24px; background: transparent; }
-#PatientOrdersWorkspace QDateEdit::down-arrow { image: none; width: 0; height: 0; }
-#PatientOrdersWorkspace QDateEdit:disabled { color: #8A97A9; background: #F6F8FC; border-color: #E2E9F2; }
-#PatientOrdersWorkspace QCalendarWidget {
- font-family: "$body"; font-size: 13px; background: #FFFFFF; color: #273244;
-}
-#PatientOrdersWorkspace QCalendarWidget QWidget#qt_calendar_navigationbar { background: #F5F8FD; }
-#PatientOrdersWorkspace QCalendarWidget QToolButton {
- min-height: 28px; max-height: 28px; padding: 0 8px; border: 0; background: transparent;
- font-family: "$body"; font-size: 13px; color: #273244;
-}
-#PatientOrdersWorkspace QCalendarWidget QToolButton:hover { background: #EAF2FF; }
-#PatientOrdersWorkspace QCalendarWidget QAbstractItemView {
- font-family: "$body"; font-size: 13px; background: #FFFFFF; alternate-background-color: #FFFFFF;
- color: #273244; selection-background-color: #1769E8; selection-color: #FFFFFF; outline: 0;
-}
-#PatientOrdersWorkspace QCheckBox { spacing: 9px; font-size: 13px; }
-#PatientOrdersWorkspace QCheckBox::indicator {
- width: 15px; height: 15px; border: 1px solid #C5D5EB; border-radius: 3px; background: #FFFFFF;
-}
-#PatientOrdersWorkspace QCheckBox::indicator:checked { background: #1769E8; border-color: #1769E8; }
-#PatientOrdersWorkspace QCheckBox::indicator:hover { border-color: #75A5F0; }
-#PatientOrdersWorkspace QCheckBox:focus { color: #1555B6; }
-#PatientOrdersWorkspace QFrame#OrderMetricCell { background: transparent; border: 0; }
-#PatientOrdersWorkspace QFrame#OrderMetricDivider { border: 0; background: #DBE5F2; }
-#PatientOrdersWorkspace QLabel[orderMetricCaption="true"] { color: #5D6B80; font-size: 13px; }
-#PatientOrdersWorkspace QLabel[orderMetricValue="true"] { color: #273244; font-size: 18px; font-weight: 500; }
-#PatientOrdersWorkspace QLabel#OrderAmountMetric { color: #1769E8; }
-#PatientOrdersWorkspace QLabel[role="sectionTitle"] { font-size: 14px; font-weight: 600; }
-#PatientOrdersWorkspace QTableWidget#OrderTable {
- border: 1px solid #E6EDF6; border-radius: 0; background: #FFFFFF; alternate-background-color: #FFFFFF;
- selection-background-color: #F5F8FF; selection-color: #273244; gridline-color: #E6EDF6;
-}
-#PatientOrdersWorkspace QTableWidget#OrderTable::item { padding: 0; border: 0; }
-#PatientOrdersWorkspace QTableWidget#OrderTable QHeaderView::section {
- min-height: 44px; padding: 0 16px; background: #F8FAFD; color: #5D6B80;
- border: 0; border-bottom: 1px solid #E1E9F4;
- font-family: "$body"; font-size: 13px; font-weight: 400;
-}
-#PatientOrdersWorkspace QWidget#OrderActionBar { background: #FFFFFF; }
-#PatientOrdersWorkspace QToolButton#OrderActionButton { padding-right: 28px; }
-#PatientOrdersWorkspace QToolButton#OrderActionButton::menu-indicator { image: none; width: 0; height: 0; }
-#PatientOrdersWorkspace QWidget#InfiniteList { background: #FFFFFF; border-top: 1px solid #E6EDF6; }
-#PatientOrdersWorkspace QMenu, QMenu#OrderActionMenu {
- font-family: "$body"; font-size: 13px; color: #273244; background: #FFFFFF;
- border: 1px solid #DBE5F2; padding: 5px;
-}
-#PatientOrdersWorkspace QMenu::item, QMenu#OrderActionMenu::item { padding: 8px 24px; }
-#PatientOrdersWorkspace QMenu::item:selected, QMenu#OrderActionMenu::item:selected { color: #1555B6; background: #EAF2FF; }
-#PatientOrdersWorkspace QScrollBar:vertical { background: #F4F7FC; width: 7px; margin: 0; }
-#PatientOrdersWorkspace QScrollBar:horizontal { background: #F4F7FC; height: 7px; margin: 0; }
-#PatientOrdersWorkspace QScrollBar::handle { background: #C8D5E6; border-radius: 3px; min-width: 24px; min-height: 24px; }
-#PatientOrdersWorkspace QScrollBar::add-line, #PatientOrdersWorkspace QScrollBar::sub-line { width: 0; height: 0; }
-#PatientOrdersWorkspace QScrollBar::add-page, #PatientOrdersWorkspace QScrollBar::sub-page { background: transparent; }
-"""
+"""Scoped surfaces for the approved patient order-management workspace."""
+
+from string import Template
+
+from .design_system import clinical_stylesheet
+from .reception_style import body_family
+
+
+def patient_orders_stylesheet() -> str:
+ return clinical_stylesheet(Template(_ORDERS).safe_substitute(body=body_family()))
+
+
+_ORDERS = """
+#PatientOrdersWorkspace { background: transparent; color: $ds_text; }
+#OrderWorkspaceContent, #OrderWorkspaceScroll { background: transparent; border: 0; }
+#PatientOrdersWorkspace QLabel, #PatientOrdersWorkspace QPushButton,
+#PatientOrdersWorkspace QToolButton, #PatientOrdersWorkspace QLineEdit,
+#PatientOrdersWorkspace QComboBox, #PatientOrdersWorkspace QDateEdit,
+#PatientOrdersWorkspace QCheckBox, #PatientOrdersWorkspace QTableWidget {
+ font-family: "$body"; font-size: 14px; font-weight: 400; color: $ds_text;
+}
+#PatientOrdersWorkspace QLabel[role="muted"] { font-size: 13px; color: $ds_muted; }
+#PatientOrdersWorkspace QFrame#OrderFilterCard,
+#PatientOrdersWorkspace QFrame#OrderTableCard {
+ background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_panel;
+}
+#PatientOrdersWorkspace QFrame#OrderSummaryStrip { background: transparent; border: 0; }
+#PatientOrdersWorkspace QPushButton, #PatientOrdersWorkspace QToolButton {
+ min-height: 38px; max-height: 38px; padding: 0 16px; border: 1px solid transparent;
+ border-radius: $ds_radius_control; background: $ds_surface_alt; color: $ds_text;
+}
+#PatientOrdersWorkspace QPushButton:hover, #PatientOrdersWorkspace QToolButton:hover {
+ background: $ds_surface_alt; border-color: $ds_line_strong; color: $ds_accent;
+}
+#PatientOrdersWorkspace QPushButton:pressed, #PatientOrdersWorkspace QToolButton:pressed { background: $ds_accent_soft; }
+#PatientOrdersWorkspace QPushButton:focus, #PatientOrdersWorkspace QToolButton:focus { border-color: $ds_focus; }
+#PatientOrdersWorkspace QPushButton#OrderSearchButton,
+#PatientOrdersWorkspace QPushButton#OrderDetailButton {
+ color: $ds_surface; background: $ds_accent; border-color: $ds_accent;
+}
+#PatientOrdersWorkspace QPushButton#OrderSearchButton:hover,
+#PatientOrdersWorkspace QPushButton#OrderDetailButton:hover { background: $ds_accent_hover; border-color: $ds_accent_hover; }
+#PatientOrdersWorkspace QPushButton#OrderSearchButton:pressed,
+#PatientOrdersWorkspace QPushButton#OrderDetailButton:pressed { background: $ds_accent_pressed; border-color: $ds_accent_pressed; }
+#PatientOrdersWorkspace QPushButton#OrderSearchButton:focus,
+#PatientOrdersWorkspace QPushButton#OrderDetailButton:focus { border-color: $ds_focus; }
+#PatientOrdersWorkspace QPushButton:disabled, #PatientOrdersWorkspace QToolButton:disabled,
+#PatientOrdersWorkspace QPushButton#OrderSearchButton:disabled,
+#PatientOrdersWorkspace QPushButton#OrderDetailButton:disabled {
+ color: $ds_disabled; background: $ds_disabled_surface; border-color: $ds_line;
+}
+#PatientOrdersWorkspace QLineEdit, #PatientOrdersWorkspace QComboBox,
+#PatientOrdersWorkspace QDateEdit {
+ min-height: 38px; max-height: 38px; padding: 0 10px; font-size: 13px;
+ background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_control;
+ selection-background-color: $ds_accent_soft; selection-color: $ds_text;
+}
+#PatientOrdersWorkspace QLineEdit:focus, #PatientOrdersWorkspace QComboBox:focus,
+#PatientOrdersWorkspace QDateEdit:focus { border-color: $ds_focus; }
+#PatientOrdersWorkspace QLineEdit QToolButton {
+ min-height: 0; max-height: 24px; min-width: 0; border: 0; padding: 0; background: transparent;
+}
+#PatientOrdersWorkspace QComboBox { padding-right: 30px; }
+#PatientOrdersWorkspace QComboBox::drop-down { border: 0; width: 28px; background: transparent; }
+#PatientOrdersWorkspace QComboBox::down-arrow { image: none; width: 0; height: 0; }
+#PatientOrdersWorkspace QComboBox QAbstractItemView {
+ font-family: "$body"; font-size: 13px; color: $ds_text; background: $ds_surface;
+ border: 1px solid $ds_line; outline: 0; selection-background-color: $ds_accent_soft; selection-color: $ds_accent;
+}
+#PatientOrdersWorkspace QComboBox QAbstractItemView::item { min-height: 30px; padding: 3px 10px; }
+#PatientOrdersWorkspace QDateEdit { padding-right: 26px; }
+#PatientOrdersWorkspace QDateEdit::drop-down { border: 0; width: 24px; background: transparent; }
+#PatientOrdersWorkspace QDateEdit::down-arrow { image: none; width: 0; height: 0; }
+#PatientOrdersWorkspace QDateEdit:disabled { color: $ds_disabled; background: $ds_disabled_surface; border-color: $ds_line; }
+#PatientOrdersWorkspace QCalendarWidget {
+ font-family: "$body"; font-size: 13px; background: $ds_surface; color: $ds_text;
+}
+#PatientOrdersWorkspace QCalendarWidget QWidget#qt_calendar_navigationbar { background: $ds_surface_alt; }
+#PatientOrdersWorkspace QCalendarWidget QToolButton {
+ min-height: 28px; max-height: 28px; padding: 0 8px; border: 0; background: transparent;
+ font-family: "$body"; font-size: 13px; color: $ds_text;
+}
+#PatientOrdersWorkspace QCalendarWidget QToolButton:hover { background: $ds_accent_soft; }
+#PatientOrdersWorkspace QCalendarWidget QAbstractItemView {
+ font-family: "$body"; font-size: 13px; background: $ds_surface; alternate-background-color: $ds_surface;
+ color: $ds_text; selection-background-color: $ds_accent; selection-color: $ds_surface; outline: 0;
+}
+#PatientOrdersWorkspace QCheckBox { spacing: 9px; font-size: 13px; }
+#PatientOrdersWorkspace QCheckBox::indicator {
+ width: 15px; height: 15px; border: 1px solid $ds_line_strong; border-radius: 3px; background: $ds_surface;
+}
+#PatientOrdersWorkspace QCheckBox::indicator:checked { background: $ds_accent; border-color: $ds_accent; }
+#PatientOrdersWorkspace QCheckBox::indicator:hover { border-color: $ds_focus; }
+#PatientOrdersWorkspace QCheckBox:focus { color: $ds_accent; }
+#PatientOrdersWorkspace QFrame#OrderMetricCell { background: transparent; border: 0; }
+#PatientOrdersWorkspace QFrame#OrderMetricDivider { border: 0; background: $ds_line; }
+#PatientOrdersWorkspace QLabel[orderMetricCaption="true"] { color: $ds_muted; font-size: 13px; }
+#PatientOrdersWorkspace QLabel[orderMetricValue="true"] { color: $ds_text; font-size: 18px; font-weight: 500; }
+#PatientOrdersWorkspace QLabel#OrderAmountMetric { color: $ds_accent; }
+#PatientOrdersWorkspace QLabel[role="sectionTitle"] { font-size: 14px; font-weight: 600; }
+#PatientOrdersWorkspace QTableWidget#OrderTable {
+ border: 0; border-radius: 0; background: $ds_surface; alternate-background-color: $ds_surface;
+ selection-background-color: $ds_accent_soft; selection-color: $ds_text; gridline-color: $ds_line;
+}
+#PatientOrdersWorkspace QTableWidget#OrderTable::item { padding: 0; border: 0; }
+#PatientOrdersWorkspace QTableWidget#OrderTable QHeaderView::section {
+ min-height: 44px; padding: 0 16px; background: $ds_surface_alt; color: $ds_muted;
+ border: 0; border-bottom: 1px solid $ds_line;
+ font-family: "$body"; font-size: 13px; font-weight: 400;
+}
+#PatientOrdersWorkspace QWidget#OrderActionBar { background: $ds_surface; }
+#PatientOrdersWorkspace QToolButton#OrderActionButton { padding-right: 28px; }
+#PatientOrdersWorkspace QToolButton#OrderActionButton::menu-indicator { image: none; width: 0; height: 0; }
+#PatientOrdersWorkspace QWidget#InfiniteList { background: $ds_surface; border-top: 1px solid $ds_line; }
+#PatientOrdersWorkspace QMenu, QMenu#OrderActionMenu {
+ font-family: "$body"; font-size: 13px; color: $ds_text; background: $ds_surface;
+ border: 1px solid $ds_line; padding: 5px;
+}
+#PatientOrdersWorkspace QMenu::item, QMenu#OrderActionMenu::item { padding: 8px 24px; }
+#PatientOrdersWorkspace QMenu::item:selected, QMenu#OrderActionMenu::item:selected { color: $ds_accent; background: $ds_accent_soft; }
+#PatientOrdersWorkspace QScrollBar:vertical { background: $ds_canvas; width: 7px; margin: 0; }
+#PatientOrdersWorkspace QScrollBar:horizontal { background: $ds_canvas; height: 7px; margin: 0; }
+#PatientOrdersWorkspace QScrollBar::handle { background: $ds_line_strong; border-radius: 3px; min-width: 24px; min-height: 24px; }
+#PatientOrdersWorkspace QScrollBar::add-line, #PatientOrdersWorkspace QScrollBar::sub-line { width: 0; height: 0; }
+#PatientOrdersWorkspace QScrollBar::add-page, #PatientOrdersWorkspace QScrollBar::sub-page { background: transparent; }
+"""
diff --git a/app/src/doctor_workstation/ui/patient_progress_style.py b/app/src/doctor_workstation/ui/patient_progress_style.py
index b9ba83397..906f34f9d 100644
--- a/app/src/doctor_workstation/ui/patient_progress_style.py
+++ b/app/src/doctor_workstation/ui/patient_progress_style.py
@@ -1,54 +1,55 @@
-"""Local typography and surfaces for the approved consultation-progress page."""
-
-from string import Template
-
-from .reception_style import body_family
-
-
-def patient_progress_stylesheet() -> str:
- return Template(_PROGRESS).substitute(body=body_family())
-
-
-_PROGRESS = """
-#PatientProgressWorkspace { background: transparent; color: #273244; }
-#ProgressWorkspaceContent, #ProgressWorkspaceScroll { background: transparent; border: 0; }
-#PatientProgressWorkspace QLabel, #PatientProgressWorkspace QPushButton,
-#PatientProgressWorkspace QTableWidget {
- font-family: "$body"; font-size: 14px; font-weight: 400; color: #273244;
-}
-#PatientProgressWorkspace QLabel[role="muted"] { font-size: 13px; color: #5D6B80; }
-#PatientProgressWorkspace QLabel[role="sectionTitle"] { font-size: 14px; font-weight: 600; }
-#PatientProgressWorkspace QLabel#EmptyStateGlyph {
- font-size: 24px; color: #1769E8; background: #F2F7FF;
- border: 1px solid #DBE5F2; border-radius: 22px;
-}
-#PatientProgressWorkspace QFrame#ProgressOverviewCard,
-#PatientProgressWorkspace QFrame#ProgressScheduleCard,
-#PatientProgressWorkspace QFrame#ProgressQueueCard {
- background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 8px;
-}
-#PatientProgressWorkspace QFrame#ProgressMetricCell { background: transparent; border: 0; }
-#PatientProgressWorkspace QFrame#ProgressMetricDivider { background: #DBE5F2; border: 0; }
-#PatientProgressWorkspace QLabel[progressMetricValue="true"] { font-size: 18px; font-weight: 500; color: #273244; }
-#PatientProgressWorkspace QLabel#ProgressTotalMetric { color: #1769E8; }
-#PatientProgressWorkspace QSplitter#ProgressSplitter { background: transparent; }
-#PatientProgressWorkspace QSplitter#ProgressSplitter::handle { background: transparent; }
-#PatientProgressWorkspace QSplitter#ProgressSplitter::handle:hover { background: #EAF2FF; }
-#PatientProgressWorkspace QTableWidget#ProgressScheduleTable,
-#PatientProgressWorkspace QTableWidget#ProgressQueueTable {
- border: 0; border-radius: 0; background: #FFFFFF; alternate-background-color: #FFFFFF;
- selection-background-color: #F2F7FF; selection-color: #273244; gridline-color: #E6EDF6;
-}
-#PatientProgressWorkspace QTableWidget::item { border: 0; padding: 0; }
-#PatientProgressWorkspace QHeaderView::section {
- min-height: 0; padding: 0 16px; background: #F5F8FD; color: #5D6B80;
- border: 0; border-bottom: 1px solid #E1E9F4;
- font-family: "$body"; font-size: 13px; font-weight: 400;
-}
-#PatientProgressWorkspace QWidget#InfiniteList { background: #FFFFFF; border-top: 1px solid #E6EDF6; }
-#PatientProgressWorkspace QScrollBar:vertical { background: #F4F7FC; width: 7px; margin: 0; }
-#PatientProgressWorkspace QScrollBar:horizontal { background: #F4F7FC; height: 7px; margin: 0; }
-#PatientProgressWorkspace QScrollBar::handle { background: #C8D5E6; border-radius: 3px; min-width: 24px; min-height: 24px; }
-#PatientProgressWorkspace QScrollBar::add-line, #PatientProgressWorkspace QScrollBar::sub-line { width: 0; height: 0; }
-#PatientProgressWorkspace QScrollBar::add-page, #PatientProgressWorkspace QScrollBar::sub-page { background: transparent; }
-"""
+"""Local typography and surfaces for the approved consultation-progress page."""
+
+from string import Template
+
+from .design_system import clinical_stylesheet
+from .reception_style import body_family
+
+
+def patient_progress_stylesheet() -> str:
+ return clinical_stylesheet(Template(_PROGRESS).safe_substitute(body=body_family()))
+
+
+_PROGRESS = """
+#PatientProgressWorkspace { background: transparent; color: $ds_text; }
+#ProgressWorkspaceContent, #ProgressWorkspaceScroll { background: transparent; border: 0; }
+#PatientProgressWorkspace QLabel, #PatientProgressWorkspace QPushButton,
+#PatientProgressWorkspace QTableWidget {
+ font-family: "$body"; font-size: 14px; font-weight: 400; color: $ds_text;
+}
+#PatientProgressWorkspace QLabel[role="muted"] { font-size: 13px; color: $ds_muted; }
+#PatientProgressWorkspace QLabel[role="sectionTitle"] { font-size: 14px; font-weight: 600; }
+#PatientProgressWorkspace QLabel#EmptyStateGlyph {
+ font-size: 24px; color: $ds_accent; background: $ds_surface_alt;
+ border: 1px solid $ds_line; border-radius: $ds_radius_panel;
+}
+#PatientProgressWorkspace QFrame#ProgressScheduleCard,
+#PatientProgressWorkspace QFrame#ProgressQueueCard {
+ background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_panel;
+}
+#PatientProgressWorkspace QFrame#ProgressOverviewCard { background: transparent; border: 0; }
+#PatientProgressWorkspace QFrame#ProgressMetricCell { background: transparent; border: 0; }
+#PatientProgressWorkspace QFrame#ProgressMetricDivider { background: $ds_line; border: 0; }
+#PatientProgressWorkspace QLabel[progressMetricValue="true"] { font-size: 18px; font-weight: 500; color: $ds_text; }
+#PatientProgressWorkspace QLabel#ProgressTotalMetric { color: $ds_accent; }
+#PatientProgressWorkspace QSplitter#ProgressSplitter { background: transparent; }
+#PatientProgressWorkspace QSplitter#ProgressSplitter::handle { background: transparent; }
+#PatientProgressWorkspace QSplitter#ProgressSplitter::handle:hover { background: $ds_accent_soft; }
+#PatientProgressWorkspace QTableWidget#ProgressScheduleTable,
+#PatientProgressWorkspace QTableWidget#ProgressQueueTable {
+ border: 0; border-radius: 0; background: $ds_surface; alternate-background-color: $ds_surface;
+ selection-background-color: $ds_accent_soft; selection-color: $ds_text; gridline-color: $ds_line;
+}
+#PatientProgressWorkspace QTableWidget::item { border: 0; padding: 0; }
+#PatientProgressWorkspace QHeaderView::section {
+ min-height: 0; padding: 0 16px; background: $ds_surface_alt; color: $ds_muted;
+ border: 0; border-bottom: 1px solid $ds_line;
+ font-family: "$body"; font-size: 13px; font-weight: 400;
+}
+#PatientProgressWorkspace QWidget#InfiniteList { background: $ds_surface; border-top: 1px solid $ds_line; }
+#PatientProgressWorkspace QScrollBar:vertical { background: $ds_canvas; width: 7px; margin: 0; }
+#PatientProgressWorkspace QScrollBar:horizontal { background: $ds_canvas; height: 7px; margin: 0; }
+#PatientProgressWorkspace QScrollBar::handle { background: $ds_line_strong; border-radius: 3px; min-width: 24px; min-height: 24px; }
+#PatientProgressWorkspace QScrollBar::add-line, #PatientProgressWorkspace QScrollBar::sub-line { width: 0; height: 0; }
+#PatientProgressWorkspace QScrollBar::add-page, #PatientProgressWorkspace QScrollBar::sub-page { background: transparent; }
+"""
diff --git a/app/src/doctor_workstation/ui/patients_style.py b/app/src/doctor_workstation/ui/patients_style.py
index 8273fb598..545c4e680 100644
--- a/app/src/doctor_workstation/ui/patients_style.py
+++ b/app/src/doctor_workstation/ui/patients_style.py
@@ -1,141 +1,154 @@
-"""Scoped technology-blue surfaces for the approved patient-list workspace."""
-
-from string import Template
-
-from .reception_style import body_family, heading_family
-
-
-def patients_chrome_stylesheet() -> str:
- return Template(_CHROME).substitute(body=body_family(), heading=heading_family())
-
-
-def patient_list_stylesheet() -> str:
- return Template(_LIST).substitute(body=body_family())
-
-
-_CHROME = """
-#PatientsPage { background: #F3F7FD; }
-#PatientsPage QWidget#PageHeader QLabel {
- font-family: "$body"; font-size: 13px; font-weight: 400; color: #5D6B80;
-}
-#PatientsPage QWidget#PageHeader QLabel[role="pageTitle"] {
- font-family: "$heading"; font-size: 20px; font-weight: 600; color: #202C3F;
-}
-#PatientsPage QPushButton#PatientRefreshButton {
- font-family: "$body"; font-size: 14px; font-weight: 400; color: #273244;
- min-height: 38px; max-height: 38px; padding: 0 20px;
- border: 1px solid #DBE5F2; border-radius: 5px; background: #FFFFFF;
-}
-#PatientsPage QPushButton#PatientRefreshButton:hover { background: #F2F7FF; border-color: #B6CDEE; }
-#PatientsPage QTabWidget#PatientWorkspaceTabs::pane { border: 0; background: transparent; top: 0; }
-#PatientsPage QTabWidget#PatientWorkspaceTabs > QTabBar::tab {
- font-family: "$body"; font-size: 14px; font-weight: 400; color: #273244;
- min-width: 84px; min-height: 42px; padding: 0 10px; margin-right: 22px;
- border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: transparent;
-}
-#PatientsPage QTabWidget#PatientWorkspaceTabs > QTabBar::tab:selected {
- color: #1769E8; border-bottom-color: #1769E8; background: transparent;
-}
-#PatientsPage QTabWidget#PatientWorkspaceTabs > QTabBar::tab:hover { color: #1769E8; background: #EAF2FF; }
-"""
-
-_LIST = """
-#PatientListWorkspace { background: transparent; color: #273244; }
-#PatientWorkspaceContent, #PatientWorkspaceScroll { background: transparent; border: 0; }
-#PatientListWorkspace QLabel, #PatientListWorkspace QPushButton,
-#PatientListWorkspace QToolButton, #PatientListWorkspace QDateEdit,
-#PatientListWorkspace QTableWidget, #PatientSearchToolbar QLineEdit,
-#PatientSearchToolbar QPushButton {
- font-family: "$body"; font-size: 14px; font-weight: 400; color: #273244;
-}
-#PatientListWorkspace QLabel[role="muted"], #PatientListWorkspace QLabel[filterLabel="true"] {
- color: #5D6B80; font-size: 13px;
-}
-#PatientListWorkspace QFrame#PatientFilterCard,
-#PatientListWorkspace QFrame#PatientSummaryStrip,
-#PatientListWorkspace QFrame#PatientListCard {
- background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 8px;
-}
-#PatientListWorkspace QPushButton, #PatientSearchToolbar QPushButton {
- min-height: 38px; max-height: 38px; padding: 0 16px;
- border: 1px solid #DBE5F2; border-radius: 5px; background: #FFFFFF;
-}
-#PatientListWorkspace QPushButton:hover, #PatientSearchToolbar QPushButton:hover {
- color: #1555B6; background: #F2F7FF; border-color: #B6CDEE;
-}
-#PatientListWorkspace QPushButton:pressed, #PatientSearchToolbar QPushButton:pressed { background: #DCEAFF; }
-#PatientListWorkspace QPushButton:focus, #PatientSearchToolbar QPushButton:focus { border-color: #75A5F0; }
-#PatientSearchToolbar QPushButton#PatientSearchButton {
- min-height: 38px; max-height: 38px; color: #FFFFFF; background: #1769E8; border-color: #1769E8;
-}
-#PatientSearchToolbar QPushButton#PatientSearchButton:hover { background: #155BCC; }
-#PatientSearchToolbar QLineEdit {
- min-height: 38px; max-height: 38px; padding: 0 8px; background: #FFFFFF;
- border: 1px solid #DBE5F2; border-radius: 5px; selection-background-color: #DCEAFF;
-}
-#PatientSearchToolbar QLineEdit:focus { border-color: #75A5F0; }
-#PatientSearchToolbar QLineEdit QToolButton { border: 0; padding: 0; background: transparent; }
-#PatientListWorkspace QPushButton[patientStatusChip="true"] {
- min-height: 44px; max-height: 44px; padding: 0 16px; font-size: 13px;
- color: #273244; border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: transparent;
-}
-#PatientListWorkspace QPushButton[patientStatusChip="true"]:checked {
- color: #1769E8; border-bottom-color: #1769E8; background: transparent;
-}
-#PatientListWorkspace QPushButton[patientStatusChip="true"]:hover { color: #1769E8; background: #F2F7FF; }
-#PatientListWorkspace QPushButton[patientQuickDate="true"] { padding: 0 12px; font-size: 13px; }
-#PatientListWorkspace QPushButton[patientQuickDate="true"]:checked,
-#PatientListWorkspace QPushButton#PatientCustomDateButton:checked {
- color: #FFFFFF; background: #1769E8; border: 1px solid #1769E8;
-}
-#PatientListWorkspace QDateEdit {
- min-height: 38px; max-height: 38px; padding: 0 8px; font-size: 13px;
- background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 5px;
- selection-background-color: #DCEAFF;
-}
-#PatientListWorkspace QDateEdit:focus { border-color: #75A5F0; }
-#PatientListWorkspace QDateEdit:disabled {
- color: #8A97A9; background: #F6F8FC; border-color: #E2E9F2;
-}
-#PatientListWorkspace QDateEdit::drop-down { border: 0; width: 20px; background: transparent; }
-#PatientListWorkspace QDateEdit::down-arrow { image: none; width: 0; height: 0; }
-#PatientListWorkspace QPushButton[summaryCard="true"] {
- min-height: 64px; max-height: 64px; padding: 0; background: transparent; border: 0; border-radius: 5px;
-}
-#PatientListWorkspace QPushButton[summaryCard="true"]:hover { background: #F2F7FF; }
-#PatientListWorkspace QFrame#PatientSummaryDivider { border: 0; background: #E1E9F4; }
-#PatientListWorkspace QWidget#PatientListHeading { background: transparent; }
-#PatientListWorkspace QLabel[role="sectionTitle"] { font-size: 14px; font-weight: 600; color: #273244; }
-#PatientListWorkspace QTableWidget#PatientTable {
- background: #FFFFFF; alternate-background-color: #FFFFFF; border: 0; border-radius: 0;
- selection-background-color: #EAF2FF; selection-color: #273244; gridline-color: #E6EDF6;
-}
-#PatientListWorkspace QTableWidget#PatientTable::item { padding: 0; border: 0; }
-#PatientListWorkspace QTableWidget#PatientTable QHeaderView::section {
- min-height: 41px; padding: 0 10px; background: #F5F8FD; color: #5D6B80;
- border: 0; border-top: 1px solid #E6EDF6; border-bottom: 1px solid #E1E9F4;
- font-family: "$body"; font-size: 13px; font-weight: 400;
-}
-#PatientListWorkspace QWidget#RowActions, #PatientListWorkspace QWidget#PatientSelectorHost { background: transparent; }
-#PatientListWorkspace QPushButton[rowAction="true"],
-#PatientListWorkspace QToolButton#RowActionsMore {
- min-height: 28px; max-height: 28px; padding: 0 5px; border: 0;
- border-radius: 4px; background: transparent; color: #1769E8; font-size: 13px;
-}
-#PatientListWorkspace QToolButton#RowActionsMore { color: #273244; padding-right: 16px; }
-#PatientListWorkspace QPushButton[rowAction="true"]:hover,
-#PatientListWorkspace QToolButton#RowActionsMore:hover { background: #DCEAFF; }
-#PatientListWorkspace QMenu { background: #FFFFFF; color: #273244; border: 1px solid #DBE5F2; padding: 4px; }
-#PatientListWorkspace QMenu::item { padding: 7px 22px; font-size: 13px; }
-#PatientListWorkspace QMenu::item:selected { background: #EAF2FF; color: #1555B6; }
-#PatientListWorkspace QCheckBox[patientSelector="true"]::indicator {
- width: 13px; height: 13px; background: #FFFFFF; border: 1px solid #CBDAED; border-radius: 3px;
-}
-#PatientListWorkspace QCheckBox[patientSelector="true"]::indicator:checked { background: #1769E8; border-color: #1769E8; }
-#PatientListWorkspace QWidget#InfiniteList { background: #FFFFFF; border-top: 1px solid #E6EDF6; }
-#PatientListWorkspace QScrollBar:vertical { background: #F4F7FC; width: 7px; margin: 0; }
-#PatientListWorkspace QScrollBar:horizontal { background: #F4F7FC; height: 7px; margin: 0; }
-#PatientListWorkspace QScrollBar::handle { background: #C8D5E6; border-radius: 3px; min-width: 24px; min-height: 24px; }
-#PatientListWorkspace QScrollBar::add-line, #PatientListWorkspace QScrollBar::sub-line { width: 0; height: 0; }
-#PatientListWorkspace QScrollBar::add-page, #PatientListWorkspace QScrollBar::sub-page { background: transparent; }
-"""
+"""Quiet clinical surfaces for the patient-list workspace."""
+
+from string import Template
+
+from .design_system import clinical_stylesheet
+from .reception_style import body_family, heading_family
+
+
+def patients_chrome_stylesheet() -> str:
+ return clinical_stylesheet(Template(_CHROME).safe_substitute(body=body_family(), heading=heading_family()))
+
+
+def patient_list_stylesheet() -> str:
+ return clinical_stylesheet(Template(_LIST).safe_substitute(body=body_family()))
+
+
+_CHROME = """
+#PatientsPage { background: $ds_canvas; }
+#PatientsPage QWidget#PageHeader QLabel {
+ font-family: "$body"; font-size: 13px; font-weight: 400; color: $ds_muted;
+}
+#PatientsPage QWidget#PageHeader QLabel[role="pageTitle"] {
+ font-family: "$heading"; font-size: 20px; font-weight: 600; color: $ds_heading;
+}
+#PatientsPage QPushButton#PatientRefreshButton {
+ font-family: "$body"; font-size: 14px; font-weight: 400; color: $ds_text;
+ min-height: 38px; max-height: 38px; padding: 0 20px;
+ border: 1px solid transparent; border-radius: $ds_radius_control; background: $ds_surface_alt;
+}
+#PatientsPage QPushButton#PatientRefreshButton:hover { background: $ds_surface_alt; border-color: $ds_line_strong; }
+#PatientsPage QPushButton#PatientRefreshButton:pressed { background: $ds_accent_soft; }
+#PatientsPage QPushButton#PatientRefreshButton:focus { border-color: $ds_focus; }
+#PatientsPage QPushButton#PatientRefreshButton:disabled { color: $ds_disabled; background: $ds_disabled_surface; }
+#PatientsPage QTabWidget#PatientWorkspaceTabs::pane { border: 0; background: transparent; top: 0; }
+#PatientsPage QTabWidget#PatientWorkspaceTabs > QTabBar::tab {
+ font-family: "$body"; font-size: 14px; font-weight: 400; color: $ds_text;
+ min-width: 84px; min-height: 42px; padding: 0 10px; margin-right: 22px;
+ border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: transparent;
+}
+#PatientsPage QTabWidget#PatientWorkspaceTabs > QTabBar::tab:selected {
+ color: $ds_accent; border-bottom-color: $ds_accent; background: transparent;
+}
+#PatientsPage QTabWidget#PatientWorkspaceTabs > QTabBar::tab:hover { color: $ds_accent; background: $ds_accent_soft; }
+"""
+
+_LIST = """
+#PatientListWorkspace { background: transparent; color: $ds_text; }
+#PatientWorkspaceContent, #PatientWorkspaceScroll { background: transparent; border: 0; }
+#PatientListWorkspace QLabel, #PatientListWorkspace QPushButton,
+#PatientListWorkspace QToolButton, #PatientListWorkspace QDateEdit,
+#PatientListWorkspace QTableWidget, #PatientSearchToolbar QLineEdit,
+#PatientSearchToolbar QPushButton {
+ font-family: "$body"; font-size: 14px; font-weight: 400; color: $ds_text;
+}
+#PatientListWorkspace QLabel[role="muted"], #PatientListWorkspace QLabel[filterLabel="true"] {
+ color: $ds_muted; font-size: 13px;
+}
+#PatientListWorkspace QFrame#PatientFilterCard,
+#PatientListWorkspace QFrame#PatientListCard {
+ background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_panel;
+}
+#PatientListWorkspace QFrame#PatientSummaryStrip { background: transparent; border: 0; }
+#PatientListWorkspace QPushButton, #PatientSearchToolbar QPushButton {
+ min-height: 38px; max-height: 38px; padding: 0 16px;
+ border: 1px solid transparent; border-radius: $ds_radius_control; background: $ds_surface_alt;
+}
+#PatientListWorkspace QPushButton:hover, #PatientSearchToolbar QPushButton:hover {
+ color: $ds_accent; background: $ds_surface_alt; border-color: $ds_line_strong;
+}
+#PatientListWorkspace QPushButton:pressed, #PatientSearchToolbar QPushButton:pressed { background: $ds_accent_soft; }
+#PatientListWorkspace QPushButton:focus, #PatientSearchToolbar QPushButton:focus { border-color: $ds_focus; }
+#PatientSearchToolbar QPushButton#PatientSearchButton {
+ min-height: 38px; max-height: 38px; color: $ds_surface; background: $ds_accent; border-color: $ds_accent;
+}
+#PatientSearchToolbar QPushButton#PatientSearchButton:hover { background: $ds_accent_hover; }
+#PatientSearchToolbar QPushButton#PatientSearchButton:pressed { background: $ds_accent_pressed; }
+#PatientSearchToolbar QPushButton#PatientSearchButton:focus { border-color: $ds_focus; }
+#PatientSearchToolbar QLineEdit {
+ min-height: 38px; max-height: 38px; padding: 0 8px; background: $ds_surface;
+ border: 1px solid $ds_line; border-radius: $ds_radius_control; selection-background-color: $ds_accent_soft;
+}
+#PatientSearchToolbar QLineEdit:focus { border-color: $ds_focus; }
+#PatientSearchToolbar QLineEdit QToolButton { border: 0; padding: 0; background: transparent; }
+#PatientListWorkspace QPushButton[patientStatusChip="true"] {
+ min-height: 44px; max-height: 44px; padding: 0 16px; font-size: 13px;
+ color: $ds_text; border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: transparent;
+}
+#PatientListWorkspace QPushButton[patientStatusChip="true"]:checked {
+ color: $ds_accent; border-bottom-color: $ds_accent; background: transparent;
+}
+#PatientListWorkspace QPushButton[patientStatusChip="true"]:hover { color: $ds_accent; background: $ds_surface_alt; }
+#PatientListWorkspace QPushButton[patientStatusChip="true"]:focus { background: $ds_accent_soft; }
+#PatientListWorkspace QPushButton[patientQuickDate="true"] { padding: 0 12px; font-size: 13px; }
+#PatientListWorkspace QPushButton[patientQuickDate="true"]:checked,
+#PatientListWorkspace QPushButton#PatientCustomDateButton:checked {
+ color: $ds_accent; background: $ds_accent_soft; border: 1px solid transparent; font-weight: 600;
+}
+#PatientListWorkspace QPushButton[patientQuickDate="true"]:focus,
+#PatientListWorkspace QPushButton#PatientCustomDateButton:focus { border-color: $ds_focus; }
+#PatientListWorkspace QDateEdit {
+ min-height: 38px; max-height: 38px; padding: 0 8px; font-size: 13px;
+ background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_control;
+ selection-background-color: $ds_accent_soft;
+}
+#PatientListWorkspace QDateEdit:focus { border-color: $ds_focus; }
+#PatientListWorkspace QDateEdit:disabled {
+ color: $ds_disabled; background: $ds_disabled_surface; border-color: $ds_line;
+}
+#PatientListWorkspace QDateEdit::drop-down { border: 0; width: 20px; background: transparent; }
+#PatientListWorkspace QDateEdit::down-arrow { image: none; width: 0; height: 0; }
+#PatientListWorkspace QPushButton[summaryCard="true"] {
+ min-height: 64px; max-height: 64px; padding: 0; background: transparent;
+ border: 1px solid transparent; border-radius: $ds_radius_control;
+}
+#PatientListWorkspace QPushButton[summaryCard="true"]:hover { background: $ds_surface_alt; }
+#PatientListWorkspace QPushButton[summaryCard="true"]:focus { border-color: $ds_focus; }
+#PatientListWorkspace QFrame#PatientSummaryDivider { border: 0; background: $ds_line; }
+#PatientListWorkspace QWidget#PatientListHeading { background: transparent; }
+#PatientListWorkspace QLabel[role="sectionTitle"] { font-size: 14px; font-weight: 600; color: $ds_text; }
+#PatientListWorkspace QTableWidget#PatientTable {
+ background: $ds_surface; alternate-background-color: $ds_surface; border: 0; border-radius: 0;
+ selection-background-color: $ds_accent_soft; selection-color: $ds_text; gridline-color: $ds_line;
+}
+#PatientListWorkspace QTableWidget#PatientTable::item { padding: 0; border: 0; }
+#PatientListWorkspace QTableWidget#PatientTable QHeaderView::section {
+ min-height: 41px; padding: 0 10px; background: $ds_surface_alt; color: $ds_muted;
+ border: 0; border-top: 1px solid $ds_line; border-bottom: 1px solid $ds_line;
+ font-family: "$body"; font-size: 13px; font-weight: 400;
+}
+#PatientListWorkspace QWidget#RowActions, #PatientListWorkspace QWidget#PatientSelectorHost { background: transparent; }
+#PatientListWorkspace QPushButton[rowAction="true"],
+#PatientListWorkspace QToolButton#RowActionsMore {
+ min-height: 28px; max-height: 28px; padding: 0 5px; border: 1px solid transparent;
+ border-radius: $ds_radius_small; background: transparent; color: $ds_accent; font-size: 13px;
+}
+#PatientListWorkspace QToolButton#RowActionsMore { color: $ds_text; padding-right: 16px; }
+#PatientListWorkspace QPushButton[rowAction="true"]:hover,
+#PatientListWorkspace QToolButton#RowActionsMore:hover { background: $ds_accent_soft; }
+#PatientListWorkspace QPushButton[rowAction="true"]:focus,
+#PatientListWorkspace QToolButton#RowActionsMore:focus { border-color: $ds_focus; }
+#PatientListWorkspace QMenu { background: $ds_surface; color: $ds_text; border: 1px solid $ds_line; padding: 4px; }
+#PatientListWorkspace QMenu::item { padding: 7px 22px; font-size: 13px; }
+#PatientListWorkspace QMenu::item:selected { background: $ds_accent_soft; color: $ds_accent; }
+#PatientListWorkspace QCheckBox[patientSelector="true"]::indicator {
+ width: 13px; height: 13px; background: $ds_surface; border: 1px solid $ds_line_strong; border-radius: 3px;
+}
+#PatientListWorkspace QCheckBox[patientSelector="true"]::indicator:checked { background: $ds_accent; border-color: $ds_accent; }
+#PatientListWorkspace QWidget#InfiniteList { background: $ds_surface; border-top: 1px solid $ds_line; }
+#PatientListWorkspace QScrollBar:vertical { background: $ds_canvas; width: 7px; margin: 0; }
+#PatientListWorkspace QScrollBar:horizontal { background: $ds_canvas; height: 7px; margin: 0; }
+#PatientListWorkspace QScrollBar::handle { background: $ds_line_strong; border-radius: 3px; min-width: 24px; min-height: 24px; }
+#PatientListWorkspace QScrollBar::add-line, #PatientListWorkspace QScrollBar::sub-line { width: 0; height: 0; }
+#PatientListWorkspace QScrollBar::add-page, #PatientListWorkspace QScrollBar::sub-page { background: transparent; }
+"""
diff --git a/app/src/doctor_workstation/ui/prescription_library_style.py b/app/src/doctor_workstation/ui/prescription_library_style.py
index 33255224b..3d018330e 100644
--- a/app/src/doctor_workstation/ui/prescription_library_style.py
+++ b/app/src/doctor_workstation/ui/prescription_library_style.py
@@ -1,410 +1,419 @@
-"""Local technology-blue rendering for the approved prescription library."""
-
-from __future__ import annotations
-
-from collections.abc import Iterable, Sequence
-from string import Template
-from typing import Any
-
-from PySide6.QtCore import QEvent, QModelIndex, QRectF, QSize, Qt, QTimer
-from PySide6.QtGui import QColor, QFont, QFontMetrics, QIcon, QPainter
-from PySide6.QtWidgets import (
- QComboBox,
- QPushButton,
- QStyle,
- QStyledItemDelegate,
- QToolTip,
- QWidget,
-)
-
-from .reception_style import body_family, heading_family
-from .widgets import SortableTable, TableColumn, first_value
-
-
-def library_stylesheet() -> str:
- return Template(_LIBRARY).substitute(body=body_family(), heading=heading_family())
-
-
-def _library_icon(kind: str, color: str = "#1769E8", size: int = 15) -> QIcon:
- # Defer the page helper lookup so importing this module alone does not
- # recurse through pages.__init__ and the library page's own style import.
- from .pages.prescriptions import _painted_icon
-
- result = QIcon()
- for mode, tint in (
- (QIcon.Mode.Normal, color),
- (QIcon.Mode.Active, color),
- (QIcon.Mode.Selected, color),
- (QIcon.Mode.Disabled, "#A4ADBA"),
- ):
- pixmap = _painted_icon(kind, tint, size).pixmap(QSize(size, size))
- for state in (QIcon.State.Off, QIcon.State.On):
- result.addPixmap(pixmap, mode, state)
- return result
-
-
-class LibraryComboBox(QComboBox):
- """Keep native combo interaction while painting the local caret."""
-
- def paintEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
- super().paintEvent(event)
- painter = QPainter(self)
- try:
- rect = QRectF(self.width() - 25, (self.height() - 14) / 2, 14, 14)
- mode = QIcon.Mode.Normal if self.isEnabled() else QIcon.Mode.Disabled
- _library_icon("chevron_down", "#5D6B80", 14).paint(painter, rect.toRect(), mode=mode)
- finally:
- painter.end()
-
-
-class LibraryTable(SortableTable):
- """Fit readable columns while preserving actions and selected template IDs."""
-
- _FLEX_COLUMNS = ((1, 2), (4, 5), (5, 2))
-
- def __init__(self, columns: Sequence[TableColumn], parent: QWidget | None = None) -> None:
- super().__init__(columns, parent)
- self.horizontalHeader().setStretchLastSection(False)
- self._minimum_widths = tuple(column.width for column in self.columns)
- self._manual_widths: dict[int, int] = {}
- self._fitting_columns = False
- self._fit_timer = QTimer(self)
- self._fit_timer.setSingleShot(True)
- self._fit_timer.timeout.connect(self._fit_columns)
- self.horizontalHeader().sectionResized.connect(self._column_resized)
- self.viewport().installEventFilter(self)
-
- def eventFilter(self, watched: Any, event: QEvent) -> bool: # noqa: N802
- if watched is self.viewport() and event.type() in {QEvent.Type.Resize, QEvent.Type.Show}:
- self._schedule_column_fit()
- return super().eventFilter(watched, event)
-
- def _schedule_column_fit(self) -> None:
- if not self._fit_timer.isActive():
- self._fit_timer.start(0)
-
- def _column_resized(self, column: int, _old_size: int, size: int) -> None:
- if self._fitting_columns:
- return
- self._manual_widths[column] = max(self._minimum_widths[column], size)
- self._schedule_column_fit()
-
- def _fit_columns(self) -> None:
- widths = [self._manual_widths.get(column, minimum)
- for column, minimum in enumerate(self._minimum_widths)]
- extra = max(0, self.viewport().width() - sum(widths))
- flexible = [(column, weight) for column, weight in self._FLEX_COLUMNS
- if column not in self._manual_widths]
- # If every text column was manually sized, keep those preferences as
- # minimums and let the herb preview absorb any remaining wide-screen space.
- flexible = flexible or [(4, 1)]
- total_weight = sum(weight for _column, weight in flexible)
- for column, weight in flexible:
- widths[column] += extra * weight // total_weight
- widths[flexible[0][0]] += max(0, self.viewport().width() - sum(widths))
- if widths == [self.columnWidth(column) for column in range(self.columnCount())]:
- return
- self._fitting_columns = True
- try:
- for column, width in enumerate(widths):
- self.setColumnWidth(column, width)
- finally:
- self._fitting_columns = False
-
- def set_rows(self, rows: Iterable[Any]) -> None:
- selected_id = first_value(self.current_data(), "id", "template_id", default=None)
- super().set_rows(rows)
- # The shared table restores an unsorted row index after enabling sort.
- # Locate the same source object in the finished visual order instead.
- if selected_id is not None:
- for row_index in range(self.rowCount()):
- item = self.item(row_index, 0)
- row = item.data(Qt.ItemDataRole.UserRole) if item is not None else None
- row_id = first_value(row, "id", "template_id", default=None)
- if row_id is not None and str(row_id) == str(selected_id):
- self.selectRow(row_index)
- return
- self.clearSelection()
- self.setCurrentCell(-1, -1)
-
- def setCellWidget(self, row: int, column: int, widget: QWidget | None) -> None: # noqa: N802
- super().setCellWidget(row, column, widget)
- if widget is None or column != 9:
- return
- widget.setObjectName("PrescriptionLibraryTableCellHost")
- widget.setAutoFillBackground(False)
- glyphs = {
- "查看处方模板": "eye",
- "AI 解释": "spark",
- "编辑处方模板": "pencil",
- "删除处方模板": "trash",
- }
- for button in widget.findChildren(QPushButton):
- if not button.property("rowAction"):
- continue
- glyph = glyphs.get(button.accessibleName()) or glyphs.get(button.toolTip())
- if glyph is not None:
- color = "#BE4657" if button.property("danger") else "#1769E8"
- button.setIcon(_library_icon(glyph, color, button.iconSize().width()))
-
-
-def _library_font(size: int = 14, *, medium: bool = False) -> QFont:
- font = QFont(heading_family() if medium else body_family())
- font.setPixelSize(size)
- font.setWeight(QFont.Weight.Medium if medium else QFont.Weight.Normal)
- return font
-
-
-def _elide(text: str, metrics: QFontMetrics, width: int) -> str:
- return metrics.elidedText(text, Qt.TextElideMode.ElideRight, max(1, width))
-
-
-def _herb_lines(text: str, metrics: QFontMetrics, width: int) -> list[str]:
- """Wrap between complete herb entries; elide only the displayed lines."""
- entries = text.split("、")
- first = entries[0]
- next_index = 1
- while next_index < min(2, len(entries)):
- candidate = first + "、" + entries[next_index]
- if metrics.horizontalAdvance(candidate) > width:
- break
- first = candidate
- next_index += 1
- lines = [_elide(first, metrics, width)]
- if next_index < len(entries):
- lines.append(_elide("、".join(entries[next_index:]), metrics, width))
- return lines
-
-
-def _name_lines(text: str, metrics: QFontMetrics, width: int) -> list[str]:
- if metrics.horizontalAdvance(text) <= width:
- return [text]
- split = 1
- while split < len(text) and metrics.horizontalAdvance(text[: split + 1]) <= width:
- split += 1
- return [_elide(text[:split], metrics, width), _elide(text[split:], metrics, width)]
-
-
-class LibraryItemDelegate(QStyledItemDelegate):
- """Paint the ten existing columns without changing display or source roles."""
-
- def sizeHint(self, option: Any, index: QModelIndex) -> QSize: # noqa: N802
- size = super().sizeHint(option, index)
- size.setHeight(78)
- return size
-
- def helpEvent(self, event: Any, view: Any, option: Any, index: QModelIndex) -> bool: # noqa: N802
- if event is not None and index.isValid() and index.column() != 9:
- text = index.data(Qt.ItemDataRole.ToolTipRole) or index.data(Qt.ItemDataRole.DisplayRole)
- if text:
- QToolTip.showText(event.globalPos(), str(text), view)
- return True
- return super().helpEvent(event, view, option, index)
-
- @staticmethod
- def _paint_lines(
- painter: QPainter,
- rect: QRectF,
- lines: list[str],
- *,
- secondary_muted: bool = False,
- ) -> None:
- line_height = 26
- top = rect.center().y() - len(lines) * line_height / 2
- for line_index, line in enumerate(lines):
- if secondary_muted and line_index:
- painter.setFont(_library_font(13))
- painter.setPen(QColor("#5D6B80"))
- line_rect = QRectF(rect.left(), top + line_index * line_height, rect.width(), line_height)
- painter.drawText(line_rect, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, line)
-
- def paint(self, painter: QPainter, option: Any, index: QModelIndex) -> None:
- painter.save()
- try:
- painter.setClipRect(option.rect)
- selected = bool(option.state & QStyle.StateFlag.State_Selected)
- hovered = bool(option.state & QStyle.StateFlag.State_MouseOver)
- background = "#F2F7FF" if selected else "#F8FAFE" if hovered else "#FFFFFF"
- painter.fillRect(option.rect, QColor(background))
- painter.setPen(QColor("#E6EDF6"))
- painter.drawLine(option.rect.bottomLeft(), option.rect.bottomRight())
- if selected and index.column() == 0:
- stripe = QRectF(option.rect.left(), option.rect.top(), 3, option.rect.height() - 1)
- painter.fillRect(stripe, QColor("#1769E8"))
- if option.state & QStyle.StateFlag.State_HasFocus:
- painter.setPen(QColor("#75A5F0"))
- painter.setBrush(Qt.BrushStyle.NoBrush)
- painter.drawRect(option.rect.adjusted(1, 1, -2, -2))
-
- column = index.column()
- if column == 9:
- return
- rect = QRectF(option.rect.adjusted(12, 0, -12, -1))
- if rect.width() <= 0:
- return
- value = index.data(Qt.ItemDataRole.DisplayRole)
- text = "" if value is None else str(value)
- font = _library_font(medium=column == 1)
- painter.setFont(font)
- painter.setPen(QColor("#273244"))
- metrics = QFontMetrics(font)
- width = int(rect.width())
-
- if column == 2:
- painter.setFont(_library_font(13))
- metrics = painter.fontMetrics()
- label = _elide(text, metrics, width - 12)
- pill_width = min(rect.width(), metrics.horizontalAdvance(label) + 14)
- pill = QRectF(rect.center().x() - pill_width / 2, rect.center().y() - 12, pill_width, 24)
- painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
- painter.setPen(Qt.PenStyle.NoPen)
- painter.setBrush(QColor("#EAF2FF"))
- painter.drawRoundedRect(pill, 4, 4)
- painter.setPen(QColor("#1769E8"))
- painter.drawText(pill, Qt.AlignmentFlag.AlignCenter, label)
- elif column == 6:
- glyph = "users" if text == "所有人可见" else "lock"
- icon_rect = QRectF(rect.left(), rect.center().y() - 7, 14, 14)
- _library_icon(glyph, "#5D6B80", 14).paint(painter, icon_rect.toRect())
- label_rect = rect.adjusted(22, 0, 0, 0)
- painter.drawText(
- label_rect,
- Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
- _elide(text, metrics, int(label_rect.width())),
- )
- elif column == 4:
- self._paint_lines(painter, rect, _herb_lines(text, metrics, width))
- elif column == 8:
- parts = text.splitlines() if "\n" in text else text.rsplit(" ", 1)
- lines = [_elide(parts[0], metrics, width)]
- if len(parts) > 1:
- lines.append(_elide(" ".join(parts[1:]), QFontMetrics(_library_font(13)), width))
- self._paint_lines(painter, rect, lines, secondary_muted=True)
- elif column == 1:
- self._paint_lines(painter, rect, _name_lines(text, metrics, width))
- else:
- alignment = Qt.AlignmentFlag.AlignCenter if column in (0, 3, 5) else (
- Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter
- )
- painter.drawText(rect, alignment, _elide(text, metrics, width))
- finally:
- painter.restore()
-
-
-_LIBRARY = """
-#PrescriptionLibraryPage { background: #F3F7FD; color: #273244; }
-#PrescriptionLibraryPage QWidget#PrescriptionLibraryContent,
-#PrescriptionLibraryPage QScrollArea#PrescriptionLibraryScroll,
-#PrescriptionLibraryPage QScrollArea#PrescriptionLibraryToolbarScroll {
- background: transparent; border: 0;
-}
-#PrescriptionLibraryPage QLabel, #PrescriptionLibraryPage QPushButton,
-#PrescriptionLibraryPage QLineEdit, #PrescriptionLibraryPage QComboBox,
-#PrescriptionLibraryPage QTableWidget {
- font-family: "$body"; font-size: 14px; font-weight: 400; color: #273244;
-}
-#PrescriptionLibraryPage QLabel[role="pageTitle"] {
- font-family: "$heading"; font-size: 20px; font-weight: 600; color: #202C3F;
-}
-#PrescriptionLibraryPage QLabel[role="muted"] { color: #5D6B80; font-size: 13px; }
-#PrescriptionLibraryPage QFrame#MetricCard,
-#PrescriptionLibraryPage QFrame#PrescriptionLibraryFilterBar,
-#PrescriptionLibraryPage QFrame#PrescriptionLibraryTableCard {
- background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 8px;
-}
-#PrescriptionLibraryPage QFrame#MetricCard QLabel[role="metricTitle"] {
- font-family: "$body"; color: #5D6B80; font-size: 13px; font-weight: 400;
-}
-#PrescriptionLibraryPage QFrame#MetricCard QLabel[role="metricValue"] {
- font-family: "$heading"; color: #273244; font-size: 18px; font-weight: 600;
-}
-#PrescriptionLibraryPage QFrame#MetricCard QLabel[metricIcon="true"] {
- border: 0; border-radius: 0; background: transparent;
-}
-#PrescriptionLibraryPage QPushButton {
- min-height: 38px; max-height: 38px; padding: 0 16px; border-radius: 5px;
- border: 1px solid #DBE5F2; background: #FFFFFF; color: #273244;
-}
-#PrescriptionLibraryPage QPushButton:hover { background: #F2F7FF; border-color: #B6CDEE; color: #1555B6; }
-#PrescriptionLibraryPage QPushButton:pressed { background: #DCEAFF; }
-#PrescriptionLibraryPage QPushButton:focus { border-color: #75A5F0; }
-#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton,
-#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton {
- background: #1769E8; border-color: #1769E8; color: #FFFFFF;
-}
-#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton:hover,
-#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton:hover {
- background: #155BCC; border-color: #155BCC;
-}
-#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton:pressed,
-#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton:pressed {
- background: #124EA9; border-color: #124EA9;
-}
-#PrescriptionLibraryPage QPushButton[variant="danger"] { color: #BE4657; border-color: #E9D8DE; }
-#PrescriptionLibraryPage QPushButton:disabled,
-#PrescriptionLibraryPage QPushButton[variant="danger"]:disabled {
- color: #97A4B6; background: #F6F8FC; border-color: #E2E9F2;
-}
-#PrescriptionLibraryPage QLineEdit, #PrescriptionLibraryPage QComboBox {
- min-height: 38px; max-height: 38px; padding: 0 12px; border: 1px solid #DBE5F2;
- border-radius: 5px; background: #FFFFFF; color: #273244;
- selection-background-color: #DCEAFF; selection-color: #273244;
-}
-#PrescriptionLibraryPage QLineEdit:focus, #PrescriptionLibraryPage QComboBox:focus { border-color: #75A5F0; }
-#PrescriptionLibraryPage QLineEdit QToolButton { border: 0; background: transparent; padding: 0; }
-#PrescriptionLibraryPage QComboBox { padding-right: 30px; font-size: 13px; }
-#PrescriptionLibraryPage QComboBox::drop-down { width: 28px; border: 0; background: transparent; }
-#PrescriptionLibraryPage QComboBox::down-arrow { image: none; width: 0; height: 0; }
-#PrescriptionLibraryPage QComboBox:disabled { color: #97A4B6; background: #F6F8FC; }
-#PrescriptionLibraryPage QComboBox QAbstractItemView {
- font-family: "$body"; font-size: 13px; color: #273244; background: #FFFFFF;
- border: 1px solid #DBE5F2; outline: 0; selection-background-color: #EAF2FF; selection-color: #1555B6;
-}
-#PrescriptionLibraryPage QComboBox QAbstractItemView::item { min-height: 30px; padding: 3px 10px; }
-#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar { background: transparent; border: 0; }
-#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton { padding: 0 12px; font-size: 13px; }
-#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton[toolbarTab="true"] {
- min-width: 80px; min-height: 40px; max-height: 40px; padding: 0 10px; margin-right: 8px;
- background: transparent; border: 0; border-bottom: 2px solid transparent;
- border-radius: 0; color: #273244; font-size: 14px;
-}
-#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton[toolbarTab="true"]:checked {
- color: #1769E8; border-bottom-color: #1769E8;
-}
-#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton[toolbarTab="true"]:hover {
- color: #1555B6; background: #F2F7FF;
-}
-#PrescriptionLibraryPage QTableWidget {
- border: 0; background: #FFFFFF; alternate-background-color: #FFFFFF;
- selection-background-color: #F2F7FF; selection-color: #273244; gridline-color: #E6EDF6;
-}
-#PrescriptionLibraryPage QTableWidget::item { padding: 0; border: 0; }
-#PrescriptionLibraryPage QHeaderView::section {
- min-height: 0; padding: 0 12px; background: #F5F8FD; color: #5D6B80;
- border: 0; border-bottom: 1px solid #DBE5F2;
- font-family: "$body"; font-size: 13px; font-weight: 400;
-}
-#PrescriptionLibraryPage QWidget#PrescriptionLibraryTableCellHost { background: transparent; border: 0; }
-#PrescriptionLibraryPage QPushButton[rowAction="true"] {
- min-width: 28px; max-width: 28px; min-height: 28px; max-height: 28px;
- padding: 0; border: 1px solid transparent; border-radius: 4px; background: transparent;
-}
-#PrescriptionLibraryPage QPushButton[rowAction="true"]:hover { background: #EAF2FF; border-color: #B6CDEE; }
-#PrescriptionLibraryPage QPushButton[rowAction="true"]:focus { border-color: #75A5F0; }
-#PrescriptionLibraryPage QPushButton[rowAction="true"][danger="true"]:hover { background: #FFF0F2; border-color: #EAC8D0; }
-#PrescriptionLibraryPage QPushButton[rowAction="true"]:disabled { background: transparent; border-color: transparent; color: #A4ADBA; }
-#PrescriptionLibraryPage QWidget#InfiniteList { background: #FFFFFF; border-top: 1px solid #E6EDF6; }
-#PrescriptionLibraryPage QLabel#EmptyStateGlyph {
- font-size: 24px; color: #1769E8; background: #F2F7FF;
- border: 1px solid #DBE5F2; border-radius: 22px;
-}
-#PrescriptionLibraryPage QWidget#EmptyState QLabel[role="muted"] { min-width: 300px; }
-#PrescriptionLibraryPage QScrollBar:vertical { background: #F4F7FC; width: 7px; margin: 0; }
-#PrescriptionLibraryPage QScrollBar:horizontal { background: #F4F7FC; height: 7px; margin: 0; }
-#PrescriptionLibraryPage QScrollBar::handle { background: #C8D5E6; border-radius: 3px; min-width: 24px; min-height: 24px; }
-#PrescriptionLibraryPage QScrollBar::add-line, #PrescriptionLibraryPage QScrollBar::sub-line { width: 0; height: 0; }
-#PrescriptionLibraryPage QScrollBar::add-page, #PrescriptionLibraryPage QScrollBar::sub-page { background: transparent; }
-"""
-
-
-__all__ = ["library_stylesheet", "LibraryComboBox", "LibraryTable", "LibraryItemDelegate"]
+"""Shared clinical tokens for the prescription library and its native delegates."""
+
+from __future__ import annotations
+
+from collections.abc import Iterable, Sequence
+from string import Template
+from typing import Any
+
+from PySide6.QtCore import QEvent, QModelIndex, QRectF, QSize, Qt, QTimer
+from PySide6.QtGui import QColor, QFont, QFontMetrics, QIcon, QPainter
+from PySide6.QtWidgets import (
+ QComboBox,
+ QPushButton,
+ QStyle,
+ QStyledItemDelegate,
+ QToolTip,
+ QWidget,
+)
+
+from .design_system import PALETTE, RADII, clinical_stylesheet
+from .reception_style import body_family, heading_family
+from .widgets import SortableTable, TableColumn, first_value
+
+
+def library_stylesheet() -> str:
+ return clinical_stylesheet(Template(_LIBRARY).safe_substitute(body=body_family(), heading=heading_family()))
+
+
+def _library_icon(kind: str, color: str = PALETTE["accent"], size: int = 15) -> QIcon:
+ # Defer the page helper lookup so importing this module alone does not
+ # recurse through pages.__init__ and the library page's own style import.
+ from .pages.prescriptions import _painted_icon
+
+ result = QIcon()
+ for mode, tint in (
+ (QIcon.Mode.Normal, color),
+ (QIcon.Mode.Active, color),
+ (QIcon.Mode.Selected, color),
+ (QIcon.Mode.Disabled, PALETTE["disabled"]),
+ ):
+ pixmap = _painted_icon(kind, tint, size).pixmap(QSize(size, size))
+ for state in (QIcon.State.Off, QIcon.State.On):
+ result.addPixmap(pixmap, mode, state)
+ return result
+
+
+class LibraryComboBox(QComboBox):
+ """Keep native combo interaction while painting the local caret."""
+
+ def paintEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
+ super().paintEvent(event)
+ painter = QPainter(self)
+ try:
+ rect = QRectF(self.width() - 25, (self.height() - 14) / 2, 14, 14)
+ mode = QIcon.Mode.Normal if self.isEnabled() else QIcon.Mode.Disabled
+ _library_icon("chevron_down", PALETTE["muted"], 14).paint(painter, rect.toRect(), mode=mode)
+ finally:
+ painter.end()
+
+
+class LibraryTable(SortableTable):
+ """Fit readable columns while preserving actions and selected template IDs."""
+
+ _FLEX_COLUMNS = ((1, 2), (4, 5), (5, 2))
+
+ def __init__(self, columns: Sequence[TableColumn], parent: QWidget | None = None) -> None:
+ super().__init__(columns, parent)
+ self.horizontalHeader().setStretchLastSection(False)
+ self._minimum_widths = tuple(column.width for column in self.columns)
+ self._manual_widths: dict[int, int] = {}
+ self._fitting_columns = False
+ self._fit_timer = QTimer(self)
+ self._fit_timer.setSingleShot(True)
+ self._fit_timer.timeout.connect(self._fit_columns)
+ self.horizontalHeader().sectionResized.connect(self._column_resized)
+ self.viewport().installEventFilter(self)
+
+ def eventFilter(self, watched: Any, event: QEvent) -> bool: # noqa: N802
+ if watched is self.viewport() and event.type() in {QEvent.Type.Resize, QEvent.Type.Show}:
+ self._schedule_column_fit()
+ return super().eventFilter(watched, event)
+
+ def _schedule_column_fit(self) -> None:
+ if not self._fit_timer.isActive():
+ self._fit_timer.start(0)
+
+ def _column_resized(self, column: int, _old_size: int, size: int) -> None:
+ if self._fitting_columns:
+ return
+ self._manual_widths[column] = max(self._minimum_widths[column], size)
+ self._schedule_column_fit()
+
+ def _fit_columns(self) -> None:
+ widths = [self._manual_widths.get(column, minimum)
+ for column, minimum in enumerate(self._minimum_widths)]
+ extra = max(0, self.viewport().width() - sum(widths))
+ flexible = [(column, weight) for column, weight in self._FLEX_COLUMNS
+ if column not in self._manual_widths]
+ # If every text column was manually sized, keep those preferences as
+ # minimums and let the herb preview absorb any remaining wide-screen space.
+ flexible = flexible or [(4, 1)]
+ total_weight = sum(weight for _column, weight in flexible)
+ for column, weight in flexible:
+ widths[column] += extra * weight // total_weight
+ widths[flexible[0][0]] += max(0, self.viewport().width() - sum(widths))
+ if widths == [self.columnWidth(column) for column in range(self.columnCount())]:
+ return
+ self._fitting_columns = True
+ try:
+ for column, width in enumerate(widths):
+ self.setColumnWidth(column, width)
+ finally:
+ self._fitting_columns = False
+
+ def set_rows(self, rows: Iterable[Any]) -> None:
+ selected_id = first_value(self.current_data(), "id", "template_id", default=None)
+ super().set_rows(rows)
+ # The shared table restores an unsorted row index after enabling sort.
+ # Locate the same source object in the finished visual order instead.
+ if selected_id is not None:
+ for row_index in range(self.rowCount()):
+ item = self.item(row_index, 0)
+ row = item.data(Qt.ItemDataRole.UserRole) if item is not None else None
+ row_id = first_value(row, "id", "template_id", default=None)
+ if row_id is not None and str(row_id) == str(selected_id):
+ self.selectRow(row_index)
+ return
+ self.clearSelection()
+ self.setCurrentCell(-1, -1)
+
+ def setCellWidget(self, row: int, column: int, widget: QWidget | None) -> None: # noqa: N802
+ super().setCellWidget(row, column, widget)
+ if widget is None or column != 9:
+ return
+ widget.setObjectName("PrescriptionLibraryTableCellHost")
+ widget.setAutoFillBackground(False)
+ glyphs = {
+ "查看处方模板": "eye",
+ "AI 解释": "spark",
+ "编辑处方模板": "pencil",
+ "删除处方模板": "trash",
+ }
+ for button in widget.findChildren(QPushButton):
+ if not button.property("rowAction"):
+ continue
+ glyph = glyphs.get(button.accessibleName()) or glyphs.get(button.toolTip())
+ if glyph is not None:
+ color = PALETTE["danger"] if button.property("danger") else PALETTE["accent"]
+ button.setIcon(_library_icon(glyph, color, button.iconSize().width()))
+
+
+def _library_font(size: int = 14, *, medium: bool = False) -> QFont:
+ font = QFont(heading_family() if medium else body_family())
+ font.setPixelSize(size)
+ font.setWeight(QFont.Weight.Medium if medium else QFont.Weight.Normal)
+ return font
+
+
+def _elide(text: str, metrics: QFontMetrics, width: int) -> str:
+ return metrics.elidedText(text, Qt.TextElideMode.ElideRight, max(1, width))
+
+
+def _herb_lines(text: str, metrics: QFontMetrics, width: int) -> list[str]:
+ """Wrap between complete herb entries; elide only the displayed lines."""
+ entries = text.split("、")
+ first = entries[0]
+ next_index = 1
+ while next_index < min(2, len(entries)):
+ candidate = first + "、" + entries[next_index]
+ if metrics.horizontalAdvance(candidate) > width:
+ break
+ first = candidate
+ next_index += 1
+ lines = [_elide(first, metrics, width)]
+ if next_index < len(entries):
+ lines.append(_elide("、".join(entries[next_index:]), metrics, width))
+ return lines
+
+
+def _name_lines(text: str, metrics: QFontMetrics, width: int) -> list[str]:
+ if metrics.horizontalAdvance(text) <= width:
+ return [text]
+ split = 1
+ while split < len(text) and metrics.horizontalAdvance(text[: split + 1]) <= width:
+ split += 1
+ return [_elide(text[:split], metrics, width), _elide(text[split:], metrics, width)]
+
+
+class LibraryItemDelegate(QStyledItemDelegate):
+ """Paint the ten existing columns without changing display or source roles."""
+
+ def sizeHint(self, option: Any, index: QModelIndex) -> QSize: # noqa: N802
+ size = super().sizeHint(option, index)
+ size.setHeight(78)
+ return size
+
+ def helpEvent(self, event: Any, view: Any, option: Any, index: QModelIndex) -> bool: # noqa: N802
+ if event is not None and index.isValid() and index.column() != 9:
+ text = index.data(Qt.ItemDataRole.ToolTipRole) or index.data(Qt.ItemDataRole.DisplayRole)
+ if text:
+ QToolTip.showText(event.globalPos(), str(text), view)
+ return True
+ return super().helpEvent(event, view, option, index)
+
+ @staticmethod
+ def _paint_lines(
+ painter: QPainter,
+ rect: QRectF,
+ lines: list[str],
+ *,
+ secondary_muted: bool = False,
+ ) -> None:
+ line_height = 26
+ top = rect.center().y() - len(lines) * line_height / 2
+ for line_index, line in enumerate(lines):
+ if secondary_muted and line_index:
+ painter.setFont(_library_font(13))
+ painter.setPen(QColor(PALETTE["muted"]))
+ line_rect = QRectF(rect.left(), top + line_index * line_height, rect.width(), line_height)
+ painter.drawText(line_rect, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, line)
+
+ def paint(self, painter: QPainter, option: Any, index: QModelIndex) -> None:
+ painter.save()
+ try:
+ painter.setClipRect(option.rect)
+ selected = bool(option.state & QStyle.StateFlag.State_Selected)
+ hovered = bool(option.state & QStyle.StateFlag.State_MouseOver)
+ background = PALETTE["accent_soft"] if selected else PALETTE["surface_alt"] if hovered else PALETTE["surface"]
+ painter.fillRect(option.rect, QColor(background))
+ painter.setPen(QColor(PALETTE["line"]))
+ painter.drawLine(option.rect.bottomLeft(), option.rect.bottomRight())
+ if selected and index.column() == 0:
+ stripe = QRectF(option.rect.left(), option.rect.top(), 3, option.rect.height() - 1)
+ painter.fillRect(stripe, QColor(PALETTE["accent"]))
+ if option.state & QStyle.StateFlag.State_HasFocus:
+ painter.setPen(QColor(PALETTE["focus"]))
+ painter.setBrush(Qt.BrushStyle.NoBrush)
+ painter.drawRect(option.rect.adjusted(1, 1, -2, -2))
+
+ column = index.column()
+ if column == 9:
+ return
+ rect = QRectF(option.rect.adjusted(12, 0, -12, -1))
+ if rect.width() <= 0:
+ return
+ value = index.data(Qt.ItemDataRole.DisplayRole)
+ text = "" if value is None else str(value)
+ font = _library_font(medium=column == 1)
+ painter.setFont(font)
+ painter.setPen(QColor(PALETTE["text"]))
+ metrics = QFontMetrics(font)
+ width = int(rect.width())
+
+ if column == 2:
+ painter.setFont(_library_font(13))
+ metrics = painter.fontMetrics()
+ label = _elide(text, metrics, width - 12)
+ pill_width = min(rect.width(), metrics.horizontalAdvance(label) + 14)
+ pill = QRectF(rect.center().x() - pill_width / 2, rect.center().y() - 12, pill_width, 24)
+ painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
+ painter.setPen(Qt.PenStyle.NoPen)
+ painter.setBrush(QColor(PALETTE["accent_soft"]))
+ painter.drawRoundedRect(pill, RADII["small"], RADII["small"])
+ painter.setPen(QColor(PALETTE["accent"]))
+ painter.drawText(pill, Qt.AlignmentFlag.AlignCenter, label)
+ elif column == 6:
+ glyph = "users" if text == "所有人可见" else "lock"
+ icon_rect = QRectF(rect.left(), rect.center().y() - 7, 14, 14)
+ _library_icon(glyph, PALETTE["muted"], 14).paint(painter, icon_rect.toRect())
+ label_rect = rect.adjusted(22, 0, 0, 0)
+ painter.drawText(
+ label_rect,
+ Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
+ _elide(text, metrics, int(label_rect.width())),
+ )
+ elif column == 4:
+ self._paint_lines(painter, rect, _herb_lines(text, metrics, width))
+ elif column == 8:
+ parts = text.splitlines() if "\n" in text else text.rsplit(" ", 1)
+ lines = [_elide(parts[0], metrics, width)]
+ if len(parts) > 1:
+ lines.append(_elide(" ".join(parts[1:]), QFontMetrics(_library_font(13)), width))
+ self._paint_lines(painter, rect, lines, secondary_muted=True)
+ elif column == 1:
+ self._paint_lines(painter, rect, _name_lines(text, metrics, width))
+ else:
+ alignment = Qt.AlignmentFlag.AlignCenter if column in (0, 3, 5) else (
+ Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter
+ )
+ painter.drawText(rect, alignment, _elide(text, metrics, width))
+ finally:
+ painter.restore()
+
+
+_LIBRARY = """
+#PrescriptionLibraryPage { background: $ds_canvas; color: $ds_text; }
+#PrescriptionLibraryPage QWidget#PrescriptionLibraryContent,
+#PrescriptionLibraryPage QScrollArea#PrescriptionLibraryScroll,
+#PrescriptionLibraryPage QScrollArea#PrescriptionLibraryToolbarScroll {
+ background: transparent; border: 0;
+}
+#PrescriptionLibraryPage QLabel, #PrescriptionLibraryPage QPushButton,
+#PrescriptionLibraryPage QLineEdit, #PrescriptionLibraryPage QComboBox,
+#PrescriptionLibraryPage QTableWidget {
+ font-family: "$body"; font-size: 14px; font-weight: 400; color: $ds_text;
+}
+#PrescriptionLibraryPage QLabel[role="pageTitle"] {
+ font-family: "$heading"; font-size: 20px; font-weight: 600; color: $ds_heading;
+}
+#PrescriptionLibraryPage QLabel[role="muted"] { color: $ds_muted; font-size: 13px; }
+#PrescriptionLibraryPage QFrame#PrescriptionLibraryFilterBar,
+#PrescriptionLibraryPage QFrame#PrescriptionLibraryTableCard {
+ background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_panel;
+}
+#PrescriptionLibraryPage QFrame#MetricCard { background: $ds_surface; border: 0; border-radius: $ds_radius_panel; }
+#PrescriptionLibraryPage QFrame#MetricCard QLabel[role="metricTitle"] {
+ font-family: "$body"; color: $ds_muted; font-size: 13px; font-weight: 400;
+}
+#PrescriptionLibraryPage QFrame#MetricCard QLabel[role="metricValue"] {
+ font-family: "$heading"; color: $ds_text; font-size: 18px; font-weight: 600;
+}
+#PrescriptionLibraryPage QFrame#MetricCard QLabel[metricIcon="true"] {
+ border: 0; border-radius: 0; background: transparent;
+}
+#PrescriptionLibraryPage QPushButton {
+ min-height: 38px; max-height: 38px; padding: 0 16px; border-radius: $ds_radius_control;
+ border: 1px solid transparent; background: $ds_surface_alt; color: $ds_text;
+}
+#PrescriptionLibraryPage QPushButton:hover { background: $ds_surface_alt; border-color: $ds_line_strong; color: $ds_accent; }
+#PrescriptionLibraryPage QPushButton:pressed { background: $ds_accent_soft; }
+#PrescriptionLibraryPage QPushButton:focus { border-color: $ds_focus; }
+#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton,
+#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton {
+ background: $ds_accent; border-color: $ds_accent; color: $ds_surface;
+}
+#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton:hover,
+#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton:hover {
+ background: $ds_accent_hover; border-color: $ds_accent_hover;
+}
+#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton:pressed,
+#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton:pressed {
+ background: $ds_accent_pressed; border-color: $ds_accent_pressed;
+}
+#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton:focus,
+#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton:focus { border-color: $ds_focus; }
+#PrescriptionLibraryPage QPushButton[variant="danger"] { color: $ds_danger; background: $ds_danger_soft; border-color: transparent; }
+#PrescriptionLibraryPage QPushButton[variant="danger"]:hover { border-color: $ds_danger; }
+#PrescriptionLibraryPage QPushButton[variant="danger"]:focus { border-color: $ds_focus; }
+#PrescriptionLibraryPage QPushButton:disabled,
+#PrescriptionLibraryPage QPushButton[variant="danger"]:disabled,
+#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton:disabled,
+#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton:disabled {
+ color: $ds_disabled; background: $ds_disabled_surface; border-color: $ds_line;
+}
+#PrescriptionLibraryPage QLineEdit, #PrescriptionLibraryPage QComboBox {
+ min-height: 38px; max-height: 38px; padding: 0 12px; border: 1px solid $ds_line;
+ border-radius: $ds_radius_control; background: $ds_surface; color: $ds_text;
+ selection-background-color: $ds_accent_soft; selection-color: $ds_text;
+}
+#PrescriptionLibraryPage QLineEdit:focus, #PrescriptionLibraryPage QComboBox:focus { border-color: $ds_focus; }
+#PrescriptionLibraryPage QLineEdit QToolButton { border: 0; background: transparent; padding: 0; }
+#PrescriptionLibraryPage QComboBox { padding-right: 30px; font-size: 13px; }
+#PrescriptionLibraryPage QComboBox::drop-down { width: 28px; border: 0; background: transparent; }
+#PrescriptionLibraryPage QComboBox::down-arrow { image: none; width: 0; height: 0; }
+#PrescriptionLibraryPage QComboBox:disabled { color: $ds_disabled; background: $ds_disabled_surface; }
+#PrescriptionLibraryPage QComboBox QAbstractItemView {
+ font-family: "$body"; font-size: 13px; color: $ds_text; background: $ds_surface;
+ border: 1px solid $ds_line; outline: 0; selection-background-color: $ds_accent_soft; selection-color: $ds_accent;
+}
+#PrescriptionLibraryPage QComboBox QAbstractItemView::item { min-height: 30px; padding: 3px 10px; }
+#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar { background: transparent; border: 0; }
+#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton { padding: 0 12px; font-size: 13px; }
+#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton[toolbarTab="true"] {
+ min-width: 80px; min-height: 40px; max-height: 40px; padding: 0 10px; margin-right: 8px;
+ background: transparent; border: 0; border-bottom: 2px solid transparent;
+ border-radius: 0; color: $ds_text; font-size: 14px;
+}
+#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton[toolbarTab="true"]:checked {
+ color: $ds_accent; border-bottom-color: $ds_accent;
+}
+#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton[toolbarTab="true"]:hover {
+ color: $ds_accent; background: $ds_surface_alt;
+}
+#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton[toolbarTab="true"]:focus { background: $ds_accent_soft; }
+#PrescriptionLibraryPage QTableWidget {
+ border: 0; background: $ds_surface; alternate-background-color: $ds_surface;
+ selection-background-color: $ds_accent_soft; selection-color: $ds_text; gridline-color: $ds_line;
+}
+#PrescriptionLibraryPage QTableWidget::item { padding: 0; border: 0; }
+#PrescriptionLibraryPage QHeaderView::section {
+ min-height: 0; padding: 0 12px; background: $ds_surface_alt; color: $ds_muted;
+ border: 0; border-bottom: 1px solid $ds_line;
+ font-family: "$body"; font-size: 13px; font-weight: 400;
+}
+#PrescriptionLibraryPage QWidget#PrescriptionLibraryTableCellHost { background: transparent; border: 0; }
+#PrescriptionLibraryPage QPushButton[rowAction="true"] {
+ min-width: 28px; max-width: 28px; min-height: 28px; max-height: 28px;
+ padding: 0; border: 1px solid transparent; border-radius: $ds_radius_small; background: transparent;
+}
+#PrescriptionLibraryPage QPushButton[rowAction="true"]:hover { background: $ds_accent_soft; border-color: $ds_line_strong; }
+#PrescriptionLibraryPage QPushButton[rowAction="true"]:focus { border-color: $ds_focus; }
+#PrescriptionLibraryPage QPushButton[rowAction="true"][danger="true"]:hover { background: $ds_danger_soft; border-color: $ds_danger_soft; }
+#PrescriptionLibraryPage QPushButton[rowAction="true"][danger="true"]:focus { border-color: $ds_focus; }
+#PrescriptionLibraryPage QPushButton[rowAction="true"]:disabled { background: transparent; border-color: transparent; color: $ds_disabled; }
+#PrescriptionLibraryPage QWidget#InfiniteList { background: $ds_surface; border-top: 1px solid $ds_line; }
+#PrescriptionLibraryPage QLabel#EmptyStateGlyph {
+ font-size: 24px; color: $ds_accent; background: $ds_surface_alt;
+ border: 1px solid $ds_line; border-radius: $ds_radius_panel;
+}
+#PrescriptionLibraryPage QWidget#EmptyState QLabel[role="muted"] { min-width: 300px; }
+#PrescriptionLibraryPage QScrollBar:vertical { background: $ds_canvas; width: 7px; margin: 0; }
+#PrescriptionLibraryPage QScrollBar:horizontal { background: $ds_canvas; height: 7px; margin: 0; }
+#PrescriptionLibraryPage QScrollBar::handle { background: $ds_line_strong; border-radius: 3px; min-width: 24px; min-height: 24px; }
+#PrescriptionLibraryPage QScrollBar::add-line, #PrescriptionLibraryPage QScrollBar::sub-line { width: 0; height: 0; }
+#PrescriptionLibraryPage QScrollBar::add-page, #PrescriptionLibraryPage QScrollBar::sub-page { background: transparent; }
+"""
+
+
+__all__ = ["library_stylesheet", "LibraryComboBox", "LibraryTable", "LibraryItemDelegate"]
diff --git a/app/src/doctor_workstation/ui/prescriptions_style.py b/app/src/doctor_workstation/ui/prescriptions_style.py
index bf1554418..9d452dfcf 100644
--- a/app/src/doctor_workstation/ui/prescriptions_style.py
+++ b/app/src/doctor_workstation/ui/prescriptions_style.py
@@ -1,107 +1,115 @@
-"""Scoped surfaces and real fonts for the approved issued-prescription page."""
-
-from string import Template
-
-from .reception_style import body_family, heading_family
-
-
-def prescriptions_stylesheet() -> str:
- return Template(_PRESCRIPTIONS).substitute(body=body_family(), heading=heading_family())
-
-
-_PRESCRIPTIONS = """
-#PrescriptionsPage { background: #F3F7FD; color: #273244; }
-#PrescriptionWorkspaceContent, #PrescriptionWorkspaceScroll { background: transparent; border: 0; }
-#PrescriptionsPage QLabel, #PrescriptionsPage QPushButton, #PrescriptionsPage QLineEdit,
-#PrescriptionsPage QComboBox, #PrescriptionsPage QDateTimeEdit, #PrescriptionsPage QTableWidget {
- font-family: "$body"; font-size: 14px; font-weight: 400; color: #273244;
-}
-#PrescriptionsPage QLabel[role="pageTitle"] {
- font-family: "$heading"; font-size: 20px; font-weight: 600; color: #202C3F;
-}
-#PrescriptionsPage QLabel[role="sectionTitle"] {
- font-family: "$heading"; font-size: 14px; font-weight: 600;
-}
-#PrescriptionsPage QLabel[role="muted"], #PrescriptionsPage QLabel#PrescriptionCountBadge {
- color: #5D6B80; font-size: 13px; background: transparent; border: 0; padding: 0;
-}
-#PrescriptionsPage QFrame#PrescriptionFilterBar, #PrescriptionsPage QFrame#PrescriptionTableCard {
- background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 8px;
-}
-#PrescriptionsPage QFrame#PrescriptionToolbar { background: transparent; border: 0; }
-#PrescriptionsPage QPushButton {
- min-height: 38px; max-height: 38px; padding: 0 16px; border-radius: 5px;
- border: 1px solid #DBE5F2; background: #FFFFFF; color: #273244;
-}
-#PrescriptionsPage QPushButton:hover { background: #F2F7FF; border-color: #B6CDEE; color: #1555B6; }
-#PrescriptionsPage QPushButton:pressed { background: #DCEAFF; }
-#PrescriptionsPage QPushButton:focus { border-color: #75A5F0; }
-#PrescriptionsPage QPushButton#PrescriptionAddButton, #PrescriptionsPage QPushButton#PrescriptionQueryButton {
- background: #1769E8; color: #FFFFFF; border-color: #1769E8;
-}
-#PrescriptionsPage QPushButton#PrescriptionAddButton:hover, #PrescriptionsPage QPushButton#PrescriptionQueryButton:hover {
- background: #155BCC; border-color: #155BCC;
-}
-#PrescriptionsPage QPushButton#PrescriptionAddButton:pressed, #PrescriptionsPage QPushButton#PrescriptionQueryButton:pressed {
- background: #124EA9; border-color: #124EA9;
-}
-#PrescriptionsPage QPushButton[variant="danger"] { color: #BE4657; background: #FFFFFF; border-color: #E9D8DE; }
-#PrescriptionsPage QPushButton:disabled, #PrescriptionsPage QPushButton[variant="danger"]:disabled {
- color: #97A4B6; background: #F6F8FC; border-color: #E2E9F2;
-}
-#PrescriptionsPage QLineEdit, #PrescriptionsPage QComboBox, #PrescriptionsPage QDateTimeEdit {
- min-height: 38px; max-height: 38px; padding: 0 12px; border: 1px solid #DBE5F2;
- border-radius: 5px; background: #FFFFFF; color: #273244;
- selection-background-color: #DCEAFF; selection-color: #273244;
-}
-#PrescriptionsPage QLineEdit:focus, #PrescriptionsPage QComboBox:focus, #PrescriptionsPage QDateTimeEdit:focus { border-color: #75A5F0; }
-#PrescriptionsPage QLineEdit QToolButton { min-width: 0; min-height: 0; border: 0; background: transparent; padding: 0; }
-#PrescriptionsPage QComboBox, #PrescriptionsPage QDateTimeEdit { padding-right: 30px; font-size: 13px; }
-#PrescriptionsPage QComboBox::drop-down, #PrescriptionsPage QDateTimeEdit::drop-down { width: 28px; border: 0; background: transparent; }
-#PrescriptionsPage QComboBox::down-arrow, #PrescriptionsPage QDateTimeEdit::down-arrow { image: none; width: 0; height: 0; }
-#PrescriptionsPage QDateTimeEdit:disabled { color: #8A97A9; background: #F6F8FC; border-color: #E2E9F2; }
-#PrescriptionsPage QPushButton#PrescriptionDoctorButton { text-align: left; padding-right: 30px; font-size: 13px; }
-#PrescriptionsPage QComboBox QAbstractItemView {
- font-family: "$body"; font-size: 13px; color: #273244; background: #FFFFFF;
- border: 1px solid #DBE5F2; outline: 0; selection-background-color: #EAF2FF; selection-color: #1555B6;
-}
-#PrescriptionsPage QComboBox QAbstractItemView::item { min-height: 30px; padding: 3px 10px; }
-#PrescriptionsPage QCalendarWidget { font-family: "$body"; font-size: 13px; background: #FFFFFF; color: #273244; }
-#PrescriptionsPage QCalendarWidget QWidget#qt_calendar_navigationbar { background: #F5F8FD; }
-#PrescriptionsPage QCalendarWidget QToolButton { min-height: 28px; border: 0; padding: 0 8px; color: #273244; background: transparent; }
-#PrescriptionsPage QCalendarWidget QAbstractItemView { color: #273244; background: #FFFFFF; selection-background-color: #1769E8; selection-color: #FFFFFF; outline: 0; }
-#PrescriptionsPage QFrame#PrescriptionToolbar QPushButton { padding: 0 12px; font-size: 13px; }
-#PrescriptionsPage QTableWidget#PrescriptionTable {
- border: 0; background: #FFFFFF; alternate-background-color: #FFFFFF;
- selection-background-color: #F2F7FF; selection-color: #273244; gridline-color: #E6EDF6;
-}
-#PrescriptionsPage QTableWidget#PrescriptionTable::item { border: 0; padding: 0; }
-#PrescriptionsPage QHeaderView::section {
- min-height: 0; padding: 0 12px; background: #F5F8FD; color: #5D6B80;
- border: 0; border-bottom: 1px solid #DBE5F2;
- font-family: "$body"; font-size: 13px; font-weight: 400;
-}
-#PrescriptionsPage QWidget#PrescriptionTableCellHost { border: 0; background: transparent; }
-#PrescriptionsPage QPushButton[rowAction="true"] {
- min-width: 28px; max-width: 28px; min-height: 28px; max-height: 28px;
- padding: 0; border: 1px solid transparent; border-radius: 4px; background: transparent;
-}
-#PrescriptionsPage QPushButton[rowAction="true"][labeled="true"] {
- min-width: 64px; max-width: 64px; color: #1769E8; font-size: 13px; padding: 0;
-}
-#PrescriptionsPage QPushButton[rowAction="true"]:hover { background: #EAF2FF; border-color: #B6CDEE; }
-#PrescriptionsPage QPushButton[rowAction="true"]:focus { border-color: #75A5F0; }
-#PrescriptionsPage QPushButton[rowAction="true"][danger="true"]:hover { background: #FFF0F2; border-color: #EAC8D0; }
-#PrescriptionsPage QPushButton[rowAction="true"]:disabled,
-#PrescriptionsPage QPushButton[rowAction="true"][labeled="true"]:disabled {
- background: transparent; border-color: transparent; color: #A4ADBA;
-}
-#PrescriptionsPage QWidget#InfiniteList { background: #FFFFFF; border-top: 1px solid #E6EDF6; }
-#PrescriptionsPage QLabel#EmptyStateGlyph { font-size: 24px; color: #1769E8; background: #F2F7FF; border: 1px solid #DBE5F2; border-radius: 22px; }
-#PrescriptionsPage QWidget#EmptyState QLabel[role="muted"] { min-width: 300px; }
-#PrescriptionsPage QScrollBar:vertical { background: #F4F7FC; width: 7px; margin: 0; }
-#PrescriptionsPage QScrollBar:horizontal { background: #F4F7FC; height: 7px; margin: 0; }
-#PrescriptionsPage QScrollBar::handle { background: #C8D5E6; border-radius: 3px; min-width: 24px; min-height: 24px; }
-#PrescriptionsPage QScrollBar::add-line, #PrescriptionsPage QScrollBar::sub-line { width: 0; height: 0; }
-#PrescriptionsPage QScrollBar::add-page, #PrescriptionsPage QScrollBar::sub-page { background: transparent; }
-"""
+"""Scoped surfaces and real fonts for the approved issued-prescription page."""
+
+from string import Template
+
+from .design_system import clinical_stylesheet
+from .reception_style import body_family, heading_family
+
+
+def prescriptions_stylesheet() -> str:
+ return clinical_stylesheet(Template(_PRESCRIPTIONS).safe_substitute(body=body_family(), heading=heading_family()))
+
+
+_PRESCRIPTIONS = """
+#PrescriptionsPage { background: $ds_canvas; color: $ds_text; }
+#PrescriptionWorkspaceContent, #PrescriptionWorkspaceScroll { background: transparent; border: 0; }
+#PrescriptionsPage QLabel, #PrescriptionsPage QPushButton, #PrescriptionsPage QLineEdit,
+#PrescriptionsPage QComboBox, #PrescriptionsPage QDateTimeEdit, #PrescriptionsPage QTableWidget {
+ font-family: "$body"; font-size: 14px; font-weight: 400; color: $ds_text;
+}
+#PrescriptionsPage QLabel[role="pageTitle"] {
+ font-family: "$heading"; font-size: 20px; font-weight: 600; color: $ds_heading;
+}
+#PrescriptionsPage QLabel[role="sectionTitle"] {
+ font-family: "$heading"; font-size: 14px; font-weight: 600;
+}
+#PrescriptionsPage QLabel[role="muted"], #PrescriptionsPage QLabel#PrescriptionCountBadge {
+ color: $ds_muted; font-size: 13px; background: transparent; border: 0; padding: 0;
+}
+#PrescriptionsPage QFrame#PrescriptionFilterBar, #PrescriptionsPage QFrame#PrescriptionTableCard {
+ background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_panel;
+}
+#PrescriptionsPage QFrame#PrescriptionToolbar { background: transparent; border: 0; }
+#PrescriptionsPage QPushButton {
+ min-height: 38px; max-height: 38px; padding: 0 16px; border-radius: $ds_radius_control;
+ border: 1px solid transparent; background: $ds_surface_alt; color: $ds_text;
+}
+#PrescriptionsPage QPushButton:hover { background: $ds_surface_alt; border-color: $ds_line_strong; color: $ds_accent; }
+#PrescriptionsPage QPushButton:pressed { background: $ds_accent_soft; }
+#PrescriptionsPage QPushButton:focus { border-color: $ds_focus; }
+#PrescriptionsPage QPushButton#PrescriptionAddButton, #PrescriptionsPage QPushButton#PrescriptionQueryButton {
+ background: $ds_accent; color: $ds_surface; border-color: $ds_accent;
+}
+#PrescriptionsPage QPushButton#PrescriptionAddButton:hover, #PrescriptionsPage QPushButton#PrescriptionQueryButton:hover {
+ background: $ds_accent_hover; border-color: $ds_accent_hover;
+}
+#PrescriptionsPage QPushButton#PrescriptionAddButton:pressed, #PrescriptionsPage QPushButton#PrescriptionQueryButton:pressed {
+ background: $ds_accent_pressed; border-color: $ds_accent_pressed;
+}
+#PrescriptionsPage QPushButton#PrescriptionAddButton:focus,
+#PrescriptionsPage QPushButton#PrescriptionQueryButton:focus { border-color: $ds_focus; }
+#PrescriptionsPage QPushButton[variant="danger"] { color: $ds_danger; background: $ds_danger_soft; border-color: transparent; }
+#PrescriptionsPage QPushButton[variant="danger"]:hover { border-color: $ds_danger; }
+#PrescriptionsPage QPushButton[variant="danger"]:focus { border-color: $ds_focus; }
+#PrescriptionsPage QPushButton:disabled, #PrescriptionsPage QPushButton[variant="danger"]:disabled,
+#PrescriptionsPage QPushButton#PrescriptionAddButton:disabled,
+#PrescriptionsPage QPushButton#PrescriptionQueryButton:disabled {
+ color: $ds_disabled; background: $ds_disabled_surface; border-color: $ds_line;
+}
+#PrescriptionsPage QLineEdit, #PrescriptionsPage QComboBox, #PrescriptionsPage QDateTimeEdit {
+ min-height: 38px; max-height: 38px; padding: 0 12px; border: 1px solid $ds_line;
+ border-radius: $ds_radius_control; background: $ds_surface; color: $ds_text;
+ selection-background-color: $ds_accent_soft; selection-color: $ds_text;
+}
+#PrescriptionsPage QLineEdit:focus, #PrescriptionsPage QComboBox:focus, #PrescriptionsPage QDateTimeEdit:focus { border-color: $ds_focus; }
+#PrescriptionsPage QLineEdit QToolButton { min-width: 0; min-height: 0; border: 0; background: transparent; padding: 0; }
+#PrescriptionsPage QComboBox, #PrescriptionsPage QDateTimeEdit { padding-right: 30px; font-size: 13px; }
+#PrescriptionsPage QComboBox::drop-down, #PrescriptionsPage QDateTimeEdit::drop-down { width: 28px; border: 0; background: transparent; }
+#PrescriptionsPage QComboBox::down-arrow, #PrescriptionsPage QDateTimeEdit::down-arrow { image: none; width: 0; height: 0; }
+#PrescriptionsPage QDateTimeEdit:disabled { color: $ds_disabled; background: $ds_disabled_surface; border-color: $ds_line; }
+#PrescriptionsPage QPushButton#PrescriptionDoctorButton { text-align: left; padding-right: 30px; font-size: 13px; }
+#PrescriptionsPage QComboBox QAbstractItemView {
+ font-family: "$body"; font-size: 13px; color: $ds_text; background: $ds_surface;
+ border: 1px solid $ds_line; outline: 0; selection-background-color: $ds_accent_soft; selection-color: $ds_accent;
+}
+#PrescriptionsPage QComboBox QAbstractItemView::item { min-height: 30px; padding: 3px 10px; }
+#PrescriptionsPage QCalendarWidget { font-family: "$body"; font-size: 13px; background: $ds_surface; color: $ds_text; }
+#PrescriptionsPage QCalendarWidget QWidget#qt_calendar_navigationbar { background: $ds_surface_alt; }
+#PrescriptionsPage QCalendarWidget QToolButton { min-height: 28px; border: 0; padding: 0 8px; color: $ds_text; background: transparent; }
+#PrescriptionsPage QCalendarWidget QAbstractItemView { color: $ds_text; background: $ds_surface; selection-background-color: $ds_accent; selection-color: $ds_surface; outline: 0; }
+#PrescriptionsPage QFrame#PrescriptionToolbar QPushButton { padding: 0 12px; font-size: 13px; }
+#PrescriptionsPage QTableWidget#PrescriptionTable {
+ border: 0; background: $ds_surface; alternate-background-color: $ds_surface;
+ selection-background-color: $ds_accent_soft; selection-color: $ds_text; gridline-color: $ds_line;
+}
+#PrescriptionsPage QTableWidget#PrescriptionTable::item { border: 0; padding: 0; }
+#PrescriptionsPage QHeaderView::section {
+ min-height: 0; padding: 0 12px; background: $ds_surface_alt; color: $ds_muted;
+ border: 0; border-bottom: 1px solid $ds_line;
+ font-family: "$body"; font-size: 13px; font-weight: 400;
+}
+#PrescriptionsPage QWidget#PrescriptionTableCellHost { border: 0; background: transparent; }
+#PrescriptionsPage QPushButton[rowAction="true"] {
+ min-width: 28px; max-width: 28px; min-height: 28px; max-height: 28px;
+ padding: 0; border: 1px solid transparent; border-radius: $ds_radius_small; background: transparent;
+}
+#PrescriptionsPage QPushButton[rowAction="true"][labeled="true"] {
+ min-width: 64px; max-width: 64px; color: $ds_accent; font-size: 13px; padding: 0;
+}
+#PrescriptionsPage QPushButton[rowAction="true"]:hover { background: $ds_accent_soft; border-color: $ds_line_strong; }
+#PrescriptionsPage QPushButton[rowAction="true"]:focus { border-color: $ds_focus; }
+#PrescriptionsPage QPushButton[rowAction="true"][danger="true"]:hover { background: $ds_danger_soft; border-color: $ds_danger_soft; }
+#PrescriptionsPage QPushButton[rowAction="true"][danger="true"]:focus { border-color: $ds_focus; }
+#PrescriptionsPage QPushButton[rowAction="true"]:disabled,
+#PrescriptionsPage QPushButton[rowAction="true"][labeled="true"]:disabled {
+ background: transparent; border-color: transparent; color: $ds_disabled;
+}
+#PrescriptionsPage QWidget#InfiniteList { background: $ds_surface; border-top: 1px solid $ds_line; }
+#PrescriptionsPage QLabel#EmptyStateGlyph { font-size: 24px; color: $ds_accent; background: $ds_surface_alt; border: 1px solid $ds_line; border-radius: $ds_radius_panel; }
+#PrescriptionsPage QWidget#EmptyState QLabel[role="muted"] { min-width: 300px; }
+#PrescriptionsPage QScrollBar:vertical { background: $ds_canvas; width: 7px; margin: 0; }
+#PrescriptionsPage QScrollBar:horizontal { background: $ds_canvas; height: 7px; margin: 0; }
+#PrescriptionsPage QScrollBar::handle { background: $ds_line_strong; border-radius: 3px; min-width: 24px; min-height: 24px; }
+#PrescriptionsPage QScrollBar::add-line, #PrescriptionsPage QScrollBar::sub-line { width: 0; height: 0; }
+#PrescriptionsPage QScrollBar::add-page, #PrescriptionsPage QScrollBar::sub-page { background: transparent; }
+"""
diff --git a/app/src/doctor_workstation/ui/reception_style.py b/app/src/doctor_workstation/ui/reception_style.py
index 23524d058..c19e1b737 100644
--- a/app/src/doctor_workstation/ui/reception_style.py
+++ b/app/src/doctor_workstation/ui/reception_style.py
@@ -4,23 +4,24 @@ from __future__ import annotations
from PySide6.QtWidgets import QApplication
+from .design_system import PALETTE
from .theme import _register_preferred_cjk_fonts
TECH_BLUE = {
- "accent": "#1769E8",
- "accent_hover": "#155BCC",
- "accent_pressed": "#124EA9",
- "selection": "#EAF2FF",
- "selected_text": "#1555B6",
- "canvas": "#F3F7FD",
- "sidebar": "#EDF4FF",
- "surface": "#FFFFFF",
- "raised": "#F7FAFE",
- "line": "#DBE5F2",
- "text": "#273244",
- "heading": "#202C3F",
- "muted": "#5D6B80",
- "focus": "#75A5F0",
+ "accent": PALETTE["accent"],
+ "accent_hover": PALETTE["accent_hover"],
+ "accent_pressed": PALETTE["accent_pressed"],
+ "selection": PALETTE["accent_soft"],
+ "selected_text": PALETTE["accent_hover"],
+ "canvas": PALETTE["canvas"],
+ "sidebar": PALETTE["sidebar"],
+ "surface": PALETTE["surface"],
+ "raised": PALETTE["surface_alt"],
+ "line": PALETTE["line"],
+ "text": PALETTE["text"],
+ "heading": PALETTE["heading"],
+ "muted": PALETTE["muted"],
+ "focus": PALETTE["focus"],
}
diff --git a/app/src/doctor_workstation/ui/reception_workspace.py b/app/src/doctor_workstation/ui/reception_workspace.py
index 0cb853d7f..6357fd1d3 100644
--- a/app/src/doctor_workstation/ui/reception_workspace.py
+++ b/app/src/doctor_workstation/ui/reception_workspace.py
@@ -170,8 +170,8 @@ QWidget#ReceptionPage QStackedWidget#ReceptionNarrowWorkspace {
}
QWidget#ReceptionPage QFrame#ReceptionQueuePanel {
background-color: #FFFFFF;
- border: 1px solid #E5ECF6;
- border-radius: 8px;
+ border: 1px solid #EDF0F5;
+ border-radius: 16px;
}
QWidget#ReceptionPage QLabel#ReceptionQueueTitle {
font-size: 18px;
@@ -200,8 +200,8 @@ QWidget#ReceptionPage QFrame#ReceptionHero,
QWidget#ReceptionPage QFrame#ReceptionClinicalCard {
min-height: 0;
background-color: #FFFFFF;
- border: 1px solid #E5ECF6;
- border-radius: 8px;
+ border: 1px solid #EDF0F5;
+ border-radius: 16px;
}
QWidget#ReceptionPage QLabel#ReceptionPatientName {
font-size: 20px;
@@ -223,8 +223,8 @@ QWidget#ReceptionPage QTabBar#ReceptionWorkspaceTabs {
background-color: #FFFFFF;
border: 0;
border-bottom: 1px solid #E5ECF6;
- border-top-left-radius: 8px;
- border-top-right-radius: 8px;
+ border-top-left-radius: 16px;
+ border-top-right-radius: 16px;
}
QWidget#ReceptionPage QTabBar#ReceptionDetailTabs::tab,
QWidget#ReceptionPage QTabBar#ReceptionWorkspaceTabs::tab {
@@ -295,8 +295,8 @@ QWidget#ReceptionPage QFrame#ReceptionPatientSummaryCard,
QWidget#ReceptionPage QFrame#ReceptionVitalsCard,
QWidget#ReceptionPage QFrame#ReceptionLabsCard {
background-color: #FFFFFF;
- border: 1px solid #E5ECF6;
- border-radius: 8px;
+ border: 1px solid #EDF0F5;
+ border-radius: 16px;
}
QWidget#ReceptionPage QLabel#ReceptionPatientSummaryValue {
color: #24334A;
@@ -367,8 +367,8 @@ QWidget#ReceptionPage QLabel[receptionMetricState="true"][alert="true"][warning=
QWidget#ReceptionPage QFrame#ReceptionAiAnalysisCard,
QWidget#ReceptionPage QFrame#ReceptionAiAssistantCard {
background-color: #FFFFFF;
- border: 1px solid #DCE5F0;
- border-radius: 8px;
+ border: 1px solid $ds_line;
+ border-radius: $ds_radius_panel;
}
QWidget#ReceptionPage QLabel#ReceptionAiTitle,
QWidget#ReceptionPage QPushButton#ReceptionAiTitle {
@@ -405,4 +405,37 @@ QWidget#ReceptionPage QScrollArea#ReceptionInsightsScroll QScrollBar::add-line:v
QWidget#ReceptionPage QScrollArea#ReceptionInsightsScroll QScrollBar::sub-line:vertical {
height: 0;
}
+QWidget#ReceptionPage QLineEdit#ReceptionQueueSearch,
+QWidget#ReceptionPage QPushButton#ReceptionDateButton,
+QWidget#ReceptionPage QPushButton#ReceptionQueueFilterToggle,
+QWidget#ReceptionPage QPushButton#ReceptionVideoButton,
+QWidget#ReceptionPage QPushButton#ReceptionNotifyButton,
+QWidget#ReceptionPage QPushButton#ReceptionHistoryButton,
+QWidget#ReceptionPage QPushButton#ReceptionImButton,
+QWidget#ReceptionPage QPushButton#ReceptionMoreButton,
+QWidget#ReceptionPage QPushButton#ReceptionCompleteButton,
+QWidget#ReceptionPage QPushButton[receptionAiPrompt="true"] {
+ border-radius: $ds_radius_control;
+}
+QWidget#ReceptionPage QPushButton:focus,
+QWidget#ReceptionPage QLineEdit:focus,
+QWidget#ReceptionPage QComboBox:focus,
+QWidget#ReceptionPage QTextEdit:focus {
+ border-color: $ds_focus;
+}
+QWidget#ReceptionPage QPushButton#ReceptionVideoButton:pressed {
+ color: $ds_surface;
+ background-color: $ds_accent_pressed;
+ border-color: $ds_accent_pressed;
+}
+QWidget#ReceptionPage QLabel[receptionMetricState="true"] {
+ border-radius: $ds_radius_small;
+}
+QWidget#ReceptionPage QFrame#ReceptionLabCell,
+QWidget#ReceptionPage QWidget#ReceptionCaseField {
+ border-bottom-color: $ds_line;
+}
+QWidget#ReceptionPage QLabel#ReceptionPatientSummaryValue[missing="true"] {
+ color: $ds_muted;
+}
"""
diff --git a/app/src/doctor_workstation/ui/shell.py b/app/src/doctor_workstation/ui/shell.py
index 5abad6e8a..628f6573e 100644
--- a/app/src/doctor_workstation/ui/shell.py
+++ b/app/src/doctor_workstation/ui/shell.py
@@ -59,6 +59,7 @@ from .chat_notifications import (
ChatNotification,
ChatNotificationCenter,
)
+from .design_system import PALETTE, clinical_stylesheet
from .dialogs.ai_consult import can_open_ai_consult
from .dialogs.ai_consult_picker import select_and_present_ai_consult
from .dialogs.diagnosis import DiagnosisDialog
@@ -72,7 +73,7 @@ from .pages import (
ReceptionPage,
)
from .reception_style import TECH_BLUE, body_family, heading_family, number_family
-from .theme import COLORS, TYPE, crisp_pixmap
+from .theme import COLORS, METRICS, TYPE, crisp_pixmap
from .widgets import (
EmptyState,
StatusBadge,
@@ -93,8 +94,8 @@ _SHELL_DESIGN_SIZE = QSize(1710, 920)
_SHELL_MINIMUM_SIZE = QSize(1024, 640)
_RECEPTION_SIDEBAR_WIDTH = 208
_RECEPTION_TOPBAR_HEIGHT = 76
-_RECEPTION_SIDEBAR_COLOR = "#F3F7FD"
-_RECEPTION_CHROME_LINE = "#E7EDF7"
+_RECEPTION_SIDEBAR_COLOR = PALETTE["sidebar"]
+_RECEPTION_CHROME_LINE = PALETTE["line"]
# Approved pages share one chrome state, so navigation among them keeps it intact.
_TECH_BLUE_PAGES = frozenset({"appointments", "consultations", "patients", "prescriptions", "prescription_library", "reception"})
@@ -1005,7 +1006,7 @@ class ShellWindow(QMainWindow):
chrome_widgets.extend(self.topbar.findChildren(_PaintedIconButton))
chrome_widgets.append(self.tabs_menu_button)
self._legacy_chrome_styles = {
- widget: widget.styleSheet() for widget in chrome_widgets
+ widget: clinical_stylesheet(widget.styleSheet()) for widget in chrome_widgets
}
self._register_pages()
self.search_shortcut = QShortcut(QKeySequence("Ctrl+K"), self)
@@ -1268,7 +1269,7 @@ class ShellWindow(QMainWindow):
color: #606163;
background-color: #FFFFFF;
border: 1px solid #EDEDEE;
- border-radius: 999px;
+ border-radius: 10px;
padding: 4px 10px;
font-size: 13px;
font-weight: 500;
@@ -1693,7 +1694,7 @@ class ShellWindow(QMainWindow):
font-family: "{body_family()}"; font-weight: 400;
min-height: 44px; max-height: 44px;
border: 0; border-left: 5px solid transparent;
- border-radius: 6px;
+ border-radius: {METRICS["r_md"]};
padding: 0 16px; font-size: {TYPE['fs_body']};
color: {TECH_BLUE['text']};
}}
@@ -1711,7 +1712,7 @@ class ShellWindow(QMainWindow):
}}
QPushButton#ShellNavButton[collapsed="true"] {{ padding: 0; }}
QFrame#ShellAssistantCard {{
- background-color: {TECH_BLUE['surface']}; border-radius: 8px;
+ background-color: {TECH_BLUE['surface']}; border-radius: {METRICS["r_lg"]};
border: 1px solid {_RECEPTION_CHROME_LINE};
}}
QLabel#ShellAssistantName {{
@@ -1723,7 +1724,7 @@ class ShellWindow(QMainWindow):
QPushButton#ShellAssistantButton, QPushButton#ShellSettingsButton {{
font-family: "{body_family()}"; font-weight: 400; font-size: {TYPE['fs_body']};
}}
- QPushButton#ShellAssistantButton {{ border-radius: 6px; }}
+ QPushButton#ShellAssistantButton {{ border-radius: {METRICS["r_md"]}; }}
QPushButton#ShellSettingsButton {{
min-height: 50px; max-height: 50px;
text-align: left; padding: 0 32px;
@@ -1738,7 +1739,7 @@ class ShellWindow(QMainWindow):
border-radius: 0;
border-bottom: 1px solid {_RECEPTION_CHROME_LINE};
}}
- QFrame#ShellGlobalSearch {{ border: 1px solid {_RECEPTION_CHROME_LINE}; border-radius: 5px; }}
+ QFrame#ShellGlobalSearch {{ background-color: {PALETTE["surface_alt"]}; border: 1px solid transparent; border-radius: {METRICS["r_md"]}; }}
QFrame#ShellUserSeparator {{ background: {_RECEPTION_CHROME_LINE}; border: 0; }}
QLabel#ShellShortcutHint {{
font-family: "{number_family()}"; font-size: {TYPE['fs_small']};
@@ -1767,7 +1768,7 @@ class ShellWindow(QMainWindow):
if isinstance(widget, _PaintedIconButton):
side = 50 if widget in (self.refresh_button, self.notification_button, self.settings_button) else 34
stylesheet += f"QToolButton#ShellPaintedIconButton {{ min-width: {side - 2}px; max-width: {side - 2}px; min-height: {side - 2}px; max-height: {side - 2}px; }}"
- widget.setStyleSheet(stylesheet)
+ widget.setStyleSheet(clinical_stylesheet(stylesheet))
self._set_reception_geometry(active)
for widget in (
diff --git a/app/src/doctor_workstation/ui/theme.py b/app/src/doctor_workstation/ui/theme.py
index c8b4e9d41..e62654238 100644
--- a/app/src/doctor_workstation/ui/theme.py
+++ b/app/src/doctor_workstation/ui/theme.py
@@ -41,46 +41,46 @@ from doctor_workstation.resources import resource_path
# ``motion`` deliberately imports nothing from this module, so this stays a
# one-way dependency: tokens here, animation there.
from . import motion
+from .design_system import PALETTE, RADII, SPACING, clinical_stylesheet
-# Neutral reading colors follow the installed Codex light chrome defaults.
+# Shared reading colors keep native pages and dialog chrome consistent.
# Brand accents are independent of reading ink; use opaque text for stable contrast.
# The legacy teal/ink aliases remain for existing callers.
COLORS = {
- "canvas": "#F4F6FA",
- "canvas_mid": "#FFFFFF",
- "canvas_glow": "#EEF1FA",
- "surface": "#FFFFFF",
- "surface_alt": "#F7F7F7",
- "raised": "#F7F7F7",
- "glass": "#FFFFFF",
- "glass_alt": "#F7F7F7",
- "line": "#EDEDEE",
- "line_soft": "#E4E4E5",
- "text": "#1A1C1F",
- "text_soft": "#606163",
- "muted": "#6A6B6D",
- "disabled_surface": "#F2F2F2",
- "disabled_text": "#8E8F90",
- "indigo": "#4F63D9",
- "indigo_hover": "#4156C4",
- "indigo_pressed": "#354BB4",
- "indigo_pale": "#EEF1FA",
- "focus": "#8B9AD9",
- "selection": "#EEF1FA",
- "success": "#287B65",
- "success_pale": "#EEF7F3",
- "warning": "#A9691D",
- "warning_pale": "#FCF5E9",
- "danger": "#BE4B58",
- "danger_pale": "#FCF0F2",
- "info": "#4F63D9",
- "info_pale": "#EEF1FA",
- # Backward-compatible names used by older UI code and integrations.
- "ink": "#1A1C1F",
- "ink_soft": "#606163",
- "teal": "#4F63D9",
- "teal_dark": "#354BB4",
- "teal_pale": "#EEF1FA",
+ "canvas": PALETTE["canvas"],
+ "canvas_mid": PALETTE["surface"],
+ "canvas_glow": PALETTE["accent_soft"],
+ "surface": PALETTE["surface"],
+ "surface_alt": PALETTE["surface_alt"],
+ "raised": PALETTE["surface_alt"],
+ "glass": PALETTE["surface"],
+ "glass_alt": PALETTE["surface_alt"],
+ "line": PALETTE["line"],
+ "line_soft": PALETTE["line_strong"],
+ "text": PALETTE["heading"],
+ "text_soft": PALETTE["text"],
+ "muted": PALETTE["muted"],
+ "disabled_surface": PALETTE["disabled_surface"],
+ "disabled_text": PALETTE["disabled"],
+ "indigo": PALETTE["accent"],
+ "indigo_hover": PALETTE["accent_hover"],
+ "indigo_pressed": PALETTE["accent_pressed"],
+ "indigo_pale": PALETTE["accent_soft"],
+ "focus": PALETTE["focus"],
+ "selection": PALETTE["accent_soft"],
+ "success": PALETTE["success"],
+ "success_pale": PALETTE["success_soft"],
+ "warning": PALETTE["warning"],
+ "warning_pale": PALETTE["warning_soft"],
+ "danger": PALETTE["danger"],
+ "danger_pale": PALETTE["danger_soft"],
+ "info": PALETTE["accent"],
+ "info_pale": PALETTE["accent_soft"],
+ "ink": PALETTE["heading"],
+ "ink_soft": PALETTE["text"],
+ "teal": PALETTE["accent"],
+ "teal_dark": PALETTE["accent_pressed"],
+ "teal_pale": PALETTE["accent_soft"],
}
@@ -122,11 +122,11 @@ METRICS = {
# ``outer - gap``. Where the gap is bigger than the outer radius the inner
# element is far enough from the corner that its own radius is free.
"r_xs": "4px", # chips, badges, tiny status pills
- "r_sm": "6px", # inline row actions, tags
- "r_md": "8px", # buttons, inputs, combo boxes
- "r_lg": "12px", # cards, filter bars, panels
- "r_xl": "16px", # the shell surfaces the cards sit on
- "pad_control": "12px", # horizontal padding inside default controls
+ "r_sm": f"{RADII['small']}px", # inline row actions, tags
+ "r_md": f"{RADII['control']}px", # buttons, inputs, combo boxes
+ "r_lg": f"{RADII['panel']}px", # cards, filter bars, panels
+ "r_xl": f"{RADII['window']}px", # the shell surfaces the cards sit on
+ "pad_control": f"{SPACING['control']}px", # horizontal padding inside default controls
"pad_compact": "9px",
}
@@ -176,7 +176,7 @@ QDialog[businessDialog="true"] QFrame#DialogSurface,
QDialog[businessDialog="true"] QFrame[dialogSurface="true"] {
background-color: $surface;
border: 1px solid $line;
- border-radius: 14px;
+ border-radius: $r_lg;
}
QDialog[businessDialog="true"] QFrame#DialogHeader,
QDialog[businessDialog="true"] QFrame[dialogRole="header"] {
@@ -275,18 +275,18 @@ QFrame#Card, QFrame#Panel, QFrame#FilterBar, QFrame#DetailPanel,
QFrame[glass="true"] {
background-color: $glass;
border: 1px solid $line;
- border-radius: 12px;
+ border-radius: $r_lg;
}
QFrame#FilterBar { background-color: $surface; }
QFrame#SubtleCard {
background-color: $glass_alt;
border: 1px solid $line;
- border-radius: 12px;
+ border-radius: $r_lg;
}
QFrame#MetricCard {
background-color: $surface;
border: 1px solid $line;
- border-radius: 11px;
+ border-radius: $r_md;
}
QFrame#MetricCard:hover { border-color: $line_soft; background-color: $surface_alt; }
QFrame#MetricCard QLabel[role="metricTitle"] { color: $muted; font-size: $fs_caption; }
@@ -297,7 +297,7 @@ QFrame#ReceptionAiCard {
min-height: 132px;
background-color: #FFFFFF;
border: 1px solid $line_soft;
- border-radius: 13px;
+ border-radius: $r_lg;
}
QLabel#ReceptionAiTitle {
color: $indigo_pressed;
@@ -313,7 +313,7 @@ QLabel#MetricGlyph {
color: $indigo;
background-color: $indigo_pale;
border: 1px solid $line_soft;
- border-radius: 11px;
+ border-radius: $r_md;
font-size: $fs_section;
font-weight: $fw_heading;
}
@@ -329,7 +329,7 @@ QGroupBox {
margin-top: 12px;
padding-top: 12px;
border: 1px solid $line;
- border-radius: 12px;
+ border-radius: $r_lg;
background-color: $glass;
font-weight: $fw_control;
}
@@ -351,7 +351,7 @@ QPushButton {
}
QPushButton:hover {
background-color: $raised;
- border-color: $indigo_hover;
+ border-color: $line_soft;
}
QPushButton:pressed {
background-color: $indigo_pale;
@@ -401,7 +401,7 @@ QPushButton[variant="primary"]:disabled {
QPushButton[variant="secondary"] {
color: $indigo_hover;
background-color: $indigo_pale;
- border-color: $line_soft;
+ border-color: $indigo_pale;
}
QPushButton[variant="secondary"]:hover {
color: $indigo_pressed;
@@ -462,7 +462,7 @@ QToolButton#RowActionsMore::menu-indicator { width: 0; height: 0; image: none; }
QFrame#NoteAttachmentTile {
background-color: $surface;
border: 1px solid $line;
- border-radius: 10px;
+ border-radius: $r_md;
}
QPushButton#NoteAttachmentPreview {
min-height: 132px;
@@ -470,7 +470,7 @@ QPushButton#NoteAttachmentPreview {
color: $muted;
background-color: $surface_alt;
border: 1px solid $line;
- border-radius: 8px;
+ border-radius: $r_md;
font-weight: $fw_control;
}
QPushButton#NoteAttachmentPreview:hover {
@@ -558,7 +558,7 @@ QPushButton[variant="chip"] {
color: $text_soft;
background-color: $surface_alt;
border-color: $line;
- border-radius: 8px;
+ border-radius: $r_md;
}
QPushButton[variant="chip"]:hover {
color: $text;
@@ -653,7 +653,7 @@ QComboBox QAbstractItemView {
background-color: $raised;
alternate-background-color: $surface_alt;
border: 1px solid $line;
- border-radius: 10px;
+ border-radius: $r_md;
padding: 5px;
outline: 0;
selection-background-color: $indigo_pressed;
@@ -692,7 +692,7 @@ QAbstractItemView, QTableWidget, QTableView, QListWidget, QListView, QTreeWidget
background-color: $surface;
alternate-background-color: $surface_alt;
border: 0;
- border-radius: 12px;
+ border-radius: $r_lg;
gridline-color: $line;
selection-background-color: $selection;
selection-color: $text;
@@ -729,17 +729,17 @@ QListWidget::item:selected, QListView::item:selected,
QTreeWidget::item:selected, QTreeView::item:selected {
background-color: $indigo_pale;
color: $indigo_pressed;
- border-radius: 8px;
+ border-radius: $r_md;
}
QListWidget::item:hover, QListView::item:hover,
QTreeWidget::item:hover, QTreeView::item:hover {
background-color: $surface_alt;
- border-radius: 8px;
+ border-radius: $r_md;
}
QTabWidget::pane {
border: 1px solid $line;
- border-radius: 12px;
+ border-radius: $r_lg;
background-color: $glass;
}
QTabBar::tab {
@@ -749,7 +749,7 @@ QTabBar::tab {
color: $muted;
background-color: transparent;
border: 1px solid transparent;
- border-radius: 9px;
+ border-radius: $r_md;
font-weight: $fw_control;
}
QTabBar::tab:hover { color: $text; background-color: $surface_alt; }
@@ -792,7 +792,7 @@ QMenu {
color: $text;
background-color: $raised;
border: 1px solid $line_soft;
- border-radius: 10px;
+ border-radius: $r_md;
padding: 6px;
}
QMenu::item {
@@ -815,7 +815,7 @@ QCalendarWidget {
color: $text;
background-color: $surface;
border: 1px solid $line;
- border-radius: 12px;
+ border-radius: $r_lg;
}
QCalendarWidget QWidget#qt_calendar_navigationbar {
background-color: $raised;
@@ -914,7 +914,7 @@ QWidget#Pager QLabel#PagerActive {
color: #FFFFFF;
background-color: $indigo;
border: 1px solid $indigo;
- border-radius: 8px;
+ border-radius: $r_md;
font-size: $fs_caption;
font-weight: $fw_control;
}
@@ -937,7 +937,7 @@ QLabel#EmptyStateGlyph {
QFrame#MessageBanner {
border: 1px solid $line;
- border-radius: 10px;
+ border-radius: $r_md;
color: $text_soft;
}
QFrame#MessageBanner QLabel { background-color: transparent; }
@@ -955,7 +955,7 @@ QLabel#Toast {
color: $text;
background-color: $raised;
border: 1px solid $line_soft;
- border-radius: 11px;
+ border-radius: $r_md;
padding: 11px 16px;
font-weight: $fw_control;
}
@@ -995,13 +995,9 @@ QLabel#UserAvatar {
font-weight: $fw_heading;
}
QWidget#LoginBrandPanel {
- background-color: qlineargradient(
- x1: 0, y1: 0, x2: 1, y2: 1,
- stop: 0 $surface,
- stop: 1 $canvas_glow
- );
+ background-color: $surface_alt;
border: 1px solid $line_soft;
- border-radius: 22px;
+ border-radius: $r_lg;
}
QFrame#LoginCard {
background-color: $glass;
@@ -1043,6 +1039,7 @@ QToolTip {
}
"""
).substitute(_QSS_TOKENS)
+GLOBAL_QSS = clinical_stylesheet(GLOBAL_QSS)
#: Per-block reading rhythm, in device pixels. ``(top, bottom, line%)``.
diff --git a/app/src/doctor_workstation/ui/widgets.py b/app/src/doctor_workstation/ui/widgets.py
index 60efcbfca..2c0b43167 100644
--- a/app/src/doctor_workstation/ui/widgets.py
+++ b/app/src/doctor_workstation/ui/widgets.py
@@ -44,6 +44,7 @@ from doctor_workstation.core.errors import (
)
from . import icons, motion
+from .design_system import PALETTE
AuthenticationExpiredHandler = Callable[[AuthenticationExpiredError], bool]
_AUTHENTICATION_EXPIRED_HANDLER: AuthenticationExpiredHandler | None = None
@@ -798,7 +799,7 @@ class _BusyTrack(QWidget):
chunk_width = max(36, int(rect.width() * 0.32))
span = rect.width() + chunk_width
x = int(self._phase * span) - chunk_width
- painter.setBrush(QColor("#4F63D9"))
+ painter.setBrush(QColor(PALETTE["accent"]))
painter.drawRoundedRect(x, 0, chunk_width, rect.height(), 3, 3)
diff --git a/app/src/doctor_workstation/video/im_ai.py b/app/src/doctor_workstation/video/im_ai.py
new file mode 100644
index 000000000..a184cb34a
--- /dev/null
+++ b/app/src/doctor_workstation/video/im_ai.py
@@ -0,0 +1,387 @@
+"""Bounded, Qt-independent AI requests for one authenticated IM window.
+
+Only server-archived clinical context is submitted. This module never sends IM
+messages and never shares the ordered call/recording lifecycle worker.
+"""
+
+from __future__ import annotations
+
+import re
+from collections import deque
+from collections.abc import Callable, Mapping
+from dataclasses import dataclass, field
+from threading import BoundedSemaphore, Event, RLock, Thread
+from time import monotonic
+from typing import Any
+from uuid import UUID, uuid4
+
+MAX_RESULT_CHARS = 65_536
+MAX_SYNC_STEPS = 24
+SYNC_TIMEOUT_SECONDS = 45.0
+_WORKER_SLOTS = BoundedSemaphore(4)
+_CANCEL_SLOTS = BoundedSemaphore(4)
+_ACTIONS = frozenset({"summary", "followup", "reply"})
+
+
+def _integer(value: Any, *, minimum: int) -> int | None:
+ if isinstance(value, bool) or not isinstance(value, (int, str)):
+ return None
+ if isinstance(value, str) and re.fullmatch(r"0|[1-9][0-9]{0,18}", value) is None:
+ return None
+ number = int(value)
+ return number if minimum <= number < 2**63 else None
+
+
+def _request_uuid(value: Any) -> bool:
+ if not isinstance(value, str) or len(value) != 36:
+ return False
+ try:
+ return str(UUID(value)) == value.lower()
+ except (ValueError, AttributeError):
+ return False
+
+
+def task_prompt(action: str, doctor_account: str) -> tuple[str, str]:
+ """Keep instructions separate from clinical source text and under API limits."""
+
+ if action not in _ACTIONS or not re.fullmatch(r"doctor_[1-9][0-9]{0,18}", doctor_account):
+ raise ValueError("AI 操作或当前医生账号无效")
+ shared = (
+ f"这是 IM 问诊辅助,本次医生 IM 账号为 {doctor_account}。"
+ "优先依据该医生与本患者最近已归档对话,结合服务端授权病历;"
+ "其他医生及历史记录仅作背景,不能当成本次已确认事实。"
+ "若未找到本次对话请明确说明,不猜测最新诉求。"
+ "区分已知、明确否认与未知,保留日期及不确定性;"
+ "不补问脉象,不编造事实、不自动确诊、不新增或更改药物剂量。"
+ )
+ instructions = {
+ "summary": "请用简短条目总结本次病情、病程、现用治疗与待核实事项,供医生交接复核。",
+ "followup": (
+ "请建议最多5条优先追问,直接给出可向患者询问的自然短句,"
+ "每条可附简短目的;避免重复已回答的问题,不做通用问卷。"
+ ),
+ "reply": (
+ "请起草一段医生可审阅后发给患者的简短自然回复,围绕该对话最近的患者问题。"
+ "不冒称已检查、已预约或已开处方,不承诺疗效,不让患者自行停换药。"
+ "只给回复草稿,不写分析过程;任何缺失资料通过必要的问题核实。"
+ ),
+ }
+ prompt = shared + instructions[action] + "此内容须由医生复核,不能自动发送。"
+ if len(prompt) > 500:
+ raise ValueError("AI 提示词超过接口长度限制")
+ return ("summary" if action == "summary" else "custom"), prompt
+
+
+def _warnings(value: Any) -> list[str]:
+ if not isinstance(value, (list, tuple)):
+ return []
+ warnings = []
+ for row in value[:20]:
+ if isinstance(row, str):
+ text = row
+ elif isinstance(row, Mapping):
+ text = row.get("message") or row.get("label")
+ if not text and row.get("code"):
+ text = (
+ "请复核回答中的脉象判断;本流程不采集脉象。"
+ if row["code"] == "PULSE_EXCLUDED_FROM_ASSESSMENT"
+ else "请对照原始记录复核,回答中的事实、否认或未知状态可能不一致。"
+ )
+ else:
+ continue
+ if isinstance(text, str) and text.strip():
+ rendered = text.strip()[:400]
+ if rendered not in warnings:
+ warnings.append(rendered)
+ return warnings
+
+
+class _RequestError(Exception):
+ """A deliberately safe, user-facing failure message."""
+
+
+@dataclass
+class _Job:
+ identity: dict[str, Any]
+ action: str
+ cancelled: Event = field(default_factory=Event)
+ completed: bool = False
+ succeeded: bool = False
+ stream_started: bool = False
+ cancel_sent: bool = False
+
+
+class ImAiController:
+ """One live request, a coalesced mailbox, and bounded daemon workers.
+
+ Qt polls ``take_result`` every 60 ms. Worker threads only mutate plain data;
+ they never touch a QObject. A cancelled worker must retire before a retry
+ starts, so rapid clicks cannot create an unbounded collection of requests.
+ """
+
+ def __init__(
+ self,
+ repository: Any,
+ *,
+ diagnosis_id: Any,
+ appointment_id: Any,
+ doctor_account: str,
+ enabled: bool = False,
+ clock: Callable[[], float] = monotonic,
+ max_sync_steps: int = MAX_SYNC_STEPS,
+ sync_timeout: float = SYNC_TIMEOUT_SECONDS,
+ ) -> None:
+ self.repository = repository
+ self.diagnosis_id = _integer(diagnosis_id, minimum=1)
+ self.appointment_id = _integer(appointment_id, minimum=0)
+ self.doctor_account = str(doctor_account)
+ self.enabled = (
+ enabled is True
+ and repository is not None
+ and self.diagnosis_id is not None
+ and self.appointment_id is not None
+ and re.fullmatch(r"doctor_[1-9][0-9]{0,18}", self.doctor_account) is not None
+ )
+ self.session_id = str(uuid4())
+ self._clock = clock
+ self._max_sync_steps = max(1, min(MAX_SYNC_STEPS, max_sync_steps))
+ self._sync_timeout = max(0.01, min(SYNC_TIMEOUT_SECONDS, sync_timeout))
+ self._lock = RLock()
+ self._closed = False
+ self._current: _Job | None = None
+ self._running: _Job | None = None
+ self._worker: Thread | None = None
+ self._mailbox: dict[str, Any] | None = None
+ self._seen: deque[str] = deque(maxlen=256)
+
+ @property
+ def config(self) -> dict[str, Any]:
+ return {
+ "version": 1,
+ "enabled": self.enabled and not self._closed,
+ "sessionId": self.session_id,
+ **({} if self.enabled else {"reason": "当前账号或问诊暂不能使用 AI 辅助。"}),
+ }
+
+ def _valid_identity(self, message: Mapping[str, Any]) -> bool:
+ return (
+ self.enabled
+ and not self._closed
+ and message.get("source") == "doctor-call"
+ and message.get("sessionId") == self.session_id
+ and _request_uuid(message.get("requestId"))
+ and isinstance(message.get("contextKey"), str)
+ and 0 < len(message["contextKey"]) <= 128
+ and _integer(message.get("diagnosisId"), minimum=1) == self.diagnosis_id
+ and _integer(message.get("appointmentId"), minimum=0) == self.appointment_id
+ and isinstance(message.get("action"), str)
+ and message["action"] in _ACTIONS
+ )
+
+ def handle(self, message: Mapping[str, Any]) -> bool:
+ with self._lock:
+ if not self._valid_identity(message):
+ return False
+ event = message.get("event")
+ identity = {key: message[key] for key in (
+ "sessionId", "requestId", "contextKey", "diagnosisId", "appointmentId", "action"
+ )}
+ if event == "im-ai-cancel":
+ if self._current is None or self._current.identity != identity:
+ return False
+ self._cancel(self._current)
+ return True
+ if event != "im-ai-request" or message["requestId"] in self._seen:
+ return False
+ self._seen.append(message["requestId"])
+ job = _Job(identity, message["action"])
+ if self._running is not None:
+ self._cancel(self._running)
+ self._current = job
+ self._publish(job, "error", message="上次请求正在结束,请稍后重试。", terminal=True)
+ return True
+ self._current = job
+ if not _WORKER_SLOTS.acquire(blocking=False):
+ self._publish(job, "error", message="AI 正在处理其他请求,请稍后重试。", terminal=True)
+ return True
+ self._running = job
+ self._publish(job, "loading", message="正在同步当前聊天记录…")
+ self._worker = Thread(target=self._run, args=(job,), name="im-ai", daemon=True)
+ try:
+ self._worker.start()
+ except RuntimeError:
+ self._running = None
+ _WORKER_SLOTS.release()
+ self._publish(job, "error", message="AI 请求暂时无法启动,请稍后重试。", terminal=True)
+ return True
+
+ def _publish(self, job: _Job, status: str, *, terminal: bool = False, **fields: Any) -> None:
+ with self._lock:
+ if self._closed or self._current is not job or job.cancelled.is_set() or job.completed:
+ return
+ if terminal:
+ job.completed = True
+ job.succeeded = status == "success"
+ self._mailbox = {**job.identity, "status": status, **fields}
+
+ def take_result(self) -> dict[str, Any] | None:
+ with self._lock:
+ result, self._mailbox = self._mailbox, None
+ return None if self._closed else result
+
+ def _sync(self, job: _Job) -> bool:
+ deadline = self._clock() + self._sync_timeout
+ token = ""
+ for _ in range(self._max_sync_steps):
+ if job.cancelled.is_set():
+ return False
+ if self._clock() >= deadline:
+ raise _RequestError("聊天同步超时,尚未生成,请稍后重试。")
+ result = self.repository.sync_im_chat_messages(
+ self.diagnosis_id, scope="current", sync_token=token
+ )
+ if job.cancelled.is_set():
+ return False
+ if self._clock() >= deadline:
+ raise _RequestError("聊天同步超时,尚未生成,请稍后重试。")
+ if not isinstance(result, Mapping) or result.get("errors"):
+ raise _RequestError("当前聊天记录未能完整同步,尚未生成,请稍后重试。")
+ if result.get("completed") is True:
+ return True
+ token = result.get("sync_token", "")
+ if not isinstance(token, str) or re.fullmatch(r"[a-f0-9]{48}", token) is None:
+ raise _RequestError("聊天同步进度无效,请更新客户端或稍后重试。")
+ raise _RequestError("聊天记录仍在同步,尚未生成,请稍后重试。")
+
+ def _run(self, job: _Job) -> None:
+ try:
+ if not self._sync(job):
+ return
+ task, prompt = task_prompt(job.action, self.doctor_account)
+ with self._lock:
+ if job.cancelled.is_set() or self._closed:
+ return
+ job.stream_started = True
+ self._publish(job, "loading", message="聊天已同步,正在整理病历资料…")
+ if job.cancelled.is_set():
+ return
+ text = ""
+ events = self.repository.stream_diagnosis_ai(
+ self.diagnosis_id, prompt, task=task,
+ request_id=job.identity["requestId"], cancelled=job.cancelled.is_set,
+ )
+ try:
+ for event in events:
+ if job.cancelled.is_set():
+ return
+ if not isinstance(event, Mapping):
+ continue
+ kind = event.get("event")
+ if kind == "delta":
+ delta = event.get("text", "")
+ if not isinstance(delta, str) or len(text) + len(delta) > MAX_RESULT_CHARS:
+ raise _RequestError("AI 内容超过显示上限,已停止接收,请缩小问题后重试。")
+ text += delta
+ self._publish(job, "streaming", text=text, message="正在生成,内容尚未完成。")
+ elif kind in {"start", "progress"}:
+ message = str(event.get("message") or "正在整理资料并生成…")[:240]
+ self._publish(job, "streaming" if text else "loading", text=text, message=message)
+ elif kind == "done":
+ result_id = event.get("diagnosis_id")
+ if result_id is not None and _integer(result_id, minimum=1) != self.diagnosis_id:
+ raise _RequestError("AI 返回的问诊上下文不匹配,结果未采用。")
+ answer = event.get("answer", event.get("content", text))
+ if not isinstance(answer, str) or not answer.strip():
+ raise _RequestError("AI 未返回完整内容,请重试。")
+ if len(answer) > MAX_RESULT_CHARS:
+ raise _RequestError("AI 内容超过显示上限,结果未采用,请缩小问题后重试。")
+ self._publish(
+ job, "success", terminal=True, text=answer,
+ message="已生成,请由医生复核后使用。",
+ modelLabel=str(event.get("model_label") or "")[:100],
+ warnings=_warnings(event.get("clinical_review_warnings")),
+ )
+ return
+ elif kind == "error":
+ raise _RequestError("AI 请求未完成,请检查权限或稍后重试。")
+ if not job.cancelled.is_set():
+ raise _RequestError("AI 连接提前结束,内容未完成,请重试。")
+ finally:
+ close = getattr(events, "close", None)
+ if callable(close):
+ close()
+ except Exception as error:
+ message = str(error) if isinstance(error, _RequestError) else (
+ "AI 请求失败,请检查权限或稍后重试。" if job.stream_started
+ else "当前聊天同步失败,尚未生成,请检查权限或稍后重试。"
+ )
+ self._publish(job, "error", message=message, terminal=True)
+ if job.stream_started and not job.cancelled.is_set() and not job.succeeded:
+ self._request_cancel(job)
+ finally:
+ with self._lock:
+ if self._running is job:
+ self._running = None
+ _WORKER_SLOTS.release()
+
+ def _cancel(self, job: _Job) -> None:
+ if job.completed or job.cancelled.is_set():
+ return
+ job.cancelled.set()
+ if self._current is job and not self._closed:
+ self._mailbox = {
+ **job.identity, "status": "cancelled",
+ "message": ("已停止本次接收,上游是否结束尚未确认。" if job.stream_started
+ else "已取消,尚未向 AI 提交请求。"),
+ }
+ if job.stream_started:
+ self._request_cancel(job)
+
+ def _request_cancel(self, job: _Job) -> None:
+ with self._lock:
+ if job.cancel_sent:
+ return
+ job.cancel_sent = True
+ if not _CANCEL_SLOTS.acquire(blocking=False):
+ return
+
+ def send() -> None:
+ try:
+ result = self.repository.cancel_diagnosis_ai(self.diagnosis_id, job.identity["requestId"])
+ if not isinstance(result, Mapping):
+ return
+ message = "已发送取消请求,上游是否结束尚未确认。"
+ terminal = result.get("upstream_terminal_status")
+ if result.get("upstream_terminal_confirmed") is True and terminal in {"stopped", "succeeded", "failed"}:
+ message = "本次接收已停止,上游工作流已结束。"
+ elif result.get("upstream_stop_confirmed") is True:
+ message = "上游已接受停止请求,是否结束尚未确认。"
+ with self._lock:
+ if not self._closed and self._current is job and job.cancelled.is_set():
+ self._mailbox = {**job.identity, "status": "cancelled", "message": message}
+ except Exception:
+ pass # Keep the visible unconfirmed cancellation; never expose transport details.
+ finally:
+ _CANCEL_SLOTS.release()
+
+ try:
+ Thread(target=send, name="im-ai-cancel", daemon=True).start()
+ except RuntimeError:
+ _CANCEL_SLOTS.release()
+
+ def close(self) -> None:
+ with self._lock:
+ if self._closed:
+ return
+ self._closed = True
+ self._mailbox = None
+ if self._running is not None:
+ self._cancel(self._running)
+
+ def wait(self, timeout: float = 1.0) -> bool:
+ """Bounded diagnostic/test helper; never called by the Qt GUI."""
+
+ worker = self._worker
+ if worker is not None:
+ worker.join(max(0.0, min(timeout, 5.0)))
+ return worker is None or not worker.is_alive()
diff --git a/app/src/doctor_workstation/video/launcher.py b/app/src/doctor_workstation/video/launcher.py
index f4efccbe9..45051df94 100644
--- a/app/src/doctor_workstation/video/launcher.py
+++ b/app/src/doctor_workstation/video/launcher.py
@@ -413,6 +413,7 @@ class VideoCallLauncher:
patient_name: str = "患者",
patient_case: Mapping[str, Any] | None = None,
on_open_diagnosis: Callable[[], None] | None = None,
+ can_ai_assistant: bool = False,
) -> Any:
request = self.prepare(
ticket,
@@ -432,6 +433,7 @@ class VideoCallLauncher:
patient_name=patient_name,
patient_case=patient_case,
on_open_diagnosis=on_open_diagnosis,
+ can_ai_assistant=can_ai_assistant is True,
)
@@ -450,6 +452,7 @@ def launch_video_call(
patient_name: str = "患者",
patient_case: Mapping[str, Any] | None = None,
on_open_diagnosis: Callable[[], None] | None = None,
+ can_ai_assistant: bool = False,
) -> Any:
"""Normalize a ticket and open a call with the requested backend."""
@@ -468,4 +471,5 @@ def launch_video_call(
patient_name=patient_name,
patient_case=patient_case,
on_open_diagnosis=on_open_diagnosis,
+ can_ai_assistant=can_ai_assistant is True,
)
diff --git a/app/src/doctor_workstation/video/window.py b/app/src/doctor_workstation/video/window.py
index 1129e7447..aab06b288 100644
--- a/app/src/doctor_workstation/video/window.py
+++ b/app/src/doctor_workstation/video/window.py
@@ -28,6 +28,7 @@ from ..services.local_audio_queue import (
LocalAudioUploadManager,
get_local_audio_upload_manager,
)
+from .im_ai import ImAiController
from .launcher import (
VideoCallRequest,
VideoTicketError,
@@ -320,6 +321,8 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
patient_name: str = "患者",
patient_case: Mapping[str, Any] | None = None,
on_open_diagnosis: Callable[[], None] | None = None,
+ can_ai_assistant: bool = False,
+ repository: Any = None,
) -> None:
super().__init__()
self.request = request
@@ -349,6 +352,18 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
self._call_cycle_closed = False
self._start_requested = False
self._shutdown_requested = False
+ self._im_ai = ImAiController(
+ repository,
+ diagnosis_id=request.diagnosis_id,
+ appointment_id=request.appointment_id,
+ doctor_account=request.user_id,
+ enabled=can_ai_assistant is True and self.open_im,
+ )
+ self._im_ai_timer = QTimer(self)
+ self._im_ai_timer.setInterval(60)
+ self._im_ai_timer.timeout.connect(self._flush_im_ai)
+ if self._im_ai.enabled:
+ self._im_ai_timer.start()
self._screenshot_preview_size = ScreenshotPreviewSize()
self._local_audio_capture: _LocalAudioCapture | None = None
self._local_audio_store: LocalAudioQueueStore | None = None
@@ -483,6 +498,7 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
"patientName": self.patient_name,
"patientCase": self.patient_case,
"mode": "chat" if self.open_im else "video",
+ "imAi": self._im_ai.config,
}
config_json = json.dumps(config, ensure_ascii=True, separators=(",", ":"))
script = f"""
@@ -524,11 +540,23 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
self._injected = result is not False
if not self._injected:
self._request_companion_shutdown("bridge-api-missing")
+ return
+ if not self._im_ai_context_is_trusted():
+ return
+ # open() may finish IM login before runJavaScript returns. Only
+ # acknowledge readiness after the native request gate is open.
+ session_id = json.dumps(self._im_ai.session_id, ensure_ascii=True)
+ self._page.runJavaScript(
+ f"window.doctorConsultation?.imAiReady?.({session_id});"
+ )
def _handle_bridge_message(self, message: Mapping[str, Any]) -> None:
if self._closing:
return
event = str(message.get("event", ""))
+ if event in {"im-ai-request", "im-ai-cancel"}:
+ self._handle_im_ai_message(message)
+ return
if event == "screenshot-preview":
visible = message.get("visible")
if isinstance(visible, bool):
@@ -622,6 +650,35 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
if not self.open_im or self._shutdown_requested:
self._close_from_companion("companion-error")
+ def _im_ai_context_is_trusted(self) -> bool:
+ return (
+ not self._closing
+ and not self._released
+ and not self._shutdown_requested
+ and self._injected
+ and self._policy.allows_main_document(self._page.url().toString())
+ )
+
+ def _handle_im_ai_message(self, message: Mapping[str, Any]) -> None:
+ if self._im_ai_context_is_trusted():
+ self._im_ai.handle(message)
+
+ def _flush_im_ai(self) -> None:
+ if not self._im_ai_context_is_trusted():
+ return
+ result = self._im_ai.take_result()
+ if result is not None:
+ payload = json.dumps(result, ensure_ascii=True, separators=(",", ":"))
+ self._page.runJavaScript(f"window.doctorConsultation?.imAiResult?.({payload});")
+
+ def _close_im_ai(self) -> None:
+ controller = getattr(self, "_im_ai", None)
+ if controller is not None:
+ controller.close()
+ timer = getattr(self, "_im_ai_timer", None)
+ if timer is not None:
+ timer.stop()
+
def _open_diagnosis_safely(self) -> None:
if self._closing or self._on_open_diagnosis is None:
return
@@ -1197,6 +1254,7 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
def _request_companion_shutdown(self, reason: str) -> None:
"""Let MediaRecorder finish and upload before WebEngine is destroyed."""
+ _EmbeddedVideoWindow._close_im_ai(self)
self._close_reason = reason
if self._closing or self._released:
return
@@ -1241,6 +1299,7 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
def _begin_shutdown(self) -> None:
if self._closing:
return
+ _EmbeddedVideoWindow._close_im_ai(self)
self._on_compact_close = None
self._closing = True
self._media_active = False
@@ -1342,6 +1401,7 @@ class VideoCallWindow:
patient_name: str = "患者",
patient_case: Mapping[str, Any] | None = None,
on_open_diagnosis: Callable[[], None] | None = None,
+ can_ai_assistant: bool = False,
) -> None:
del browser_opener # Reserved for a future authenticated handoff implementation.
try:
@@ -1360,6 +1420,7 @@ class VideoCallWindow:
self.open_im = bool(open_im)
self.patient_name = str(patient_name or "患者").strip() or "患者"
self.patient_case = dict(patient_case or {})
+ self.can_ai_assistant = can_ai_assistant is True
self.on_open_diagnosis = on_open_diagnosis
self.logger = logger or _LOGGER
self.location = resolve_companion_location(
@@ -1391,6 +1452,8 @@ class VideoCallWindow:
patient_name=self.patient_name,
patient_case=self.patient_case,
on_open_diagnosis=self.on_open_diagnosis,
+ can_ai_assistant=self.can_ai_assistant,
+ repository=self.repository,
)
except Exception:
self.lifecycle.end("window-open-failed")
@@ -1436,6 +1499,7 @@ def open_video_call(
patient_name: str = "患者",
patient_case: Mapping[str, Any] | None = None,
on_open_diagnosis: Callable[[], None] | None = None,
+ can_ai_assistant: bool = False,
) -> VideoCallWindow:
"""Create and immediately open a trusted embedded video window."""
@@ -1452,6 +1516,7 @@ def open_video_call(
patient_name=patient_name,
patient_case=patient_case,
on_open_diagnosis=on_open_diagnosis,
+ can_ai_assistant=can_ai_assistant,
).open()
diff --git a/app/tests/test_ai_consult_ui.py b/app/tests/test_ai_consult_ui.py
index d68fc681c..1c886d97f 100644
--- a/app/tests/test_ai_consult_ui.py
+++ b/app/tests/test_ai_consult_ui.py
@@ -26,6 +26,7 @@ from PySide6.QtWidgets import (
from doctor_workstation.core import PermissionSet
from doctor_workstation.services import ApiClient, DemoDoctorRepository, RemoteDoctorRepository
+from doctor_workstation.ui.design_system import PALETTE
from doctor_workstation.ui.dialogs import ai_consult as ai_consult_module
from doctor_workstation.ui.dialogs.ai_consult import (
AiConsultDialog,
@@ -2306,14 +2307,14 @@ def test_risk_block_uses_the_red_alert_palette() -> None:
assert "#FEF3F2" in risk_card
assert "#F1B35C" not in risk_card # 旧的橙色描边
marker = qss.split("QLabel#AiConsultRiskMarker {", 1)[1].split("}", 1)[0]
- assert "#BE4B58" in marker
+ assert PALETTE["danger"] in marker
def test_clinical_bodies_are_no_longer_rendered_at_eleven_pixels() -> None:
qss = ai_consult_module.AI_CONSULT_QSS
body = qss.rsplit("QLabel#AiConsultRiskBody {", 1)[1].split("}", 1)[0]
- assert "color: #1a1c1f" in body.lower()
+ assert f'color: {PALETTE["text"]}' in body
assert "font-size: 14px" in body
block = qss.split("QLabel#AiConsultClinicalBody,", 1)[1].split("}", 1)[0]
assert "font-size: 14px" in block
diff --git a/app/tests/test_appointment_drawer_visual.py b/app/tests/test_appointment_drawer_visual.py
index c34129ae7..fe057392a 100644
--- a/app/tests/test_appointment_drawer_visual.py
+++ b/app/tests/test_appointment_drawer_visual.py
@@ -10,6 +10,7 @@ from PySide6.QtCore import QDate, QSize, Qt
from PySide6.QtWidgets import QApplication, QStyle, QStyleOptionButton, QWidget
from doctor_workstation.ui.appointment_drawer import APPOINTMENT_DRAWER_QSS, AppointmentDrawer
+from doctor_workstation.ui.design_system import PALETTE
@pytest.fixture(scope="module")
@@ -565,8 +566,39 @@ def test_keyboard_focus_has_a_visible_state(
assert focus_target.hasFocus()
assert application.focusWidget() is focus_target
assert 'QPushButton[appointmentDate="true"]:focus' in APPOINTMENT_DRAWER_QSS
- assert "border-color: #8B9AD9;" in APPOINTMENT_DRAWER_QSS
+ assert f"border-color: {PALETTE['focus']};" in APPOINTMENT_DRAWER_QSS
drawer.close()
host.close()
application.processEvents()
+
+
+@pytest.mark.parametrize("button_kind", ["date", "slot"])
+def test_appointment_hover_keeps_hit_target_stable_after_relayout(
+ application: QApplication, button_kind: str,
+) -> None:
+ """Hovering must not move a time choice or restore a stale layout position."""
+ from PySide6.QtCore import QEvent, QPoint, QPointF
+ from PySide6.QtGui import QEnterEvent
+
+ host, drawer = _show_drawer(
+ application, (1440, 900), repository=_VisualRepository(), autoload=True,
+ )
+ tomorrow = QDate.currentDate().addDays(1).toString("yyyy-MM-dd")
+ button = drawer.date_buttons[tomorrow] if button_kind == "date" else drawer.slot_buttons["09:30-10:00"]
+ original = button.geometry()
+ try:
+ for _ in range(3):
+ application.sendEvent(button, QEnterEvent(QPointF(10, 10), QPointF(30, 34), QPointF(30, 34)))
+ assert button.geometry() == original
+ assert button.graphicsEffect() is None
+ relocated = original.topLeft() + QPoint(12, 16)
+ button.move(relocated) # A resize/reflow while the pointer stays inside.
+ application.sendEvent(button, QEvent(QEvent.Type.Leave))
+ assert button.pos() == relocated
+ button.setGeometry(original)
+ button.click()
+ assert button.isChecked()
+ finally:
+ drawer.close()
+ host.close()
diff --git a/app/tests/test_diagnosis_drawer_visual.py b/app/tests/test_diagnosis_drawer_visual.py
index 470facfa2..8d8693307 100644
--- a/app/tests/test_diagnosis_drawer_visual.py
+++ b/app/tests/test_diagnosis_drawer_visual.py
@@ -22,6 +22,7 @@ from PySide6.QtWidgets import (
)
from doctor_workstation.core import PermissionSet
+from doctor_workstation.ui.design_system import PALETTE
from doctor_workstation.ui.diagnosis_drawer import (
DiagnosisChoiceButtons,
DiagnosisComboBox,
@@ -1012,14 +1013,14 @@ def test_choice_chips_keep_visible_checked_style_when_readonly(
application.processEvents()
# Sample the pad (not glyph center) so white text does not hide the fill.
enabled_color = selected.grab().toImage().pixelColor(6, selected.height() // 2)
- assert enabled_color.name().lower() == "#eef1fa"
+ assert enabled_color.name().lower() == PALETTE["accent_soft"].lower()
diet.setReadOnly(True)
application.processEvents()
disabled_color = selected.grab().toImage().pixelColor(6, selected.height() // 2)
assert selected.isChecked()
assert selected.isEnabled()
assert diet.isReadOnly()
- assert disabled_color.name().lower() == "#eef1fa"
+ assert disabled_color.name().lower() == PALETTE["accent_soft"].lower()
dialog.close()
application.processEvents()
@@ -1039,7 +1040,7 @@ def test_view_only_drawer_shows_selected_choice_chips(
selected = next(button for button in diet._buttons if button.isChecked())
application.processEvents()
color = selected.grab().toImage().pixelColor(6, selected.height() // 2)
- assert color.name().lower() == "#eef1fa"
+ assert color.name().lower() == PALETTE["accent_soft"].lower()
assert diet.isReadOnly()
assert not dialog.save_button.isVisibleTo(dialog)
dialog.close()
diff --git a/app/tests/test_diagnosis_index_visual.py b/app/tests/test_diagnosis_index_visual.py
index 450def724..75050d297 100644
--- a/app/tests/test_diagnosis_index_visual.py
+++ b/app/tests/test_diagnosis_index_visual.py
@@ -23,6 +23,7 @@ from PySide6.QtWidgets import (
)
from doctor_workstation.core import PermissionSet
+from doctor_workstation.ui.design_system import PALETTE
from doctor_workstation.ui.diagnosis_index_widgets import (
DIAGNOSIS_INDEX_QSS,
DiagnosisItemDelegate,
@@ -424,8 +425,8 @@ def test_empty_loading_and_compact_footer_keep_the_table_shell(
@pytest.mark.parametrize(
("record", "stripe", "channel"),
[
- (_row(701, DiagnosisViewRecord=[{"is_confirmed": 0}]), "#a9691d", "warning"),
- (_row(702, has_appointment=0, appointments=[]), "#4f63d9", "info"),
+ (_row(701, DiagnosisViewRecord=[{"is_confirmed": 0}]), PALETTE["warning"].lower(), "warning"),
+ (_row(702, has_appointment=0, appointments=[]), PALETTE["accent"].lower(), "info"),
],
)
def test_semantic_hover_preserves_three_pixel_stripe_on_neutral_background(
@@ -452,9 +453,9 @@ def test_semantic_hover_preserves_three_pixel_stripe_on_neutral_background(
assert image.pixelColor(0, 20).name() == stripe
assert image.pixelColor(1, 20).name() == stripe
assert image.pixelColor(2, 20).name() == stripe
- assert image.pixelColor(3, 20).name() == "#f7f7f7", f"{channel} stripe widened"
- assert image.pixelColor(6, 20).name() == "#f7f7f7"
- assert image.pixelColor(40, 20).name() == "#f7f7f7"
+ assert image.pixelColor(3, 20).name() == PALETTE["surface_alt"].lower(), f"{channel} stripe widened"
+ assert image.pixelColor(6, 20).name() == PALETTE["surface_alt"].lower()
+ assert image.pixelColor(40, 20).name() == PALETTE["surface_alt"].lower()
def test_page_hides_fixed_shadow_and_preserves_admin_token_contract(
diff --git a/app/tests/test_diagnosis_table_blue.py b/app/tests/test_diagnosis_table_blue.py
index fd129b46e..f26add35a 100644
--- a/app/tests/test_diagnosis_table_blue.py
+++ b/app/tests/test_diagnosis_table_blue.py
@@ -9,10 +9,17 @@ from pathlib import Path
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
-from PySide6.QtCore import QPoint, Qt
-from PySide6.QtGui import QFont
+from PySide6.QtCore import QPoint, QRect, Qt
+from PySide6.QtGui import QFont, QImage, QPainter
from PySide6.QtTest import QTest
-from PySide6.QtWidgets import QApplication, QLabel, QToolButton, QVBoxLayout, QWidget
+from PySide6.QtWidgets import (
+ QApplication,
+ QLabel,
+ QStyleOptionViewItem,
+ QToolButton,
+ QVBoxLayout,
+ QWidget,
+)
from doctor_workstation.ui.diagnosis_index_widgets import (
DiagnosisTableHost,
@@ -115,6 +122,79 @@ def test_blue_metrics_are_opt_in_and_expand_for_complete_content(application: QA
legacy.close()
+@pytest.mark.parametrize(
+ "size,column_width,row_height",
+ [((1024, 640), 84, 75), ((1440, 900), 126, 72)],
+)
+def test_followup_paint_keeps_time_whole_and_preserves_density(
+ application: QApplication, size: tuple[int, int], column_width: int, row_height: int,
+) -> None:
+ class RecordingPainter(QPainter):
+ def __init__(self, image: QImage) -> None:
+ super().__init__(image)
+ self.lines: list[tuple[QRect, int, str]] = []
+
+ def drawText(self, rect: QRect, flags: int, text: str) -> None: # noqa: N802
+ self.lines.append((QRect(rect), flags, text))
+ super().drawText(rect, flags, text)
+
+ row = {
+ "id": 501, "has_prescription": 1,
+ "followup_time_text": "2026-08-17 09:00", "followup_doctor_name": "陈医生",
+ }
+ original = copy.deepcopy(row)
+ host = DiagnosisTableHost(tech_blue=True)
+ host.resize(*size)
+ host.set_rows([row])
+ host.show()
+ _settle(application)
+ try:
+ assert host.main.columnWidth(6) == column_width
+ assert host.main.rowHeight(0) == row_height
+ assert host.fixed.rowHeight(0) == row_height
+ index = host.model.index(0, 6)
+ full_text = "2026-08-17 09:00\n陈医生"
+ assert index.data() == full_text
+ assert index.data(Qt.ItemDataRole.ToolTipRole) == full_text
+ option = QStyleOptionViewItem()
+ option.rect = QRect(0, 0, column_width, row_height)
+ image = QImage(column_width, row_height, QImage.Format.Format_ARGB32)
+ painter = RecordingPainter(image)
+ host.main.itemDelegate().paint(painter, option, index)
+ painter.end()
+ expected = ["2026-08-17", "09:00", "陈医生"] if size[0] == 1024 else [
+ "2026-08-17 09:00", "陈医生",
+ ]
+ assert [line[2] for line in painter.lines] == expected
+ content = option.rect.adjusted(8, 8, -8, -8)
+ for rect, flags, _text in painter.lines:
+ assert content.contains(rect)
+ assert flags & Qt.TextFlag.TextSingleLine
+ assert not flags & Qt.TextFlag.TextWrapAnywhere
+ assert row == original
+ finally:
+ host.close()
+ _settle(application)
+
+
+def test_followup_long_metadata_has_complete_tooltip(application: QApplication) -> None:
+ host = DiagnosisTableHost(tech_blue=True)
+ row = {
+ "id": 502, "has_prescription": 1,
+ "followup_time_text": "2026-08-17 09:00-09:30",
+ "followup_doctor_name": "陈医生(内分泌科专家门诊)", "followup_rx_voided": True,
+ }
+ original = copy.deepcopy(row)
+ host.set_rows([row])
+ index = host.model.index(0, 6)
+ assert index.data(Qt.ItemDataRole.ToolTipRole) == (
+ "2026-08-17 09:00-09:30\n陈医生(内分泌科专家门诊)\n处方已作废"
+ )
+ assert index.data() == index.data(Qt.ItemDataRole.ToolTipRole)
+ assert row == original
+ host.close()
+
+
@pytest.mark.parametrize("tech_blue", [False, True])
def test_geometry_has_no_minimum_height_feedback_and_tracks_both_scroll_axes(
application: QApplication, tech_blue: bool,
diff --git a/app/tests/test_doctor_selection.py b/app/tests/test_doctor_selection.py
index c0729c7d4..342609447 100644
--- a/app/tests/test_doctor_selection.py
+++ b/app/tests/test_doctor_selection.py
@@ -8,6 +8,7 @@ from PySide6.QtCore import QPoint, Qt, QTimer
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication
+from doctor_workstation.ui.design_system import PALETTE
from doctor_workstation.ui.pages.prescriptions import DoctorMultiSelect, _DoctorSelectionDialog
from doctor_workstation.ui.theme import apply_theme
@@ -74,7 +75,7 @@ def test_checked_row_blue_and_unchecked_white(dialog, application):
rect = dialog.listing.visualItemRect(item_for(dialog, doctor_id))
colors.append(image.pixelColor(int((rect.right() - 70) * scale),
int(rect.center().y() * scale)).name())
- assert colors == ["#eaf2ff", "#ffffff"]
+ assert colors == [PALETTE["accent_soft"].lower(), PALETTE["surface"].lower()]
def test_accept_commits_cancel_preserves_and_reopen_restores(application):
diff --git a/app/tests/test_im_ai_repository.py b/app/tests/test_im_ai_repository.py
new file mode 100644
index 000000000..91e38d722
--- /dev/null
+++ b/app/tests/test_im_ai_repository.py
@@ -0,0 +1,42 @@
+"""Current-peer archive paging preserves old callers and request identities."""
+
+import pytest
+
+from doctor_workstation.services.mock_repository import DemoDoctorRepository
+from doctor_workstation.services.repository import RemoteDoctorRepository
+
+
+class Client:
+ def __init__(self):
+ self.calls = []
+
+ def post(self, endpoint, payload, *, timeout=None):
+ self.calls.append((endpoint, payload, timeout))
+ return {"completed": False, "sync_token": "a" * 48, "errors": []}
+
+
+def test_sync_optional_parameters_and_timeout_preserve_exact_legacy_payload():
+ client = Client()
+ repository = RemoteDoctorRepository(client)
+ repository.sync_im_chat_messages(501)
+ result = repository.sync_im_chat_messages(501, scope="current", sync_token="a" * 48)
+ assert client.calls == [
+ ("tcm.diagnosis/triggerImChatSync", {"diagnosis_id": 501}, 15.0),
+ ("tcm.diagnosis/triggerImChatSync",
+ {"diagnosis_id": 501, "scope": "current", "sync_token": "a" * 48}, 15.0),
+ ]
+ assert result["completed"] is False
+
+
+@pytest.mark.parametrize("kwargs", [{"scope": "other"}, {"sync_token": "bad"}, {"sync_token": None}])
+def test_sync_rejects_invalid_options_without_network(kwargs):
+ client = Client()
+ with pytest.raises(ValueError):
+ RemoteDoctorRepository(client).sync_im_chat_messages(501, **kwargs)
+ assert not client.calls
+
+
+def test_mock_sync_supports_paging_contract_and_legacy_receipt():
+ repository = DemoDoctorRepository()
+ assert repository.sync_im_chat_messages(501)["queued"] is True
+ assert repository.sync_im_chat_messages(501, scope="current")["completed"] is True
diff --git a/app/tests/test_im_ai_service.py b/app/tests/test_im_ai_service.py
new file mode 100644
index 000000000..99606401b
--- /dev/null
+++ b/app/tests/test_im_ai_service.py
@@ -0,0 +1,270 @@
+"""Offline tests for native IM AI authorization, synchronization and races."""
+
+from __future__ import annotations
+
+from collections import deque
+from threading import BoundedSemaphore, Event
+from uuid import uuid4
+
+import pytest
+
+from doctor_workstation.video import im_ai
+
+
+class Repository:
+ def __init__(self, pages=None, events=None):
+ self.pages = deque(pages or [{"completed": True, "errors": []}])
+ self.events = events or [{"event": "done", "diagnosis_id": 501, "answer": "合成回复"}]
+ self.sync_calls = []
+ self.stream_calls = []
+ self.cancel_calls = []
+ self.cancel_called = Event()
+
+ def sync_im_chat_messages(self, diagnosis_id, **kwargs):
+ self.sync_calls.append((diagnosis_id, kwargs))
+ return self.pages.popleft()
+
+ def stream_diagnosis_ai(self, diagnosis_id, prompt, **kwargs):
+ self.stream_calls.append((diagnosis_id, prompt, kwargs))
+ yield from self.events
+
+ def cancel_diagnosis_ai(self, diagnosis_id, request_id):
+ self.cancel_calls.append((diagnosis_id, request_id))
+ self.cancel_called.set()
+ return {"cancel_requested": True}
+
+
+def controller(repository=None, **kwargs):
+ return im_ai.ImAiController(
+ repository or Repository(), diagnosis_id=501, appointment_id=101,
+ doctor_account="doctor_7", enabled=True, **kwargs,
+ )
+
+
+def request(service, **changes):
+ return {
+ "source": "doctor-call", "event": "im-ai-request", "sessionId": service.session_id,
+ "requestId": str(uuid4()), "contextKey": "view-1", "diagnosisId": "501",
+ "appointmentId": 101, "action": "summary", **changes,
+ }
+
+
+@pytest.mark.parametrize("action,task", [("summary", "summary"), ("followup", "custom"), ("reply", "custom")])
+def test_current_peer_sync_completes_before_ai_and_keeps_identity(action, task):
+ token = "a" * 48
+ repository = Repository(pages=[
+ {"completed": False, "phase": "checking_accounts", "sync_token": token, "errors": []},
+ {"completed": False, "phase": "syncing", "sync_token": token, "errors": []},
+ {"completed": True, "errors": []},
+ ], events=[
+ {"event": "start"}, {"event": "delta", "text": "合成"},
+ {"event": "done", "diagnosis_id": 501, "answer": "合成完整回复", "model_label": "模型",
+ "clinical_review_warnings": [{"code": "PULSE_EXCLUDED_FROM_ASSESSMENT", "source_id": "report"}]},
+ ])
+ service = controller(repository)
+ message = request(service, action=action)
+ assert service.handle(message)
+ assert service.wait()
+ result = service.take_result()
+ assert result["status"] == "success"
+ assert result["text"] == "合成完整回复"
+ assert result["requestId"] == message["requestId"]
+ assert result["modelLabel"] == "模型"
+ assert "不采集脉象" in result["warnings"][0]
+ assert len(repository.sync_calls) == 3
+ assert repository.sync_calls[0] == (501, {"scope": "current", "sync_token": ""})
+ assert repository.sync_calls[1][1]["sync_token"] == token
+ assert len(repository.stream_calls) == 1
+ diagnosis_id, prompt, options = repository.stream_calls[0]
+ assert diagnosis_id == 501 and options["task"] == task
+ assert options["request_id"] == message["requestId"]
+ assert "doctor_7" in prompt and len(prompt) <= 500
+ assert "不补问脉象" in prompt and "不自动确诊" in prompt
+ assert not repository.cancel_calls
+ assert service.take_result() is None
+ assert not service.handle(message) # A replay cannot submit another billable request.
+
+
+@pytest.mark.parametrize("changes", [
+ {"sessionId": "other"}, {"diagnosisId": "502"}, {"diagnosisId": True},
+ {"diagnosisId": "0501"}, {"appointmentId": 102}, {"requestId": "invalid"},
+ {"contextKey": ""}, {"contextKey": "x" * 129}, {"action": "prescription"},
+ {"action": {}}, {"source": "another-page"}, {"event": "send-message"},
+])
+def test_invalid_identity_or_action_cannot_read_patient_context(changes):
+ repository = Repository()
+ service = controller(repository)
+ assert not service.handle(request(service, **changes))
+ assert not repository.sync_calls and not repository.stream_calls
+
+
+def test_permission_default_denied_and_each_host_has_unique_session():
+ repository = Repository()
+ disabled = im_ai.ImAiController(
+ repository, diagnosis_id=501, appointment_id=101, doctor_account="doctor_7"
+ )
+ assert disabled.config["enabled"] is False
+ assert not disabled.handle(request(disabled))
+ assert controller().session_id != controller().session_id
+
+
+@pytest.mark.parametrize("page", [
+ {"queued": True}, {"completed": "true"}, {"completed": True, "errors": ["private detail"]},
+ {"completed": False, "sync_token": "bad"}, None,
+])
+def test_incomplete_or_failed_sync_never_generates(page):
+ repository = Repository(pages=[page])
+ service = controller(repository)
+ assert service.handle(request(service))
+ assert service.wait()
+ result = service.take_result()
+ assert result["status"] == "error"
+ assert "private detail" not in str(result)
+ assert not repository.stream_calls and not repository.cancel_calls
+
+
+def test_sync_step_and_time_budget_are_bounded():
+ page = {"completed": False, "sync_token": "b" * 48, "errors": []}
+ repository = Repository(pages=[page] * 10)
+ service = controller(repository, max_sync_steps=2)
+ service.handle(request(service))
+ assert service.wait()
+ assert len(repository.sync_calls) == 2
+ assert service.take_result()["status"] == "error"
+ assert not repository.stream_calls
+
+ times = iter([0, 0, 46])
+ repository = Repository()
+ service = controller(repository, clock=lambda: next(times))
+ service.handle(request(service))
+ assert service.wait()
+ assert "超时" in service.take_result()["message"]
+ assert not repository.stream_calls
+
+
+def test_cancel_during_sync_stops_before_model_submission():
+ entered, release = Event(), Event()
+
+ class SlowSync(Repository):
+ def sync_im_chat_messages(self, diagnosis_id, **kwargs):
+ entered.set()
+ assert release.wait(2)
+ return super().sync_im_chat_messages(diagnosis_id, **kwargs)
+
+ repository = SlowSync()
+ service = controller(repository)
+ message = request(service)
+ service.handle(message)
+ try:
+ assert entered.wait(1)
+ assert service.handle({**message, "event": "im-ai-cancel"})
+ assert "尚未向 AI" in service.take_result()["message"]
+ finally:
+ release.set()
+ assert service.wait()
+ assert not repository.stream_calls and not repository.cancel_calls
+ assert service.take_result() is None
+
+
+def test_cancel_is_independent_and_late_response_cannot_overwrite_next_request():
+ entered, release, cancel_release = Event(), Event(), Event()
+
+ class SlowStream(Repository):
+ def stream_diagnosis_ai(self, *args, **kwargs):
+ self.stream_calls.append((args, kwargs))
+ yield {"event": "delta", "text": "尚未完成"}
+ entered.set()
+ assert release.wait(2)
+ yield {"event": "done", "answer": "迟到的旧结果"}
+
+ def cancel_diagnosis_ai(self, *args):
+ result = super().cancel_diagnosis_ai(*args)
+ assert cancel_release.wait(2)
+ return result
+
+ repository = SlowStream()
+ service = controller(repository)
+ first = request(service)
+ service.handle(first)
+ try:
+ assert entered.wait(1)
+ assert service.take_result()["text"] == "尚未完成"
+ service.handle({**first, "event": "im-ai-cancel"})
+ assert repository.cancel_called.wait(1) # Independent HTTP starts while stream is blocked.
+ assert service.take_result()["status"] == "cancelled"
+ second = request(service, contextKey="view-2")
+ assert service.handle(second)
+ result = service.take_result()
+ assert result["requestId"] == second["requestId"] and result["status"] == "error"
+ assert len(repository.stream_calls) == 1
+ finally:
+ release.set()
+ cancel_release.set()
+ assert service.wait()
+ assert service.take_result() is None
+
+
+def test_close_invalidates_mailbox_and_cancels_without_waiting():
+ entered, release = Event(), Event()
+
+ class SlowStream(Repository):
+ def stream_diagnosis_ai(self, *args, **kwargs):
+ entered.set()
+ assert release.wait(2)
+ yield {"event": "done", "answer": "旧患者回复"}
+
+ repository = SlowStream()
+ service = controller(repository)
+ message = request(service)
+ service.handle(message)
+ try:
+ assert entered.wait(1)
+ service.close()
+ assert repository.cancel_called.wait(1)
+ assert service.take_result() is None
+ assert not service.handle(request(service))
+ finally:
+ release.set()
+ assert service.wait()
+ assert service.take_result() is None
+
+
+@pytest.mark.parametrize("events", [
+ [{"event": "delta", "text": "不完整"}],
+ [{"event": "done", "answer": ""}],
+ [{"event": "done", "diagnosis_id": 502, "answer": "其他患者"}],
+ [{"event": "delta", "text": "x" * (im_ai.MAX_RESULT_CHARS + 1)}],
+ [{"event": "done", "answer": "x" * (im_ai.MAX_RESULT_CHARS + 1)}],
+])
+def test_incomplete_mismatched_and_oversized_results_are_not_usable(events):
+ repository = Repository(events=events)
+ service = controller(repository)
+ service.handle(request(service))
+ assert service.wait()
+ assert service.take_result()["status"] == "error"
+ assert repository.cancel_called.wait(1)
+ assert len(repository.stream_calls) == 1 # No transport/validation retry.
+
+
+def test_thousands_of_deltas_are_coalesced_into_one_mailbox_result():
+ events = [{"event": "delta", "text": "字"}] * 4000 + [{"event": "done"}]
+ service = controller(Repository(events=events))
+ service.handle(request(service))
+ assert service.wait()
+ result = service.take_result()
+ assert result["status"] == "success" and result["text"] == "字" * 4000
+ assert service.take_result() is None
+
+
+def test_capacity_rejection_does_not_spawn_or_sync(monkeypatch):
+ slots = BoundedSemaphore(1)
+ slots.acquire()
+ monkeypatch.setattr(im_ai, "_WORKER_SLOTS", slots)
+ repository = Repository()
+ service = controller(repository)
+ try:
+ service.handle(request(service))
+ assert service.take_result()["status"] == "error"
+ assert not repository.sync_calls
+ finally:
+ slots.release()
diff --git a/app/tests/test_im_ai_window.py b/app/tests/test_im_ai_window.py
new file mode 100644
index 000000000..c0107bc3d
--- /dev/null
+++ b/app/tests/test_im_ai_window.py
@@ -0,0 +1,157 @@
+"""Exercise bridge trust and JSON delivery without starting WebEngine or HTTP."""
+
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+import sys
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import Mock
+
+import pytest
+
+from doctor_workstation.video import window
+from doctor_workstation.video.security import TrustedDocumentPolicy
+
+pytestmark = pytest.mark.skipif(not window.WEBENGINE_AVAILABLE, reason="optional QtWebEngine")
+TRUSTED = "https://video.example.test/im/index.html"
+
+
+def host(**changes):
+ item = SimpleNamespace(
+ _closing=False, _released=False, _shutdown_requested=False, _injected=True,
+ _policy=TrustedDocumentPolicy.from_url(TRUSTED, is_local=False),
+ _page=Mock(), _im_ai=Mock(), _im_ai_timer=Mock(),
+ )
+ item._page.url.return_value.toString.return_value = TRUSTED
+ item._im_ai_context_is_trusted = lambda: window._EmbeddedVideoWindow._im_ai_context_is_trusted(item)
+ for key, value in changes.items():
+ setattr(item, key, value)
+ return item
+
+
+@pytest.mark.parametrize("changes", [
+ {"_closing": True}, {"_released": True}, {"_shutdown_requested": True}, {"_injected": False},
+])
+def test_inactive_or_closing_page_cannot_submit_or_receive_ai(changes):
+ item = host(**changes)
+ window._EmbeddedVideoWindow._handle_im_ai_message(item, {"event": "im-ai-request"})
+ window._EmbeddedVideoWindow._flush_im_ai(item)
+ item._im_ai.handle.assert_not_called()
+ item._im_ai.take_result.assert_not_called()
+ item._page.runJavaScript.assert_not_called()
+
+
+@pytest.mark.parametrize("url", ["about:blank", "https://evil.example.test/im/index.html", TRUSTED + "?other=1"])
+def test_document_navigation_cannot_reuse_authenticated_ai_bridge(url):
+ item = host()
+ item._page.url.return_value.toString.return_value = url
+ window._EmbeddedVideoWindow._handle_im_ai_message(item, {"event": "im-ai-request"})
+ window._EmbeddedVideoWindow._flush_im_ai(item)
+ item._im_ai.handle.assert_not_called()
+ item._page.runJavaScript.assert_not_called()
+
+
+def test_trusted_bridge_routes_only_to_identity_checked_controller():
+ item = host()
+ message = {"source": "doctor-call", "event": "im-ai-request", "diagnosisId": 501}
+ window._EmbeddedVideoWindow._handle_im_ai_message(item, message)
+ item._im_ai.handle.assert_called_once_with(message)
+
+
+def test_result_content_is_json_encoded_and_no_javascript_is_executed():
+ item = host()
+ payload = {"status": "success", "text": '\");window.bad=true;//\n\u2028', "warnings": ["合成提示"]}
+ item._im_ai.take_result.return_value = payload
+ window._EmbeddedVideoWindow._flush_im_ai(item)
+ script = item._page.runJavaScript.call_args.args[0]
+ prefix, suffix = "window.doctorConsultation?.imAiResult?.(", ");"
+ assert script.startswith(prefix) and script.endswith(suffix)
+ assert json.loads(script[len(prefix):-len(suffix)]) == payload
+ assert "\\u2028" in script
+
+
+def test_host_acknowledges_initial_summary_only_after_request_gate_opens():
+ item = host(_injected=False)
+ item._im_ai.session_id = 'synthetic-session-\\"\u2028'
+
+ def verify_gate(script):
+ assert item._im_ai_context_is_trusted() is True
+ prefix, suffix = "window.doctorConsultation?.imAiReady?.(", ");"
+ assert script.startswith(prefix) and script.endswith(suffix)
+ assert json.loads(script[len(prefix):-len(suffix)]) == item._im_ai.session_id
+
+ item._page.runJavaScript.side_effect = verify_gate
+ window._EmbeddedVideoWindow._after_injection(item, True)
+ item._page.runJavaScript.assert_called_once()
+
+
+@pytest.mark.parametrize("changes", [
+ {"_closing": True}, {"_released": True}, {"_shutdown_requested": True},
+])
+def test_late_injection_cannot_acknowledge_a_closed_ai_context(changes):
+ item = host(_injected=False, **changes)
+ window._EmbeddedVideoWindow._after_injection(item, True)
+ item._page.runJavaScript.assert_not_called()
+
+
+def test_navigation_cannot_receive_ai_readiness_acknowledgement():
+ item = host(_injected=False)
+ item._page.url.return_value.toString.return_value = "https://evil.example.test/im/index.html"
+ window._EmbeddedVideoWindow._after_injection(item, True)
+ item._page.runJavaScript.assert_not_called()
+
+
+def test_failed_injection_closes_without_ai_readiness_acknowledgement():
+ item = host(_injected=False, _request_companion_shutdown=Mock())
+ window._EmbeddedVideoWindow._after_injection(item, False)
+ item._request_companion_shutdown.assert_called_once_with("bridge-api-missing")
+ item._page.runJavaScript.assert_not_called()
+
+
+def test_shutdown_cancels_ai_before_waiting_for_media_or_destroying_page():
+ item = host(
+ _start_requested=True, _call_cycle_closed=False, _companion_ended=False,
+ _shutdown_timer=Mock(), close=Mock(),
+ )
+ window._EmbeddedVideoWindow._request_companion_shutdown(item, "window-closed")
+ item._im_ai.close.assert_called_once()
+ item._im_ai_timer.stop.assert_called_once()
+ assert item._shutdown_requested is True
+ item.close.assert_not_called() # Recording shutdown still gets its existing grace period.
+ item._shutdown_timer.start.assert_called_once_with(190_000)
+
+
+def test_qt_notify_rejects_oversized_or_wrong_source_payloads():
+ callback = Mock()
+ bridge = window._QtVideoBridge(callback, Mock())
+ bridge.notify("x" * 16_385)
+ bridge.notify(json.dumps({"source": "evil", "event": "im-ai-request"}))
+ bridge.notify("[]")
+ callback.assert_not_called()
+ message = {"source": "doctor-call", "event": "im-ai-cancel"}
+ bridge.notify(json.dumps(message))
+ callback.assert_called_once_with(message)
+
+
+def test_video_module_remains_importable_without_optional_qt():
+ source = Path(__file__).resolve().parents[1] / "src"
+ script = """
+import builtins
+original_import = builtins.__import__
+def without_qt(name, *args, **kwargs):
+ if name == 'PySide6' or name.startswith('PySide6.'):
+ raise ImportError('synthetic core-only installation')
+ return original_import(name, *args, **kwargs)
+builtins.__import__ = without_qt
+from doctor_workstation.video.window import WEBENGINE_AVAILABLE, VideoCallWindow
+from doctor_workstation.video.im_ai import ImAiController
+assert WEBENGINE_AVAILABLE is False
+"""
+ result = subprocess.run(
+ [sys.executable, "-c", script], env={**os.environ, "PYTHONPATH": str(source)},
+ capture_output=True, text=True, timeout=10, check=False,
+ )
+ assert result.returncode == 0, result.stderr
diff --git a/app/tests/test_motion.py b/app/tests/test_motion.py
index aba2864ec..94f994f39 100644
--- a/app/tests/test_motion.py
+++ b/app/tests/test_motion.py
@@ -12,17 +12,16 @@ from __future__ import annotations
import os
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
-# The module disables itself under the offscreen platform so widget grabs in the
-# other suites capture settled frames; these tests are about the animation, so
-# they opt back in.
-os.environ["DOCTOR_MOTION"] = "on"
-
import pytest
-from PySide6.QtCore import QEvent, QPoint, QPointF, Qt
-from PySide6.QtGui import QWheelEvent
+from PySide6.QtCore import QAbstractAnimation, QEvent, QPoint, QPointF, QPropertyAnimation, Qt
+from PySide6.QtGui import QKeyEvent, QWheelEvent
from PySide6.QtWidgets import (
+ QAbstractItemView,
QApplication,
+ QGraphicsDropShadowEffect,
QLabel,
+ QListWidget,
+ QPlainTextEdit,
QScrollArea,
QStackedWidget,
QVBoxLayout,
@@ -32,6 +31,13 @@ from PySide6.QtWidgets import (
from doctor_workstation.ui import motion
+@pytest.fixture(autouse=True)
+def enable_motion(monkeypatch: pytest.MonkeyPatch) -> None:
+ # Opt in per test so collecting this module does not animate other suites'
+ # screenshots or leak motion settings across the shared QApplication.
+ monkeypatch.setenv("DOCTOR_MOTION", "on")
+
+
@pytest.fixture(scope="module")
def application() -> QApplication:
return QApplication.instance() or QApplication([])
@@ -122,15 +128,22 @@ def _scroll_area(application: QApplication) -> QScrollArea:
return area
-def _wheel(delta: int) -> QWheelEvent:
+def _wheel(
+ delta: int,
+ *,
+ horizontal: int = 0,
+ pixels: int = 0,
+ modifiers: Qt.KeyboardModifier = Qt.KeyboardModifier.NoModifier,
+ phase: Qt.ScrollPhase = Qt.ScrollPhase.NoScrollPhase,
+) -> QWheelEvent:
return QWheelEvent(
QPointF(50, 50),
QPointF(50, 50),
- QPoint(0, 0),
- QPoint(0, delta),
+ QPoint(0, pixels),
+ QPoint(horizontal, delta),
Qt.MouseButton.NoButton,
- Qt.KeyboardModifier.NoModifier,
- Qt.ScrollPhase.NoScrollPhase,
+ modifiers,
+ phase,
False,
)
@@ -226,3 +239,273 @@ def test_reading_surfaces_get_smooth_scrolling_from_the_theme(
assert getattr(area, "_doctor_smooth_scroll", None) is not None
area.close()
+
+
+def test_repeated_fade_continues_from_current_opacity(application: QApplication) -> None:
+ widget = QWidget()
+ motion.fade_in(widget)
+ first = widget._doctor_motion["fade"]
+ first.setCurrentTime(motion.BASE // 2)
+ opacity = widget.graphicsEffect().opacity()
+
+ motion.fade_in(widget)
+
+ assert widget.graphicsEffect().opacity() == pytest.approx(opacity)
+ assert widget._doctor_motion["fade"].startValue() == pytest.approx(opacity)
+ assert first.state() == QAbstractAnimation.State.Stopped
+ widget.close()
+
+
+def test_fade_out_starts_at_full_opacity(application: QApplication) -> None:
+ widget = QWidget()
+ widget.show()
+
+ motion.fade_out(widget)
+
+ assert widget.graphicsEffect().opacity() == pytest.approx(1.0)
+ widget.close()
+
+
+def test_reversing_fade_does_not_run_cancelled_hide_callback(application: QApplication) -> None:
+ widget = QWidget()
+ widget.show()
+ completed = []
+ motion.fade_out(widget, on_finished=lambda: completed.append(True))
+ outgoing = widget._doctor_motion["fade"]
+ outgoing.setCurrentTime(motion.FAST // 2)
+ opacity = widget.graphicsEffect().opacity()
+
+ motion.fade_in(widget)
+ incoming = widget._doctor_motion["fade"]
+
+ assert incoming.startValue() == pytest.approx(opacity)
+ incoming.setCurrentTime(incoming.duration())
+ application.processEvents()
+ assert widget.isVisible()
+ assert not completed
+ assert widget.graphicsEffect() is None
+ widget.close()
+
+
+def test_previous_fade_cleanup_does_not_delete_reentrant_fade(application: QApplication) -> None:
+ widget = QWidget()
+ widget.show()
+ motion.fade_out(widget, on_finished=lambda: motion.fade_in(widget))
+ outgoing = widget._doctor_motion["fade"]
+
+ outgoing.setCurrentTime(outgoing.duration())
+ incoming = widget._doctor_motion["fade"]
+ effect = widget.graphicsEffect()
+ application.processEvents()
+
+ assert widget.graphicsEffect() is effect
+ assert incoming.state() == QAbstractAnimation.State.Running
+ incoming.setCurrentTime(incoming.duration())
+ application.processEvents()
+ assert widget.graphicsEffect() is None
+ assert widget.isVisible()
+ widget.close()
+
+
+def test_replaced_and_completed_animations_are_released(application: QApplication) -> None:
+ widget = QWidget()
+ destroyed = []
+ for _ in range(10):
+ motion.fade_in(widget)
+ widget._doctor_motion["fade"].destroyed.connect(lambda: destroyed.append(True))
+ fade = widget._doctor_motion["fade"]
+ fade.setCurrentTime(fade.duration())
+ application.processEvents()
+ application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
+
+ assert not widget._doctor_motion
+ assert not widget.findChildren(QPropertyAnimation)
+ assert len(destroyed) == 10
+ widget.close()
+
+
+def test_fades_preserve_existing_graphics_effects(application: QApplication) -> None:
+ widget = QWidget()
+ shadow = QGraphicsDropShadowEffect(widget)
+ widget.setGraphicsEffect(shadow)
+
+ motion.fade_in(widget)
+ assert widget.graphicsEffect() is shadow
+ motion.fade_out(widget)
+ application.processEvents()
+
+ assert widget.graphicsEffect() is shadow
+ assert widget.isHidden()
+ widget.close()
+
+
+def test_repeated_enter_does_not_accumulate_position_offset(application: QApplication) -> None:
+ host = QWidget()
+ widget = QWidget(host)
+ origin = QPoint(10, 20)
+ widget.move(origin)
+ motion.enter(widget)
+ widget._doctor_motion["enter"].setCurrentTime(motion.BASE // 3)
+ position = widget.pos()
+
+ motion.enter(widget)
+
+ assert widget.pos() == position
+ arrival = widget._doctor_motion["enter"]
+ assert arrival.endValue() == origin
+ arrival.setCurrentTime(arrival.duration())
+ assert widget.pos() == origin
+ host.close()
+
+
+def test_disabling_motion_settles_an_active_entry(
+ application: QApplication, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ host = QWidget()
+ widget = QWidget(host)
+ origin = QPoint(10, 20)
+ widget.move(origin)
+ motion.enter(widget)
+ monkeypatch.setenv("DOCTOR_MOTION", "off")
+
+ motion.enter(widget)
+ application.processEvents()
+
+ assert widget.pos() == origin
+ assert widget.graphicsEffect() is None
+ assert not widget._doctor_motion
+ host.close()
+
+
+def test_wheel_reversal_discards_pending_travel(application: QApplication) -> None:
+ area = _scroll_area(application)
+ motion.install_smooth_scroll(area)
+ scroller = area._doctor_smooth_scroll
+ bar = area.verticalScrollBar()
+ bar.setValue(500)
+ for _ in range(4):
+ scroller.eventFilter(area.viewport(), _wheel(-120))
+ scroller._animation.setCurrentTime(30)
+ position = bar.value()
+
+ scroller.eventFilter(area.viewport(), _wheel(120))
+
+ assert scroller._animation.startValue() == position
+ assert scroller._animation.endValue() == position - motion.SCROLL_STEP
+ scroller._animation.setCurrentTime(60)
+ assert bar.value() < position
+ area.close()
+
+
+@pytest.mark.parametrize("interaction", ["set_value", "keyboard", "slider_press", "range_change"])
+def test_direct_scroll_interaction_cancels_pending_wheel(
+ application: QApplication, interaction: str
+) -> None:
+ area = _scroll_area(application)
+ motion.install_smooth_scroll(area)
+ scroller = area._doctor_smooth_scroll
+ bar = area.verticalScrollBar()
+ scroller.eventFilter(area.viewport(), _wheel(-120))
+ scroller._animation.setCurrentTime(30)
+
+ if interaction == "set_value":
+ bar.setValue(500)
+ elif interaction == "keyboard":
+ application.sendEvent(
+ area,
+ QKeyEvent(QEvent.Type.KeyPress, Qt.Key.Key_Down, Qt.KeyboardModifier.NoModifier),
+ )
+ elif interaction == "slider_press":
+ bar.setSliderDown(True)
+ else:
+ bar.setRange(0, 50)
+
+ assert scroller._animation.state() == QAbstractAnimation.State.Stopped
+ assert scroller._target == bar.value()
+ if interaction == "set_value":
+ scroller.eventFilter(area.viewport(), _wheel(-120))
+ assert scroller._animation.endValue() == 500 + motion.SCROLL_STEP
+ area.close()
+
+
+@pytest.mark.parametrize(
+ "wheel_options",
+ [
+ {"pixels": -8},
+ {"phase": Qt.ScrollPhase.ScrollUpdate},
+ {"phase": Qt.ScrollPhase.ScrollMomentum},
+ {"modifiers": Qt.KeyboardModifier.ControlModifier},
+ {"modifiers": Qt.KeyboardModifier.ShiftModifier},
+ {"horizontal": -120},
+ ],
+)
+def test_native_gestures_cancel_pending_wheel(
+ application: QApplication, wheel_options: dict
+) -> None:
+ area = _scroll_area(application)
+ motion.install_smooth_scroll(area)
+ scroller = area._doctor_smooth_scroll
+ scroller.eventFilter(area.viewport(), _wheel(-120))
+ scroller._animation.setCurrentTime(30)
+ delta = 0 if "horizontal" in wheel_options else -120
+
+ assert not scroller.eventFilter(area.viewport(), _wheel(delta, **wheel_options))
+ assert scroller._animation.state() == QAbstractAnimation.State.Stopped
+ assert scroller._target == area.verticalScrollBar().value()
+ area.close()
+
+
+@pytest.mark.parametrize("kind", ["items", "text_blocks"])
+def test_non_pixel_scrollbars_keep_native_wheel_steps(application: QApplication, kind: str) -> None:
+ if kind == "items":
+ area = QListWidget()
+ area.addItems([f"row {index}" for index in range(300)])
+ area.setVerticalScrollMode(QAbstractItemView.ScrollMode.ScrollPerItem)
+ else:
+ area = QPlainTextEdit("\n".join(f"line {index}" for index in range(300)))
+ area.resize(300, 200)
+ area.show()
+ application.processEvents()
+ motion.install_smooth_scroll(area)
+
+ assert not area._doctor_smooth_scroll.eventFilter(area.viewport(), _wheel(-120))
+ application.sendEvent(area.viewport(), _wheel(-120))
+ assert 0 < area.verticalScrollBar().value() < motion.SCROLL_STEP
+ area.close()
+
+
+def test_pending_scroll_reaches_edge_before_handing_wheel_back(application: QApplication) -> None:
+ area = _scroll_area(application)
+ motion.install_smooth_scroll(area)
+ scroller = area._doctor_smooth_scroll
+ bar = area.verticalScrollBar()
+ bar.setValue(bar.maximum() - 20)
+
+ assert scroller.eventFilter(area.viewport(), _wheel(-120))
+ assert scroller.eventFilter(area.viewport(), _wheel(-120))
+ scroller._animation.setCurrentTime(scroller._animation.duration())
+ assert not scroller.eventFilter(area.viewport(), _wheel(-120))
+ area.close()
+
+
+def test_horizontal_scroller_honors_horizontal_and_shift_wheel(application: QApplication) -> None:
+ area = QScrollArea()
+ content = QWidget()
+ content.resize(2000, 1000)
+ area.setWidget(content)
+ area.resize(300, 200)
+ motion.install_smooth_scroll(area, orientation=Qt.Orientation.Horizontal)
+ area.show()
+ application.processEvents()
+ scroller = area._doctor_smooth_scroll
+
+ assert not scroller.eventFilter(area.viewport(), _wheel(-120))
+ assert scroller.eventFilter(area.viewport(), _wheel(0, horizontal=-120))
+ scroller._animation.setCurrentTime(scroller._animation.duration())
+ assert area.horizontalScrollBar().value() == motion.SCROLL_STEP
+ assert area.verticalScrollBar().value() == 0
+ assert scroller.eventFilter(
+ area.viewport(), _wheel(-120, modifiers=Qt.KeyboardModifier.ShiftModifier)
+ )
+ assert scroller._animation.endValue() == motion.SCROLL_STEP * 2
+ area.close()
diff --git a/app/tests/test_prescriptions_tech_blue.py b/app/tests/test_prescriptions_tech_blue.py
index 8a4613f86..3c529ec04 100644
--- a/app/tests/test_prescriptions_tech_blue.py
+++ b/app/tests/test_prescriptions_tech_blue.py
@@ -16,6 +16,7 @@ from PySide6.QtWidgets import QAbstractItemView, QApplication, QPushButton
from doctor_workstation.core import PermissionSet
from doctor_workstation.services import DemoDoctorRepository
from doctor_workstation.ui import icons
+from doctor_workstation.ui.design_system import PALETTE
from doctor_workstation.ui.pages import prescriptions as prescriptions_module
from doctor_workstation.ui.shell import ShellWindow
from doctor_workstation.ui.theme import apply_theme
@@ -222,7 +223,7 @@ def test_sorted_native_row_view_button_targets_visible_record(
def test_blue_icon_disabled_variant_does_not_modify_shared_icon_cache(application) -> None:
- kind, color, size = "pencil", "#1769E8", 19
+ kind, color, size = "pencil", PALETTE["accent"], 19
shared = icons.icon(kind, color, size)
original_key = shared.cacheKey()
original_normal = shared.pixmap(size, size, QIcon.Mode.Normal).toImage()
@@ -230,13 +231,19 @@ def test_blue_icon_disabled_variant_does_not_modify_shared_icon_cache(applicatio
blue = prescriptions_module._blue_prescription_icon(kind, color, size)
+ assert blue is not shared
assert icons.icon(kind, color, size) is shared
assert shared.cacheKey() == original_key
assert shared.pixmap(size, size, QIcon.Mode.Normal).toImage() == original_normal
assert shared.pixmap(size, size, QIcon.Mode.Disabled).toImage() == original_disabled
assert blue.pixmap(size, size, QIcon.Mode.Normal).toImage() == original_normal
- assert blue.pixmap(size, size, QIcon.Mode.Disabled).toImage() == icons.pixmap(kind, "#A4ADBA", size).toImage()
- assert blue.pixmap(size, size, QIcon.Mode.Disabled).toImage() != original_disabled
+ assert blue.pixmap(size, size, QIcon.Mode.Disabled).toImage() == icons.pixmap(kind, PALETTE["disabled"], size).toImage()
+ assert blue.pixmap(size, size, QIcon.Mode.Disabled).toImage() == original_disabled
+ # Both surfaces share the disabled colour; changing the returned icon still
+ # must not mutate the cached icon used by another page.
+ blue.addPixmap(icons.pixmap(kind, PALETTE["danger"], size), QIcon.Mode.Disabled)
+ assert shared.cacheKey() == original_key
+ assert shared.pixmap(size, size, QIcon.Mode.Disabled).toImage() == original_disabled
def test_long_doctor_button_paints_compactly_without_truncating_real_value(shell_factory, application) -> None:
diff --git a/app/tests/test_reception_blue_design.py b/app/tests/test_reception_blue_design.py
index fdc7c696e..801f669be 100644
--- a/app/tests/test_reception_blue_design.py
+++ b/app/tests/test_reception_blue_design.py
@@ -6,6 +6,7 @@ from PySide6.QtGui import QPalette
from PySide6.QtWidgets import QApplication, QFrame, QLabel, QPushButton
from doctor_workstation.core import PermissionSet
+from doctor_workstation.ui.design_system import PALETTE
from doctor_workstation.ui.pages import reception as reception_module
from doctor_workstation.ui.pages.reception import ReceptionPage
from doctor_workstation.ui.theme import apply_theme
@@ -43,12 +44,12 @@ def page(application, monkeypatch):
def test_primary_action_and_reading_ink_use_separate_colors(page, application):
page.video_button.setEnabled(True)
settle(application)
- assert page.video_button.palette().color(QPalette.ColorRole.Button).name() == "#1769e8"
- assert page.video_button.palette().color(QPalette.ColorRole.ButtonText).name() == "#ffffff"
- assert page.case_labels["present"].palette().color(QPalette.ColorRole.WindowText).name() == "#273244"
+ assert page.video_button.palette().color(QPalette.ColorRole.Button).name() == PALETTE["accent"].lower()
+ assert page.video_button.palette().color(QPalette.ColorRole.ButtonText).name() == PALETTE["surface"].lower()
+ assert page.case_labels["present"].palette().color(QPalette.ColorRole.WindowText).name() == PALETTE["text"].lower()
page.video_button.setEnabled(False)
settle(application)
- assert page.video_button.palette().color(QPalette.ColorRole.ButtonText).name() == "#8e8f90"
+ assert page.video_button.palette().color(QPalette.ColorRole.ButtonText).name() == PALETTE["disabled"].lower()
def test_typography_preserves_regular_body_and_distinct_values(page):
diff --git a/app/tests/test_text_call_policy.py b/app/tests/test_text_call_policy.py
index 88ccb9671..5bfa572d8 100644
--- a/app/tests/test_text_call_policy.py
+++ b/app/tests/test_text_call_policy.py
@@ -164,6 +164,59 @@ def test_diagnosis_callback_previews_exact_appointment_session(chat_controller):
assert len(case.previews) == 1 # A closed session cannot borrow another appointment's video.
+@pytest.mark.parametrize("permissions, expected", [
+ (None, False),
+ ([], False),
+ (["tcm.diagnosis/read"], False),
+ (["tcm.diagnosis.aiAssistant"], False),
+ (["tcm.diagnosis/aiAssistant"], True),
+ (["tcm.diagnosis/*"], True),
+ (["*"], True),
+])
+def test_im_ai_capability_comes_from_current_shell_permissions(chat_controller, permissions, expected):
+ case = chat_controller
+ case.controller.shell_window.permissions = permissions
+ case.controller._request_video({
+ "patient_id": 8, "diagnosis_id": 123, "appointment_id": 456,
+ "mode": "im", "can_ai_assistant": True,
+ })
+ case.complete(0)
+ assert case.launched[0][1]["can_ai_assistant"] is expected
+
+
+def test_im_ai_permission_is_evaluated_after_ticket_load(chat_controller):
+ case = chat_controller
+ case.controller.shell_window.permissions = ["tcm.diagnosis/aiAssistant"]
+ case.request(456)
+ case.controller.shell_window.permissions = []
+ case.complete(0)
+ assert case.launched[0][1]["can_ai_assistant"] is False
+
+
+@pytest.mark.parametrize("capability, expected", [(True, True), (False, False), (None, False), (1, False), ("true", False)])
+def test_video_launcher_forwards_only_explicit_ai_capability(monkeypatch, capability, expected):
+ from doctor_workstation.video import window as window_module
+ from doctor_workstation.video.launcher import launch_video_call
+
+ launches = []
+ sentinel = object()
+
+ def capture(request, **kwargs):
+ launches.append((request, kwargs))
+ return sentinel
+
+ monkeypatch.setattr(window_module, "open_video_call", capture)
+ result = launch_video_call(
+ ticket(), repository=object(), open_im=True, can_ai_assistant=capability,
+ )
+ assert result is sentinel
+ request, options = launches[0]
+ assert request.diagnosis_id == 123
+ assert request.patient_id == 8
+ assert request.appointment_id == 456
+ assert options["can_ai_assistant"] is expected
+
+
@pytest.mark.parametrize("second_diagnosis", [123, 124])
@pytest.mark.parametrize("completion_order", [(0, 1), (1, 0)])
def test_latest_im_selection_retires_pending_callbacks(chat_controller, second_diagnosis, completion_order):
diff --git a/app/tests/test_ui_contract.py b/app/tests/test_ui_contract.py
index 7bc78229b..648072cb1 100644
--- a/app/tests/test_ui_contract.py
+++ b/app/tests/test_ui_contract.py
@@ -295,6 +295,48 @@ def test_real_demo_login_reaches_success_without_widget_adapter(
application.processEvents()
+def test_login_password_group_keeps_focus_when_reveal_is_keyboard_focused(tmp_path: Any) -> None:
+ application = QApplication.instance() or QApplication([])
+ apply_theme(application)
+ window = LoginWindow(
+ object(), settings=QSettings(str(tmp_path / "focus.ini"), QSettings.Format.IniFormat),
+ )
+ window.show()
+ application.processEvents()
+ group = window.password_edit.parentWidget()
+ geometry = group.geometry()
+ try:
+ for control in (window.password_edit, window.reveal_button):
+ control.setFocus()
+ application.processEvents()
+ assert group.property("focused") is True
+ assert group.geometry() == geometry
+ window.login_button.setFocus()
+ application.processEvents()
+ assert group.property("focused") is False
+ assert group.geometry() == geometry
+ finally:
+ window.close()
+
+
+def test_compact_login_keeps_the_whole_form_visible(tmp_path: Any) -> None:
+ application = QApplication.instance() or QApplication([])
+ apply_theme(application)
+ window = LoginWindow(
+ object(), settings=QSettings(str(tmp_path / "compact.ini"), QSettings.Format.IniFormat),
+ )
+ window.resize(860, 640)
+ window.show()
+ application.processEvents()
+ try:
+ assert not window.brand_panel.isVisible()
+ assert window.login_scroll.verticalScrollBar().maximum() == 0
+ assert window.card.height() >= window.card.minimumSizeHint().height()
+ assert window.login_button.isVisibleTo(window)
+ finally:
+ window.close()
+
+
def test_remembered_password_survives_a_new_login_window(tmp_path: Any) -> None:
application = QApplication.instance() or QApplication([])
settings_path = tmp_path / "remember-password.ini"
diff --git a/app/tests/test_ui_detail_refinements.py b/app/tests/test_ui_detail_refinements.py
index acac857b1..c19fb5681 100644
--- a/app/tests/test_ui_detail_refinements.py
+++ b/app/tests/test_ui_detail_refinements.py
@@ -38,6 +38,8 @@ def page(application, monkeypatch):
def test_reception_prompts_remain_readable_in_a_narrow_workspace(page, application):
+ # The responsive workspace exposes insights in its second tab.
+ page.workbench.mode_tabs.setCurrentIndex(1)
settle(application)
for button in page.ai_prompt_buttons:
assert button.width() >= button.minimumSizeHint().width()
@@ -48,6 +50,8 @@ def test_reception_prompts_remain_readable_in_a_narrow_workspace(page, applicati
def test_hidden_tall_consultation_does_not_expand_daily_records(page, application):
+ # Force real overflow: a short case is allowed to fill the viewport.
+ page.case_labels["present"].setText("Long clinical history\n" * 80)
page.detail_tabs.setCurrentIndex(0)
settle(application)
consultation_height = page.clinical_pages.height()
diff --git a/app/video_companion/dist/assets/index-CMN1CXTr.css b/app/video_companion/dist/assets/index-CMN1CXTr.css
new file mode 100644
index 000000000..38989167b
--- /dev/null
+++ b/app/video_companion/dist/assets/index-CMN1CXTr.css
@@ -0,0 +1 @@
+:root{--accent: #4267b2;--accent-hover: #355995;--accent-soft: #eaf0fb;--surface: #fff;--surface-soft: #f5f7fa;--border: #e6eaf0;--text: #344258;--muted: #647287;--heading: #223047;--surface-alt: #f7f9fc;--border-strong: #d4dce8;--success: #287b65;--success-soft: #edf7f2;--danger: #b54a59;--danger-soft: #fcf0f2;--radius-small: 6px;--radius-panel: 16px;--radius-control: 10px;--motion-ease: cubic-bezier(.2, .7, .2, 1);font-family:Microsoft YaHei UI,PingFang SC,Noto Sans CJK SC,system-ui,sans-serif;color:var(--text);background:var(--surface-soft);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;transition:background-color .14s var(--motion-ease),border-color .14s var(--motion-ease),color .14s var(--motion-ease),transform .12s var(--motion-ease)}button:enabled:active{transform:translateY(1px)}button:focus-visible,a:focus-visible{outline:2px solid var(--accent);outline-offset:3px}button:disabled{cursor:not-allowed;opacity:.55}.consultation-shell{width:100%;height:100%;min-width:0;min-height:0;background:var(--surface-soft)}.consultation-shell--video-only{min-height:0}.consultation-shell--with-ai{display:grid;grid-template-columns:minmax(0,1fr) var(--im-ai-panel-width, 330px);column-gap:8px}.im-ai-resizer{position:absolute;z-index:1;top:0;bottom:0;left:-8px;width:8px;min-height:0;cursor:col-resize;touch-action:none;background:var(--surface-soft);outline:none}.im-ai-resizer:before{position:absolute;inset:0 3px;border-radius:2px;background:var(--border);content:""}.im-ai-resizer>span{position:absolute;top:calc(50% - 20px);left:2px;width:4px;height:40px;border-radius:3px;background:var(--border-strong)}.im-ai-resizer:hover:before,.im-ai-resizer:focus-visible:before,.consultation-shell--resizing .im-ai-resizer:before{background:var(--accent)}.im-ai-resizer:focus-visible{outline:2px solid var(--accent);outline-offset:-2px}.consultation-shell--resizing,.consultation-shell--resizing *{cursor:col-resize!important;user-select:none!important}.chat-panel{display:grid;grid-template-rows:minmax(74px,auto) minmax(0,1fr) auto;width:100%;height:100%;min-width:0;min-height:0;background:var(--surface-soft)}.chat-header{display:flex;align-items:center;gap:14px;padding:12px 20px;border-bottom:1px solid var(--border);background:var(--surface)}.patient-avatar{display:grid;place-items:center;width:44px;height:44px;border-radius:var(--radius-control);color:#fff;background:var(--accent);font-size:18px;font-weight:700}.chat-heading{min-width:0;flex:1}.chat-heading h1{margin:0;color:var(--heading);font-size:18px;line-height:1.4}.chat-heading p{display:flex;align-items:center;gap:7px;margin:3px 0 0;color:var(--muted);font-size:12px}.connection-dot{width:7px;height:7px;border-radius:50%;background:#a3adbd}.connection-dot--online{background:var(--success)}.primary-action,.send-button,.capture-button{border:1px solid var(--accent);border-radius:var(--radius-control);color:#fff;background:var(--accent);font-weight:600}.secondary-action{padding:9px 13px;border:1px solid var(--border-strong);border-radius:var(--radius-control);color:var(--text);background:#fff;font-weight:600}.secondary-action:enabled:hover{border-color:var(--accent);color:var(--accent-hover);background:var(--accent-soft)}.primary-action{display:flex;gap:8px;align-items:center;padding:10px 16px}.primary-action:enabled:hover,.send-button:enabled:hover,.capture-button:enabled:hover{background:var(--accent-hover)}.message-list{overflow-y:auto;padding:18px max(24px,calc((100% - 920px)/2));background:var(--surface-soft)}.load-more{display:block;margin:0 auto 18px;padding:6px 12px;border:1px solid var(--border);border-radius:var(--radius-control);color:var(--muted);background:#fff;font-size:12px}.empty-chat{display:grid;justify-items:center;margin-top:min(16vh,110px);color:var(--muted);text-align:center}.empty-chat__icon{display:grid;place-items:center;width:62px;height:62px;margin-bottom:12px;border:1px solid var(--border);border-radius:var(--radius-panel);color:var(--accent);background:#fff;font-weight:800}.empty-chat h2{margin:0;color:var(--heading);font-size:17px}.empty-chat p{margin:7px 0;font-size:13px}.message-row{display:flex;flex-direction:column;align-items:flex-start;margin:12px 0}.message-row--mine{align-items:flex-end}.message-row--call-status{align-items:center;margin:16px 0}.call-status-event{display:inline-flex;align-items:center;gap:8px;min-height:32px;padding:0 12px;border:1px solid var(--border);border-radius:var(--radius-control);color:var(--muted);background:var(--surface);font-size:12px}.call-status-event__icon{display:grid;place-items:center;width:20px;height:20px;border-radius:10px;color:var(--accent);background:var(--accent-soft);font-size:11px}.call-status-event strong{color:var(--heading);font-weight:700}.call-status-event time{color:var(--muted);font-variant-numeric:tabular-nums}.call-status-event--connected{border-color:#bdebdc;background:var(--success-soft)}.call-status-event--connected .call-status-event__icon{color:var(--success);background:#dff7ee}.call-status-event--failed{border-color:#f3c8cf;background:var(--danger-soft)}.call-status-event--failed .call-status-event__icon{color:var(--danger);background:#ffe6e9}.message-meta{margin:0 8px 5px;color:var(--muted);font-size:11px}.message-bubble{max-width:min(72%,620px);padding:10px 13px;border:1px solid var(--border);border-radius:10px var(--radius-panel) var(--radius-panel) var(--radius-panel);background:#fff;line-height:1.6;word-break:break-word}.message-row--mine .message-bubble{border-color:var(--accent);border-radius:var(--radius-panel) 10px var(--radius-panel) var(--radius-panel);color:#fff;background:var(--accent)}.message-bubble p{margin:0;white-space:pre-wrap}.message-image,.message-video{display:block;max-width:min(360px,100%);max-height:280px;border-radius:var(--radius-control)}.message-file{display:flex;align-items:center;gap:8px;color:inherit;text-decoration:none}.message-bubble audio{max-width:min(320px,100%)}.composer{padding:10px 18px 14px;border-top:1px solid var(--border);background:#fff}.composer-toolbar{display:flex;align-items:center;justify-content:space-between;min-height:30px;color:var(--muted);font-size:11px}.composer-toolbar button{padding:5px 9px;border:0;border-radius:10px;color:var(--accent);background:var(--accent-soft);font-size:12px}.composer-tools{display:flex;align-items:center;gap:8px;min-width:0}.composer-toolbar .im-ai-toggle{display:none}.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 var(--border-strong);border-radius:var(--radius-control);outline:none;transition:border-color .14s var(--motion-ease),background-color .14s var(--motion-ease);color:var(--text);background:var(--surface-alt);line-height:1.5}.composer textarea:focus{border-color:var(--accent);outline:2px solid var(--accent-soft);outline-offset:1px;background:var(--surface)}.send-button{align-self:end;height:40px}.inline-notice{margin-bottom:7px;color:var(--success);font-size:12px}.inline-notice--error{color:var(--danger)}.im-ai-panel{position:relative;display:grid;grid-template-rows:auto auto minmax(0,1fr) auto;min-width:0;min-height:0;height:100%;overflow:visible;border-left:1px solid var(--border);background:var(--surface);color:var(--text)}.im-ai-header{display:flex;align-items:center;gap:10px;min-height:74px;padding:14px 18px}.im-ai-mark{display:grid;place-items:center;flex-shrink:0;width:32px;height:32px;border:1px solid var(--border-strong);border-radius:var(--radius-control);color:var(--accent);background:var(--surface-alt);font-size:12px;font-weight:700;letter-spacing:.02em}.im-ai-header>div{flex:1;min-width:0}.im-ai-header h2{margin:0;color:var(--heading);font-size:15px;line-height:1.5;font-weight:600}.im-ai-header p{margin:2px 0 0;color:var(--muted);font-size:11px}.im-ai-close{display:none;width:32px;height:32px;flex-shrink:0;border:0;border-radius:var(--radius-small);background:var(--surface-soft);color:var(--muted);font-size:23px;line-height:1}.im-ai-close:hover{background:var(--accent-soft);color:var(--accent)}.im-ai-tools{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:5px;padding:0 14px 14px;border-bottom:1px solid var(--border)}.im-ai-tools button{min-height:36px;padding:7px 4px;border:1px solid var(--border);border-radius:var(--radius-small);background:var(--surface);color:var(--muted);font-size:12px;white-space:nowrap}.im-ai-tools button:enabled:hover,.im-ai-tools .im-ai-tool--selected{border-color:var(--border-strong);background:var(--accent-soft);color:var(--accent-hover)}.im-ai-tools .im-ai-tool--selected{font-weight:600}.im-ai-tool__saved{margin-left:3px;color:var(--success);font-weight:700}.im-ai-body{min-height:0;overflow-y:auto;padding:18px;overscroll-behavior:contain}.im-ai-body:focus-visible{outline:2px solid var(--accent-soft);outline-offset:-2px}.im-ai-empty{padding:16px 0}.im-ai-empty__line{display:block;width:28px;height:3px;margin-bottom:18px;border-radius:2px;background:var(--border-strong)}.im-ai-empty strong{color:var(--heading);font-size:14px;font-weight:600;line-height:1.6}.im-ai-empty p{margin:10px 0;color:var(--muted);font-size:13px;line-height:1.85}.im-ai-empty .im-ai-source{margin-top:26px;padding-top:14px;border-top:1px solid var(--border);font-size:11px}.im-ai-result-heading{display:flex;align-items:baseline;justify-content:space-between;flex-wrap:wrap;gap:6px;margin-bottom:10px}.im-ai-result-heading h3{margin:0;color:var(--heading);font-size:14px;font-weight:600}.im-ai-result-heading span{max-width:100%;color:var(--muted);font-size:10px;overflow-wrap:anywhere}.im-ai-status{margin:0 0 14px;color:var(--muted);font-size:12px;line-height:1.7;overflow-wrap:anywhere}.im-ai-status--error{padding:10px 12px;border-radius:var(--radius-small);color:var(--danger);background:var(--danger-soft)}.im-ai-text{margin:0;overflow-wrap:anywhere;font-size:14px;line-height:1.85}.im-ai-text :is(h1,h2,h3,h4,h5,h6){margin:20px 0 10px;padding-left:9px;border-left:3px solid var(--accent);color:var(--heading);font-size:14px;font-weight:700;line-height:1.65}.im-ai-text>:first-child{margin-top:0}.im-ai-text>:last-child{margin-bottom:0}.im-ai-text p{margin:0 0 12px}.im-ai-text strong{padding:1px 2px;border-radius:3px;background:var(--accent-soft);color:var(--heading);font-weight:700;-webkit-box-decoration-break:clone;box-decoration-break:clone}.im-ai-text .im-ai-metric-label{color:var(--accent-hover);font-weight:600}.im-ai-text .im-ai-metric-value{padding:1px 4px;border-radius:4px;background:#e8effb;color:#234c93;font-weight:700;font-variant-numeric:tabular-nums;-webkit-box-decoration-break:clone;box-decoration-break:clone}.im-ai-text :is(ul,ol){margin:10px 0 16px;padding-left:22px}.im-ai-text li{padding-left:2px;margin:7px 0}.im-ai-text li::marker{color:var(--accent);font-weight:600}.im-ai-text li>p{margin-bottom:6px}.im-ai-text li :is(ul,ol){margin-block:5px}.im-ai-text blockquote{margin:14px 0;padding:9px 12px;border-left:3px solid var(--border-strong);background:var(--surface-soft);color:var(--muted)}.im-ai-text blockquote>:last-child{margin-bottom:0}.im-ai-text code{padding:2px 4px;border-radius:4px;background:var(--surface-soft);color:var(--text);font-size:12px}.im-ai-text pre{margin:14px 0;padding:10px;border-radius:var(--radius-small);background:var(--surface-soft);white-space:pre-wrap;overflow-wrap:anywhere}.im-ai-text pre code{padding:0;background:none}.im-ai-text hr{margin:18px 0;border:0;border-top:1px solid var(--border)}.im-ai-text table{width:100%;margin:14px 0;border-collapse:collapse;table-layout:fixed;font-size:12px}.im-ai-text :is(th,td){padding:7px;border:1px solid var(--border);vertical-align:top;text-align:left}.im-ai-text th{background:var(--surface-soft);color:var(--heading);font-weight:600}.im-ai-loading{display:grid;gap:12px;margin:24px 0}.im-ai-loading span{height:8px;border-radius:4px;background:var(--surface-soft)}.im-ai-loading span:nth-child(2){width:86%}.im-ai-loading span:nth-child(3){width:62%}.im-ai-warnings{margin:18px 0 0;padding:12px 12px 12px 26px;border-radius:var(--radius-small);background:var(--surface-soft);color:var(--muted);font-size:11px;line-height:1.8;overflow-wrap:anywhere}.im-ai-warnings li+li{margin-top:6px}.im-ai-footer{border-top:1px solid var(--border);padding:12px 16px;background:var(--surface-alt)}.im-ai-footer p{margin:8px 0 0;color:var(--muted);font-size:11px;line-height:1.65}.im-ai-result-actions{display:flex;flex-wrap:wrap;align-items:center;gap:8px}.im-ai-result-actions:empty{display:none}.im-ai-result-actions button{min-height:34px;padding:7px 12px;border:1px solid var(--border-strong);border-radius:var(--radius-control);background:var(--surface);color:var(--text);font-size:12px}.im-ai-result-actions button:enabled:hover{border-color:var(--accent);color:var(--accent-hover)}.im-ai-result-actions .im-ai-apply{margin-left:auto;border-color:var(--accent);background:var(--accent);color:#fff;font-weight:600}.im-ai-result-actions .im-ai-apply:enabled:hover{background:var(--accent-hover);color:#fff}.video-layer{position:relative;display:grid;grid-template-columns:minmax(0,1fr);width:100%;height:100%;min-height:420px;overflow:hidden;color:#f7f8fa;background:#101720}.video-layer--with-rail{grid-template-columns:minmax(0,1fr) clamp(330px,31vw,380px)}.video-layer--overlay{position:fixed;z-index:1000;inset:0}.video-stage{position:relative;min-width:0;min-height:0;overflow:hidden;background:#101720}.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 var(--border);border-radius:var(--radius-panel);color:var(--text);background:var(--surface)}.eyebrow{margin:0 0 10px;color:var(--muted);font-size:12px;font-weight:600;letter-spacing:.02em}.status-card h2{margin:0;font-size:clamp(22px,2.4vw,28px);font-weight:600;line-height:1.25}.status-hint{margin:14px 0 0;color:var(--muted);font-size:14px}.status-dot{width:10px;height:10px;margin-top:5px;border-radius:50%;background:#77818c}.status-dot--starting,.status-dot--live{background:var(--success)}.status-dot--error{background:var(--danger)}.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 var(--border);border-radius:var(--radius-control);color:var(--text);background:var(--surface);font-size:13px}.live-status .status-dot{width:7px;height:7px;margin:0;box-shadow:none}.consultation-rail{position:relative;z-index:55;display:grid;grid-template-rows:auto minmax(0,1.08fr) minmax(0,.92fr);min-width:0;min-height:0;overflow:hidden;border-left:1px solid var(--border);color:var(--text);background:var(--surface-soft)}.consultation-rail__header{display:grid;grid-template-columns:42px minmax(0,1fr) auto;gap:11px;align-items:center;min-height:74px;padding:13px 16px;border-bottom:1px solid var(--border);background:#fff}.consultation-rail__avatar{display:grid;place-items:center;width:42px;height:42px;border-radius:var(--radius-control);color:#fff;background:var(--accent);font-size:17px;font-weight:700}.consultation-rail__identity{display:grid;gap:3px;min-width:0}.consultation-rail__identity strong{overflow:hidden;color:var(--text);font-size:16px;line-height:1.3;text-overflow:ellipsis;white-space:nowrap}.consultation-rail__identity span{overflow:hidden;color:var(--muted);font-size:11px;text-overflow:ellipsis;white-space:nowrap}.diagnosis-chip{padding:5px 7px;border-radius:var(--radius-small);color:var(--accent);background:var(--accent-soft);font-size:11px;font-weight:600;font-variant-numeric:tabular-nums;white-space:nowrap}.consultation-rail__actions{display:grid;flex:0 0 auto;justify-items:end;gap:5px}.open-diagnosis-button{display:inline-flex;align-items:center;gap:4px;min-height:28px;padding:5px 8px;border:1px solid var(--border-strong);border-radius:10px;color:var(--accent);background:#fff;font-size:11px;font-weight:700;white-space:nowrap}.open-diagnosis-button:enabled:hover{border-color:var(--accent);background:var(--accent-soft)}.case-panel,.transcript-panel{display:grid;grid-template-rows:auto minmax(0,1fr);min-height:0;overflow:hidden}.case-panel{border-bottom:1px solid var(--border)}.rail-section-heading{display:flex;align-items:center;justify-content:space-between;gap:12px;min-height:48px;padding:10px 16px;border-bottom:1px solid var(--border);background:var(--surface)}.rail-section-heading>div{display:flex;align-items:center;gap:8px}.rail-section-heading h2{margin:0;color:var(--heading);font-size:14px;font-weight:700;letter-spacing:-.01em}.rail-section-heading>span{overflow:hidden;max-width:154px;color:var(--muted);font-size:10px;text-overflow:ellipsis;white-space:nowrap}.rail-section-heading__index{color:var(--accent);font-family:Cascadia Mono,SFMono-Regular,Consolas,monospace;font-size:10px;font-weight:700}.case-panel__content,.live-captions{min-height:0;overflow-y:auto;overscroll-behavior:contain;scrollbar-color:#b9c3d5 transparent;scrollbar-width:thin}.case-panel__content{padding:5px 16px 14px}.case-field-list{display:grid}.case-field{display:grid;grid-template-columns:72px minmax(0,1fr);gap:10px;padding:10px 0;border-bottom:1px solid var(--border)}.case-field:last-child{border-bottom:0}.case-field>span{padding-top:2px;color:var(--muted);font-size:11px;font-weight:600}.case-field p{margin:0;color:var(--text);font-size:12px;line-height:1.55;overflow-wrap:anywhere;white-space:pre-wrap}.case-field--risk>span{color:var(--danger)}.case-field--risk p{color:var(--danger);font-weight:600}.live-captions{display:grid;align-content:start;gap:9px;padding:12px 14px 18px;background:var(--surface-soft)}.caption-entry{padding:10px 11px;border-left:2px solid var(--accent);border-radius:var(--radius-control);background:#fff}.caption-entry--partial{border-left-color:#9ca6b7;opacity:.78}.caption-entry header{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:5px}.caption-entry strong{color:var(--accent);font-size:11px}.caption-entry time{color:var(--muted);font-size:10px;font-variant-numeric:tabular-nums}.caption-entry p{margin:0;color:var(--text);font-size:13px;line-height:1.58;overflow-wrap:anywhere;white-space:pre-wrap}.transcript-state{position:relative;padding-left:12px}.transcript-state:before{position:absolute;top:50%;left:0;width:6px;height:6px;transform:translateY(-50%);border-radius:50%;background:#a5adbb;content:""}.transcript-state--active{color:var(--success)!important}.transcript-state--active:before{background:var(--success)}.rail-empty{display:grid;gap:5px;align-content:center;min-height:112px;padding:18px;color:var(--muted);text-align:center}.rail-empty strong{color:var(--text);font-size:12px}.rail-empty span{font-size:11px;line-height:1.55}.rail-empty--case{min-height:100%}.video-actions{position:absolute;z-index:40;right:22px;bottom:24px;display:flex;gap:10px}.video-actions button{padding:10px 15px;border-radius:var(--radius-control);font-weight:600}.recording-status{display:inline-flex;align-items:center;gap:8px;padding:10px 15px;border:1px solid var(--border);border-radius:var(--radius-control);color:var(--muted);background:var(--surface);font-size:13px;font-weight:600}.recording-status--active,.recording-status--error{border-color:#edccd3;color:var(--danger);background:var(--danger-soft)}.recording-indicator{width:9px;height:9px;border-radius:50%;background:var(--danger)}.hangup-button{border:1px solid var(--danger);color:#fff;background:var(--danger)}.hangup-button:enabled:hover{border-color:#a64454;background:#a64454}.video-notice{position:absolute;z-index:40;left:22px;bottom:26px;max-width:calc(100% - 420px);padding:9px 12px;border:1px solid #cae5dc;border-radius:var(--radius-control);color:var(--success);background:var(--success-soft);font-size:13px}.video-notice--error{border-color:#edccd3;color:var(--danger);background:var(--danger-soft)}.screenshot-dialog-backdrop{position:absolute;z-index:120;inset:0;display:grid;place-items:center;padding:24px;background:#101720a3}.screenshot-dialog{display:grid;grid-template-rows:auto minmax(0,1fr) auto auto;gap:14px;width:min(920px,100%);height:min(840px,calc(100vh - 48px));max-height:calc(100vh - 48px);padding:20px;overflow:hidden;border:1px solid var(--border);border-radius:var(--radius-panel);color:var(--text);background:#fff;animation:screenshot-enter .16s var(--motion-ease)}.screenshot-dialog>header,.screenshot-dialog>footer{display:flex;align-items:center;justify-content:space-between;gap:16px}.screenshot-dialog h2{margin:2px 0 0;color:var(--heading);font-size:20px;line-height:1.35}.screenshot-dialog .eyebrow{margin:0;color:var(--accent)}.screenshot-dialog>header>button{width:36px;height:36px;border:0;border-radius:var(--radius-control);color:var(--muted);background:var(--surface-alt);font-size:24px}.screenshot-preview-frame{display:grid;place-items:center;min-height:0;overflow:hidden;border-radius:12px;background:#0b0f16}.screenshot-preview-frame img{display:block;width:100%;height:100%;min-height:0;max-width:100%;max-height:100%;object-fit:contain}.screenshot-dialog__hint{margin:0;color:var(--muted);font-size:13px}.screenshot-dialog>footer{justify-content:flex-end}.screenshot-dialog>footer button{min-width:112px;padding:10px 18px;border-radius:var(--radius-control);font-weight:700}.screenshot-cancel{border:1px solid var(--border);color:var(--text);background:#fff}.screenshot-confirm{border:1px solid var(--accent);color:#fff;background:var(--accent)}.screenshot-confirm:enabled:hover{background:var(--accent-hover)}@media (max-width: 980px){.consultation-shell--with-ai{grid-template-columns:minmax(0,1fr)}.composer-toolbar .im-ai-toggle{display:inline-flex;align-items:center;gap:3px}.im-ai-backdrop{position:fixed;z-index:800;inset:0;background:#22304733}.im-ai-panel{display:none;position:fixed;z-index:801;inset:0 0 0 auto;width:var(--im-ai-panel-width, min(360px, 100%))}.im-ai-resizer--drawer{left:-4px;background:transparent}.im-ai-panel--open{display:grid}.im-ai-close{display:block}.video-layer--with-rail{grid-template-columns:minmax(0,1fr) 310px}.video-actions{right:12px;bottom:14px;left:12px;flex-wrap:wrap;justify-content:flex-end}.recording-status{flex-basis:100%;width:fit-content;margin-left:auto;font-size:11px}.consultation-rail__header{padding-inline:12px}.diagnosis-chip{display:none}.case-panel__content,.rail-section-heading{padding-inline:12px}}@media (max-width: 700px){.chat-header{gap:10px;padding:10px 14px}.chat-heading h1{font-size:16px}.chat-heading p{font-size:11px}.primary-action{padding:9px 12px;font-size:12px}.secondary-action{padding:9px 10px;font-size:12px}.message-list{padding:14px}.message-bubble{max-width:88%}.composer{padding:8px 14px 12px}.composer-row{grid-template-columns:minmax(0,1fr) 68px;gap:10px}.video-layer,.video-stage{min-height:280px}.video-layer--with-rail{grid-template-columns:minmax(0,1fr)}.consultation-rail{display:none}.video-actions{right:10px;bottom:10px;left:auto;gap:6px}.recording-status{display:none}.video-actions button{padding:8px 11px;border-radius:10px;font-size:11px}.live-status{top:10px;padding:7px 10px;font-size:11px}.video-notice{left:10px;bottom:52px;max-width:calc(100% - 20px)}.screenshot-dialog-backdrop{padding:12px}.screenshot-dialog{height:calc(100vh - 24px);max-height:calc(100vh - 24px);padding:12px;gap:10px}.screenshot-dialog h2{font-size:16px}.screenshot-dialog>header>button{flex-shrink:0}}.load-more:enabled:hover,.screenshot-cancel:enabled:hover{border-color:var(--border-strong);background:var(--surface-soft)}.composer-toolbar button:enabled:hover{background:var(--accent-soft)}.screenshot-dialog>header>button:enabled:hover{color:var(--text);background:var(--border)}.message-file:hover{text-decoration:underline;text-underline-offset:3px}@keyframes screenshot-enter{0%{opacity:.8;transform:translateY(4px)}to{opacity:1;transform:translateY(0)}}@media (max-width: 480px){.patient-avatar{width:38px;height:38px;flex-shrink:0}.composer-toolbar>span{display:none}.screenshot-dialog__hint{font-size:11px}}@media (max-height: 480px){.im-ai-header{min-height:54px;padding:8px 14px}.im-ai-header p{display:none}.im-ai-tools{padding-bottom:8px}.im-ai-body{padding:12px 14px}.im-ai-empty{padding:0}.im-ai-empty__line{display:none}.im-ai-footer{padding:8px 14px}.im-ai-footer p{margin-top:5px;font-size:10px}.chat-panel{grid-template-rows:minmax(64px,auto) minmax(0,1fr) auto}.composer textarea{min-height:56px;height:56px;max-height:84px}}@media (prefers-reduced-motion: reduce){button,.composer textarea{transition:none}button:enabled:active{transform:none}.screenshot-dialog{animation:none}}
diff --git a/app/video_companion/dist/assets/index-B4Apl_Sl.js b/app/video_companion/dist/assets/index-C_tMrPfb.js
similarity index 58%
rename from app/video_companion/dist/assets/index-B4Apl_Sl.js
rename to app/video_companion/dist/assets/index-C_tMrPfb.js
index cea6dbe22..3404d6492 100644
--- a/app/video_companion/dist/assets/index-B4Apl_Sl.js
+++ b/app/video_companion/dist/assets/index-C_tMrPfb.js
@@ -1,4 +1,4 @@
-(function(){const i=document.createElement("link").relList;if(i&&i.supports&&i.supports("modulepreload"))return;for(const I of document.querySelectorAll('link[rel="modulepreload"]'))l(I);new MutationObserver(I=>{for(const h of I)if(h.type==="childList")for(const f of h.addedNodes)f.tagName==="LINK"&&f.rel==="modulepreload"&&l(f)}).observe(document,{childList:!0,subtree:!0});function r(I){const h={};return I.integrity&&(h.integrity=I.integrity),I.referrerPolicy&&(h.referrerPolicy=I.referrerPolicy),I.crossOrigin==="use-credentials"?h.credentials="include":I.crossOrigin==="anonymous"?h.credentials="omit":h.credentials="same-origin",h}function l(I){if(I.ep)return;I.ep=!0;const h=r(I);fetch(I.href,h)}})();var mg=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function yW(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function kU(t){if(t.__esModule)return t;var i=t.default;if(typeof i=="function"){var r=function l(){return this instanceof l?Reflect.construct(i,arguments,this.constructor):i.apply(this,arguments)};r.prototype=i.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(t).forEach(function(l){var I=Object.getOwnPropertyDescriptor(t,l);Object.defineProperty(r,l,I.get?I:{enumerable:!0,get:function(){return t[l]}})}),r}var z1={exports:{}},HoA=z1.exports,r8;function qoA(){return r8||(r8=1,function(t,i){(function(r,l){t.exports=l()})(HoA,function(){const r=s=>s===void 0,l=s=>typeof s=="string",I=s=>{var n;return(n=Object.prototype.toString.call(s).match(/^\[object (.*)\]$/))===null||n===void 0?void 0:n[1].toLowerCase()},h=s=>typeof Array.isArray=="function"?Array.isArray(s):I(s)==="array",f=s=>s!==null&&typeof s=="object",w=s=>h(s)||f(s),_=s=>{if(typeof s!="string")return!1;const n=s[0];return!/[^a-zA-Z0-9]/.test(n)},G=s=>{if(typeof s!="object"||s===null)return!1;const n=Object.getPrototypeOf(s);if(n===null)return!0;let g=n;for(;Object.getPrototypeOf(g)!==null;)g=Object.getPrototypeOf(g);return n===g};function U(s=99999999){return Math.round(Math.random()*s)}const j=(s,n,g,u)=>{if(!w(s)||!w(n))return 0;let E=0;const m=Object.keys(n);let D;for(let M=0,T=m.length;M"u"&&typeof uni.requireNativePlugin=="function",io=Et&&typeof wx.miniapp=="object",Eo=typeof uni<"u",Vs=yt&&typeof tt.enterChat=="function",ki=Et||qe||yt||Oe||gt||To||Fi,ns=typeof window>"u"&&!ki&&typeof mg<"u"&&mg.NativeScriptGlobals!==void 0,jo=typeof mg<"u"&&(mg.nativeModuleProxy!==void 0||mg.ReactNative!==void 0),Ao=typeof wx<"u"&&typeof wx.getAccountInfoSync=="function"&&!!wx.getAccountInfoSync().plugin,Zt=typeof uni<"u"?!ki:typeof window<"u"&&!ki&&!jo,oo=qe?qq:yt?tt:Oe?swan:gt?my:Et?wx:To?uni:Fi?jd:{},bi=Zt&&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":yt?s="TT_MP":Oe?s="BAIDU_MP":gt?s="ALI_MP":Et?s=io?"DONUT_NATIVE_APP":"WX_MP":To?s="UNI_NATIVE_APP":ns?s="NS_NATIVE_APP":jo&&(s="RN_NATIVE_APP"),sA[s]}(),ce=/iPad/i.test(bi),Ve=/iPhone/i.test(bi)&&!ce,Ot=/iPod/i.test(bi),nt=Ve||ce||Ot,It=function(){const s=bi.match(/OS (\d+)_/i);return s&&s[1]?s[1]:null}(),ei=/Android/i.test(bi),ti=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),Ze=/Edge/i.test(bi),wt=!Ze&&/Chrome/i.test(bi),Nt=/MSIE/.test(bi)||bi.indexOf("Trident")>-1&&bi.indexOf("rv:11.0")>-1,Oi=function(){const s=/MSIE\s(\d+)\.\d/.exec(bi);let n=s&&parseFloat(s[1]);return!n&&/Trident\/7.0/i.test(bi)&&/rv:11.0/.test(bi)&&(n=11),n}(),po=/Safari/i.test(bi)&&!wt&&!ei&&!Ze,No=/Windows/i.test(bi),so=/MAC OS X/i.test(bi),Go=Zt&&typeof Worker<"u"&&!Nt,An=ei||nt,rn=function(){if(typeof window>"u"||window.navigator===void 0)return!1;const{standalone:s}=window.navigator;return!(!nt||s||po)}();function Es(){let s="unknown";if(so&&(s="mac"),No&&(s="windows"),nt&&(s="ios"),ei&&(s="android"),ki)try{const{platform:n}=oo.getSystemInfoSync();n!==void 0&&(s=n)}catch(n){console.error(n)}return s}const an=typeof process<"u"&&process.versions!==void 0&&process.versions.node!==void 0&&typeof window>"u";function Do(s,n){var g={};for(var u in s)Object.prototype.hasOwnProperty.call(s,u)&&n.indexOf(u)<0&&(g[u]=s[u]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function"){var E=0;for(u=Object.getOwnPropertySymbols(s);E{oo.request({url:g,data:u,method:n,timeout:E,header:{"content-type":zr},success:M=>m(M.data),fail:()=>D(new Error(`{"message":"Network error","code":${Jn}}`))})}):an?void 0:new Promise((m,D)=>{const M=new XMLHttpRequest,T=setTimeout(()=>{M.abort(),D(new Error(`{"message":"Request timeout","code":${Qr}}`))},E);M.onreadystatechange=function(){if(M.readyState===4)if(clearTimeout(T),M.status===200||M.status===304)try{m(M.responseText?JSON.parse(M.responseText):null)}catch{m(M.responseText)}else D(new Error(`{"message":"Network error","code":${Jn}}`))},M.open(n,g,!0),M.setRequestHeader("Content-type",zr),M.send(u||null)})})}function Rs(s){if(s==null)return!0;if(typeof s=="boolean")return!1;if(typeof s=="number")return s===0;if(typeof s=="string"||typeof s=="function"||Array.isArray(s))return s.length===0;if(s instanceof Error)return s.message==="";if(G(s)){for(const n in s)if(Object.prototype.hasOwnProperty.call(s,n))return!1;return!0}return(Object.prototype.toString.call(s)==="[object Map]"||Object.prototype.toString.call(s)==="[object Set]"||Object.prototype.toString.call(s)==="[object File]")&&s.size===0}function or(s,n){if(s===null||typeof s!="object")return s;const g=n||new WeakMap;if(g.has(s))return g.get(s);if(s instanceof Date)return new Date(s.getTime());if(s instanceof RegExp)return new RegExp(s.source,s.flags);if(s instanceof Map){const m=new Map;return g.set(s,m),s.forEach((D,M)=>{m.set(or(M,g),or(D,g))}),m}if(s instanceof Set){const m=new Set;return g.set(s,m),s.forEach(D=>{m.add(or(D,g))}),m}if(Array.isArray(s)){const m=[];return g.set(s,m),s.forEach(D=>{m.push(or(D,g))}),m}const u=Object.getPrototypeOf(s),E=Object.create(u);return g.set(s,E),[...Object.getOwnPropertyNames(s),...Object.getOwnPropertySymbols(s)].forEach(m=>{if(m==="__ob__"||m==="__v_skip"||m==="__v_isRef"||m==="__v_isReadonly")return;const D=Object.getOwnPropertyDescriptor(s,m);D&&(D.get||D.set?Object.defineProperty(E,m,D):E[m]=or(s[m],g))}),E}function en(s,n,g){const u=new WeakSet,E=(m,D)=>{if(n&&(D=n(m,D)),D===void 0)return"undefined";if(D===null)return null;if(Number.isNaN(D))return"NaN";if(D===1/0)return"Infinity";if(D===-1/0)return"-Infinity";if(typeof D=="function")return`[Function: ${D.name||"anonymous"}]`;if(typeof D=="symbol")return D.toString();if(typeof D=="bigint")return`${D.toString()}n`;if(typeof D=="object"&&D!==null){if(u.has(D))return"[Circular]";u.add(D)}return D instanceof Date?D.toISOString():D instanceof Error?{name:D.name,message:D.message}:D instanceof Map?{dataType:"Map",value:Array.from(D.entries())}:D instanceof Set?{dataType:"Set",value:Array.from(D.values())}:D};try{return JSON.stringify(s,E,g)}catch(m){return console.error("Failed to stringify:",m),""}}function wn(){let s,n;return{promise:new Promise((g,u)=>{s=g,n=u}),resolve:s,reject:n}}var qt,yg=Object.freeze({__proto__:null,ANDROID_VERSION:ti,IE_VERSION:Oi,IN_ALIPAY_MINI_APP:gt,IN_BAIDU_MINI_APP:Oe,IN_BROWSER:Zt,IN_DONUT_NATIVE_APP:io,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:jo,IN_TT_MINI_APP:yt,IN_TT_MINI_GAME:Me,IN_UNI_APP:Eo,IN_UNI_NATIVE_APP:To,IN_WX_MINI_APP:Et,IN_WX_MINI_APP_DESK:jt,IN_WX_MINI_GAME:re,IN_WX_MINI_PLUGIN:Ao,IOS_VERSION:It,IS_ANDROID:ei,IS_CHROME:wt,IS_EDGE:Ze,IS_FIREFOX:be,IS_IE:Nt,IS_IOS:nt,IS_IPAD:ce,IS_IPHONE:Ve,IS_IPOD:Ot,IS_MAC:so,IS_SAFARI:po,IS_WECHAT:vs,IS_WIN:No,IS_WORKER_AVAILABLE:Go,MINI_APP_NAMESPACE:oo,USER_AGENT:bi,base16EncodeBinaryString:lA,deepCopyWithMethods:or,deepMerge:j,generatePromise:wn,getPlatformType:Es,getType:I,httpRequest:Pi,isArray:h,isArrayOrObject:w,isEmpty:Rs,isH5:An,isIOSWebView:rn,isNumber:s=>s!==null&&(typeof s=="number"&&!Number.isNaN(s-0)||typeof s=="object"&&s.constructor===Number),isObject:f,isPlainObject:G,isString:l,isUndefined:r,isUniIOSApp:function(){return To&&uni.getDeviceInfo().platform.toLocaleLowerCase()==="ios"},isValidRequestKey:_,platform:HA,randomInt:U,randomString:function(){const s="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let n="";for(let g=32;g>0;--g)n+=s[Math.floor(62*Math.random())];return n},safeStringify:en});class On{constructor(){this.listeners={}}on(n,g,u){this.listeners[n]||(this.listeners[n]=[]),this.listeners[n].push({fn:g,context:u})}off(n,g,u){var E;g&&(this.listeners[n]=(E=this.listeners[n])===null||E===void 0?void 0:E.filter(m=>{const D=m.fn===g,M=!u||m.context===u;return!(D&&M)}))}emit(n,...g){const u=this.listeners[n];u&&u.forEach(E=>{const{fn:m,context:D}=E;try{m.apply(D,g)}catch(M){console.warn(`Error in event handler for ${n} error: ${en(M)}`)}})}once(n,g,u){const E=(...m)=>{g.apply(u,m),this.off(n,E)};this.on(n,E)}}(function(s){s.BUSINESS_COMMAND="business_command",s.C2C_REALTIME_MESSAGE="c2c_realtime_message",s.C2C_MESSAGE_MODIFIED="c2c_message_modified",s.C2C_REVOKED_MESSAGE="c2c_message_revoked",s.GROUP_REALTIME_MESSAGE="group_realtime_message",s.GROUP_MESSAGE_MODIFIED="group_message_modified",s.GROUP_MESSAGE_REVOKED="group_message_revoked",s.C2C_MESSAGE_READ_RECEIPT="c2c_message_read_receipt",s.MESSAGE_REACTION_UPDATED="message_reaction_updated",s.MESSAGE_REACTION_UPDATED_SYNC="message_reaction_updated_sync",s.GROUP_AT_TIPS="group_at_tips",s.USER_STATUS_UPDATE="user_status_update",s.FRIEND_LIST_MODIFIED="friend_list_modified",s.PROFILE_MODIFIED="profile_modified",s.CONV_MODIFIED="conversation_modified",s.GROUP_TIPS_NOTIFICATION="group_tips_notification",s.GROUP_MESSAGE_READ_RECEIPT="group_message_read_receipt",s.GROUP_MESSAGE_READ_SYNC="group_message_read_sync",s.GROUP_SYSTEM_NOTIFICATION="group_system_notification",s.C2C_MESSAGE_PEER_READ="c2c_message_peer_read",s.C2C_MESSAGE_READ_SYNC="c2c_message_read_sync",s.C2C_REMIND_TYPE_SYNC="c2c_remind_type_sync",s.FOLLOW_LIST_UPDATED="follow_list_updated",s.MESSAGE_EXTENSIONS_UPDATED="message_extensions_updated",s.ALL_MESSAGE_READ="all_message_read",s.CONVERSATION_MARK_UPDATED="conversation_mark_updated",s.CONVERSATION_GROUP_ADD="conversation_group_add",s.CONVERSATION_GROUP_DELETED="conversation_group_deleted",s.CONVERSATION_GROUP_UPDATED="conversation_group_updated",s.ALL_RECEIVE_MESSAGE_OPTION="all_receive_message_option",s.TOPIC_AT_TIPS="topic_at_tips",s.TOPIC_TIPS_NOTIFICATION="topic_tips_notification",s.TOPIC_SYSTEM_NOTIFICATION="topic_system_notification",s.TOPIC_MESSAGE_READ_SYNC="topic_message_read_sync",s.TOPIC_LATEST_MESSAGE="topic_latest_message",s.GROUP_MESSAGE_PINNED="group_message_pinned"})(qt||(qt={}));const Gn=[16,17];function Js(s){var n;const g=[];return(n=s?.GroupTips)===null||n===void 0||n.forEach(u=>{var E;u.GroupInfo.MillionGroupFlag===2?g.push(qt.TOPIC_TIPS_NOTIFICATION):Gn.includes((E=u?.MsgBody)===null||E===void 0?void 0:E.OpType)?g.push(qt.GROUP_MESSAGE_PINNED):g.push(qt.GROUP_TIPS_NOTIFICATION)}),g}const pr=[{conditions:[{type:"event",value:100}],subType:qt.BUSINESS_COMMAND},{conditions:[{type:"event",value:24}],subType:qt.ALL_RECEIVE_MESSAGE_OPTION},{conditions:[{type:"event",value:26}],subType:qt.TOPIC_LATEST_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgArray"}],subType:qt.C2C_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgModNotifys"}],subType:qt.C2C_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"ProfileDataMod"}],subType:qt.PROFILE_MODIFIED},{conditions:[{type:"hasKey",value:"UserStatusList"}],subType:qt.USER_STATUS_UPDATE},{conditions:[{type:"hasKey",value:"FriendListMod"}],subType:qt.FRIEND_LIST_MODIFIED},{conditions:[{type:"hasKey",value:"GroupMsgArray"}],subType:qt.GROUP_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"GroupMsgModNotifys"}],subType:qt.GROUP_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"C2cNotifyMsgArray"}],subTypeParser:function(s){var n;const g=[];return(n=s?.C2cNotifyMsgArray)===null||n===void 0||n.forEach(u=>{u.WithdrawC2cMsgNotify&&g.push(qt.C2C_REVOKED_MESSAGE),u.C2cReadedReceipt&&g.push(qt.C2C_MESSAGE_PEER_READ),u.ReadC2cMsgNotify&&g.push(qt.C2C_MESSAGE_READ_SYNC),u.MuteNotificationsSync&&g.push(qt.C2C_REMIND_TYPE_SYNC)}),g}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:4}],subTypeParser:Js},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:5}],subTypeParser:function(s){var n;const g=[];return(n=s?.GroupTips)===null||n===void 0||n.forEach(u=>{Array.isArray(u.MsgBody.GroupWithdrawInfoArray)?g.push(qt.GROUP_MESSAGE_REVOKED):Array.isArray(u.MsgBody.GroupMsgReceiptList)?g.push(qt.GROUP_MESSAGE_READ_RECEIPT):Array.isArray(u.MsgBody.GroupReadInfoArray)?u.MsgBody.GroupReadInfoArray[0].TopicId?g.push(qt.TOPIC_MESSAGE_READ_SYNC):g.push(qt.GROUP_MESSAGE_READ_SYNC):u.GroupInfo.MillionGroupFlag===2?g.push(qt.TOPIC_SYSTEM_NOTIFICATION):g.push(qt.GROUP_SYSTEM_NOTIFICATION)}),g}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:6}],subTypeParser:Js},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:12}],subTypeParser:function(s){var n;const g=[];return(n=s?.GroupTips)===null||n===void 0||n.forEach(u=>{const{GroupAtTips:{TopicId:E}}=u;E?g.push(qt.TOPIC_AT_TIPS):g.push(qt.GROUP_AT_TIPS)}),g}},{conditions:[{type:"hasKey",value:"RecentContactMod"}],subTypeParser:function(s){var n;const g=[];return(n=s?.RecentContactMod)===null||n===void 0||n.forEach(u=>{switch(u.PushType){case je.CONV_MARK_UPDATED:g.push(qt.CONVERSATION_MARK_UPDATED);break;case je.CONV_GROUP_ADDED:g.push(qt.CONVERSATION_GROUP_ADD);break;case je.CONV_GROUP_DELETED:g.push(qt.CONVERSATION_GROUP_DELETED);break;case je.CONV_GROUP_UPDATED:g.push(qt.CONVERSATION_GROUP_UPDATED);break;default:g.push(qt.CONV_MODIFIED)}}),g}},{conditions:[{type:"hasKey",value:"MsgReactionNotifyList"}],subType:qt.MESSAGE_REACTION_UPDATED},{conditions:[{type:"hasKey",value:"MsgReactionNotify"}],subType:qt.MESSAGE_REACTION_UPDATED_SYNC},{conditions:[{type:"hasKey",value:"C2cMsgInfo"}],subType:qt.C2C_MESSAGE_READ_RECEIPT},{conditions:[{type:"hasKey",value:"FollowChangeList"}],subType:qt.FOLLOW_LIST_UPDATED},{conditions:[{type:"hasKey",value:"MsgExtensionNotify"}],subType:qt.MESSAGE_EXTENSIONS_UPDATED},{conditions:[{type:"hasKey",value:"C2CReadAllMsg"}],subType:qt.ALL_MESSAGE_READ}];var Pn;function mr(s){var n;const g=Array.isArray((n=s?.body)===null||n===void 0?void 0:n.EventArray)?s.body.EventArray:[],u=[];return g.forEach(E=>{E.Flag=s.body.Flag;const m=pr.find(M=>M.conditions.every(T=>{switch(T.type){case"event":return E.Event===T.value;case"hasKey":return Object.prototype.hasOwnProperty.call(E,T.value);default:return!1}}));if(!m)return null;let D=[];typeof m.subTypeParser=="function"?D=m.subTypeParser(E):m.subType&&(D=m.subType),Array.isArray(D)?D.forEach(M=>{u.push({type:`${Pn.SERVER_PUSH_MESSAGE}:${M}`,data:E})}):u.push({type:`${Pn.SERVER_PUSH_MESSAGE}:${D}`,data:E})}),u}(function(s){s.SERVER_PUSH_MESSAGE="im_open_push.msg_push",s.SERVER_PUSH_MESSAGE_MULTIPLE="im_open_push.multi_msg_push_ws",s.ERROR="error"})(Pn||(Pn={}));const mo={[Pn.SERVER_PUSH_MESSAGE]:mr,[Pn.SERVER_PUSH_MESSAGE_MULTIPLE]:mr,[Pn.ERROR]:function(s){const{errorCode:n}=s;return[{type:`error:${n}`,data:s}]}},gn=new class{constructor(){this._outerEventEmitter=null,this._innerEventEmitter=null,this._filteredCallbackMap=new Map,this._outerEventEmitter=new On,this._innerEventEmitter=new On,this.InnerEventSubType=qt}subscribeInnerEvent(s,n,g,u,E){var m;let D,M,T,P;["string","number"].includes(typeof n)?(T=`${s}:${n}`,P=g,M=u,D=E):(T=s,P=n,M=g,D=typeof u=="function"?u:void 0),D?this._subscribeWithFilter(T,P,M,D):(m=this._innerEventEmitter)===null||m===void 0||m.on(T,P,M)}emitInnerEvent(s,n){var g,u;if((g=this._innerEventEmitter)===null||g===void 0||g.emit(s,n),Object.keys(mo).includes(s)){const E=(u=mo[s])===null||u===void 0?void 0:u.call(mo,n);E?.forEach(m=>{var D;m&&((D=this._innerEventEmitter)===null||D===void 0||D.emit(m.type,m.data))})}}subscribeOuterEvent(s,n,g){var u;(u=this._outerEventEmitter)===null||u===void 0||u.on(s,n,g)}unSubscribeOuterEvent(s,n,g){var u;(u=this._outerEventEmitter)===null||u===void 0||u.off(s,n,g)}unSubscribeInnerEvent(s,n,g,u){if(["string","number"].includes(typeof n)){const E=g,m=`${s}:${n}`;this._unsubscribeEvent(m,E,u)}else{const E=n;this._unsubscribeEvent(s,E,g)}}emitOuterEvent(s,n){var g;(g=this._outerEventEmitter)===null||g===void 0||g.emit(s,n)}getOuterEventEmitter(){return this._outerEventEmitter}rest(){this._outerEventEmitter=null,this._innerEventEmitter=null}_subscribeWithFilter(s,n,g,u){var E;const m=D=>{u.call(g,D)&&n.call(g,D)};this._filteredCallbackMap.has(s)||this._filteredCallbackMap.set(s,[]),this._filteredCallbackMap.get(s).push({originalCallback:n,filteredCallback:m,filter:u,context:g}),(E=this._innerEventEmitter)===null||E===void 0||E.on(s,m,g)}_unsubscribeEvent(s,n,g){var u,E;const m=this._filteredCallbackMap.get(s);if(m){const D=m.findIndex(M=>M.originalCallback===n&&M.context===g);if(D!==-1){const{filteredCallback:M}=m[D];return(u=this._innerEventEmitter)===null||u===void 0||u.off(s,M,g),m.splice(D,1),void(m.length===0&&this._filteredCallbackMap.delete(s))}}(E=this._innerEventEmitter)===null||E===void 0||E.off(s,n,g)}};class Sl{constructor(){this._socket=null}connectSocket(n){return this._socket=new WebSocket(n),this._socket}send(n){var g,u;try{(g=this._socket)===null||g===void 0||g.send(n)}catch(E){(u=this._onSendFail)===null||u===void 0||u.call(this,E)}}bindSocketHandlers(n){const{onOpen:g,onMessage:u,onClose:E,onError:m,onSendFail:D}=n;this._socket&&(this._socket.binaryType="arraybuffer",this._socket.onopen=g,this._socket.onmessage=u,this._socket.onclose=E,this._socket.onerror=m,this._onSendFail=D)}unbindSocketHandlers(){this._socket&&(this._socket.onopen=null,this._socket.onmessage=null,this._socket.onclose=null,this._socket.onerror=null)}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}class cn{constructor(n){this._onError=n.onError}connectSocket(n){const g=this;return this._socket=oo.connectSocket({url:n,header:{"content-type":"application/json"},complete:()=>{},fail:u=>g._onError(u)}),this._socket}send(n){var g;(g=this._socket)===null||g===void 0||g.send({data:n,fail:this._onSendFail})}bindSocketHandlers(n){const{onOpen:g,onMessage:u,onClose:E,onError:m,onSendFail:D}=n;this._socket&&(this._socket.onClose(E),this._socket.onOpen(g),this._socket.onMessage(u),this._socket.onError(m),this._onSendFail=D)}unbindSocketHandlers(){this._socket&&(this._socket.onClose(()=>{}),this._socket.onOpen(()=>{}),this._socket.onMessage(()=>{}),this._socket.onError(()=>{}))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}const fr="CONNECT",Ls="SEND",Jc="DISCONNECT",ms="OPEN",as="MESSAGE",Ru="CLOSE",Wa="ERROR",Cs="SEND_FAIL";class sg{constructor(){this._worker=null,this._blobUrl=null}connectSocket(n){const g=new Blob([`
+(function(){const i=document.createElement("link").relList;if(i&&i.supports&&i.supports("modulepreload"))return;for(const I of document.querySelectorAll('link[rel="modulepreload"]'))c(I);new MutationObserver(I=>{for(const C of I)if(C.type==="childList")for(const f of C.addedNodes)f.tagName==="LINK"&&f.rel==="modulepreload"&&c(f)}).observe(document,{childList:!0,subtree:!0});function n(I){const C={};return I.integrity&&(C.integrity=I.integrity),I.referrerPolicy&&(C.referrerPolicy=I.referrerPolicy),I.crossOrigin==="use-credentials"?C.credentials="include":I.crossOrigin==="anonymous"?C.credentials="omit":C.credentials="same-origin",C}function c(I){if(I.ep)return;I.ep=!0;const C=n(I);fetch(I.href,C)}})();var mg=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function HW(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function HU(t){if(t.__esModule)return t;var i=t.default;if(typeof i=="function"){var n=function c(){return this instanceof c?Reflect.construct(i,arguments,this.constructor):i.apply(this,arguments)};n.prototype=i.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(t).forEach(function(c){var I=Object.getOwnPropertyDescriptor(t,c);Object.defineProperty(n,c,I.get?I:{enumerable:!0,get:function(){return t[c]}})}),n}var aY={exports:{}},psA=aY.exports,_8;function msA(){return _8||(_8=1,function(t,i){(function(n,c){t.exports=c()})(psA,function(){const n=s=>s===void 0,c=s=>typeof s=="string",I=s=>{var r;return(r=Object.prototype.toString.call(s).match(/^\[object (.*)\]$/))===null||r===void 0?void 0:r[1].toLowerCase()},C=s=>typeof Array.isArray=="function"?Array.isArray(s):I(s)==="array",f=s=>s!==null&&typeof s=="object",w=s=>C(s)||f(s),_=s=>{if(typeof s!="string")return!1;const r=s[0];return!/[^a-zA-Z0-9]/.test(r)},N=s=>{if(typeof s!="object"||s===null)return!1;const r=Object.getPrototypeOf(s);if(r===null)return!0;let g=r;for(;Object.getPrototypeOf(g)!==null;)g=Object.getPrototypeOf(g);return r===g};function L(s=99999999){return Math.round(Math.random()*s)}const q=(s,r,g,u)=>{if(!w(s)||!w(r))return 0;let E=0;const m=Object.keys(r);let D;for(let M=0,T=m.length;M"u"&&typeof uni.requireNativePlugin=="function",to=ct&&typeof wx.miniapp=="object",so=typeof uni<"u",ks=Dt&&typeof tt.enterChat=="function",Gi=ct||Ve||Dt||Pt||oi||Co||Ni,As=typeof window>"u"&&!Gi&&typeof mg<"u"&&mg.NativeScriptGlobals!==void 0,Lo=typeof mg<"u"&&(mg.nativeModuleProxy!==void 0||mg.ReactNative!==void 0),$i=typeof wx<"u"&&typeof wx.getAccountInfoSync=="function"&&!!wx.getAccountInfoSync().plugin,zt=typeof uni<"u"?!Gi:typeof window<"u"&&!Gi&&!Lo,Ao=Ve?qq:Dt?tt:Pt?swan:oi?my:ct?wx:Co?uni:Ni?jd:{},Ri=zt&&window&&window.navigator&&window.navigator.userAgent||"",Es=/(micromessenger|webbrowser)/i.test(Ri),VA=function(){let s="WEB";return Es?s="WEB":Ve?s="QQ_MP":Dt?s="TT_MP":Pt?s="BAIDU_MP":oi?s="ALI_MP":ct?s=to?"DONUT_NATIVE_APP":"WX_MP":Co?s="UNI_NATIVE_APP":As?s="NS_NATIVE_APP":Lo&&(s="RN_NATIVE_APP"),tA[s]}(),Ee=/iPad/i.test(Ri),Je=/iPhone/i.test(Ri)&&!Ee,Ut=/iPod/i.test(Ri),ot=Je||Ee||Ut,ut=function(){const s=Ri.match(/OS (\d+)_/i);return s&&s[1]?s[1]:null}(),$t=/Android/i.test(Ri),Zt=function(){const s=Ri.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(!s)return null;const r=s[1]&&parseFloat(s[1]),g=s[2]&&parseFloat(s[2]);return r&&g?parseFloat(`${s[1]}.${s[2]}`):r||null}(),Ge=/Firefox/i.test(Ri),Xe=/Edge/i.test(Ri),se=!Xe&&/Chrome/i.test(Ri),ve=/MSIE/.test(Ri)||Ri.indexOf("Trident")>-1&&Ri.indexOf("rv:11.0")>-1,pt=function(){const s=/MSIE\s(\d+)\.\d/.exec(Ri);let r=s&&parseFloat(s[1]);return!r&&/Trident\/7.0/i.test(Ri)&&/rv:11.0/.test(Ri)&&(r=11),r}(),mo=/Safari/i.test(Ri)&&!se&&!$t&&!Xe,No=/Windows/i.test(Ri),no=/MAC OS X/i.test(Ri),Go=zt&&typeof Worker<"u"&&!ve,An=$t||ot,rn=function(){if(typeof window>"u"||window.navigator===void 0)return!1;const{standalone:s}=window.navigator;return!(!ot||s||mo)}();function ds(){let s="unknown";if(no&&(s="mac"),No&&(s="windows"),ot&&(s="ios"),$t&&(s="android"),Gi)try{const{platform:r}=Ao.getSystemInfoSync();r!==void 0&&(s=r)}catch(r){console.error(r)}return s}const an=typeof process<"u"&&process.versions!==void 0&&process.versions.node!==void 0&&typeof window>"u";function So(s,r){var g={};for(var u in s)Object.prototype.hasOwnProperty.call(s,u)&&r.indexOf(u)<0&&(g[u]=s[u]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function"){var E=0;for(u=Object.getOwnPropertySymbols(s);E{Ao.request({url:g,data:u,method:r,timeout:E,header:{"content-type":Zr},success:M=>m(M.data),fail:()=>D(new Error(`{"message":"Network error","code":${qn}}`))})}):an?void 0:new Promise((m,D)=>{const M=new XMLHttpRequest,T=setTimeout(()=>{M.abort(),D(new Error(`{"message":"Request timeout","code":${mr}}`))},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":${qn}}`))},M.open(r,g,!0),M.setRequestHeader("Content-type",Zr),M.send(u||null)})})}function Rs(s){if(s==null)return!0;if(typeof s=="boolean")return!1;if(typeof s=="number")return s===0;if(typeof s=="string"||typeof s=="function"||Array.isArray(s))return s.length===0;if(s instanceof Error)return s.message==="";if(N(s)){for(const r in s)if(Object.prototype.hasOwnProperty.call(s,r))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 rr(s,r){if(s===null||typeof s!="object")return s;const g=r||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(rr(M,g),rr(D,g))}),m}if(s instanceof Set){const m=new Set;return g.set(s,m),s.forEach(D=>{m.add(rr(D,g))}),m}if(Array.isArray(s)){const m=[];return g.set(s,m),s.forEach(D=>{m.push(rr(D,g))}),m}const u=Object.getPrototypeOf(s),E=Object.create(u);return g.set(s,E),[...Object.getOwnPropertyNames(s),...Object.getOwnPropertySymbols(s)].forEach(m=>{if(m==="__ob__"||m==="__v_skip"||m==="__v_isRef"||m==="__v_isReadonly")return;const D=Object.getOwnPropertyDescriptor(s,m);D&&(D.get||D.set?Object.defineProperty(E,m,D):E[m]=rr(s[m],g))}),E}function en(s,r,g){const u=new WeakSet,E=(m,D)=>{if(r&&(D=r(m,D)),D===void 0)return"undefined";if(D===null)return null;if(Number.isNaN(D))return"NaN";if(D===1/0)return"Infinity";if(D===-1/0)return"-Infinity";if(typeof D=="function")return`[Function: ${D.name||"anonymous"}]`;if(typeof D=="symbol")return D.toString();if(typeof D=="bigint")return`${D.toString()}n`;if(typeof D=="object"&&D!==null){if(u.has(D))return"[Circular]";u.add(D)}return D instanceof Date?D.toISOString():D instanceof Error?{name:D.name,message:D.message}:D instanceof Map?{dataType:"Map",value:Array.from(D.entries())}:D instanceof Set?{dataType:"Set",value:Array.from(D.values())}:D};try{return JSON.stringify(s,E,g)}catch(m){return console.error("Failed to stringify:",m),""}}function wn(){let s,r;return{promise:new Promise((g,u)=>{s=g,r=u}),resolve:s,reject:r}}var jt,yg=Object.freeze({__proto__:null,ANDROID_VERSION:Zt,IE_VERSION:pt,IN_ALIPAY_MINI_APP:oi,IN_BAIDU_MINI_APP:Pt,IN_BROWSER:zt,IN_DONUT_NATIVE_APP:to,IN_FEISHU_MINI_APP:ks,IN_JD_MINI_APP:Ni,IN_MINI_APP:Gi,IN_NODE:an,IN_NS_NATIVE_APP:As,IN_QQ_MINI_APP:Ve,IN_RN_APP:Lo,IN_TT_MINI_APP:Dt,IN_TT_MINI_GAME:ti,IN_UNI_APP:so,IN_UNI_NATIVE_APP:Co,IN_WX_MINI_APP:ct,IN_WX_MINI_APP_DESK:wt,IN_WX_MINI_GAME:ce,IN_WX_MINI_PLUGIN:$i,IOS_VERSION:ut,IS_ANDROID:$t,IS_CHROME:se,IS_EDGE:Xe,IS_FIREFOX:Ge,IS_IE:ve,IS_IOS:ot,IS_IPAD:Ee,IS_IPHONE:Je,IS_IPOD:Ut,IS_MAC:no,IS_SAFARI:mo,IS_WECHAT:Es,IS_WIN:No,IS_WORKER_AVAILABLE:Go,MINI_APP_NAMESPACE:Ao,USER_AGENT:Ri,base16EncodeBinaryString:lA,deepCopyWithMethods:rr,deepMerge:q,generatePromise:wn,getPlatformType:ds,getType:I,httpRequest:Yi,isArray:C,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:N,isString:c,isUndefined:n,isUniIOSApp:function(){return Co&&uni.getDeviceInfo().platform.toLocaleLowerCase()==="ios"},isValidRequestKey:_,platform:VA,randomInt:L,randomString:function(){const s="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let r="";for(let g=32;g>0;--g)r+=s[Math.floor(62*Math.random())];return r},safeStringify:en});class Pn{constructor(){this.listeners={}}on(r,g,u){this.listeners[r]||(this.listeners[r]=[]),this.listeners[r].push({fn:g,context:u})}off(r,g,u){var E;g&&(this.listeners[r]=(E=this.listeners[r])===null||E===void 0?void 0:E.filter(m=>{const D=m.fn===g,M=!u||m.context===u;return!(D&&M)}))}emit(r,...g){const u=this.listeners[r];u&&u.forEach(E=>{const{fn:m,context:D}=E;try{m.apply(D,g)}catch(M){console.warn(`Error in event handler for ${r} error: ${en(M)}`)}})}once(r,g,u){const E=(...m)=>{g.apply(u,m),this.off(r,E)};this.on(r,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 bn=[16,17];function Js(s){var r;const g=[];return(r=s?.GroupTips)===null||r===void 0||r.forEach(u=>{var E;u.GroupInfo.MillionGroupFlag===2?g.push(jt.TOPIC_TIPS_NOTIFICATION):bn.includes((E=u?.MsgBody)===null||E===void 0?void 0:E.OpType)?g.push(jt.GROUP_MESSAGE_PINNED):g.push(jt.GROUP_TIPS_NOTIFICATION)}),g}const fr=[{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 r;const g=[];return(r=s?.C2cNotifyMsgArray)===null||r===void 0||r.forEach(u=>{u.WithdrawC2cMsgNotify&&g.push(jt.C2C_REVOKED_MESSAGE),u.C2cReadedReceipt&&g.push(jt.C2C_MESSAGE_PEER_READ),u.ReadC2cMsgNotify&&g.push(jt.C2C_MESSAGE_READ_SYNC),u.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 r;const g=[];return(r=s?.GroupTips)===null||r===void 0||r.forEach(u=>{Array.isArray(u.MsgBody.GroupWithdrawInfoArray)?g.push(jt.GROUP_MESSAGE_REVOKED):Array.isArray(u.MsgBody.GroupMsgReceiptList)?g.push(jt.GROUP_MESSAGE_READ_RECEIPT):Array.isArray(u.MsgBody.GroupReadInfoArray)?u.MsgBody.GroupReadInfoArray[0].TopicId?g.push(jt.TOPIC_MESSAGE_READ_SYNC):g.push(jt.GROUP_MESSAGE_READ_SYNC):u.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 r;const g=[];return(r=s?.GroupTips)===null||r===void 0||r.forEach(u=>{const{GroupAtTips:{TopicId:E}}=u;E?g.push(jt.TOPIC_AT_TIPS):g.push(jt.GROUP_AT_TIPS)}),g}},{conditions:[{type:"hasKey",value:"RecentContactMod"}],subTypeParser:function(s){var r;const g=[];return(r=s?.RecentContactMod)===null||r===void 0||r.forEach(u=>{switch(u.PushType){case We.CONV_MARK_UPDATED:g.push(jt.CONVERSATION_MARK_UPDATED);break;case We.CONV_GROUP_ADDED:g.push(jt.CONVERSATION_GROUP_ADD);break;case We.CONV_GROUP_DELETED:g.push(jt.CONVERSATION_GROUP_DELETED);break;case We.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 xn;function yr(s){var r;const g=Array.isArray((r=s?.body)===null||r===void 0?void 0:r.EventArray)?s.body.EventArray:[],u=[];return g.forEach(E=>{E.Flag=s.body.Flag;const m=fr.find(M=>M.conditions.every(T=>{switch(T.type){case"event":return E.Event===T.value;case"hasKey":return Object.prototype.hasOwnProperty.call(E,T.value);default:return!1}}));if(!m)return null;let D=[];typeof m.subTypeParser=="function"?D=m.subTypeParser(E):m.subType&&(D=m.subType),Array.isArray(D)?D.forEach(M=>{u.push({type:`${xn.SERVER_PUSH_MESSAGE}:${M}`,data:E})}):u.push({type:`${xn.SERVER_PUSH_MESSAGE}:${D}`,data:E})}),u}(function(s){s.SERVER_PUSH_MESSAGE="im_open_push.msg_push",s.SERVER_PUSH_MESSAGE_MULTIPLE="im_open_push.multi_msg_push_ws",s.ERROR="error"})(xn||(xn={}));const fo={[xn.SERVER_PUSH_MESSAGE]:yr,[xn.SERVER_PUSH_MESSAGE_MULTIPLE]:yr,[xn.ERROR]:function(s){const{errorCode:r}=s;return[{type:`error:${r}`,data:s}]}},gn=new class{constructor(){this._outerEventEmitter=null,this._innerEventEmitter=null,this._filteredCallbackMap=new Map,this._outerEventEmitter=new Pn,this._innerEventEmitter=new Pn,this.InnerEventSubType=jt}subscribeInnerEvent(s,r,g,u,E){var m;let D,M,T,P;["string","number"].includes(typeof r)?(T=`${s}:${r}`,P=g,M=u,D=E):(T=s,P=r,M=g,D=typeof u=="function"?u:void 0),D?this._subscribeWithFilter(T,P,M,D):(m=this._innerEventEmitter)===null||m===void 0||m.on(T,P,M)}emitInnerEvent(s,r){var g,u;if((g=this._innerEventEmitter)===null||g===void 0||g.emit(s,r),Object.keys(fo).includes(s)){const E=(u=fo[s])===null||u===void 0?void 0:u.call(fo,r);E?.forEach(m=>{var D;m&&((D=this._innerEventEmitter)===null||D===void 0||D.emit(m.type,m.data))})}}subscribeOuterEvent(s,r,g){var u;(u=this._outerEventEmitter)===null||u===void 0||u.on(s,r,g)}unSubscribeOuterEvent(s,r,g){var u;(u=this._outerEventEmitter)===null||u===void 0||u.off(s,r,g)}unSubscribeInnerEvent(s,r,g,u){if(["string","number"].includes(typeof r)){const E=g,m=`${s}:${r}`;this._unsubscribeEvent(m,E,u)}else{const E=r;this._unsubscribeEvent(s,E,g)}}emitOuterEvent(s,r){var g;(g=this._outerEventEmitter)===null||g===void 0||g.emit(s,r)}getOuterEventEmitter(){return this._outerEventEmitter}rest(){this._outerEventEmitter=null,this._innerEventEmitter=null}_subscribeWithFilter(s,r,g,u){var E;const m=D=>{u.call(g,D)&&r.call(g,D)};this._filteredCallbackMap.has(s)||this._filteredCallbackMap.set(s,[]),this._filteredCallbackMap.get(s).push({originalCallback:r,filteredCallback:m,filter:u,context:g}),(E=this._innerEventEmitter)===null||E===void 0||E.on(s,m,g)}_unsubscribeEvent(s,r,g){var u,E;const m=this._filteredCallbackMap.get(s);if(m){const D=m.findIndex(M=>M.originalCallback===r&&M.context===g);if(D!==-1){const{filteredCallback:M}=m[D];return(u=this._innerEventEmitter)===null||u===void 0||u.off(s,M,g),m.splice(D,1),void(m.length===0&&this._filteredCallbackMap.delete(s))}}(E=this._innerEventEmitter)===null||E===void 0||E.off(s,r,g)}};class Ml{constructor(){this._socket=null}connectSocket(r){return this._socket=new WebSocket(r),this._socket}send(r){var g,u;try{(g=this._socket)===null||g===void 0||g.send(r)}catch(E){(u=this._onSendFail)===null||u===void 0||u.call(this,E)}}bindSocketHandlers(r){const{onOpen:g,onMessage:u,onClose:E,onError:m,onSendFail:D}=r;this._socket&&(this._socket.binaryType="arraybuffer",this._socket.onopen=g,this._socket.onmessage=u,this._socket.onclose=E,this._socket.onerror=m,this._onSendFail=D)}unbindSocketHandlers(){this._socket&&(this._socket.onopen=null,this._socket.onmessage=null,this._socket.onclose=null,this._socket.onerror=null)}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}class cn{constructor(r){this._onError=r.onError}connectSocket(r){const g=this;return this._socket=Ao.connectSocket({url:r,header:{"content-type":"application/json"},complete:()=>{},fail:u=>g._onError(u)}),this._socket}send(r){var g;(g=this._socket)===null||g===void 0||g.send({data:r,fail:this._onSendFail})}bindSocketHandlers(r){const{onOpen:g,onMessage:u,onClose:E,onError:m,onSendFail:D}=r;this._socket&&(this._socket.onClose(E),this._socket.onOpen(g),this._socket.onMessage(u),this._socket.onError(m),this._onSendFail=D)}unbindSocketHandlers(){this._socket&&(this._socket.onClose(()=>{}),this._socket.onOpen(()=>{}),this._socket.onMessage(()=>{}),this._socket.onError(()=>{}))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}const Dr="CONNECT",Us="SEND",Jc="DISCONNECT",fs="OPEN",as="MESSAGE",wu="CLOSE",Wa="ERROR",hs="SEND_FAIL";class sg{constructor(){this._worker=null,this._blobUrl=null}connectSocket(r){const g=new Blob([`
let _socket = null;
self.onmessage = (event) => {
@@ -95,26 +95,26 @@
_socket = null;
}
}
-`],{type:"application/javascript"});this._worker=new Worker(URL.createObjectURL(g)),this._worker.postMessage({type:fr,url:n})}send(n){var g,u;try{(g=this._worker)===null||g===void 0||g.postMessage({type:Ls,data:n})}catch(E){(u=this._onSendFail)===null||u===void 0||u.call(this,E)}}bindSocketHandlers(n){const{onOpen:g,onMessage:u,onClose:E,onError:m,onSendFail:D}=n;if(this._worker){const M={[ms]:g,[as]:u,[Ru]:E,[Wa]:m,[Cs]:D};this._onSendFail=D,this._worker.onmessage=T=>{var P;const{type:W}=T?.data||{};typeof M[W]=="function"&&((P=M[W])===null||P===void 0||P.call(M,T?.data))}}}unbindSocketHandlers(){this._worker&&(this._worker.onmessage=null)}disconnect(){this._worker&&(this._worker.postMessage({type:Jc}),this._worker.terminate(),this._worker=null),this._blobUrl&&(URL.revokeObjectURL(this._blobUrl),this._blobUrl=null)}}class HI{}var As,$i=new class{constructor(){this._store=new Map}get(s){return this._store.get(s)}getStorage(s){return ki?gt?my.getStorageSync({key:s}).data:oo.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?gt?my.setStorageSync({key:s,data:JSON.stringify(n)}):oo.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=oo.connectSocket({url:n,header:{"content-type":"application/json"},multiple:!0,complete:()=>{}}),this._socket}send(n){var g;(g=this._socket)===null||g===void 0||g.send({data:n,fail:this._onSendFail})}bindSocketHandlers(n){const{onOpen:g,onMessage:u,onClose:E,onError:m,onSendFail:D}=n;this._socket&&(this._socket.onClose(E),this._socket.onOpen(g),this._socket.onMessage(M=>u(M?.data)),this._socket.onError(()=>m),this._onSendFail=D)}unbindSocketHandlers(){this._socket&&(this._socket.onClose(()=>{}),this._socket.onOpen(()=>{}),this._socket.onMessage(()=>{}),this._socket.onError(()=>{}))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}(function(s){s[s.CONNECTED=0]="CONNECTED",s[s.CONNECTING=1]="CONNECTING",s[s.DISCONNECTED=2]="DISCONNECTED"})(As||(As={}));class ng{constructor(n){this._url="",this._readyState=As.DISCONNECTED,this._url=n,this._id=U(),this._emitter=new On,gt?this._socket=new pc:Et||To||yt||qe||Fi||Oe?this._socket=new cn({onError:this._onError.bind(this)}):an?this._socket=new HI:this._canUseWebWorker()?this._socket=new sg:this._socket=new Sl,this.connect()}connect(){this.doOpen(),this._bindSocketHandlers()}doOpen(){[As.CONNECTED,As.CONNECTING].includes(this._readyState)||(this._readyState=As.CONNECTING,this._ws=this._socket.connectSocket(this._url))}send(n){this._readyState!==As.CONNECTED?this.reconnect():this._socket.send(n)}reconnect(){[As.CONNECTED,As.CONNECTING].includes(this._readyState)||(this.disconnect(),this.doOpen())}getId(){return this._id}on(n,g,u){this._emitter.on(n,g,u)}off(n,g,u){this._emitter.off(n,g,u)}isConnected(){return this._readyState===As.CONNECTED}disconnect(){this._readyState=As.DISCONNECTED,this._unbindSocketHandlers(),this._socket.disconnect()}_onOpen(n){this._readyState===As.CONNECTING&&(this._readyState=As.CONNECTED,this._emitter.emit("connect",{socketId:this._id,event:n}))}_onMessage(n){this._emitter.emit("message",n)}_onClose(n){this._readyState=As.DISCONNECTED,this._emitter.emit("close",{socketId:this._id,event:n})}_onError(n){this._readyState=As.DISCONNECTED,this._emitter.emit("error",{socketId:this._id,error:n})}_onSendFail(n){this._readyState=As.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=$i.get("cloudConfig")||{};return(r(n.isWorkerEnabled)||n.isWorkerEnabled==="1")&&Go}}const Dg={[ut.SINGAPORE]:[[2e7,3e7],[172e7,173e7]],[ut.KOREA]:[[3e7,4e7],[173e7,174e7]],[ut.GERMANY]:[[4e7,5e7],[174e7,175e7]],[ut.IND]:[[5e7,6e7],[175e7,176e7]],[ut.JPN]:[[6e7,7e7],[176e7,177e7]],[ut.USA]:[[7e7,8e7],[177e7,178e7]],[ut.INDONESIA]:[[8e7,9e7],[178e7,179e7]],[ut.KSA]:[[9e7,1e8],[179e7,18e8]]};function ua(s){var n;if(!((n=$i.get("instance"))===null||n===void 0)&&n.oversea)return ut.OVERSEA;for(const g of Object.keys(Dg))for(const[u,E]of Dg[g])if(s>=u&&s`${iA}=${W[iA]}`).join("&"));var W;return g?`${s}/binfo?${P}&compress=gzip`:`${s}/info?${P}`}function Hs(s){const n=$i.get("instance"),{sdkAppId:g,testEnv:u,proxyServer:E}=n,m=ua(g);if(u)return Hn(ft.TEST[m].DEFAULT,{isBinary:s});if(!Rs(E))return Hn(E,{isBinary:s});const D=ft.PRODUCTION[m],M=Zt&&D.ANYCAST,T=Zt,P=!!D.BACKUP_CN;return Hn({[bo.INITIAL]:()=>(_o=bo.DEFAULT,D.DEFAULT),[bo.DEFAULT]:()=>(_o=bo.IPV6,D.IPV6),[bo.IPV6]:()=>(_o=bo.BACKUP,D.BACKUP),[bo.BACKUP]:()=>T?(_o=bo.BACKUP_WEB_ONLY,function(W){const iA=Math.floor(10001*Math.random())+1e4;return W.replace("*",String(iA))}(D.BACKUP_WEB_ONLY)):P?(_o=bo.BACKUP_CN,D.BACKUP_CN):M?(_o=bo.ANYCAST,D.ANYCAST):D.DEFAULT,[bo.BACKUP_WEB_ONLY]:()=>P?(_o=bo.BACKUP_CN,D.BACKUP_CN):M?(_o=bo.ANYCAST,D.ANYCAST):D.DEFAULT,[bo.BACKUP_CN]:()=>(_o=M?bo.ANYCAST:bo.DEFAULT,D[_o]),[bo.ANYCAST]:()=>(_o=bo.DEFAULT,D.ANYCAST="",D.DEFAULT)}[_o](),{isBinary:s})}var Sg=new class{constructor(){this._timeOffsetWithServer=0}getServerTimeMs(){return Date.now()+this._timeOffsetWithServer}getServerTimeSeconds(){return Math.floor(this.getServerTimeMs()/1e3)}getTimeOffsetWithServer(){return this._timeOffsetWithServer}calculateTimeOffsetWithServer(s,n){const g=Date.now(),u=g-s;this._timeOffsetWithServer=n+u-g}};const mc=16;var fn=new class{constructor(){this._tasks=[],this._timer=null,this._taskMap=new Map}_addTaskToScheduler(s){const{id:n}=s;this.removeTask(n),this._tasks.push(s),this._taskMap.set(n,s),this._sort(),this._scheduleNextTask()}_createTask(s){const{id:n,callback:g,context:u,isOnce:E=!1,intervalMs:m=mc}=s,D=Math.max(m,mc);return{id:n,nextExecuteTime:Date.now()+D,intervalMs:m,callback:g,context:u,isOnce:E}}addTask(s){const n=this._createTask(s);this._addTaskToScheduler(n)}addOnceTask(s){const n=this._createTask(Object.assign(Object.assign({},s),{isOnce:!0}));this._addTaskToScheduler(n)}removeTask(s){const n=this._tasks.findIndex(g=>g.id===s);n>-1&&(this._tasks.splice(n,1),this._taskMap.delete(s),this._scheduleNextTask())}updateTaskInterval(s,n){const g=this._taskMap.get(s);g&&(g.intervalMs=n,g.nextExecuteTime=Date.now()+n,this._sort(),this._scheduleNextTask())}clearAllTasks(){this._tasks=[],this._taskMap.clear(),this._timer&&(clearTimeout(this._timer),this._timer=null)}dispose(){this.clearAllTasks()}_sort(){this._tasks.sort((s,n)=>s.nextExecuteTime-n.nextExecuteTime)}_scheduleNextTask(){this._timer&&(clearTimeout(this._timer),this._timer=null);const s=this._tasks[0];if(s){const n=Math.max(0,s.nextExecuteTime-Date.now());this._timer=setTimeout(()=>this._execute(),n)}}_execute(){const s=Date.now();for(;this._tasks.length&&this._tasks[0].nextExecuteTime<=s;){const n=this._tasks[0];try{n.context?n.callback.call(n.context):n.callback(),n.isOnce?this.removeTask(n.id):(n.nextExecuteTime=s+n.intervalMs,this._sort())}catch(g){console.warn(`Task ${n.id} execution failed:`,g),n.isOnce&&this.removeTask(n.id)}}this._scheduleNextTask()}};function Ga(s){const n=[];for(let g=0;g=55296&&u<=56319){const E=s.charCodeAt(++g)-56320+(u-55296<<10)+65536;n.push(240|E>>18,128|E>>12&63,128|E>>6&63,128|63&E)}else u<=127?n.push(u):u<=2047?n.push(192|u>>6,128|63&u):n.push(224|u>>12,128|u>>6&63,128|63&u)}return new Uint8Array(n)}function In(s){const n=Array.isArray(s)?[]:Object.create(null);for(const g in s)Object.prototype.hasOwnProperty.call(s,g)&&_(g)&&s[g]!=null&&(s[g]===null||typeof s[g]!="object"?n[g]=s[g]:n[g]=In(s[g]));return n}function fs(s,n){if(mA.includes(s))return 0;const g=Ga(JSON.stringify(n));let u=4294967295;const{length:E}=g;for(let m=0;m>>=1:u=u>>>1^3988292384}return(4294967295^u)>>>0}function Ea(s){const{servcmd:n,data:g}=s,u=function(m){const D=$i.get("login")||{},M=$i.get("instance")||{};return{servcmd:m,ver:"v4",platform:HA,websdkappid:537048168,websdkversion:"1.7.3",a2:D.a2Key||void 0,tinyid:D.tinyID||void 0,status_instid:D.statusInstanceId||0,sdkappid:M.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:D.a2Key?void 0:D.userId,usersig:D.a2Key?void 0:D.userSig,sdkability:478343027,sdkability_ext:lA(""),cappid:M.applicationID||0,tjgID:"",seq:Sa(),cs:0}}(n),E=In(g);return u.cs=fs(n,E),{head:u,body:E}}function yn(s){const{servcmd:n,data:g}=s,u=function(m){const D=$i.get("login")||{},M=$i.get("instance")||{};return{servcmd:m,ver:"v4",platform:HA,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:M.sdkAppId,contenttype:"",reqtime:Math.floor(Date.now()/1e3),identifier:"",usersig:"",status_instid:D.statusInstanceId||0,sdkability:478343027,sdkability_ext:lA(""),cappid:M.applicationID||0,seq:Sa(),cs:0}}(n),E=In(g);return u.cs=fs(n,E),{head:u,body:E}}let ba=U();function Sa(){return ba=ba<2415919103?ba+1:U(),ba}function $(){var s;const n=$i.get("login")||{},g=$i.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=$i.get("webPush"))===null||s===void 0?void 0:s.userId),platform:HA,instance_id:g.instanceId,trace_id:new Date().getTime()}}var K,vA=Object.freeze({__proto__:null,calcBodyCRC:fs,filterProtocolDataInvalidFields:In,generateCosSpecifiedData:function(s){const{servcmd:n,data:g}=s,u=function(m){const D=$i.get("login")||{},M=$i.get("instance")||{};return{servcmd:m,ver:"v4",platform:HA,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:M.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:D.userId,usersig:D.userSig,status_instid:D.statusInstanceId||0,sdkability:478343027,sdkability_ext:lA(""),cappid:M.applicationID||0,seq:Sa(),cs:0}}(n),E=In(g);return u.cs=fs(n,E),{head:u,body:E}},generateProtocolData:Ea,generateSSOLogProtocolData:yn,generateSequence:Sa,getCommonHead:$,getHostSite:ua,taskScheduler:fn,timeManager:Sg});(function(s){s[s.info=4]="info",s[s.warning=5]="warning",s[s.error=6]="error"})(K||(K={}));const qA={method:"extension",networkType:"network_type",eventType:"event_type",code:"error_code",message:"error_message",moreMessage:"more_message",duplicate:"duplicate",costTime:"cost_time",level:"level",uiPlatform:"ui_platform",timestamp:"timestamp"};class Ae{constructor(n){this.level=K.info,this._canSendLog=!0,this._logCreatedAt=Sg.getServerTimeMs(),this.timestamp=0,this.networkType=8,this.code=0,this.moreMessage="",this.method="",this.message="",this.costTime=0,this.duplicate=!1,this.eventType=0,this.uiPlatform=this._getUiPlatform(),this._sdkEdition=this._getSDKEdition();const{method:g,eventType:u=0,message:E="",costTime:m=0,error:D,uiPlatform:M,moreMessage:T="",code:P=0,startTime:W=0}=n||{};this.eventType=u,this.method=g,this.message=E,this.costTime=m,this.moreMessage=`${T} startTime:${W}`,this.code=P,D&&this.setError(D),Rs(M)||(this.uiPlatform=M)}setMoreMessage(n){this.moreMessage=`${this.moreMessage} ${n}`}updateLogCreatedAtByTimeOffset(){this._logCreatedAt+=Sg.getTimeOffsetWithServer()}end(n=!1){this._canSendLog&&(this._canSendLog=!1,this.timestamp=Sg.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe()),n&&this._ssoLogModule.uploadSSOLogData())}setError(n){var g;return n instanceof Error?this._canSendLog?(!((g=$i.get("netWorkMonitor"))===null||g===void 0)&&g.isNetworkOnline&&(n.errorCode&&(this.code=n.errorCode),n.errorMessage&&this.setMoreMessage(n.errorMessage)),this.level=K.error,this):this:(console.warn("SSOLogData.setError value not instanceof Error, please check!"),this)}setLogInfo(n){return Object.keys(n).forEach(g=>{Object.keys(qA).includes(g)&&(this[g]=n[g])}),this}setSSOLogModule(n){this._ssoLogModule=n}_convertSSOLogDataKeyToServe(){const n={};return Object.keys(this).forEach(g=>{const u=g;qA[u]&&(n[qA[u]]=this[u])}),n}_getUiPlatform(){var n;const g=(n=$i.get("instance"))===null||n===void 0?void 0:n.scene;if(typeof g=="string"){const u=Number(g);return isNaN(u)?void 0:u}}_getSDKEdition(){var n;return(n=$i.get("instance"))===null||n===void 0?void 0:n.sdkEdition}}var me;(function(s){s.RECONNECTED="reconnected",s.CLOUD_CONFIG_UPDATE="cloud_config_update",s.SOCKET_DISCONNECTED="socket_disconnected"})(me||(me={}));var Pe=me;const Fe=20,rt=6e4,Ct=[4,5,6],Rt="report-logger";var Yt=new class{constructor(){this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._reportLevel=[4,5,6],this._minThreshold=Fe,this._maxThreshold=100,this._waitingTime=rt,this._lastReportAt=Date.now(),this._ssoLogMap=new Map,this._logLevel=IA.DEBUG,this._throttleConfig={global:{throttleTime:xe,maxCount:Qe},single:{throttleTime:ue,maxCount:Ce}},this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap=new Map,gn.subscribeInnerEvent(Pe.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),fn.addTask({id:Rt,intervalMs:1e3,callback:this._checkAndReportIfDue,context:this}),this._logQueue=[],this._savePlatFormInfo()}_handleCloudConfigUpdate(s){const{evt_rpt_threshold:n=Fe,evt_rpt_waiting:g=rt,evt_rpt_level:u=Ct,evt_rpt_sdkappid_bl:E="",evt_rpt_tinyid_wl:m="",evt_rpt_global_throttle_time:D=xe,evt_rpt_global_throttle_count:M=Qe,evt_rpt_single_throttle_time:T=ue,evt_rpt_single_throttle_count:P=Ce}=s||{};this._sdkAppIdBlackList=E.split(",").map(W=>Number(W)),this._waitingTime=Number(g),this._minThreshold=n,this._reportLevel=u,this._tinyIdWhiteList=m.split(","),this._throttleConfig={global:{throttleTime:D,maxCount:M},single:{throttleTime:T,maxCount:P}}}createSSOLogData(s){const n=new Ae(s);return n.setSSOLogModule(this),this._ssoLogMap.set(s.method,n),n}getSSOLogData(s){return this._ssoLogMap.get(s)||{}}pushToLogQueue(s){s&&(this._logQueue.push(s),this._shouldUploadImmediately()&&this.uploadSSOLogData())}setLogLevel(s){[IA.DEBUG,IA.ERROR,IA.INFO,IA.NONE,IA.WARN].includes(s)&&(this._logLevel=s)}debug(s,n="",g){this._log(IA.DEBUG,s,n,g)}info(s,n="",g){this._log(IA.INFO,s,n,g)}warn(s,n="",g){this._log(IA.WARN,s,n,g)}error(s,n="",g){this._log(IA.ERROR,s,n,g)}_shouldUploadImmediately(){return this._logQueue.length>=this._minThreshold}_isReportDue(){return Date.now()>=this._lastReportAt+this._waitingTime}_checkAndReportIfDue(){this._isReportDue()&&this._logQueue.length>0&&this.uploadSSOLogData()}uploadSSOLogData(){return pA(this,void 0,void 0,function*(){if(this._logQueue.length===0)return;const s=this._logQueue.slice();this._logQueue=[];try{const n=this._filterLogs(s);if(n.length===0)return void(this._lastReportAt=Date.now());const g={Header:$(),Event:n};Rs(g.Header.user_id)||(yield function(u){const E="imopenstat.tim_web_report_v2",m=yn({servcmd:E,data:u}),D=`${m.head.seq}${E}`;return ye.sendPacket(m,{requestId:D})}(g))}catch(n){this._requeueFailedLogs(s),this.debug("uploadSSOLogData",en(n))}finally{this._lastReportAt=Date.now()}})}_requeueFailedLogs(s){this._logQueue=s.concat(this._logQueue);const n=this._logQueue.length-200;n>0&&(this._logQueue.splice(0,n),this.debug("uploadSSOLogData",`log queue overflow, dropped ${n} oldest logs`))}_savePlatFormInfo(){var s,n;if(Et){const g=(n=(s=wx.getAccountInfoSync)===null||s===void 0?void 0:s.call(wx))===null||n===void 0?void 0:n.miniProgram;if(g){const{appId:u,envVersion:E}=g;$i.set("instance",{appId:u,envVersion:E})}}else Zt&&$i.set("instance",{href:window.location.href})}_filterLogs(s){const{tinyID:n}=$i.get("login")||{},{sdkAppId:g}=$i.get("instance")||{};return this._sdkAppIdBlackList.includes(g)&&!this._tinyIdWhiteList.includes(n)?[]:s.filter(u=>this._reportLevel.includes(u.level))}_checkThrottle(s){return!!this._checkGlobalThrottle()||this._checkSingleThrottle(s)}_checkGlobalThrottle(){const s=Date.now();if(s-this._globalThrottle.startTime>=this._throttleConfig.global.throttleTime)this._globalThrottle.count=1,this._globalThrottle.startTime=s;else if(this._globalThrottle.count++,this._globalThrottle.count>this._throttleConfig.global.maxCount)return!0;return!1}_checkSingleThrottle(s){const n=Date.now(),g=this._singleThrottleMap.get(s);return g?n-g.startTime>=this._throttleConfig.single.throttleTime?(g.count=1,g.startTime=n,!1):g.count>=this._throttleConfig.single.maxCount||(g.count++,!1):(this._singleThrottleMap.set(s,{count:1,startTime:n}),!1)}_shouldLog(s){return s>=this._logLevel&&this._logLevel!==IA.NONE}_shouldReport(s){return this._reportLevel.includes(WA[s])}_formatLog(s,n,g,u){const E=new Date,m=`${E.getHours()}:${E.getMinutes()}:${E.getSeconds()}:${E.getMilliseconds()}`,D=`<${IA[s]}>`;return Nt||ki?[`${cA} [${m}] ${D} [${n}] ${g}`]:["%c%s%c%s","background:#0abf5b; padding:1px; border-radius:3px; color: #fff",cA,"",`[${m}] ${D} [${n}] ${g} params: ${en(u)}`]}_log(s,n,g,u){if(this._shouldLog(s)){const E=this._formatLog(s,n,g,u);TA[s].apply(console,E)}if(this._shouldReport(s)){const E=this._getThrottleKey(n,g,u);this._checkThrottle(E)||this.createSSOLogData(Object.assign(Object.assign({message:g},u),{method:n})).end()}}_getThrottleKey(s,n,g){const u=`${s}${n}${en(Object.assign(Object.assign({},g),{costTime:""}))}`,E=Ga(JSON.stringify(u));let m=4294967295;const{length:D}=E;for(let M=0;M>>=1:m=m>>>1^3988292384}return`${(4294967295^m)>>>0}`}reset(){console.log("SSO_LOG_MODULE.reset"),fn.removeTask(Rt),gn.unSubscribeInnerEvent(Pe.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),this._lastReportAt=0,this.uploadSSOLogData(),this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._minThreshold=Fe,this._maxThreshold=100,this._waitingTime=rt,this._logQueue=[],this._logLevel=IA.DEBUG,this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap.clear()}};const Ii=15e3,ct="Channel",xt="channel_schedule_task",Ji="channel_reconnect_task",Ki="connected",qs="connecting",Mi="disconnected",zo=1e3,Mg="network_status_change",sr="activity_status_change",yr="send_fail",xn="reconnect_failed",Ml="socket_error",Ks="socket_close";function aI(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function Wg(s){return Wg=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(n){return typeof n}:function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},Wg(s)}function fc(s){throw new Error('Could not dynamically require "'+s+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var wu,Ma={exports:{}},vl=(wu||(wu=1,function(s){s.exports=function n(g,u,E){function m(T,P){if(!u[T]){if(!g[T]){if(!P&&fc)return fc(T);if(D)return D(T,!0);var W=new Error("Cannot find module '"+T+"'");throw W.code="MODULE_NOT_FOUND",W}var iA=u[T]={exports:{}};g[T][0].call(iA.exports,function(EA){return m(g[T][1][EA]||EA)},iA,iA.exports,n,g,u,E)}return u[T].exports}for(var D=fc,M=0;M>>6:(EA<65536?iA[xA++]=224|EA>>>12:(iA[xA++]=240|EA>>>18,iA[xA++]=128|EA>>>12&63),iA[xA++]=128|EA>>>6&63),iA[xA++]=128|63&EA);return iA},u.buf2binstring=function(W){return P(W,W.length)},u.binstring2buf=function(W){for(var iA=new E.Buf8(W.length),EA=0,RA=iA.length;EA>10&1023,SA[RA++]=56320|1023&kA)}return P(SA,RA)},u.utf8border=function(W,iA){var EA;for((iA=iA||W.length)>W.length&&(iA=W.length),EA=iA-1;0<=EA&&(192&W[EA])==128;)EA--;return EA<0||EA===0?iA:EA+M[W[EA]]>iA?EA:iA}},{"./common":1}],3:[function(n,g,u){g.exports=function(E,m,D,M){for(var T=65535&E,P=E>>>16&65535,W=0;D!==0;){for(D-=W=2e3>>1:m>>>1;D[M]=m}return D}();g.exports=function(m,D,M,T){var P=E,W=T+M;m^=-1;for(var iA=T;iA>>8^P[255&(m^D[iA])];return-1^m}},{}],6:[function(n,g,u){g.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],7:[function(n,g,u){g.exports=function(E,m){var D,M,T,P,W,iA,EA,RA,kA,xA,LA,SA,OA,JA,ae,se,_i,Ti,Ft,Ni,cs,Se,mt,UA,ri;D=E.state,M=E.next_in,UA=E.input,T=M+(E.avail_in-5),P=E.next_out,ri=E.output,W=P-(m-E.avail_out),iA=P+(E.avail_out-257),EA=D.dmax,RA=D.wsize,kA=D.whave,xA=D.wnext,LA=D.window,SA=D.hold,OA=D.bits,JA=D.lencode,ae=D.distcode,se=(1<>>=Ft=Ti>>>24,OA-=Ft,(Ft=Ti>>>16&255)==0)ri[P++]=65535&Ti;else{if(!(16&Ft)){if(!(64&Ft)){Ti=JA[(65535&Ti)+(SA&(1<>>=Ft,OA-=Ft),OA<15&&(SA+=UA[M++]<>>=Ft=Ti>>>24,OA-=Ft,!(16&(Ft=Ti>>>16&255))){if(!(64&Ft)){Ti=ae[(65535&Ti)+(SA&(1<>>=Ft,OA-=Ft,(Ft=P-W)>3,SA&=(1<<(OA-=Ni<<3))-1,E.next_in=M,E.next_out=P,E.avail_in=M>>24&255)+(Se>>>8&65280)+((65280&Se)<<8)+((255&Se)<<24)}function SA(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new E.Buf16(320),this.work=new E.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function OA(Se){var mt;return Se&&Se.state?(mt=Se.state,Se.total_in=Se.total_out=mt.total=0,Se.msg="",mt.wrap&&(Se.adler=1&mt.wrap),mt.mode=RA,mt.last=0,mt.havedict=0,mt.dmax=32768,mt.head=null,mt.hold=0,mt.bits=0,mt.lencode=mt.lendyn=new E.Buf32(kA),mt.distcode=mt.distdyn=new E.Buf32(xA),mt.sane=1,mt.back=-1,iA):EA}function JA(Se){var mt;return Se&&Se.state?((mt=Se.state).wsize=0,mt.whave=0,mt.wnext=0,OA(Se)):EA}function ae(Se,mt){var UA,ri;return Se&&Se.state?(ri=Se.state,mt<0?(UA=0,mt=-mt):(UA=1+(mt>>4),mt<48&&(mt&=15)),mt&&(mt<8||15=Gi.wsize?(E.arraySet(Gi.window,mt,UA-Gi.wsize,Gi.wsize,0),Gi.wnext=0,Gi.whave=Gi.wsize):(ri<(_s=Gi.wsize-Gi.wnext)&&(_s=ri),E.arraySet(Gi.window,mt,UA-ri,_s,Gi.wnext),(ri-=_s)?(E.arraySet(Gi.window,mt,UA-ri,ri,0),Gi.wnext=ri,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),bt=Gt=0,UA.mode=2;break}if(UA.flags=0,UA.head&&(UA.head.done=!1),!(1&UA.wrap)||(((255&Gt)<<8)+(Gt>>8))%31){Se.msg="incorrect header check",UA.mode=30;break}if((15&Gt)!=8){Se.msg="unknown compression method",UA.mode=30;break}if(bt-=4,Va=8+(15&(Gt>>>=4)),UA.wbits===0)UA.wbits=Va;else if(Va>UA.wbits){Se.msg="invalid window size",UA.mode=30;break}UA.dmax=1<>8&1),512&UA.flags&&(dg[0]=255&Gt,dg[1]=Gt>>>8&255,UA.check=D(UA.check,dg,2,0)),bt=Gt=0,UA.mode=3;case 3:for(;bt<32;){if(xi===0)break A;xi--,Gt+=ri[Gi++]<>>8&255,dg[2]=Gt>>>16&255,dg[3]=Gt>>>24&255,UA.check=D(UA.check,dg,4,0)),bt=Gt=0,UA.mode=4;case 4:for(;bt<16;){if(xi===0)break A;xi--,Gt+=ri[Gi++]<>8),512&UA.flags&&(dg[0]=255&Gt,dg[1]=Gt>>>8&255,UA.check=D(UA.check,dg,2,0)),bt=Gt=0,UA.mode=5;case 5:if(1024&UA.flags){for(;bt<16;){if(xi===0)break A;xi--,Gt+=ri[Gi++]<>>8&255,UA.check=D(UA.check,dg,2,0)),bt=Gt=0}else UA.head&&(UA.head.extra=null);UA.mode=6;case 6:if(1024&UA.flags&&(xi<(Bo=UA.length)&&(Bo=xi),Bo&&(UA.head&&(Va=UA.head.extra_len-UA.length,UA.head.extra||(UA.head.extra=new Array(UA.head.extra_len)),E.arraySet(UA.head.extra,ri,Gi,Bo,Va)),512&UA.flags&&(UA.check=D(UA.check,ri,Bo,Gi)),xi-=Bo,Gi+=Bo,UA.length-=Bo),UA.length))break A;UA.length=0,UA.mode=7;case 7:if(2048&UA.flags){if(xi===0)break A;for(Bo=0;Va=ri[Gi+Bo++],UA.head&&Va&&UA.length<65536&&(UA.head.name+=String.fromCharCode(Va)),Va&&Bo>9&1,UA.head.done=!0),Se.adler=UA.check=0,UA.mode=12;break;case 10:for(;bt<32;){if(xi===0)break A;xi--,Gt+=ri[Gi++]<>>=7&bt,bt-=7&bt,UA.mode=27;break}for(;bt<3;){if(xi===0)break A;xi--,Gt+=ri[Gi++]<>>=1)){case 0:UA.mode=14;break;case 1:if(Ni(UA),UA.mode=20,mt!==6)break;Gt>>>=2,bt-=2;break A;case 2:UA.mode=17;break;case 3:Se.msg="invalid block type",UA.mode=30}Gt>>>=2,bt-=2;break;case 14:for(Gt>>>=7&bt,bt-=7&bt;bt<32;){if(xi===0)break A;xi--,Gt+=ri[Gi++]<>>16^65535)){Se.msg="invalid stored block lengths",UA.mode=30;break}if(UA.length=65535&Gt,bt=Gt=0,UA.mode=15,mt===6)break A;case 15:UA.mode=16;case 16:if(Bo=UA.length){if(xi>>=5,bt-=5,UA.ndist=1+(31&Gt),Gt>>>=5,bt-=5,UA.ncode=4+(15&Gt),Gt>>>=4,bt-=4,286>>=3,bt-=3}for(;UA.have<19;)UA.lens[rS[UA.have++]]=0;if(UA.lencode=UA.lendyn,UA.lenbits=7,_I={bits:UA.lenbits},Yl=T(0,UA.lens,0,19,UA.lencode,0,UA.work,_I),UA.lenbits=_I.bits,Yl){Se.msg="invalid code lengths set",UA.mode=30;break}UA.have=0,UA.mode=19;case 19:for(;UA.have>>16&255,wI=65535&Yg,!((Tr=Yg>>>24)<=bt);){if(xi===0)break A;xi--,Gt+=ri[Gi++]<>>=Tr,bt-=Tr,UA.lens[UA.have++]=wI;else{if(wI===16){for(iE=Tr+2;bt>>=Tr,bt-=Tr,UA.have===0){Se.msg="invalid bit length repeat",UA.mode=30;break}Va=UA.lens[UA.have-1],Bo=3+(3&Gt),Gt>>>=2,bt-=2}else if(wI===17){for(iE=Tr+3;bt>>=Tr)),Gt>>>=3,bt-=3}else{for(iE=Tr+7;bt>>=Tr)),Gt>>>=7,bt-=7}if(UA.have+Bo>UA.nlen+UA.ndist){Se.msg="invalid bit length repeat",UA.mode=30;break}for(;Bo--;)UA.lens[UA.have++]=Va}}if(UA.mode===30)break;if(UA.lens[256]===0){Se.msg="invalid code -- missing end-of-block",UA.mode=30;break}if(UA.lenbits=9,_I={bits:UA.lenbits},Yl=T(P,UA.lens,0,UA.nlen,UA.lencode,0,UA.work,_I),UA.lenbits=_I.bits,Yl){Se.msg="invalid literal/lengths set",UA.mode=30;break}if(UA.distbits=6,UA.distcode=UA.distdyn,_I={bits:UA.distbits},Yl=T(W,UA.lens,UA.nlen,UA.ndist,UA.distcode,0,UA.work,_I),UA.distbits=_I.bits,Yl){Se.msg="invalid distances set",UA.mode=30;break}if(UA.mode=20,mt===6)break A;case 20:UA.mode=21;case 21:if(6<=xi&&258<=gr){Se.next_out=Or,Se.avail_out=gr,Se.next_in=Gi,Se.avail_in=xi,UA.hold=Gt,UA.bits=bt,M(Se,ln),Or=Se.next_out,_s=Se.output,gr=Se.avail_out,Gi=Se.next_in,ri=Se.input,xi=Se.avail_in,Gt=UA.hold,bt=UA.bits,UA.mode===12&&(UA.back=-1);break}for(UA.back=0;xg=(Yg=UA.lencode[Gt&(1<>>16&255,wI=65535&Yg,!((Tr=Yg>>>24)<=bt);){if(xi===0)break A;xi--,Gt+=ri[Gi++]<>ac)])>>>16&255,wI=65535&Yg,!(ac+(Tr=Yg>>>24)<=bt);){if(xi===0)break A;xi--,Gt+=ri[Gi++]<>>=ac,bt-=ac,UA.back+=ac}if(Gt>>>=Tr,bt-=Tr,UA.back+=Tr,UA.length=wI,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(iE=UA.extra;bt>>=UA.extra,bt-=UA.extra,UA.back+=UA.extra}UA.was=UA.length,UA.mode=23;case 23:for(;xg=(Yg=UA.distcode[Gt&(1<>>16&255,wI=65535&Yg,!((Tr=Yg>>>24)<=bt);){if(xi===0)break A;xi--,Gt+=ri[Gi++]<>ac)])>>>16&255,wI=65535&Yg,!(ac+(Tr=Yg>>>24)<=bt);){if(xi===0)break A;xi--,Gt+=ri[Gi++]<>>=ac,bt-=ac,UA.back+=ac}if(Gt>>>=Tr,bt-=Tr,UA.back+=Tr,64&xg){Se.msg="invalid distance code",UA.mode=30;break}UA.offset=wI,UA.extra=15&xg,UA.mode=24;case 24:if(UA.extra){for(iE=UA.extra;bt>>=UA.extra,bt-=UA.extra,UA.back+=UA.extra}if(UA.offset>UA.dmax){Se.msg="invalid distance too far back",UA.mode=30;break}UA.mode=25;case 25:if(gr===0)break A;if(Bo=ln-gr,UA.offset>Bo){if((Bo=UA.offset-Bo)>UA.whave&&UA.sane){Se.msg="invalid distance too far back",UA.mode=30;break}Bo>UA.wnext?(Bo-=UA.wnext,Il=UA.wsize-Bo):Il=UA.wnext-Bo,Bo>UA.length&&(Bo=UA.length),_C=UA.window}else _C=_s,Il=Or-UA.offset,Bo=UA.length;for(gr_i?(Ft=Il[_C+xA[mt]],Ni=bt[tE+xA[mt]]):(Ft=96,Ni=0),SA=1<>Or)+(OA-=SA)]=Ti<<24|Ft<<16|Ni,OA!==0;);for(SA=1<>=1;if(SA!==0?(Gt&=SA-1,Gt+=SA):Gt=0,mt++,--ln[Se]==0){if(Se===ri)break;Se=W[iA+xA[mt]]}if(_s{const M=new Uint8Array(D).slice(4);let T;try{T=vl.inflate(M,{to:"string"})}catch(P){console.error("inflate error",P)}return T})(s.data):function(D){const M=new Uint8Array(D);let T="",P=0;const{length:W}=M;for(;P0)for(let kA=0;kA{var u;const{uplinkData:E,canResend:m,resolve:D,reject:M,timeout:T}=n;if(m){this._pendingRequests.set(g,{resolve:D,reject:M,timestamp:Date.now(),uplinkData:E,timeout:T,canResend:m});const P=this._isBinarySupported?Ga(E).buffer:E;(u=this._socketAdapter)===null||u===void 0||u.send(P)}else this._pendingRequests.delete(g)})}_onConnect(s){const{socketId:n,event:g={}}=s||{};this._connectionId=n,this._connectionEstablishedTime=Date.now();const u=Date.now()-this._connectionStartTime,E=`${ct}.onConnect cost:${u} ms. socketID:${n} res:${JSON.stringify(g)}`;if(this._ssoLog({method:"onConnect",message:E}),this._checkPendingRequestsAndResend(),this._sendHeartbeatIfReady(),this._isReconnecting){const m=`${ct}.reconnect success`;this._ssoLog({method:"reconnectSuccess",message:m}),gn.emitInnerEvent(Pe.RECONNECTED),this._isReconnecting=!1}this._resetReconnectDelay(),this._handleConnectStateChange({state:Ki,shouldEmitEvent:!0,shouldAttemptReconnect:!1})}_sendAck(s){const n=Ea({servcmd:"openim.ws_msg_push_ack",data:{SessionData:s}});this.sendPacket(n)}_executeScheduledTaskIfReady(){return pA(this,void 0,void 0,function*(){this._clearTimeoutRequest(),this._sendHeartbeatIfReady()})}_canSendHeartbeat(){var s;return((s=this._socketAdapter)===null||s===void 0?void 0:s.isConnected())&&Date.now()>=this._nextHeartbeatAt&&!this._isHeartbeatInProgress}_sendHeartbeat(){return pA(this,void 0,void 0,function*(){var s;const n=Ea({servcmd:"heartbeat.alive",data:{}});try{const g=`${n.head.seq}${n.head.servcmd}`;yield this.sendPacket(n,{requestId:g,timeout:3e3})}catch(g){const u=(s=$i.get("netWorkMonitor"))===null||s===void 0?void 0:s.isNetworkOnline,E=`${ct}.sendHeartbeat failed. isNetWorkOnline:${u} error: ${en(g)}`;this._ssoLog({method:"sendHeartbeatError",message:E}),this._handleConnectStateChange({state:Mi,shouldEmitEvent:!0,shouldAttemptReconnect:!0})}})}_sendHeartbeatIfReady(){return pA(this,void 0,void 0,function*(){this._canSendHeartbeat()&&(this._isHeartbeatInProgress=!0,yield this._sendHeartbeat(),this._isHeartbeatInProgress=!1)})}_updateHeartbeatTime(){this._nextHeartbeatAt=To?Date.now()+5e3:Date.now()+1e4}_handleNetworkStatusChange(s){const n=`${ct}.networkStatusChange ${JSON.stringify(s)}`;this._ssoLog({method:"networkStatusChange",message:n});const{isNetworkOnline:g,networkType:u}=s;g&&u!=="none"?this._handleConnectStateChange({state:Ki,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Mg}):this._handleConnectStateChange({state:Mi,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Mg})}isPrivateNetWork(){const s=$i.get("instance")||{};return s.proxyServer&&!s.fileDownloadProxy}_handleConnectStateChange(s){const{state:n,shouldAttemptReconnect:g,shouldEmitEvent:u,reason:E}=s,m=`${ct}._handleConnectStateChange currentConnectState: ${this._currentConnectState} shouldAttemptReconnect: ${g} shouldEmitEvent: ${u} reason: ${E}`;this._currentConnectState!==n&&(this._ssoLog({method:"handleConnectStateChange",message:m}),u&&(Yt.info("_handleConnectStateChange",` from ${this._currentConnectState} to ${n}`),gn.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:n}}),this._currentConnectState=n,n===Mi&&gn.emitInnerEvent(Pe.SOCKET_DISCONNECTED)),g&&(this._resetReconnectDelay(),fn.addTask({id:Ji,intervalMs:this._intendedDelay,callback:this._scheduleReconnectWithBackoff,context:this})))}_handleActivityStatusChange(s){var n,g;const u=(g=(n=this._socketAdapter)===null||n===void 0?void 0:n._ws)===null||g===void 0?void 0:g.readyState,E=`${ct}.activityStatusChange ${JSON.stringify(s)} readyState: ${u}`;Yt.debug("activityStatusChange",E),u===3&&this._handleConnectStateChange({state:Mi,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:sr})}_resetReconnectDelay(){var s;Yt.debug(`${ct}._resetReconnectDelay`),fn.removeTask(Ji);const n=(s=$i.get("activityMonitor"))===null||s===void 0?void 0:s.isActive;this._intendedDelay=n?zo:1e3}_scheduleReconnectWithBackoff(){var s;const n=(s=$i.get("activityMonitor"))===null||s===void 0?void 0:s.isActive;this._intendedDelay=n?Math.min(5e3,Math.max(zo,1.5*this._intendedDelay)):Math.min(3e5,Math.max(1e3,1.5*this._intendedDelay));const g=new Date().toTimeString().slice(0,8),u=`${ct}.scheduleReconnectWithBackoff timeStr: ${g} intendedDelay: ${this._intendedDelay}`;Yt.debug(u),this.reconnect(),fn.updateTaskInterval(Ji,this._intendedDelay)}_ssoLog(s){const{method:n,message:g}=s;Yt.info(n,g)}_diagnose(){this.isPrivateNetWork()||(this._lastDiagnoseAt=Date.now(),function(s){pA(this,void 0,void 0,function*(){const n=s.split("/")[2];if(!n.startsWith("ws"))return;const g=`https://${n}/v3/netcheck/getconninfo?${s.slice(s.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield Pi({method:"GET",url:g,data:{}})}catch(u){Yt.warn("diagnoseBySSO",`diagnoseBySSO failed. error:${u.message}`)}})}(this._url),function(s){pA(this,void 0,void 0,function*(){const n=`https://boce-cdn.my-imcloud.com/v3/netcheck/getconninfo?${s.slice(s.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield Pi({method:"GET",url:n,data:{}})}catch(g){Yt.warn(`diagnoseByCDN', 'diagnoseByCDN failed. error:${g.message}`)}})}(this._url),this._beforeSendInterceptors=[])}_clearTimeoutRequest(){for(const[s,n]of this._pendingRequests.entries()){const{reject:g,timestamp:u,timeout:E}=n;Date.now()-u>=E&&(this._pendingRequests.delete(s),Date.now()-this._lastDiagnoseAt>=3e4&&this._diagnose(),g({errorCode:Qr,errorInfo:"NETWORK_TIMEOUT",data:{requestId:s}}))}}_updateIsBinarySupported(){var s;if(!((s=$i.get("instance"))===null||s===void 0)&&s.devMode)return void(this._isBinarySupported=!1);const n=Es();if((gt||Et&&n==="windows"||Vs)&&(this._isBinarySupported=!1),To){const{uniRuntimeVersion:g=""}=oo.getSystemInfoSync();(function(u){const E=u.split(".").map(Number),[m=0,D=0,M=0]=E;return m>2||!(m<2)&&(D>2||!(D<2)&&M>=6)})(g)||(this._isBinarySupported=!1)}}_isCompressedData(s){const n=new Uint8Array(s);return n[0]===67&&n[1]===79&&n[2]===77&&n[3]===80}};const fe={init:function(s){$i.set("instance",s),ye.init()},destroy:function(){ye.dispose(),$i.clear(),fn.dispose()},notificationCenter:gn,channel:ye,store:$i,ssoLog:Yt,utils:yg,common:vA,constants:Mt},vg=s=>typeof s=="function";function rg(s,n,g){const u=g||[];if(!s||!n)return!1;const E=Object.keys(s).filter(D=>!u.includes(D)),m=Object.keys(n).filter(D=>!u.includes(D));return E.length===m.length&&E.every(D=>!!n.hasOwnProperty(D)&&(typeof s[D]=="object"&&s[D]!==null?rg(s[D],n[D],g):s[D]===n[D]))}var Rg;(function(s){s.SDK_READY="sdkStateReady",s.SDK_NOT_READY="sdkStateNotReady",s.SDK_DESTROY="sdkDestroy",s.MESSAGE_RECEIVED="onMessageReceived",s.ROOM_CUSTOM_DATA_RECEIVED="onRoomCustomDataReceived",s.MESSAGE_MODIFIED="onMessageModified",s.MESSAGE_REVOKED="onMessageRevoked",s.MESSAGE_READ_BY_PEER="onMessageReadByPeer",s.MESSAGE_READ_RECEIPT_RECEIVED="onMessageReadReceiptReceived",s.MESSAGE_EXTENSIONS_UPDATED="onMessageExtensionsUpdated",s.MESSAGE_EXTENSIONS_DELETED="onMessageExtensionsDeleted",s.MESSAGE_REACTIONS_UPDATED="onMessageReactionsUpdated",s.CONVERSATION_LIST_UPDATED="onConversationListUpdated",s.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED="onTotalUnreadMessageCountUpdated",s.CONVERSATION_GROUP_LIST_UPDATED="onConversationGroupListUpdated",s.CONVERSATION_IN_GROUP_UPDATED="onConversationInGroupUpdated",s.GROUP_LIST_UPDATED="onGroupListUpdated",s.GROUP_ATTRIBUTES_UPDATED="groupAttributesUpdated",s.GROUP_COUNTER_UPDATED="onGroupCounterUpdated",s.TOPIC_CREATED="onTopicCreated",s.TOPIC_DELETED="onTopicDeleted",s.TOPIC_UPDATED="onTopicUpdated",s.PROFILE_UPDATED="onProfileUpdated",s.USER_STATUS_UPDATED="onUserStatusUpdated",s.BLACKLIST_UPDATED="blacklistUpdated",s.FRIEND_LIST_UPDATED="onFriendListUpdated",s.FRIEND_GROUP_LIST_UPDATED="onFriendGroupListUpdated",s.FRIEND_APPLICATION_LIST_UPDATED="onFriendApplicationListUpdated",s.MY_FOLLOWERS_LIST_UPDATED="onMyFollowersListUpdated",s.MY_FOLLOWING_LIST_UPDATED="onMyFollowingListUpdated",s.MUTUAL_FOLLOWERS_LIST_UPDATED="onMutualFollowersListUpdated",s.KICKED_OUT="kickedOut",s.ERROR="error",s.NET_STATE_CHANGE="netStateChange",s.ALL_RECEIVE_MESSAGE_OPT_UPDATED="onAllReceiveMessageOptUpdated",s.SERVER_CONFIG_UPDATED="onServerConfigUpdated",s.PINNED_GROUP_MESSAGE_UPDATED="onPinnedGroupMessageUpdated",s.WEB_PUSH_MESSAGE_RECEIVED="onWebPushMessageReceived",s.GROUP_ONLINE_MEMBER_COUNT_CHANGED="onGroupOnlineMemberCountChanged",s.RICH_STATUS_CHANGED="onRichStatusChanged"})(Rg||(Rg={}));var Dn,Dr=Rg;(function(s){s.LOGOUT="logout",s.DESTROY="destroy",s.CLOUD_CONFIG_UPDATE="cloud_config_update",s.PROFILE_UPDATE="profile_updated",s.ERROR="error",s.RECONNECTED="reconnected",s.FORCE_OFFLINE="im_open_status.stat_forceoffline",s.COMMERCIAL_CONFIG_PUSH="im_sdk_config_mgr.push_imsdk_purchase_bitsv2",s.OVERLOAD_PUSH="OverLoadPush.notify2",s.NEW_MESSAGE="new_message",s.MESSAGE_PUSH="im_open_push.msg_push",s.MESSAGE_DELETED="message_deleted",s.MESSAGE_REVOKED="message_revoked",s.MESSAGE_MODIFIED="message_modified",s.SOCKET_DISCONNECTED="socket_disconnected",s.CONVERSATION_UPDATED="conversation_updated",s.TOPIC_MESSAGE_DELETED="topic_message_deleted",s.TOPIC_MESSAGE_REVOKED="topic_message_revoked",s.TOPIC_MESSAGE_MODIFIED="topic_message_modified",s.TOPIC_NEW_MESSAGE="topic_new_message",s.QUALITY_STAT="quality_stat",s.SYNC_CONVERSATION_LIST="sync_conversation_list",s.HISTORY_MESSAGE_FETCHED="history_message_fetched"})(Dn||(Dn={}));var ui,no=Dn;(function(s){s.NEW_INVITATION_RECEIVED="newInvitationReceived",s.INVITEE_ACCEPTED="ts_invitee_accepted",s.INVITEE_REJECTED="ts_invitee_rejected",s.INVITATION_CANCELLED="ts_invitation_cancelled",s.INVITATION_TIMEOUT="ts_invitation_timeout",s.INVITATION_MODIFIED="ts_invitation_modified"})(ui||(ui={}));var qc=ui;const zg=Object.assign({},{KICKED_OUT_MULT_ACCOUNT:"multipleAccount",KICKED_OUT_MULT_DEVICE:"multipleDevice",KICKED_OUT_USERSIG_EXPIRED:"userSigExpired",KICKED_OUT_REST_API:"REST_API_Kick"}),wg={MSG_TEXT:"TIMTextElem",MSG_IMAGE:"TIMImageElem",MSG_AUDIO:"TIMSoundElem",MSG_FILE:"TIMFileElem",MSG_FACE:"TIMFaceElem",MSG_VIDEO:"TIMVideoFileElem",MSG_LOCATION:"TIMLocationElem",MSG_GRP_TIP:"TIMGroupTipElem",MSG_GRP_SYS_NOTICE:"TIMGroupSystemNoticeElem",MSG_CUSTOM:"TIMCustomElem",MSG_MERGER:"TIMRelayElem",MSG_STREAM:"TIMStreamElem"};var Yr;(function(s){s.UNSENT="unSend",s.SUCCESS="success",s.FAIL="fail"})(Yr||(Yr={}));const yc={modify:no.MESSAGE_MODIFIED,delete:no.MESSAGE_DELETED,revoke:no.MESSAGE_REVOKED};var Kc;(function(s){s[s.FORWARD=0]="FORWARD",s[s.BACKWARD=1]="BACKWARD"})(Kc||(Kc={}));const ag=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},wg),{MSG_PRIORITY_HIGH:"High",MSG_PRIORITY_NORMAL:"Normal",MSG_PRIORITY_LOW:"Low",MSG_PRIORITY_LOWEST:"Lowest"}),{RECEIVE_WITH_OFFLINE_PUSH_EXCEPT_AT:"AcceptNotNotifyExceptAt",NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT:"AcceptNotNotifyExceptAt",NOT_RECEIVE_MSG_EXCEPT_AT:"NotReceiveMsgExceptAt",MSG_AT_ALL:"__kImSDK_MesssageAtALL__"}),{MSG_REMIND_ACPT_AND_NOTE:"AcceptAndNotify",MSG_REMIND_ACPT_NOT_NOTE:"AcceptNotNotify",MSG_REMIND_DISCARD:"Discard"}),{MessageStatus:Yr,Direction:Kc}),_u={[yc.modify]:no.TOPIC_MESSAGE_MODIFIED,[yc.delete]:no.TOPIC_MESSAGE_DELETED,[yc.revoke]:no.TOPIC_MESSAGE_REVOKED},SE={GENDER_UNKNOWN:"Gender_Type_Unknown",GENDER_FEMALE:"Gender_Type_Female",GENDER_MALE:"Gender_Type_Male",USER_STATUS_UNKNOWN:0,USER_STATUS_ONLINE:1,USER_STATUS_OFFLINE:2,USER_STATUS_UNLOGINED:3,USER_NOT_FOUND:"@TLS#NOT_FOUND"},_g=Object.assign({},SE),ka={CONV_C2C:"C2C",CONV_GROUP:"GROUP",CONV_TOPIC:"TOPIC",CONV_SYSTEM:"@TIM#SYSTEM"},Dc=Object.assign(Object.assign(Object.assign(Object.assign({},ka),{CONV_AT_ME:1,CONV_AT_ALL:2,CONV_AT_ALL_AT_ME:3}),{CONV_MARK_TYPE_STAR:1,CONV_MARK_TYPE_UNREAD:2,CONV_MARK_TYPE_FOLD:4,CONV_MARK_TYPE_HIDE:8}),{READ_ALL_C2C_MSG:"readAllC2CMessage",READ_ALL_GROUP_MSG:"readAllGroupMessage",READ_ALL_MSG:"readAllMessage"}),ME=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},{SNS_TYPE_NO_RELATION:"CheckResult_Type_NoRelation",SNS_TYPE_A_WITH_B:"CheckResult_Type_AWithB",SNS_TYPE_B_WITH_A:"CheckResult_Type_BWithA",SNS_TYPE_BOTH_WAY:"CheckResult_Type_BothWay"}),{ALLOW_TYPE_ALLOW_ANY:"AllowType_Type_AllowAny",ALLOW_TYPE_NEED_CONFIRM:"AllowType_Type_NeedConfirm",ALLOW_TYPE_DENY_ANY:"AllowType_Type_DenyAny"}),{SNS_ADD_TYPE_SINGLE:"Add_Type_Single",SNS_ADD_TYPE_BOTH:"Add_Type_Both"}),{SNS_DELETE_TYPE_SINGLE:"Delete_Type_Single",SNS_DELETE_TYPE_BOTH:"Delete_Type_Both"}),{SNS_APPLICATION_TYPE_BOTH:"Pendency_Type_Both",SNS_APPLICATION_SENT_TO_ME:"Pendency_Type_ComeIn",SNS_APPLICATION_SENT_BY_ME:"Pendency_Type_SendOut",SNS_APPLICATION_AGREE:"Response_Action_Agree",SNS_APPLICATION_AGREE_AND_ADD:"Response_Action_AgreeAndAdd"}),{SNS_CHECK_TYPE_BOTH:"CheckResult_Type_Both",SNS_CHECK_TYPE_SINGLE:"CheckResult_Type_Single"}),{FORBID_TYPE_NONE:"AdminForbid_Type_None",FORBID_TYPE_SEND_OUT:"AdminForbid_Type_SendOut"}),La={GRP_WORK:"Private",GRP_PUBLIC:"Public",GRP_MEETING:"ChatRoom",GRP_AVCHATROOM:"AVChatRoom",GRP_COMMUNITY:"Community",GRP_ROOM:"Room",GRP_LIVE:"Live"},sa={COMMUNITY:"@TGS#_",TOPIC:"@TOPIC#_"},Tg={JOINED:1,QUITTED:2,KICKED:3,ADMIN_SET:4,ADMIN_CANCELED:5,GROUP_PROFILE_UPDATED:6,GROUP_MEMBER_PROFILE_UPDATED:7,TOPIC_PROFILE_UPDATED:8},gI=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},La),{GRP_MBR_ROLE_OWNER:"Owner",GRP_MBR_ROLE_ADMIN:"Admin",GRP_MBR_ROLE_MEMBER:"Member",GRP_MBR_ROLE_CUSTOM:"Custom"}),{GRP_TIP_MBR_JOIN:1,GRP_TIP_MBR_QUIT:2,GRP_TIP_MBR_KICKED_OUT:3,GRP_TIP_MBR_SET_ADMIN:4,GRP_TIP_MBR_CANCELED_ADMIN:5,GRP_TIP_GRP_PROFILE_UPDATED:6,GRP_TIP_MBR_PROFILE_UPDATED:7,GRP_TIP_BAN_AVCHATROOM_MEMBER:10,GRP_TIP_UNBAN_AVCHATROOM_MEMBER:11}),{JOIN_OPTIONS_FREE_ACCESS:"FreeAccess",JOIN_OPTIONS_NEED_PERMISSION:"NeedPermission",JOIN_OPTIONS_DISABLE_APPLY:"DisableApply",JOIN_STATUS_SUCCESS:"JoinedSuccess",JOIN_STATUS_ALREADY_IN_GROUP:"AlreadyInGroup",JOIN_STATUS_WAIT_APPROVAL:"WaitAdminApproval"}),{INVITE_OPTIONS_DISABLE_INVITE:"DisableInvite",INVITE_OPTIONS_NEED_PERMISSION:"NeedPermission",INVITE_OPTIONS_FREE_ACCESS:"FreeAccess"}),{GRP_PROFILE_OWNER_ID:"ownerID",GRP_PROFILE_CREATE_TIME:"createTime",GRP_PROFILE_LAST_INFO_TIME:"lastInfoTime",GRP_PROFILE_MEMBER_NUM:"memberNum",GRP_PROFILE_MAX_MEMBER_NUM:"maxMemberNum",GRP_PROFILE_JOIN_OPTION:"joinOption",GRP_PROFILE_INVITE_OPTION:"inviteOption",GRP_PROFILE_INTRODUCTION:"introduction",GRP_PROFILE_NOTIFICATION:"notification",GRP_PROFILE_MUTE_ALL_MBRS:"muteAllMembers"}),{GROUP_ID_PREFIX:sa,GROUP_TIPS_OPERATION_TYPE:Tg}),hs={IOS_OFFLINE_PUSH_NO_SOUND:"push.no_sound",IOS_OFFLINE_PUSH_DEFAULT_SOUND:"default"},Lo=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},zg),ag),_g),Dc),ME),gI),hs),{NET_STATE_CONNECTING:"connecting",NET_STATE_DISCONNECTED:"disconnected",NET_STATE_CONNECTED:"connected"}),da={NO_SDKAPPID:2e3,NO_TINYID:2022,NO_A2KEY:2023,USER_NOT_LOGGED_IN:2024,REPEAT_LOGIN:2025,MSG_SEND_FAIL:2100,MSG_SEND_FAIL_NOT_IN_AV:2101,MSG_SEND_GRP_WITH_TOPIC_FAIL:2115,MSG_INSTANCE_REQUIRED:2105,MSG_INVALID_CONV_TYPE:2106,MSG_REVOKE_FAIL:2110,MSG_DELETE_FAIL:2111,MSG_UNREAD_ALL_FAIL:2112,READ_RECEIPT_MSG_LIST_EMPTY:2114,CANNOT_DELETE_GRP_SYSTEM_NOTICE:2116,NOT_MY_FRIEND:2700,NETWORK_ERROR:2800,NETWORK_TIMEOUT:2801,NO_NETWORK:2805,UNCAUGHT_ERROR:2903,INVALID_OPERATION:2905,SDK_IS_NOT_READY:2999,LOGGING_IN:3e3,LOGIN_FAILED:3001,KICKED_OUT_MULT_DEVICE:3002,KICKED_OUT_MULT_ACCOUNT:3003,KICKED_OUT_USERSIG_EXPIRED:3004,LOGGED_OUT:3005,KICKED_OUT_REST_API:3006,NO_USE:3122,OPTIONS_IS_EMPTY:3153,MSG_A2KEY_EXPIRED:20002,ACCOUNT_A2KEY_EXPIRED:70001,HELLO_ANSWER_KICKED_OUT:1002,OPEN_SERVICE_OVERLOAD_ERROR:60022},nr={BASIC:"1",STANDARD:"2",PROFESSIONAL:"3",NODE:"4"},Vt={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"},Kt={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={[Vt.SYNC_SERVER_INFO_AFTER_RE_ONLINE]:[{stepId:Kt.USER_STATUS_UPDATE},{stepId:Kt.GROUP_ATTRIBUTE_CACHE_CLEAR},{stepId:Kt.UNREAD_MESSAGE_SYNC,dependency:Kt.C2C_HISTORY_MESSAGE_RECOVER},{stepId:Kt.CONVERSATION_RECOVER},{stepId:Kt.HISTORY_MESSAGE_RECOVER,dependency:Kt.CONVERSATION_RECOVER},{stepId:Kt.BLACKLIST_RECOVER},{stepId:Kt.FRIEND_RECOVER},{stepId:Kt.FRIEND_APPLICATION_LIST_RECOVER},{stepId:Kt.GROUP_REVOKED_NOTICE_RECOVER,dependency:Kt.HISTORY_MESSAGE_RECOVER},{stepId:Kt.GROUP_TIPS_RECOVER,dependency:Kt.HISTORY_MESSAGE_RECOVER},{stepId:Kt.TOPIC_REQUEST_INFO_RESET},{stepId:Kt.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,dependency:Kt.UNREAD_MESSAGE_SYNC},{stepId:Kt.HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD,dependency:Kt.UNREAD_MESSAGE_SYNC},{stepId:Kt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Kt.UNREAD_MESSAGE_SYNC,Kt.CONVERSATION_RECOVER]},{stepId:Kt.EMIT_C2C_MESSAGE_EVENT,dependency:[Kt.UNREAD_MESSAGE_SYNC,Kt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED],skipIfDependencyMissing:!1},{stepId:Kt.C2C_HISTORY_MESSAGE_RECOVER,dependency:Kt.CONVERSATION_RECOVER},{stepId:Kt.STREAM_MESSAGE_RECOVER}],[Vt.SYNC_SERVER_INFO_AFTER_LOGIN]:[{stepId:Kt.COMMERCIAL_CONFIG_UPDATE},{stepId:Kt.CLOUD_CONFIG_SYNC},{stepId:Kt.USER_PROFILE_SYNC},{stepId:Kt.UNREAD_MESSAGE_SYNC},{stepId:Kt.FRIEND_AND_BLACKLIST_SYNC},{stepId:Kt.GROUP_LIST_SYNC},{stepId:Kt.CONVERSATION_LIST_SYNC},{stepId:Kt.SIGNALING_MESSAGE_RECOVER,dependency:Kt.UNREAD_MESSAGE_SYNC},{stepId:Kt.UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED,dependency:[Kt.UNREAD_MESSAGE_SYNC]},{stepId:Kt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Kt.UNREAD_MESSAGE_SYNC,Kt.CONVERSATION_LIST_SYNC]},{stepId:Kt.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,dependency:[Kt.GROUP_LIST_SYNC,Kt.CONVERSATION_LIST_SYNC]},{stepId:Kt.CONVERSATION_GROUP_LIST_SYNC},{stepId:Kt.CONVERSATION_GROUP_UPDATE,dependency:[Kt.CONVERSATION_LIST_SYNC,Kt.CONVERSATION_GROUP_LIST_SYNC]},{stepId:Kt.QUALITY_REPORT}],[Vt.RECEIVE_C2C_NEW_MESSAGE]:[{stepId:Kt.HANDLE_C2C_NEW_MESSAGE},{stepId:Kt.UNREAD_MESSAGE_SYNC},{stepId:Kt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Kt.HANDLE_C2C_NEW_MESSAGE},{stepId:Kt.EMIT_C2C_MESSAGE_EVENT,dependency:[Kt.HANDLE_C2C_NEW_MESSAGE,Kt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1},{stepId:Kt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Kt.UNREAD_MESSAGE_SYNC]}],[Vt.RECEIVE_GROUP_NEW_MESSAGE]:[{stepId:Kt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Kt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Kt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Kt.UPDATE_GROUP_NEXT_SEQUENCE,dependency:Kt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Kt.UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE,dependency:Kt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Kt.EMIT_GROUP_MESSAGE_EVENT,dependency:[Kt.HANDLE_GROUP_NEW_MESSAGE,Kt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1}],[Vt.RECEIVE_GROUP_TIPS_NOTIFICATION]:[{stepId:Kt.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:Kt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Kt.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:Kt.EMIT_GROUP_TIPS_EVENT,dependency:[Kt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,Kt.HANDLE_GROUP_TIPS_NOTIFICATION],skipIfDependencyMissing:!1}]},cI={MESSAGE_SEND_SUCCESS_RATE:"messageSendSuccessRate"},rr={TOTAL_COUNT:"sendMessageTotalCount",SUCCESS_COUNT:"sendMessageSuccessCount",FAILED_COUNT:"sendMessageFailedCount",SEND_COST:"sendMessageCost"},qI=["login","getMyProfile","getUserProfile","updateMyProfile","setSelfStatus","getUserStatus","subscribeUserStatus","unsubscribeUserStatus","modifyMessage","deleteGroupMember","dismissGroup","getGroupMemberList","getGroupOnlineMemberCount","joinGroup","markGroupMemberList","quitGroup","searchCloudMessages","searchCloudGroups","searchCloudGroupMembers","searchCloudUsers","getMyFollowingList","getMyFollowersList","getMutualFollowersList","followUser","unfollowUser","getUserFollowInfo","checkFollowType","getFriendProfile","addFriend","deleteFriend","updateFriend","checkFriend","setFriendApplicationRead","createFriendGroup","deleteFriendGroup","addToFriendGroup","removeFromFriendGroup","renameFriendGroup","changeGroupOwner","createGroup","dismissGroup","getGroupList","getGroupOnlineMemberCount","getGroupProfile","searchGroupByID","updateGroupProfile","handleGroupApplication","deleteGroupAttributes","getGroupAttributes","initGroupAttributes","setGroupAttributes","addGroupMember","deleteGroupMember","getGroupMemberList","getGroupMemberProfile","setGroupMemberMuteTime","setGroupMemberNameCard","setGroupMemberRole","deleteMessage","revokeMessage","setMessageExtensions","getMessageExtensions","deleteMessageExtensions","getMessageList","addMessageReaction","removeMessageReaction","clearHistoryMessage","sendMessageReadReceipt","getMessageReadReceiptList","getGroupMessageReadMemberList","createMergerMessage","invite","accept","cancel","reject","modifyInvitation","deleteConversation","pinConversation","setMessageRead","setAllMessageRead","getConversationList","getTotalUnreadMessageCount","renameConversationGroup","deleteConversationGroup","markConversation","setConversationCustomData","deleteConversationsFromGroup","addConversationsToGroup","createConversationGroup"];var za=Object.freeze({__proto__:null,ERROR_CODE:da,InnerEvent:no,NEED_LOG_API:qI,OuterConstant:Lo,OuterEvent:Dr,PUSH:hs,QUALITY_METRICS:cI,SDK_EDITION:nr,SDK_INFO:{VERSION:"1.7.3",APPID:537048168},SEND_MESSAGE_STAT:rr,SignalingEvent:qc,WEB_PUSH_ACCOUNT_TYPE:1,WORKFLOW_DEFINITIONS:Ng,WORKFLOW_NAME:Vt,WORKFLOW_STEP:Kt}),na,un,Sn;(function(s){s[s.USER_INITIATED=0]="USER_INITIATED",s[s.KICKED_OUT=1]="KICKED_OUT"})(na||(na={})),function(s){s[s.multipleAccount=1]="multipleAccount",s[s.multipleDevice=2]="multipleDevice",s[s.restApi=3]="restApi"}(un||(un={})),function(s){s[s.multipleDevice=3002]="multipleDevice",s[s.multipleAccount=3003]="multipleAccount",s[s.usersigExpired=70001]="usersigExpired",s[s.restApi=20002]="restApi"}(Sn||(Sn={}));const Tu={[un.multipleAccount]:"multipleAccount",[un.multipleDevice]:"multipleDevice",[un.restApi]:"REST_API_Kick",[Sn.multipleAccount]:"multipleAccount",[Sn.multipleDevice]:"multipleDevice",[Sn.restApi]:"REST_API_Kick",[Sn.usersigExpired]:"userSigExpired"},Gg="login_online_presence_task",{ERROR:Ua,DESTROY:jc,FORCE_OFFLINE:KI}=no,{KICKED_OUT_MULT_ACCOUNT:vE,KICKED_OUT_MULT_DEVICE:lI,KICKED_OUT_REST_API:Nu,ACCOUNT_A2KEY_EXPIRED:Rl,MSG_A2KEY_EXPIRED:Sc}=da;class Gu{init(){const{notificationCenter:n}=fe;n.subscribeInnerEvent(KI,this._handleForceOfflineFromServerPush,this),n.subscribeInnerEvent(Ua,Sc,this._handleForceOfflineFromResponse,this,this._isChatLoginEvent),n.subscribeInnerEvent(Ua,Rl,this._handleForceOfflineFromResponse,this,this._isChatLoginEvent),n.subscribeInnerEvent(Ua,vE,this._handleForceOfflineFromResponse,this),n.subscribeInnerEvent(Ua,lI,this._handleForceOfflineFromResponse,this),n.subscribeInnerEvent(Ua,Nu,this._handleForceOfflineFromResponse,this),n.subscribeInnerEvent(jc,this._dispose,this)}_handleForceOfflineFromServerPush(n){var g;if(((g=fe.store.get("login"))===null||g===void 0?void 0:g.isLoggedIn)===!0){const{EventArray:u=[]}=n?.body||{};this._extractKickedOutMessages(u).forEach(E=>{const{KickoutMsgNotify:{KickType:m,NewInstInfo:D,Instid:M}}=E;this._isCurrentInstanceKickedOut(M)&&this._processKickedOutReasonInfo({kickedOutReasonCode:m,newInstanceInfo:D})})}}_extractKickedOutMessages(n){return n.reduce((g,u)=>[...g,...u.C2cNotifyMsgArray||[]],[]).filter(g=>{var u;return this._isKickedOut((u=g?.KickoutMsgNotify)===null||u===void 0?void 0:u.KickType)})}_handleForceOfflineFromResponse(n){const{errorCode:g}=n;this._processKickedOutReasonInfo({kickedOutReasonCode:g})}_processKickedOutReasonInfo(n){return pA(this,void 0,void 0,function*(){const{kickedOutReasonCode:g}=n,{ssoLog:u,utils:{safeStringify:E}}=fe;try{this._logKickedOutEvent(n),this._shouldLogoutAfterKickedOut(g)?yield fe.login.loginAction.logout(na.KICKED_OUT):fe.login.loginAction.handleLogoutCompleted()}catch(m){u.debug("_processKickedOutReasonInfo",` fail ${E(m)}`)}finally{fe.notificationCenter.emitOuterEvent(Dr.KICKED_OUT,{data:{type:Tu[g]},name:Dr.KICKED_OUT})}})}_logKickedOutEvent(n){const{kickedOutReasonCode:g,newInstanceInfo:u={}}=n,E=`type:${Tu[g]} newInstanceInfo: ${JSON.stringify(u)}`;fe.ssoLog.warn("kickedOut",E)}_isKickedOut(n){return[un.multipleAccount,un.multipleDevice,un.restApi].includes(n)}_isChatLoginEvent(n){const{requestHead:g}=n||{};return g?.idtype!==1}_shouldLogoutAfterKickedOut(n){return![Sn.usersigExpired,un.restApi].includes(n)}_isCurrentInstanceKickedOut(n){const{isLoggedIn:g,statusInstanceId:u}=fe.store.get("login")||{};return g===!0&&n===u}_dispose(){const{notificationCenter:n}=fe;n.unSubscribeInnerEvent(KI,this._handleForceOfflineFromServerPush,this),n.unSubscribeInnerEvent(Ua,Rl,this._handleForceOfflineFromResponse,this),n.unSubscribeInnerEvent(Ua,Sc,this._handleForceOfflineFromResponse,this),n.unSubscribeInnerEvent(Ua,vE,this._handleForceOfflineFromResponse,this),n.unSubscribeInnerEvent(Ua,lI,this._handleForceOfflineFromResponse,this),n.unSubscribeInnerEvent(Ua,Nu,this._handleForceOfflineFromResponse,this),n.unSubscribeInnerEvent(jc,this._dispose,this)}}function bu(s){return pA(this,void 0,void 0,function*(){const n="im_open_status.wslogin",g=fe.common.generateProtocolData({servcmd:n,data:{State:"Online",is_web_uniapp:0,InstType:0,CustomInfo:s}}),u=`${g.head.seq}${n}`,E=yield fe.channel.sendPacket(g,{timeout:9e4,requestId:u});if(E){const{HelloInterval:m,InstId:D,TinyId:M,TimeStamp:T,CustomStatus:P,PurchaseBits:W,A2Key:iA,RichMsgAuthKey:EA,ErrorCode:RA,ErrorInfo:kA,ActionStatus:xA}=E;return{helloInterval:m,instanceID:D,tinyID:M,timeStamp:T,customStatus:P,purchaseBits:W,a2Key:iA,authKey:EA,errorCode:RA,errorInfo:kA,actionStatus:xA}}})}function wl(){const{store:s}=fe;return ua(s.get("instance").sdkAppId)!==ut.CHINA}function rs(s){var n;try{const g=$i.getStorage("errorMessage");if(!s||!g)return"";const u=((n=JSON.parse(g))===null||n===void 0?void 0:n.errorMessage)||{},{code:E,replacement1:m="",replacement2:D=""}=s;if(!E)return"";const M=wl()?`${E}_en`:`${E}_cn`;let T=u[u[M]?M:E]||"";return T&&(m&&(T=T.replace("$replacement1",m)),D&&(T=T.replace("$replacement2",D))),T}catch(g){return console.warn("Error parsing stored error messages:",g),""}}class gs extends Error{constructor(n={}){n.code=n.code||n.errorCode;let{functionName:g="Unknown",code:u,message:E="",data:m="",moreMessage:D="",errorMessage:M=""}=n;M=(u?rs(n):"")||M||E;let T=u?`${g} failed. error: {"message": ${M}, "code": ${u}}`:`${g} failed. error: {"message": ${M}}`;T=`${T} ${D}`,super(),this.code=u,this.errorCode=u,this.errorMessage=M,this.message=T,this.data=m}}function ud(s,n){var g;if(s&&((g=fe.store.get("login"))===null||g===void 0?void 0:g.isLoggedIn)!==!0)throw new gs({code:da.USER_NOT_LOGGED_IN,functionName:n})}function II(s,n,g){if(Array.isArray(s))for(let u=0;u{return P===(W=u,Object.prototype.toString.call(W).match(/^\[object (.*)\]$/)[1].toLowerCase());var W})){for(let W=0;W{const{interceptor:E,context:m}=u;E.apply(m,[g])})}(s)}function Mc(s,n){RE.push({interceptor:s,context:n})}function Wc(s){const{params:n,auth:g}=s;n&&typeof n=="object"&&Object.assign(_l,n),g&&typeof g=="object"&&Object.assign(Ed,g)}function tn(s){return fe.store.get("commercialConfig").get(s)}class ws{constructor(){this._handlers=new Map,this._activeWorkflows=new Map,this._stepStartTimes=new Map,this._logHandlers={start:(n,g)=>{const u=Date.now();g?(this._stepStartTimes.set(`${n}-${g}`,u),fe.ssoLog.debug("_executeWorkflowStep",`[Workflow ${n}] Step ${g} started at ${new Date(u).toISOString()}`)):(this._workflowStartTimes.set(n,u),fe.ssoLog.debug("_executeWorkflowStep",`[Workflow ${n}] started at ${new Date(u).toISOString()}`))},success:(n,g)=>{const u=Date.now();if(g){const E=this._stepStartTimes.get(`${n}-${g}`),m=E?u-E:0;this._stepStartTimes.delete(`${n}-${g}`),fe.ssoLog.debug("_executeWorkflowStep",`[Workflow ${n}] Step ${g} completed successfully at ${new Date(u).toISOString()} (${m}ms)`)}else{const E=this._workflowStartTimes.get(n),m=E?u-E:0;this._workflowStartTimes.delete(n),fe.ssoLog.debug("_executeWorkflowStep",`[Workflow ${n}] completed successfully at ${new Date(u).toISOString()} (${m}ms)`)}},error:(n,g,u)=>{const{ssoLog:E,utils:{safeStringify:m}}=fe,D=Date.now();if(g){const M=this._stepStartTimes.get(`${n}-${g}`),T=M?D-M:0;this._stepStartTimes.delete(`${n}-${g}`),E.error("_executeWorkflowStep",`[Workflow ${n}] Step ${g} failed at ${new Date(D).toISOString()} (${T}ms) ${m(u)}`,{error:u})}else{const M=this._workflowStartTimes.get(n),T=M?D-M:0;this._workflowStartTimes.delete(n),E.error("_executeWorkflowStep",`[Workflow ${n}] failed at ${new Date(D).toISOString()} (${T}ms) ${m(u)}`,{error:u})}}}}static getInstance(){return ws._instance||(ws._instance=new ws),ws._instance}static setInstance(n){ws._instance=n}init(){this._initializeWorkflows()}registerWorkflowStep(n,g,u,E){if(!this._handlers.has(n))return void fe.ssoLog.debug("registerWorkflowStep",`Workflow '${n}' not defined in core`);if(!Ng[n].find(D=>D.stepId===g))return void fe.ssoLog.debug("registerWorkflowStep",`Step '${g}' not defined in workflow '${n}'`);const m=this._handlers.get(n);m.has(g)||m.set(g,E?u.bind(E):u)}executeWorkflow(n,g){return pA(this,void 0,void 0,function*(){if(!this._validateWorkflow(n))return;fe.ssoLog.debug("executeWorkflow",`[Workflow ${n}] Started execution at ${new Date().toISOString()}`);const u=Ng[n],E={},m={cancelled:!1};this._activeWorkflows.set(n,{cancelToken:m});try{const D=new Map;u.forEach(T=>{D.set(T.stepId,T)});const M={workflowName:n,pendingSteps:new Set(u.map(T=>T.stepId)),completedSteps:new Set,runningSteps:new Set,stepMap:D,stepResults:E,data:g,cancelToken:m};yield new Promise((T,P)=>{const W=()=>{if(m.cancelled)return void T();this._getExecutableSteps({pendingSteps:M.pendingSteps,completedSteps:M.completedSteps,stepMap:M.stepMap,workflowName:n}).filter(iA=>!M.runningSteps.has(iA)).forEach(iA=>{M.completedSteps.has(iA)||M.runningSteps.has(iA)||this._executeWorkflowStep(iA,M,{onComplete:()=>{if(M.pendingSteps.size===0)return void T();this._getExecutableSteps({pendingSteps:M.pendingSteps,completedSteps:M.completedSteps,stepMap:M.stepMap,workflowName:n}).filter(EA=>!M.runningSteps.has(EA)).length===0&&M.runningSteps.size===0&&(fe.ssoLog.debug("executeWorkflow",`Workflow ${n} completed with some steps skipped due to dependency failures`),T())},onError:P,onStepComplete:W})})};W()}),fe.ssoLog.debug("executeWorkflow",`[Workflow ${n}] Completed execution at ${new Date().toISOString()}`)}catch(D){fe.ssoLog.error("executeWorkflow",`[Workflow ${n}] Failed execution at ${new Date().toISOString()}`,{error:D})}finally{this._activeWorkflows.delete(n)}})}_executeWorkflowStep(n,g,u){return pA(this,void 0,void 0,function*(){const{workflowName:E,runningSteps:m,stepMap:D,stepResults:M,data:T}=g;m.add(n),this._logWorkflowExecution(E,n,"start");try{const P=D.get(n);let W=null;P?.dependency&&(l(P.dependency)?W=M[P.dependency]:Array.isArray(P.dependency)&&(W={},P.dependency.forEach(EA=>{W[EA]=M[EA]})));const iA=this._handlers.get(E).get(n);if(iA){const EA=yield Promise.resolve(iA({data:T,result:W}));M[n]=EA,this._logWorkflowExecution(E,n,"success")}g.completedSteps.add(n)}catch(P){const W=`[Workflow].${E}.${n}`,{errorCode:iA,errorInfo:EA=`${W} failed`}=P||{},RA=new gs({functionName:W,code:iA,message:EA});fe.ssoLog.error(W,EA,{error:RA}),this._logWorkflowExecution(E,n,"error",P),u.onError(P)}finally{m.delete(n),g.pendingSteps.delete(n),u.onStepComplete(),u.onComplete()}})}reset(){this._cancelAllWorkflows()}destroy(){this.reset(),this._handlers.clear()}_initializeWorkflows(){Object.keys(Ng).forEach(n=>{this._handlers.has(n)||this._handlers.set(n,new Map)})}_cancelWorkFlow(n){const g=this._activeWorkflows.get(n);if(!g)return;const{cancelToken:u}=g;u.cancelled=!0,this._activeWorkflows.delete(n)}_cancelAllWorkflows(){Object.keys(Ng).forEach(n=>{this._cancelWorkFlow(n)})}_validateWorkflow(n){return Ng[n]?!!this._handlers.get(n):!1}_getExecutableSteps(n){const{pendingSteps:g,completedSteps:u,stepMap:E,workflowName:m}=n;return Array.from(g).filter(D=>{const M=E.get(D)||{},{dependency:T,skipIfDependencyMissing:P=!0}=M;if(!T)return!0;if(l(T))return this._isStepRegistered({workflowName:m,stepId:T})?u.has(T):!P;if(h(T)){if(T.filter(W=>!this._isStepRegistered({workflowName:m,stepId:W})).length>0&&P)return!1;for(const W of T)if(!u.has(W))return!1;return!0}return!1})}_isStepRegistered(n){var g;const{workflowName:u,stepId:E}=n;return(g=this._handlers.get(u))===null||g===void 0?void 0:g.has(E)}_logWorkflowExecution(n,g,u,E){this._logHandlers[u](n,g)}}const Ca=new Map,Xr=({type:s,groupID:n})=>s===Lo.GRP_COMMUNITY||`${n}`.startsWith(sa.COMMUNITY)&&!`${n}`.includes(sa.TOPIC),zc=(s="")=>{const n=s.startsWith("GROUP")?s.replace("GROUP",""):s;return n.startsWith(sa.COMMUNITY)&&`${n}`.includes(sa.TOPIC)},dd="openim",Zg="million_group_open_http_svc";function gg(s){return pA(this,void 0,void 0,function*(){const{servcmd:n,data:g}=function(m){const{data:D}=m;return wE(D)||Xg(D)}(s)?function(m){let{servcmd:D,data:M}=m;return Xg(M)?function(T){const{servcmd:P,data:W}=T;let{GroupId:iA=""}=W;const EA=iA;return[iA]=EA.split(sa.TOPIC),{servcmd:qn(P),data:Object.assign(Object.assign({},W),{GroupId:iA,TopicId:EA})}}(m):(wE(M)&&(D=qn(D)),{servcmd:D,data:M})}(s):s,u=fe.common.generateProtocolData({servcmd:n,data:g}),E=`${u.head.seq}${n}`;return fe.channel.sendPacket(u,{requestId:E,timeout:s.timeout})})}function wE(s){const{Type:n,GroupId:g,GroupIdList:u=[]}=s,E=g||u[0]||"";return Xr({type:n,groupID:E})}function Xg(s){const{GroupId:n=""}=s;return zc(n)}function qn(s){if(s.includes(dd))return s;const n=s.split(".")[1];return`${Zg}.${n}`}function Ar(){var s;return(s=fe.store.get("login"))===null||s===void 0?void 0:s.userId}const Fa=s=>h(s)||f(s),Cd=(s,n,g,u)=>{if(!Fa(s)||!Fa(n))return 0;let E=0;const m=Object.keys(n);let D;for(let M=0,T=m.length;M{if(r(n))return"";if(s===Lo.MSG_TEXT)return n.text||"";const g=jI[s];return g?ku(g):""},Xc=[{cmd:"ws_get_user_status",interval:5,count:20},{cmd:"ws_status_subscribe",interval:5,count:20},{cmd:"ws_status_unsubscribe",interval:5,count:20},{cmd:"get_group_self_member_info",interval:5,count:20},{cmd:"modify_group_base_info",interval:1,count:8},{cmd:"get_pendency",interval:1,count:15},{cmd:"set_group_attr",interval:5,count:10},{cmd:"modify_group_attr",interval:5,count:10},{cmd:"delete_group_attr",interval:5,count:10},{cmd:"clear_group_attr",interval:5,count:10},{cmd:"get_group_attr",interval:5,count:20},{cmd:"update_group_counter",interval:5,count:20},{cmd:"get_group_counter",interval:5,count:20},{cmd:"get_topic",interval:1,count:10},{cmd:"read_all_unread_msg",interval:1,count:1},{cmd:"query",interval:5,count:20}],WI="im_sdk_config_mgr.fetch_config",EI="im_sdk_config_mgr.push_configv2",$c="cloud-config",Al=2996,va=new class{init(s){this.core=s}};function bg(s){return pA(this,void 0,void 0,function*(){const{sdkAppId:n}=va.core.store.get("instance")||{},g=va.core.helper.generateProtocolData({servcmd:WI,data:{uint32_sdkappid:n,uint64_version:s}}),u=`${g.head.seq}${WI}`;return va.core.channel.sendPacket(g,{requestId:u})})}var ys=new class{constructor(){this._core=null,this._expirationTime=0,this._version=0,this._isFetching=!1,this._cmdFrequencyLimitMap=new Map,this._methodCallFrequencyMap=new Map}install(s){this._core=s;const{notificationCenter:n,InnerEvent:g,helper:u,constants:{WORKFLOW_NAME:E,WORKFLOW_STEP:m},channel:D}=s;n.subscribeInnerEvent(EI,this._handlePushedConfig,this),u.registerWorkflowStep(E.SYNC_SERVER_INFO_AFTER_LOGIN,m.CLOUD_CONFIG_SYNC,this._handleLoginSuccess,this),n.subscribeInnerEvent(g.LOGOUT,this._reset,this),n.subscribeInnerEvent(g.DESTROY,this._dispose,this),u.registerExperimentalAPI("getServerConfig",this),this._updateCmdFreqLimitMap(Xc),D.registerBeforeSendInterceptor(this.checkMethodCallOverLimit,this)}getServerConfig(s){return pA(this,void 0,void 0,function*(){var n;const g={code:0,data:""};return s&&(g.data=((n=this._core.store.get("cloudConfig"))===null||n===void 0?void 0:n[s])||""),g})}checkMethodCallOverLimit(s){if(!this._cmdFrequencyLimitMap.has(s))return;if(!this._methodCallFrequencyMap.has(s))return void this._methodCallFrequencyMap.set(s,{startTime:Date.now(),methodCallCounter:1});const{count:n,interval:g}=this._cmdFrequencyLimitMap.get(s);let{startTime:u,methodCallCounter:E}=this._methodCallFrequencyMap.get(s);if(Date.now()-u>1e3*g)this._methodCallFrequencyMap.set(s,{startTime:Date.now(),methodCallCounter:1});else if(E+=1,this._methodCallFrequencyMap.set(s,{startTime:u,methodCallCounter:E}),E>n)throw new this._core.helper.ChatError({code:Al,replacement1:s})}_handlePushedConfig(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g}}=this._core;n.info("_handlePushedConfig",g(s)),yield this._updateCloudConfig(s)})}_handleLoginSuccess(){return pA(this,void 0,void 0,function*(){const{ssoLog:s,utils:{safeStringify:n}}=this._core;try{if(this._canFetch()){const g=yield bg(this._version);s.info("_fetchCloudConfigIfLogin",n(g)),yield this._updateCloudConfig(g)}this._core.helper.taskScheduler.addTask({id:$c,intervalMs:1e3,callback:this._fetchCloudConfigIfReady,context:this})}catch(g){s.debug("_fetchCloudConfigIfLogin",n(g))}})}_fetchCloudConfigIfReady(){return pA(this,void 0,void 0,function*(){const{ssoLog:s,utils:{safeStringify:n}}=this._core;if(this._canFetch())try{const g=yield bg(this._version);s.info("_fetchCloudConfigIfReady",n(g)),yield this._updateCloudConfig(g)}catch(g){s.error("_fetchCloudConfigIfReady",n(g))}})}_updateCloudConfig(s){return pA(this,void 0,void 0,function*(){const n=this._parseCloudConfig(s);n&&(this._core.store.set("cloudConfig",n),yield this._parseCmdFreqLimit(),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.CLOUD_CONFIG_UPDATE,n),this._core.notificationCenter.emitOuterEvent(this._core.OuterEvent.SERVER_CONFIG_UPDATED,{name:this._core.OuterEvent.SERVER_CONFIG_UPDATED,data:{config:n}}))})}_canFetch(){const{isLoggedIn:s}=this._core.store.get("login")||{};return s&&!this._isFetching&&Date.now()>=this._expirationTime}_parseCloudConfig(s){const{int32_error_code:n,str_error_message:g,str_json_config:u,uint32_expired_time:E,uint32_sdkappid:m,uint64_version:D}=s;let M=null;if(n===0){if(this._version!==D)try{M=JSON.parse(u),this._version=D}catch{}this._expirationTime=Date.now()+1e3*E}else this._expirationTime=n===void 0?Date.now()+36e5:Date.now()+12e4;return M}_parseCmdFreqLimit(){return pA(this,void 0,void 0,function*(){var s;let n=(s=yield this.getServerConfig("cmd_frequency_limit"))===null||s===void 0?void 0:s.data;const{isEmpty:g}=this._core.utils;if(!g(n))try{n=JSON.parse(n),this._updateCmdFreqLimitMap(n)}catch(u){console.warn(u)}})}_updateCmdFreqLimitMap(s){s.forEach(n=>{this._cmdFrequencyLimitMap.set(n.cmd,{interval:n.interval,count:n.count})})}_reset(){this._core.helper.taskScheduler.removeTask($c),this._core.store.clear("cloudConfig"),this._updateCmdFreqLimitMap(Xc),this._methodCallFrequencyMap.clear(),this._expirationTime=0,this._version=0,this._isFetching=!1}_dispose(){const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(EI,this._handlePushedConfig,this),s.unSubscribeInnerEvent(n.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this),this._reset()}};class Kn{constructor(n=0,g=0){this.high=n,this.low=g}equal(n){return n!==null&&this.low===n.low&&this.high===n.high}toString(){const n=Number(this.high).toString(16);let g=Number(this.low).toString(16);if(g.length<8){let u=8-g.length;for(;u;)g=`0${g}`,u--}return n+g}}const vc={SEARCH_GRP_SNS:new Kn(0,Math.pow(2,1)).toString(),AV_HISTORY_MSG:new Kn(0,Math.pow(2,2)).toString(),GRP_COMMUNITY:new Kn(0,Math.pow(2,3)).toString(),MSG_TO_SPECIFIED_GRP_MBR:new Kn(0,Math.pow(2,4)).toString(),AV_MBR_LIST:new Kn(0,Math.pow(2,6)).toString(),USER_STATUS:new Kn(0,Math.pow(2,7)).toString(),CONV_MARK:new Kn(0,Math.pow(2,9)).toString(),CONV_GROUP:new Kn(0,Math.pow(2,10)).toString(),AV_BAN_MBR:new Kn(0,Math.pow(2,11)).toString(),MSG_EXT:new Kn(0,Math.pow(2,13)).toString(),GRP_COUNTER:new Kn(0,Math.pow(2,15)).toString(),PLUGIN_TRANSLATE:new Kn(Math.pow(2,6)).toString(),PLUGIN_VOICE_TO_TEXT:new Kn(Math.pow(2,7)).toString(),PLUGIN_CS:new Kn(Math.pow(2,8)).toString(),PLUGIN_PUSH:new Kn(Math.pow(2,9)).toString(),PLUGIN_BOT:new Kn(Math.pow(2,10)).toString(),MSG_REACTION:new Kn(Math.pow(2,16)).toString(),FOLLOW:new Kn(Math.pow(2,20)).toString()},zI="CommercialConfig",ZI="commercial-config";var _E=new class{constructor(){this._core=null,this._expirationTime=0,this._isFetching=!1,this._featureMap=new Map,this._methodKeyMap=new Map,this._purchaseBits="0"}install(s){this._core=s;const{helper:n,notificationCenter:g,constants:{WORKFLOW_NAME:u,WORKFLOW_STEP:E,InnerEvent:m}}=s;g.subscribeInnerEvent(m.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),g.subscribeInnerEvent(m.LOGOUT,this._handleLogout,this),g.subscribeInnerEvent(m.DESTROY,this._dispose,this),n.registerWorkflowStep(u.SYNC_SERVER_INFO_AFTER_LOGIN,E.COMMERCIAL_CONFIG_UPDATE,this._syncCommercialConfig,this),s.helper.registerExperimentalAPI("isCommercialAbilityEnabled",this),s.helper.registerExperimentalAPI("queryCommercialAbility",this)}isCommercialAbilityEnabled(s){return pA(this,void 0,void 0,function*(){const n=parseInt(s,10).toString(2),{length:g}=n;let u,E=!0;for(let m=g-1,D=0;m>=0;m--,D++)if(n.charAt(m)==="1"&&(u=D<32?new Kn(0,2**D).toString():new Kn(2**(D-32),0).toString(),!this._featureMap.get(u))){E=!1;break}return this._core.ssoLog.debug("isFeatureEnabled",`${zI}.isFeatureEnabled decimalNumber:${s} key:${u} ret:${E}`),{code:0,data:{enabled:E}}})}queryCommercialAbility(){return this._purchaseBits}_fetchAndParseCommercialConfig(){return pA(this,void 0,void 0,function*(){var s;const{ssoLog:n,utils:{safeStringify:g},common:{buildAndSendPacket:u}}=this._core;try{this._isFetching=!0;const E=yield u({servcmd:"im_sdk_config_mgr.fetch_imsdk_purchase_bitsv2",data:{uint32_sdkappid:(s=this._core.store.get("instance"))===null||s===void 0?void 0:s.sdkAppId}});E&&(this._parseCommercialConfig(E),this._core.store.set("commercialConfig",this._methodKeyMap))}catch(E){n.error("_fetchAndParseCommercialConfig",g(E))}finally{this._isFetching=!1}})}_syncCommercialConfig(s){return pA(this,void 0,void 0,function*(){const{purchaseBits:n}=s?.data||{};n&&(this._parsePurchaseBits(n),this._core.store.set("commercialConfig",this._methodKeyMap)),this._canFetch()&&(yield this._fetchAndParseCommercialConfig()),this._core.helper.taskScheduler.addTask({id:ZI,intervalMs:1e3,callback:this._fetchCommercialConfigIfReady,context:this})})}_canFetch(){var s;const n=(s=this._core.store.get("login"))===null||s===void 0?void 0:s.isLoggedIn,g=Date.now()>=this._expirationTime;return n&&!this._isFetching&&g}_handlePushedConfig(s){s?.body&&(this._parseCommercialConfig(s.body),this._core.store.set("commercialConfig",this._methodKeyMap))}_fetchCommercialConfigIfReady(){return pA(this,void 0,void 0,function*(){this._canFetch()&&(yield this._fetchAndParseCommercialConfig())})}_parseCommercialConfig(s){const{ssoLog:n}=this._core;if(typeof s!="object")return;const{int32_error_code:g,str_error_message:u,str_purchase_bits:E,uint32_expired_time:m}=s;g===0?(this._parsePurchaseBits(E),this._expirationTime=Date.now()+1e3*m):g===void 0?(n.warn("_parseCommercialConfig",`${zI}._parseCommercialConfig failed. Invalid message format:`,s),this._expirationTime=Date.now()+36e5):(n.warn("_parseCommercialConfig",`${zI}._parseCommercialConfig errorCode:${g} errorMessage:${u}`),this._expirationTime=Date.now()+12e4)}_isValidPurchaseBits(s){return s&&typeof s=="string"&&s.length>=1&&s.length<=64&&/[01]{1,64}/.test(s)}_parsePurchaseBits(s){const{ssoLog:n,utils:{safeStringify:g}}=this._core;if(this._isValidPurchaseBits(s)){this._purchaseBits=s,this._featureMap.clear(),this._methodKeyMap.clear();let u=null;for(let E=s.length-1,m=0;E>=0;E--,m++)if(u=m<32?new Kn(0,2**m).toString():new Kn(2**(m-32),0).toString(),s[E]==="1"){this._featureMap.set(u,!0);const D=this._getKeyByValue(vc,u);D&&this._methodKeyMap.set(D,!0)}else{this._featureMap.set(u,!1);const D=this._getKeyByValue(vc,u);D&&this._methodKeyMap.set(D,!1)}}else n.warn("_parsePurchaseBits",`${zI}.parsePurchaseBits invalid purchases:${g(s)}`)}_getKeyByValue(s,n){const g=Object.entries(s).find(([u,E])=>E===n);return g?g[0]:void 0}_handleLogout(){this._reset()}_dispose(){this._reset(),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._core.helper.taskScheduler.removeTask(ZI),this._core.store.set("commercialConfig",{}),this._expirationTime=0,this._isFetching=!1,this._featureMap.clear(),this._purchaseBits="0"}},rh=new class{constructor(){this._core=null,this._serverOverloadInfoMap=new Map}install(s){this._core=s;const{notificationCenter:n,InnerEvent:g,channel:u}=this._core;n.subscribeInnerEvent(g.OVERLOAD_PUSH,this._handleOverLoadPush,this),n.subscribeInnerEvent(g.LOGOUT,this._reset,this),n.subscribeInnerEvent(g.DESTROY,this._dispose,this),u.registerBeforeSendInterceptor(this.checkServerOverload,this)}checkServerOverload(s){if(!this._serverOverloadInfoMap.has(s))return;const{overloadStartTimestamp:n,delaySeconds:g}=this._serverOverloadInfoMap.get(s);if(Date.now()-n<=1e3*g)throw new this._core.helper.ChatError({functionName:s,message:"service is busy, please try again later"});this._serverOverloadInfoMap.delete(s)}_handleOverLoadPush(s){const{OverLoadServCmd:n,DelaySecs:g}=s;this._serverOverloadInfoMap.set(n,{overloadStartTimestamp:Date.now(),delaySeconds:g})}_reset(){this._serverOverloadInfoMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(n.OVERLOAD_PUSH,this._handleOverLoadPush,this),s.unSubscribeInnerEvent(n.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this)}},IC=new class{constructor(){this.name="ConfigCenter"}install(s){va.init(s),ys.install(s),_E.install(s),rh.install(s)}},ah=new class{constructor(){this.name="ErrorMessage",this._core=null}install(s){return pA(this,void 0,void 0,function*(){if(this._core=s,this._canFetch()){const n=yield this._fetchErrorMessage();if(!n)return;const g=this._parseResponse(n);this._saveErrorMessage(g)}})}_canFetch(){const s=this._core.store.getStorage("errorMessage");return!s||this._isExpired(s)}_saveErrorMessage(s){this._core.store.setStorage("errorMessage",{errorMessage:s,errorMessageSavedTime:new Date().getTime()})}_fetchErrorMessage(){return pA(this,void 0,void 0,function*(){try{return yield this._core.helper.httpRequest({method:"GET",url:"https://web.sdk.qcloud.com/im/download/error-message/v3/0.0.6/tim-error-message.txt"})}catch(s){console.error(s)}})}_isExpired(s){if(!s)return!0;const{errorMessageSavedTime:n}=s;return n&&new Date().getTime()-n>=6048e5}_parseResponse(s){if(typeof s=="string"){const n=s.split(`;
-`),g={},u=new RegExp(/'/g);for(let E=0;E{var JA,ae,se;const _i=function(Ti,Ft){const{From_Account:Ni,From_AccountHeadurl:cs,From_AccountNick:Se,IsNeedReadReceipt:mt,MsgBody:UA,MsgClientTime:ri,MsgRandom:_s,MsgSeq:Gi,MsgTimeStamp:Or,SendMsgControl:xi,SupportMessageExtension:gr,To_Account:Gt,TinyId:bt,MsgCheckResult:tE,CloudCustomData:ln,IsPeerRead:Bo,MsgFlagBits:Il,MsgVersion:_C,EventArray:Tr}=Ti;return{from:Ni,avatar:cs,nick:Se,needReadReceipt:mt===1,readReceiptSentByPeer:Bo,clientTime:ri,messageFlagBits:Il,random:_s,sequence:Gi,time:Or,messageControlInfo:xi,isSupportExtension:gr,to:Gt,tinyID:bt,checkResult:tE,cloudCustomData:ln,messageVersion:_C,eventArray:Tr,elements:Ft.message.messageHelper.parseServerPushMessageElement(UA)}}(OA,xA);if(!((se=(ae=(JA=OA?.EventArray)===null||JA===void 0?void 0:JA[0])===null||ae===void 0?void 0:ae.hasOwnProperty)===null||se===void 0)&&se.call(ae,"C2cNotifyMsgArray"))SA.push(...function(Ti){var Ft;const Ni=[];return(Ft=Ti.EventArray)===null||Ft===void 0||Ft.forEach(cs=>{var Se,mt;const{C2cNotifyMsgArray:UA}=cs,ri=(mt=(Se=UA?.[0])===null||Se===void 0?void 0:Se.WithdrawC2cMsgNotify)===null||mt===void 0?void 0:mt.C2cWithdrawInfoArray;Array.isArray(ri)&&Ni.push(...ri)}),Ni}(OA));else{const Ti=xA.message.messageFactory.createMessage(Object.assign(Object.assign({},_i),{conversationType:"C2C",flow:"in"})),{elements:Ft}=_i;Ti.setElement(Ft),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,ro;(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"}(ro||(ro={}));var uC=new class{constructor(){this.name="UnreadMessageSynchronizer",this._unreadDBMessageMap=new Map,this._cookie="",this._localConversationIDListBeforeDisconnect=[]}install(s){this._core=s;const{constants:n}=s;s.helper.registerWorkflowStep(n.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,n.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterReOnline,this),s.helper.registerWorkflowStep(n.WORKFLOW_NAME.RECEIVE_C2C_NEW_MESSAGE,n.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterNewMessageReceived,this),s.helper.registerWorkflowStep(n.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_LOGIN,n.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterLogin,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.SOCKET_DISCONNECTED,this._handleDisconnect,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.LOGOUT,this._reset,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this)}_syncUnreadMessage(s){return pA(this,void 0,void 0,function*(){const{isAfterReOnline:n=!1,isAfterNewMessageReceived:g=!1,isAfterLogin:u=!1}=s||{};let E=kg.START_SYNC;const m=[],D=[],M=[],T=[];for(;this._canContinueSync({cookie:this._cookie,syncFlag:E});){const P=yield this._fetchUnreadDBMessage({cookie:this._cookie,syncFlag:E,syncTriggerEvent:g?ro.NEW_MESSAGE_RECEIVED:ro.LOGIN_SUCCESS});if(!P)break;const{unreadMessageList:W=[],revokedMessageList:iA=[],overflowUnreadCountList:EA,unreadCountList:RA,groupTipList:kA}=P;if(this._cookie=P?.cookie||"",E=P?.syncFlag,this._parseAndSaveUnreadMessageList(W),M.push(...iA),this._updateConversationUnreadOptions({unreadCountList:RA,overflowUnreadCountList:EA,conversationUpdateFieldList:m}),Array.isArray(kA)&&D.push(...kA),n){const{messages:xA}=this._handleNewMessageList(W);T.push(...xA)}}return n?{conversationUpdateFieldList:m,revokedMessageList:M,unreadMessageMap:this._unreadDBMessageMap,groupTipList:D,messages:T,isUnreadC2CMessage:!0}:{conversationUpdateFieldList:m,isInstantMessage:!u,isUnreadC2CMessage:!0,revokedMessageList:M,unreadMessageMap:this._unreadDBMessageMap,groupTipList:D}})}_syncUnreadDBMessageAfterLogin(){return pA(this,void 0,void 0,function*(){return this._cookie="",this._syncUnreadMessage({isAfterLogin:!0})})}_syncUnreadDBMessageAfterNewMessageReceived(s){return pA(this,void 0,void 0,function*(){if(s.data.Flag===1)return this._syncUnreadMessage({isAfterNewMessageReceived:!0})})}_updateConversationUnreadOptions(s){const{unreadCountList:n,overflowUnreadCountList:g,conversationUpdateFieldList:u}=s,{constants:{OuterConstant:{CONV_C2C:E,CONV_SYSTEM:m}}}=this._core;n?.forEach(D=>{const{From_Account:M,UnreadCount:T}=D;if(M!==m){const P=u.find(({conversationID:W})=>W===`${E}${M}`);P?P.unreadCount=T:u.push({conversationID:`${E}${M}`,unreadCount:T,type:E})}}),g?.forEach(D=>{const{From_Account:M,LastMsgTime:T}=D;M!==m&&(u.find(({conversationID:P})=>P===`${E}${M}`)||u.push({conversationID:`${E}${M}`,type:E,lastMsgTime:T}))})}_syncUnreadDBMessageAfterReOnline(){return pA(this,void 0,void 0,function*(){return this._syncUnreadMessage({isAfterReOnline:!0})})}_updateMessageProfile(s){var n;const{messageDataHandler:g}=this._core.message||{},u=(n=this._core.store.get("login"))===null||n===void 0?void 0:n.userId,{from:E,nick:m,avatar:D,conversationID:M=""}=s;if(E!==u){const T=g.getLatestMsgSentByPeer(M);if(T){const{nick:P,avatar:W}=T;m&&D?m===P&&D===W||g.updateNickAndAvatarOfSentMessage({conversationID:M,latestNick:m,latestAvatar:D,isSentByMe:!1}):(s.nick=P,s.avatar=W)}}else{const T=g.getLatestMsgSentByMe(M);!T||m===T.nick&&D===T.avatar||g.updateNickAndAvatarOfSentMessage({conversationID:M,latestNick:m,latestAvatar:D,isSentByMe:!0})}}_handleNewMessageList(s){const{messageDataHandler:n}=this._core.message||{},g=new Map,u=[];return s.forEach(E=>{this._updateMessageProfile(E);let m=E.isModified===1;if(n.isMessageSentByCurrentInstance(E)?E.isModified=m:m=!1,E.isOnlineMessage())E._onlineOnlyFlag=!0,n.isMessageSentByCurrentInstance(E)||u.push(E);else if(this._shouldStoreUnreadMessage(E)){if(n.storeConversationMessage(E)){const{conversationID:D,conversationType:M,conversationSubType:T,flow:P,_isExcludedFromUnreadCount:W,_isExcludedFromLastMessage:iA}=E,EA=iA?"":E;g.has(D)?(g.get(D).lastMessage=EA,P==="in"&&(W||g.get(D).unreadCount++)):g.set(D,{conversationID:D,type:M,subType:T,unreadCount:W||P!=="in"?0:1,lastMessage:EA})}n.isMessageSentByCurrentInstance(E)&&!m||u.push(E)}}),{messages:u,conversationOptions:g}}_shouldStoreUnreadMessage(s){var n;const{conversationID:g}=s,{message:u,appStore:E,utils:{isEmpty:m}}=this._core||{},D=Array.from(((n=E.conversationStore.getConversationMap())===null||n===void 0?void 0:n.keys())||[]),M=this._getLocalLastMessageTime(g);return!u.messageDataHandler.isInMessageList(s)&&D.includes(g)&&this._localConversationIDListBeforeDisconnect.includes(g)&&!m(M)}_fetchUnreadDBMessage(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g}}=this._core;try{n.debug("_fetchUnreadDBMessage",`unread-message-synchronizer._fetchUnreadDBMessage options:${g(s)}`);const E=yield el(s,this._core);if(!E)return null;const{syncFlag:m,unreadMessageList:D,revokedMessageList:M,cookie:T,unreadCountList:P,overflowUnreadCountList:W,groupTipList:iA}=E;return this._parseAndSaveUnreadMessageList(D),{syncFlag:m,cookie:T,unreadMessageList:D,revokedMessageList:M,unreadCountList:P,overflowUnreadCountList:W,groupTipList:iA}}catch(u){console.log(u)}})}_canContinueSync({cookie:s,syncFlag:n}){var g;return n===kg.START_SYNC||n===kg.SYNCING&&!(!((g=this._core)===null||g===void 0)&&g.helper.isEmpty(s))}_parseAndSaveUnreadMessageList(s){s.forEach(n=>{const{ID:g}=n;this._unreadDBMessageMap.set(g,n)})}_handleDisconnect(){var s;const{appStore:n}=this._core;this._localConversationIDListBeforeDisconnect=Array.from(((s=n.conversationStore.getConversationMap())===null||s===void 0?void 0:s.keys())||[])}_getLocalLastMessageTime(s){const{message:n}=this._core,g=n.messageDataHandler.getLocalMessageList(s),u=g[g.length-1];return u?.time}_reset(){this._cookie="",this._unreadDBMessageMap.clear()}_dispose(){var s,n;(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),(n=this._core)===null||n===void 0||n.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),this._reset()}},TE=new class{init(s){var n;this._core=s,this._visibilityChangeHandler=this._handleVisibilityChange.bind(this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this),document?.addEventListener("visibilitychange",this._visibilityChangeHandler),(n=this._core)===null||n===void 0||n.store.set("activityMonitor",{isActive:!0})}_handleVisibilityChange(){var s,n;const g=document?.visibilityState==="visible";(s=this._core)===null||s===void 0||s.store.set("activityMonitor",{isActive:g}),(n=this._core)===null||n===void 0||n.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:g})}_reset(){var s;(s=this._core)===null||s===void 0||s.store.clear("activityMonitor")}_dispose(){document?.removeEventListener("visibilitychange",this._visibilityChangeHandler);const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this),this._reset()}},NE=new class{init(s){var n;this._core=s,this._bindAppActivityEvent(),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this),(n=this._core)===null||n===void 0||n.store.set("activityMonitor",{isActive:!0})}_bindAppActivityEvent(){var s,n,g,u,E;const{MINI_APP_NAMESPACE:m,IN_TT_MINI_GAME:D,IN_WX_MINI_GAME:M}=((s=this._core)===null||s===void 0?void 0:s.utils)||{};D||M?((n=m?.onShow)===null||n===void 0||n.call(m,()=>{var T,P;(T=this._core)===null||T===void 0||T.store.set("activityMonitor",{isActive:!0}),(P=this._core)===null||P===void 0||P.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})}),(g=m?.onHide)===null||g===void 0||g.call(m,()=>{var T,P;(T=this._core)===null||T===void 0||T.store.set("activityMonitor",{isActive:!1}),(P=this._core)===null||P===void 0||P.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})})):((u=m?.onAppShow)===null||u===void 0||u.call(m,()=>{var T,P;(T=this._core)===null||T===void 0||T.store.set("activityMonitor",{isActive:!0}),(P=this._core)===null||P===void 0||P.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})}),(E=m?.onAppHide)===null||E===void 0||E.call(m,()=>{var T,P;(T=this._core)===null||T===void 0||T.store.set("activityMonitor",{isActive:!1}),(P=this._core)===null||P===void 0||P.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})}))}_reset(){var s;(s=this._core)===null||s===void 0||s.store.clear("activityMonitor")}_dispose(){const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this),this._reset()}},hd=new class{init(s){const{IN_MINI_APP:n,IN_WX_MINI_PLUGIN:g}=s.helper;g||(n?NE.init(s):TE.init(s))}};const GE="none",tl="online";var dI=new class{init(s){this._core=s,this._activateNetworkMonitoring(),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return pA(this,void 0,void 0,function*(){navigator.onLine?this._onOnline():this._onOffline(),this._onOnlineCallback=this._onOnline.bind(this),this._onOfflineCallback=this._onOffline.bind(this),window.addEventListener("online",this._onOnlineCallback),window.addEventListener("offline",this._onOfflineCallback)})}_deactivateNetworkMonitoring(){this._onOnlineCallback!==null&&(window.removeEventListener("online",this._onOnlineCallback),this._onOnlineCallback=null),this._onOfflineCallback!==null&&(window.removeEventListener("offline",this._onOfflineCallback),this._onOfflineCallback=null)}_onNetworkStatusChange(s){var n,g;const{isConnected:u,networkType:E}=s;(n=this._core)===null||n===void 0||n.store.set("netWorkMonitor",{isNetworkOnline:u,networkType:E}),(g=this._core)===null||g===void 0||g.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:u,networkType:E})}_onOnline(){this._onNetworkStatusChange({isConnected:!0,networkType:tl})}_onOffline(){this._onNetworkStatusChange({isConnected:!1,networkType:GE})}_reset(){var s;this._deactivateNetworkMonitoring(),(s=this._core)===null||s===void 0||s.store.clear("netWorkMonitor")}_dispose(){var s,n;(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent((n=this._core)===null||n===void 0?void 0:n.InnerEvent.DESTROY,this._dispose,this),this._reset()}},Lu=new class{init(s){this._core=s,this._activateNetworkMonitoring(),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return pA(this,void 0,void 0,function*(){try{const{utils:{MINI_APP_NAMESPACE:s}}=this._core;this._mpNetworkStatusCallback=this._onNetworkStatusChange.bind(this),s.onNetworkStatusChange(this._onNetworkStatusChange.bind(this))}catch(s){console.error(s)}})}_deactivateNetworkMonitoring(){if(this._mpNetworkStatusCallback!==null){const{utils:{MINI_APP_NAMESPACE:s}}=this._core;s.offNetworkStatusChange&&s.offNetworkStatusChange(this._mpNetworkStatusCallback),this._mpNetworkStatusCallback=null}}_onNetworkStatusChange(s){var n,g;const{isConnected:u,networkType:E}=s;(n=this._core)===null||n===void 0||n.store.set("netWorkMonitor",{isNetworkOnline:u,networkType:E}),(g=this._core)===null||g===void 0||g.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:u,networkType:E})}_reset(){var s;this._deactivateNetworkMonitoring(),(s=this._core)===null||s===void 0||s.store.clear("netWorkMonitor")}_dispose(){var s,n;(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent((n=this._core)===null||n===void 0?void 0:n.InnerEvent.DESTROY,this._dispose,this),this._reset()}},Uu=new class{init(s){const{IN_MINI_APP:n}=s.utils;n?Lu.init(s):dI.init(s)}},EC=new class{constructor(){this.name="SystemStateMonitor"}install(s){hd.init(s),Uu.init(s)}};const wr=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=wr}install(s){this._core=s;const{notificationCenter:n,InnerEvent:g,helper:u}=s;n.subscribeInnerEvent(g.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),n.subscribeInnerEvent(g.LOGOUT,this._reset,this),n.subscribeInnerEvent(g.DESTROY,this._dispose,this),n.subscribeInnerEvent("im_open_push.msg_push",n.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this),u.registerExperimentalAPI("sendTRTCCustomData",this,"transferBusinessCommand"),u.registerExperimentalAPI("sendRoomCustomData",this,"transferBusinessCommand")}transferBusinessCommand(s){return pA(this,void 0,void 0,function*(){const n="transferBusinessCommand";try{const{serviceCommand:g=cg}=s||{};if(!this._isValidTransferredCommand(g))throw new this._core.helper.ChatError({code:2995,functionName:n});return{code:0,data:(yield function(E,m){return pA(this,void 0,void 0,function*(){const{helper:D,channel:M}=m,{serviceCommand:T=cg,data:P}=E||{};let W={};try{W=typeof P=="string"?JSON.parse(P):P}catch(RA){console.warn(RA)}const iA=D.generateProtocolData({servcmd:T,data:W}),EA=`${iA.head.seq}${T}`;return M.sendPacket(iA,{requestId:EA,shouldRejectOnError:!1})})}(s,this._core))||{}}}catch(g){throw console.warn(g),new this._core.helper.ChatError({code:g?.errorCode,message:g?.errorInfo,data:{},functionName:n})}})}_onCloudConfigUpdate(s={}){try{if(typeof s.rtc_cmd!="string")return;const n=JSON.parse(s.rtc_cmd);Array.isArray(n)&&(this._transferredCommands=new Set([...this._transferredCommands,...n]))}catch(n){console.log(n)}}_isValidTransferredCommand(s=""){const n=`${s?.split(".")[0]}.*`;return this._transferredCommands.has(n)}_onServerPushBusinessCommand(s){const{OuterEvent:n,notificationCenter:g}=this._core,{MsgContent:u}=s||{},{ROOM_CUSTOM_DATA_RECEIVED:E}=n;g.emitOuterEvent(E,{name:E,data:u})}_reset(){this._transferredCommands=wr}_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 Fu=1,Tl=2,Bd=3,$r=4,CI=5,_n="TIMCustomElem",dC="C2C",il="GROUP",Qd="invite",hI="accept",Oa="cancel",CC="reject",Pa="modifyInvitation",ur="signaling",pd=8010,Ou="signaling-timeout";function Er(s){return s.filter(n=>{if(n.type===_n){const{cloudCustomData:g="",payload:{data:u=""}={}}=n,E=g.match(/"type":"tsignaling"/),m=u.match(/inviteID/),D=u.match(/actionType/);return E||m&&D}return!1})}function wc(s){const{data:n}=s.payload;try{return JSON.parse(n)}catch(g){return console.error(g),null}}function ol(s,n){return s.toString(16).padStart(n,"0")}function Lg(s){if(s<0||s>53)throw new Error("Number of digits must be between 0 and 53");if(s<=30)return Math.floor(Math.random()*(1<0;const M=this._core.common.getCurrentUserID();return D.includes(M)}return!0}updateSignaling(s){const n=`${ur}.updateSignaling`,{inviteID:g,inviter:u,inviteeList:E,groupID:m}=s;if(console.log(`${n} inviteID:${g} inviter:${u} groupID:${m}`),m&&this.hasSignaling(g)){const D=E[0],{inviteeList:M}=this._onlineSignalingMap.get(g);M.includes(D)&&(M.splice(M.indexOf(D),1),console.log(`${n} remove ${D}. localInviteeList.length:${M.length}`)),M.length===0&&this.removeSignaling(g)}else this.removeSignaling(g)}setSignalingListenStatus(s){this._isSignalingListening=s}getSignalingListenStatus(){return this._isSignalingListening}_dispose(){var s,n;this._reset(),(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),(n=this._core)===null||n===void 0||n.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._isSignalingListening=!1}_reset(){this._onlineSignalingMap.clear()}},$g=new class{init(s){this._core=s}createInviteSignaling(s){const n=this._generateInviteID(),g=this._createInviteSignalingData(Object.assign(Object.assign({},s),{inviteID:n})),{groupID:u,inviteeList:E}=g,m=u||E[0];return{signaling:this._createSignaling(g,m),signalingData:g,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createAcceptSignaling(s){const n=this._createAcceptSignalingData(s),{groupID:g,inviter:u}=n,E=g||u;return{signaling:this._createSignaling(n,E),signalingData:n,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createCancelSignaling(s){const n=this._createCancelSignalingData(s),{groupID:g,inviteeList:u}=n,E=g||u[0];return{signaling:this._createSignaling(n,E),signalingData:n,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createRejectSignaling(s){const n=this._createRejectSignalingData(s),{groupID:g,inviter:u}=n,E=g||u;return{signaling:this._createSignaling(n,E),signalingData:n,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createTimeoutSignaling(s){const{isInviter:n=!1}=s,g=this._createTimeoutSignalingData(s),{groupID:u,inviteeList:E,inviter:m}=g,D=u||(n?E[0]:m);return{signaling:this._createSignaling(g,D),signalingData:g,signalingExtensionOptions:this._createSignalingExtensionOptions(g)}}_createSignalingExtensionOptions(s){var n,g;const{data:u="",onlineUserOnly:E,inviteID:m="",offlinePushInfo:D,actionType:M}=s,T=((g=(n=Oo.getSignaling(m))===null||n===void 0?void 0:n.signaling)===null||g===void 0?void 0:g._onlineOnlyFlag)||!1;return{onlineUserOnly:E||T,offlinePushInfo:D,messageControlInfo:this._createMessageControlInfo(u,M)}}_createMessageControlInfo(s,n){const g=n===CI&&!!s.match(/excludeTimeoutSignalingFromHistoryMessage/),u=!!s.match(/excludeFromHistoryMessage/)||!!s.match(/excludeOriginalSignalingFromHistoryMessage/);return{excludedFromContentModeration:!0,excludedFromUnreadCount:g||u,excludedFromLastMessage:g||u}}_createInviteSignalingData(s){const n=`${ur}._createInviteSignalingData`,{userID:g,timeout:u=0,groupID:E="",inviteeList:m=[]}=s,D=this._core.common.getCurrentUserID(),M=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:Fu,inviter:D,inviteeList:E?m:[g],timeout:u});return console.log(`${n} signalingData:`,M),M}_createAcceptSignalingData(s){const n=`${ur}._createAcceptSignalingData`,{inviteID:g}=s,u=this._core.common.getCurrentUserID(),{inviter:E,groupID:m}=Oo.getSignaling(g),D=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:Bd,groupID:m,inviter:E,inviteeList:[u]});return console.log(`${n} signalingData:`,D),D}_createCancelSignalingData(s){const n=`${ur}._createCancelSignalingData`,{inviteID:g}=s,u=this._core.common.getCurrentUserID(),{inviteeList:E,groupID:m}=Oo.getSignaling(g),D=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:Tl,groupID:m,inviter:u,inviteeList:E});return console.log(`${n} signalingData:`,D),D}_createRejectSignalingData(s){const n=`${ur}._createRejectSignalingData`,{inviteID:g}=s,u=this._core.common.getCurrentUserID(),{inviter:E,groupID:m}=Oo.getSignaling(g),D=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:$r,groupID:m,inviter:E,inviteeList:[u]});return console.log(`${n} signalingData:`,D),D}_createTimeoutSignalingData(s){const n=`${ur}._createTimeoutSignalingData`,{isInviter:g=!1,inviteID:u}=s,{inviteeList:E,inviter:m}=Oo.getSignaling(u),D=this._core.common.getCurrentUserID(),M=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:CI,inviter:m,inviteeList:g?E:[D]});return console.log(`${n} signalingData:`,M),M}_createSignaling(s,n){var g,u,E;const{groupID:m=""}=s,D={to:n,conversationType:m?il:dC,priority:"High",payload:{data:JSON.stringify(s)}};return(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageFactory)===null||E===void 0?void 0:E.createCustomMessage(D)}_generateInviteID(){return[ol(Lg(32),8),ol(Lg(16),4),ol(16384|Lg(12),4),ol(32768|Lg(14),4),ol(Lg(48),12)].join("-")}_generateBaseSignalData(s){const{data:n="",inviteID:g="",groupID:u=""}=s;return{businessID:1,timeout:0,data:n,inviteID:g,groupID:u}}},Za=new class{constructor(){this._isProcessingSignaling=!1}init(s){this._core=s,s.helper.registerApi({apiName:"invite",context:this}),s.helper.registerApi({apiName:"accept",context:this}),s.helper.registerApi({apiName:"cancel",context:this}),s.helper.registerApi({apiName:"reject",context:this}),s.helper.registerApi({apiName:"modifyInvitation",context:this}),s.helper.registerApi({apiName:"getSignalingInfo",context:this}),s.helper.registerApi({apiName:"addSignalingListener",context:this}),s.helper.registerApi({apiName:"removeSignalingListener",context:this}),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.LOGOUT,this._reset,this)}invite(s){return pA(this,void 0,void 0,function*(){var n;try{this._validateBeforeInvite(s);const{signaling:g,signalingData:u,signalingExtensionOptions:E}=$g.createInviteSignaling(s),m=yield this._sendSignaling(g,E);if(m?.code===0){const{inviteID:D,timeout:M}=u;return Oo.saveSignaling(D,Object.assign(Object.assign({},u),{signaling:g})),M>0&&((n=this._core)===null||n===void 0||n.helper.taskScheduler.addOnceTask({id:`${Ou}-${D}`,intervalMs:1e3*(M+5),callback:this.handleInvitationExpiryTimer.bind(this,D)})),Object.assign(Object.assign({},m),{inviteID:D})}return m}catch(g){throw g}})}accept(s){return pA(this,void 0,void 0,function*(){try{const{inviteID:n}=s;this._validateBeforeAccept(n),this._isProcessingSignaling=!0;const{signaling:g,signalingData:u,signalingExtensionOptions:E}=$g.createAcceptSignaling(s),m=yield this._sendSignaling(g,E);return m?.code===0?(Oo.updateSignaling(u),Object.assign(Object.assign({},m),{inviteID:n})):m}catch(n){throw n}finally{this._isProcessingSignaling=!1}})}cancel(s){return pA(this,void 0,void 0,function*(){try{const{inviteID:n}=s;this._validateBeforeCancel(n),this._isProcessingSignaling=!0;const{signaling:g,signalingExtensionOptions:u}=$g.createCancelSignaling(s),E=yield this._sendSignaling(g,u);return E?.code===0?(Oo.removeSignaling(n),Object.assign(Object.assign({},E),{inviteID:n})):E}catch(n){throw n}finally{this._isProcessingSignaling=!1}})}reject(s){return pA(this,void 0,void 0,function*(){try{const{inviteID:n}=s;this._validateBeforeReject(n),this._isProcessingSignaling=!0;const{signaling:g,signalingExtensionOptions:u}=$g.createRejectSignaling(s),E=yield this._sendSignaling(g,u);return E?.code===0?(Oo.removeSignaling(n),Object.assign(Object.assign({},E),{inviteID:n})):E}catch(n){throw n}finally{this._isProcessingSignaling=!1}})}modifyInvitation(s){return pA(this,void 0,void 0,function*(){var n,g;const{inviteID:u,data:E}=s;let m="";try{this._validateBeforeModifyInvitation(u);const D=Oo.getSignaling(u),{signaling:M}=D,T=Do(D,["signaling"]);m=M.payload.data,T.data=E,M.payload.data=JSON.stringify(T);const P=yield(g=(n=this._core)===null||n===void 0?void 0:n.message.messageAction)===null||g===void 0?void 0:g.modifyMessage(M);return Oo.hasSignaling(u)&&Oo.saveSignaling(u,Object.assign(Object.assign({},T),{signaling:M})),P}catch(D){if(m){const{signaling:M}=Oo.getSignaling(u);M.payload.data=m}throw D}})}getSignalingInfo(s){const{ssoLog:n,utils:{safeStringify:g}}=this._core;if(Er([s]).length===0)return;const u=wc(s),E={businessID:u.businessID||1,inviteID:u.inviteID,groupID:u.groupID||"",inviter:u.inviter||"",inviteeList:u.inviteeList||[],data:u.data||"",actionType:u.actionType||Fu,timeout:u.timeout||0};return n.debug(`${ur} getSignalingInfo ${g(E)}`),E}addSignalingListener(s,n,g){var u,E;s===((u=this._core)===null||u===void 0?void 0:u.SignalingEvent.NEW_INVITATION_RECEIVED)&&Oo.setSignalingListenStatus(!0),(E=this._core)===null||E===void 0||E.notificationCenter.subscribeOuterEvent(s,n,g)}removeSignalingListener(s,n,g){var u,E;s===((u=this._core)===null||u===void 0?void 0:u.SignalingEvent.NEW_INVITATION_RECEIVED)&&Oo.setSignalingListenStatus(!1),(E=this._core)===null||E===void 0||E.notificationCenter.unSubscribeOuterEvent(s,n,g)}handleInvitationExpiryTimer(s){const n=Oo.getOnlineSignalingMap(),g=this._core.common.getCurrentUserID();if(!n.has(s))return;const u=n.get(s).inviter===g;this._sendTimeoutNotice({inviteID:s,isInviter:u})}_sendSignaling(s,n){return pA(this,void 0,void 0,function*(){var g,u,E;return(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageSender)===null||E===void 0?void 0:E.sendMessage(s,n)})}_sendTimeoutNotice(s){return pA(this,void 0,void 0,function*(){var n,g,u;this._core.ssoLog.debug("_sendTimeoutNotice",`${ur}._sendTimeoutNotice params:${JSON.stringify(s)}`);const{isInviter:E,inviteID:m}=s,{signaling:D,signalingData:M,signalingExtensionOptions:T}=$g.createTimeoutSignaling(s),P=yield this._sendSignaling(D,T);if(P?.code===0){const{data:W,groupID:iA,inviteeList:EA,inviter:RA}=M;(n=this._core)===null||n===void 0||n.notificationCenter.emitOuterEvent((g=this._core)===null||g===void 0?void 0:g.SignalingEvent.INVITATION_TIMEOUT,{name:(u=this._core)===null||u===void 0?void 0:u.SignalingEvent.INVITATION_TIMEOUT,data:{data:W,groupID:iA,inviteID:m,inviteeList:EA,inviter:RA,isSelfTimeout:!0,message:D}}),E?Oo.removeSignaling(m):Oo.updateSignaling(M)}})}_validateInviteId(s,n){if(!Oo.hasSignaling(n))throw new this._core.helper.ChatError({functionName:s,code:pd})}_validateProcessStatus(s){if(this._isProcessingSignaling)throw new this._core.helper.ChatError({functionName:s,message:"processing other signaling operations"})}_validateBeforeInvite(s){const n=Qd,{userID:g}=s,u=this._core.common.getCurrentUserID();if(g===u)throw new this._core.helper.ChatError({functionName:n,message:`cannot invite yourself, currentUserId:${u}, inviteeId:${g}`})}_validateBeforeAccept(s){const n=hI;this._validateInviteId(n,s),this._validateProcessStatus(n);const g=this._core.common.getCurrentUserID(),{inviteeList:u}=Oo.getSignaling(s);if(!u.includes(g)){const E=`userID:${g} not in inviteeList. inviteID:${s}`;throw new this._core.helper.ChatError({functionName:n,message:E})}}_validateBeforeCancel(s){const n=Oa;this._validateInviteId(n,s),this._validateProcessStatus(n);const g=this._core.common.getCurrentUserID(),{inviter:u}=Oo.getSignaling(s);if(u!==g){const E=`unmatched inviter:${u} and my userID:${g}`;throw new this._core.helper.ChatError({functionName:n,message:E})}}_validateBeforeReject(s){const n=CC;this._validateInviteId(n,s),this._validateProcessStatus(n);const g=this._core.common.getCurrentUserID(),{inviteeList:u}=Oo.getSignaling(s);if(!u.includes(g)){const E=`userID:${g} not in inviteeList. inviteID:${s}`;throw new this._core.helper.ChatError({functionName:n,message:E})}}_validateBeforeModifyInvitation(s){const n=Pa;this._validateInviteId(n,s)}_dispose(){var s,n;this._reset(),(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),(n=this._core)===null||n===void 0||n.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this)}_reset(){this._isProcessingSignaling=!1}},Nl=new class{constructor(){this._actionProcessor=new Map([[Fu,this._onNewInvitationReceived.bind(this)],[$r,this._onInviteeRejected.bind(this)],[Bd,this._onInviteeAccepted.bind(this)],[Tl,this._onInvitationCancelled.bind(this)],[CI,this._onInvitationTimeout.bind(this)]])}init(s){this._core=s,s.notificationCenter.subscribeOuterEvent(s.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),s.notificationCenter.subscribeOuterEvent(s.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this)}handleActionSignaling(s){s.forEach(n=>{const g=wc(n);if(g){const u=this._actionProcessor.get(g.actionType);u?.(g,n)}})}_handleMessageReceived(s){if(!Oo.getSignalingListenStatus())return;const n=Er(s.data);n.length!==0&&this.handleActionSignaling(n)}_handleMessageModified(s){if(!Oo.getSignalingListenStatus())return;const n=Er(s.data);n.length>0&&n.forEach(g=>{const u=wc(g);u&&this._onInvitationModified(u,g)})}_onNewInvitationReceived(s,n){var g,u;const E=`${ur}._onNewInvitationReceived`,{inviteID:m,inviteeList:D,groupID:M}=s,T=this._core.common.getCurrentUserID();if(this._core.ssoLog.debug("_onNewInvitationReceived",`${E} signalingData:${JSON.stringify(s)}}`),M&&!D.includes(T))return;let{timeout:P}=s;const W=Date.now()/1e3-n.time;P>0&&W>0&&P>W&&(P-=W);const iA=Oo.getSignaling(m);iA!==s&&(iA||Oo.saveSignaling(m,Object.assign(Object.assign({},s),{signaling:n})),P>0&&((g=this._core)===null||g===void 0||g.helper.taskScheduler.addOnceTask({id:`${Ou}-${m}`,intervalMs:1e3*P,callback:Za.handleInvitationExpiryTimer.bind(Za,m)})),this._emitEvent({name:(u=this._core)===null||u===void 0?void 0:u.SignalingEvent.NEW_INVITATION_RECEIVED,data:Object.assign(Object.assign({},this._generateBaseEmitData(s)),{inviteeList:D})}))}_onInviteeRejected(s){var n;const g=`${ur}._onInviteeRejected`,{inviteID:u,inviter:E,groupID:m,inviteeList:D}=s,M=Oo.hasSignaling(u);this._core.ssoLog.debug("_onInviteeRejected",`${g} inviteID:${u} hasInviteID:${M} inviter:${E} groupID:${m}`),M&&(Oo.updateSignaling(s),this._emitEvent({name:(n=this._core)===null||n===void 0?void 0:n.SignalingEvent.INVITEE_REJECTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(s)),{invitee:D[0]})}))}_onInviteeAccepted(s){var n;const g=`${ur}._onInviteeAccepted`,{inviteID:u,inviter:E,groupID:m,inviteeList:D}=s,M=Oo.hasSignaling(u);this._core.ssoLog.debug("_onInviteeAccepted",`${g} inviteID:${u} hasInviteID:${M} inviter:${E} groupID:${m}`),M&&(Oo.updateSignaling(s),this._emitEvent({name:(n=this._core)===null||n===void 0?void 0:n.SignalingEvent.INVITEE_ACCEPTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(s)),{invitee:D[0]})}))}_onInvitationCancelled(s){var n;const g=`${ur}._onInvitationCancelled`,{inviteID:u,inviter:E,groupID:m}=s,D=Oo.hasSignaling(u);this._core.ssoLog.debug("_onInvitationCancelled",`${g} inviteID:${u} hasInviteID:${D} inviter:${E} groupID:${m}`),D&&(Oo.removeSignaling(u),this._emitEvent({name:(n=this._core)===null||n===void 0?void 0:n.SignalingEvent.INVITATION_CANCELLED,data:this._generateBaseEmitData(s)}))}_onInvitationTimeout(s){var n;const g=`${ur}._onInvitationTimeout`,{inviteID:u,inviteeList:E}=s,m=Oo.hasSignaling(u);this._core.ssoLog.debug("_onInvitationTimeout",`${g} inviteID:${u} hasInviteID:${m} data:${s.data}`),m&&(Oo.updateSignaling(s),this._emitEvent({name:(n=this._core)===null||n===void 0?void 0:n.SignalingEvent.INVITATION_TIMEOUT,data:Object.assign(Object.assign({},this._generateBaseEmitData(s)),{inviteeList:E,isSelfTimeout:!1})}))}_onInvitationModified(s,n){var g;const u=`${ur}._onInvitationModified`,{inviteID:E,data:m}=s,D=Oo.hasSignaling(E);this._core.ssoLog.debug("_onInvitationModified",`${u} inviteID:${E} data:${m}`),D&&(Oo.saveSignaling(E,Object.assign(Object.assign({},s),{signaling:n})),this._emitEvent({name:(g=this._core)===null||g===void 0?void 0:g.SignalingEvent.INVITATION_MODIFIED,data:{inviteID:E,data:m}}))}_emitEvent(s){var n;(n=this._core)===null||n===void 0||n.notificationCenter.emitOuterEvent(s.name,s)}_generateBaseEmitData(s){const{inviteID:n,inviter:g,groupID:u,data:E}=s;return{inviteID:n,inviter:g,groupID:u,data:E||""}}_dispose(){var s,n,g;(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),(n=this._core)===null||n===void 0||n.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),(g=this._core)===null||g===void 0||g.notificationCenter.unSubscribeOuterEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}},Aa=new class{constructor(){this._offlineSignalingMap=new Map}init(s){this._core=s;const{notificationCenter:n,helper:g,constants:{InnerEvent:u,WORKFLOW_STEP:E,WORKFLOW_NAME:m}}=s;n.subscribeInnerEvent(u.DESTROY,this._dispose,this),n.subscribeInnerEvent(u.LOGOUT,this._reset,this),g.registerWorkflowStep(m.SYNC_SERVER_INFO_AFTER_LOGIN,E.SIGNALING_MESSAGE_RECOVER,this._handleC2COfflineMessage,this)}_handleC2COfflineMessage(s){const{result:{unreadMessageMap:n}={}}=s||{};if(!(n?.size!==0&&Oo.getSignalingListenStatus()))return;const g=Er([...n.values()]);if(g.length!==0&&(g.forEach(u=>{this._handleC2CActionType(u)}),this._offlineSignalingMap.size>0)){const u=this._sortOfflineSignalingByTime();Nl.handleActionSignaling(u)}}_handleC2CActionType(s){const n=wc(s);if(!n)return;const{actionType:g}=n;g===Fu?this._saveValidOfflineInvite(n,s):this._removeOfflineInvite(n)}_saveValidOfflineInvite(s,n){const{inviteID:g,inviteeList:u=[],timeout:E=0}=s,m=this._core.common.getCurrentUserID();if(!u.includes(m))return;const D=Date.now()/1e3-n.time;E>0&&D>E&&E!==0||this._offlineSignalingMap.set(g,Object.assign(Object.assign({},s),{signalingList:[n]}))}_removeOfflineInvite(s){const{inviteID:n=""}=s;this._offlineSignalingMap.has(n)&&this._offlineSignalingMap.delete(n)}_sortOfflineSignalingByTime(){let s=[];return this._offlineSignalingMap.forEach(n=>{s=[...s,...n.signalingList]}),s.sort((n,g)=>n.time-g.time)}_dispose(){var s,n;this._reset(),(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),(n=this._core)===null||n===void 0||n.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._offlineSignalingMap.clear()}};const gh={invite:{userID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0},timeout:{required:!1,rules:["number"],allowEmpty:!1},onlineUserOnly:{required:!1,rules:["boolean"],allowEmpty:!1},offlinePushInfo:{required:!1,rules:["object"],allowEmpty:!1}},cancel:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},accept:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},reject:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},modifyInvitation:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}}},js={invite:!0,cancel:!0,accept:!0,reject:!0,modifyInvitation:!0};var XI=new class{constructor(){this.name="Signaling"}install(s){Za.init(s),Nl.init(s),$g.init(s),Oo.init(s),Aa.init(s),s.helper.registerValidateConfig({auth:js,params:gh})}};const Us=new class{init(s){this.core=s}};function _c(s){let n;const{message:g}=Us.core,{conversationID:u,messageID:E}=s;return n=g.messageDataHandler.getLocalMessageList(u).find(m=>m.ID===E),!n&&(n=g.messageDataHandler.getSparseMessageList(u).find(m=>m.ID===E)),n}function Ac(s){return s.map(n=>{const{from:g,to:u,cloudCustomData:E,avatar:m,nick:D,ID:M,clientSequence:T,clientTime:P,messageRandom:W,messageSequence:iA,time:EA}=n;return{ClientSeq:T,CloudCustomData:E,From_Account:g,From_AccountHeadurl:m,From_AccountNick:D,Id:M,MsgBody:JSON.parse(JSON.stringify(n.transformElementsToServerFormat())),MsgClientTime:P,MsgRandom:W,Random:W,MsgSeq:iA,MsgTimeStamp:EA,ReceiverId:u,SenderId:g,To_Account:u}})}function dr(s){var n;const{From_Account:g,From_AccountHeadurl:u,From_AccountNick:E,GroupId:m,MsgClientTime:D,ClientSeq:M,To_Account:T,MsgTimeStamp:P,TinyId:W,MsgRandom:iA,MsgSeq:EA}=s;return{from:g,avatar:u,nick:E,clientTime:D,time:P,tinyID:W,random:iA,sequence:EA,to:T,groupID:m,clientSequence:M,_elements:(n=s.MsgBody)===null||n===void 0?void 0:n.map(RA=>{const{MsgType:kA}=RA;return Us.core.message.messageFactory.getElementClass(kA).parseServerPushElement(RA)})}}var Vr,Xa;(function(s){s.MSG_TEXT="TIMTextElem",s.MSG_CUSTOM="TIMCustomElem",s.MSG_LOCATION="TIMLocationElem",s.MSG_FACE="TIMFaceElem",s.MSG_STREAM="TIMStreamElem"})(Vr||(Vr={})),function(s){s[s.FORWARD=0]="FORWARD",s[s.BACKWARD=1]="BACKWARD"}(Xa||(Xa={}));const bE="MSG_REACTION",hC="MSG_EXT",ch=0,ao=1,Tc={ZH_CN:"zh (cmn-Hans-CN)",EN_US:"en-US",YUE_HK:"yue-Hant-HK",JA_JP:"ja-JP",ZH_PY:"zh-PY"},Gl="16k_zh",BC="16k_en",QC="16k_yue",bl="16k_ja",$I="16k_zh-PY",BI={[Tc.ZH_CN]:Gl,[Tc.EN_US]:BC,[Tc.YUE_HK]:QC,[Tc.JA_JP]:bl,[Tc.ZH_PY]:$I},QI=/\.(wav|pcm|ogg-opus|speex|silk|mp3|m4a|aac|amr)/,kE={READ:0,UNREAD:1},kl=1,Ll=2,Ug=3;var ec;(function(s){s.IN="in",s.OUT="out"})(ec||(ec={}));const md=16,LE=17;var Nc;(function(s){s[s.DATA=0]="DATA",s[s.REVOKED=1]="REVOKED"})(Nc||(Nc={}));var Au;(function(s){s[s.NORMAL=0]="NORMAL",s[s.TIMEOUT=1]="TIMEOUT"})(Au||(Au={}));const lo="StreamMsg.PushStreamHttp";var UE=new class{constructor(){this._reactionsMap=new Map}init(s){this._core=s;const{helper:n,notificationCenter:g,InnerEvent:{MESSAGE_PUSH:u},InnerEventSubType:{MESSAGE_REACTION_UPDATED:E,MESSAGE_REACTION_UPDATED_SYNC:m}}=s;n.registerApi({apiName:"addMessageReaction",context:this}),n.registerApi({apiName:"removeMessageReaction",context:this}),n.registerApi({apiName:"getMessageReactions",context:this}),n.registerApi({apiName:"getAllUserListOfMessageReaction",context:this}),g.subscribeInnerEvent(u,E,this._handleReactionUpdated,this),g.subscribeInnerEvent(u,m,this._handleReactionSync,this)}addMessageReaction(s,n){return pA(this,void 0,void 0,function*(){const{OuterConstant:g,ssoLog:u,helper:E}=this._core;this._validateMessageReactionBusinessCapability();const{conversationID:m,ID:D,conversationType:M,from:T,to:P,clientSequence:W,random:iA,time:EA,sequence:RA}=s,kA=`conversationID:${m} messageID:${D} reactionID:${n}`;try{return this._recordMessageReactedByMe(D,n),M===g.CONV_C2C?yield function(xA,LA){return pA(this,void 0,void 0,function*(){var SA;const{from:OA,to:JA,clientSequence:ae,random:se,time:_i,reactionID:Ti}=xA,Ft={From_Account:OA,To_Account:JA,MsgKey:`${ae}_${se}_${_i}`,Reaction:Ti,Add_Account:[(SA=LA.store.get("login"))===null||SA===void 0?void 0:SA.userId]};return Us.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_add",data:Ft})})}({from:T,to:P,clientSequence:W,random:iA,time:EA,reactionID:n},this._core):M===g.CONV_GROUP&&(yield function(xA,LA){return pA(this,void 0,void 0,function*(){var SA;const{to:OA,reactionID:JA,sequence:ae}=xA,se={GroupId:OA,MsgSeq:ae,Reaction:JA,Add_Account:[(SA=LA.store.get("login"))===null||SA===void 0?void 0:SA.userId]};return Us.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_add",data:se})})}({to:P,reactionID:n,sequence:RA},this._core)),{code:0,successLog:{message:kA}}}catch(xA){this._removeMyReactionRecord(D,n);const{errorCode:LA}=xA||{};throw new E.ChatError({functionName:"addMessageReaction",code:LA,moreMessage:kA})}})}removeMessageReaction(s,n){return pA(this,void 0,void 0,function*(){const{OuterConstant:g,helper:u}=this._core;this._validateMessageReactionBusinessCapability();const{conversationID:E,ID:m,conversationType:D,from:M,to:T,clientSequence:P,random:W,time:iA,sequence:EA}=s,RA=`conversationID:${E} messageID:${m} reactionID:${n}`;try{return this._removeMyReactionRecord(m,n),D===g.CONV_C2C?yield function(kA,xA){return pA(this,void 0,void 0,function*(){var LA;const{from:SA,to:OA,clientSequence:JA,random:ae,time:se,reactionID:_i}=kA,Ti={From_Account:SA,To_Account:OA,MsgKey:`${JA}_${ae}_${se}`,Reaction:_i,Del_Account:[(LA=xA.store.get("login"))===null||LA===void 0?void 0:LA.userId]};return Us.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_del",data:Ti})})}({from:M,to:T,clientSequence:P,random:W,time:iA,reactionID:n},this._core):D===g.CONV_GROUP&&(yield function(kA,xA){return pA(this,void 0,void 0,function*(){var LA;const{to:SA,reactionID:OA,sequence:JA}=kA,ae={GroupId:SA,MsgSeq:JA,Reaction:OA,Del_Account:[(LA=xA.store.get("login"))===null||LA===void 0?void 0:LA.userId]};return Us.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_del",data:ae},xA)})}({to:T,reactionID:n,sequence:EA},this._core)),{code:0,successLog:{message:RA}}}catch(kA){const{errorCode:xA}=kA||{};throw new u.ChatError({functionName:"removeMessageReaction",code:xA,moreMessage:RA})}})}getAllUserListOfMessageReaction(s){return pA(this,void 0,void 0,function*(){this._validateMessageReactionBusinessCapability();const{message:n,reactionID:g,nextSeq:u=0}=s,E=s.count>100?100:s.count,{conversationID:m}=n,{ssoLog:D,helper:M,constants:T}=this._core;try{let P=null;if(P=m.startsWith(T.OuterConstant.CONV_C2C)?yield function(W){return pA(this,void 0,void 0,function*(){const{message:iA,nextSeq:EA,reactionID:RA,count:kA}=W,{from:xA,to:LA,clientSequence:SA,random:OA,time:JA}=iA,ae={Reaction:RA,NextSeq:EA,Count:kA,From_Account:xA,To_Account:LA,MsgKey:`${SA}_${OA}_${JA}`};return Us.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_iterate",data:ae})})}({message:n,reactionID:g,nextSeq:u,count:E}):yield function(W){return pA(this,void 0,void 0,function*(){const{message:iA,nextSeq:EA,reactionID:RA,count:kA}=W,{sequence:xA,to:LA}=iA,SA={Reaction:RA,NextSeq:EA,GroupId:LA,Count:kA,MsgSeq:xA};return Us.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_iterate",data:SA})})}({message:n,reactionID:g,nextSeq:u,count:E}),P){const{Reaction_Account:W,NextSeq:iA}=P,EA=yield this._getUserProfileList(W);return{code:0,data:{nextSeq:iA,isCompleted:u===0,userList:EA}}}}catch(P){const{errorCode:W}=P||{};throw new M.ChatError({functionName:"getAllUserListOfMessageReaction",code:W})}})}getMessageReactions(s){return pA(this,void 0,void 0,function*(){const{constants:n}=this._core;this._validateMessageReactionBusinessCapability();const{messageList:g,maxUserCountPerReaction:u=10}=s,E=g[0];let m=null;const D=new Map,{from:M,to:T,conversationType:P}=E,W=this._generateMessageKeyList(g,D);P===n.OuterConstant.CONV_C2C?m=yield function(kA){return pA(this,void 0,void 0,function*(){const{from:xA,to:LA,messageKeyList:SA,maxUserCountPerReaction:OA}=kA,JA={From_Account:xA,To_Account:LA,MsgKeyList:SA,Count:OA};return Us.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_multi_stat",data:JA})})}({from:M,to:T,messageKeyList:W,maxUserCountPerReaction:u}):P===n.OuterConstant.CONV_GROUP&&(m=yield function(kA){return pA(this,void 0,void 0,function*(){const{groupId:xA,messageSequenceList:LA,maxUserCountPerReaction:SA}=kA,OA={GroupId:xA,MsgSeqList:LA,Count:SA};return Us.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_multi_stat",data:OA})})}({groupId:T,messageSequenceList:W,maxUserCountPerReaction:u}));const{Results:iA=[]}=m||{},EA=this._extractUserIDsFromReactionResults(iA),RA=yield this._getUserProfileMap(EA);return{code:0,data:{resultList:iA.map(kA=>{const{ReactionList:xA,MsgSeq:LA,MsgKey:SA}=kA;return{messageID:this._generateMessageID({messageSequence:LA,messageKey:SA,messageIDMap:D}),reactionList:xA.map(OA=>{const{Reaction:JA,Count:ae,Reaction_Account:se,ReactedByMe:_i}=OA;return{reactionID:JA,totalUserCount:ae,partialUserList:this._generatePartialUserInfo({userIDList:se,userProfileMap:RA}),reactedByMyself:_i===1}})}})}}})}dispose(){this._reactionsMap.clear()}_extractUserIDsFromReactionResults(s){const n=[];return s?.forEach(g=>{const{ReactionList:u=[]}=g;u.forEach(E=>{E.Reaction_Account&&n.push(...E.Reaction_Account)})}),n}_getUserProfileList(s){return pA(this,void 0,void 0,function*(){var n;try{const g=yield(n=this._core.user.userProfile)===null||n===void 0?void 0:n.getUserProfile({userIDList:s});return g?g.data:[]}catch{return[]}})}_getUserProfileMap(s){return pA(this,void 0,void 0,function*(){const n=new Map;return(yield this._getUserProfileList(s)).forEach(g=>{const{nick:u,avatar:E,userID:m}=g;n.set(m,{nick:u,avatar:E,userID:m})}),n})}_recordMessageReactedByMe(s,n){const g=`${s}-${n}`;this._reactionsMap.has(g)?this._reactionsMap.get(g).reactedByMe=!0:this._reactionsMap.set(g,{reactedByMe:!0})}_removeMyReactionRecord(s,n){const g=`${s}-${n}`;this._reactionsMap.has(g)&&(this._reactionsMap.get(g).reactedByMe=!1)}_recordMessageReactionInfo(s){const{messageID:n,reactionID:g,reactionInfo:u}=s,E=`${n}-${g}`,m=this._reactionsMap.get(E)||{};this._reactionsMap.set(E,Object.assign(Object.assign({},m),u))}_validateMessageReactionBusinessCapability(){const{helper:s,constants:n}=this._core;if(!s.checkBusinessCapabilityBits(bE))throw new s.ChatError({functionName:"addMessageReaction",code:n.ERROR_CODE.NO_USE,replacement1:"addMessageReaction"})}_handleReactionUpdated(s){const{MsgReactionNotifyList:n}=s,{notificationCenter:g,constants:u}=this._core;n.forEach(E=>pA(this,void 0,void 0,function*(){const{C2CMsgInfo:m,GroupMsgInfo:D,MsgReactionSummary:M}=E,{TinyId:T,MsgClientTime:P,MsgRandom:W}=Object.assign(Object.assign({},m),D),iA=`${T}-${P}-${W}`,EA=this._extractUserIDsFromReactionResults([{ReactionList:M}]),RA=yield this._getUserProfileMap(EA),kA=M.map(xA=>{var LA;const{Reaction:SA,Reaction_Account:OA}=xA,JA=this._generatePartialUserInfo({userIDList:OA,userProfileMap:RA}),ae=OA?xA.Count:0,se=((LA=this._reactionsMap.get(`${iA}-${SA}`))===null||LA===void 0?void 0:LA.reactedByMe)||!1;return this._recordMessageReactionInfo({messageID:iA,reactionID:SA,reactionInfo:{reactionID:SA,totalUserCount:ae,partialUserList:JA}}),{reactionID:SA,totalUserCount:ae,partialUserList:JA,reactedByMyself:se}});g.emitOuterEvent(u.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:u.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:iA,reactionList:kA}})}))}_handleReactionSync(s){var n;const{notificationCenter:g,constants:u}=this._core,{C2CMsgInfo:E={},GroupMsgInfo:m={},Reaction:D,OperateType:M}=s.MsgReactionNotify,{TinyId:T="",MsgClientTime:P=0,MsgRandom:W=0}=Object.assign(Object.assign({},E),m),iA=`${T}-${P}-${W}`,EA=`${iA}-${D}`;if(M===1?this._recordMessageReactedByMe(iA,D):this._removeMyReactionRecord(iA,D),(n=this._reactionsMap.get(EA))===null||n===void 0?void 0:n.reactionID){const RA=this._reactionsMap.get(EA);RA.reactedByMyself=M===1,g.emitOuterEvent(u.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:u.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:iA,reactionList:[RA]}})}}_generatePartialUserInfo({userIDList:s,userProfileMap:n}){const g=[];return s?.forEach(u=>{n.has(u)&&g.push(n.get(u))}),g}_generateMessageID(s){const{messageSequence:n,messageKey:g,messageIDMap:u}=s;return g?u.get(g):u.get(n)}_generateMessageKeyList(s,n){const{constants:g}=this._core,u=s[0],{conversationType:E}=u;let m=[];return E===g.OuterConstant.CONV_C2C?m=s.map(D=>{const{clientSequence:M,random:T,time:P,ID:W}=D,iA=`${M}_${T}_${P}`;return n.set(iA,W),iA}):E===g.OuterConstant.CONV_GROUP&&(m=s.map(D=>{const{ID:M,sequence:T}=D;return n.set(T,M),T})),m}},$a=new class{init(s){this._core=s;const{helper:n,InnerEvent:{MESSAGE_PUSH:g},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:u,GROUP_MESSAGE_READ_RECEIPT:E},notificationCenter:m}=s;n.registerApi({apiName:"sendMessageReadReceipt",context:this}),n.registerApi({apiName:"getMessageReadReceiptList",context:this}),n.registerApi({apiName:"getGroupMessageReadMemberList",context:this}),m.subscribeInnerEvent(g,u,this._handleC2CMessageReadReceipt,this),m.subscribeInnerEvent(g,E,this._handleGroupMessageReadReceipt,this)}sendMessageReadReceipt(s){return pA(this,void 0,void 0,function*(){var n;const{common:g,constants:u}=this._core,E=this._filterValidMessageSendByOther(s);if(E.length===0)throw new g.ChatError({code:u.ERROR_CODE.READ_RECEIPT_MSG_LIST_EMPTY});try{const{conversationType:m}=E[0];return m===u.OuterConstant.CONV_C2C?yield function(D){return pA(this,void 0,void 0,function*(){const{common:M,constants:T}=Us.core,P=D[0].conversationID.replace(T.OuterConstant.CONV_C2C,""),W=D.map(EA=>{const{from:RA,to:kA,sequence:xA,random:LA,time:SA,clientTime:OA}=EA;return{From_Account:RA,To_Account:kA,MsgSeq:xA,MsgRandom:LA,MsgTime:SA,MsgClientTime:OA}}),iA={Peer_Account:P,C2CMsgInfo:W};return M.buildAndSendPacket({servcmd:"openim.c2c_msg_read_receipt",data:iA})})}(E):yield function(D){return pA(this,void 0,void 0,function*(){const{common:M,constants:T}=Us.core,P={GroupId:D[0].conversationID.replace(T.OuterConstant.CONV_GROUP,""),MsgSeqList:D.map(W=>({MsgSeq:W.sequence}))};return M.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_receipt",data:P})})}(E),{code:0,data:{}}}catch(m){const{errorCode:D,errorInfo:M}=m;throw new g.ChatError({code:D,message:M,moreMessage:`peerAccount:${(n=E?.[0])===null||n===void 0?void 0:n.conversationID}`})}})}getMessageReadReceiptList(s){return pA(this,void 0,void 0,function*(){const{common:n,constants:g}=this._core;try{const{conversationType:u}=s[0];if(u===g.OuterConstant.CONV_GROUP){const E=this._filterValidMessageSendByMe(s);if(E?.length>0){const m=yield function(M){return pA(this,void 0,void 0,function*(){const{common:T,constants:P}=Us.core,W={GroupId:M[0].conversationID.replace(P.OuterConstant.CONV_GROUP,""),MsgSeqList:M.map(iA=>({MsgSeq:iA.sequence}))};return T.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt",data:W})})}(E),{GroupMsgReceiptList:D}=m||{};this._updateGroupMessagesReadReceiptInfo({messageList:s,readReceiptList:D})}}return{code:0,data:{messageList:s}}}catch(u){const{errorCode:E,errorInfo:m}=u;throw new n.ChatError({code:E,message:m})}})}getGroupMessageReadMemberList(s){return pA(this,void 0,void 0,function*(){const{constants:n,common:g}=this._core,{message:u,filter:E=kE.READ,cursor:m=""}=s,{conversationID:D,sequence:M,ID:T}=u,P=D.replace(n.OuterConstant.CONV_GROUP,""),W=s.count>=100?100:s.count;try{const iA=yield function(EA){return pA(this,void 0,void 0,function*(){const{sequence:RA,groupID:kA,filter:xA,cursor:LA,count:SA}=EA,OA={MsgSeq:RA,GroupId:kA,Filter:xA,Cursor:LA,Num:SA};return Us.core.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt_detail",data:OA})})}({groupID:P,sequence:M,filter:E,cursor:m,count:W});if(iA){const{Cursor:EA,IsFinish:RA,UnreadList:kA,ReadList:xA}=iA,LA={cursor:EA,isCompleted:RA===1,messageID:T,unreadUserIDList:[],readUserIDList:[]};return E===kE.READ?LA.readUserIDList=xA.map(SA=>SA.Read_Account):E===kE.UNREAD&&(LA.unreadUserIDList=kA.map(SA=>SA.Unread_Account)),{code:0,data:LA}}}catch(iA){const{errorCode:EA,errorInfo:RA}=iA;throw new g.ChatError({code:EA,message:RA})}})}_handleC2CMessageReadReceipt(s){const n=[],{constants:g,helper:u}=this._core,{C2cMsgInfo:E,PeerReadTime:m,Peer_Account:D}=s;if(u.isEmpty(E))return;const M=`${g.OuterConstant.CONV_C2C}${D}`;E?.forEach(T=>{const{TinyId:P,MsgClientTime:W,MsgRandom:iA}=T,EA=`${P}-${W}-${iA}`,RA=_c({conversationID:M,messageID:EA});RA&&!RA.readReceiptInfo.isPeerRead&&(RA.readReceiptInfo.isPeerRead=!0,RA.readReceiptInfo.timestamp=m,n.push({userID:D,messageID:EA,isPeerRead:!0,timestamp:m}))}),this._emitReadReceiptEventIfNeed(n)}_updateGroupMessagesReadReceiptInfo(s){const{messageList:n,readReceiptList:g}=s,u=new Map;n.forEach(E=>{u.set(E.sequence,E)}),g?.forEach(E=>{if(E.Code===0){const{MsgSeq:m,ReadNum:D,UnreadNum:M}=E,T=u.get(m);T&&(T.readReceiptInfo.readCount=D,T.readReceiptInfo.unreadCount=M)}})}_handleGroupMessageReadReceipt(s){const n=[],{constants:g}=this._core,{GroupTips:u}=s;u.forEach(E=>{const{MsgBody:{GroupMsgReceiptList:m},GroupInfo:{GroupId:D}}=E,M=`${g.OuterConstant.CONV_GROUP}${D}`;m?.forEach(T=>{const{TinyId:P,MsgClientTime:W,MsgRandom:iA,ReadNum:EA,UnreadNum:RA}=T,kA=`${P}-${W}-${iA}`,xA=_c({conversationID:M,messageID:kA}),LA={groupID:D,messageID:kA,readCount:0,unreadCount:0};xA&&(typeof EA=="number"&&(xA.readReceiptInfo.readCount=EA,LA.readCount=EA),typeof RA=="number"&&(xA.readReceiptInfo.unreadCount=RA,LA.unreadCount=RA),n.push(LA))})}),this._emitReadReceiptEventIfNeed(n)}_emitReadReceiptEventIfNeed(s){const{notificationCenter:n,OuterEvent:g}=this._core;s.length>0&&n.emitOuterEvent(g.MESSAGE_READ_RECEIPT_RECEIVED,{name:g.MESSAGE_READ_RECEIPT_RECEIVED,data:s})}_filterValidMessageSendByOther(s){return this._filterNeedReadReceiptMessages(s).filter(n=>{const{from:g}=n;return g!==this._core.common.getCurrentUserID()})}_filterValidMessageSendByMe(s){const{OuterConstant:n}=this._core.constants;return this._filterNeedReadReceiptMessages(s).filter(g=>{const{from:u,status:E}=g;return u===this._core.common.getCurrentUserID()&&E===n.MessageStatus.SUCCESS})}_filterNeedReadReceiptMessages(s){return s.filter(n=>n.needReadReceipt===!0)}dispose(){const{InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:n,GROUP_MESSAGE_READ_RECEIPT:g},notificationCenter:u}=this._core;u.unSubscribeInnerEvent(s,n,this._handleC2CMessageReadReceipt,this),u.unSubscribeInnerEvent(s,g,this._handleGroupMessageReadReceipt,this)}};function eu(s,n,g){return pA(this,void 0,void 0,function*(){const{common:{buildAndSendPacket:u}}=Us.core,{from:E,to:m,clientSequence:D,random:M,time:T}=s;return u({servcmd:"openim_msg_ext_http_svc.set_key_values",data:{From_Account:E,To_Account:m,MsgKey:`${D}_${M}_${T}`,OperateType:g,ExtensionList:n}})})}function Pu(s,n,g){return pA(this,void 0,void 0,function*(){const{common:{buildAndSendPacket:u}}=Us.core,{to:E,sequence:m}=s;return u({servcmd:"openim_msg_ext_http_svc.group_set_key_values",data:{GroupId:E,MsgSeq:m,OperateType:g,ExtensionList:n}})})}var Gc=new class{constructor(){this._messageExtensionsMap=new Map,this._extensionsLatestSequenceMap=new Map,this._completedFetchExtensions=new Set}init(s){this._core=s;const{notificationCenter:n,helper:{registerApi:g},InnerEvent:{MESSAGE_PUSH:u,LOGOUT:E},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:m}}=s;g({apiName:"setMessageExtensions",context:this}),g({apiName:"getMessageExtensions",context:this}),g({apiName:"deleteMessageExtensions",context:this}),n.subscribeInnerEvent(u,m,this._handleMessageExtensionsNotify,this),n.subscribeInnerEvent(E,this.reset,this)}setMessageExtensions(s,n){return pA(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("setMessageExtensions");const{constants:{OuterConstant:g},ssoLog:u}=this._core,{ID:E,conversationID:m,sequence:D,time:M,conversationType:T}=s;let P=n;n.length>20&&(P=n.slice(0,20),u.warn("setMessageExtensions","the length of extensions cannot exceed 20"));const W=this._generateServerExtensions(s,P),iA=`convID:${m} messageID:${E} sequence:${D} time:${M} count:${P.length}`;try{let EA;if(T===g.CONV_C2C?EA=yield eu(s,W,kl):T===g.CONV_GROUP&&(EA=yield Pu(s,W,kl)),EA){const{resultList:RA,successCount:kA,failureCount:xA}=this._handleModifyMessageExtensions(s,EA);return{code:0,data:{extensions:RA},successLog:{message:`${iA} successCount:${kA} failCount:${xA}`}}}return{code:0,data:{extensions:[]}}}catch(EA){const{errorCode:RA}=EA;throw new this._core.helper.ChatError({functionName:"setMessageExtensions",code:RA,moreMessage:iA})}})}getMessageExtensions(s){return pA(this,void 0,void 0,function*(){const{utils:{isUndefined:n}}=this._core;this._validateMessageExtensionBusinessCapability("getMessageExtensions");const{conversationID:g,ID:u,sequence:E,time:m}=s,D=`convID:${g} messageID:${u} sequence:${E} time:${m}`;try{let M;this._completedFetchExtensions.has(u)&&(M=this._extensionsLatestSequenceMap.get(u));const T=yield this._fetchMessageExtensions(s,M);return n(M)&&T.length>1&&this._completedFetchExtensions.add(u),{code:0,data:{extensions:T},successLog:{message:D}}}catch(M){const{errorCode:T,errorInfo:P=""}=M||{};throw new this._core.common.ChatError({code:T,message:P,moreMessage:D})}})}deleteMessageExtensions(s,n){return pA(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("deleteMessageExtensions");const{utils:{isEmpty:g},constants:{OuterConstant:u}}=this._core,{conversationType:E,conversationID:m,sequence:D,ID:M,time:T}=s;let P=Ug;const W=[];g(n)||(P=Ll,n?.forEach(RA=>{W.push({key:RA,value:"",seq:0})}));const iA=`convID:${m} messageID:${M} sequence:${D} time:${T} operateType:${P}`,EA=this._generateServerExtensions(s,W);try{let RA;if(E===u.CONV_C2C?RA=yield eu(s,EA,P):E===u.CONV_GROUP&&(RA=yield Pu(s,EA,P)),RA){const{resultList:kA,successCount:xA,failureCount:LA}=this._handleModifyMessageExtensions(s,RA);return{code:0,data:{extensions:kA},successLog:{message:`${iA}successCount:${xA} failCount:${LA}`}}}return{code:0,data:{extensions:[]}}}catch(RA){const{errorCode:kA}=RA;throw new this._core.helper.ChatError({functionName:"deleteMessageExtensions",code:kA,moreMessage:iA})}})}reset(){this._messageExtensionsMap.clear(),this._extensionsLatestSequenceMap.clear(),this._completedFetchExtensions.clear()}dispose(){this.reset();const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:n,LOGOUT:g},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:u}}=this._core;s.unSubscribeInnerEvent(n,u,this._handleMessageExtensionsNotify,this),s.subscribeInnerEvent(g,this.reset,this)}_handleModifyMessageExtensions(s,n){const{ID:g}=s,{Seq:u}=n,E=n.ExtensionList||[],m=[];let D=0,M=0,T=[];return E.forEach(P=>{const{ErrorCode:W,Extension:iA}=P,{Key:EA,Value:RA,Seq:kA}=iA;m.push({code:W,key:EA,value:RA}),W===0?D++:M++,T.push({key:EA,value:RA,seq:kA})}),this._extensionsLatestSequenceMap.set(g,u),T.length>0&&this._updateLocalExtensions(s.ID,T),{resultList:m,successCount:D,failureCount:M}}_updateLocalExtensions(s,n){this._messageExtensionsMap.has(s)||this._messageExtensionsMap.set(s,new Map);const g=this._messageExtensionsMap.get(s);n?.forEach(u=>{const{key:E,seq:m,value:D=""}=u;g?.set(E,{value:D,seq:m})})}_fetchMessageExtensions(s,n){return pA(this,void 0,void 0,function*(){const{constants:{OuterConstant:g},utils:{isEmpty:u}}=this._core;try{let E;const{conversationType:m,ID:D}=s;if(m===g.CONV_C2C?E=yield function(M,T){const{common:{buildAndSendPacket:P}}=Us.core,{from:W,to:iA,clientSequence:EA,random:RA,time:kA}=M;return P({servcmd:"openim_msg_ext_http_svc.get_key_values",data:{From_Account:W,To_Account:iA,MsgKey:`${EA}_${RA}_${kA}`,StartSeq:T}})}(s,n):m===g.CONV_GROUP&&(E=yield function(M,T){const{common:{buildAndSendPacket:P}}=Us.core,{to:W,sequence:iA}=M;return P({servcmd:"openim_msg_ext_http_svc.group_get_key_values",data:{GroupId:W,MsgSeq:iA,StartSeq:T}})}(s,n)),E){const{LatestSeq:M,ClearSeq:T,CompleteFlag:P}=E,W=(E.ExtensionList||[]).map(EA=>({key:EA.Key,value:EA.Value,seq:EA.Seq}));if(this._updateLocalExtensions(D,W),this._clearLocationExtensions(D,T),this._extensionsLatestSequenceMap.set(D,M),P!==1){const EA=W[W.length-1].seq+1;return this._fetchMessageExtensions(s,EA)}const iA=[];if(this._messageExtensionsMap.has(D)){const EA=this._messageExtensionsMap.get(D);EA?.forEach((RA,kA)=>{const{value:xA}=RA;u(xA)||iA.push({key:kA,value:xA})})}return iA}}catch(E){throw E}})}_clearLocationExtensions(s,n){if(!(n<=0)&&this._messageExtensionsMap.has(s)){const g=this._messageExtensionsMap.get(s);g?.forEach((u,E)=>{u.seq<=n&&g.delete(E)})}}_generateServerExtensions(s,n){const{ID:g}=s;if(this._messageExtensionsMap.has(g)){const u=this._messageExtensionsMap.get(g);return n.map(E=>{var m;const{key:D,value:M}=E;let T=0;return u?.has(D)&&(T=(m=u.get(D))===null||m===void 0?void 0:m.seq),{Key:D,Value:M,Seq:T}})}return n.map(u=>({Key:u.key,Value:u.value,Seq:0}))}_validateMessageExtensionBusinessCapability(s){const{helper:n,constants:g}=this._core;if(!n.checkBusinessCapabilityBits(hC))throw new n.ChatError({functionName:s,code:g.ERROR_CODE.NO_USE,replacement1:s})}_handleMessageExtensionsNotify(s){const{SetKVInfo:n,DeleteKVInfo:g,ClearKVInfo:u,MsgOptType:E,TinyId:m,MsgLastSeq:D,ExtensionC2cMsgInfo:M,ExtensionGroupMsgInfo:T}=s?.MsgExtensionNotify||{},P=M||T||{},{MsgClientTime:W,MsgRandom:iA}=P,EA=`${m}-${W}-${iA}`;this._extensionsLatestSequenceMap.set(EA,D),E===kl?this._handleMessageExtensionsUpdated({messageID:EA,updateMessageExtensionsInfo:n}):E===Ll?this._handleMessageExtensionsDeleted({messageID:EA,deleteMessageExtensionsInfo:g}):E===Ug&&this._handleMessageExtensionsCleared({messageID:EA,clearMessageExtensionsInfo:u})}_handleMessageExtensionsUpdated(s){const{notificationCenter:n,OuterEvent:g}=this._core,{messageID:u,updateMessageExtensionsInfo:E=[]}=s,m=[];E.forEach(D=>{const{MsgKeyValue:M=[]}=D,T=M.map(P=>(m.push({key:P.Key,value:P.Value}),{key:P.Key,value:P.Value,seq:P.Seq}));this._updateLocalExtensions(u,T)}),n.emitOuterEvent(g.MESSAGE_EXTENSIONS_UPDATED,{name:g.MESSAGE_EXTENSIONS_UPDATED,data:{messageID:u,extensions:m}})}_handleMessageExtensionsDeleted(s){const{notificationCenter:n,OuterEvent:g}=this._core,{messageID:u,deleteMessageExtensionsInfo:E=[]}=s,m=[];E.forEach(D=>{const{MsgKeyValue:M=[]}=D,T=M.map(P=>(m.push(P.Key),{key:P.Key,seq:P.Seq}));this._updateLocalExtensions(u,T)}),n.emitOuterEvent(g.MESSAGE_EXTENSIONS_DELETED,{name:g.MESSAGE_EXTENSIONS_DELETED,data:{messageID:u,keyList:m}})}_handleMessageExtensionsCleared(s){const{notificationCenter:n,OuterEvent:{MESSAGE_EXTENSIONS_DELETED:g},utils:{isEmpty:u}}=this._core,{messageID:E,clearMessageExtensionsInfo:m=[]}=s,D=[];m.forEach(M=>{const{ClearMsgSeq:T}=M;this._messageExtensionsMap.has(E)&&(this._messageExtensionsMap.get(E)||[]).forEach((P,W)=>{P.seq<=T&&!u(P.value)&&D.push(W)}),this._clearLocationExtensions(E,T)}),n.emitOuterEvent(g,{name:g,data:{messageID:E,keyList:D}})}};const pI={key:"message",required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>{const{constants:{OuterConstant:n}}=Us.core;return s.status!==n.MessageStatus.SUCCESS?"message is not success":s.isSupportExtension===!0||"message is not support extension"}},sl={setMessageExtensions:[pI,{key:"extensions",required:!0,rules:["array"],allowEmpty:!1}],getMessageExtensions:[pI],deleteMessageExtensions:[pI]},nl=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({deleteMessage:[{required:!0,rules:["array"],allowEmpty:!1}],revokeMessage:[{required:!0,rules:["object"],allowEmpty:!1}],resendMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"options",required:!1,rules:["object"],allowEmpty:!1}],getMessageList:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},nextReqMessageID:{required:!1,rules:["string"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}},getMessageListHopping:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},sequence:{required:!1,rules:["number"],allowEmpty:!0},direction:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}},createTextAtMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>{const n=function(g){var u;return typeof g?.text!="string"||typeof g.text=="string"&&((u=g?.text)===null||u===void 0?void 0:u.length)===0?"payload.text is invalid.":!0}(s);return n!==!0?n:!(s?.atUserList&&!Array.isArray(s.atUserList))||"atUserList should be an array or undefind."}}},findMessage:[{required:!0,rules:["string"],allowEmpty:!1}],translateText:{sourceTextList:{required:!0,rules:["array"],allowEmpty:!1},sourceLanguage:{required:!0,rules:["string"],allowEmpty:!1},targetLanguage:{required:!0,rules:["string"],allowEmpty:!1}},createForwardMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!(!s.startsWith("C2C")&&!s.startsWith("GROUP"))||"conversationType is invalid."},payload:{required:!0,rules:["object"],allowEmpty:!1}},createLocationMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>{const{utils:{isString:n,isNumber:g}}=Us.core;return n(s?.description)?g(s?.longitude)?!!g(s?.latitude)||"payload.latitude must be a number.":"payload.longitude must be a number.":"payload.description must be a string."}}}},{addMessageReaction:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"reactionID",required:!0,rules:["string"],allowEmpty:!1}],removeMessageReaction:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"reactionID",required:!0,rules:["string"],allowEmpty:!1}],getMessageReactions:{messageList:{required:!0,rules:["array"],allowEmpty:!1},maxUserCountPerReaction:{required:!1,rules:["number"],allowEmpty:!0,customValidator:s=>typeof s!="number"?"maxUserCountPerReaction is invalid.":!(s<0||s>10)||"maxUserCountPerReaction should between [0, 10]."}},getAllUserListOfMessageReaction:{message:{required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>s.status==="success"||"message is invalid."},reactionID:{required:!0,rules:["string"],allowEmpty:!1},nextSeq:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}}}),{sendMessageReadReceipt:[{required:!0,rules:["array"],allowEmpty:!1}],getMessageReadReceiptList:[{required:!0,rules:["array"],allowEmpty:!1}],getGroupMessageReadMemberList:{message:{required:!0,rules:["object"],allowEmpty:!1},filter:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0},cursor:{required:!1,rules:["string"],allowEmpty:!0}}}),sl),{pinGroupMessage:{groupID:{required:!0,rules:["string"],allowEmpty:!1},message:{required:!0,rules:["object"],allowEmpty:!1},isPinned:{required:!0,rules:["boolean"],allowEmpty:!1}},getPinnedGroupMessageList:[{key:"groupID",required:!0,rules:["string"],allowEmpty:!1}]}),{createQuoteMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"quotedMessage",required:!0,rules:["object"],allowEmpty:!1}]}),xa=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({deleteMessage:!0,revokeMessage:!0,resendMessage:!0,getMessageList:!0,getMessageListHopping:!0,createTextAtMessage:!0,findMessage:!0,translateText:!0,createForwardMessage:!0,createLocationMessage:!0},{addMessageReaction:!0,removeMessageReaction:!0,getMessageReactions:!0,getAllUserListOfMessageReaction:!0}),{sendMessageReadReceipt:!0,getMessageReadReceiptList:!0,getGroupMessageReadMemberList:!0}),{setMessageExtensions:!0,getMessageExtensions:!0,deleteMessageExtensions:!0}),{pinGroupMessage:!0,getPinnedGroupMessageList:!0}),{createQuoteMessage:!0});class FE{constructor(n){this._core=n}deleteMessage(n){return pA(this,void 0,void 0,function*(){const{to:g,messageIdentifiers:u}=n,E={From_Account:this._core.common.getCurrentUserID(),To_Account:g,MsgKeyList:u};return this._core.common.buildAndSendPacket({servcmd:"openim.delete_c2c_msg_ramble",data:E})})}revokeMessage(n){return pA(this,void 0,void 0,function*(){const{to:g,from:u,sequence:E,time:m,random:D}=n,M={MsgInfo:{From_Account:u,To_Account:g,MsgSeq:E,MsgRandom:D,MsgTimeStamp:m}};return this._core.common.buildAndSendPacket({servcmd:"openim.msgwithdraw",data:M})})}}class ra{constructor(n){this._core=n}deleteMessage(n){return pA(this,void 0,void 0,function*(){const{to:g,messageIdentifiers:u}=n,E={GroupId:g,Deleter_Account:this._core.common.getCurrentUserID(),Seqs:u};return this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_ramble_msg_by_seq",data:E})})}revokeMessage(n){return pA(this,void 0,void 0,function*(){const{to:g,sequence:u}=n,E={GroupId:g,MsgSeqList:[{MsgSeq:u}]};return this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_recall",data:E})})}}const Mn=2116;class kr{constructor(n){this._core=n}generateRevokeMessage(n){const{conversationID:g,sequence:u,random:E,tinyID:m,clientTime:D,revokeReason:M,revoker:T}=n;let P={};const{messageDataHandler:W}=this._core.message;return P=W.revokeMessage({conversationID:g,sequence:u,random:E,revoker:T}),P||(P={conversationID:g,sequence:u},m&&D&&E&&(P.ID=`${m}-${D}-${E}`)),P.revoker=T,P.revokeReason=M,P.revokerInfo={userID:T,nick:"",avatar:""},P}updateRevokerInfo(n){return pA(this,void 0,void 0,function*(){const g=n.map(u=>u.revoker);try{const u=yield this._fetchUserInfos(g);u&&n.forEach(E=>{const{revoker:m}=E;u[m]&&(E.revokerInfo.nick=u[m].nick||"",E.revokerInfo.avatar=u[m].avatar||"",E.revokerInfo.userID=m)})}catch(u){console.debug(u)}})}_fetchUserInfos(n){return pA(this,void 0,void 0,function*(){var g,u;const E=yield(g=this._core.user.userProfile)===null||g===void 0?void 0:g.getUserProfile({userIDList:n});return E?.data?(u=E.data)===null||u===void 0?void 0:u.reduce((m,{userID:D,nick:M,avatar:T})=>(m[D]={nick:M||"",avatar:T||""},m),{}):null})}}var rl=new class{constructor(){this._core=null,this._c2cMessageAction=null,this._groupMessageAction=null}init(s){this._core=s,this._groupMessageAction=new ra(s),this._c2cMessageAction=new FE(s),this._messageHelper=new kr(s);const{helper:n}=s;n.registerApi({apiName:"deleteMessage",context:this}),n.registerApi({apiName:"revokeMessage",context:this}),n.registerApi({apiName:"resendMessage",context:this}),n.registerApi({apiName:"findMessage",context:this}),n.registerApi({apiName:"createQuoteMessage",context:this})}deleteMessage(s){return pA(this,void 0,void 0,function*(){let n=[],g=[];const{conversationID:u,conversationType:E}=s[0],m=u.replace(E,"");if(E==="@TIM#SYSTEM")throw new this._core.helper.ChatError({code:Mn});if(s.forEach(D=>{const{conversationID:M,conversationType:T,status:P,_onlineOnlyFlag:W,sequence:iA,random:EA,time:RA}=D||{};if(P==="success"&&M===u&&T===E){if(!W){const kA=T==="C2C"?`${iA}_${EA}_${RA}`:String(iA);n.push(kA)}g.push(D)}}),n.length===0)return this._handleDeleteMessageSuccess(g),{code:0,data:{messageList:g}};n.length>30&&(n=n.slice(0,30),g=g.slice(0,30));try{return E==="C2C"?yield this._c2cMessageAction.deleteMessage({to:m,messageIdentifiers:n}):yield this._groupMessageAction.deleteMessage({to:m,messageIdentifiers:n}),this._handleDeleteMessageSuccess(g),{code:0,data:{messageList:g}}}catch(D){const{utils:{safeStringify:M}}=this._core,{errorCode:T,errorInfo:P}=D;throw new this._core.helper.ChatError({functionName:"deleteMessage",code:T,message:P,moreMessage:`messageIdentifiers: ${M(n)}`})}})}revokeMessage(s){return pA(this,void 0,void 0,function*(){var n;const{conversationType:g,isRevoked:u,ID:E,type:m,from:D,to:M}=s;let T=null;const P=`type:${m} from:${D} to:${M} ID:${E}`;if(g==="@TIM#SYSTEM")throw new this._core.helper.ChatError({message:"system message cannot be revoked"});if(u)throw new this._core.helper.ChatError({message:"message has been revoked",moreMessage:P});try{if(T=g==="C2C"?yield this._c2cMessageAction.revokeMessage(s):yield this._groupMessageAction.revokeMessage(s),T){const{RecallRetList:W}=T,iA=((n=W?.[0])===null||n===void 0?void 0:n.RetCode)||0;if(iA!==0)throw new this._core.helper.ChatError({code:iA,moreMessage:P});return s.isRevoked=!0,yield this._handleRevokeMessageSuccess(s),{code:0,data:{message:s},successLog:{message:P}}}}catch(W){const{errorCode:iA}=W;throw new this._core.helper.ChatError({functionName:"revokeMessage",code:iA,moreMessage:P})}})}resendMessage(s,n){return pA(this,void 0,void 0,function*(){var g,u;return s.isResend=!0,s.status="unSend",(u=(g=this._core)===null||g===void 0?void 0:g.apiMap)===null||u===void 0?void 0:u.sendMessage(s,n)})}findMessage(s){return this._core.message.messageDataHandler.findMessage(s)}createQuoteMessage(s,n){const{ID:g,time:u,sequence:E}=n;return s.quoteInfo={msgID:g,messageTime:u,messageSequence:E},s}_handleDeleteMessageSuccess(s){if(s.length===0)return;const{message:{messageDataHandler:n},common:{isTopic:g},notificationCenter:u,InnerEvent:E}=this._core;s.forEach(D=>{D.isDeleted=!0;const M=n.getLocalMessageList(D.conversationID);M?.forEach(T=>{T.ID===D.ID&&(T.isDeleted=!0)})});const{conversationID:m=""}=s[0];g(m)?u.emitInnerEvent(E.TOPIC_MESSAGE_DELETED,m):u.emitInnerEvent(E.MESSAGE_DELETED,m)}_handleRevokeMessageSuccess(s){return pA(this,void 0,void 0,function*(){var n;const g=(n=this._core.store.get("login"))===null||n===void 0?void 0:n.userId,{conversationID:u,sequence:E,random:m}=s;this._core.message.messageDataHandler.revokeMessage({conversationID:u,sequence:E,random:m,revoker:g}),yield this._messageHelper.updateRevokerInfo([s])})}};class Ul{static parseServerPushElement(n){const{MsgContent:g={}}=n,{Index:u,Data:E}=g;return new Ul({index:u,data:E})}constructor(n){this.type=Vr.MSG_FACE;const{index:g,data:u}=n;this.content={index:g,data:u}}validateBeforeSend(){var n,g;return typeof((n=this.content)===null||n===void 0?void 0:n.index)=="number"&&typeof((g=this.content)===null||g===void 0?void 0:g.data)=="string"?{isValid:!0}:{isValid:!1,error:{message:"content is invalid"}}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},u=g?this.payload:this.content,{index:E,data:m}=u;return{MsgType:this.type,MsgContent:{Index:E,Data:m}}}}class bc{static parseServerPushElement(n){const{MsgContent:g={}}=n,{Desc:u,Longitude:E,Latitude:m}=g;return new bc({description:u,longitude:E,latitude:m})}constructor(n){this.type=Vr.MSG_LOCATION;const{description:g,longitude:u,latitude:E}=n;this.content={description:g,longitude:u,latitude:E}}validateBeforeSend(){return{isValid:!0}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},u=g?this.payload:this.content,{description:E,longitude:m,latitude:D}=u;return{MsgType:this.type,MsgContent:{Desc:E,Longitude:m,Latitude:D}}}}class OE{static parseServerPushElement(n){const{MsgContent:g={}}=n,{StreamMsgID:u,CompatibleText:E,Markdown:m,BinaryData:D,ErrorCode:M,ErrorMsg:T}=g;return new OE({streamMessageID:u,compatibleText:E,markdown:m,binaryData:D,errorCode:M,errorMessage:T})}constructor(n){this.type=Vr.MSG_STREAM,this.content={streamMessageID:"",compatibleText:"",errorCode:0,errorMessage:"",isStreamEnded:!1},this._chunks=[],this._latestIndex=0;const{streamMessageID:g,compatibleText:u,markdown:E,binaryData:m,errorCode:D=0,errorMessage:M="",isStreamEnded:T=!1,chunks:P=[],latestIndex:W=0}=n;this.content.streamMessageID=g,this.content.compatibleText=u,this.content.markdown=E,this.content.binaryData=m,this.content.errorCode=D,this.content.errorMessage=M,this.content.isStreamEnded=T,this.content.chunks=P,this.content.latestIndex=W}updateChunks(n){if(!n||n.length===0)return;const g=n.sort((m,D)=>m.index-D.index),u=this._getMaxRevokedChunkIndex(g);u>=0&&(this._chunks=[],this._latestIndex=u,this._updateContent());const E=this._getValidChunks(g);if(E.length!==0&&(this._mergeAndSortChunks(E),this._chunks.length>0)){const m=this._chunks[this._chunks.length-1];this._latestIndex=m.index,this._updateContent(),this.content.isStreamEnded=m.isLast}}getLatestIndex(){return this._latestIndex}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},u=g?this.payload:this.content,{streamMessageID:E,chunks:m}=u,D=m?.map(M=>({EventType:M.eventType||"data",Index:M.index,Markdown:M.markdown,IsLast:M.isLast}));return{MsgType:this.type,MsgContent:{StreamMsgID:E,Chunks:D}}}validateBeforeSend(){var n,g;return((g=(n=this.content)===null||n===void 0?void 0:n.chunks)===null||g===void 0?void 0:g.length)>0?{isValid:!0}:{isValid:!1,error:{message:"content is invalid"}}}_filterContinuousChunks(n,g){if(n.length===0)return[];const u=[];let E=g;for(const m of n){if(m.index>E)break;m.index===E&&(u.push(m),E++)}return u}_mergeAndSortChunks(n){const g=new Map;this._chunks.forEach(u=>{g.set(u.index,u)}),n.forEach(u=>{g.set(u.index,u)}),this._chunks=Array.from(g.values()).sort((u,E)=>u.index-E.index)}_updateContent(){this.content.markdown=this._chunks.map(g=>g.markdown).join("");const n=this._chunks.map(g=>g.binaryData).filter(g=>g?.length>0);if(n.length===0)this.content.binaryData=new Uint8Array(0);else if(n.length===1)this.content.binaryData=n[0];else{const g=n.reduce((m,D)=>m+D.length,0),u=new Uint8Array(g);let E=0;for(const m of n)u.set(m,E),E+=m.length;this.content.binaryData=u}}_getMaxRevokedChunkIndex(n){let g=-1;for(let u=0;ug&&(g=E.index)}return g}_getValidChunks(n){const g=n.filter(u=>u.eventType===Nc.DATA&&u.index>this._latestIndex);return this._filterContinuousChunks(g,this._latestIndex+1)}}var kc=new class{init(s){this._core=s,s.message.messageFactory.registerElementClass(Vr.MSG_FACE,Ul),s.message.messageFactory.registerElementClass(Vr.MSG_LOCATION,bc),s.message.messageFactory.registerElementClass(Vr.MSG_STREAM,OE),s.helper.registerApi({apiName:"createFaceMessage",context:this}),s.helper.registerApi({apiName:"createTextAtMessage",context:this}),s.helper.registerApi({apiName:"createForwardMessage",context:this}),s.helper.registerApi({apiName:"createLocationMessage",context:this})}createFaceMessage(s){if(!s)return null;const{index:n,data:g}=s?.payload||{},u=new Ul({index:n,data:g}),E=this._core.common.getCurrentUserID(),m=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:E}));return m.setElement(u),m}createTextAtMessage(s){const{atUserList:n}=s?.payload||{},g=this._core.apiMap.createTextMessage(s),{OuterConstant:u}=this._core;if(!g)return null;if(Array.isArray(n)){const E=[],m=[];n.forEach(D=>{D!==u.MSG_AT_ALL?(E.push({GroupAtAllFlag:ch,GroupAt_Account:D}),m.push(D)):(E.push({GroupAtAllFlag:ao}),m.push(u.MSG_AT_ALL))}),g._groupAtInfoList=E,g.atUserList=m}return g}createForwardMessage(s){const{helper:n,OuterConstant:g}=this._core,{to:u,conversationType:E,priority:m,payload:D,needReadReceipt:M,receiverList:T,cloudCustomData:P="",isSupportExtension:W=!1}=s;if(!Array.isArray(D._elements))throw new n.ChatError({functionName:"createForwardMessage",code:2454});if(D.type===g.MSG_GRP_TIP)throw new n.ChatError({functionName:"createForwardMessage",code:2453});const iA=this._core.common.getCurrentUserID(),EA=this._core.message.messageFactory.createMessage({to:u,from:iA,conversationType:E,isPlaceMessage:0,priority:m,payload:D,needReadReceipt:M,isSupportExtension:W,cloudCustomData:P,receiverList:T});return EA.setRelayFlag(!0),EA.setElement(D._elements[0]),EA}createLocationMessage(s){if(!s)return null;const{description:n,longitude:g,latitude:u}=s?.payload||{},E=new bc({description:n,longitude:g,latitude:u}),m=this._core.common.getCurrentUserID(),D=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:m}));return D.setElement(E),D}};let xu=class{init(s){this._messageHelper=new kr(s),this._core=s;const{notificationCenter:n,InnerEvent:{MESSAGE_PUSH:g},InnerEventSubType:{C2C_REVOKED_MESSAGE:u},helper:{registerWorkflowStep:E},constants:{WORKFLOW_NAME:m,WORKFLOW_STEP:D}}=s;n.subscribeInnerEvent(g,u,this._handleC2CNotifyMessage,this),E(m.SYNC_SERVER_INFO_AFTER_RE_ONLINE,D.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,this._handleC2CRevokeMessagesFromUnreadMessageSync,this)}_handleC2CNotifyMessage(s){const{C2cNotifyMsgArray:n}=s;n?.forEach(g=>{Object.keys(g).includes("WithdrawC2cMsgNotify")&&this._handleC2CRevokeMessage(g)})}_handleC2CRevokeMessage(s){return pA(this,void 0,void 0,function*(){try{const{WithdrawC2cMsgNotify:{C2cWithdrawInfoArray:n}}=s;yield this._parseAndEmitC2CRevokedMessages(n)}catch(n){console.debug(n)}})}_parseAndEmitC2CRevokedMessages(s){return pA(this,void 0,void 0,function*(){const n=[],{notificationCenter:g,OuterEvent:u,common:{getCurrentUserID:E}}=this._core;s.forEach(m=>{var D;const{MsgRand:M,MsgSeq:T,To_Account:P,From_Account:W,RevokerInfo:{Revoker_Account:iA,Revoke_Reason:EA}}=m,RA=E()===W?`C2C${P}`:`C2C${W}`,kA=((D=m?.RevokerInfo)===null||D===void 0?void 0:D.Reason)||EA,xA=this._messageHelper.generateRevokeMessage({conversationID:RA,sequence:T,random:M,revoker:iA,revokeReason:kA});n.push(xA)}),n.length>0&&(yield this._messageHelper.updateRevokerInfo(n),g.emitOuterEvent(u.MESSAGE_REVOKED,{name:u.MESSAGE_REVOKED,data:n}))})}_handleC2CRevokeMessagesFromUnreadMessageSync(s){return pA(this,void 0,void 0,function*(){const{revokedMessageList:n}=s.result;yield this._parseAndEmitC2CRevokedMessages(n)})}dispose(){const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:n},InnerEventSubType:{C2C_REVOKED_MESSAGE:g}}=this._core;s.unSubscribeInnerEvent(n,g,this._handleC2CNotifyMessage,this)}},pC=class{init(s){this._messageHelper=new kr(s),this._core=s;const{notificationCenter:n,InnerEvent:{MESSAGE_PUSH:g},InnerEventSubType:{GROUP_MESSAGE_REVOKED:u}}=s;n.subscribeInnerEvent(g,u,this._handleGroupNotifyMessage,this)}_handleGroupNotifyMessage(s){const{GroupTips:n}=s;n?.forEach(g=>{var u;Array.isArray((u=g?.MsgBody)===null||u===void 0?void 0:u.GroupWithdrawInfoArray)&&this._handleGroupRevokeMessage(g)})}_handleGroupRevokeMessage(s){return pA(this,void 0,void 0,function*(){try{const{RevokerInfo:n,MsgBody:{GroupWithdrawInfoArray:g},GroupInfo:u}=s,E=[],m=[],{notificationCenter:D,OuterEvent:M,utils:{isEmpty:T},common:{isCommunity:P}}=this._core;let W=!1;u&&(W=P({groupID:u.GroupId})||!T(u.TopicId)),g.forEach(iA=>{const{Random:EA,MsgSeq:RA,GroupId:kA,MsgClientTime:xA,TinyId:LA,TopicId:SA,RevokerInfo:{Revoker_Account:OA=n?.Revoker_Account||"",Reason:JA=n?.Reason||""}}=iA,ae=SA?`GROUP${SA}`:`GROUP${kA}`,se=this._messageHelper.generateRevokeMessage({conversationID:ae,sequence:RA,random:EA,tinyID:LA,clientTime:xA,revoker:OA,revokeReason:JA});W?(se.revokerInfo.nick=u.From_AccountNick,se.revokerInfo.avatar=u.From_AccountHeadurl,E.push(se)):m.push(se)}),m.length>0&&(yield this._messageHelper.updateRevokerInfo(m),E.push(...m)),E.length!==0&&D.emitOuterEvent(M.MESSAGE_REVOKED,{name:M.MESSAGE_REVOKED,data:E})}catch(n){console.debug(n)}})}dispose(){const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:n},InnerEventSubType:{GROUP_MESSAGE_REVOKED:g}}=this._core;s.unSubscribeInnerEvent(n,g,this._handleGroupNotifyMessage,this)}};var tu=new class{constructor(){this._c2cMessageReceiver=new xu,this._groupMessageReceiver=new pC}init(s){this._c2cMessageReceiver.init(s),this._groupMessageReceiver.init(s)}dispose(){this._c2cMessageReceiver.dispose(),this._groupMessageReceiver.dispose()}},lh=new class{constructor(){this._core=null}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"translateText",context:this})}translateText(s){return pA(this,void 0,void 0,function*(){try{const{sourceLanguage:n,sourceTextList:g,targetLanguage:u}=s,E=yield function(m,D){return pA(this,void 0,void 0,function*(){var M,T;const{sourceTextList:P,sourceLanguage:W,targetLanguage:iA}=m,{store:EA,common:RA}=D,kA={SourceText:P,Source:W,Target:iA,FromAccount:(M=EA.get("login"))===null||M===void 0?void 0:M.tinyID,SDKAppID:(T=EA.get("instance"))===null||T===void 0?void 0:T.sdkAppId},xA=yield RA.buildAndSendPacket({servcmd:"im_open_translate.ws_batch_trans_text",data:kA});if(xA){const{CmdErrorCode:LA,TargetText:SA}=xA;return{cmdErrorCode:LA,translatedTextList:SA}}})}({sourceLanguage:n,sourceTextList:g,targetLanguage:u},this._core);if(E){const{cmdErrorCode:{ErrorCode:m,ErrorInfo:D},translatedTextList:M}=E;if(m===0)return{code:0,data:{translatedTextList:M}};throw{errorCode:m,errorInfo:D,message:D}}}catch(n){const{errorCode:g,errorInfo:u}=n||{};throw new this._core.helper.ChatError({functionName:"translateText",code:g,message:u})}})}},Yu=new class{init(s){this._core=s,s.helper.registerApi({apiName:"convertVoiceToText",context:this})}convertVoiceToText(s){return pA(this,void 0,void 0,function*(){var n;const{message:g,language:u=Tc.ZH_PY}=s;let{url:E}=g.payload||{};const m=this._core.common.getCurrentUserID();g.from===m&&g.flow==="out"&&(E=g.payload.remoteAudioUrl),this._validateVoiceFormat(E);const D=((n=QI.exec(E))===null||n===void 0?void 0:n[1])||"mp3",M=BI[u]||$I;try{const T=yield function(P){var W;const{store:iA,common:EA}=Us.core,{url:RA,format:kA,serverLanguageType:xA}=P,LA={BytesUrl:RA,BytesEngServiceType:xA,BytesVoiceFormat:kA,Uint32Sdkappid:(W=iA.get("instance"))===null||W===void 0?void 0:W.sdkAppId,Uint64SourceType:0};return EA.buildAndSendPacket({servcmd:"im_open_speech.ws_sentence_recognition",data:LA})}({url:E,format:D,serverLanguageType:M});if(T){const{CmdErrorCode:P,BytesResult:W}=T;if(P.ErrorCode===0)return{code:0,data:{result:W}};throw{code:P.ErrorCode,message:P.ErrorInfo}}}catch(T){const{code:P,message:W}=T||{};throw new this._core.common.ChatError({functionName:"convertVoiceToText",code:P,message:W})}})}_validateVoiceFormat(s){if(!QI.test(s))throw new this._core.common.ChatError({code:2119})}};class mI{constructor(n){const{constants:g,common:u,utils:E}=Us.core,{CONV_C2C:m,CONV_GROUP:D}=g.OuterConstant,{ID:M,tinyID:T,from:P,to:W,clientTime:iA=u.timeManager.getServerTimeSeconds()||0,random:EA,sequence:RA,cloudCustomData:kA="",nick:xA="",avatar:LA="",clientSequence:SA,conversationType:OA,groupID:JA,_elements:ae,time:se}=n;this.ID=M||`${T}-${iA}-${EA}`,this.messageRandom=EA,this.from=P,this.messageSender=P,this.time=se,this.messageSequence=RA,this.clientSequence=SA||RA,this.clientTime=iA,this.cloudCustomData=kA,this.messageReceiver=W,this.avatar=LA,this.nick=xA;const _i=E.deepCopyWithMethods(ae);_i.forEach(Ti=>{Ti.payload=Ti.content,delete Ti.content}),this.messageBody=_i,M?OA.startsWith(m)?this.receiverUserID=W:OA.startsWith(D)&&(this.receiverGroupID=W):JA?(this.receiverGroupID=JA,this.messageReceiver=JA):W&&(this.receiverUserID=W,this.messageReceiver=W)}transformElementsToServerFormat(){return this.messageBody?Array.isArray(this.messageBody)?this.messageBody.map(n=>n.transformToServerFormat({isMergerMessage:!0})):this.messageBody.transformToServerFormat({isMergerMessage:!0}):null}}class al{static parseServerPushElement(n){const{MsgContent:g}=n,{MsgList:u=[],CompatibleText:E,AbstractList:m,Title:D,PbMsgKey:M,JsonMsgKey:T}=g||{},P=u.map(W=>dr(W));return new al({messageList:P,title:D,abstractList:m,compatibleText:E,pbDownloadKey:M,downloadKey:T})}constructor(n){this.type=Us.core.constants.OuterConstant.MSG_MERGER;const{messageList:g,title:u,abstractList:E,compatibleText:m,pbDownloadKey:D="",downloadKey:M="",version:T=0,layersOverLimit:P=!1}=n,W=[];g.forEach(iA=>{if(iA){const EA=new mI(iA);W.push(EA)}}),this.content={messageList:W,title:u,abstractList:E,compatibleText:m,version:T,downloadKey:M,pbDownloadKey:D,layersOverLimit:P}}validateBeforeSend(){const{isEmpty:n}=Us.core.helper;return n(this.content.messageList)?{isValid:!1,error:{message:"content is invalid"}}:{isValid:!0}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},u=g?this.payload:this.content,{abstractList:E,compatibleText:m,downloadKey:D,layersOverLimit:M,pbDownloadKey:T,title:P,version:W,messageList:iA}=u;return{MsgType:this.type,MsgContent:{AbstractList:E,CompatibleText:m,JsonMsgKey:D,LayersOverLimit:M,PbMsgKey:T,Title:P,Version:W,MsgList:Ac(iA)}}}}var mC=new class{init(s){this._core=s;const{message:n,helper:g,constants:{OuterConstant:u}}=s;n.messageFactory.registerElementClass(u.MSG_MERGER,al),g.registerApi({apiName:"createMergerMessage",context:this}),g.registerApi({apiName:"sendMessage",context:this,matcher:E=>E[0].type===u.MSG_MERGER}),g.registerApi({apiName:"downloadMergerMessage",context:this})}createMergerMessage(s){const{common:n}=this._core;if(!s)return null;const g=new al(s.payload),u=n.getCurrentUserID(),E=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:u}));return E.setRelayFlag(!0),E.setElement(g),E}sendMessage(s,n){return pA(this,void 0,void 0,function*(){var g,u,E;try{const m=function(P){let W="utf-8";Us.core.helper.IN_BROWSER&&document&&(W=document.charset.toLowerCase());let iA,EA=0,RA=0;if(RA=P.length,W==="utf-8"||W==="utf8")for(let kA=0;kA11264){D=this._core.utils.deepCopyWithMethods(s);try{const{JsonMsgKey:P,PbMsgKey:W}=yield function(EA){return pA(this,void 0,void 0,function*(){const{payload:{messageList:RA}}=EA,kA={MsgList:Ac(RA)};return Us.core.common.buildAndSendPacket({servcmd:"im_long_msg.save_relay_json_msg",data:kA})})}(D),{payload:iA}=D;M=new al(Object.assign(Object.assign({},iA),{messageList:[],downloadKey:P,pbDownloadKey:W})),D.setElement(M)}catch(P){console.error(P)}}const{data:{message:T}}=yield(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageSender)===null||E===void 0?void 0:E.sendMessage(D,n);return M&&T.setElement(s._elements),{code:0,data:{message:T}}}catch(m){const{errorCode:D}=m;throw new this._core.helper.ChatError({code:D})}})}downloadMergerMessage(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n}=this._core,g=s.payload,{downloadKey:u,pbDownload:E,type:m,messageList:D}=g,M=Do(g,["downloadKey","pbDownload","type","messageList"]);try{const T=yield function(iA){return pA(this,void 0,void 0,function*(){return Us.core.common.buildAndSendPacket({servcmd:"im_long_msg.get_relay_json_msg",data:{JsonMsgKey:iA}})})}(u),{MsgList:P}=T||{},W=P?.map(iA=>{const EA=dr(iA);return new mI(EA)});return typeof s.isOnlineMessage=="function"?s.setElement({type:s.type,content:Object.assign({messageList:W},M)}):(s.payload.messageList=W,s.payload.downloadKey="",s.payload.pbDownloadKey=""),n.info("downloadMergerMessage",` success downloadKey:${u}`),s}catch(T){const{errorCode:P}=T;throw new this._core.helper.ChatError({functionName:"downloadMergerMessage",code:P,moreMessage:u})}})}},aa=new class{init(s){this._core=s,this._core.helper.registerExperimentalAPI("sendComboMessage",this)}sendComboMessage(s){return pA(this,void 0,void 0,function*(){const{appStore:n,message:g,common:{getCurrentUserID:u},utils:{isArray:E}}=this._core,{GroupId:m,To_Account:D}=s;s.From_Account=s.From_Account||u();let M=null;if(m){M=this._generateGroupMessage(Object.assign(Object.assign({},s),{ToGroupId:m}));const T=n.userStore.getUserProfile(u());M.level=T?.level||0,E(D)&&D.length>0&&(M._receiverList=D)}else D&&(M=this._generateC2CMessage(s));return g.messageSender.sendMessage(M,s)})}_generateC2CMessage(s){const{message:n,OuterConstant:{CONV_C2C:g}}=this._core,u=g,E=n.messageHelper.parseServerPushMessage(s),m=n.messageFactory.createMessage(Object.assign(Object.assign({},E),{conversationType:u,flow:ec.OUT})),{elements:D}=E;return m.setElement(D),m}_generateGroupMessage(s){const{message:n,OuterConstant:{CONV_GROUP:g}}=this._core,u=g,E=n.messageHelper.parseServerGroupMessage(s),m=n.messageFactory.createMessage(Object.assign(Object.assign({},E),{conversationType:u,flow:ec.OUT})),{elements:D}=E;return m.setElement(D),m}},tc=new class{init(s){this._core=s;const{helper:n,notificationCenter:g,InnerEvent:{MESSAGE_PUSH:u},InnerEventSubType:{GROUP_MESSAGE_PINNED:E}}=s;g.subscribeInnerEvent(u,E,this._handleGroupMessagePinned,this),n.registerApi({apiName:"pinGroupMessage",context:this}),n.registerApi({apiName:"getPinnedGroupMessageList",context:this})}pinGroupMessage(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n,common:{isTopic:g},OuterConstant:{GROUP_ID_PREFIX:u},helper:{ChatError:E}}=this._core;let{groupID:m,message:D,isPinned:M}=s;const{sequence:T}=D;try{return yield function(P){return pA(this,void 0,void 0,function*(){const{common:{buildAndSendPacket:W,getCurrentUserID:iA}}=Us.core,{groupID:EA,sequence:RA,isPinned:kA}=P,xA=iA(),LA=kA?"group_open_http_svc.pin_message":"group_open_http_svc.unpin_message",SA={GroupId:EA,MsgSeq:RA};return kA?SA.Pinner_Account=xA:SA.UnPinner_Account=xA,W({servcmd:LA,data:SA})})}({groupID:m,sequence:T,isPinned:M}),{code:0,data:{}}}catch(P){const{errorCode:W,errorInfo:iA}=P||{};throw new E({code:W,message:iA})}})}getPinnedGroupMessageList(s){return pA(this,void 0,void 0,function*(){let n=[];try{const g=yield function(u){return pA(this,void 0,void 0,function*(){const{groupID:E}=u,{common:{buildAndSendPacket:m}}=Us.core;return m({servcmd:"group_open_http_svc.get_pinned_messages",data:{GroupId:E}})})}({groupID:s});if(g){const{PinnedMsgList:u=[]}=g;n=yield this._updatePinnedMessageInfo({serverPinnedMessageList:u,groupID:s})}return{code:0,data:{messageList:n}}}catch(g){throw g}})}_handleGroupMessagePinned(s){const{message:{messageHelper:n,messageFactory:g},notificationCenter:u,OuterEvent:E,OuterConstant:m}=this._core;s.GroupTips.forEach(D=>{const{ToGroupId:M,MsgBody:{PinnedMsg:T,OpType:P,MsgOperatorMemberExtraInfo:W,SdkGroupMessageId:iA}}=D,{UserId:EA,NickName:RA="",ImageUrl:kA=""}=W;let xA=null,LA=!1;if(P===md){LA=!0;const SA=n.parseServerGroupMessage(T);xA=g.createMessage(Object.assign(Object.assign({},SA),{conversationType:m.CONV_GROUP,flow:"in"})),xA.setElement(SA.elements),xA.pinnerInfo={userID:EA,nick:RA,avatar:kA}}else if(P===LE){const{ClientTime:SA,Random:OA,SenderTinyId:JA,ServerTime:ae,MsgSeq:se}=iA;xA={ID:`${JA}-${SA}-${OA}`,sequence:se,random:OA,time:ae,clientTime:SA}}xA&&u.emitOuterEvent(E.PINNED_GROUP_MESSAGE_UPDATED,{name:E.PINNED_GROUP_MESSAGE_UPDATED,data:{groupID:M,message:xA,isPinned:LA,operatorInfo:{userID:EA,nick:RA,avatar:kA}}})})}_findMessageBySequence(s,n){const{message:{messageDataHandler:g}}=this._core;return[...g.getLocalMessageList(s),...g.getSparseMessageList(s)].find(u=>u.sequence===n)}_updatePinnedMessageInfo(s){return pA(this,arguments,void 0,function*({serverPinnedMessageList:n,groupID:g}){const{OuterConstant:{CONV_GROUP:u},utils:{isEmpty:E}}=this._core,m=[],D=[],M=[],T=new Map,P=`${u}${g}`;for(let iA=0;iA{const{sequence:kA}=RA,xA=T.get(kA),LA=iA[xA]||{userID:xA,nick:"",avatar:""};RA.pinnerInfo=LA}),m.sort((RA,kA)=>RA.sequence-kA.sequence),m}return[]})}_fetchPinnedMessageInfo(s){return pA(this,void 0,void 0,function*(){var n,g;const{message:{messageHistory:u},user:{userProfile:E},utils:{isArray:m}}=this._core,{conversationID:D,messageSequenceList:M,pinnerIDList:T}=s,P=yield Promise.all([this._fetchMessageBySequence({conversationID:D,messageSequenceList:M}),E?.getUserProfile({userIDList:T})]);if(m(P)){const W={};return(((n=P[1])===null||n===void 0?void 0:n.data)||[]).forEach(iA=>{const{userID:EA,nick:RA="",avatar:kA=""}=iA;W[EA]={userID:EA,nick:RA,avatar:kA}}),{messageList:((g=P[0])===null||g===void 0?void 0:g.messageList)||[],pinnerInfoMap:W}}})}_fetchMessageBySequence(s){return pA(this,void 0,void 0,function*(){const{utils:{isEmpty:n},message:{messageHistory:g}}=this._core,{conversationID:u,messageSequenceList:E}=s;return n(E)?[]:g.getGroupRoamingMessagesByAnchor({conversationID:u,messageSequenceList:E,getType:3})})}};class lg{constructor(n){this.eventType=Nc.DATA,this.index=0,this.markdown="",this.isLast=!1,this.binaryData=null;const{EventType:g,Index:u,Markdown:E,IsLast:m,BinaryData:D}=n;this.eventType=g,this.index=u,this.markdown=E,this.isLast=m,this.binaryData=D}}var fI=new class{constructor(){this._messageMap=new Map,this._retryCountMap=new Map}init(s){this._core=s;const{notificationCenter:n,OuterEvent:{MESSAGE_RECEIVED:g},InnerEvent:{HISTORY_MESSAGE_FETCHED:u},common:{workflowManager:E},constants:{WORKFLOW_NAME:m,WORKFLOW_STEP:D}}=s;n.subscribeInnerEvent(lo,this._handleStreamMessageChunkPush,this),n.subscribeOuterEvent(g,this._handleMessageReceived,this),n.subscribeInnerEvent(u,this.processHistoryMessage,this),E.registerWorkflowStep(m.SYNC_SERVER_INFO_AFTER_RE_ONLINE,D.STREAM_MESSAGE_RECOVER,this._recoverStreamMessage,this)}processHistoryMessage(s){const{utils:{isEmpty:n,safeStringify:g},ssoLog:u}=this._core;try{s?.forEach(E=>{var m;if(this._isValidStreamMessage(E)){const D=(m=E?._elements)===null||m===void 0?void 0:m[0],{streamMessageID:M,markdown:T,binaryData:P}=D?.content||{};n(T)&&n(P)?(this._messageMap.set(M,E),this._fetchStreamMessageChunks(E)):D.content.isStreamEnded=!0}})}catch(E){u.error("processHistoryMessage.error",g(E))}}_handleMessageReceived(s){const n=s.data;n?.forEach(g=>{var u,E;if(this._isValidStreamMessage(g)){const{streamMessageID:m}=((E=(u=g?._elements)===null||u===void 0?void 0:u[0])===null||E===void 0?void 0:E.content)||{};m&&(this._messageMap.set(m,g),this._fetchStreamMessageChunks(g))}})}_isValidStreamMessage(s){var n,g;const{utils:{isEmpty:u}}=this._core,{streamMessageID:E}=((g=(n=s?._elements)===null||n===void 0?void 0:n[0])===null||g===void 0?void 0:g.content)||{};return s.type===Vr.MSG_STREAM&&!u(E)}_fetchStreamMessageChunks(s){return pA(this,void 0,void 0,function*(){var n,g;const{constants:{ERROR_CODE:u},ssoLog:E,utils:{safeStringify:m}}=this._core,D=(n=s._elements)===null||n===void 0?void 0:n[0],M=(g=D?.content)===null||g===void 0?void 0:g.streamMessageID;try{const{from:T,to:P}=s,W=D.getLatestIndex();if(D.content.isStreamEnded)return;const iA=yield function(EA){return pA(this,void 0,void 0,function*(){const{from:RA,to:kA,streamMessageID:xA,index:LA}=EA,SA={From_Account:RA,To_Account:kA,StreamMsgID:xA,AckIndex:LA};return Us.core.common.buildAndSendPacket({servcmd:"StreamMsg.GetStreamHttp",data:SA,timeout:5e3})})}({from:T,to:P,streamMessageID:M,index:W});if(iA){const{ErrorCode:EA,ErrorInfo:RA}=iA;if(EA!==0)throw D.content.errorCode=EA,D.content.errorMessage=RA,{errorCode:EA,errorMessage:RA}}}catch(T){if(T.errorCode===u.NETWORK_TIMEOUT&&this._shouldRetryFetch(M)){const P=this._retryCountMap.get(M)||0;E.debug("_fetchStreamMessageChunks.timeout",`error: ${m(T)} retried: ${P}`),this._retryCountMap.set(M,P+1),this._fetchStreamMessageChunks(s)}else E.error("_fetchStreamMessageChunks.error",m(T))}})}_shouldRetryFetch(s){const{utils:{isNumber:n}}=this._core;if(!this._retryCountMap.has(s))return this._retryCountMap.set(s,1),!0;const g=this._retryCountMap.get(s);return!!(n(g)&&g<=3)}_onStreamEnded(s,n,g){const{ssoLog:u}=this._core;g.content.isStreamEnded=!0,g.stopReason=n,this._messageMap.delete(s),u.debug("_onStreamEnded",`streamMessage end, StopReason: ${n}`)}_handleStreamMessageChunkPush(s){var n;const{ssoLog:g}=this._core,{StopReason:u,Chunks:E,StreamID:m}=s?.body||{},D=this._messageMap.get(m);if(!D)return void g.warn(`_handleStreamMessageChunkPush, unfounded message: ${m}`);const M=(n=D._elements)===null||n===void 0?void 0:n[0];if(M&&this._validateExpectedChunk(M,E)){if(E.length>0){const T=E.map(P=>new lg(P));M.updateChunks(T)}this._emitMessageModify(D),function(T,P){pA(this,void 0,void 0,function*(){const{common:{generateProtocolData:W},utils:{safeStringify:iA},ssoLog:EA,channel:RA}=Us.core,kA={StreamMsgID:T,AckIndex:P};try{const xA=W({servcmd:"StreamMsg.AckHttp",data:kA});RA.sendPacket(xA)}catch(xA){EA.debug("sendStreamChunkAck",iA(xA))}})}(m,M.getLatestIndex()),M.content.isStreamEnded&&this._onStreamEnded(m,u,M)}}_emitMessageModify(s){const{notificationCenter:n,OuterEvent:{MESSAGE_MODIFIED:g}}=this._core;n.emitOuterEvent(g,{name:g,data:[s]})}_validateExpectedChunk(s,n){const g=s.getLatestIndex()+1;let u=!1;for(let E=0;Em.Index).join(", ")}]`),!1}return!0}_recoverStreamMessage(){this._retryCountMap.clear();const{ssoLog:s,utils:{safeStringify:n}}=this._core;try{const g=Array.from(this._messageMap.entries());for(let u=Math.max(0,g.length-300);u{const LA=this._getResponseBody(kA,E,iA&&EA),SA=this._buildResponse(kA,LA);if(kA.status===200)n(null,SA);else{if(EA&&!RA.includes(EA))return s.url=this._domainName2IP(RA,EA),s.uploadByIP=!0,this.request(s,n);n({code:kA.status,message:JSON.stringify(kA.responseText)},SA)}},kA.onerror=()=>{const LA=this._getResponseBody(kA,E,iA&&EA),SA=this._buildResponse(kA,LA),OA={code:kA.status,message:kA.status===0?"CORS blocked or network error":JSON.stringify(kA.responseText)};n(OA,SA)},s.onProgress&&kA.upload&&(kA.upload.onprogress=LA=>{const{total:SA,loaded:OA}=LA,JA=Math.min(Math.floor(100*OA/SA),100);s.onProgress({total:SA,loaded:OA,percent:JA/100})}),kA.send(P),kA})}_buildResponse(s,n){const g={};return s.getAllResponseHeaders().trim().split(`
-`).forEach(u=>{if(u){const[E,m]=u.split(":").map(D=>D.trim());g[E.toLowerCase()]=m}}),{statusCode:s.status,statusMessage:s.statusText,headers:g,data:n}}_getResponseBody(s,n,g){return s.status===200&&n?{location:n,uploadIP:g}:{response:s.responseText,uploadIP:g}}_queryString(s,n="&",g="="){var u;const{isEmpty:E,isPlainObject:m}=(u=this._core)===null||u===void 0?void 0:u.utils;return E(s)?"":m(s)?Object.keys(s).map(D=>{const M=encodeURIComponent(D)+g;return Array.isArray(s[D])?s[D].map(T=>M+encodeURIComponent(T)).join(n):M+encodeURIComponent(s[D])}).filter(Boolean).join(n):void 0}_domainName2IP(s,n){return s.replace(/^http(s)?:\/\/(.*?)\//,`https://${n}/`)}};const Ju=["unknown","image","video","audio","log"];var yI=new class{init(s){this._core=s}request(s,n){var g;const{MINI_APP_NAMESPACE:u,IN_ALIPAY_MINI_APP:E,isUniIOSApp:m}=(g=this._core)===null||g===void 0?void 0:g.utils,{resources:D="",headers:M={},url:T,downloadUrl:P=""}=s;let W=T,iA=null;const EA=P?P.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/):null;if(!EA)return void console.warn("message Invalid download URL format");const RA=decodeURIComponent(EA[3]),kA=RA.includes("?")?RA.split("?")[0]:RA||"",xA={key:s.fileKey||kA,success_action_status:200,"Content-Type":""},LA={};if(m()){const[OA,JA]=T.split("?sign=");JA&&(W=`${OA}?sign=${encodeURIComponent(JA)}`,LA.sign=decodeURIComponent(JA),LA.signature=decodeURIComponent(JA))}let SA={url:W,header:M,name:"file",filePath:D,formData:Object.assign(Object.assign({},xA),LA),timeout:s.timeout||3e5};if(E){const{name:OA}=SA,JA=Do(SA,["name"]);SA=Object.assign(Object.assign({},JA),{fileName:"file",fileType:s.fileType?Ju[s.fileType]:"image"})}return iA=u.uploadFile(Object.assign(Object.assign({},SA),{success:OA=>{this._handleResponse({response:OA,downloadUrl:P,callback:n})},fail:OA=>{this._handleResponse({response:OA,downloadUrl:P,callback:n})}})),iA.onProgressUpdate&&iA.onProgressUpdate(OA=>{s.onProgress&&s.onProgress({total:OA.totalBytesExpectedToSend||0,loaded:OA.totalBytesSent||0,percent:OA.progress?Math.floor(OA.progress)/100:0})}),iA}_handleResponse(s){const{downloadUrl:n,response:g,callback:u}=s,E={};if(g.header)for(const D in g.header)g.header.hasOwnProperty(D)&&(E[D.toLowerCase()]=g.header[D]);const m=+g.statusCode;m===200?u(null,{statusCode:m,headers:E,data:Object.assign(Object.assign({},g.data),{location:n})}):u({code:m,message:JSON.stringify(g.data)},{statusCode:m,headers:E,data:void 0})}};function gl(s){return function(n){return Object.prototype.toString.call(n).match(/^\[object (.*)\]$/)[1].toLowerCase()}(s)==="file"}function Lr(s){const n=s||99999999;return Math.round(Math.random()*n)}function Ur(s,n=!0,g=!0){const u=Date.now();return n?g?u-s+" ms":`${Math.round((u-s)/1e3)} s`:g?u-s:Math.round((u-s)/1e3)}function Ig(s){return`${Array.from({length:8},()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1)).join("")}-${s}`}function ar(s,n){return Math.round(Number(s)*10**n)/10**n}function _r(s){return s<=1048576?`${ar(s/1024,1)}KB/s`:`${ar(s/1048576,1)}MB/s`}const ic="TIMImageElem",Fg="TIMSoundElem",Ya="TIMFileElem",Fl="TIMVideoFileElem",ha="RichMediaMessagePlugin",DI=["rich.my-imcloud.com","imrich.qcloud.com"],iu=1,Ba=2,cl=3,xE=255;var ou;(function(s){s.UNSENT="unSend",s.SUCCESS="success",s.FAIL="fail"})(ou||(ou={}));const YE={wechat:/^(wxfile:\/\/tmp_|http:\/\/temp\/|cloud:\/\/temp-)/,alipay:/^(https:\/\/resource\/|alipayfile:\/\/tmp\/)/,baidu:/^(http:\/\/tmp\/|swanfile:\/\/tmp_)/,bytedance:/^(ttfile:\/\/tmp_|\/(var|tmp)\/|tttemp:\/\/)/,qq:/^(qqfile:\/\/tmp_|http:\/\/qtemp\/)/},Jr=Symbol("isCustomUpload");var su,Pt=new class{init(s){this._core=s}addAuthToUrl(s=""){if(this._isMiniProgramTempFile(s))return s;const n=function(g){return g?g.startsWith("https://")?g:g.startsWith("http://")?g.replace("http://","https://"):g:""}(s);return this.processResourceUrl(n)}removeAuthToUrl(s){return function(n,g){const[u,E]=n.split("?");if(!E)return u;const m=E.split("&").reduce((M,T)=>{const[P,W]=T.split("=");return P&&P!==g&&(M[P]=W||""),M},{}),D=Object.keys(m).map(M=>`${M}${m[M]?`=${m[M]}`:""}`).join("&");return D?`${u}?${D}`:u}(s,"authKey")}_isMiniProgramTempFile(s){return!!this.getPlatformFlags().IN_MINI_APP&&Object.values(YE).some(n=>n.test(s))}extractFileFromInput(s){const{utils:{isArray:n}}=this._core;return gl(s)?s:function(g){if(typeof g!="object"||g===null)return!1;const u=Object.getPrototypeOf(g);if(u===null)return!0;let E=u;for(;Object.getPrototypeOf(E)!==null;)E=Object.getPrototypeOf(E);return u===E}(s)&&typeof uni<"u"?n(s.tempFiles)&&s.tempFiles.length>0?s.tempFiles[0]:n(s.files)?s.files[0]:s.tempFile?s.tempFile:null:s instanceof HTMLInputElement&&s.files&&s.files.length>0?s.files[0]:null}probeImageWidthHeight(s){return pA(this,void 0,void 0,function*(){var n;const{IN_MINI_APP:g,IN_BROWSER:u}=((n=this._core)===null||n===void 0?void 0:n.utils)||{};return this._shouldSkipProbing()?{width:0,height:0}:u?this._probeImageDimensionsWeb(s):g?this._probeImageDimensionsMiniApp(s):void 0})}isSimpleCos(){var s;const n=((s=this._core)===null||s===void 0?void 0:s.store.get("cloudConfig"))||{},{simple_cos:g}=n;return g!=="0"}getFileDNList(){var s;let n=DI;const g=((s=this._core)===null||s===void 0?void 0:s.store.get("cloudConfig"))||{},{file_dn_list:u}=g;if(u===void 0)return n;try{JSON.parse(u).forEach(E=>{n.includes(E)||n.push(E)})}catch(E){console.warn(E),n=DI}return n}getPlatform(){var s;return(s=this._core)===null||s===void 0?void 0:s.utils.platform}generateUUID(s,n){var g;let u=`${this.getSDKAppID()}-${this.getCurrentUserID()}-${(g=this._core)===null||g===void 0?void 0:g.utils.randomString()}`;if(n)return`${u}.${n}`;const E=s.name||s.value||s.url||s.tempFilePath,m=E&&E.slice(E.lastIndexOf(".")+1);return m&&(u=`${u}.${m}`),u}processResourceUrl(s){if(!s)return"";let n=s;const g=this.getFileDownloadProxy(),u=this.getAuthKey(),E=this.getFileDNList();return g&&(s.startsWith("http://")?n=s.replace(/^http:\/\/[^/]+/,g):s.startsWith("https://")&&(n=s.replace(/^https:\/\/[^/]+/,g))),u&&n.indexOf("authKey=")===-1&&function(D,M){let T=!1;if(D){const P=D.match(/:\/\/([0-9]?\.)?(.[^/:]+)/),W=P&&P[2]||"";if(W.includes("rich-dev"))return!0;for(let iA=0;iA-1?`${n}&authKey=${u}`:`${n}?authKey=${u}`),n}getCurrentUserID(){var s,n;return(n=(s=this._core)===null||s===void 0?void 0:s.store.get("login"))===null||n===void 0?void 0:n.userId}getSDKAppID(){var s,n;return(n=(s=this._core)===null||s===void 0?void 0:s.store.get("instance"))===null||n===void 0?void 0:n.sdkAppId}getFileDownloadProxy(){var s,n;return((n=(s=this._core)===null||s===void 0?void 0:s.store.get("instance"))===null||n===void 0?void 0:n.fileDownloadProxy)||""}getFileUploadProxy(){var s,n;return((n=(s=this._core)===null||s===void 0?void 0:s.store.get("instance"))===null||n===void 0?void 0:n.fileUploadProxy)||""}getAuthKey(){var s,n;return((n=(s=this._core)===null||s===void 0?void 0:s.store.get("login"))===null||n===void 0?void 0:n.authKey)||""}isPrivateNetWork(){var s,n;return(n=(s=this._core)===null||s===void 0?void 0:s.store.get("instance"))===null||n===void 0?void 0:n.proxyServer}getPlatformFlags(){var s;const{IN_BROWSER:n,IN_MINI_APP:g,IN_RN_APP:u,IN_UNI_NATIVE_APP:E}=(s=this._core)===null||s===void 0?void 0:s.utils;return{IN_BROWSER:n,IN_MINI_APP:g,IN_RN_APP:u,IN_UNI_NATIVE_APP:E}}isEmpty(s){var n;const{isEmpty:g}=(n=this._core)===null||n===void 0?void 0:n.utils;return g(s)}generateURL(s,n){const{needAddAuthToUrl:g=!0}=n||{};return g?this.addAuthToUrl(s):s}_probeImageDimensionsMiniApp(s){var n;const{MINI_APP_NAMESPACE:g}=((n=this._core)===null||n===void 0?void 0:n.utils)||{};return new Promise(u=>{g.getImageInfo({src:s,success:E=>u({width:E.width,height:E.height}),fail:()=>u({width:0,height:0})})})}_shouldSkipProbing(){var s;const{IN_RN_APP:n,IS_IE:g,IE_VERSION:u,IN_WX_MINI_GAME:E}=((s=this._core)===null||s===void 0?void 0:s.utils)||{};return n||g&&u===9||E}_probeImageDimensionsWeb(s){return new Promise(n=>{const g=new Image,u=()=>{g.onload=null,g.onerror=null,g.src=""};g.onload=()=>{n({width:g.width,height:g.height}),u()},g.onerror=()=>{n({width:0,height:0}),u()},g.src=s})}},Hu={exports:{}},qu=(su||(su=1,function(s){s.exports=function(n){var g=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];function u(LA,SA){var OA=LA[0],JA=LA[1],ae=LA[2],se=LA[3];JA=((JA+=((ae=((ae+=((se=((se+=((OA=((OA+=(JA&ae|~JA&se)+SA[0]-680876936|0)<<7|OA>>>25)+JA|0)&JA|~OA&ae)+SA[1]-389564586|0)<<12|se>>>20)+OA|0)&OA|~se&JA)+SA[2]+606105819|0)<<17|ae>>>15)+se|0)&se|~ae&OA)+SA[3]-1044525330|0)<<22|JA>>>10)+ae|0,JA=((JA+=((ae=((ae+=((se=((se+=((OA=((OA+=(JA&ae|~JA&se)+SA[4]-176418897|0)<<7|OA>>>25)+JA|0)&JA|~OA&ae)+SA[5]+1200080426|0)<<12|se>>>20)+OA|0)&OA|~se&JA)+SA[6]-1473231341|0)<<17|ae>>>15)+se|0)&se|~ae&OA)+SA[7]-45705983|0)<<22|JA>>>10)+ae|0,JA=((JA+=((ae=((ae+=((se=((se+=((OA=((OA+=(JA&ae|~JA&se)+SA[8]+1770035416|0)<<7|OA>>>25)+JA|0)&JA|~OA&ae)+SA[9]-1958414417|0)<<12|se>>>20)+OA|0)&OA|~se&JA)+SA[10]-42063|0)<<17|ae>>>15)+se|0)&se|~ae&OA)+SA[11]-1990404162|0)<<22|JA>>>10)+ae|0,JA=((JA+=((ae=((ae+=((se=((se+=((OA=((OA+=(JA&ae|~JA&se)+SA[12]+1804603682|0)<<7|OA>>>25)+JA|0)&JA|~OA&ae)+SA[13]-40341101|0)<<12|se>>>20)+OA|0)&OA|~se&JA)+SA[14]-1502002290|0)<<17|ae>>>15)+se|0)&se|~ae&OA)+SA[15]+1236535329|0)<<22|JA>>>10)+ae|0,JA=((JA+=((ae=((ae+=((se=((se+=((OA=((OA+=(JA&se|ae&~se)+SA[1]-165796510|0)<<5|OA>>>27)+JA|0)&ae|JA&~ae)+SA[6]-1069501632|0)<<9|se>>>23)+OA|0)&JA|OA&~JA)+SA[11]+643717713|0)<<14|ae>>>18)+se|0)&OA|se&~OA)+SA[0]-373897302|0)<<20|JA>>>12)+ae|0,JA=((JA+=((ae=((ae+=((se=((se+=((OA=((OA+=(JA&se|ae&~se)+SA[5]-701558691|0)<<5|OA>>>27)+JA|0)&ae|JA&~ae)+SA[10]+38016083|0)<<9|se>>>23)+OA|0)&JA|OA&~JA)+SA[15]-660478335|0)<<14|ae>>>18)+se|0)&OA|se&~OA)+SA[4]-405537848|0)<<20|JA>>>12)+ae|0,JA=((JA+=((ae=((ae+=((se=((se+=((OA=((OA+=(JA&se|ae&~se)+SA[9]+568446438|0)<<5|OA>>>27)+JA|0)&ae|JA&~ae)+SA[14]-1019803690|0)<<9|se>>>23)+OA|0)&JA|OA&~JA)+SA[3]-187363961|0)<<14|ae>>>18)+se|0)&OA|se&~OA)+SA[8]+1163531501|0)<<20|JA>>>12)+ae|0,JA=((JA+=((ae=((ae+=((se=((se+=((OA=((OA+=(JA&se|ae&~se)+SA[13]-1444681467|0)<<5|OA>>>27)+JA|0)&ae|JA&~ae)+SA[2]-51403784|0)<<9|se>>>23)+OA|0)&JA|OA&~JA)+SA[7]+1735328473|0)<<14|ae>>>18)+se|0)&OA|se&~OA)+SA[12]-1926607734|0)<<20|JA>>>12)+ae|0,JA=((JA+=((ae=((ae+=((se=((se+=((OA=((OA+=(JA^ae^se)+SA[5]-378558|0)<<4|OA>>>28)+JA|0)^JA^ae)+SA[8]-2022574463|0)<<11|se>>>21)+OA|0)^OA^JA)+SA[11]+1839030562|0)<<16|ae>>>16)+se|0)^se^OA)+SA[14]-35309556|0)<<23|JA>>>9)+ae|0,JA=((JA+=((ae=((ae+=((se=((se+=((OA=((OA+=(JA^ae^se)+SA[1]-1530992060|0)<<4|OA>>>28)+JA|0)^JA^ae)+SA[4]+1272893353|0)<<11|se>>>21)+OA|0)^OA^JA)+SA[7]-155497632|0)<<16|ae>>>16)+se|0)^se^OA)+SA[10]-1094730640|0)<<23|JA>>>9)+ae|0,JA=((JA+=((ae=((ae+=((se=((se+=((OA=((OA+=(JA^ae^se)+SA[13]+681279174|0)<<4|OA>>>28)+JA|0)^JA^ae)+SA[0]-358537222|0)<<11|se>>>21)+OA|0)^OA^JA)+SA[3]-722521979|0)<<16|ae>>>16)+se|0)^se^OA)+SA[6]+76029189|0)<<23|JA>>>9)+ae|0,JA=((JA+=((ae=((ae+=((se=((se+=((OA=((OA+=(JA^ae^se)+SA[9]-640364487|0)<<4|OA>>>28)+JA|0)^JA^ae)+SA[12]-421815835|0)<<11|se>>>21)+OA|0)^OA^JA)+SA[15]+530742520|0)<<16|ae>>>16)+se|0)^se^OA)+SA[2]-995338651|0)<<23|JA>>>9)+ae|0,JA=((JA+=((se=((se+=(JA^((OA=((OA+=(ae^(JA|~se))+SA[0]-198630844|0)<<6|OA>>>26)+JA|0)|~ae))+SA[7]+1126891415|0)<<10|se>>>22)+OA|0)^((ae=((ae+=(OA^(se|~JA))+SA[14]-1416354905|0)<<15|ae>>>17)+se|0)|~OA))+SA[5]-57434055|0)<<21|JA>>>11)+ae|0,JA=((JA+=((se=((se+=(JA^((OA=((OA+=(ae^(JA|~se))+SA[12]+1700485571|0)<<6|OA>>>26)+JA|0)|~ae))+SA[3]-1894986606|0)<<10|se>>>22)+OA|0)^((ae=((ae+=(OA^(se|~JA))+SA[10]-1051523|0)<<15|ae>>>17)+se|0)|~OA))+SA[1]-2054922799|0)<<21|JA>>>11)+ae|0,JA=((JA+=((se=((se+=(JA^((OA=((OA+=(ae^(JA|~se))+SA[8]+1873313359|0)<<6|OA>>>26)+JA|0)|~ae))+SA[15]-30611744|0)<<10|se>>>22)+OA|0)^((ae=((ae+=(OA^(se|~JA))+SA[6]-1560198380|0)<<15|ae>>>17)+se|0)|~OA))+SA[13]+1309151649|0)<<21|JA>>>11)+ae|0,JA=((JA+=((se=((se+=(JA^((OA=((OA+=(ae^(JA|~se))+SA[4]-145523070|0)<<6|OA>>>26)+JA|0)|~ae))+SA[11]-1120210379|0)<<10|se>>>22)+OA|0)^((ae=((ae+=(OA^(se|~JA))+SA[2]+718787259|0)<<15|ae>>>17)+se|0)|~OA))+SA[9]-343485551|0)<<21|JA>>>11)+ae|0,LA[0]=OA+LA[0]|0,LA[1]=JA+LA[1]|0,LA[2]=ae+LA[2]|0,LA[3]=se+LA[3]|0}function E(LA){var SA,OA=[];for(SA=0;SA<64;SA+=4)OA[SA>>2]=LA.charCodeAt(SA)+(LA.charCodeAt(SA+1)<<8)+(LA.charCodeAt(SA+2)<<16)+(LA.charCodeAt(SA+3)<<24);return OA}function m(LA){var SA,OA=[];for(SA=0;SA<64;SA+=4)OA[SA>>2]=LA[SA]+(LA[SA+1]<<8)+(LA[SA+2]<<16)+(LA[SA+3]<<24);return OA}function D(LA){var SA,OA,JA,ae,se,_i,Ti=LA.length,Ft=[1732584193,-271733879,-1732584194,271733878];for(SA=64;SA<=Ti;SA+=64)u(Ft,E(LA.substring(SA-64,SA)));for(OA=(LA=LA.substring(SA-64)).length,JA=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],SA=0;SA>2]|=LA.charCodeAt(SA)<<(SA%4<<3);if(JA[SA>>2]|=128<<(SA%4<<3),SA>55)for(u(Ft,JA),SA=0;SA<16;SA+=1)JA[SA]=0;return ae=(ae=8*Ti).toString(16).match(/(.*?)(.{0,8})$/),se=parseInt(ae[2],16),_i=parseInt(ae[1],16)||0,JA[14]=se,JA[15]=_i,u(Ft,JA),Ft}function M(LA){var SA,OA,JA,ae,se,_i,Ti=LA.length,Ft=[1732584193,-271733879,-1732584194,271733878];for(SA=64;SA<=Ti;SA+=64)u(Ft,m(LA.subarray(SA-64,SA)));for(OA=(LA=SA-64>2]|=LA[SA]<<(SA%4<<3);if(JA[SA>>2]|=128<<(SA%4<<3),SA>55)for(u(Ft,JA),SA=0;SA<16;SA+=1)JA[SA]=0;return ae=(ae=8*Ti).toString(16).match(/(.*?)(.{0,8})$/),se=parseInt(ae[2],16),_i=parseInt(ae[1],16)||0,JA[14]=se,JA[15]=_i,u(Ft,JA),Ft}function T(LA){var SA,OA="";for(SA=0;SA<4;SA+=1)OA+=g[LA>>8*SA+4&15]+g[LA>>8*SA&15];return OA}function P(LA){var SA;for(SA=0;SA"u"||ArrayBuffer.prototype.slice||function(){function LA(SA,OA){return(SA=0|SA||0)<0?Math.max(SA+OA,0):Math.min(SA,OA)}ArrayBuffer.prototype.slice=function(SA,OA){var JA,ae,se,_i,Ti=this.byteLength,Ft=LA(SA,Ti),Ni=Ti;return OA!==n&&(Ni=LA(OA,Ti)),Ft>Ni?new ArrayBuffer(0):(JA=Ni-Ft,ae=new ArrayBuffer(JA),se=new Uint8Array(ae),_i=new Uint8Array(this,Ft,JA),se.set(_i),ae)}}(),xA.prototype.append=function(LA){return this.appendBinary(W(LA)),this},xA.prototype.appendBinary=function(LA){this._buff+=LA,this._length+=LA.length;var SA,OA=this._buff.length;for(SA=64;SA<=OA;SA+=64)u(this._hash,E(this._buff.substring(SA-64,SA)));return this._buff=this._buff.substring(SA-64),this},xA.prototype.end=function(LA){var SA,OA,JA=this._buff,ae=JA.length,se=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(SA=0;SA>2]|=JA.charCodeAt(SA)<<(SA%4<<3);return this._finish(se,ae),OA=P(this._hash),LA&&(OA=kA(OA)),this.reset(),OA},xA.prototype.reset=function(){return this._buff="",this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},xA.prototype.getState=function(){return{buff:this._buff,length:this._length,hash:this._hash.slice()}},xA.prototype.setState=function(LA){return this._buff=LA.buff,this._length=LA.length,this._hash=LA.hash,this},xA.prototype.destroy=function(){delete this._hash,delete this._buff,delete this._length},xA.prototype._finish=function(LA,SA){var OA,JA,ae,se=SA;if(LA[se>>2]|=128<<(se%4<<3),se>55)for(u(this._hash,LA),se=0;se<16;se+=1)LA[se]=0;OA=(OA=8*this._length).toString(16).match(/(.*?)(.{0,8})$/),JA=parseInt(OA[2],16),ae=parseInt(OA[1],16)||0,LA[14]=JA,LA[15]=ae,u(this._hash,LA)},xA.hash=function(LA,SA){return xA.hashBinary(W(LA),SA)},xA.hashBinary=function(LA,SA){var OA=P(D(LA));return SA?kA(OA):OA},xA.ArrayBuffer=function(){this.reset()},xA.ArrayBuffer.prototype.append=function(LA){var SA,OA=RA(this._buff.buffer,LA),JA=OA.length;for(this._length+=LA.byteLength,SA=64;SA<=JA;SA+=64)u(this._hash,m(OA.subarray(SA-64,SA)));return this._buff=SA-64>2]|=JA[SA]<<(SA%4<<3);return this._finish(se,ae),OA=P(this._hash),LA&&(OA=kA(OA)),this.reset(),OA},xA.ArrayBuffer.prototype.reset=function(){return this._buff=new Uint8Array(0),this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},xA.ArrayBuffer.prototype.getState=function(){var LA=xA.prototype.getState.call(this);return LA.buff=EA(LA.buff),LA},xA.ArrayBuffer.prototype.setState=function(LA){return LA.buff=iA(LA.buff,!0),xA.prototype.setState.call(this,LA)},xA.ArrayBuffer.prototype.destroy=xA.prototype.destroy,xA.ArrayBuffer.prototype._finish=xA.prototype._finish,xA.ArrayBuffer.hash=function(LA,SA){var OA=P(M(new Uint8Array(LA)));return SA?kA(OA):OA},xA}()}(Hu)),Hu.exports),fC=aI(qu),q=new class{constructor(){this.uploadFileTryCount=0,this.maxRetries=1,this.systemClockOffset=0,this.httpRequest=null,this.uploadFileType="",this.duration=900,this.fetchCosTryCount=0}init(s){var n;this._core=s;const{IN_MINI_APP:g}=s.utils;this.httpRequest=g?yI:Vu,(n=this.httpRequest)===null||n===void 0||n.init(s)}uploadToCOS(s){return pA(this,void 0,void 0,function*(){const n=`${ha} uploadToCOS`,{ssoLog:g,utils:{safeStringify:u}}=this._core,{file:E}=s;this.uploadFileType=s.uploadFileType,g.debug("uploadToCOS",`${n} options:${u(s)}`);try{const m=Date.now(),D=yield this._createCosOptions(s),M=D.fileExistsInCOS?{data:{location:D.downloadUrl}}:yield this._uploadFile(D);this._handleUploadError(M,s);const T=this._createUploadResult(E,M),P=Date.now()-m,W=function(EA){return EA<1024?`${EA}B`:EA<1048576?`${Math.floor(EA/1024)}KB`:`${Math.floor(EA/1048576)}MB`}(E.size),iA=`size:${W} time:${P}ms speed:${_r(1e3*E.size/P)}`;return g.debug("uploadToCOS",`${n} ok. name:${E.name} ${iA}`),{uploadOptions:D,response:T}}catch(m){throw g.warn("uploadToCOS",`${n} failed, error:${u(m)}`),m}})}_handleUploadError(s,n){var g,u;const{ChatError:E}=(g=this._core)===null||g===void 0?void 0:g.helper;if(s.statusCode===403)throw n.url,!((u=s?.data)===null||u===void 0)&&u.uploadIP&&s.data.uploadIP,new E({message:"Upload failed with status 403"})}_createUploadResult(s,n){return{fileName:s.name,fileSize:s.size,fileType:s.type.slice(s.type.indexOf("/")+1).toLowerCase(),location:n.data.location||"",uploadTime:Ur(Date.now(),!1),uploadSpeed:_r(1e3*s.size/Ur(Date.now(),!1))}}_createCosOptions(s){return pA(this,void 0,void 0,function*(){const{fileName:n,resources:g,uploadMethod:u}=yield this._prepareUploadParams(s),E=this._isC2CConversation(s.message.conversationID)?1:2;try{const m=yield this._fetchCosSignatureUrl({fileType:this.uploadFileType,fileName:n,uploadMethod:u,duration:this.duration,userID:s.message.from,conversationType:E}),{uploadUrl:D,downloadUrl:M,requestSnapshotUrl:T,thumbUrl:P,largeUrl:W,fileKey:iA,existFlag:EA}=m,RA=!Pt.isPrivateNetWork()&&m.uploadIP;return{url:this._getRawOrUploadProxyUrl(D),fileType:this.uploadFileType,fileName:n,resources:g,downloadUrl:M,requestSnapshotUrl:T,thumbUrl:P,largeUrl:W,fileKey:iA,uploadIP:RA||"",fileExistsInCOS:EA===1,onProgress:kA=>this._handleUploadProgress(kA,s)}}catch(m){throw console.error("Failed to create COS pre-signed URL options:",m),m}})}_prepareUploadParams(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g,isEmpty:u}}=this._core;n.debug("_prepareUploadParams",` prepareUploadParams:${g(s)}`);const{file:E}=s,{IN_MINI_APP:m,IN_RN_APP:D}=Pt.getPlatformFlags(),M=m||D,T=M&&s.message.type!==Ya,{name:P}=E,W=P.slice(P.lastIndexOf(".")),iA=`${Lr(999999)}${W}`,EA=T?E.name:iA,RA=yield this._generateHashFileName(E);return{fileName:u(RA)?Ig(EA):`${RA}${W}`,resources:M?E.url:E,uploadMethod:M?1:0}})}_generateHashFileName(s){return pA(this,void 0,void 0,function*(){const{utils:{IN_MINI_APP:n,IN_BROWSER:g,IN_UNI_NATIVE_APP:u,isArray:E},ssoLog:m}=this._core,D=Date.now();let M="";return g&&(M=yield this._generateHashFileNameInWeb(s)),n&&(E(s.tempFiles)&&(s=s.tempFiles[0]),u||(M=yield this._generateFileNameInMiniProgram(s)),u&&(M=yield this._generateFileNameInUNINativeApp(s))),m.info("_generateHashFileName",`hashFileName:${M} costTime:${Date.now()-D}`),M})}_generateHashFileNameInWeb(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g}}=this._core;let u="";try{u=yield new Promise((E,m)=>{const D=File.prototype.slice||File.prototype.mozSlice||File.prototype.webkitSlice;D||(n.warn("_generateHashFileNameInWeb","Browser does not support file slicing"),E(""));const M=10485760,T=Math.ceil(s.size/M);let P=0;const W=new fC.ArrayBuffer,iA=new FileReader,EA=setTimeout(()=>{iA.abort(),n.warn("_generateHashFileNameInWeb","File hash generation timeout"),E("")},2e3);function RA(){const kA=P*M,xA=kA+M>=s.size?s.size:kA+M;iA.readAsArrayBuffer(D.call(s,kA,xA))}iA.onload=kA=>{n.debug("_generateHashFileNameInWeb",`read chunk nr ${P+1} of ${T}`),W.append(kA.target.result),P++,P{clearTimeout(EA),m(kA)},RA()})}catch(E){n.warn("_generateHashFileNameInWeb",g(E))}return u})}_generateFileNameInMiniProgram(s){return pA(this,void 0,void 0,function*(){const{utils:{MINI_APP_NAMESPACE:n,safeStringify:g,isEmpty:u},ssoLog:E}=this._core;let m="";if(u(s.url))return E.warn("_generateFileNameInMiniProgram","file.url is empty"),m;if(typeof n?.getFileSystemManager!="function")return E.warn("_generateFileNameInUNINativeApp","getFileSystemManager is not a function"),m;try{m=yield new Promise((D,M)=>{n.getFileSystemManager().getFileInfo({filePath:s.url,success:T=>{D(T.digest)},fail:T=>{M(T)}})})}catch(D){E.warn("_generateFileNameInMiniProgram",g(D))}return m})}_generateFileNameInUNINativeApp(s){return pA(this,void 0,void 0,function*(){var n;const{utils:{safeStringify:g,isEmpty:u},ssoLog:E}=this._core;let m="";if(u(s.url))return E.warn("_generateFileNameInUNINativeApp","file.url is empty"),m;if(typeof((n=plus==null?void 0:plus.io)===null||n===void 0?void 0:n.getFileInfo)!="function")return E.warn("_generateFileNameInUNINativeApp","plus.io.getFileInfo is not a function"),m;try{m=yield new Promise((D,M)=>{plus.io.getFileInfo({filePath:s.url,success:T=>{D(T.digest)},fail:T=>{M(T)}})})}catch(D){E.warn("_generateFileNameInMiniProgram",g(D))}return m})}_handleUploadProgress(s,n){if(typeof n.onProgress=="function")try{n.onProgress(s.percent)}catch(g){throw console.warn("Upload progress callback error:",g),g}}_fetchCosSignatureUrl(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g}}=this._core,u=Pt.isSimpleCos(),E=this._prepareCosRequestData(s),m=u?"im_cos_msg.simple_sig":"im_cos_msg.pre_sig";try{const D=yield function(T,P,W){return pA(this,void 0,void 0,function*(){try{const{helper:iA,channel:EA}=W,RA=iA.generateCosSpecifiedData({servcmd:T,data:P}),kA=`${RA.head.seq}${T}`;return yield EA.sendPacket(RA,{requestId:kA})}catch(iA){throw console.warn("getCosSig error:",iA),iA}})}(m,E,this._core);this.fetchCosTryCount=0;const M=this._processResponse(D);return n.debug("_fetchCosSignatureUrl",` ok. isSimpleCos:${u} data:${g(M)}`),M||{}}catch(D){if(this.fetchCosTryCount<1)return this.fetchCosTryCount++,this._fetchCosSignatureUrl(s);throw this.fetchCosTryCount=0,D}})}_processResponse(s){var n;const g=Pt.isSimpleCos(),u=g?(n=s?.rpt_pre_sig)===null||n===void 0?void 0:n[0]:s;if(!u)return{};if(g){const{str_final_ip:W,rpt_pre_sig:iA,uint32_file_id:EA,uint32_exist_flag:RA,str_download_url:kA,str_upload_url:xA,str_snapshot_url:LA,str_file_key:SA}=u;return{uploadIP:W,preSig:iA,fileID:EA,existFlag:RA,downloadUrl:kA,uploadUrl:xA,requestSnapshotUrl:LA,fileKey:SA}}const{upload_url:E,download_url:m,snapshot_url:D,thumb_url:M,large_url:T,file_key:P}=u;return{uploadUrl:E,downloadUrl:m,requestSnapshotUrl:D,thumbUrl:M,largeUrl:T,fileKey:P}}_prepareCosRequestData(s){return Pt.isSimpleCos()?{uint32_upload_method:s.uploadMethod,uint32_platform:Pt.getPlatform(),uint32_sdkappid:Pt.getSDKAppID(),str_user_id:s.userID,uint32_scene:s.conversationType,rpt_upload_object:[{uint32_file_id:1,uint32_file_type:s.fileType,str_file_name:s.fileName}]}:{file_type:s.fileType,file_name:s.fileName,upload_method:s.uploadMethod,Duration:s.duration}}_uploadFile(s){return pA(this,void 0,void 0,function*(){return new Promise((n,g)=>{this.httpRequest.request(s,(u,E)=>{u&&this.uploadFileTryCount=3e4}_syncSystemClock(s){var n,g,u;const E=((n=s.headers)===null||n===void 0?void 0:n.date)||((g=s.headers)===null||g===void 0?void 0:g.Date)||((u=s.error)===null||u===void 0?void 0:u.ServerTime);if(E){const m=Date.now(),D=Date.parse(E);this.systemClockOffset=D-m}}_getRawOrUploadProxyUrl(s){const n=Pt.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,b=2252,x=2253,tA=["jpg","jpeg","gif","png","bmp","image","webp"],uA={JPG:1,JPEG:1,GIF:2,PNG:3,BMP:4,UNKNOWN:255},wA=1,XA=2;class pe{constructor(n,g){this.instanceID=Lr(9999999),this.sizeType=n.type||0,this.type=0,this.size=n.size||0,this.width=n.width||0,this.height=n.height||0,this.imageUrl=Pt.addAuthToUrl(n.imageUrl||n.url||""),this.url=Pt.addAuthToUrl(n.url||g)}setSizeType(n){this.sizeType=n}setType(n){this.type=n}setImageUrl(n){n&&(this.imageUrl=Pt.addAuthToUrl(n))}getImageUrl(){return this.imageUrl}}function p(s){const{originUrl:n,originWidth:g,originHeight:u,min:E=198}=s,m=parseInt(g)||0,D=parseInt(u)||0,M={url:void 0,width:0,height:0};if((m<=D?m:D)<=E)M.url=n,M.width=m,M.height=D;else{D<=m?(M.width=Math.ceil(m*E/D),M.height=E):(M.width=E,M.height=Math.ceil(D*E/m));const T=n&&n.indexOf("?")>-1?`${n}&`:`${n}?`;M.url=E===198?`${T}imageView2/3/w/198/h/198`:`${T}imageView2/3/w/720/h/720`}if(n===void 0){const{url:T}=M;return Do(M,["url"])}return M}class B{constructor(n){this._imageMemoryURL="",this._percent=0,this.type=ic;const{uuid:g,file:u,imageFormat:E,imageInfoArray:m=[],isCustomUpload:D=!1}=n;this._imageMemoryURL=this.createImageDataAsURL(u),this.content={imageFormat:E,uuid:g,imageInfoArray:[]},this[Jr]=D,this.initImageInfoArray(m),this.autoFixUrl()}static parseServerPushElement(n){const{MsgContent:g}=n,{ImageFormat:u,ImageInfoArray:E,UUID:m}=g,D=function(M){return M.map(T=>({size:T.Size,type:T.Type,width:T.Width,height:T.Height,url:T.URL}))}(E);return new B({imageFormat:u,imageInfoArray:D,uuid:m})}createImageDataAsURL(n){let g="";const{IN_MINI_APP:u,IN_RN_APP:E,IN_BROWSER:m}=Pt.getPlatformFlags();return n&&((u||E)&&(g=n.url),m&&(g=window.URL.createObjectURL(n))),g}initImageInfoArray(n=[]){const g={type:0,size:0,width:0,height:0,url:""};for(let u=0;u<3;u++){const E=n[u]||Object.assign({},g),m=new pe(E,this._imageMemoryURL);m.setSizeType(u+1),m.setType(u),this.addImageInfo(m)}this.updateAccessSideImageInfoArray()}autoFixUrl(){const n=["http","https"];this.content.imageInfoArray.forEach(g=>{if(!g.url||g.imageUrl==="")return;const[u,...E]=g.imageUrl.split("://"),m=E.join("://");n.includes(u)||g.setImageUrl(`https://${m}`)})}updatePercent(n){this._percent=Math.min(n,1)}updateImageFormat(n){this.content.imageFormat=uA[n.toUpperCase()]||uA.UNKNOWN}addImageInfo(n){this.content.imageInfoArray.length>=3||this.content.imageInfoArray.push(n)}updateImageInfoArray(n){const g=this.content.imageInfoArray.length;let u;for(let E=0;E({InstanceId:g.instanceID,Type:g.sizeType,MsgType:g.type,Size:g.size,Width:g.width,Height:g.height,URL:Pt.removeAuthToUrl(g.imageUrl)}))}}const v=new class{init(s){this.core=s}},N={[iu]:"i",[cl]:"a",[Ba]:"v",[xE]:"f"};let O=null,z=null;function X(s){var n;const{store:g,utils:{isNumber:u,safeStringify:E},ssoLog:m}=v.core;try{const D=((n=g.get("cloudConfig"))===null||n===void 0?void 0:n.upload_size_limit)||"";D!==z&&(z=D,O=JSON.parse(D)||{});const M=O?.[N[s]];if(u(M))return 1024*M*1024}catch(D){m.debug("getCloudControlUploadSizeLimit",E(D))}return null}var rA=new class{constructor(){this._messageOptionsMap=new Map}init(s){var n;this._core=s;const{notificationCenter:g,helper:u,InnerEvent:E,message:m}=s;u.registerApi({apiName:"createImageMessage",context:this}),u.registerExperimentalAPI("createImageMessage",this,"createCustomUploadImageMessage"),(n=m?.messageFactory)===null||n===void 0||n.registerElementClass(ic,B),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createImageMessage(s){var n,g,u;try{const E=(n=this._core.store.get("login"))===null||n===void 0?void 0:n.userId,m=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:E})),D=this._processImage(s);s.payload.file=D;const M={imageFormat:uA.UNKNOWN,uuid:Pt.generateUUID(D),file:D,imageInfoArray:[]},T=new B(M);return m.setElement(T),this._messageOptionsMap.set(m.clientSequence,s),m}catch(E){throw E}}createCustomUploadImageMessage(s){var n,g,u,E;const{store:m,utils:{isEmpty:D}}=this._core,M=(n=m.get("login"))===null||n===void 0?void 0:n.userId,T=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:M})),{largeImageUuid:P,largeFileSize:W,largeImageWidth:iA,largeImageHeight:EA,largeImageUrl:RA,originImageUuid:kA,originFileSize:xA,originImageWidth:LA,originImageHeight:SA,originImageUrl:OA,thumbImageUuid:JA,thumbFileSize:ae,thumbImageWidth:se,thumbImageHeight:_i,thumbImageUrl:Ti}=((E=s?.payload)===null||E===void 0?void 0:E.file)||{};if(D(OA)||D(kA))throw new Error("createImageMessageExperimental originImageUrl or originImageUuid is empty");const Ft=new B({imageFormat:uA.UNKNOWN,uuid:kA,imageInfoArray:[{instanceID:kA,size:xA,width:LA,height:SA,imageUrl:OA,url:OA},{instanceID:P,size:W,width:iA,height:EA,imageUrl:RA,url:RA},{instanceID:JA,size:ae,width:se,height:_i,imageUrl:Ti,url:Ti}],isCustomUpload:!0});return T.setElement(Ft),this._messageOptionsMap.set(T.clientSequence,s),T._skipUpload=!0,T}upload(s){return pA(this,void 0,void 0,function*(){const n=s.getElements()[0],{file:g}=this._messageOptionsMap.get(s.clientSequence).payload;this._validateBeforeUploadImage(g);const u=yield this._performImageUpload(n,s,g),E=this._generateImageInfo(u);return n.updateImageFormat(u?.fileType),n.updateImageInfoArray(E),this._updateImageType(n.content.imageInfoArray),s})}_performImageUpload(s,n,g){return pA(this,void 0,void 0,function*(){const{to:u}=n,E={uploadFileType:iu,file:g,to:u,message:n,onProgress:M=>{var T,P;s.updatePercent(M),(P=(T=this._messageOptionsMap.get(n.clientSequence))===null||T===void 0?void 0:T.onProgress)===null||P===void 0||P.call(T,M)}},{uploadOptions:m,response:D}=yield q.uploadToCOS(E);return this._parseResponse(m,D)})}_generateImageInfo(s){const{location:n,fileSize:g,width:u,height:E,smallImageUrl:m,smallImageWidth:D,smallImageHeight:M,largeImageUrl:T,largeImageWidth:P,largeImageHeight:W,imageInfoArray:iA}=s,EA=Pt.addAuthToUrl(n),RA={size:g,url:EA,width:u,height:E};return iA?.length>0?this._processImageInfoArray(iA,g):m&&T?[Object.assign({},RA),{largeImageUrl:T,largeImageWidth:P,largeImageHeight:W},{smallImageUrl:m,smallImageWidth:D,smallImageHeight:M}]:[Object.assign({},RA),this._generateThumbInfo(EA,u,E,720),this._generateThumbInfo(EA,u,E,198)]}_generateThumbInfo(s,n,g,u){return p({originUrl:s,originWidth:n,originHeight:g,min:u})}_processImageInfoArray(s,n){let g,u,E;for(const m of s)m.type===1?(u=m,u.size=n):m.type===2?(E=m,E.size=n):(g=m,g.size=n);return[Object.assign({},g),Object.assign({},E),Object.assign({},u)]}_parseResponse(s,n){return pA(this,void 0,void 0,function*(){try{const{thumbUrl:g,largeUrl:u,downloadUrl:E}=s;if(g&&u&&(yield this._getImageInfoByUrl(g,n,"thumb"),yield this._getImageInfoByUrl(u,n,"large")),Pt.isSimpleCos()&&!Pt.isPrivateNetWork()&&(yield this._getImageInfoArray(E,n),n?.uploadIP)){const m=this._extractDomainFromUrl(E);m&&(yield this._getDownloadIP(m,n))}return n}catch(g){throw g}})}_extractDomainFromUrl(s){var n;try{const g=s.match(/:\/\/([^\/]+)/);return g?g[1]:null}catch(g){return(n=this._core)===null||n===void 0||n.ssoLog.warn("_extractDomainFromUrl",`Failed to extract domain from URL:${g.message}`),null}}_getImageInfoByUrl(s,n,g){return pA(this,void 0,void 0,function*(){var u;try{const E=Pt.addAuthToUrl(s),{width:m=0,height:D=0}=yield Pt.probeImageWidthHeight(E);n.width=m,n.height=D,g==="thumb"?(n.smallImageUrl=s,n.smallImageWidth=m,n.smallImageHeight=D):(n.largeImageUrl=s,n.largeImageWidth=m,n.largeImageHeight=D)}catch(E){(u=this._core)===null||u===void 0||u.ssoLog.warn("_getImageInfoByUrl",`Failed to get ${g} image info:${E.message}`)}})}_validateBeforeUploadImage(s){var n;const{ChatError:g}=(n=this._core)===null||n===void 0?void 0:n.helper;if(!s)throw new g({code:oA});this._checkImageType(s),this._checkImageSize(s)}_processImage(s){var n;try{const{IN_MINI_APP:g}=(n=this._core)===null||n===void 0?void 0:n.utils;let{file:u}=s.payload;return u=g?this._processMiniAppImageFile(u):this._processWebImageFile(u),u}catch(g){throw g}}_processMiniAppImageFile(s){gl(s)&&console.warn("FileUnsupportedInMiniApp","createImageMessage");const n=s.tempFiles[0].path||s.tempFiles[0].tempFilePath;return{url:n,name:n.slice(n.lastIndexOf("/")+1),size:s.tempFiles&&s.tempFiles[0].size||1,type:n.slice(n.lastIndexOf(".")+1).toLowerCase()}}_processWebImageFile(s){var n;const{ChatError:g}=(n=this._core)===null||n===void 0?void 0:n.helper,u=Pt.extractFileFromInput(s);if(!u)throw new g({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return u}_getDownloadIP(s,n){return pA(this,void 0,void 0,function*(){const g=`${ha} getDownloadIP domainName: ${s}`;try{const u=yield function(m,D){return pA(this,void 0,void 0,function*(){try{const{helper:M,channel:T}=D,P="im_cos_msg.get_final_ip",W={str_domain:m},iA=M.generateProtocolData({servcmd:P,data:W}),EA=`${iA.head.seq}${P}`;return yield T.sendPacket(iA,{requestId:EA})}catch(M){throw console.warn("getFinalIP error:",M),M}})}(s,this._core);if(!u||!u.str_final_ip)return;console.log(`${g} ok. downloadIP:${u}`);const E=n.location.split("/");E[0]=u.str_final_ip,n.location=E.join("/")}catch(u){console.warn(u)}})}_getImageInfoArray(s,n){return pA(this,void 0,void 0,function*(){try{const g=yield function(u,E){return pA(this,void 0,void 0,function*(){try{const{helper:m,channel:D}=E,M="im_cos_msg.get_imageinfo",T={str_image_url:u},P=m.generateProtocolData({servcmd:M,data:T}),W=`${P.head.seq}${M}`;return yield D.sendPacket(P,{requestId:W})}catch(m){throw console.warn("getImageInfo error:",m),m}})}(s,this._core);return n.imageInfoArray=this._processImageInfoResponse(g),n}catch(g){throw n.imageInfoArray=void 0,g}})}_processImageInfoResponse(s){if(!s)return[];const{rpt_msg_image_info:n}=s;return n.map(g=>({type:g.uint32_image_type,url:g.str_url,width:g.uint32_width,height:g.uint32_height,imageFormat:g.str_image_format}))}_checkImageType(s){const{utils:n,helper:g}=this._core;let u="";if(n.IN_MINI_APP&&(u=s.url.slice(s.url.lastIndexOf(".")+1)),n.IN_BROWSER&&(u=s.name.slice(s.name.lastIndexOf(".")+1)),tA.indexOf(u.toLowerCase())<0)throw new g.ChatError({code:b})}_checkImageSize(s){const{utils:n,helper:g,store:u}=this._core;let E=0;if(E=(n.IN_MINI_APP,s.size),E===0)throw new g.ChatError({code:L});if(E>=(X(iu)||20971520))throw new g.ChatError({code:x})}_updateImageType(s){s[1].type=XA,s[2].type=wA}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this)}};const DA=2108,GA=2401,VA=2402,ee="2.5.0",Ee="1.18.0";function We(s,n){const g=s.split("."),u=n.split("."),E=Math.max(g.length,u.length);for(;g.lengthM)return 1;if(D0;return{isValid:n,error:n?null:{message:"content can not be empty"}}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},u=g?this.payload:this.content,{uuid:E,downloadFlag:m,fileUrl:D,fileName:M,fileSize:T}=u;return{MsgType:this.type,MsgContent:{Download_Flag:m,Url:Pt.removeAuthToUrl(D),FileName:M,FileSize:T,UUID:E}}}_getFileInfo(n){const{utils:{IN_UNI_NATIVE_APP:g}}=v.core;if(n.fileName&&n.fileSize)return{size:n.fileSize,name:n.fileName};const{file:u}=n;return u?(g&&this._processNativeAppFile(u),{size:u.size,name:u.name}):{size:0,name:""}}_processNativeAppFile(n){if(n.path&&n.path.includes(".")){const g=n.path.slice(n.path.lastIndexOf(".")+1).toLowerCase();n.type=g,n.name||(n.name=`${Lr(999999)}.${g}`)}n.name||(n.type="",n.name=n.path.slice(n.path.lastIndexOf("/")+1).toLowerCase()),n.suffix&&(n.type=n.suffix),n.url||(n.url=n.path)}}ot=Jr;var Ut=new class{constructor(){this._messageOptionsMap=new Map}init(s){var n;this._core=s;const{notificationCenter:g,helper:u,InnerEvent:E,message:m}=s;u.registerApi({apiName:"createFileMessage",context:this}),u.registerExperimentalAPI("createFileMessage",this,"createCustomUploadFileMessage"),(n=m?.messageFactory)===null||n===void 0||n.registerElementClass(Ya,at),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createFileMessage(s){var n,g,u;try{this._checkVersion();const E=this._processFile(s.payload.file);s.payload.file=E;const m=(n=this._core.store.get("login"))===null||n===void 0?void 0:n.userId,D=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:m})),M={uuid:Pt.generateUUID(E),file:E},T=new at(M);return D.setElement(T),this._messageOptionsMap.set(D.clientSequence,s),D}catch(E){throw E}}createCustomUploadFileMessage(s){var n,g,u;try{const{store:E,message:m,utils:{isEmpty:D}}=this._core,M=(n=E.get("login"))===null||n===void 0?void 0:n.userId,{url:T,uuid:P,fileSize:W,fileName:iA=""}=((g=s?.payload)===null||g===void 0?void 0:g.file)||{};if(D(T))throw new Error("url is required");const EA=(u=m.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:M})),RA=new at({url:T,uuid:P,file:{size:W,name:iA},isCustomUpload:!0});return EA.setElement(RA),EA}catch(E){throw E}}upload(s){return pA(this,void 0,void 0,function*(){const{file:n}=this._messageOptionsMap.get(s.clientSequence).payload;this._validateBeforeUploadFile(n);const g=s.getElements()[0],u=yield this._performFileUpload(g,s,n),E=Pt.addAuthToUrl(u?.location);return g.updateFileUrl(E),s})}_validateBeforeUploadFile(s){const{helper:{ChatError:n}}=this._core;if(!s)throw new n({code:GA});const g=X(xE)||104857600;if(s.size>g)throw new n({code:VA});if(s.size===0)throw new n({code:DA})}_performFileUpload(s,n,g){return pA(this,void 0,void 0,function*(){const{to:u}=n,E={uploadFileType:xE,file:g,to:u,message:n,onProgress:D=>{var M,T;s.updatePercent(D),(T=(M=this._messageOptionsMap.get(n.clientSequence))===null||M===void 0?void 0:M.onProgress)===null||T===void 0||T.call(M,D)}},{response:m}=yield q.uploadToCOS(E);return m})}_processFile(s){var n,g;const{IN_BROWSER:u,IN_RN_APP:E,IN_WX_MINI_APP:m,IN_QQ_MINI_APP:D,IN_UNI_NATIVE_APP:M}=(n=this._core)===null||n===void 0?void 0:n.utils,{ChatError:T}=(g=this._core)===null||g===void 0?void 0:g.helper;if(u||M){const P=Pt.extractFileFromInput(s);if(!P)throw new T({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return P}if(m||D){const{tempFiles:P}=s;return Object.assign(Object.assign({},P[0]),{url:P[0].path})}return E?Object.assign(Object.assign({},s),{url:s.uri}):s}_checkVersion(){var s,n;const{MINI_APP_NAMESPACE:g,IN_MINI_APP:u,IN_WX_MINI_APP:E,IN_QQ_MINI_APP:m,IN_UNI_NATIVE_APP:D}=(s=this._core)===null||s===void 0?void 0:s.utils,{ChatError:M}=(n=this._core)===null||n===void 0?void 0:n.helper;if(u){if(!(E||m||D))throw new M({message:"Unsupported mini app environment"});const T=g.getSystemInfoSync().SDKVersion;if(E&&We(T,ee)<0)throw new M({message:`WXChooseMessageFile requires SDK version ${ee} or higher`});if(m&&We(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 Jt=2108,Ui=2351,go=2352,Xi=["mp4","quicktime","mov","video"];var Ei;class Po{constructor(n){this.type=Fl,this.uploadProgress=0,this[Ei]=!1;const g=typeof n?.videoSecond=="number"?n?.videoSecond:0;this[Jr]=n.isCustomUpload||!1,this.content={remoteVideoUrl:Pt.addAuthToUrl(n.remoteVideoUrl||n.videoUrl||""),videoFormat:n.videoFormat,videoSecond:parseInt(g?.toString(),10),videoSize:n.videoSize,videoUrl:Pt.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:Pt.addAuthToUrl(n.thumbUrl),snapshotUrl:Pt.addAuthToUrl(n.thumbUrl)}}static parseServerPushElement(n){const{MsgContent:g}=n,{VideoUrl:u,VideoFormat:E,VideoSecond:m,VideoSize:D,VideoDownloadFlag:M,VideoUUID:T,ThumbUUID:P,ThumbFormat:W,ThumbWidth:iA,SnapshotWidth:EA,ThumbHeight:RA,SnapshotHeight:kA,ThumbSize:xA,SnapshotSize:LA,ThumbDownloadFlag:SA,ThumbUrl:OA,SnapshotUrl:JA}=g;return new Po({videoUrl:u,videoFormat:E,videoSecond:m,videoSize:D,videoDownloadFlag:M,videoUUID:T,thumbUUID:P,thumbFormat:W,thumbWidth:iA,snapshotWidth:EA,thumbHeight:RA,snapshotHeight:kA,thumbSize:xA,snapshotSize:LA,thumbDownloadFlag:SA,thumbUrl:OA,snapshotUrl:JA})}updatePercent(n){this.uploadProgress=Math.min(n,1)}updateVideoUrl(n){n&&(this.content.remoteVideoUrl=n)}updateSnapshotInfo(n){const{snapshotUrl:g,snapshotWidth:u,snapshotHeight:E}=n;Pt.isEmpty(g)||(this.content.thumbUrl=this.content.snapshotUrl=g),Pt.isEmpty(u)||(this.content.thumbWidth=this.content.snapshotWidth=Number(u)),Pt.isEmpty(E)||(this.content.thumbHeight=this.content.snapshotHeight=Number(E))}validateBeforeSend(){if(this[Jr])return{isValid:!0};const n=this.content.remoteVideoUrl!=="";return{isValid:n,error:n?null:{message:"content can not be empty"}}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},u=g?this.payload:this.content,{remoteVideoUrl:E,videoFormat:m,videoSecond:D,videoSize:M,videoDownloadFlag:T,videoUUID:P,thumbUUID:W,thumbFormat:iA,thumbWidth:EA,snapshotWidth:RA,thumbHeight:kA,snapshotHeight:xA,thumbSize:LA,snapshotSize:SA,thumbDownloadFlag:OA,thumbUrl:JA,snapshotUrl:ae}=u;return{MsgType:this.type,MsgContent:{VideoUrl:Pt.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:Pt.removeAuthToUrl(JA),SnapshotUrl:Pt.removeAuthToUrl(ae)}}}}Ei=Jr;var es,pi=new class{constructor(){this._messageOptionsMap=new Map}init(s){var n;this._core=s;const{notificationCenter:g,helper:u,InnerEvent:E,message:m}=s;u.registerApi({apiName:"createVideoMessage",context:this}),u.registerExperimentalAPI("createVideoMessage",this,"createCustomUploadVideoMessage"),(n=m?.messageFactory)===null||n===void 0||n.registerElementClass(Fl,Po),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createVideoMessage(s){var n,g,u;try{const E=this._processVideo(s);s.payload.file=E;const m=(n=this._core.store.get("login"))===null||n===void 0?void 0:n.userId,D=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:m})),M={videoFormat:E.videoFile.type,videoSecond:ar(E.videoFile.second,0),videoSize:E.videoFile.size,remoteVideoUrl:"",videoUrl:E.videoFile.url,videoUUID:Pt.generateUUID(E.videoFile),thumbUUID:Pt.generateUUID(E.videoFile,"jpg"),thumbWidth:E.width||200,thumbHeight:E.height||200,thumbUrl:E.thumbUrl,thumbSize:E.thumbSize,thumbFormat:"jpg"},T=new Po(M);return D.setElement(T),this._messageOptionsMap.set(D.clientSequence,s),D}catch(E){throw E}}createCustomUploadVideoMessage(s){var n,g,u;try{const{store:E,message:m}=this._core;this._validateCustomUploadVideoMessage(s);const D=(n=E.get("login"))===null||n===void 0?void 0:n.userId,{videoUrl:M,videoUuid:T,duration:P,snapshotUrl:W,snapshotUuid:iA,videoFileSize:EA,videoType:RA,snapshotWidth:kA,snapshotHeight:xA,snapshotFileSize:LA,snapshotType:SA="jpg"}=((g=s?.payload)===null||g===void 0?void 0:g.file)||{},OA=(u=m.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:D})),JA=new Po({videoFormat:RA,videoSecond:P||0,videoSize:EA,remoteVideoUrl:M,videoUrl:M,videoUUID:T,thumbUUID:iA,thumbWidth:kA||200,thumbHeight:xA||200,thumbUrl:W,thumbSize:LA,thumbFormat:SA,isCustomUpload:!0});return OA.setElement(JA),this._messageOptionsMap.set(OA.clientSequence,s),OA}catch(E){throw E}}upload(s){return pA(this,void 0,void 0,function*(){const n=s.getElements()[0],{file:g}=this._messageOptionsMap.get(s.clientSequence).payload;this._validateBeforeUploadVideo(g);const u=yield this._performVideoUpload(n,s,g),{location:E,snapshotInfo:m}=u,D=Pt.addAuthToUrl(E);return n.updateVideoUrl(D),Pt.isEmpty(m)||n.updateSnapshotInfo(m),s})}_validateBeforeUploadVideo(s){const{helper:{ChatError:n}}=this._core,g=X(Ba)||104857600;if(s.videoFile.size>g)throw new n({code:Ui});if(s.videoFile.size===0)throw new n({code:Jt});if(Xi.indexOf(s.videoFile.type)===-1)throw new n({code:go})}_validateCustomUploadVideoMessage(s){var n;const{utils:{isEmpty:g,isNumber:u}}=this._core,{videoUrl:E,videoUuid:m,duration:D,snapshotUrl:M,snapshotUuid:T}=((n=s?.payload)===null||n===void 0?void 0:n.file)||{};if(g(E)||g(m)||!u(D)||g(M)||g(T))throw new Error("Invalid video message options: missing required fields (videoUrl, videoUuid, duration, snapshotUrl, snapshotUuid)")}_performVideoUpload(s,n,g){return pA(this,void 0,void 0,function*(){const{to:u}=n,E={uploadFileType:Ba,file:g,to:u,message:n,onProgress:M=>{var T,P;s.updatePercent(M),(P=(T=this._messageOptionsMap.get(n.clientSequence))===null||T===void 0?void 0:T.onProgress)===null||P===void 0||P.call(T,M)}},{response:m,uploadOptions:D}=yield q.uploadToCOS(E);return{snapshotInfo:yield this._getSnapshotInfoByUrl(D.requestSnapshotUrl),location:m.location}})}_processVideo(s){var n,g;try{const{ChatError:u}=(n=this._core)===null||n===void 0?void 0:n.helper,{IN_MINI_APP:E,IN_BROWSER:m}=(g=this._core)===null||g===void 0?void 0:g.utils;let{file:D}=s.payload,M={};if(E&&(M=this._processMiniVideoFile(D),D.name=M.name,D.url=M.url,D.type=M.type),m){const T=Pt.extractFileFromInput(D);if(!T)throw new u({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});D=T,M=this._processWebVideoFile(D)}return D.videoFile=M,D.thumbUrl="",D.thumbSize=0,D}catch(u){throw console.warn(`${ha} _processFile error:`,u),u}}_processMiniVideoFile(s){const{utils:{IN_UNI_NATIVE_APP:n},helper:{ChatError:g}}=this._core;if(gl(s))throw new g({message:"FileUnsupportedInMiniApp"});Array.isArray(s.tempFiles)&&(s=s.tempFiles[0]);let u=s.tempFilePath.slice(s.tempFilePath.lastIndexOf(".")+1).toLowerCase();return n&&(u=s.fileType||u),{url:s.tempFilePath,name:s.tempFilePath.slice(s.tempFilePath.lastIndexOf("/")+1),size:s.size||1,second:s.duration||0,type:u}}_processWebVideoFile(s){const{name:n,size:g=1,duration:u=0,type:E}=s,m=E.split("/")[1];return{url:window.URL.createObjectURL(s),name:n,size:g,second:u,type:m}}_getSnapshotInfoByUrl(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n}=this._core;try{n.debug("_getSnapshotInfoByUrl",`${ha} _getSnapshotInfoByUrl url:${s}`);const g={version:1,platform:Pt.getPlatform(),cover_name:Ig(Lr(99999)),snapshot_url:s},u=yield function(T,P){return pA(this,void 0,void 0,function*(){try{const W="im_cos_msg.video_cover",{helper:iA,channel:EA}=P,RA=iA.generateCosSpecifiedData({servcmd:W,data:T}),kA=`${RA.head.seq}${W}`;return yield EA.sendPacket(RA,{requestId:kA})}catch(W){throw console.warn("getSnapshotInfo error:",W),W}})}(g,this._core),{download_url:E}=u||{};if(n.debug("_getSnapshotInfoByUrl",`${ha} _getSnapshotInfoByUrl OK snapshotUrl:${E}`),Pt.isEmpty(E))return{};const m=Pt.addAuthToUrl(E),{width:D=0,height:M=0}=yield Pt.probeImageWidthHeight(m);return{snapshotUrl:m,snapshotWidth:D,snapshotHeight:M}}catch(g){throw g}})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this)}};class ji{constructor(n){this.uploadProgress=0,this.type=Fg,this[es]=!1,this[Jr]=n.isCustomUpload||!1,this.content={downloadFlag:2,second:n.second,size:n.size,url:Pt.generateURL(n.url,{needAddAuthToUrl:!this[Jr]}),remoteAudioUrl:Pt.addAuthToUrl(n.url||""),uuid:n.uuid}}static parseServerPushElement(n){const{MsgContent:g}=n,{Url:u,Download_Flag:E,Second:m,Size:D,UUID:M}=g;return new ji({url:u,downloadFlag:E,second:m,size:D,uuid:M})}updatePercent(n){this.uploadProgress=Math.min(n,1)}updateAudioUrl(n){this.content.remoteAudioUrl=n}validateBeforeSend(){if(this[Jr])return{isValid:!0};const n=this.content.remoteAudioUrl!=="";return{isValid:n,error:n?null:{message:"content can not be empty"}}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},u=g?this.payload:this.content,{uuid:E,downloadFlag:m,remoteAudioUrl:D,size:M,second:T}=u;return{MsgType:this.type,MsgContent:{Url:Pt.removeAuthToUrl(D),Download_Flag:m,Second:T,Size:M,UUID:E}}}}es=Jr;const Ws=2108,_e=2300,_t=2301;var FA=new class{constructor(){this._messageOptionsMap=new Map}init(s){var n;this._core=s;const{notificationCenter:g,helper:u,InnerEvent:E,message:m}=s;u.registerApi({apiName:"createAudioMessage",context:this}),u.registerExperimentalAPI("createAudioMessage",this,"createCustomUploadAudioMessage"),(n=m?.messageFactory)===null||n===void 0||n.registerElementClass(Fg,ji),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createAudioMessage(s){var n,g,u;try{let{file:E}=s.payload;E=this._processAudioFile(s.payload.file),s.payload.file=E;const m=(n=this._core.store.get("login"))===null||n===void 0?void 0:n.userId,D=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:m})),M={second:Math.max(1,Math.round((E.duration||E.second)/1e3)),size:E.fileSize||E.size||1,url:E.tempFilePath||E.uri||E.url,uuid:Pt.generateUUID(E)},T=new ji(M);return D.setElement(T),this._messageOptionsMap.set(D.clientSequence,s),D}catch(E){throw E}}createCustomUploadAudioMessage(s){var n,g,u;try{this._validateCustomUploadOptions(s);const{store:E,message:m}=this._core,D=(n=E.get("login"))===null||n===void 0?void 0:n.userId,{url:M,uuid:T,duration:P,fileSize:W}=((g=s?.payload)===null||g===void 0?void 0:g.file)||{},iA=(u=m.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:D})),EA=new ji({second:P,size:W||1,url:M,uuid:T,isCustomUpload:!0});return iA.setElement(EA),this._messageOptionsMap.set(iA.clientSequence,s),iA}catch(E){throw E}}upload(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g}}=this._core;n.debug("upload",`${ha} uploadAudio message:${g(s)}`);const{file:u}=this._messageOptionsMap.get(s.clientSequence).payload;this._validateBeforeUploadAudio(u);const E=s.getElements()[0],m=yield this._performAudioUpload(E,s,u),D=Pt.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 u=X(cl)||20971520;if(s.size>u)throw new n({code:_t});if(s.size===0)throw new n({code:Ws})}_performAudioUpload(s,n,g){return pA(this,void 0,void 0,function*(){const{to:u}=n,E={uploadFileType:cl,file:g,to:u,message:n,onProgress:D=>{var M,T;s.updatePercent(D),(T=(M=this._messageOptionsMap.get(n.clientSequence))===null||M===void 0?void 0:M.onProgress)===null||T===void 0||T.call(M,D)}},{response:m}=yield q.uploadToCOS(E);return m})}_processAudioFile(s){var n;const{IN_MINI_APP:g,IN_BROWSER:u}=(n=this._core)===null||n===void 0?void 0:n.utils;return g?this._processMiniFile(s):u?this._processWebFile(s):void 0}_processMiniFile(s){return{url:s.tempFilePath,name:s.tempFilePath.slice(s.tempFilePath.lastIndexOf("/")+1),size:s.fileSize,second:s.duration,type:s.tempFilePath.slice(s.tempFilePath.lastIndexOf(".")+1).toLowerCase()}}_processWebFile(s){if(s.tempFilePath||s.uri)return s;const n=URL.createObjectURL(s);return s.tempFilePath=n,s}_validateCustomUploadOptions(s){var n;const{utils:{isEmpty:g}}=this._core,{url:u,uuid:E,duration:m}=((n=s?.payload)===null||n===void 0?void 0:n.file)||{};if(g(u)||g(E)||g(m))throw new Error("Invalid audio message options")}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this)}};const Xt={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:Xt,createAudioMessage:Xt,createVideoMessage:Xt,createFileMessage:Xt},Ai={createImageMessage:!0,createAudioMessage:!0,createVideoMessage:!0,createFileMessage:!0},us={[ic]:rA,[Ya]:Ut,[Fl]:pi,[Fg]:FA};var vi=new class{constructor(){this.name="RichMediaMessage"}install(s){this._core=s;const{constants:{OuterConstant:{MSG_AUDIO:n,MSG_FILE:g,MSG_IMAGE:u,MSG_VIDEO:E}}}=s;v.init(s),rA.init(s),Ut.init(s),pi.init(s),FA.init(s),q.init(s),Pt.init(s),s.helper.registerApi({apiName:"sendMessage",context:this,matcher:m=>[n,g,u,E].includes(m[0].type)}),s.helper.registerValidateConfig({auth:Ai,params:En})}sendMessage(s,n){return pA(this,void 0,void 0,function*(){var g,u,E;try{return this._isCustomUpload(s)||(yield this._upload(s)),yield(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageSender)===null||E===void 0?void 0:E.sendMessage(s,n)}catch(m){throw m}})}_upload(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g}}=this._core;if(n.debug("_upload",` uploadFile message:${g(s)}`),s._relayFlag!==!0)try{const u=us[s.type];u&&(yield u.upload(s),n.info("_upload",` type:${s.type}`))}catch(u){throw s.status=ou.FAIL,u instanceof Error&&(u.data={message:s}),this._core.message.messageDataHandler.storeConversationMessage(s),u}})}_isCustomUpload(s){var n,g;return((g=(n=s._elements)===null||n===void 0?void 0:n[0])===null||g===void 0?void 0:g[Jr])===!0}};const ho=new class{init(s){this.core=s}};class ht{constructor(n){this.conversationID=n.conversationID||"",this.unreadCount=n.unreadCount||0,this.type=n.type||"",this.lastMessage=ho.core.common.buildLastMessage(n.lastMessage),this.peerReadTime=n.peerReadTime||0,this.groupAtInfoList=[],this.remark=n.remark||"",this.isPinned=n.isPinned||!1,this.messageRemindType=n.messageRemindType,this.markList=n.markList||[],this.customData=n.customData||"",this.conversationGroupList=n.conversationGroupList||[],this.draftText=n.draftText||"",this.userProfile=n.userProfile,this.groupProfile=n.groupProfile,this.subType=n.subType||"",this._isInfoCompleted=!1,this._init()}_init(){var n;const{core:{OuterConstant:g,utils:{isUndefined:u}}}=ho;u(this.userProfile)&&this.type===g.CONV_C2C?this.userProfile={userID:this.conversationID.replace(g.CONV_C2C,"")}:this.type===g.CONV_GROUP&&(!this.subType&&(!((n=this.groupProfile)===null||n===void 0)&&n.type)&&(this.subType=this.groupProfile.type),u(this.groupProfile)&&(this.groupProfile={groupID:this.conversationID.replace(g.CONV_GROUP,""),selfInfo:{},lastMessage:{},type:this.subType}))}updateUnreadCount(n){var g;const{core:{OuterConstant:u,utils:{isUndefined:E},store:m}}=ho,{nextUnreadCount:D,isFromGetConversations:M,isUnreadC2CMessage:T}=n;if(E(D))return;if(this.subType===u.GRP_AVCHATROOM)return void(this.unreadCount=0);if(M&&this.type===u.CONV_GROUP)return void(this.unreadCount=D);if(T&&this.type===u.CONV_C2C)return void(this.unreadCount=D);const P=((g=m.get("cloudConfig"))===null||g===void 0?void 0:g.support_unread_count_for_meeting)==="1";this.subType!==u.GRP_MEETING||P?this.unreadCount+=D:this.unreadCount=0}updateLastMessage(n){this.lastMessage=ho.core.common.buildLastMessage(n)}reduceUnreadCount(){return this.unreadCount>=1&&(this.unreadCount-=1,!0)}isLastMessageRevoked(n){const{core:{OuterConstant:g}}=ho,{sequence:u,time:E}=n;return this.type===g.CONV_C2C&&u===this.lastMessage.lastSequence&&E===this.lastMessage.lastTime||this.type===g.CONV_GROUP&&u===this.lastMessage.lastSequence}setLastMessageRevoked(n){this.lastMessage.isRevoked=n}setLastMessageRevoker(n){this.lastMessage.revoker=n}setDraftText(n){this.draftText=n}updateGroupAtInfoList(n){const{core:{common:{updateGroupAtInfo:g}}}=ho;g(n,this.groupAtInfoList)}clearGroupAtInfoList(){this.groupAtInfoList.length=0}getProfileCompleted(){return this._isInfoCompleted}setProfileCompleted(){this._isInfoCompleted=!0}}const Qt=s=>{const{core:{OuterConstant:n,utils:{isString:g}}}=ho;return g(s)&&s.slice(0,3)===n.CONV_C2C},ug=s=>{const{core:{OuterConstant:n,utils:{isString:g}}}=ho;return g(s)&&s.slice(0,5)===n.CONV_GROUP},ks=s=>{const{core:{OuterConstant:n,utils:{isString:g}}}=ho;return g(s)&&s===n.CONV_SYSTEM};function Wi(s){const{OuterConstant:n}=ho.core;let g="";return s===0?g=n.MSG_REMIND_ACPT_AND_NOTE:s===1?g=n.MSG_REMIND_DISCARD:s===2?g=n.MSG_REMIND_ACPT_NOT_NOTE:s===3&&(g=n.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),g}function Hr(s){const{OuterConstant:n}=ho.core;let g;return s.startsWith(n.CONV_C2C)&&(g=s.replace(n.CONV_C2C,"")),g==="@TLS#ERROR"||g==="@TLS#NOT_FOUND"}function oc(s,n){const{helper:g}=ho.core,u=new g.ChatError({functionName:s,code:n?.errorCode||n?.code,message:n?.errorInfo||n?.message});throw console.error(`${s} fail:`,u),u}var is,ga;(function(s){s[s.OFF=0]="OFF",s[s.ON=1]="ON"})(is||(is={})),function(s){s[s.ONLY_CONVERSATIONID=1]="ONLY_CONVERSATIONID"}(ga||(ga={}));var Qa;(function(s){s[s.CONV_NOT_FOUND=2500]="CONV_NOT_FOUND",s[s.USER_OR_GRP_NOT_FOUND=2501]="USER_OR_GRP_NOT_FOUND",s[s.CONV_UN_RECORDED_TYPE=2502]="CONV_UN_RECORDED_TYPE"})(Qa||(Qa={}));const ea=0,H=1;var BA=new class{constructor(){this._name="GetC2CMessageRemindType"}init(s){this._core=s}get(s){return pA(this,void 0,void 0,function*(){try{const{common:n}=this._core,g=yield function(E,m){return pA(this,void 0,void 0,function*(){const{toAccount:D,userIDList:M}=E,T={To_Account:D,Peer_Account:M};return m.common.buildAndSendPacket({servcmd:"openim.get_c2c_peer_mute_notifications",data:T})})}({toAccount:n.getCurrentUserID(),userIDList:s},this._core),{MuteNotificationsList:u=[]}=g||{};u.forEach(E=>{const{Peer_Account:m,MuteNotifications:D}=E,M=`${this._core.OuterConstant.CONV_C2C}${m}`,T=Wi(D);NA.patchMessageRemindType([M],T)})}catch(n){console.error(`${this._name}.get fail:`,n)}})}},yA=new class{constructor(){this._name="GetGroupMessageRemindType"}init(s){this._core=s}get(s){return pA(this,void 0,void 0,function*(){if(s.length!==0)try{const n=yield function(u,E){return pA(this,void 0,void 0,function*(){const{groupIDList:m,responseFilter:D}=u,M={GroupIdList:m,ResponseFilter:D};return E.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_self_member_info",data:M})})}({groupIDList:s,responseFilter:{MemberInfoFilter:["MsgFlag"]}},this._core),{GroupInfo:g=[]}=n||{};g.forEach(u=>{var E;const{GroupId:m,MemberList:D}=u,M=((E=D[0])===null||E===void 0?void 0:E.MsgFlag)||"",T=`${this._core.OuterConstant.CONV_GROUP}${m}`;NA.patchMessageRemindType([T],M)})}catch(n){console.error(`${this._name}.get fail:`,n)}})}},NA=new class{constructor(){this._name="ConversationDataHandler",this._totalUnreadCount=0,this._groupAtTipsList=[]}init(s){this._core=s;const{helper:n,notificationCenter:g,appStore:{conversationStore:u},constants:{WORKFLOW_NAME:E,WORKFLOW_STEP:m},InnerEvent:{SYNC_CONVERSATION_LIST:D,MESSAGE_PUSH:M,NEW_MESSAGE:T,MESSAGE_DELETED:P,MESSAGE_REVOKED:W,MESSAGE_MODIFIED:iA,CONVERSATION_UPDATED:EA,LOGOUT:RA,DESTROY:kA},InnerEventSubType:{C2C_MESSAGE_PEER_READ:xA}}=s;this._conversationStore=u,n.registerWorkflowStep(E.SYNC_SERVER_INFO_AFTER_LOGIN,m.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),n.registerWorkflowStep(E.SYNC_SERVER_INFO_AFTER_LOGIN,m.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,this._handleGroupListSyncFinished,this),n.registerWorkflowStep(E.RECEIVE_C2C_NEW_MESSAGE,m.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),n.registerWorkflowStep(E.RECEIVE_C2C_NEW_MESSAGE,m.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),n.registerWorkflowStep(E.RECEIVE_GROUP_NEW_MESSAGE,m.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),n.registerWorkflowStep(E.SYNC_SERVER_INFO_AFTER_RE_ONLINE,m.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),n.registerWorkflowStep(E.RECEIVE_GROUP_TIPS_NOTIFICATION,m.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this);const{InnerEventSubType:{GROUP_AT_TIPS:LA}}=g;g.subscribeInnerEvent(D,this._handleConversationSynced,this),g.subscribeInnerEvent(T,this._handleNewMessage,this),g.subscribeInnerEvent(M,LA,this._handleNewGroupAtTips,this),g.subscribeInnerEvent(P,this._handleMessageDeleted,this),g.subscribeInnerEvent(W,this._handleMessageRevoked,this),g.subscribeInnerEvent(iA,this._handleMessageModified,this),g.subscribeInnerEvent(EA,this._handleConversationUpdated,this),g.subscribeInnerEvent(M,xA,this._handleMessageRead,this),g.subscribeInnerEvent(RA,this._reset,this),g.subscribeInnerEvent(kA,this._dispose,this),s.ssoLog.debug(`${this._name}.init`)}_handleConversationSynced(s){this.updateLocalConversationList({conversationUpdateFieldList:s.conversationUpdateFieldList||[],isFromGetConversations:!0,updateUnreadCount:!0}),this.emitConversationListUpdate()}_handleUnreadSyncFinished(s){const{constants:{WORKFLOW_STEP:n}}=this._core,{conversationUpdateFieldList:g=[],groupTipList:u=[],isUnreadC2CMessage:E}=s.result[n.UNREAD_MESSAGE_SYNC]||{};let m=!1;g.forEach(D=>{const{conversationID:M,unreadCount:T}=D,P=this.getLocalConversation(M);P&&P.unreadCount!==T&&(P.updateUnreadCount({nextUnreadCount:T,isUnreadC2CMessage:E}),m=!0)}),m&&this.emitConversationListUpdate(),this._handleGroupAtTipsSynced(u)}_handleGroupAtTipsSynced(s){var n;for(let g=0;g0&&this._handleNewGroupAtTips({GroupTips:M._groupAtInfoList}),m=!0}m&&this.emitConversationListUpdate()}_handleNewMessage(s){const{conversationUpdateFieldList:n=[],isInstantMessage:g=!0,isUnreadC2CMessage:u=!1,updateUnreadCount:E=!0}=s.result||{};if(n.length===0)return;const{common:{isTopic:m}}=this._core;m(n[0].conversationID)||(this.updateLocalConversationList({conversationUpdateFieldList:n,isInstantMessage:g,isUnreadC2CMessage:u,isFromGetConversations:!1,updateUnreadCount:E}),n.filter(D=>this._isConversationNeedShow(D.conversationID)).length>0&&this.emitConversationListUpdate())}_handleNewGroupAtTips(s){const{GroupTips:n=[]}=s;n.forEach(g=>{const{GroupAtTips:u,MsgBody:E,MsgRandom:m,ClientSeq:D}=g;let M={};u?M=this._convertGroupAtTipsKey(u):E?M=Object.assign({},this._convertGroupAtTipsKey(E)):g.groupAtType&&(M=Object.assign({},g)),M.__random=m,M.__sequence=D,this._groupAtTipsList.push(M)}),console.log(`${this._name}._handleNewGroupAtTips groupAtTipsList: ${JSON.stringify(this._groupAtTipsList)}`),this._updateGroupAtInfoList()}_convertGroupAtTipsKey(s){const{From_Account:n,GroupId:g,MsgSeq:u,GroupAtType:E}=s;return{from:n,groupID:g,sequence:u,groupAtType:E}}_updateGroupAtInfoList(){if(this._groupAtTipsList.length===0)return;const{common:s,OuterConstant:n}=this._core,g=s.getCurrentUserID();let u=!1;this._groupAtTipsList.forEach(E=>{const{groupID:m,from:D}=E;if(D!==g){const M=this.getLocalConversation(`${n.CONV_GROUP}${m}`);M&&(M.updateGroupAtInfoList(E),u=!0)}}),u&&this.emitConversationListUpdate(),this._groupAtTipsList.length=0}_handleMessageDeleted(s){var n,g;console.log(`${this._name}._handleMessageDeleted, conversationID:`,s);const{message:{messageDataHandler:u},OuterConstant:E}=this._core,m=u?.getLocalMessageList(s)||[];let D={};for(let P=(m.length||0)-1;P>=0;P--)if(!m[P].isDeleted&&m[P]._isExcludedFromLastMessage!==!0){D=m[P];break}const M=this.getLocalConversation(s);if(!M)return;let T=!1;M.lastMessage.lastSequence===D.sequence&&M.lastMessage.lastTime===D.time||(!((g=(n=this._core)===null||n===void 0?void 0:n.helper)===null||g===void 0)&&g.isEmpty(D)&&(D=void 0),M.updateLastMessage(D),T=!0),s.startsWith(E.CONV_C2C)&&this.updateUnreadCount(s),T&&(this.emitConversationListUpdate(),console.log(`${this._name}._handleMessageDeleted. update conversationID:${s} with lastMessage:`,M.lastMessage))}_handleMessageRevoked(s){const{messageList:n=[],updateUnreadCount:g=!0}=s;if(console.log(`${this._name}._handleMessageRevoked messageList:${n.length}`),n.length===0)return;let u=null,E=!1;n.forEach(m=>{u=this.getLocalConversation(m.conversationID),u&&(g&&u.reduceUnreadCount()&&(E=!0),u.isLastMessageRevoked({sequence:m.sequence,time:m.time})&&(u.setLastMessageRevoked(!0),u.setLastMessageRevoker(m.revoker),E=!0))}),E&&this.emitConversationListUpdate()}_handleMessageModified(s){const{utils:{isEmpty:n},common:{getMessagePreviewText:g},ssoLog:u}=this._core;u.debug(`${this._name}._handleMessageModified`,JSON.stringify(s));const{conversationID:E,messageList:m}=s,D=this.getLocalConversation(E);if(n(D))return;const{lastMessage:M}=D;if(M){const T=m?.[0]||{};M.lastTime===T.time&&M.lastSequence===T.sequence&&M.version!==T.version&&(M.type=T.type,M.payload=T.payload,M.messageForShow=g(T.type,T.payload),M.cloudCustomData=T.cloudCustomData,M.version=T.version,this.emitConversationListUpdate(),console.log(`${this._name} conversationID:${E} lastMessage updated`))}}_handleConversationUpdated(s){this.emitConversationListUpdate(s?.needSort)}updateLocalConversationList(s){const{isFromGetConversations:n}=s,{newConversationList:g}=this._getTmpConversationListMapping(s);this._sortConversationList(),n||this._updateNewConversationProfile(g),this._core.ssoLog.debug("updateLocalConversationList",` newConversationList: ${g.length}`)}_getTmpConversationListMapping(s){const{OuterConstant:n}=this._core,{conversationUpdateFieldList:g,isFromGetConversations:u,isInstantMessage:E,isUnreadC2CMessage:m=!1,updateUnreadCount:D}=s,M=[],T=g?.length;for(let P=0;P{M[1].isPinned===!0?s(M[1].lastMessage.lastTime)?u.push(M):g.push(M):s(M[1].lastMessage.lastTime)?m.push(M):E.push(M)});const D=g.sort((M,T)=>T[1].lastMessage.lastTime-M[1].lastMessage.lastTime).concat(u).concat(E.sort((M,T)=>T[1].lastMessage.lastTime-M[1].lastMessage.lastTime)).concat(m);this._updateConversationMapFromList(D)}_updateNewConversationProfile(s){if(s.length===0)return;const n=[],g=[],{OuterConstant:{CONV_GROUP:u,CONV_C2C:E}}=this._core;s.forEach(m=>{const{conversationID:D,type:M}=m;if(M===E){const T=D.replace(E,"");n.push(T)}else if(M===u){const T=D.replace(u,"");g.push(T)}}),n.length>0&&this._updateC2CConversation(n),g.length>0&&this._updateGroupConversation(g)}_updateC2CConversation(s){var n;const{OuterConstant:{CONV_C2C:g},appStore:{userStore:u},user:E}=this._core;let m=!1;(n=E.userProfile)===null||n===void 0||n.getUserProfile({userIDList:s}).then(D=>{(D?.data||[]).forEach(M=>{var T;const{userID:P}=M,W=this.getLocalConversation(`${g}${P}`);if(W){const iA=((T=u.getFriend(P))===null||T===void 0?void 0:T.remark)||"";W.remark=iA,W.userProfile=M,m=!0}}),m&&this.emitConversationListUpdate()}).catch(D=>{}),BA.get(s)}_updateGroupConversation(s){return pA(this,void 0,void 0,function*(){const{OuterConstant:{CONV_GROUP:n},appStore:{groupStore:g},utils:{safeStringify:u},ssoLog:E,apiMap:{getGroupProfile:m}}=this._core;let D=!1;try{yield Promise.all(s.map(M=>pA(this,void 0,void 0,function*(){const T=g.getGroup(M),P=this.getLocalConversation(`${n}${M}`);T&&P&&(P.groupProfile=T,D=!0),P&&!P.getProfileCompleted()&&typeof m=="function"&&(yield m({groupID:M}))}))),yA.get(s),D&&this.emitConversationListUpdate()}catch(M){E.debug("_updateGroupConversation",u(M))}})}_handleMessageRead(s){const{OuterConstant:{CONV_C2C:n}}=this._core,{C2cNotifyMsgArray:g=[]}=s||{};g.forEach(u=>{const{To_Account:E,UinPairReadArray:m=[]}=u?.C2cReadedReceipt||{};m?.forEach(D=>{const{LastReadTime:M}=D,T=`${n}${E}`;this._updateConversationReadInfo({conversationID:T,peerReadTime:M}),this._updateMessageListPeerRead({conversationID:T,peerReadTime:M})})})}_updateConversationReadInfo(s){const{appStore:n,utils:{isEmpty:g},common:{getCurrentUserID:u}}=this._core,{conversationID:E,peerReadTime:m}=s,D=n.conversationStore.getConversationMap();if(D.has(E)){const M=D.get(E);M.peerReadTime=m;const T=M?.lastMessage;g(T)||T.fromAccount===u()&&T.lastTime<=m&&!T.isPeerRead&&(T.isPeerRead=!0,n.conversationStore.updateConversation(E,{lastMessage:T}))}}_updateMessageListPeerRead(s){const{notificationCenter:n,OuterEvent:g,message:u}=this._core,{conversationID:E,peerReadTime:m}=s,D=u.messageDataHandler.getLocalMessageList(E),M=u.messageDataHandler.getSparseMessageList(E),T=[];D.forEach(P=>{P.time<=m&&!P.isPeerRead&&P.flow==="out"&&(P.isPeerRead=!0,T.push(P))}),M.forEach(P=>{P.time<=m&&!P.isPeerRead&&P.flow==="out"&&(P.isPeerRead=!0,T.push(P))}),n.emitOuterEvent(g.MESSAGE_READ_BY_PEER,{name:g.MESSAGE_READ_BY_PEER,data:T})}_isConversationNeedShow(s){var n,g;const{OuterConstant:{CONV_GROUP:u,GRP_ROOM:E,GRP_LIVE:m},utils:{isUndefined:D}}=this._core,M=this.getLocalConversation(s);if(D(M))return!0;const T=M.type===u&&((n=M.groupProfile)===null||n===void 0?void 0:n.type)===E,P=M.type===u&&((g=M.groupProfile)===null||g===void 0?void 0:g.type)===m;return!(T||P)}updateUnreadCount(s,n=!0){var g,u;let E=!1;const m=this.getLocalConversation(s),D=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageDataHandler)===null||u===void 0?void 0:u.getLocalMessageList(s);if(!m)return E;const M=m.unreadCount,T=D?.filter(P=>!P.isRead&&!P._onlineOnlyFlag&&!P.isDeleted).length;return console.log(`${this._name}._updateUnreadCount conversationID:${s} currentUnreadCount:${M} newUnreadCount:${T}`),M!==T&&(m.unreadCount=T,E=!0,n===!0&&this.emitConversationListUpdate()),E}emitConversationListUpdate(s=!1){var n,g;s&&this._sortConversationList();const{OuterEvent:{CONVERSATION_LIST_UPDATED:u},conversation:E}=this._core,m=this.getLocalConversationList();this._emitEvent({name:u,data:m,isSyncCompleted:(g=(n=E?.syncConversationHandler)===null||n===void 0?void 0:n.isSyncCompleted)===null||g===void 0?void 0:g.call(n)}),this._emitTotalUnreadCountUpdate()}_emitTotalUnreadCountUpdate(){var s;const n=this.getTotalUnreadMessageCount();this._totalUnreadCount!==n&&(this._core.ssoLog.debug("_emitTotalUnreadCountUpdate",` from ${this._totalUnreadCount} to ${n}`),this._totalUnreadCount=n,this._emitEvent({name:(s=this._core)===null||s===void 0?void 0:s.OuterEvent.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED,data:n}))}_emitEvent(s){var n;(n=this._core)===null||n===void 0||n.notificationCenter.emitOuterEvent(s.name,s)}getTotalUnreadMessageCount(){const{OuterConstant:s,utils:{isEmpty:n}}=this._core,g=this.getLocalConversationList();let u=0;return g.forEach(E=>{E.type!==s.CONV_SYSTEM&&(n(E.messageRemindType)||E.messageRemindType===s.MSG_REMIND_ACPT_AND_NOTE)&&(u+=E.unreadCount)}),u}getLocalConversationList(){return[...this._conversationStore.getConversationMap().values()].filter(s=>this._isConversationNeedShow(s.conversationID))}hasLocalConversation(s){return this._conversationStore.getConversationMap().has(s)}getLocalConversation(s){return this._conversationStore.getConversationMap().get(s)}setLocalConversation(s,n){return this._conversationStore.getConversationMap().set(s,n)}deleteLocalConversation(s){this._conversationStore.getConversationMap().delete(s)}_updateConversationMapFromList(s){this._clearConversationMap();for(const[n,g]of s)this.setLocalConversation(n,g)}_clearConversationMap(){this._conversationStore.getConversationMap().clear()}patchMessageRemindType(s,n){let g=!1;s.forEach(u=>{const E=this.getLocalConversation(u);E?.messageRemindType!==n&&(E.messageRemindType=n,g=!0)}),console.log(`${this._name}.patchMessageRemindType conversationIDList:${s} messageRemindType:${n} hasUpdated:${g}`),g&&this.emitConversationListUpdate()}markMessageAsRead(s){const{message:{messageDataHandler:n}}=this._core,{conversationID:g,lastReadTime:u=0,lastReadSequence:E=0}=s,m=n?.getLocalMessageList(g);if(m.length===0)return;const{length:D}=m;for(let M=D-1;M>=0;M--){const T=m[M],P=u&&T.time>u,W=E&&T.sequence>E;if(!P&&!W){if(T.flow==="in"&&T.isRead)break;T.setIsRead(!0)}}}appendToPinnedConversation(s){const n=[...this._conversationStore.getConversationMap().entries()],g=n.findIndex(u=>u[1].isPinned===!1);n.splice(g,0,[s.conversationID,s]),this._updateConversationMapFromList(n),this.emitConversationListUpdate()}_reset(){this._clearConversationMap(),this._totalUnreadCount=0,this._groupAtTipsList=[]}_dispose(){const{notificationCenter:s,InnerEvent:{NEW_MESSAGE:n,MESSAGE_DELETED:g,MESSAGE_REVOKED:u,MESSAGE_MODIFIED:E,CONVERSATION_UPDATED:m,LOGOUT:D,DESTROY:M,SYNC_CONVERSATION_LIST:T}}=this._core,{InnerEventSubType:{GROUP_AT_TIPS:P}}=s;s.unSubscribeInnerEvent(n,this._handleNewMessage,this),s.unSubscribeInnerEvent(n,P,this._handleNewGroupAtTips,this),s.unSubscribeInnerEvent(g,this._handleMessageDeleted,this),s.unSubscribeInnerEvent(u,this._handleMessageRevoked,this),s.unSubscribeInnerEvent(E,this._handleMessageModified,this),s.unSubscribeInnerEvent(m,this._handleConversationUpdated,this),s.unSubscribeInnerEvent(T,this._handleConversationSynced,this),s.unSubscribeInnerEvent(D,this._reset,this),s.unSubscribeInnerEvent(M,this._dispose,this)}},zA=new class{constructor(){this._name="GetConversationList"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"getConversationList",context:this})}getConversationList(s){return pA(this,void 0,void 0,function*(){return{code:0,data:{conversationList:this._getConversationList(s),isSyncCompleted:this._core.conversation.syncConversationHandler.isSyncCompleted()}}})}_getConversationList(s){const{utils:{isUndefined:n,isArray:g,isPlainObject:u}}=this._core;if(n(s))return NA.getLocalConversationList();if(g(s))return s.length===0?[]:NA.getLocalConversationList().filter(E=>s.includes(E.conversationID));if(u(s)){const{type:E,markType:m,groupName:D,hasUnreadCount:M,hasGroupAtInfo:T}=s;return NA.getLocalConversationList().filter(P=>this._filterType(P,E)&&this._filterMarkType(P,m)&&this._filterGroupName(P,D)&&this._filterUnreadCount(P,M)&&this._filterGroupAtInfo(P,T))}return[]}_filterType(s,n){const{OuterConstant:g}=this._core;return n!==g.CONV_C2C&&n!==g.CONV_GROUP||s.type===n}_filterGroupName(s,n){const{utils:{isString:g}}=this._core;return!g(n)||(n===""?s.conversationGroupList.length===0:s.conversationGroupList.includes(n))}_filterMarkType(s,n){const{utils:{isNumber:g}}=this._core;return!g(n)||(n===0?s.markList.length===0:s.markList.includes(n))}_filterUnreadCount(s,n){let g=!0;return n===!0?g=s.unreadCount>=1:n===!1&&(g=s.unreadCount===0),g}_filterGroupAtInfo(s,n){let g=!0;return n===!0?g=s.groupAtInfoList.length>=1:n===!1&&(g=s.groupAtInfoList.length===0),g}},we=new class{constructor(){this._name="GetConversationProfile"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"getConversationProfile",context:this})}getConversationProfile(s){return pA(this,void 0,void 0,function*(){const{OuterConstant:{CONV_C2C:n,CONV_GROUP:g,GRP_AVCHATROOM:u},appStore:{groupStore:E},utils:{isEmpty:m}}=this._core,D={code:0,data:{}};let M=NA.getLocalConversation(s);if(ks(s))return D.data.conversation=M,D;let T=!1;const P=Qt(s)?n:g;if(m(M)&&(T=!0,M=new ht({conversationID:s,type:P})),console.log(`${this._name}.getConversationProfile conversationID:${s} isNewConversation:${T}`),D.data.conversation=M,M?.getProfileCompleted())return D;if(P===n){const W=s.replace(n,"");yield this._handleC2CConversation(M,W),T&&(yield BA.get([W]))}if(P===g){const W=s.replace(g,"");if(!E.getGroup(W))return D;yield this._handleGroupConversation(M,W),T&&M.groupProfile.type!==u&&(yield yA.get([W]))}return D})}_handleC2CConversation(s,n){return pA(this,void 0,void 0,function*(){var g,u;const{user:E,helper:m,utils:{isEmpty:D},appStore:{conversationStore:M,userStore:T}}=this._core,{conversationID:P}=s,W=yield(g=E.userProfile)===null||g===void 0?void 0:g.getUserProfile({userIDList:[n]});if(W?.data.length===0)throw new m.ChatError({code:Qa.USER_OR_GRP_NOT_FOUND});s.userProfile=W?.data[0];const iA=(u=T.getFriend(n))===null||u===void 0?void 0:u.remark;D(iA)||s.remark===iA||(s.remark=iA),s.setProfileCompleted();const EA=NA.hasLocalConversation(P);console.log(`${this._name}._handleC2CConversation conversationID:${P} hasLocalConversation: ${EA}`),EA?M.updateConversation(P,s):NA.appendToPinnedConversation(s)})}_handleGroupConversation(s,n){return pA(this,void 0,void 0,function*(){const{apiMap:{getGroupProfile:g},appStore:{conversationStore:u}}=this._core,{conversationID:E}=s,m=yield g({groupID:n});s.groupProfile=m?.data.group,s.setProfileCompleted();const D=NA.hasLocalConversation(E);console.log(`${this._name}._handleGroupConversation conversationID:${E} hasLocalConversation: ${D}`),D?u.updateConversation(E,s):NA.appendToPinnedConversation(s)})}},le=new class{init(s){const{helper:n}=s;n.registerApi({apiName:"getTotalUnreadMessageCount",context:this})}getTotalUnreadMessageCount(){return NA.getTotalUnreadMessageCount()}},Ne=new class{constructor(){this._serverGroupConversationLastReadSeqMap=new Map,this._name="SetMessageRead"}init(s){this._core=s;const{helper:n,common:{isTopic:g},notificationCenter:u,InnerEvent:{MESSAGE_PUSH:E},InnerEventSubType:{ALL_MESSAGE_READ:m}}=s;n.registerApi({apiName:"setMessageRead",context:this,matcher:D=>!g(D[0].conversationID)}),n.registerApi({apiName:"setAllMessageRead",context:this}),u.subscribeInnerEvent(E,m,this._handleAllMessageRead,this)}handleC2CMessageReadSync(s){const{helper:{isEmpty:n},OuterConstant:g}=this._core;s.forEach(u=>{const{ReadC2cMsgNotify:E}=u;if(!n(E)){const{UinPairReadArray:m=[]}=E;m.forEach(D=>{const{From_Account:M,LastReadTime:T}=D,P=`${g.CONV_C2C}${M}`;console.log(`${this._name}.handleC2CMessageReadSync conversationID:${P} lastReadTime:${T}`),NA.markMessageAsRead({conversationID:P,lastReadTime:T}),NA.updateUnreadCount(P)})}})}handleGroupMessageReadSync(s){const{OuterConstant:n,utils:{isUndefined:g}}=this._core;s.forEach(u=>{const{GroupReadInfoArray:E}=u.MsgBody;g(E)||E.forEach(m=>{const{GroupId:D,LastReadMsgSeq:M}=m,T=`${n.CONV_GROUP}${D}`;console.log(`${this._name}.handleGroupMessageReadSync conversationID:${T} lastReadSequence:${M}`),NA.markMessageAsRead({conversationID:T,lastReadSequence:M}),NA.updateUnreadCount(T),this._clearGroupAtInfoList(T)})})}setMessageRead(s){return pA(this,void 0,void 0,function*(){var n,g;const{OuterConstant:u}=this._core,{conversationID:E}=s,m={code:0,data:{}},D=NA.getLocalConversation(E);let M=`${this._name}.setMessageRead conversationID:${E} unreadCount:${D?.unreadCount||0}`;if(m.successLog={message:M},!D)return m;const T=!(!((g=(n=this._core)===null||n===void 0?void 0:n.helper)===null||g===void 0)&&g.isEmpty(D.groupAtInfoList));if(D.type===u.CONV_GROUP&&T&&this._deleteGroupAtTips(E),D.unreadCount===0)return m;const{helper:{ChatError:P}}=this._core;try{if(D.type===u.CONV_C2C){const W=this._getLocalMessageMaxTime(D);M+=`lastMessageTime:${W}`,yield this._setC2CMessageRead(E,W)}if(D.type===u.CONV_GROUP){const W=this._getLocalMessageMaxSequence(D);M+=`lastMessageSequence:${W}`,yield this._setGroupMessageRead(E,W)}}catch(W){const{errorCode:iA,errorInfo:EA}=W;throw new P({functionName:"setMessageRead",code:iA,message:EA,moreMessage:M})}return D.type===u.CONV_SYSTEM&&(D.unreadCount=0),NA.emitConversationListUpdate(),Object.assign(Object.assign({},m),{successLog:{message:M}})})}setAllMessageRead(){return pA(this,arguments,void 0,function*(s={}){const{OuterConstant:{READ_ALL_MSG:n},utils:{safeStringify:g}}=this._core;let u=`scope:${s.scope}`;s.scope||(s.scope=n);const{scope:E}=s,m=this._generateSetAllMessageReadRequestData(E);if(m.allC2CMessageReadStatus===ea&&m.groupMessageReadInfoList.length===0)return{code:0};try{const D=yield function(M){return pA(this,void 0,void 0,function*(){const{allC2CMessageReadStatus:T,groupMessageReadInfoList:P}=M,W={C2CReadAllMsg:T,GroupReadInfo:P};return ho.core.common.buildAndSendPacket({servcmd:"openim.read_all_unread_msg",data:W})})}(m);if(D){const{GroupReadInfoArray:M,C2CReadAllMsg:T}=D,P=this._parseGroupReadInfo(M);this._updateAllConversationReadStatus({allC2CMessageReadStatus:T})>0&&NA.emitConversationListUpdate(),u+=`failureGroupInfoList:${g(P)}`}return{code:0,successLog:{message:u}}}catch(D){const{errorCode:M}=D;throw new this._core.helper.ChatError({functionName:"setAllMessageRead",code:M,moreMessage:u})}})}_handleAllMessageRead(s){const{GroupReadInfoArray:n,C2CReadAllMsg:g}=s;this._parseGroupReadInfo(n),this._updateAllConversationReadStatus({allC2CMessageReadStatus:g})>0&&NA.emitConversationListUpdate()}_updateAllConversationReadStatus(s){const{OuterConstant:{CONV_C2C:n,CONV_GROUP:g},appStore:u}=this._core,E=u.conversationStore.getConversationMap(),{allC2CMessageReadStatus:m}=s;let D=0;for(const[M,T]of E)if(T.unreadCount>=1){if(m===H&&T.type===n){const P=this._getLocalMessageMaxTime(T);NA.markMessageAsRead({conversationID:M,lastReadTime:P})}else if(T.type===g){const P=M.replace(g,"");if(this._serverGroupConversationLastReadSeqMap.has(P)){const W=this._serverGroupConversationLastReadSeqMap.get(P);NA.markMessageAsRead({conversationID:M,lastReadSequence:W})}}NA.updateUnreadCount(M,!1)&&(D+=1)}return D}_generateSetAllMessageReadRequestData(s){const{OuterConstant:{CONV_C2C:n,CONV_GROUP:g,READ_ALL_C2C_MSG:u},appStore:E}=this._core,m={allC2CMessageReadStatus:ea,groupMessageReadInfoList:[]},D=E.conversationStore.getConversationMap();for(const[,M]of D){const{type:T,unreadCount:P}=M;if(this._shouldSetAllMessageRead({scope:s,type:T,unreadCount:P})){if(T===n&&m.allC2CMessageReadStatus===ea){if(m.allC2CMessageReadStatus=H,s===u)break}else if(T===g){const W=this._getLocalMessageMaxSequence(M),{groupID:iA}=M.groupProfile;m.groupMessageReadInfoList.push({GroupId:iA,MsgSeq:W})}}}return m}_parseGroupReadInfo(s){const{utils:{isUndefined:n}}=this._core,g=[];return s?.forEach(u=>{const{GroupId:E,MsgSeq:m,RetCode:D,LastReadMsgSeq:M}=u;n(D)?this._serverGroupConversationLastReadSeqMap.set(E,M):(this._serverGroupConversationLastReadSeqMap.set(E,m),D!==0&&g.push(`${E}-${m}-${D}`))}),g}_deleteGroupAtTips(s){return pA(this,void 0,void 0,function*(){console.log(`${this._name}._deleteGroupAtTips conversationID:${s}`);const n=NA.getLocalConversation(s);if(!n)return;const g=n?.groupAtInfoList||[];if(g.length!==0)try{const{common:{getCurrentUserID:u,isCommunity:E},OuterConstant:{CONV_GROUP:m,CONV_AT_ALL:D}}=this._core;let M=[...g];if(E({groupID:s.replace(m,"")})&&(M=g.filter(P=>!P.atTypeArray.includes(D)),M.length===0))return void this._clearGroupAtInfoList(s,!1);const T=M.map(P=>({From_Account:P.from,To_Account:u(),MsgSeq:P.__sequence,MsgRandom:P.__random,GroupId:P.groupID}));yield function(P,W){return pA(this,void 0,void 0,function*(){const{messageListToDelete:iA}=P,EA={DelMsgList:iA};return W.common.buildAndSendPacket({servcmd:"openim.deletemsg",data:EA})})}({messageListToDelete:T},this._core),console.log(`${this._name}._deleteGroupAtTips ok. count:${g.length}`),this._clearGroupAtInfoList(s)}catch(u){console.error(`${this._name}._deleteGroupAtTips fail:`,u)}})}_clearGroupAtInfoList(s,n=!0){const g=NA.getLocalConversation(s);g&&(g.groupAtInfoList.length>0&&(g.clearGroupAtInfoList(),console.log(`${this._name}._clearGroupAtInfoList conversationID:${s} needEmitConversationUpdate:${n}`)),n&&NA.emitConversationListUpdate())}_getLocalMessageMaxTime(s){var n;const{conversationID:g}=s,u=this._core.message.messageDataHandler.getLocalMessageList(g),E=Math.max(...u.map(D=>D.time));let m=((n=s?.lastMessage)===null||n===void 0?void 0:n.lastTime)||0;return E>m&&(console.log(`${this._name}._getLocalMessageMaxTime update lastMessageTime from ${m} to ${E}`),m=E),m}_getLocalMessageMaxSequence(s){var n;const{conversationID:g}=s,u=this._core.message.messageDataHandler.getLocalMessageList(g),E=Math.max(...u.map(D=>D.sequence));let m=((n=s?.lastMessage)===null||n===void 0?void 0:n.lastSequence)||0;return E>m&&(console.log(`${this._name}._getLocalMessageMaxSequence update lastMessageSequence from ${m} to ${E}`),m=E),m}_setC2CMessageRead(s,n){return pA(this,void 0,void 0,function*(){try{yield function(g,u){return pA(this,void 0,void 0,function*(){return u.common.buildAndSendPacket({servcmd:"openim.msgreaded",data:g})})}({C2CMsgReaded:{Cookie:"",C2CMsgReadedItem:[{To_Account:s.replace("C2C",""),LastedMsgTime:n,Receipt:1}]}},this._core),console.log(`${this._name}._setC2CMessageRead ok, lastReadTime:${n}`),NA.markMessageAsRead({conversationID:s,lastReadTime:n}),NA.updateUnreadCount(s)}catch(g){throw console.warn(`${this._name}._setC2CMessageRead fail:`,g),g}})}_setGroupMessageRead(s,n){return pA(this,void 0,void 0,function*(){try{yield function(g,u){return pA(this,void 0,void 0,function*(){const{groupID:E,lastMessageSequence:m}=g,D={GroupId:E,MsgReadedSeq:m};return u.common.buildAndSendPacket({servcmd:"group_open_http_svc.msg_read_report",data:D})})}({groupID:s.replace("GROUP",""),lastMessageSequence:n},this._core),console.log(`${this._name}._setGroupMessageRead ok, lastReadSequence:${n}`),NA.markMessageAsRead({conversationID:s,lastReadSequence:n}),NA.updateUnreadCount(s)}catch(g){throw console.warn(`${this._name}._setGroupMessageRead fail:`,g),g}})}_shouldSetAllMessageRead(s){const{OuterConstant:{CONV_C2C:n,CONV_GROUP:g,READ_ALL_MSG:u,READ_ALL_C2C_MSG:E,READ_ALL_GROUP_MSG:m}}=this._core,{type:D,scope:M,unreadCount:T}=s;return!(T<=0)&&(!(D!==n||![u,E].includes(M))||!(D!==g||![u,m].includes(M)))}},ge=new class{constructor(){this._name="PinConversation"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"pinConversation",context:this})}handleConversationPinned(s,n){const{utils:{isArray:g}}=this._core;if(!g(s))return;const{OuterConstant:u}=this._core;let E=!1;s.forEach(m=>{const{Type:D,Peer_Account:M,GroupId:T}=m;let P;D===1?P=NA.getLocalConversation(`${u.CONV_C2C}${M}`):D===2&&(P=NA.getLocalConversation(`${u.CONV_GROUP}${T}`)),P&&(console.log(`${this._name}.handleConversationPinned conversationID:${P.conversationID} localPinned:${P.isPinned} remotePinned:${n}`),n&&!P.isPinned&&(P.isPinned=!0,E=!0),!n&&P.isPinned&&(P.isPinned=!1,E=!0))}),E&&NA.emitConversationListUpdate(!0)}pinConversation(s){return pA(this,void 0,void 0,function*(){const{OuterConstant:n,common:g,helper:{ChatError:u}}=this._core,{conversationID:E,isPinned:m}=s,D={code:0,data:{conversationID:E}},M=NA.getLocalConversation(E);if(M&&M.isPinned===m)return D;if(ks(E))return M&&(M.isPinned=m),NA.emitConversationListUpdate(!0),D;const T=`conversationID:${E} isPinned:${m}`;try{let P=null;if(Qt(E)?P={Type:1,To_Account:E.replace(n.CONV_C2C,"")}:ug(E)&&(P={Type:2,GroupId:E.replace(n.CONV_GROUP,"")}),yield function(iA,EA){return pA(this,void 0,void 0,function*(){const{fromAccount:RA,operationType:kA,itemList:xA}=iA,LA={From_Account:RA,OperationType:kA,RecentContactItem:xA};return EA.common.buildAndSendPacket({servcmd:"recentcontact.top",data:LA})})}({fromAccount:g.getCurrentUserID(),operationType:m===!0?1:2,itemList:[P]},this._core)){if(M)M.isPinned!==m&&(M.isPinned=m);else{const iA=new ht({conversationID:E,type:Qt(E)?n.CONV_C2C:n.CONV_GROUP,isPinned:m});NA.setLocalConversation(E,iA)}NA.emitConversationListUpdate(!0)}return Object.assign(Object.assign({},D),{successLog:{message:T}})}catch(P){const{errorCode:W,errorInfo:iA}=P;throw new u({functionName:"pinConversation",code:W,message:iA,moreMessage:T})}})}},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,u=[];s.forEach(E=>{const{Type:m,Peer_Account:D,GroupId:M}=E;m===1&&u.push(`${g.CONV_C2C}${D}`),m===2&&u.push(`${g.CONV_GROUP}${M}`)}),console.log(`${this._name}.handleConversationDeleted conversationIDList:${u}`),this._deleteLocalConversationList(u)}deleteConversation(s){return pA(this,void 0,void 0,function*(){const{utils:{isString:n}}=this._core;if(n(s))return this._deleteConversation({conversationIDList:[s],flag:ga.ONLY_CONVERSATIONID});const g=Object.assign({},s);return g.conversationIDList.length>100&&(g.conversationIDList=g.conversationIDList.slice(0,100)),this._deleteConversation(g)})}_deleteConversation(s){return pA(this,void 0,void 0,function*(){const{conversationIDList:n,clearHistoryMessage:g=!0,flag:u=0}=s,{helper:{ChatError:E}}=this._core,m=`conversationIDList:${n} clearHistoryMessage:${g}`;try{const D=yield Promise.all([this._deleteConversationFromLocal(n),this._deleteConversationFromServer(n,g)]),M=[...D[0],...D[1]];if(M.length===0)throw new this._core.helper.ChatError({code:Qa.CONV_NOT_FOUND});return{code:0,data:u===ga.ONLY_CONVERSATIONID?{conversationID:M[0]}:{conversationIDList:M},successLog:{message:m}}}catch(D){const{errorCode:M,errorInfo:T}=D;throw new E({code:M,message:T,moreMessage:m})}})}_deleteConversationFromLocal(s){const{OuterConstant:n}=this._core;return s.filter(g=>{var u;if(!NA.hasLocalConversation(g))return!1;const E=(u=NA.getLocalConversation(g))===null||u===void 0?void 0:u.type;return E!==n.CONV_GROUP||this._hasLocalGroup(g)?E===n.CONV_SYSTEM&&(this._deleteLocalConversation(g),!0):(this._deleteLocalConversation(g),!0)})}_deleteConversationFromServer(s,n){return pA(this,void 0,void 0,function*(){const{OuterConstant:g,common:u}=this._core,E={fromAccount:u.getCurrentUserID(),conversationList:[],clearHistoryMessage:n?1:0};if(s.forEach(D=>{var M;if(NA.hasLocalConversation(D)){const T=((M=NA.getLocalConversation(D))===null||M===void 0?void 0:M.type)||"",P=D.replace(T,"");T===g.CONV_C2C?E.conversationList.push({To_Account:P,Type:1}):T===g.CONV_GROUP&&this._hasLocalGroup(D)&&E.conversationList.push({ToGroupid:P,Type:2})}}),E.conversationList.length===0)return[];const m=yield function(D,M){return pA(this,void 0,void 0,function*(){const{fromAccount:T,conversationList:P,clearHistoryMessage:W}=D,iA={From_Account:T,ContactItem:P,ClearRamble:W};return M.common.buildAndSendPacket({servcmd:"recentcontact.batch_delete",data:iA})})}(E,this._core);if(m){const{ResultItem:D=[]}=m,M=[];return D.length>0&&D.forEach(T=>{if(T.ResultCode===0){const P=T.Type===1?`${g.CONV_C2C}${T.To_Account}`:`${g.CONV_GROUP}${T.ToGroupid}`;M.push(P)}}),this._deleteLocalConversationList(M),M}return[]})}_deleteLocalConversationList(s){let n=!1;s.forEach(g=>{NA.hasLocalConversation(g)&&(this._deleteLocalConversation(g,!1),n=!0)}),console.log(`${this._name}._deleteLocalConversationList isUpdate:${n}`),n&&NA.emitConversationListUpdate()}_deleteLocalConversation(s,n=!0){const g=NA.hasLocalConversation(s);console.log(`${this._name}._deleteLocalConversation conversationID:${s} has:${g}`),g&&(NA.deleteLocalConversation(s),this._deleteConversationLocalMessage(s),n&&NA.emitConversationListUpdate())}_hasLocalGroup(s){const{OuterConstant:{CONV_GROUP:n},appStore:{groupStore:g}}=this._core,u=s.replace(n,"");return!!g.getGroup(u)}_deleteConversationLocalMessage(s){console.log(`${this._name}._deleteConversationLocalMessage conversationID:${s}`),this._core.message.messageDataHandler.deleteConversationMessageList(s),this._core.message.messageHistory.completedHistoryConversations.delete(s)}},vt=new class{constructor(){this._name="SetConversationDraft"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"setConversationDraft",context:this})}setConversationDraft(s){return pA(this,void 0,void 0,function*(){const{conversationID:n,draftText:g}=s;if(console.log(`${this._name} conversationID:${n} draftText:${g}`),!NA.hasLocalConversation(n))throw new this._core.helper.ChatError({code:Qa.CONV_NOT_FOUND});const u=NA.getLocalConversation(n);return u?.setDraftText(g),NA.emitConversationListUpdate(),{code:0,data:{conversation:u}}})}},Wt=new class{constructor(){this._name="SetC2CMessageRemindType"}init(s){this._core=s}set(s,n){return pA(this,void 0,void 0,function*(){s.length>30&&(console.warn(`${this._name}.set userIDList length:${s.length} exceeds limit 30`),s.splice(30));const g=function(){const{MSG_REMIND_ACPT_AND_NOTE:P,MSG_REMIND_DISCARD:W,MSG_REMIND_ACPT_NOT_NOTE:iA}=ho.core.OuterConstant;return{[P]:0,[W]:1,[iA]:2}}()[n],u=yield function(P,W){return pA(this,void 0,void 0,function*(){const{userIDList:iA,receiveMessageOption:EA}=P,RA={Peer_Account:iA,Mute_Notifications:EA};return W.common.buildAndSendPacket({servcmd:"openim.set_c2c_peer_mute_notifications",data:RA})})}({userIDList:s,receiveMessageOption:g},this._core),{ErrorList:E=[]}=u||{},m=[];E.forEach(P=>{const{Peer_Account:W,ErrorCode:iA}=P;m.push({userID:W,code:iA});const EA=s.indexOf(W);EA>-1&&s.splice(EA,1)});const D=[],M=[],{OuterConstant:T}=this._core;return s.forEach(P=>{M.push(`${T.CONV_C2C}${P}`),D.push({userID:P})}),NA.patchMessageRemindType(M,n),{code:0,data:{successUserIDList:D,failureUserIDList:m}}})}},ci=new class{constructor(){this._name="SetGroupMessageRemindType"}init(s){this._core=s}set(s,n){return pA(this,void 0,void 0,function*(){const{common:{getCurrentUserID:g,isTopic:u},OuterConstant:E}=this._core;if(yield function(m,D){return pA(this,void 0,void 0,function*(){const{groupID:M,userID:T,receiveMessageOption:P}=m,W={GroupId:M,Member_Account:T,MsgFlag:P};return D.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:W})})}({groupID:s,userID:g(),receiveMessageOption:n},this._core),!u(s)){const m=`${E.CONV_GROUP}${s}`;NA.patchMessageRemindType([m],n)}return{code:0,data:{groupID:s,messageRemindType:n}}})}},Dt=new class{constructor(){this._name="SetMessageRemindType"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"setMessageRemindType",context:this})}handleC2CMessageRemindTypeSync(s){const{helper:{isEmpty:n},OuterConstant:g,ssoLog:u}=this._core;s.forEach(E=>{const{MuteNotificationsSync:m}=E;if(!n(m)){const{To_Account:D,MuteNotifications:M}=m,T=D.map(W=>`${g.CONV_C2C}${W}`),P=Wi(M);u.debug(`${this._name}.handleC2CMessageRemindTypeSync conversationIDList:${T} messageRemindType:${P}`),NA.patchMessageRemindType(T,P)}})}setMessageRemindType(s){return pA(this,void 0,void 0,function*(){const n="setMessageRemindType",{groupID:g,userIDList:u,messageRemindType:E}=s,{helper:m,utils:{isUndefined:D},ssoLog:M}=this._core;try{if(!D(g))return M.debug(`${this._name}.${n} groupID:${g} messageRemindType:${E}`),yield ci.set(g,E);if(!D(u))return M.debug(`${this._name}.${n} userIDList:${u} messageRemindType:${E}`),yield Wt.set(u,E);throw new m.ChatError({functionName:n,message:"userIDList or groupID is required"})}catch(T){throw new m.ChatError({functionName:n,code:T?.errorCode,message:T?.errorInfo,moreMessage:`groupID:${g} userIDList:${u} messageRemindType:${E}`})}})}},Bi=new class{init(s){s.ssoLog.debug("ConversationAction.init"),this._core=s,zA.init(s),we.init(s),le.init(s),Ne.init(s),ge.init(s),Ue.init(s),vt.init(s),Dt.init(s);const{notificationCenter:n,InnerEvent:{MESSAGE_PUSH:g,DESTROY:u}}=this._core,{InnerEventSubType:{CONV_MODIFIED:E,C2C_MESSAGE_READ_SYNC:m,GROUP_MESSAGE_READ_SYNC:D,C2C_REMIND_TYPE_SYNC:M}}=n;n.subscribeInnerEvent(g,E,this._onConversationModified,this),n.subscribeInnerEvent(g,m,this._onC2CMessageReadSync,this),n.subscribeInnerEvent(g,M,this._onC2CMessageRemindTypeSync,this),n.subscribeInnerEvent(g,D,this._onGroupMessageReadSync,this),n.subscribeInnerEvent(u,this._dispose,this)}_onConversationModified(s){const{constants:{ConvModifyPushType:n}}=this._core,{RecentContactMod:g=[]}=s;g.forEach(u=>{const{PushType:E}=u;if(E===n.CONV_DELETED){const{RecentContactList:m}=u.RecentContactDeleteItem;Ue.handleConversationDeleted(m)}if(E===n.CONV_PINED){const{RecentContactList:m}=u.RecentContactTopItem;ge.handleConversationPinned(m,!0)}if(E===n.CONV_UNPINED){const{RecentContactList:m}=u.RecentContactTopItem;ge.handleConversationPinned(m,!1)}})}_onC2CMessageReadSync(s){const{C2cNotifyMsgArray:n=[]}=s;Ne.handleC2CMessageReadSync(n)}_onC2CMessageRemindTypeSync(s){const{C2cNotifyMsgArray:n=[]}=s;Dt.handleC2CMessageRemindTypeSync(n)}_onGroupMessageReadSync(s){const{GroupTips:n=[]}=s;Ne.handleGroupMessageReadSync(n)}_dispose(){const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:n,DESTROY:g}}=this._core,{InnerEventSubType:{CONV_MODIFIED:u,C2C_MESSAGE_READ_SYNC:E,GROUP_MESSAGE_READ_SYNC:m,C2C_REMIND_TYPE_SYNC:D}}=s;s.unSubscribeInnerEvent(n,u,this._onConversationModified,this),s.unSubscribeInnerEvent(n,E,this._onC2CMessageReadSync,this),s.unSubscribeInnerEvent(n,D,this._onC2CMessageRemindTypeSync,this),s.unSubscribeInnerEvent(n,m,this._onGroupMessageReadSync,this),s.unSubscribeInnerEvent(g,this._dispose,this)}},eo=new class{init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"setAllReceiveMessageOpt",context:this})}setAllReceiveMessageOpt(s){return pA(this,void 0,void 0,function*(){try{const{OuterConstant:{MSG_REMIND_ACPT_NOT_NOTE:n}}=this._core,{messageRemindType:g=n,isRepeated:u=!0}=s,{startTime:E=0,endTime:m=0}=this._calcStartAndEndTime(s),D=yield function(M){return pA(this,void 0,void 0,function*(){const{common:T}=ho.core,{startTime:P,endTime:W,isRepeated:iA,messageRemindType:EA}=M,RA={StartTime:P,EndTime:W,IsRepeated:iA,Level:EA};return T.buildAndSendPacket({servcmd:"im_msg_db_logic.ws_set_do_not_disturb",data:RA})})}({messageRemindType:this._getType(g),startTime:E,endTime:m,isRepeated:u?is.ON:is.OFF});return{code:0,data:{errorCode:D.ErrorCode,errorInfo:D.ErrorInfo}}}catch(n){oc("setAllReceiveMessageOpt",n)}})}_calcStartAndEndTime(s){const{startHour:n=0,startMinute:g=0,startSecond:u=0,duration:E=0,isRepeated:m=!0}=s,D=new Date,M=new Date(D.getFullYear(),D.getMonth(),D.getDate(),n,g,u),T=Math.round(M.getTime()/1e3);let P=T+E;return m&&E>=86400&&(P=T+86400),{startTime:T,endTime:P}}_getType(s){const{OuterConstant:n}=this._core;return{[n.MSG_REMIND_ACPT_AND_NOTE]:0,[n.MSG_REMIND_DISCARD]:1,[n.MSG_REMIND_ACPT_NOT_NOTE]:2}[s]}},Is=new class{init(s){this._core=s;const{helper:n,notificationCenter:g,InnerEvent:u}=s;n.registerApi({apiName:"getAllReceiveMessageOpt",context:this}),g.subscribeInnerEvent(u.MESSAGE_PUSH,g.InnerEventSubType.ALL_RECEIVE_MESSAGE_OPTION,this.onAllReceiveMsgOptionNotify,this)}onAllReceiveMsgOptionNotify(s){const n=this._handleResult(s),{notificationCenter:g,OuterEvent:{ALL_RECEIVE_MESSAGE_OPT_UPDATED:u}}=this._core;g.emitOuterEvent(u,{name:u,data:n})}getAllReceiveMessageOpt(){return pA(this,void 0,void 0,function*(){try{const s=yield function(){return pA(this,void 0,void 0,function*(){const{common:n}=ho.core,g={To_Account:n.getCurrentUserID()};return n.buildAndSendPacket({servcmd:"im_msg_db_logic.ws_get_do_not_disturb",data:g})})}();return{code:0,data:this._handleResult(s)}}catch(s){oc("getAllReceiveMessageOpt",s)}})}_handleResult(s){const{OuterConstant:n}=this._core,{MSG_REMIND_ACPT_AND_NOTE:g,MSG_REMIND_DISCARD:u,MSG_REMIND_ACPT_NOT_NOTE:E}=n,m={0:g,1:u,2:E},{Level:D,StartTime:M,EndTime:T,IsRepeated:P}=s;return{messageRemindType:m[D]||g,startTime:M,endTime:T,isRepeated:P===is.ON}}},Uo=new class{init(s){s.ssoLog.debug("ReceiveMessageOptions.init"),this._core=s,Wt.init(s),ci.init(s),BA.init(s),yA.init(s),eo.init(s),Is.init(s)}};const si=s=>!Qt(s)&&!ug(s)&&!ks(s),Fr={getConversationProfile:[{key:"conversationID",required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!si(s)||"conversationID is invalid."}],setMessageRead:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!si(s)||"conversationID is invalid."}},pinConversation:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!si(s)||"conversationID is invalid."},isPinned:{required:!0,rules:["boolean"],allowEmpty:!1}},deleteConversation:[{key:"options",required:!0,rules:["string","object"],allowEmpty:!1,customValidator:s=>{const{core:{utils:{isArray:n,isObject:g,isString:u}}}=ho;if(!u(s)&&!g(s))return"options is String or Object.";if(u(s)&&si(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(si(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=>!(!Qt(s)&&!ug(s))||"conversationID is invalid."},draftText:{required:!0,rules:["string"],allowEmpty:!0}},setAllReceiveMessageOpt:{messageRemindType:{required:!1,rules:["string"],allowEmpty:!0},startHour:{required:!1,rules:["number"],allowEmpty:!0},startMinute:{required:!1,rules:["number"],allowEmpty:!0},startSecond:{required:!1,rules:["number"],allowEmpty:!0},duration:{required:!1,rules:["number"],allowEmpty:!0},isRepeated:{required:!1,rules:["boolean"],allowEmpty:!0}}},Zo={getConversationList:!0,getConversationProfile:!0,getTotalUnreadCount:!0,setMessageRead:!0,pinConversation:!0,deleteConversation:!0,setConversationDraft:!0,setMessageRemindType:!0,getAllReceiveMessageOpt:!0,setAllReceiveMessageOpt:!0};var jn=new class{constructor(){this.name="Conversation"}install(s){ho.init(s),Bi.init(s),Uo.init(s),NA.init(s),s.helper.registerValidateConfig({auth:Zo,params:Fr})}};const Wn=new class{init(s){this.core=s}},ta="AVChatRoom",qr="AV_HISTORY_MSG",sc="GRP_COUNTER",Ku="Set",mm="Increase",Ri="Decrease",ni=0,yo=1,on=2,os=["Type","Name","Introduction","Notification","FaceUrl","Owner_Account","CreateTime","InfoSeq","LastInfoTime","LastMsgTime","MemberNum","MaxMemberNum","ApplyJoinOption","NextMsgSeq","ShutUpAllMember","InviteJoinOption","LastRecallTime"],Eg=["Type","Name","Introduction","Notification","FaceUrl","CreateTime","Owner_Account","LastInfoTime","LastMsgTime","NextMsgSeq","MemberNum","MaxMemberNum","ApplyJoinOption","InviteJoinOption"],Ol=["Role","JoinTime","MsgFlag","MsgSeq"],fd=["Role","JoinTime","MsgSeq","MsgFlag","NameCard"],Lc=0,Mr=1,SI="notStart",nu="resolved",Og="rejected",ru=10018,MI=11e3,Uc=2,ju=["Owner","Admin","Member"],fm=["Role","JoinTime","NameCard","ShutUpUntil","OnlineStatus"],ym=0,Dm=1,Sm=2,cD=4,lD=1,Fv=2,ID=3,uD=4,Ov=5,BT=1,yd=0,QT=4,ED=6,pT=400,dD=300,mT={from:!0,groupID:!0,groupName:!0,to:!0},Pv={from:!0,groupID:!0,groupName:!0,to:!0,type:!0},fT=2,xv=4,yT=5,DT=7,CD=8,hD=15,TQ=20,Mm=21,vm=2600,Dd=2602,ST=2603,MT=2620,Rm=2621,BD=2623,Ih=2660,vT=2661,RT=2681,wm=2683,Yv=2684,QD=2685,_m=2687,Vv=3122,wT=10018,_T={0:"DisableInvite",1:"NeedPermission",2:"FreeAccess"},Jv=s=>s===Wn.core.OuterConstant.GRP_PUBLIC,Sd=s=>s===Wn.core.OuterConstant.GRP_AVCHATROOM,Tm=(s,n)=>{const{isArray:g}=Wn.core.utils;if(!g(s)||!g(n))return!1;let u=!1;return n.forEach(({key:E,value:m})=>{const D=s.find(M=>M.key===E);D?D.value!==m&&(D.value=m,u=!0):(s.push({key:E,value:m}),u=!0)}),u},Md=s=>{const n=[];if(!s)return n;for(let g=0,u=s.length;g{const n=[];for(let g=0,u=s.length;g0&&M.members.forEach(T=>{T.userID===this.selfInfo.userID&&D(this.selfInfo,T,["sequence"])})}updateSelfInfo(n){const{nameCard:g,joinTime:u,role:E,messageRemindType:m,readedSequence:D,excludedUnreadSequenceList:M}=n,{common:{deepMerge:T}}=Wn.core;T(this.selfInfo,{nameCard:g,joinTime:u,role:E,messageRemindType:m,readedSequence:D,excludedUnreadSequenceList:M},[],["",null,void 0,0,NaN])}setSelfNameCard(n){this.selfInfo.nameCard=n}}var Yi=new class{constructor(){this._name="GroupDataHandler"}init(s){this._core=s;const{appStore:{groupStore:n}}=s;this._groupMap=n.getGroupMap()}hasLocalGroup(s){return this._groupMap.has(s)}getLocalGroup(s){return this._groupMap.get(s)}updateLocalGroup(s){const{common:{getCurrentUserID:n}}=this._core;let g;s.forEach(E=>{var m;g=E.groupID,this.hasLocalGroup(g)?(m=this.getLocalGroup(g))===null||m===void 0||m.updateGroup(E):(this._groupMap.set(g,new Wu(E)),this._clearGroupLocalMessage(g))});const u=n();for(const[,E]of this._groupMap)E.selfInfo.userID=u,E.selfInfo.role==="Owner"&&(E.ownerID=u)}deleteLocalGroup(s){this._groupMap.delete(s)}getLocalGroupList(){const{OuterConstant:{GRP_ROOM:s,GRP_LIVE:n}}=this._core;return[...this._groupMap.values()].filter(g=>{const{type:u}=g;return u!==s&&u!==n})}clearLocalGroup(){this._groupMap.clear()}emitGroupListUpdate(){const s=this.getLocalGroupList(),{OuterEvent:{GROUP_LIST_UPDATED:n},notificationCenter:g}=this._core;g.emitOuterEvent(n,{name:n,data:s})}updateConversationGroupProfile(s){const{appStore:{conversationStore:n},OuterConstant:{CONV_GROUP:g}}=this._core,u=`${g}${s}`,E=n.getConversation(u);if(E){const m=this.getLocalGroup(s);E.setProfileCompleted(),n.updateConversation(u,{groupProfile:m})}}reset(){this.clearLocalGroup()}_clearGroupLocalMessage(s){const{message:{messageHistory:n,messageDataHandler:g},OuterConstant:{CONV_GROUP:u},ssoLog:E}=this._core;E.debug("_clearGroupLocalMessage",`groupID:${s}`);const m=`${u}${s}`;n.completedHistoryConversations.delete(m),g.deleteConversationMessageList(m)}};function Gm(s,n){return pA(this,void 0,void 0,function*(){const{type:g,limit:u,offset:E,supportTopic:m=0,memberAccount:D,responseFilter:M}=s,T={Type:g,Limit:u,Offset:E,Member_Account:D,ResponseFilter:M,SupportTopic:m,NeedAppDefineData:1};return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_joined_group_list",data:T})})}const dn=function(s,n){return{code:0,data:s||{},successLog:n}};var Hv=new class{constructor(){this._name="GetGroupList",this._pagingStatus=SI,this.PAGING_GRP_COUNT_LIMIT=200}init(s){this._core=s;const{helper:n,constants:{WORKFLOW_NAME:g,WORKFLOW_STEP:u}}=s;n.registerApi({apiName:"getGroupList",context:this}),n.registerWorkflowStep(g.SYNC_SERVER_INFO_AFTER_LOGIN,u.GROUP_LIST_SYNC,this._syncGroupList,this)}getGroupList(){return pA(this,arguments,void 0,function*(s=!1){if(s){const g=[];return yield this._pagingGetJoinedCommunityList({limit:this.PAGING_GRP_COUNT_LIMIT,offset:0,groupList:g}),Yi.updateLocalGroup(g),Yi.getLocalGroupList()}if(this._core.ssoLog.debug("getGroupList",`${this._name}.getGroupList pagingStatus:${this._pagingStatus}`),this._pagingStatus===Og||this._pagingStatus===SI)return this._syncGroupList().then(()=>{const g=Yi.getLocalGroupList();return dn({groupList:g,isSyncCompleted:this._isSyncCompleted()})}).catch(g=>{throw g});const n=Yi.getLocalGroupList();return dn({groupList:n,isSyncCompleted:this._isSyncCompleted()},{message:`return group count:${n.length}`})})}_syncGroupList(){return pA(this,void 0,void 0,function*(){this._pagingStatus===SI&&Yi.clearLocalGroup();const s=this.PAGING_GRP_COUNT_LIMIT,n=[];try{yield this._pagingGetGroupList({limit:s,offset:0,groupList:n}),this._pagingStatus=nu,this._groupListTreeShaking(n),Yi.updateLocalGroup(n);const g=Yi.getLocalGroupList();return this._core.ssoLog.debug("_syncGroupList",`${this._name}._syncGroupList ok, count:${g.length}`),Yi.emitGroupListUpdate(),g}catch(g){throw this._pagingStatus=Og,g}})}_pagingGetGroupList(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n}=this._core,{isCommunityRelay:g=!1,groupList:u}=s;let E,{limit:m,offset:D}=s;const M=[...os];g&&(E=this._core.OuterConstant.GRP_COMMUNITY,M.push("AtInfoList"));try{const T=yield Gm({type:E,limit:m,offset:D,memberAccount:this._core.store.get("login").userId,responseFilter:{GroupBaseInfoFilter:M,SelfInfoFilter:[...Ol]}},this._core),{GroupIdList:P=[],TotalCount:W=0}=T||{},iA=this._convertGroupKey(P);u.push(...iA);const EA=D+m,RA=!(W>EA),kA=`offset:${D} limit:${m} total:${W} isCompleted:${RA} current:${u.length} isCommunityRelay:${g}`;return n.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList ok. ${kA}`),g?RA?u:(D=EA,this._pagingGetGroupList({isCommunityRelay:!0,limit:m,offset:D,groupList:u})):RA?(n.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList start to get community list`),D=0,this._pagingGetGroupList({isCommunityRelay:!0,limit:m,offset:D,groupList:u})):(D=EA,this._pagingGetGroupList({limit:m,offset:D,groupList:u}))}catch(T){if(T.ErrorCode===ru)return n.warn("_pagingGetGroupList",`${this._name}._pagingGetGroupList response size exceeds the limit, request count:${m}`),m=50,this._pagingGetGroupList({isCommunityRelay:g,limit:m,offset:D,groupList:u});if(g)return T.code===MI&&n.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList ok. community unavailable`),u;throw T}})}_pagingGetJoinedCommunityList(s){return pA(this,void 0,void 0,function*(){const{common:{getCurrentUserID:n},OuterConstant:g,ssoLog:u}=this._core,{groupList:E}=s;let{limit:m,offset:D}=s;try{const M=yield Gm({limit:m,offset:D,type:g.GRP_COMMUNITY,memberAccount:n(),supportTopic:1,responseFilter:{GroupBaseInfoFilter:[...os],SelfInfoFilter:[...Ol]}},this._core),{GroupIdList:T=[],TotalCount:P=0}=M||{},W=this._convertGroupKey(T);E.push(...W);const iA=D+m,EA=!(P>iA),RA=`offset:${D} limit:${m} total:${P} isCompleted:${EA} current:${E.length}`;return u.debug("_pagingGetJoinedCommunityList",`${this._name}._pagingGetJoinedCommunityList ok. ${RA}`),EA?E:(D=iA,this._pagingGetJoinedCommunityList({limit:m,offset:D,groupList:E}))}catch(M){if(M.code===wT)return u.warn("_pagingGetJoinedCommunityList",`${this._name}._pagingGetJoinedCommunityList response size exceeds the limit, request count:${m}`),m=50,this._pagingGetJoinedCommunityList({limit:m,offset:D,groupList:E});throw M}})}_groupListTreeShaking(s){const n=new Map([...Yi.getLocalGroupList()]);for(let u=0,E=s.length;u{const{AtFlagList:E,AtMsgSeq:m,From_Account:D}=u;g.push({groupID:s,groupAtType:E,sequence:m,from:D})}),g}},zu=new class{constructor(){this._name="CreateGroup"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"createGroup",context:this})}createGroup(s){return pA(this,void 0,void 0,function*(){var n;this._preCheckParams(s);const{helper:{ChatError:g}}=this._core;try{const{utils:{isEmpty:u},common:{getCurrentUserID:E},OuterConstant:{GRP_AVCHATROOM:m}}=this._core,D=yield function(iA,EA){return pA(this,void 0,void 0,function*(){const{name:RA,type:kA,groupID:xA,introduction:LA,notification:SA,avatar:OA,maxMemberNum:JA,joinOption:ae,inviteOption:se,memberList:_i,groupCustomField:Ti,isSupportTopic:Ft}=iA;let Ni,cs;_i&&(Ni=_i.map(mt=>{const{userID:UA,memberCustomField:ri}=mt;return{Member_Account:UA,AppMemberDefinedData:ri?VE(ri):void 0}})),Ti&&(cs=VE(Ti));const Se={Name:RA,Type:kA,GroupId:xA,Introduction:LA,Notification:SA,FaceUrl:OA,MaxMemberCount:JA,ApplyJoinOption:ae,InviteJoinOption:se,MemberList:Ni,AppDefinedData:cs,SupportTopic:Ft,webPushFlag:1};return EA.common.buildAndSendPacket({servcmd:"group_open_http_svc.create_group",data:Se})})}(Object.assign(Object.assign({},s),{ownerID:E()}),this._core),{GroupId:M,OverJoinedGroupLimit_Account:T=[]}=D||{},P=`${this._name}.createGroup ok, type:${s.type} groupID:${M} overLimitUserIDList:${T}`;if(u(s.memberList)||u(T)||(s.memberList=(n=s.memberList)===null||n===void 0?void 0:n.filter(iA=>T.includes(iA.userID))),s.type===m)return dn({group:new Wu(Object.assign(Object.assign({},s),{groupID:M}))},{message:P});Yi.updateLocalGroup([Object.assign(Object.assign({},s),{groupID:M})]);const W=Yi.getLocalGroup(M);return this._notNeedSendCustomMessage(s)||(this._sendCustomMessage(M,s.type),Yi.emitGroupListUpdate()),dn({group:W},{message:P})}catch(u){const{errorCode:E,errorInfo:m}=u;throw new g({functionName:"createGroup",code:E,message:m,moreMessage:` groupID:${s.groupID}`})}})}_preCheckParams(s){const{type:n,groupID:g}=s,{utils:{isEmpty:u,isUndefined:E},common:{isCommunity:m}}=this._core,D=!u(g);if(!(()=>{const{GRP_PUBLIC:M,GRP_WORK:T,GRP_MEETING:P,GRP_AVCHATROOM:W,GRP_COMMUNITY:iA}=Wn.core.OuterConstant;return[M,T,P,W,iA]})().includes(n))throw new this._core.helper.ChatError({code:vm});if(!m({type:n})){if(D&&m({groupID:g}))throw new this._core.helper.ChatError({code:Dd});E(s.isSupportTopic)||(s.isSupportTopic=void 0)}if(this._canIUseMemberList(n)||E(s.memberList)||(s.memberList=void 0),this._canIUseJoinOption(n)||E(s.joinOption)||(s.joinOption=void 0),m({type:n})){if(D&&!m({groupID:g}))throw new this._core.helper.ChatError({code:Dd});s.isSupportTopic=this._canIUseTopic(s)?1:0}}_canIUseMemberList(s){return!Sd(s)}_canIUseJoinOption(s){return Jv(s)||this._core.common.isCommunity({type:s})}_canIUseTopic(s){const{isSupportTopic:n}=s;return n===!0}_notNeedSendCustomMessage(s){const{type:n,isSupportTopic:g}=s,{OuterConstant:{GRP_AVCHATROOM:u,GRP_COMMUNITY:E}}=this._core;return n===u||n===E&&g===1}_sendCustomMessage(s,n){var g,u,E,m,D,M;const{OuterConstant:T,common:{t:P}}=this._core;let W=P("CREATE_GROUP"),iA=Lc;n===T.GRP_COMMUNITY&&(W=P("CREATE_COMMUNITY"),iA=Mr);const EA={to:s,conversationType:"GROUP",payload:{data:JSON.stringify({businessID:"group_create",content:W,cmd:iA,opUser:this._core.store.get("login").userId,version:4})}},RA=(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageFactory)===null||E===void 0?void 0:E.createCustomMessage(EA);(M=(D=(m=this._core)===null||m===void 0?void 0:m.message)===null||D===void 0?void 0:D.messageSender)===null||M===void 0||M.sendMessage(RA,{})}},zs=new class{constructor(){this._name="AttributesDataHandler",this._groupAttributesCache=new Map,this._groupAttributesCacheValuesCopy={}}init(s){this._core=s;const{helper:n,constants:g}=s;n.registerWorkflowStep(g.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,g.WORKFLOW_STEP.GROUP_ATTRIBUTE_CACHE_CLEAR,this.clearLocalMainSequence,this)}clearLocalMainSequence(){this._groupAttributesCache.forEach(s=>{s.localMainSequence=0})}isGroupAttributesUpdated(s){const{elements:{newGroupProfile:n}}=s,{utils:{isEmpty:g,isUndefined:u}}=this._core;return!u(n)&&!g(n.groupAttributeOption)}handleGroupAttributesUpdated(s){const{groupID:n,groupAttributeOption:g}=s,{serverMainSequence:u,groupAttributeList:E=[],operation:m}=g;this._core.ssoLog.debug("handleGroupAttributesUpdated",`${this._name}.handleGroupAttributesUpdated groupID:${n} operation:${m}`);const{utils:{isUndefined:D}}=this._core;D(m)||(this.refreshGroupAttributesCache({groupID:n,serverMainSequence:u,groupAttributeList:E,operation:m}),this.emitGroupAttributesUpdated(n))}initGroupAttributesCache(s){const{groupID:n,avChatRoomKey:g}=s;this._groupAttributesCache.set(n,{lastUpdateTime:0,localMainSequence:0,serverMainSequence:0,avChatRoomKey:g,values:new Map}),this._core.ssoLog.debug("initGroupAttributesCache",`${this._name}.initGroupAttributesCache. groupID:${n} avChatRoomKey:${g}`)}hasGroupAttributesCache(s){return this._groupAttributesCache.has(s)}getGroupAttributesCache(s){return this.hasGroupAttributesCache(s)||this.initGroupAttributesCache({groupID:s}),this._groupAttributesCache.get(s)}deleteGroupAttributesCache(s){this.hasGroupAttributesCache(s)&&this._groupAttributesCache.delete(s)}refreshGroupAttributesCache(s){const{groupID:n,serverMainSequence:g,groupAttributeList:u,operation:E}=s;if(this.hasGroupAttributesCache(n)){const m=this.getGroupAttributesCache(n),{localMainSequence:D}=m;E!==Ov&&g-D!==1||(m.serverMainSequence=g,m.localMainSequence=g,m.lastUpdateTime=Date.now(),this._updateGroupAttributesCacheValues({groupAttributes:m,groupAttributeList:u,operation:E})),g-D>1&&(m.serverMainSequence=g),this._groupAttributesCache.set(n,m),this._core.ssoLog.debug("refreshGroupAttributesCache",`${this._name}.refreshGroupAttributesCache. operation:${E} localMainSequence:${D} serverMainSequence:${g}`)}}_updateGroupAttributesCacheValues(s){const{groupAttributes:n,groupAttributeList:g=[],operation:u}=s;u!==ID?u!==uD?(u===lD&&n.values.clear(),g.forEach(E=>{const{key:m,value:D,sequence:M}=E;n.values.set(m,{value:D,sequence:M})})):g.forEach(E=>{n.values.delete(E.key)}):n.values.clear()}getGroupAttributesCacheValues(s){var n;const{groupID:g,keyList:u=[]}=s,E={};if(this.hasGroupAttributesCache(g)){const{values:m}=this.getGroupAttributesCache(g);if(u.length===0){for(const D of m.keys())E[D]=((n=m.get(D))===null||n===void 0?void 0:n.value)||"";return E}return u.forEach(D=>{var M;m.has(D)&&(E[D]=((M=m.get(D))===null||M===void 0?void 0:M.value)||"")}),E}return E}saveGroupAttributesCacheValuesCopy(s){this._groupAttributesCacheValuesCopy=this.getGroupAttributesCacheValues({groupID:s})}emitGroupAttributesUpdated(s){var n,g;const{OuterConstant:{GRP_ROOM:u,GRP_LIVE:E}}=this._core,m=this.getGroupAttributesCacheValues({groupID:s}),D=this._core.appStore.groupStore.getGroup(s),{updatedKeyList:M,deletedKeyList:T}=this._computeValuesChangedData(m);M.length===0&&T.length===0||([u,E].includes(D.type)?(this._core.ssoLog.debug("RICH_STATUS_CHANGED",`${this._name}.emitRichStatusChanged update count:${M.length}, delete count:${T.length}`),this._emitEvent({name:(n=this._core)===null||n===void 0?void 0:n.OuterEvent.RICH_STATUS_CHANGED,data:{groupID:s,richStatus:m,updatedKeyList:M,deletedKeyList:T}})):(this._core.ssoLog.debug("emitGroupAttributesUpdated",`${this._name}.emitGroupAttributesUpdated update count:${M.length}, delete count:${T.length}`),this._emitEvent({name:(g=this._core)===null||g===void 0?void 0:g.OuterEvent.GROUP_ATTRIBUTES_UPDATED,data:{groupID:s,groupAttributes:m,updatedKeyList:M,deletedKeyList:T}})))}_computeValuesChangedData(s){const{utils:{isUndefined:n}}=this._core,g=[],u=[];return Object.keys(s).forEach(E=>{s[E]!==this._groupAttributesCacheValuesCopy[E]&&g.push(E)}),Object.keys(this._groupAttributesCacheValuesCopy).forEach(E=>{n(s[E])&&u.push(E)}),this._groupAttributesCacheValuesCopy={},{updatedKeyList:g,deletedKeyList:u}}_emitEvent(s){var n;(n=this._core)===null||n===void 0||n.notificationCenter.emitOuterEvent(s.name,s)}convertKeyValueMapToList(s){const n=[];return Object.keys(s).forEach(g=>{n.push({key:g,value:s[g]})}),n}reset(){this._groupAttributesCache.clear(),this._groupAttributesCacheValuesCopy={}}},Eh=new class{constructor(){this._name="DismissGroup"}init(s,n){this._core=s;const{helper:g}=s;g.registerApi({apiName:"dismissGroup",context:this,matcher:()=>!n.getInstalledSubPlugins().includes(ta)})}dismissGroup(s){return pA(this,void 0,void 0,function*(){const{helper:{ChatError:n}}=this._core;try{yield function(u,E){return pA(this,void 0,void 0,function*(){const m={GroupId:u};return E.common.buildAndSendPacket({servcmd:"group_open_http_svc.destroy_group",data:m})})}(s,this._core);const{type:g}=Yi.getLocalGroup(s);return Yi.deleteLocalGroup(s),Yi.emitGroupListUpdate(),zs.deleteGroupAttributesCache(s),dn({groupID:s,type:g},{message:s})}catch(g){const{errorCode:u,errorInfo:E}=g;throw new n({functionName:"dismissGroup",code:u,message:E})}})}},Pl=new class{constructor(){this._name="GetGroupProfile"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"getGroupProfile",context:this})}getGroupProfile(s){return pA(this,void 0,void 0,function*(){const{groupID:n,groupCustomFieldFilter:g}=s,u={groupIDList:[n],responseFilter:{GroupBaseInfoFilter:[...os],AppDefinedDataFilter_Group:g,MemberInfoFilter:[...fd]}},{helper:{ChatError:E}}=this._core;try{const m=yield this.getGroupProfileAdvance(u),{successGroupList:D,failureGroupList:M}=m;if(M.length>0)throw M[0];let T;return!Yi.hasLocalGroup(n)&&Sd(D[0].type)?T=new Wu(D[0]):(Yi.updateLocalGroup(D),T=Yi.getLocalGroup(n)),T.isSupportTopic||Yi.updateConversationGroupProfile(n),dn({group:T},{message:`groupID:${n}`})}catch(m){const{code:D,message:M}=m;throw new E({functionName:"getGroupProfile",code:D,message:M})}})}getGroupProfileAdvance(s){return pA(this,void 0,void 0,function*(){const{groupIDList:n}=s,{common:{isCommunity:g}}=this._core,u=n.filter(T=>!g({groupID:T})),E=n.filter(T=>g({groupID:T}));u.length>50&&(u.length=50),E.length>50&&(E.length=50);const m=yield Promise.all([this._getGroupProfileAdvance(Object.assign(Object.assign({},s),{groupIDList:u})),this._getGroupProfileAdvance(Object.assign(Object.assign({},s),{groupIDList:E,isCommunityProfile:!0}))]),D=[],M=[];return m.forEach(T=>{D.push(...T.successGroupList),M.push(...T.failureGroupList)}),{successGroupList:D,failureGroupList:M}})}_getGroupProfileAdvance(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{isUndefined:g}}=this._core,{isCommunityProfile:u=!1}=s,E=Do(s,["isCommunityProfile"]);if(E.groupIDList.length===0)return{successGroupList:[],failureGroupList:[]};try{const m=yield function(W,iA){return pA(this,void 0,void 0,function*(){const{groupIDList:EA,responseFilter:RA}=W,kA={GroupIdList:EA,ResponseFilter:RA};return iA.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_self_member_info",data:kA})})}(E,this._core),{GroupInfo:D=[]}=m||{},M=this._convertGroupProfileKey(D),T=M.filter(W=>g(W.errorCode)||W.errorCode===0),P=M.filter(W=>W.errorCode&&W.errorCode!==0).map(W=>({code:W.errorCode,message:W.errorInfo,data:{groupID:W.groupID}}));return n.debug("_getGroupProfileAdvance",`${this._name}._getGroupProfileAdvance ok, groupID:${E.groupIDList.join(",")}`),{successGroupList:T,failureGroupList:P}}catch(m){if(u)return{successGroupList:[],failureGroupList:[]};throw m}})}_convertGroupProfileKey(s){const n=[];for(let g=0,u=s.length;g0&&u{const{Key:T,Value:P=0}=M;E.set(T,P)}),this._groupCountersMap.set(n,{lastUpdateTime:Date.now(),groupCounterSeq:u,counters:E,avChatRoomKey:m})}}initGroupCountersCache(s){const{groupID:n,avChatRoomKey:g}=s;this._groupCountersMap.set(n,{lastUpdateTime:0,groupCounterSeq:0,counters:new Map,avChatRoomKey:g})}getLocalCounters(s,n){const g={};if(!this._hasLocalGroupCounters(s))return g;const{counters:u}=this.getLocalGroupCounters(s);if(n.length>0)n.forEach(E=>{u.has(E)&&(g[E]=u.get(E))});else for(const E of u.keys())g[E]=u.get(E);return g}deleteLocalGroupCounters(s){const{groupID:n,counterList:g=[],groupCounterSeq:u}=s;if(this._hasLocalGroupCounters(n)){const{counters:E,avChatRoomKey:m}=this.getLocalGroupCounters(n);g.forEach(D=>{E.delete(D.key)}),this._groupCountersMap.set(n,{lastUpdateTime:Date.now(),groupCounterSeq:u,counters:E,avChatRoomKey:m})}}setGroupCounters(s,n){if(!this._hasLocalGroupCounters(s))return;const g=this.getLocalGroupCounters(s),{counters:u}=g;let E=!1;Object.entries(n).forEach(([m,D])=>{u.has(m)&&u.get(m)!==D&&(u.set(m,D),E=!0)}),E&&this._groupCountersMap.set(s,Object.assign(Object.assign({},g),{lastUpdateTime:Date.now(),counters:u}))}_hasLocalGroupCounters(s){return this._groupCountersMap.has(s)}reset(){this._groupCountersMap.clear()}},JE=new class{constructor(){this._name="JoinGroup"}init(s,n){this._core=s;const{helper:g}=s;g.registerApi({apiName:"joinGroup",context:this,matcher:()=>!n.getInstalledSubPlugins().includes(ta)})}joinGroup(s){return pA(this,void 0,void 0,function*(){const{groupID:n}=s,{helper:{ChatError:g},OuterConstant:u,ssoLog:E}=this._core;try{if(Yi.hasLocalGroup(n))try{return yield Pl.getGroupProfile({groupID:n}),dn({status:u.JOIN_STATUS_ALREADY_IN_GROUP,group:Yi.getLocalGroup(n)},{message:`groupID:${n} joinedStatus:${u.JOIN_STATUS_ALREADY_IN_GROUP}`})}catch{return E.warn("joinGroup",`${this._name}.joinGroup ${n} was unjoined, start to join!`),Yi.deleteLocalGroup(n),yield this._applyJoinGroup(s)}return yield this._applyJoinGroup(s)}catch(m){const{errorCode:D,errorInfo:M}=m;throw new g({functionName:"joinGroup",code:D,message:M,moreMessage:`groupID:${n}`})}})}_applyJoinGroup(s){return pA(this,void 0,void 0,function*(){const{OuterConstant:n,helper:g,ssoLog:u}=this._core,{groupID:E}=s,m=Object.assign({},s),D=g.checkBusinessCapabilityBits(qr);D&&(m.historyMessageFlag=1);const M=yield function(SA,OA){return pA(this,void 0,void 0,function*(){const{groupID:JA,applyMessage:ae,historyMessageFlag:se}=SA,_i={GroupId:JA,ApplyMsg:ae,HugeGroupHistoryMsgFlag:se};return OA.common.buildAndSendPacket({servcmd:"group_open_http_svc.apply_join_group",data:_i})})}(m,this._core),{Type:T,JoinedStatus:P,LongPollingKey:W,StartSeq:iA,HugeGroupFlag:EA,AVChatRoomKey:RA,RspMsgList:kA=[]}=M||{},xA=`groupID:${E} joinedStatus:${P} longPollingKey:${W} startSeq:${iA} avChatRoomFlag:${EA} canGetAVChatRoomHistoryMsg:${D}, historyMessageCount:${kA.length}`;u.debug("_applyJoinGroup",`${this._name}._applyJoinGroup ok, ${xA}`);let LA=new Wu({groupID:E,type:T});if(P===n.JOIN_STATUS_WAIT_APPROVAL)return dn({status:n.JOIN_STATUS_WAIT_APPROVAL,group:LA});if(P===n.JOIN_STATUS_SUCCESS){try{LA=(yield Pl.getGroupProfile({groupID:E})).data.group}catch(SA){u.warn("_applyJoinGroup",`${this._name}._applyJoinGroup getGroupProfile failed, groupID: ${E}, errorCode:${SA?.code}`)}return this._handleJoinResult({group:LA,avChatRoomFlag:EA,longPollingKey:W,startSequence:iA,avChatRoomKey:RA,historyMessageList:kA})}throw new this._core.helper.ChatError({code:Ih})})}_handleJoinResult(s){const{group:n,avChatRoomFlag:g,avChatRoomKey:u}=s;return g===1?(zs.initGroupAttributesCache({groupID:n.groupID,avChatRoomKey:u}),nc.initGroupCountersCache({groupID:n.groupID,avChatRoomKey:u}),dn(s)):(Yi.updateLocalGroup([n]),Yi.emitGroupListUpdate(),dn({status:this._core.OuterConstant.JOIN_STATUS_SUCCESS,group:n},{message:`groupID:${n.groupID}`}))}},NQ=new class{constructor(){this._name="QuitGroup"}init(s,n){this._core=s;const{helper:g}=s;g.registerApi({apiName:"quitGroup",context:this,matcher:()=>!n.getInstalledSubPlugins().includes(ta)})}quitGroup(s){return pA(this,void 0,void 0,function*(){if(!Yi.hasLocalGroup(s))throw new this._core.helper.ChatError({code:BD});const{helper:{ChatError:n}}=this._core;try{yield function(u,E){return pA(this,void 0,void 0,function*(){const m={GroupId:u};return E.common.buildAndSendPacket({servcmd:"group_open_http_svc.quit_group",data:m})})}(s,this._core);const{type:g}=Yi.getLocalGroup(s);return Yi.deleteLocalGroup(s),Yi.emitGroupListUpdate(),zs.deleteGroupAttributesCache(s),dn({groupID:s,type:g},{message:`groupID:${s}`})}catch(g){const{errorCode:u,errorInfo:E}=g;throw new n({functionName:"quitGroup",code:u,message:E,moreMessage:`groupID:${s}`})}})}},cB=new class{constructor(){this._name="SearchGroup"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"searchGroupByID",context:this})}searchGroupByID(s){return pA(this,void 0,void 0,function*(){try{const n=yield function(OA,JA){return pA(this,void 0,void 0,function*(){const ae={GroupIdList:[OA],GroupBasePublicInfoFilter:[...Eg]};return JA.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_public_info",data:ae})})}(s,this._core),{GroupInfo:g=[]}=n||{},{AppDefinedData:u=[],ApplyJoinOption:E,CreateTime:m,FaceUrl:D,Introduction:M,InviteJoinOption:T,MaxMemberNum:P,MemberNum:W,Name:iA,Owner_Account:EA,Type:RA,ErrorCode:kA,ErrorInfo:xA}=g[0];if(kA!==0)throw new this._core.helper.ChatError({code:kA,message:xA});const LA=Md(u),SA=new Wu({groupID:s,name:iA,avatar:D,introduction:M,joinOption:E,inviteOption:T,maxMemberCount:P,memberCount:W,type:RA,ownerID:EA,createTime:m,groupCustomField:LA});return dn({group:SA})}catch(n){const{errorCode:g,errorInfo:u}=n;throw new this._core.helper.ChatError({functionName:"searchGroupByID",code:g,message:u})}})}},TT=new class{constructor(){this._name="UpdateGroupProfile"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"updateGroupProfile",context:this})}updateGroupProfile(s){return pA(this,void 0,void 0,function*(){const{groupID:n}=s,{utils:{isUndefined:g,safeStringify:u},ssoLog:E,helper:m}=this._core;let D=Yi.getLocalGroup(n);if(D){const{type:M}=D;this._canIUseJoinOption(M)||g(s.joinOption)||(E.warn("updateGroupProfile",`${this._name}.updateGroupProfile groupID:${n} joinOption is unavailable for Work/Meeting/AVChatRoom`),s.joinOption=void 0)}g(s.muteAllMembers)||(s.muteAllMembers=s.muteAllMembers===!0?"On":"Off");try{return yield function(M,T){return pA(this,void 0,void 0,function*(){const{groupID:P,name:W,avatar:iA,introduction:EA,notification:RA,muteAllMembers:kA,joinOption:xA,inviteOption:LA,groupCustomField:SA}=M,OA={GroupId:P,Name:W,FaceUrl:iA,Introduction:EA,Notification:RA,ShutUpAllMember:kA,ApplyJoinOption:xA,InviteJoinOption:LA,AppDefinedData:SA?VE(SA):void 0};return T.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_base_info",data:OA})})}(s,this._core),D?(D.updateGroup(s),Yi.emitGroupListUpdate()):D=new Wu(s),dn({group:D},{message:`groupID:${n}`})}catch(M){const{errorCode:T,errorInfo:P}=M;throw new m.ChatError({code:T,message:P,moreMessage:`options:${u(s)}`})}})}_canIUseJoinOption(s){return Jv(s)||this._core.common.isCommunity({type:s})}},NT=new class{constructor(){this._name="ChangeGroupOwner"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"changeGroupOwner",context:this})}changeGroupOwner(s){return pA(this,void 0,void 0,function*(){const n="changeGroupOwner",{groupID:g,newOwnerID:u}=s,E=Yi.getLocalGroup(g),{helper:m,OuterConstant:D,common:{getCurrentUserID:M}}=this._core;if(E?.type===D.GRP_AVCHATROOM)throw new m.ChatError({functionName:n,code:MT});if(u===M())throw new m.ChatError({functionName:n,code:Rm});try{return yield function(T,P){return pA(this,void 0,void 0,function*(){const{groupID:W,newOwnerID:iA}=T,EA={GroupId:W,NewOwner_Account:iA};return P.common.buildAndSendPacket({servcmd:"group_open_http_svc.change_group_owner",data:EA})})}(s,this._core),E.ownerID=u,Yi.emitGroupListUpdate(),dn({group:E})}catch(T){throw new m.ChatError({functionName:n,code:T?.errorCode,message:T?.errorInfo})}})}},GQ=new class{constructor(){this._name="GetGroupOnlineMemberCount",this._onlineMemberCountMap=new Map}init(s,n){this._core=s;const{helper:g}=s;g.registerApi({apiName:"getGroupOnlineMemberCount",context:this,matcher:()=>!n.getInstalledSubPlugins().includes(ta)})}getGroupOnlineMemberCount(s){return pA(this,void 0,void 0,function*(){const n="getGroupOnlineMemberCount";if(!Yi.hasLocalGroup(s))return dn({memberCount:0});const g=Date.now();if(this._onlineMemberCountMap.has(s)){const u=this._onlineMemberCountMap.get(s),{lastReqTime:E=0,memberCount:m=0}=u||{};if(g-E<=6e4)return dn({memberCount:m})}try{const u=yield function(D,M){return pA(this,void 0,void 0,function*(){const T={GroupId:D};return M.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_online_member_num",data:T})})}(s,this._core),{OnlineMemberNum:E=0}=u||{};this._onlineMemberCountMap.set(s,{lastReqTime:Date.now(),memberCount:E});const m=`${this._name}.${n} ok. groupID:${s} memberCount:${E}`;return dn({memberCount:E},{message:m})}catch(u){throw new this._core.helper.ChatError({functionName:n,code:u?.errorCode,message:u?.errorInfo})}})}},bQ=new class{init(s,n){s.ssoLog.debug("GroupAction.init"),Hv.init(s),zu.init(s),Eh.init(s,n),JE.init(s,n),NQ.init(s,n),cB.init(s),Pl.init(s),TT.init(s),NT.init(s),GQ.init(s,n)}dismissGroup(s){return Eh.dismissGroup(s)}joinGroup(s){return JE.joinGroup(s)}quitGroup(s){return NQ.quitGroup(s)}getGroupOnlineMemberCount(s){return GQ.getGroupOnlineMemberCount(s)}},qv=new class{constructor(){this._name="GetGroupApplicationList"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"getGroupApplicationList",context:this})}getGroupApplicationList(){return pA(this,void 0,void 0,function*(){const s="getGroupApplicationList";try{const n=yield Promise.all([this._getGroupApplicationList(),this._getGroupApplicationList({type:this._core.OuterConstant.GRP_COMMUNITY})]);this._core.ssoLog.debug("getGroupApplicationList",`${this._name}.${s} ok.`);const g=this._handleGroupApplicationResult([...n[0],...n[1]]);return dn({applicationList:g})}catch(n){throw new this._core.helper.ChatError({functionName:s,code:n?.errorCode,message:n?.errorInfo})}})}_getGroupApplicationList(s){return pA(this,void 0,void 0,function*(){const{type:n,startTime:g=0,limit:u=20}=s||{},{common:E}=this._core;let m;try{m=yield function(P,W){return pA(this,void 0,void 0,function*(){const{type:iA,startTime:EA,limit:RA,handleAccount:kA}=P,xA={Type:iA,StartTime:EA,Limit:RA,Handle_Account:kA};return W.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_pendency",data:xA})})}({type:n,startTime:g,limit:u,handleAccount:E.getCurrentUserID()},this._core)}catch(P){if(P?.errorCode!==11e3)throw P;m={}}const{NextStartTime:D=0,PendencyList:M=[]}=m||{};if(D===0)return M;const T=yield this._getGroupApplicationList(Object.assign(Object.assign({},s),{startTime:D}));return[...M,...T]})}_handleGroupApplicationResult(s){const n=[];return s.forEach(g=>{const u=this._convertApplicationData(g),{handled:E}=u,m=Do(u,["handled"]);E===0&&n.push(m)}),n}_convertApplicationData(s){const{Handled:n,AddTime:g,ApplyInviteMsg:u,Authentication:E,FromUserNickName:m,From_Account:D,GroupId:M,GroupName:T,PendencyType:P,To_Account:W}=s;return{handled:n,messageKey:g,applicant:D,applicantNick:m,groupID:M,groupName:T,authentication:E,applicationType:P,userID:W,note:u,addTime:g}}},Kv=new class{constructor(){this._name="HandleGroupApplication"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"handleGroupApplication",context:this})}handleGroupApplication(s){return pA(this,void 0,void 0,function*(){const{application:n}=s,g=this._handleParams(s);try{n?.applicationType===Uc?yield function(E,m){return pA(this,void 0,void 0,function*(){const{groupID:D,handleAction:M,handleMessage:T,applicant:P,authentication:W,invitee:iA}=E,EA={GroupId:D,HandleMsg:M,ApprovalMsg:T,Applicant_Account:P,Authentication:W,Invited_Account:iA};return m.common.buildAndSendPacket({servcmd:"group_open_http_svc.handle_invite_join_permission_group",data:EA})})}(g,this._core):yield function(E,m){return pA(this,void 0,void 0,function*(){const{groupID:D,handleAction:M,handleMessage:T,applicant:P,authentication:W,messageKey:iA}=E,EA={GroupId:D,HandleMsg:M,ApprovalMsg:T,Applicant_Account:P,Authentication:W,MsgKey:iA};return m.common.buildAndSendPacket({servcmd:"group_open_http_svc.handle_apply_join_group",data:EA})})}(g,this._core);const u=Yi.getLocalGroup(g.groupID);return dn({group:u})}catch(u){throw new this._core.helper.ChatError({functionName:"handleGroupApplication",code:u?.errorCode,message:u?.errorInfo})}})}_handleParams(s){var n;const{handleAction:g,handleMessage:u,message:E,application:m}=s;let D,M,T,P,W;if(E){const{payload:iA}=E||{};D=iA.operatorID,M=(n=iA.groupProfile)===null||n===void 0?void 0:n.groupID,T=iA.authentication,P=iA.messageKey}else D=m?.applicant||"",M=m?.groupID||"",T=m?.authentication||"",P=m?.messageKey||0;return m?.applicationType===Uc&&(W=m.userID),{handleAction:g,handleMessage:u,applicant:D,invitee:W,groupID:M,authentication:T,messageKey:P}}},pD=new class{init(s){s.ssoLog.debug("GroupApplication.init"),qv.init(s),Kv.init(s)}};let DC=class{constructor(s){this.userID="",this.avatar="",this.nick="",this.role="",this.joinTime="",this.nameCard="",this.muteUntil=0,this.memberCustomField=[],this.isOnline=!1,this.updateMember(s)}updateMember(s){const{core:{utils:{isUndefined:n},common:{deepMerge:g}}}=Wn;n(s.muteTime)||(this.muteUntil=Math.floor((Date.now()+1e3*s.muteTime)/1e3)),n(s.onlineStatus)||(this.isOnline=s.onlineStatus==="Online");const u=[null,void 0,"",0,NaN];s.memberCustomField&&Tm(this.memberCustomField,s.memberCustomField),g(this,s,["memberCustomField","marks","onlineStatus","muteTime"],u)}};function lB(s,n){return pA(this,void 0,void 0,function*(){const{groupID:g,userID:u,muteTime:E,role:m,nameCard:D,memberCustomField:M}=s;let T;M&&(T=VE(M));const P={GroupId:g,Member_Account:u,ShutUpTime:E,Role:m,NameCard:D,AppMemberDefinedData:T};return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:P})})}var mD=new class{constructor(){this._name="GetGroupMemberList"}init(s,n){this._core=s;const{helper:g}=s;g.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>!n.getInstalledSubPlugins().includes(ta)})}getGroupMemberList(s){return pA(this,void 0,void 0,function*(){const n="getGroupMemberList",{groupID:g,offset:u=0,count:E=100,role:m="",filter:D=""}=s,M=Yi.getLocalGroup(g),T=E>100?100:E,P={groupID:g,offset:u,limit:T,memberRoleFilter:ju.includes(m)?[m]:void 0,memberInfoFilter:fm};try{const W=yield function(se,_i){return pA(this,void 0,void 0,function*(){const{isCommunity:Ti}=_i.common,{groupID:Ft,offset:Ni,limit:cs,memberRoleFilter:Se,memberInfoFilter:mt}=se,UA={GroupId:Ft,Limit:cs,MemberRoleFilter:Se,MemberInfoFilter:mt};return Ti({groupID:Ft})?UA.Next=String(Ni):UA.Offset=Ni,_i.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_member_info",data:UA})})}(P,this._core),{MemberList:iA,MemberNum:EA,Next:RA}=W||{},kA=`${this._name}.${n} ok, totalMemberCount:${EA} next:${RA}`,{utils:{isArray:xA,isEmpty:LA},common:{isCommunity:SA}}=this._core;if(M&&(M.memberCount=EA),!xA(iA)||iA.length===0)return dn({memberList:[],offset:0},{message:kA});let OA=u+T;SA({groupID:g})&&(OA=LA(RA)?0:RA),iA.lengthD.userID),u=yield(n=this._core.user.userProfile)===null||n===void 0?void 0:n.getUserProfile({userIDList:g}),E=u?.data||[],m=new Map(E.map(D=>[D.userID,D]));return s.forEach(D=>{if(m.has(D.userID)){const{nick:M="",avatar:T=""}=m.get(D.userID);D.nick=M,D.avatar=T}}),s})}_generateGroupMember(s){const n=[];for(let g=0,u=s.length;g50&&(T.warn("getGroupMemberProfile",`${this._name}.${n} userIDList length:${u.length} exceeds limit 50`),u.splice(50));const P=`userIDList length:${u.length} groupID:${g}`;try{const W=yield function(kA,xA){return pA(this,void 0,void 0,function*(){const{groupID:LA,userIDList:SA,memberInfoFilter:OA,memberCustomFieldFilter:JA}=kA,ae={GroupId:LA,Member_List_Account:SA,MemberInfoFilter:OA,AppDefinedDataFilter_GroupMember:JA};return xA.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_specified_group_member_info",data:ae})})}({groupID:g,userIDList:u,memberCustomFieldFilter:E,memberInfoFilter:[...fm]},this._core),{MemberList:iA}=W||{};if(!M(iA)||iA.length===0)return dn({memberList:[]});let EA=this._convertMemberInfo(iA);EA=yield this._getMemberAvatarAndNick(EA);const RA=this._generateGroupMember(EA);return dn({memberList:RA},{message:P})}catch(W){throw new D.ChatError({functionName:n,code:W?.errorCode,message:W?.errorInfo,moreMessage:P})}})}_convertMemberInfo(s){const n=[];for(let g=0,u=s.length;gD.userID),u=yield(n=this._core.user.userProfile)===null||n===void 0?void 0:n.getUserProfile({userIDList:g}),E=u?.data||[],m=new Map(E.map(D=>[D.userID,D]));return s.forEach(D=>{if(m.has(D.userID)){const{nick:M="",avatar:T=""}=m.get(D.userID);D.nick=M,D.avatar=T}}),s})}_generateGroupMember(s){const n=[];for(let g=0,u=s.length;g({Member_Account:M}));try{const M=yield function(RA,kA){return pA(this,void 0,void 0,function*(){const{groupID:xA,userIDList:LA}=RA,SA={GroupId:xA,MemberList:LA};return kA.common.buildAndSendPacket({servcmd:"group_open_http_svc.add_group_member",data:SA})})}({groupID:g,userIDList:D},this._core),{MemberList:T=[]}=M||{},{failureUserIDList:P,successUserIDList:W,existedUserIDList:iA,overLimitUserIDList:EA}=this._handleResult(T);return dn({failureUserIDList:P,successUserIDList:W,existedUserIDList:iA,overLimitUserIDList:EA,group:E},{message:` groupID:${g} successUserIDList:${W} failureUserIDList:${P} existedUserIDList:${iA} overLimitUserIDList:${EA}`})}catch(M){throw new m.ChatError({functionName:n,code:M?.errorCode,message:M?.errorInfo})}})}_handleResult(s){const n=[],g=[],u=[],E=[];return s.forEach(m=>{const{Result:D,Member_Account:M}=m;D===ym?n.push(M):D===Dm?g.push(M):D===Sm?u.push(M):D===cD&&E.push(M)}),{failureUserIDList:n,successUserIDList:g,existedUserIDList:u,overLimitUserIDList:E}}},Rd=new class{constructor(){this._name="DeleteGroupMember"}init(s,n){this._core=s;const{helper:g}=s;g.registerApi({apiName:"deleteGroupMember",context:this,matcher:()=>!n.getInstalledSubPlugins().includes(ta)})}deleteGroupMember(s){return pA(this,void 0,void 0,function*(){const n="deleteGroupMember",{groupID:g,userIDList:u}=s,E=Yi.getLocalGroup(g),{helper:m,utils:{isUndefined:D},ssoLog:M}=this._core;if(D(E))throw new m.ChatError({functionName:n,code:ST});u.length>20&&(M.warn("deleteGroupMember",`${this._name}.${n} userIDList length:${u.length} exceeds limit 20`),u.splice(20));try{return yield function(T,P){return pA(this,void 0,void 0,function*(){const{groupID:W,userIDList:iA,reason:EA}=T,RA={GroupId:W,MemberToDel_Account:iA,Reason:EA};return P.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_member",data:RA})})}({groupID:g,userIDList:u},this._core),dn({group:E,userIDList:u},{message:`groupID:${g} userIDList length:${u.length}`})}catch(T){throw new m.ChatError({functionName:n,code:T?.errorCode,message:T?.errorInfo})}})}},jv=new class{constructor(){this._name="SetGroupMemberMuteTime"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"setGroupMemberMuteTime",context:this})}setGroupMemberMuteTime(s){return pA(this,void 0,void 0,function*(){const{helper:n}=this._core,{groupID:g,userID:u,muteTime:E}=s,m=` groupID:${g} userID:${u} muteTime:${E}`;this._preCheckSettingMuteParams(s);try{yield lB(s,this._core);const D=Yi.getLocalGroup(g),M=new DC({userID:u,muteTime:E});return dn({group:D,member:M},{message:m})}catch(D){throw new n.ChatError({functionName:"setGroupMemberMuteTime",code:D?.errorCode,message:D?.errorInfo,moreMessage:m})}})}_preCheckSettingMuteParams(s){const{userID:n}=s,{store:g,helper:u}=this._core;if(n===g.get("login").userId)throw new u.ChatError({functionName:"setGroupMemberMuteTime",code:QD})}},LQ=new class{constructor(){this._name="SetGroupMemberRole"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"setGroupMemberRole",context:this})}setGroupMemberRole(s){return pA(this,void 0,void 0,function*(){const n="setGroupMemberRole",{helper:g}=this._core,{groupID:u,userID:E,role:m}=s,D=`${this._name}.${n} ok, groupID:${u} userID:${E} role:${m}`;this._preCheckSettingRoleParams(s);try{yield lB(s,this._core);const M=Yi.getLocalGroup(u),T=new DC({userID:E,role:m});return dn({group:M,member:T},{message:D})}catch(M){throw new g.ChatError({functionName:n,code:M?.errorCode,message:M?.errorInfo,moreMessage:D})}})}_preCheckSettingRoleParams(s){var n;const{groupID:g,userID:u,role:E}=s,{store:m,helper:D,OuterConstant:M,common:{isCommunity:T}}=this._core,P=Yi.getLocalGroup(g);if(((n=P?.selfInfo)===null||n===void 0?void 0:n.role)!==M.GRP_MBR_ROLE_OWNER)throw new D.ChatError({functionName:"setGroupMemberRole",code:RT});if(u===m.get("login").userId)throw new D.ChatError({functionName:"setGroupMemberRole",code:Yv});const W=[...ju];if(T({groupID:g})&&W.push(M.GRP_MBR_ROLE_CUSTOM),!W.includes(E))throw new D.ChatError({functionName:"setGroupMemberRole",code:wm})}},fD=new class{constructor(){this._name="SetGroupMemberNameCard"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"setGroupMemberNameCard",context:this})}setGroupMemberNameCard(s){return pA(this,void 0,void 0,function*(){var n;const g="setGroupMemberNameCard",{helper:u,common:{getCurrentUserID:E}}=this._core,{groupID:m,userID:D=E(),nameCard:M}=s,T=`${this._name}.${g} ok, groupID:${m} userID:${D} nameCard:${M}`;this._preCheckSettingNameCardParams(s);try{yield lB({groupID:m,userID:D,nameCard:M},this._core);const W=Yi.getLocalGroup(m);D===((n=W?.selfInfo)===null||n===void 0?void 0:n.userID)&&(W.updateSelfInfo({nameCard:M}),Yi.emitGroupListUpdate(),Yi.updateConversationGroupProfile(m));const iA=new DC({userID:D,nameCard:M});return dn({group:W,member:iA},{message:T})}catch(P){throw new u.ChatError({functionName:g,code:P?.errorCode,message:P?.errorInfo,moreMessage:T})}})}_preCheckSettingNameCardParams(s){const{groupID:n}=s,{helper:g}=this._core,u=Yi.getLocalGroup(n);if(Sd(u?.type))throw new g.ChatError({functionName:"setGroupMemberNameCard",code:_m})}},bm=new class{constructor(){this._name="SetGroupMemberCustomField"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"setGroupMemberCustomField",context:this})}setGroupMemberCustomField(s){return pA(this,void 0,void 0,function*(){const n="setGroupMemberCustomField",{helper:g,common:{getCurrentUserID:u}}=this._core;this._preCheckSettingCustomFiledParams(s);const{groupID:E,userID:m=u(),memberCustomField:D}=s,M=`${this._name}.${n} ok, groupID:${E}userID:${m} memberCustomField:${JSON.stringify(D)}`;try{yield lB({groupID:E,userID:m,memberCustomField:D},this._core);const P=Yi.getLocalGroup(E),W=new DC({userID:m,memberCustomField:D});return dn({group:P,member:W},{message:M})}catch(T){throw new g.ChatError({functionName:n,code:T?.errorCode,message:T?.errorInfo,moreMessage:M})}})}_preCheckSettingCustomFiledParams(s){const{groupID:n}=s,{helper:g}=this._core,u=Yi.getLocalGroup(n);if(Sd(u?.type))throw new g.ChatError({functionName:"setGroupMemberCustomField",code:_m})}},Wv=new class{init(s,n){s.ssoLog.debug("GroupMember.init"),mD.init(s,n),kQ.init(s),vd.init(s),Rd.init(s,n),jv.init(s),LQ.init(s),fD.init(s),bm.init(s)}getGroupMemberList(s){return mD.getGroupMemberList(s)}deleteGroupMember(s){return Rd.deleteGroupMember(s)}},GT=new class{init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"getGroupCounters",context:this})}getGroupCounters(s){return pA(this,void 0,void 0,function*(){const n="getGroupCounters";try{Nm(n,sc);const{groupID:g,keyList:u=[]}=s,{avChatRoomKey:E,lastUpdateTime:m}=nc.getLocalGroupCounters(g);if(!(Date.now()-m>=this._getExpireTime()))return{code:0,data:{counters:nc.getLocalCounters(g,u)}};const D=yield function(P){return pA(this,void 0,void 0,function*(){const{groupID:W,GroupCounterKeys:iA,avChatRoomKey:EA}=P,{common:RA}=Wn.core,kA={GroupId:W,keyList:iA,BytesKey:EA};return RA.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_counter",data:kA})})}({groupID:g,keyList:u,avChatRoomKey:E}),{GroupCounter:M=[],GroupCounterSeq:T}=D;return nc.updateLocalGroupCounters({groupID:g,counterList:M,groupCounterSeq:T}),{code:0,data:{counters:nc.getLocalCounters(g,u)}}}catch(g){yC(n,g)}})}_getExpireTime(){const{store:s,utils:{isUndefined:n}}=this._core,g=s.get("cloudConfig")||{},{grp_counter_expire_time:u}=g;return n(u)?3e4:Number(u)}},km=new class{init(s){const{helper:n}=s;n.registerApi({apiName:"setGroupCounters",context:this}),n.registerApi({apiName:"increaseGroupCounter",context:this}),n.registerApi({apiName:"decreaseGroupCounter",context:this})}setGroupCounters(s){return pA(this,void 0,void 0,function*(){return this._handleCounterOperation(Ku,s)})}increaseGroupCounter(s){return pA(this,void 0,void 0,function*(){return this._handleCounterOperation(mm,s)})}decreaseGroupCounter(s){return pA(this,void 0,void 0,function*(){return this._handleCounterOperation(Ri,s)})}_handleCounterOperation(s,n){return pA(this,void 0,void 0,function*(){const g=`${s}GroupCounter`;try{Nm(g,sc);const{groupID:u,key:E,value:m=0}=n,{avChatRoomKey:D}=nc.getLocalGroupCounters(u),M=s===Ku?this._convertObjectToList(n.counters):[{Key:E,Value:m}],T=yield this._updateGroupCounters({groupID:u,counterList:M,avChatRoomKey:D,mode:s});return nc.setGroupCounters(u,T),{code:0,data:{counters:T}}}catch(u){yC(g,u)}})}_updateGroupCounters(s){return pA(this,void 0,void 0,function*(){const n=yield function(E){const{groupID:m,counterList:D,mode:M,avChatRoomKey:T}=E,{common:P}=Wn.core,W={GroupId:m,GroupCounter:D,Mode:M,BytesKey:T};return P.buildAndSendPacket({servcmd:"group_open_http_svc.update_group_counter",data:W})}(s),{GroupCounter:g=[]}=n,u={};return g.forEach(E=>{const{Key:m,Value:D=0}=E;u[m]=D}),u})}_convertObjectToList(s){return Object.entries(s).map(([n,g])=>({Key:n,Value:g||0}))}},IB=new class{init(s){this._core=s,GT.init(s),km.init(s)}isGroupCounterUpdated(s){const{elements:{groupCounterInfo:n}}=s,{utils:{isEmpty:g}}=this._core;return!g(n)}handleGroupCounterUpdated(s){const{to:n,elements:{groupCounterInfo:g}}=s;g.forEach(u=>{const{type:E,groupCounterSeq:m,counterList:D=[]}=u;E!==ni&&E!==on||this._processAndNotifyCounterUpdate(n,m,D),E===yo&&nc.deleteLocalGroupCounters({groupID:n,groupCounterSeq:m,counterList:D})})}_processAndNotifyCounterUpdate(s,n,g){const{OuterEvent:u,notificationCenter:E}=this._core;nc.updateLocalGroupCounters({groupID:s,groupCounterSeq:n,counterList:g}),g.forEach(({Key:m,Value:D=0})=>{E.emitOuterEvent(u.GROUP_COUNTER_UPDATED,{name:u.GROUP_COUNTER_UPDATED,data:{groupID:s,key:m,value:D}})})}reset(){nc.reset()}},Lm=new class{constructor(){this._name="InitGroupAttributes"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"initGroupAttributes",context:this})}initGroupAttributes(s){return pA(this,void 0,void 0,function*(){const{groupID:n,groupAttributes:g}=s,{serverMainSequence:u,avChatRoomKey:E}=zs.getGroupAttributesCache(n),m=zs.convertKeyValueMapToList(g);try{const D=yield function(W,iA){return pA(this,void 0,void 0,function*(){const{groupID:EA,mainSequence:RA,groupAttributeList:kA,avChatRoomKey:xA}=W,LA={GroupId:EA,AttrMainSeq:RA,GroupAttr:kA,BytesKey:xA,AttrControl:["RaceConflict"]};return iA.common.buildAndSendPacket({servcmd:"group_open_http_svc.set_group_attr",data:LA})})}({groupID:n,avChatRoomKey:E,groupAttributeList:m,mainSequence:u},this._core),{AttrMainSeq:M,GroupAttr:T}=D||{},P=T.map(W=>{const{Key:iA,seq:EA}=W;return{key:iA,value:g[iA],sequence:EA}});return zs.saveGroupAttributesCacheValuesCopy(n),zs.refreshGroupAttributesCache({groupID:n,serverMainSequence:M,groupAttributeList:P,operation:lD}),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})}})}},bT=new class{constructor(){this._name="SetGroupAttributes"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"setGroupAttributes",context:this}),n.registerExperimentalAPI("setRichStatus",this)}setGroupAttributes(s){return pA(this,void 0,void 0,function*(){const{groupID:n,groupAttributes:g,richStatusMode:u}=s,{serverMainSequence:E,avChatRoomKey:m,values:D}=zs.getGroupAttributesCache(n),M=zs.convertKeyValueMapToList(g).map(T=>{var P;const{key:W,value:iA}=T;return{key:W,value:iA,seq:((P=D.get(T.key))===null||P===void 0?void 0:P.sequence)||0}});try{const T=yield function(EA,RA){return pA(this,void 0,void 0,function*(){const{groupID:kA,mainSequence:xA,groupAttributeList:LA,avChatRoomKey:SA,richStatusMode:OA}=EA,JA={GroupId:kA,AttrMainSeq:xA,GroupAttr:LA,BytesKey:SA,AttrControl:["RaceConflict"],AllowRoomEngineOpt:OA};return RA.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_attr",data:JA})})}({groupID:n,avChatRoomKey:m,groupAttributeList:M,mainSequence:E,richStatusMode:u},this._core),{AttrMainSeq:P,GroupAttr:W}=T||{},iA=W.map(EA=>{const{Key:RA,seq:kA}=EA;return{key:RA,value:g[RA],sequence:kA}});return zs.saveGroupAttributesCacheValuesCopy(n),zs.refreshGroupAttributesCache({groupID:n,serverMainSequence:P,groupAttributeList:iA,operation:Fv}),zs.emitGroupAttributesUpdated(n),dn({groupAttributes:g},{message:` groupID:${n} serverMainSequence:${P}`})}catch(T){throw new this._core.helper.ChatError({functionName:"setGroupAttributes",code:T?.errorCode,message:T?.errorInfo})}})}setRichStatus(s){return pA(this,void 0,void 0,function*(){const{groupID:n,richStatus:g}=s;return this.setGroupAttributes({groupID:n,groupAttributes:g,richStatusMode:!0})})}},yD=new class{constructor(){this._name="DeleteGroupAttributes"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"deleteGroupAttributes",context:this}),n.registerExperimentalAPI("deleteRichStatus",this)}deleteGroupAttributes(s){return pA(this,void 0,void 0,function*(){const n="deleteGroupAttributes",{groupID:g,keyList:u=[],richStatusMode:E}=s;try{let m;m=u.length===0?yield this._clearGroupAttributes(g,{richStatusMode:E}):yield this._deleteGroupAttributes(g,{keyList:u,richStatusMode:E});const{resultList:D,serverMainSequence:M,operation:T,groupAttributeList:P}=m||{},W=`${this._name}.${n} ok. groupID:${g} operation: ${T}`;return zs.saveGroupAttributesCacheValuesCopy(g),zs.refreshGroupAttributesCache({groupID:g,serverMainSequence:M,groupAttributeList:P,operation:T}),zs.emitGroupAttributesUpdated(g),dn({keyList:D},{message:W})}catch(m){throw new this._core.helper.ChatError({functionName:n,code:m?.errorCode,message:m?.errorInfo})}})}deleteRichStatus(s){return pA(this,void 0,void 0,function*(){return this.deleteGroupAttributes(Object.assign(Object.assign({},s),{richStatusMode:!0}))})}_deleteGroupAttributes(s,n){return pA(this,void 0,void 0,function*(){const{serverMainSequence:g,avChatRoomKey:u,values:E}=zs.getGroupAttributesCache(s),{keyList:m,richStatusMode:D}=n,M=[],T=[];m.forEach(iA=>{if(E.has(iA)){const{sequence:EA=0}=E.get(iA)||{};T.push({key:iA,seq:EA}),M.push(iA)}});const P=yield function(iA,EA){return pA(this,void 0,void 0,function*(){const{groupID:RA,mainSequence:kA,groupAttributeList:xA,avChatRoomKey:LA,richStatusMode:SA}=iA,OA={GroupId:RA,AttrMainSeq:kA,GroupAttr:xA,BytesKey:LA,AttrControl:["RaceConflict"],AllowRoomEngineOpt:SA};return EA.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_attr",data:OA})})}({groupID:s,avChatRoomKey:u,groupAttributeList:T,mainSequence:g,richStatusMode:D},this._core),{AttrMainSeq:W}=P||{};return{resultList:M,serverMainSequence:W,groupAttributeList:T,operation:uD}})}_clearGroupAttributes(s,n){return pA(this,void 0,void 0,function*(){const{serverMainSequence:g,avChatRoomKey:u,values:E}=zs.getGroupAttributesCache(s),{richStatusMode:m}=n||{},D=[...E.keys()],M=yield function(P,W){return pA(this,void 0,void 0,function*(){const{groupID:iA,mainSequence:EA,avChatRoomKey:RA,richStatusMode:kA}=P,xA={GroupId:iA,AttrMainSeq:EA,BytesKey:RA,AttrControl:["RaceConflict"],AllowRoomEngineOpt:kA};return W.common.buildAndSendPacket({servcmd:"group_open_http_svc.clear_group_attr",data:xA})})}({groupID:s,avChatRoomKey:u,mainSequence:g,richStatusMode:m},this._core),{AttrMainSeq:T}=M||{};return{resultList:D,serverMainSequence:T,operation:ID}})}},DD=new class{constructor(){this._name="GetGroupAttributes"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"getGroupAttributes",context:this}),n.registerExperimentalAPI("getRichStatus",this,"getGroupAttributes")}getGroupAttributes(s){return pA(this,void 0,void 0,function*(){const{groupID:n}=s,{avChatRoomKey:g,lastUpdateTime:u,localMainSequence:E,serverMainSequence:m}=zs.getGroupAttributesCache(n),{helper:{ChatError:D}}=this._core,M=`groupID:${n} localMainSequence:${E} serverMainSequence:${m} keyList:${s.keyList}`;if(Date.now()-u>=3e4||E{const{key:iA,value:EA,seq:RA}=W;return{key:iA,value:EA,sequence:RA}});return zs.refreshGroupAttributesCache({groupID:u,serverMainSequence:M,groupAttributeList:P,operation:Ov}),{serverGroupAttributeList:T}})}},UQ=new class{init(s){s.ssoLog.debug("GroupAttribute.init"),Lm.init(s),bT.init(s),yD.init(s),DD.init(s),zs.init(s)}isGroupAttributesUpdated(s){return zs.isGroupAttributesUpdated(s)}handleGroupAttributesUpdated(s){const{to:n,elements:{newGroupProfile:g}}=s,{groupAttributeOption:u}=g,{serverMainSequence:E,withChangedAttributeInfo:m}=u,{localMainSequence:D}=zs.getGroupAttributesCache(n),M=E-D;if(console.log(`GroupAttribute.handleGroupAttributesUpdated groupID:${n} withChangedAttributeInfo:${m} diffSequence:${M}`),M!==0)if(zs.saveGroupAttributesCacheValuesCopy(n),m!==1||M!==1){if(zs.hasGroupAttributesCache(n)){const{avChatRoomKey:T}=zs.getGroupAttributesCache(n);DD.getGroupAttributesFromServer({groupID:n,avChatRoomKey:T}).then(()=>{zs.emitGroupAttributesUpdated(n)}).catch(()=>{})}}else zs.handleGroupAttributesUpdated({groupID:n,groupAttributeOption:u})}reset(){zs.reset()}};function HE(s,n="tips"){const{ClientSeq:g,From_Account:u,MsgClientTime:E,MsgPriority:m,MsgRandom:D,MsgSeq:M,MsgTimeStamp:T,TinyId:P,ToGroupId:W,GroupInfo:iA,MsgBody:EA}=s,RA=function(kA){const{GroupCode:xA,GroupId:LA,GroupName:SA,GroupType:OA,MsgFrom_AccountExtraInfo:JA,From_Account:ae,To_Account:se}=kA;return{groupCode:xA,groupID:LA,groupName:SA,type:OA,messageFromAccountExtraInformation:JA,from:ae,to:se}}(iA);return{clientSequence:g,from:u,clientTime:E,priority:m,random:D,sequence:M,time:T,tinyID:P,to:W,groupProfile:RA,elements:n==="tips"?Zu(EA):dh(EA)}}function Zu(s){const n={};return Object.keys(s).forEach(g=>{var u,E;switch(g){case"MemberNum":n.memberCount=s[g];break;case"OpType":n.operationType=s[g];break;case"Operator_Account":n.operatorID=s[g];break;case"List_Account":n.userIDList=s[g];break;case"MsgMemberExtraInfo":n.memberInfoList=(u=s[g])===null||u===void 0?void 0:u.map(m=>SD(m));break;case"MsgOperatorMemberExtraInfo":n.operatorInfo=SD(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=_T[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 SD(s){const{ImageUrl:n,NickName:g,Role:u,UserId:E}=s;return{avatar:n,nick:g,role:u,userID:E}}function dh(s){const n={};return Object.keys(s).forEach(g=>{switch(g){case"MsgKey":n.messageKey=s[g];break;case"Operator_Account":n.operatorID=s[g];break;case"ReportType":n.operationType=s[g];break;case"Authentication":n.authentication=s[g];break;case"MsgFlag":n.messageRemindType=s[g];break;case"UserDefinedField":n.userDefinedField=s[g];break;case"RemarkInfo":n.remarkInfo=s[g];break;case"BanDuration":n.duration=s[g];break;case"MuteTime":n.muteTime=s[g];break;case"MsgMemberExtraInfoList":n.inviteeInfoList=(u=s[g]||[])==null?void 0:u.map(E=>{const{UserId:m,ImageUrl:D,NickName:M}=E;return{userID:m,avatar:D,nick:M}});break;case"MemberList_Account":n.inviteeList=s[g]}var u}),n}class Um{constructor(n){this.type=Wn.core.OuterConstant.MSG_GRP_TIP,this.content={},this._initContent(n)}static parseServerPushElement(n){const g=Zu(n);return new Um(g)}_initContent(n){Object.keys(n).forEach(g=>{switch(g){case"groupProfile":this._initGroupProfile(n[g]);break;case"operatorInfo":this._initOperatorInfo(n[g]);break;case"memberInfoList":case"msgMemberInfo":this._updateMemberList(n[g]);break;case"newGroupProfile":this._initNewGroupProfile(n[g]);break;case"memberExtraInfo":case"remarkInfo":case"onlineMemberInfo":break;default:this.content[g]=n[g]}}),this.content.userIDList||(this.content.userIDList=[this.content.operatorID])}_initGroupProfile(n){this.content.groupProfile={};const g=Object.keys(n);for(let u=0;u{n.forEach(u=>{g.userID===u.userID&&Object.assign(g,u)})}):this.content.memberList=n}_initNewGroupProfile(n){this.content.newGroupProfile={};const g=Object.keys(n);for(let u=0;u0&&this._handleGroupTipMessage(g),{conversationUpdateFieldList:u,messageList:g}}_emitGroupTipsEvent(s){var n;const{constants:{WORKFLOW_STEP:g}}=this._core,{messageList:u=[]}=((n=s?.result)===null||n===void 0?void 0:n[g.HANDLE_GROUP_TIPS_NOTIFICATION])||{};if(u.length>0){const{notificationCenter:E,OuterEvent:m}=this._core;E.emitOuterEvent(m.MESSAGE_RECEIVED,{name:m.MESSAGE_RECEIVED,data:u})}}_handleGroupTips(s,n=!0){const{Event:g,GroupTips:u}=s,E=new Map,m=[],D=[];for(let M=0,T=u.length;M{const{operationType:u}=g.payload;switch(u){case n.JOINED:this._handleNewMemberJoined(g);break;case n.QUITTED:this._handleMemberQuitted(g);break;case n.KICKED:this._handleMemberKicked(g);break;case n.GROUP_PROFILE_UPDATED:this._handleGroupProfileUpdated(g);break;case n.ADMIN_SET:this._handleMemberGrantAdmin(g);break;case n.ADMIN_CANCELED:this._handleMemberRevokeAdmin(g)}})}_handleNewMemberJoined(s){this._handleGroupMemberCountUpdated(s)}_handleMemberQuitted(s){this._handleGroupMemberCountUpdated(s)}_handleMemberKicked(s){this._handleGroupMemberCountUpdated(s)}_handleGroupProfileUpdated(s){var n;const{newGroupProfile:g,groupProfile:u,operatorInfo:E}=s.payload,{groupID:m}=u,D=Yi.getLocalGroup(m);Object.keys(g).forEach(T=>{switch(T){case"ownerID":this._handleGroupOwnerChanged(m,g);break;case"groupName":D.name=g[T];break;case"groupCustomField":Array.isArray(D[T])&&Array.isArray(g[T])?Tm(D[T],g[T]):D[T]=g[T];break;default:D[T]=g[T]}});const{utils:{isUndefined:M}}=this._core;M(E)||((n=D?.selfInfo)===null||n===void 0?void 0:n.userID)!==E.userID||Object.keys(E).forEach(T=>{T==="nameCard"&&D.updateSelfInfo({nameCard:E[T]}),T==="role"&&this._updateSelfRole(D,E[T])}),Yi.emitGroupListUpdate(),Yi.updateConversationGroupProfile(m)}_handleGroupOwnerChanged(s,n){const{common:g,OuterConstant:u}=this._core,E=Yi.getLocalGroup(s),m=g.getCurrentUserID(),{ownerID:D}=n;m===D&&E.updateGroup({ownerID:D,selfInfo:{role:u.GRP_MBR_ROLE_OWNER}})}_updateSelfRole(s,n){const{OuterConstant:g}=this._core;let u=g.GRP_MBR_ROLE_MEMBER;n===pT?u=g.GRP_MBR_ROLE_OWNER:n===dD&&(u=g.GRP_MBR_ROLE_ADMIN),s.updateSelfInfo({role:u})}_handleGroupMemberCountUpdated(s){const{memberCount:n,groupProfile:{groupID:g}}=s.payload,u=Yi.getLocalGroup(g),{utils:{isNumber:E}}=this._core;u&&E(n)&&u.memberCount!==n&&(u.memberCount=n,Yi.emitGroupListUpdate(),Yi.updateConversationGroupProfile(g))}_handleGroupTipsRecover(s){const{utils:{isArray:n}}=this._core,{groupTipList:g}=s?.result||{};n(g)&&g.forEach(u=>{const{messageList:E}=this._handleGroupTips({Event:u.Event,GroupTips:[u]},!1);this._handleGroupTipMessage(E)})}_handleMemberGrantAdmin(s){const{OuterConstant:n}=this._core,{groupProfile:g,userIDList:u}=s.payload,E=this._core.common.getCurrentUserID(),{groupID:m}=g,D=Yi.getLocalGroup(m);D&&u.includes(E)&&(D.updateSelfInfo({role:n.GRP_MBR_ROLE_ADMIN}),Yi.emitGroupListUpdate(),Yi.updateConversationGroupProfile(m))}_handleMemberRevokeAdmin(s){const{OuterConstant:n}=this._core,{groupProfile:g,userIDList:u}=s.payload,E=this._core.common.getCurrentUserID(),{groupID:m}=g,D=Yi.getLocalGroup(m);D&&u.includes(E)&&(D.updateSelfInfo({role:n.GRP_MBR_ROLE_MEMBER}),Yi.emitGroupListUpdate(),Yi.updateConversationGroupProfile(m))}};class FQ{constructor(n){this.type=Wn.core.OuterConstant.MSG_GRP_SYS_NOTICE,this.content={},this._initContent(n)}static parseServerPushElement(n){const g=dh(n);return new FQ(g)}_initContent(n){Object.keys(n).forEach(g=>{switch(g){case"remarkInfo":this.content.handleMessage=n[g];break;case"groupProfile":this._initGroupProfile(n[g]);break;case"memberInfoList":break;default:this.content[g]=n[g]}})}_initGroupProfile(n){this.content.groupProfile={};const g=Object.keys(n);for(let u=0;u0&&this._handleGroupSysTemMessage(g,E),g===!0&&E.length>0&&m.emitOuterEvent(D.MESSAGE_RECEIVED,{name:D.MESSAGE_RECEIVED,data:E})}_handleGroupSystemNotification(s,n){const g=[];let u={};for(let E=0;E0?[u]:[],messageList:g}}_assembleMessage(s){const{message:{messageFactory:n},OuterConstant:g,utils:{randomInt:u}}=this._core;s.flow="in",s.conversationType=g.CONV_SYSTEM,s.conversationSubType=s.groupProfile.type,s.conversationID=g.CONV_SYSTEM;const E=n.createMessage(s),m=new FQ(Object.assign(Object.assign({},s.elements),{groupProfile:Object.assign({},s.groupProfile)}));E.setElement(m),E.isSystemMessage=!0;const D=E.sequence===1&&E.random===1,M=E.sequence===2&&E.random===2;return(D||M)&&(E.sequence=u(),E.random=u(),E.generateMessageID()),E}_handleConversationOptions(s,n){const{OuterConstant:g}=this._core,u={conversationID:g.CONV_SYSTEM,unreadCount:0,type:g.CONV_SYSTEM,subType:s.conversationSubType,lastMessage:null};return n&&u.unreadCount++,u}_handleGroupSysTemMessage(s,n){s&&n.forEach(g=>{const{operationType:u}=g.payload;switch(u){case fT:this._handleGroupJoinResult(g);break;case xv:this._handleMemberKicked(g);break;case yT:this._handleGroupDismissed(g);break;case DT:this._handleGroupInvitedResult(g);break;case CD:this._handleGroupQuitResult(g);break;case TQ:this._handleMessageRemindTypeSynced(g);break;case Mm:this._handleAVChatRoomMemberBanned(g)}})}_handleGroupJoinResult(s){const{groupProfile:n}=s.payload,{groupID:g,type:u}=n,E=Yi.hasLocalGroup(g);this._core.ssoLog.debug("_handleGroupJoinResult",` groupID:${g} type:${u} hasLocalGroup:${E}`),E||Sd(u)||(Yi.updateLocalGroup([Object.assign({},n)]),Yi.emitGroupListUpdate())}_handleMemberKicked(s){const{groupProfile:{groupID:n,type:g}}=s.payload;Yi.hasLocalGroup(n)&&this._deleteLocalGroup(n,g),this._updateConversationProfile(n,{unreadCount:0})}_handleGroupDismissed(s){const{groupProfile:{groupID:n,type:g}}=s.payload;Yi.hasLocalGroup(n)&&this._deleteLocalGroup(n,g),this._updateConversationProfile(n,{unreadCount:0})}_handleGroupInvitedResult(s){const{groupProfile:n}=s.payload,{groupID:g}=n,u=Yi.hasLocalGroup(g);this._core.ssoLog.debug("_handleGroupInvitedResult",` groupID:${g} hasLocalGroup:${u}`),u||Pl.getGroupProfile({groupID:g}).then(E=>{const{data:{group:m}}=E;Yi.updateLocalGroup([Object.assign({},m)]),Yi.emitGroupListUpdate()})}_handleGroupQuitResult(s){const{groupProfile:{groupID:n,type:g}}=s.payload,u=Yi.hasLocalGroup(n);this._core.ssoLog.debug("_handleGroupQuitResult",` groupID:${n} type:${g} hasLocalGroup:${u}`),u&&this._deleteLocalGroup(n,g),this._updateConversationProfile(n,{unreadCount:0})}_handleMessageRemindTypeSynced(s){const{groupProfile:{groupID:n},messageRemindType:g}=s.payload;this._updateConversationProfile(n,{messageRemindType:g})}_handleAVChatRoomMemberBanned(s){const{groupProfile:{groupID:n,type:g}}=s.payload;this._deleteLocalGroup(n,g)}_deleteLocalGroup(s,n){if(Sd(n)){const{appStore:{conversationStore:g},OuterConstant:{CONV_GROUP:u}}=this._core;g.deleteConversation(`${u}${s}`)}Yi.deleteLocalGroup(s),Yi.emitGroupListUpdate()}_updateConversationProfile(s,n){const{appStore:{conversationStore:g},OuterConstant:{CONV_GROUP:u}}=this._core,E=`${u}${s}`;g.getConversation(E)&&g.updateConversation(E,n)}},MD=new class{init(s){this._core=s,s.ssoLog.debug("GroupNotificationHandler.init"),zv.init(s),Zv.init(s);const{notificationCenter:n,InnerEvent:g}=s,{InnerEventSubType:u}=n;n.subscribeInnerEvent(g.MESSAGE_PUSH,u.GROUP_TIPS_NOTIFICATION,this._onNewGroupTipsNotification,this),n.subscribeInnerEvent(g.MESSAGE_PUSH,u.GROUP_SYSTEM_NOTIFICATION,this._onNewGroupSystemNotification,this),n.subscribeInnerEvent(g.DESTROY,this._dispose,this)}_onNewGroupTipsNotification(s){const{common:{workflowManager:n},constants:{WORKFLOW_NAME:g}}=this._core;n.executeWorkflow(g.RECEIVE_GROUP_TIPS_NOTIFICATION,s)}_onNewGroupSystemNotification(s){Zv.onNewGroupSystemNotification(s)}_dispose(){const{notificationCenter:s,InnerEvent:n}=this._core,{InnerEventSubType:g}=s;s.unSubscribeInnerEvent(n.MESSAGE_PUSH,g.GROUP_TIPS_NOTIFICATION,this._onNewGroupTipsNotification,this),s.unSubscribeInnerEvent(n.MESSAGE_PUSH,g.GROUP_SYSTEM_NOTIFICATION,this._onNewGroupSystemNotification,this)}};const vn={required:!0,rules:["string"],allowEmpty:!1},OQ={required:!0,rules:["number"],allowEmpty:!1},wd={required:!0,rules:["array"],allowEmpty:!1},vD={required:!0,rules:["object"],allowEmpty:!1},kT={createGroup:{name:vn,type:vn},dismissGroup:[Object.assign({key:"groupID"},vn)],joinGroup:{groupID:vn,applyMessage:{required:!1,rules:["string"],allowEmpty:!0}},quitGroup:[Object.assign({key:"groupID"},vn)],searchGroupByID:[Object.assign({key:"groupID"},vn)],getGroupProfile:{groupID:vn,groupCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},updateGroupProfile:{groupID:vn,muteAllMembers:{required:!1,rules:["boolean"],allowEmpty:!1}},changeGroupOwner:{groupID:vn,newOwnerID:vn},getGroupOnlineMemberCount:[Object.assign({key:"groupID"},vn)],handleGroupApplication:{handleAction:vn},getGroupMemberList:{groupID:vn},getGroupMemberProfile:{groupID:vn,userIDList:wd,memberCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},addGroupMember:{groupID:vn,userIDList:wd},deleteGroupMember:{groupID:vn,userIDList:wd},setGroupMemberMuteTime:{groupID:vn,userID:vn,muteTime:Object.assign(Object.assign({},OQ),{customValidator:s=>!(s<0)||"muteTime must be a non-negative number."})},setGroupMemberRole:{groupID:vn,userID:vn,role:vn},setGroupMemberNameCard:{groupID:vn,userID:{required:!1,rules:["string"],allowEmpty:!1},nameCard:vn},setGroupMemberCustomField:{groupID:vn,userID:{required:!1,rules:["string"],allowEmpty:!1},memberCustomField:wd},markGroupMemberList:{groupID:vn,markType:Object.assign(Object.assign({},OQ),{customValidator:s=>!(s<1e3)||"markType must be greater than or equal to 1000."}),enableMark:{required:!0,rules:["boolean"],allowEmpty:!1},userIDList:wd},initGroupAttributes:{groupID:vn,groupAttributes:vD},setGroupAttributes:{groupID:vn,groupAttributes:vD},deleteGroupAttributes:{groupID:vn,keyList:Object.assign(Object.assign({},wd),{allowEmpty:!0})},getGroupAttributes:{groupID:vn,keyList:Object.assign(Object.assign({},wd),{allowEmpty:!0})},getGroupCounters:{groupID:vn,keyList:{required:!1,rules:["array"],allowEmpty:!0}},setGroupCounters:{groupID:vn,counters:vD},increaseGroupCounter:{groupID:vn,key:vn,value:OQ},decreaseGroupCounter:{groupID:vn,key:vn,value:OQ}},LT={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 UT=new class{constructor(){this._installedSubPlugins=[],this.groupDataHandler=Yi,this.groupAction=bQ,this.groupAttribute=UQ,this.groupMember=Wv,this.groupCounter=IB,this.name="Group"}install(s,n=[]){this._core=s,Wn.init(s),Yi.init(s),bQ.init(s,this),Wv.init(s,this),pD.init(s),IB.init(s),UQ.init(s),MD.init(s),s.helper.registerValidateConfig({auth:LT,params:kT}),this._installSubPlugins(n);const{notificationCenter:g,InnerEvent:u}=s;g.subscribeInnerEvent(u.LOGOUT,this._reset,this),g.subscribeInnerEvent(u.DESTROY,this._dispose,this)}getInstalledSubPlugins(){return this._installedSubPlugins}_installSubPlugins(s){const{utils:{isArray:n}}=this._core;s&&n(s)&&s.forEach(g=>{var u;this._installedSubPlugins.includes(g.name)||((u=g.install)===null||u===void 0||u.call(g,this._core,this),this._installedSubPlugins.push(g.name))})}_reset(){Yi.reset(),UQ.reset(),IB.reset()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(n.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this)}};const uB=new class{init(s){this.core=s}},Xv="AV_MBR_LIST",FT="AV_BAN_MBR",qE={NORMAL_MESSAGE:3,GROUP_TIPS_HAS_ROAMING:4,GROUP_SYSTEM_MESSAGE:5,GROUP_TIPS_HAS_NO_ROAMING:6,BROADCAST_MESSAGE:17,MESSAGE_REVOKED:20,MESSAGE_REACTION:21,LIVE_CUSTOM_DATA:100},Ch={GROUP_DISMISSED:5,QUIT_GROUP:8,AVCHATROOM_MEMBER_BANNED:21},RD=60,wD=2603,OT=2686,PT=2688,PQ=3122;class $v{constructor(n){const{core:g,manager:u,groupID:E,getRequestParams:m,onSuccess:D,onFail:M}=n;this._name="Polling",this._core=g,this._manager=u,this._timeoutID=-1,this._isRunning=!1,this._groupID=E,this._getRequestParams=m,this._onSuccess=D,this._onFail=M}start(){this._isRunning=!0,this._request(),console.log(`${this._name}.start pollingInterval:${this._manager.getCurrentPollingInterval(this._groupID)}`)}isRunning(){return this._isRunning}_request(){return pA(this,void 0,void 0,function*(){try{const n=this._getRequestParams(this._groupID),g=yield function(E,m){return pA(this,void 0,void 0,function*(){const{longPollingKey:D,startSequence:M,startBroadcastSeq:T,simplifiedMessage:P}=E,W={Key:D,StartSeq:M,StartBroadcastSeq:T,DownsizeFlag:P,USP:1,HoldTime:90};return m.common.buildAndSendPacket({servcmd:"group_open_long_polling_http_svc.get_msg",data:W})})}(n,this._core);this._onSuccess(this._groupID,g);const u=this._manager.getCurrentPollingInterval(this._groupID);this._runNextPolling(u)}catch(n){this._onFail(this._groupID,n),this._runNextPolling(2e3)}})}_runNextPolling(n){this.isRunning()&&(this._timeoutID>-1&&clearTimeout(this._timeoutID),this._timeoutID=setTimeout(this._request.bind(this),n))}stop(){console.log(`${this._name}.stop timerID:${this._timeoutID}`),this._timeoutID>-1&&(clearTimeout(this._timeoutID),this._timeoutID=-1),this._isRunning=!1}}class hh{constructor(n){this._maxLength=n,this._map=new Map}set(n){var g;if(this._map.size>=this._maxLength){const u=((g=this._map.entries().next().value)===null||g===void 0?void 0:g[0])||"";this._map.delete(u)}this._map.set(n,1)}has(n){return this._map.has(n)}delete(n){this.has(n)&&this._map.delete(n)}clear(){this._map.clear()}}const Xu=s=>s===qE.GROUP_TIPS_HAS_NO_ROAMING||s===qE.GROUP_TIPS_HAS_ROAMING,xQ=s=>s===qE.GROUP_SYSTEM_MESSAGE;function Fm(s){const n=function(g){const{E:u,MCT:E,MR:m,MP:D,MTS:M,GId:T,MS:P,CCD:W,F_Account:iA,IsSys:EA,GInf:RA,MsgBody:kA}=g,xA=Do(g,["E","MCT","MR","MP","MTS","GId","MS","CCD","F_Account","IsSys","GInf","MsgBody"]);return Object.assign({Event:u,MsgClientTime:E,MsgRandom:m,MsgPriority:D,MsgTimeStamp:M,ToGroupId:T,MsgSeq:P,CloudCustomData:W,From_Account:iA,IsSystemMsg:EA,GroupInfo:_D(RA),MsgBody:xT(kA)},xA)}(s);return function(g){const{Event:u}=g;(Xu(u)||xQ(u))&&(g.From_Account=g.From_Account||"@TIM#SYSTEM"),E=u,(E===qE.BROADCAST_MESSAGE||(m=>m===qE.NORMAL_MESSAGE)(u))&&function(m){const{core:{OuterConstant:D}}=uB;m.CloudCustomData=m.CloudCustomData||"",m.MsgBody=m.MsgBody.map(M=>{if(M.MsgType===D.MSG_CUSTOM){const{content:T={}}=M;M.content=Object.assign({Data:"",Desc:"",Ext:""},T)}return M})}(g);var E;Xu(u)&&function(m){const{GroupJoinType:D,MsgOperatorMemberExtraInfo:M={},MsgMemberExtraInfo:T,Operator_Account:P,List_Account:W,OpType:iA}=m.MsgBody||{};typeof D=="number"||iA!==1&&iA!==2||(m.MsgBody.GroupJoinType=iA===2?0:1),T||(m.MsgBody.MsgMemberExtraInfo=W?.map(EA=>({UserId:EA}))),iA!==1||T||(m.MsgBody.MsgMemberExtraInfo=[{UserId:M.UserId}]),m.MsgBody.MsgOperatorMemberExtraInfo=Object.assign({Operator_Account:P,ImageUrl:"",NickName:""},M)}(g),xQ(u)&&function(m){const{MsgOperatorMemberExtraInfo:D={},Operator_Account:M}=m.MsgBody||{};m.MsgBody.MsgMemberExtraInfo=Object.assign({UserId:M,ImageUrl:"",NickName:""},D),m.MsgBody=Object.assign({Authentication:"",RemarkInfo:"",MsgKey:1e3*m.MsgTimeStamp},m.MsgBody),m.MsgBody=Object.keys(m.MsgBody).filter(T=>T!=="MsgOperatorMemberExtraInfo").reduce((T,P)=>Object.assign(Object.assign({},T),{[P]:m.MsgBody[P]}),{})}(g)}(n),n}function _D(s){const n=s||{},{GN:g,GT:u,F_Hd:E,F_NN:m,F_Ll:D}=n,M=Do(n,["GN","GT","F_Hd","F_NN","F_Ll"]),T=Object.assign({GroupName:g,GroupType:u},M);return E&&(T.From_AccountHeadurl=E),m&&(T.From_AccountNick=m),D&&(T.From_AccountLevel=D),T}function xT(s){let n=s;Array.isArray(s)||(n=[s]);const g=n.map(u=>{const{O_Account:E,Opt:m,L_Account:D,RT:M,UDF:T,OpInf:P,OnlineInf:W,MsgMemberExtraInfo:iA}=u,EA=Do(u,["O_Account","Opt","L_Account","RT","UDF","OpInf","OnlineInf","MsgMemberExtraInfo"]),RA=Object.assign({Operator_Account:E,OpType:m,List_Account:D,ReportType:M,UserDefinedField:T},EA);return P&&(RA.MsgOperatorMemberExtraInfo=function(kA){const{Img:xA,NN:LA}=kA,SA=Do(kA,["Img","NN"]);return Object.assign({ImageUrl:xA,NickName:LA},SA)}(P)),iA&&(RA.MsgMemberExtraInfo=function(kA){return kA?.map(xA=>{const{Img:LA,NN:SA}=xA,OA=Do(xA,["Img","NN"]);return Object.assign({ImageUrl:LA,NickName:SA},OA)})}(iA)),W&&(RA.OnlineMemberInfo=function(kA){const{ET:xA,Num:LA}=kA;return{ExpireTime:xA,OnlineMemberNum:LA}}(W)),RA});return Array.isArray(s)?g:g[0]}var Bh=new class{constructor(){this._name="MessageParser",this._sequenceList=new hh(200),this._messageIDList=new hh(100),this._broadcastMessageIDMap=new Map,this._reportMessageStackedCount=0}init(s,n){this._core=s,this._avChatRoomHandler=n}onMessageReceived(s,n,g=!1){this._sortServerMessageList({groupID:s,serverMessageList:n,isHistoryMessage:g});const u=this._handleMessageList(s,n);if(u.length===0)return;if(!g){const{appStore:{conversationStore:T},OuterConstant:{CONV_GROUP:P},common:{buildLastMessage:W}}=this._core,iA=W(u[u.length-1]);T.updateConversation(`${P}${s}`,{lastMessage:iA})}this._checkMessageStacked(u);const E=u.filter(T=>T.isModified===!0),m=u.filter(T=>T.isModified===!1),{OuterEvent:{MESSAGE_RECEIVED:D,MESSAGE_MODIFIED:M}}=this._core;E.length>0&&this._emitEvent({name:M,data:E}),m.length>0&&this._emitEvent({name:D,data:m})}_sortServerMessageList(s){const{groupID:n,serverMessageList:g,isHistoryMessage:u}=s;let E=[];this._avChatRoomHandler.isPollingSimplifiedMessage()&&!u?(g.sort((m,D)=>m.MS-D.MS),E=g.map(m=>m.MS)):(g.sort((m,D)=>m.MsgSeq-D.MsgSeq),E=g.map(m=>m.MsgSeq)),console.log(`${this._name}._sortServerMessageList groupID:${n} count:${E.length} sequenceList:${E}`),E.length=0}_handleMessageList(s,n){var g;const{message:{messageDataHandler:u,messageHelper:E}}=this._core,m=this._avChatRoomHandler.isPollingSimplifiedMessage(),D=[],M=n.length;for(let T=0;Tg===qE.MESSAGE_REVOKED)(n)?(this._handleMessageRevoked(s),null):(g=>g===qE.LIVE_CUSTOM_DATA)(n)?(this._onLiveCustomData(s),null):(g=>g===qE.MESSAGE_REACTION)(n)?null:s:(console.warn(`${this._name}.onMessageReceived unknown event:${n}`),null)}_createMessage(s){const{message:{messageFactory:n},OuterConstant:g}=this._core;let u=g.CONV_GROUP;s.elements.type===g.MSG_GRP_SYS_NOTICE&&(u=g.CONV_SYSTEM);const E=!!s.isSystemMessage,m=n.createMessage(Object.assign(Object.assign({},s),{conversationType:u,isSystemMessage:E,flow:"in"}));return m.setElement(s.elements),m}_filterDuplicateMessage(s){const{common:n}=this._core;if(!n.isUnlimitedAVChatRoom()){if(this._sequenceList.has(s.sequence))return null;this._sequenceList.set(s.sequence)}const g=this._messageIDList.has(s.ID);return g?(console.warn(`${this._name}_filterDuplicateMessageItem ID:${s.ID} has:${g}`),null):(this._messageIDList.set(s.ID),s)}_handleMessageRevoked(s){const{OuterConstant:n,OuterEvent:{MESSAGE_REVOKED:g}}=this._core,{ToGroupId:u,MsgBody:{RevokeMsgList:E},RevokerInfo:{Revoker_Account:m,Reason:D=""}}=s,M=[];E.forEach(T=>{const{TinyId:P,MsgClientTime:W,Random:iA,MsgSeq:EA}=T,RA={conversationID:`${n.CONV_GROUP}${u}`,ID:`${P}-${W}-${iA}`,revoker:m,revokeReason:D,revokerInfo:{userID:m,nick:"",avatar:""},sequence:EA};M.push(RA)}),M.length!==0&&this._emitEvent({name:g,data:M})}_onLiveCustomData(s){const{OuterEvent:{ROOM_CUSTOM_DATA_RECEIVED:n}}=this._core,{ToGroupId:g,MsgSeq:u,MsgTimeStamp:E,MsgBody:m}=s,D=m?.Content||m?.MsgContent||"";this._emitEvent({name:n,data:D}),console.log(`${this._name}._onLiveCustomData groupID:${g} sequence:${u} time:${E} data:${D}`)}_onGroupDismissed(s){this._avChatRoomHandler.reset(s)}_checkMessageStacked(s){const{length:n}=s;if(n>=100&&this._reportMessageStackedCount<5){const g=this._avChatRoomHandler.getJoinedGroups();this._core.ssoLog.info("MessageStacked",`count:${n} groupID:${g.join(",")}`),this._reportMessageStackedCount+=1}}_emitEvent(s){this._core.notificationCenter.emitOuterEvent(s.name,s)}onBroadcastMessageReceived(s){const{message:{messageHelper:n},OuterEvent:{MESSAGE_RECEIVED:g}}=this._core,u=this._avChatRoomHandler.isPollingSimplifiedMessage(),E=[],m=s.length;for(let D=0;D0&&this._emitEvent({name:g,data:E})}_updateLocalOnlineMemberCountFromTips(s){const{utils:{isEmpty:n}}=this._core,{ToGroupId:g,MsgBody:{OnlineMemberInfo:u}}=s;if(n(u))return;const{OnlineMemberNum:E=0,ExpireTime:m=RD}=u,D=Date.now();let M=this._avChatRoomHandler.getLocalOnlineMemberCount(g);n(M)?M={lastReqTime:0,lastSyncTime:0,latestUpdateTime:D,memberCount:E,expireTime:m}:(M.latestUpdateTime=D,M.memberCount=E),this._avChatRoomHandler.updateLocalOnlineMemberCount(g,M)}reset(){this._reportMessageStackedCount=0,this._sequenceList.clear(),this._messageIDList.clear(),this._broadcastMessageIDMap.clear()}};const EB=s=>{const{core:{store:n}}=uB;return(n.get("cloudConfig")||{})[s]},Qh=s=>{const{core:{utils:{isUndefined:n}}}=uB;return!n(s)},YQ=()=>{const s=EB("polling_interval");return Qh(s)?parseInt(s,10):300},dB=()=>{const s=EB("polling_simplified_msg");return Qh(s)?parseInt(s,10):0};var AR=new class{constructor(){this._name="GetAVChatRoomOnlineMemberCount"}init(s,n){this._core=s,this._parentPlugin=n;const{helper:g}=s;g.registerApi({apiName:"getGroupOnlineMemberCount",context:this,matcher:()=>n.getInstalledSubPlugins().length>0})}getGroupOnlineMemberCount(s){return pA(this,void 0,void 0,function*(){const{appStore:{groupStore:n},OuterConstant:g}=this._core,u=n.getGroup(s);return u?u.type===g.GRP_AVCHATROOM?this._getOnlineMemberCount(s):this._parentPlugin.groupAction.getGroupOnlineMemberCount(s):{code:0,data:{memberCount:0}}})}_getOnlineMemberCount(s){return pA(this,void 0,void 0,function*(){const n="_getOnlineMemberCount",{utils:{isEmpty:g}}=this._core,u=Pg.getLocalOnlineMemberCount(s);if(g(u)||this._isExpired(s)){const{memberCount:E=0}=yield this._getOnlineMemberCountFromServer(s);return console.log(`${this._name}.${n} ok, groupID:${s} memberCount:${E} from server.`),{code:0,data:{memberCount:E}}}return console.log(`${this._name}.${n} ok, groupID:${s} memberCount:${u.memberCount} from local.`),{code:0,data:{memberCount:u.memberCount}}})}_isExpired(s){const n=Pg.getLocalOnlineMemberCount(s),g=Date.now(),u=g-n.lastSyncTime>1e3*n.expireTime,E=g-n.latestUpdateTime>1e4,m=g-n.lastReqTime>3e3;return u&&E&&m}_getOnlineMemberCountFromServer(s){return pA(this,void 0,void 0,function*(){const n="_getOnlineMemberCountFromServer";try{const g=yield function(M,T){return pA(this,void 0,void 0,function*(){const P={GroupId:M};return T.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_online_member_num",data:P})})}(s,this._core),{OnlineMemberNum:u=0,ExpireTime:E=RD}=g||{},m=Date.now(),D={lastSyncTime:m,latestUpdateTime:m,lastReqTime:m,memberCount:u,expireTime:E};return Pg.updateLocalOnlineMemberCount(s,D),{memberCount:u}}catch(g){const u=new this._core.helper.ChatError({functionName:n,code:g?.errorCode,message:g?.errorInfo});throw console.error(`${this._name}.${n} fail:`,u),u}})}},Pg=new class{constructor(){this._name="AVChatRoomHandler",this._joinedGroupMap=new Map,this._pollingRequestInfoMap=new Map,this._pollingInstanceMap=new Map,this._onlineMemberCountMap=new Map,this._pollingIntervalMap=new Map,this._pollingNoMessageCountMap=new Map,this._membersReqInfoMap=new Map,this._startBroadcastSequence=1}init(s,n){this._core=s,this._parentPlugin=n,Bh.init(s,this),s.ssoLog.debug("AVChatRoomHandler.init")}onAVChatRoomSystemNotification(s){const{OuterConstant:{GRP_AVCHATROOM:n}}=this._core,{GroupTips:g=[]}=s;for(let u=0;u0&&(n=[...this._joinedGroupMap.values()].filter(g=>g.type===s)),n}handleJoinGroupResult(s){return pA(this,void 0,void 0,function*(){const{utils:{isUndefined:n},OuterConstant:{CONV_GROUP:g},apiMap:{getConversationProfile:u},OuterConstant:E}=this._core,{longPollingKey:m,group:D,historyMessageList:M=[]}=s,{groupID:T}=D;return yield this._preCheck(D),this._joinedGroupMap.set(T,D),this._parentPlugin.groupDataHandler.updateLocalGroup([D]),this._parentPlugin.groupDataHandler.emitGroupListUpdate(),u(`${g}${T}`),AR.getGroupOnlineMemberCount(T),M.length>0&&Bh.onMessageReceived(T,M,!0),n(m)?{code:0,data:{status:E.JOIN_STATUS_SUCCESS,group:D}}:{code:0,data:this.startMessageLongPolling(s)}})}isGroupCounterUpdated(s){return this._parentPlugin.groupCounter.isGroupCounterUpdated(s)}handleGroupCounterUpdated(s){this._parentPlugin.groupCounter.handleGroupCounterUpdated(s)}_preCheck(s){return pA(this,void 0,void 0,function*(){const{common:n,OuterConstant:g,helper:u,apiMap:{quitGroup:E},ssoLog:m}=this._core;if(n.isUnlimitedAVChatRoom()){if(this._pollingInstanceMap.size>(()=>{const T=EB("polling_count_limit");return Qh(T)&&T>0?parseInt(T,10):20})())throw new u.ChatError({code: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:u=1,group:E}=s,{groupID:m}=E;return this._pollingRequestInfoMap.set(m,{longPollingKey:g,startSequence:u}),this._pollingIntervalMap.set(m,YQ()),this._startPolling(m),this._reportLongPollingCount(),{status:n.JOIN_STATUS_SUCCESS,group:E}}_startPolling(s){if(this._core.ssoLog.debug("_startPolling",`${this._name}._startPolling groupID:${s}`),this._pollingInstanceMap.has(s)){const g=this._pollingInstanceMap.get(s);return void(g?.isRunning()||g==null||g.start())}const n=new $v({core:this._core,manager:this,groupID:s,getRequestParams:this._handleRequestParams.bind(this),onSuccess:this._handleSuccess.bind(this),onFail:this._handleFailure.bind(this)});n.start(),this._pollingInstanceMap.set(s,n)}_handleRequestParams(s){const{longPollingKey:n,startSequence:g}=this._pollingRequestInfoMap.get(s)||{};return s===[...this._pollingInstanceMap.keys()][0]?{longPollingKey:n,startSequence:g,startBroadcastSeq:this._startBroadcastSequence,simplifiedMessage:dB()}:{longPollingKey:n,startSequence:g,simplifiedMessage:dB()}}_handleSuccess(s,n){const{ErrorCode:g}=n;if(g!==0){const{longPollingKey:u,startSequence:E}=this._pollingRequestInfoMap.get(s)||{};return void console.warn(`${this._name}._handleSuccess groupID:${s} key:${u} startSeq:${E} errorCode:${g}`)}this._hasJoinedAVChatRoom(s)&&this._handleResponseData(s,n)}_handleResponseData(s,n){const{Key:g,NextSeq:u,NextBroadcastSeq:E,RspMsgList:m=[],RspBroadcastMsgList:D=[]}=n;if(g&&u&&this._pollingRequestInfoMap.set(s,{longPollingKey:g,startSequence:u}),E&&E>this._startBroadcastSequence&&(this._startBroadcastSequence=E),m.length>0)this._getPollingNoMessageCount(s)!==0&&(this._updatePollingNoMessageCount(s,0),this._pollingIntervalMap.set(s,YQ())),Bh.onMessageReceived(s,m);else{let M=this._getPollingNoMessageCount(s);if(M+=1,this._updatePollingNoMessageCount(s,M),M===(()=>{const T=EB("polling_no_msg_count");return Qh(T)?parseInt(T,10):20})()){const T=YQ()+(()=>{const P=EB("polling_interval_plus");return Qh(P)?parseInt(P,10):2e3})();this._pollingIntervalMap.set(s,T)}}D.length>0&&Bh.onBroadcastMessageReceived(D)}_handleFailure(s,n){const{ssoLog:g,utils:{safeStringify:u}}=this._core;g.warn("polling",`${this._name}._handleFailure groupID:${s} error: ${u(n)}`)}_joinedAVChatRoomCount(){const{OuterConstant:s}=this._core;let n=[];return this._joinedGroupMap.size>0&&(n=this.getJoinedGroups().filter(g=>g.type===s.GRP_AVCHATROOM)),n.length}_hasJoinedAVChatRoom(s){return this._joinedGroupMap.has(s)}getJoinedGroups(){return[...this._joinedGroupMap.values()]}updateLocalLiveGroup(s,n){this._joinedGroupMap.set(s,n),this._parentPlugin.groupDataHandler.updateLocalGroup([n])}handleLiveHistoryMessages(s,n){Bh.onMessageReceived(s,n,!0)}isOverFrequencyLimit(s){if(!this._membersReqInfoMap.has(s))return this._membersReqInfoMap.set(s,{startTime:Date.now(),requestCount:1}),!1;let{startTime:n,requestCount:g}=this._membersReqInfoMap.get(s);const{interval:u,count:E}=(()=>{const m=EB("av_members_freq_limit");if(Qh(m)){const{interval:D,count:M}=JSON.parse(m);if(M>0&&D>0)return{interval:D,count:M}}return{interval:30,count:4}})();return Date.now()-n>1e3*u?(this._membersReqInfoMap.set(s,{startTime:Date.now(),requestCount:1}),!1):(g+=1,this._membersReqInfoMap.set(s,{startTime:n,requestCount:g}),g>E)}_stopPolling(s){if(this._core.ssoLog.debug("_stopPolling",`${this._name}._stopPolling groupID:${s}`),s){const{appStore:{conversationStore:n},OuterConstant:{CONV_GROUP:g}}=this._core;n.deleteConversation(`${g}${s}`);const u=this._pollingInstanceMap.get(s);return u?.stop(),this._parentPlugin.groupDataHandler.deleteLocalGroup(s),this._pollingInstanceMap.delete(s),this._pollingRequestInfoMap.delete(s),this._joinedGroupMap.delete(s),this._onlineMemberCountMap.delete(s),this._pollingIntervalMap.delete(s),this._pollingNoMessageCountMap.delete(s),void this._membersReqInfoMap.delete(s)}for(const n of this._pollingInstanceMap.values())n?.stop();this._pollingInstanceMap.clear(),this._pollingRequestInfoMap.clear(),this._joinedGroupMap.clear(),this._onlineMemberCountMap.clear(),this._pollingIntervalMap.clear(),this._pollingNoMessageCountMap.clear(),this._membersReqInfoMap.clear()}_updatePollingNoMessageCount(s,n){this._pollingNoMessageCountMap.set(s,n)}_getPollingNoMessageCount(s){return this._pollingNoMessageCountMap.get(s)||0}_reportLongPollingCount(){const s=this._joinedGroupMap.size;if(s>1){const{common:n,OuterConstant:g,ssoLog:u}=this._core,E=n.isUnlimitedAVChatRoom()?1:0,m=[],D=[];Array.from(this._joinedGroupMap.values()).forEach(({groupID:M,type:T})=>{T===g.GRP_LIVE?D.push(M):m.push(M)}),u.info("longPollingCount",String(s),{moreMessage:`av:${m.join(",")} live:${D.join(",")} code: ${E}`,eventType:29})}}reset(s){this._stopPolling(s),this._startBroadcastSequence=1,Bh.reset()}},eR=new class{init(s,n){this._core=s,this._parentPlugin=n;const{helper:g}=s;g.registerApi({apiName:"joinGroup",context:this,matcher:()=>n.getInstalledSubPlugins().length>0})}joinGroup(s){return pA(this,void 0,void 0,function*(){const{OuterConstant:n}=this._core,g=yield this._parentPlugin.groupAction.joinGroup(s),{data:{status:u,group:{type:E}}}=g;return E===n.GRP_AVCHATROOM?u===n.JOIN_STATUS_ALREADY_IN_GROUP?g:Pg.handleJoinGroupResult(g.data):g})}},YT=new class{init(s,n){this._core=s,this._parentPlugin=n;const{helper:g}=s;g.registerApi({apiName:"quitGroup",context:this,matcher:()=>n.getInstalledSubPlugins().length>0})}quitGroup(s){return pA(this,void 0,void 0,function*(){const{OuterConstant:n}=this._core,g=yield this._parentPlugin.groupAction.quitGroup(s),{data:{type:u}}=g;return u===n.GRP_AVCHATROOM&&Pg.reset(s),g})}},tR=new class{init(s,n){this._core=s,this._parentPlugin=n;const{helper:g}=s;g.registerApi({apiName:"dismissGroup",context:this,matcher:()=>n.getInstalledSubPlugins().length>0})}dismissGroup(s){return pA(this,void 0,void 0,function*(){const{OuterConstant:n}=this._core,g=yield this._parentPlugin.groupAction.dismissGroup(s),{data:{type:u}}=g;return u===n.GRP_AVCHATROOM&&Pg.reset(s),g})}},Om=new class{constructor(){this._name="GetAVChatRoomMemberList"}init(s,n){this._core=s,this._parentPlugin=n;const{helper:g}=s;g.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>n.getInstalledSubPlugins().length>0})}getGroupMemberList(s){return pA(this,void 0,void 0,function*(){const{appStore:{groupStore:n},helper:g,OuterConstant:u}=this._core,{groupID:E}=s,m=n.getGroup(E);if(m?.type===u.GRP_AVCHATROOM&&g.checkBusinessCapabilityBits(Xv)){if(Pg.isOverFrequencyLimit(E))throw{code:2996,message:`Over frequency limit: get_members-${E}`};return this._getGroupMemberList(s)}return this._parentPlugin.groupMember.getGroupMemberList(s)})}_getGroupMemberList(s){return pA(this,void 0,void 0,function*(){const n="_getGroupMemberList",{helper:g}=this._core;try{const u=yield function(M,T){return pA(this,void 0,void 0,function*(){const{groupID:P,offset:W=0}=M,iA={GroupId:P,Timestamp:W};return T.common.buildAndSendPacket({servcmd:"group_open_avchatroom_http_svc.get_members",data:iA})})}(s,this._core),{MemberList:E=[],NextTimestamp:m=0}=u||{},D=this._handleMemberList(E);return console.log(`${this._name}.${n} ok, groupID:${s.groupID} count:${D.length} nextOffset:${m}`),{code:0,data:{memberList:D,offset:m}}}catch(u){const E=new g.ChatError({functionName:n,code:u?.errorCode,message:u?.errorInfo});throw console.error(`${this._name}.${n} fail:`,E),E}})}_handleMemberList(s){return s.map(n=>{const{Member_Account:g,NickName:u="",Avatar:E="",Remark:m="",JoinTime:D=0,Marks:M=[]}=n;return{userID:g,nick:u,avatar:E,remark:m,joinTime:D,marks:M,isOnline:!0}})}},Pm=new class{constructor(){this._name="DeleteAVChatRoomMember"}init(s,n){this._core=s,this._parentPlugin=n;const{helper:g}=s;g.registerApi({apiName:"deleteGroupMember",context:this,matcher:()=>n.getInstalledSubPlugins().length>0})}deleteGroupMember(s){return pA(this,void 0,void 0,function*(){const n="deleteGroupMember",{appStore:{groupStore:g},utils:{isUndefined:u},helper:E,OuterConstant:m}=this._core,{groupID:D}=s,M=g.getGroup(D);if(u(M))throw new E.ChatError({functionName:n,code:wD});if(M.type===m.GRP_AVCHATROOM){if(E.checkBusinessCapabilityBits(FT))return this._deleteGroupMember(s);throw new E.ChatError({functionName:n,code:PQ})}return this._parentPlugin.groupMember.deleteGroupMember(s)})}_deleteGroupMember(s){return pA(this,void 0,void 0,function*(){const n="_deleteGroupMember",{appStore:{groupStore:g},helper:u,ssoLog:E}=this._core,{groupID:m,duration:D=0,userIDList:M}=s;if(D===0)throw new u.ChatError({functionName:n,code:OT});try{return yield function(T,P){return pA(this,void 0,void 0,function*(){const{groupID:W,userIDList:iA,duration:EA,reason:RA}=T,kA={GroupId:W,Members_Account:iA,Duration:EA,Description:RA};return P.common.buildAndSendPacket({servcmd:"group_open_http_svc.ban_group_member",data:kA})})}(s,this._core),E.debug(n,`${this._name}.${n} ok, groupID:${m}`),{code:0,data:{group:g.getGroup(m),userIDList:M}}}catch(T){throw new u.ChatError({functionName:n,code:T?.errorCode,message:T?.errorInfo})}})}},_d=new class{constructor(){this._name="MarkAVChatRoomMember"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"markGroupMemberList",context:this})}markGroupMemberList(s){return pA(this,void 0,void 0,function*(){const n="markGroupMemberList",{groupID:g,markType:u,enableMark:E,userIDList:m=[]}=s,D=this._generateRequestData(s);try{const M=yield function(iA,EA){return pA(this,void 0,void 0,function*(){const{groupID:RA,operationType:kA,memberList:xA}=iA,LA={GroupId:RA,CommandType:kA,MemberList:xA};return EA.common.buildAndSendPacket({servcmd:"group_open_avchatroom_http_svc.modify_user_info",data:LA})})}(D,this._core),{MemberList:T=[]}=M||{},{successUserIDList:P,failureUserIDList:W}=this._handleResult(T,m);return{code:0,data:{successUserIDList:P,failureUserIDList:W},successLog:{message:`${this._name}.${n} ok, groupID:${g} markType:${u} enableMark:${E} success:${P.length} fail:${W.length}`}}}catch(M){throw new this._core.helper.ChatError({functionName:n,code:M?.errorCode,message:M?.errorInfo})}})}_generateRequestData(s){const{groupID:n,markType:g,enableMark:u,userIDList:E=[]}=s,m=u===!0?1:2,D=[...E];return D.length>500&&console.warn(`${this._name}._generateRequestData, the length of userIDList cannot exceed 500`),{groupID:n,operationType:m,memberList:D.map(M=>({Member_Account:M,Marks:[g]}))}}_handleResult(s,n){const g=[],u=[];return s.length===n.length?(g.push(...n),{successUserIDList:g,failureUserIDList:u}):(n.forEach(E=>{s.find(m=>m.Member_Account===E)?g.push(E):u.push(E)}),{successUserIDList:g,failureUserIDList:u})}},iR=new class{init(s,n){s.ssoLog.debug("AVChatRoomAction.init"),eR.init(s,n),YT.init(s,n),tR.init(s,n),Om.init(s,n),AR.init(s,n),Pm.init(s,n),_d.init(s)}},oR=new class{constructor(){this._name="LiveHandler"}init(s){this._core=s;const{helper:n,ssoLog:g}=s;n.registerExperimentalAPI("startMessageLongPolling",this),n.registerExperimentalAPI("stopMessageLongPolling",this),g.debug("LiveHandler.init")}startMessageLongPolling(s){const{common:n,utils:{isEmpty:g},OuterConstant:u,ssoLog:E}=this._core,{groupID:m,longPollingKey:D,longPollingSequence:M=1}=s;if(g(D))return E.warn("startMessageLongPolling",`${this._name}.startMessageLongPolling longPollingKey is empty.`),Promise.resolve({});Pg.hasPollingInstance(m)&&this.stopMessageLongPolling({groupID:m});const T=Pg.getJoinedLiveList(),P=n.isUnlimitedAVChatRoom();!P&&T.length>0&&this.stopMessageLongPolling({groupID:T[0].groupID}),E.debug("startMessageLongPolling",`${this._name}.startMessageLongPolling isUnlimited:${P} groupID:${m} longPollingKey:${D} longPollingSequence:${M}`);const W={groupID:m,type:u.GRP_LIVE};return Pg.updateLocalLiveGroup(m,W),this._getLiveHistoryMessages({groupID:m,longPollingKey:D,startSequence:M}),Pg.startMessageLongPolling({group:W,longPollingKey:D,startSequence:M})}stopMessageLongPolling(s){const{groupID:n}=s;return Pg.reset(n),this._core.ssoLog.debug("stopMessageLongPolling",`${this._name}.stopMessageLongPolling ok, groupID:${n}`),Promise.resolve({groupID:n})}_getLiveHistoryMessages(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n}=this._core,{groupID:g}=s;try{const u=yield function(m,D){return pA(this,void 0,void 0,function*(){const{groupID:M,longPollingKey:T,startSequence:P}=m,W={GroupId:M,LongPollingKey:T,PullPreSeq:P};return D.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_huge_group_msg",data:W})})}(s,this._core),{RspMsgList:E=[]}=u||{};n.debug("_getLiveHistoryMessages",`${this._name}._getLiveHistoryMessages ok, groupID:${g} count:${E.length}`),E.length>0&&Pg.handleLiveHistoryMessages(g,E)}catch(u){n.debug("_getLiveHistoryMessages",`${this._name}._getLiveHistoryMessages failed, groupID:${g} info:${u.message}`)}})}},xm=new class{constructor(){this.name="AVChatRoom"}install(s,n){this._core=s,uB.init(s),Pg.init(s,n),iR.init(s,n),oR.init(s);const{notificationCenter:g,InnerEvent:u}=s,{InnerEventSubType:E}=g;g.subscribeInnerEvent(u.MESSAGE_PUSH,E.GROUP_SYSTEM_NOTIFICATION,this._onAVChatRoomSystemNotification,this),g.subscribeInnerEvent(u.LOGOUT,this._reset,this),g.subscribeInnerEvent(u.DESTROY,this._dispose,this)}_onAVChatRoomSystemNotification(s){Pg.onAVChatRoomSystemNotification(s)}_reset(){Pg.reset()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:n}=this._core,{InnerEventSubType:g}=s;s.unSubscribeInnerEvent(n.MESSAGE_PUSH,g.GROUP_SYSTEM_NOTIFICATION,this._onAVChatRoomSystemNotification,this),s.unSubscribeInnerEvent(n.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this)}};const Ag=new class{init(s){this.core=s}},Ym="message",CB="user",hB={OR:"or",AND:"and"},vI=20,VT=20,sR=20,ph={required:!1,rules:["array"],allowEmpty:!0,customValidator:s=>!s||!!(Array.isArray(s)&&s.length<=5)||"keywordList should be an array and length <= 5"},Vm={required:!1,rules:["string"],allowEmpty:!0,customValidator:s=>!s||!![hB.OR,hB.AND].includes(s)||"keywordListMatchType should be OR or AND"},SC={required:!1,rules:["number"],allowEmpty:!0,customValidator:s=>typeof s=="number"&&s>=1&&s<=100||"count must be a number between 1 and 100"},VQ={required:!1,rules:["string"],allowEmpty:!0},nR={required:!1,rules:["array"],allowEmpty:!0,customValidator:s=>{const{OuterConstant:n}=Ag.core;if(!Array.isArray(s))return"groupTypeList should be an array";const g=[n.GRP_PUBLIC,n.GRP_COMMUNITY,n.GRP_WORK,n.GRP_MEETING];let u=!1;for(let E=0;E{const{OuterConstant:n}=Ag.core,g=[n.MSG_TEXT,n.MSG_IMAGE,n.MSG_AUDIO,n.MSG_FILE,n.MSG_VIDEO,n.MSG_LOCATION,n.MSG_CUSTOM,n.MSG_MERGER];let u=!1;for(let E=0;E{const{OuterConstant:n}=Ag.core;return!(!s?.startsWith(n.CONV_C2C)&&!s?.startsWith(n.CONV_GROUP)&&s!==n.CONV_SYSTEM)||"conversationID is invalid"}},Jm=s=>({required:!1,rules:["number"],allowEmpty:!0,customValidator:n=>typeof n=="number"&&n>=0||`${s} should be a number >= 0';`}),TD={required:!1,rules:["string"],allowEmpty:!0,customValidator:s=>{const{OuterConstant:n}=Ag.core;return!![n.GENDER_FEMALE,n.GENDER_MALE].includes(s)||"gender is invalid"}},Hm={searchCloudMessages:{keywordList:ph,keywordListMatchType:Vm,cursor:VQ,senderUserIDList:{required:!1,rules:["array"],allowEmpty:!0,customValidator:s=>!!(Array.isArray(s)&&s.length<=5)||"senderUserIDList should be an array and length <= 5"},messageTypeList:rR,conversationID:aR,timePosition:Jm("timePosition"),timePeriod:Jm("timePeriod")},searchCloudUsers:{keywordList:ph,keywordListMatchType:Vm,cursor:VQ,count:SC,miniBirthday:Jm("miniBirthday"),maxBirthday:Jm("maxBirthday"),gender:TD},searchCloudGroupMembers:{keywordList:ph,keywordListMatchType:Vm,cursor:VQ,count:SC,groupTypeList:nR,groupIDList:{required:!1,rules:["array"],allowEmpty:!0}},searchCloudGroups:{keywordList:ph,keywordListMatchType:Vm,cursor:VQ,count:SC,groupTypeList:nR}},ND={searchCloudMessages:!0,searchCloudUsers:!0,searchCloudGroupMembers:!0,searchCloudGroups:!0};var GD=new class{constructor(){this.name="CloudSearch"}install(s){this._core=s,Ag.init(s),s.helper.registerApi({apiName:"searchCloudMessages",context:this}),s.helper.registerApi({apiName:"searchCloudUsers",context:this}),s.helper.registerApi({apiName:"searchCloudGroupMembers",context:this}),s.helper.registerApi({apiName:"searchCloudGroups",context:this}),s.helper.registerValidateConfig({auth:ND,params:Hm})}searchCloudMessages(s){return pA(this,void 0,void 0,function*(){try{const{OuterConstant:n,helper:g}=this._core,{conversationID:u,timePeriod:E,timePosition:m}=s,D=Do(s,["conversationID","timePeriod","timePosition"]),M=Object.assign({count:100},D);u&&(u.startsWith(n.CONV_C2C)?M.account=u.replace(n.CONV_C2C,""):u.startsWith(n.CONV_GROUP)&&(M.groupID=u.replace(n.CONV_GROUP,""))),this._setTimeRangeParams(M,{timePeriod:E,timePosition:m});const T=yield function(LA){return pA(this,void 0,void 0,function*(){const{count:SA,keywordList:OA,keywordListMatchType:JA,senderUserIDList:ae,messageTypeList:se,endTime:_i,startTime:Ti,cursor:Ft,account:Ni,groupID:cs}=LA,Se={Count:SA,KeywordList:OA,MatchType:JA,SendUserIDList:ae,MsgTypeList:se,EndTime:_i,StartTime:Ti,Cursor:Ft,PeerAccount:Ni,GroupID:cs};return Ag.core.common.buildAndSendPacket({servcmd:"message_search.query",data:Se})})}(M);if(!T)return{code:0,data:{}};const{ErrorCode:P,ErrorInfo:W,TotalCount:iA,Cursor:EA="",ConversationMsgs:RA=[]}=T;if(P!==0)throw{errorCode:P,errorInfo:W};const kA=`keywordList:${s.keywordList} keywordListMatchType:${s.keywordListMatchType} cursor:${s.cursor} res: totalCount:${iA}`;return{code:0,data:{searchResultList:RA.map(LA=>{const{MsgList:SA,Count:OA,GroupID:JA,UserID:ae}=LA,se=JA?`${n.CONV_GROUP}${JA}`:`${n.CONV_C2C}${ae}`;if(this._isSearchingAllConversations(s)&&OA>1)return{conversationID:se,messageCount:OA,messageList:[]};const _i=SA.map(Ti=>g.isEmpty(JA)?function(Ft,Ni){const cs=Ni.OuterConstant.CONV_C2C,Se=Ni.message.messageHelper.parseServerPushMessage(Ft),mt=Ni.message.messageFactory.createMessage(Object.assign(Object.assign({},Se),{conversationType:cs,flow:"in"}));return mt.setElement(Se.elements),mt}(Ti,this._core):function(Ft,Ni){const cs=Ni.OuterConstant.CONV_GROUP,Se=Ni.message.messageHelper.parseServerGroupMessage(Ft),mt=Ni.message.messageFactory.createMessage(Object.assign(Object.assign({},Se),{conversationType:cs,flow:"in"}));return mt.setElement(Se.elements),mt}(Ti,this._core));return{conversationID:se,messageCount:OA,messageList:_i}}),cursor:EA,totalCount:iA},successLog:{message:kA}}}catch(n){const{errorCode:g,errorInfo:u}=n||{};this._handleError({errorCode:g,errorInfo:u,searchType:Ym,functionName:"searchCloudMessages"})}})}searchCloudUsers(s){return pA(this,void 0,void 0,function*(){var n;try{const{keywordListMatchType:g,count:u=VT}=s,E=Do(s,["keywordListMatchType","count"]),m=Object.assign({count:u,keywordListMatchType:g===hB.AND?1:0},E);this._setBirthdayRangeParams(m,s);const D=yield function(kA){return pA(this,void 0,void 0,function*(){const{count:xA,keywordList:LA,keywordListMatchType:SA,miniBirthday:OA,maxBirthday:JA,cursor:ae,gender:se}=kA,_i={Count:xA,Keywords:LA,KeywordMatchType:SA,Cursor:ae,UserBirthStart:OA,UserBirthEnd:JA,Gender:se};return Ag.core.common.buildAndSendPacket({servcmd:"user_search.query",data:_i})})}(m);if(!D)return{error:0,data:{}};const{ErrorCode:M,ErrorInfo:T,TotalCount:P,Cursor:W="",Users:iA=[]}=D;if(M!==0)throw{errorCode:M,errorInfo:T};const EA=`keywordList:${s.keywordList} keywordListMatchType:${s.keywordListMatchType} cursor:${s.cursor} count:${s.count} res: totalCount:${P}`,RA=[];for(let kA=0,xA=iA.length;kA({tag:ae.Tag,value:ae.StrValue})),JA=(n=this._core.user.userProfile)===null||n===void 0?void 0:n.createProfile(LA,OA);RA.push(JA)}return{code:0,data:{searchResultList:RA,cursor:W,totalCount:P},successLog:{message:EA}}}catch(g){const{errorCode:u,errorInfo:E}=g||{};this._handleError({errorCode:u,errorInfo:E,searchType:CB,functionName:"searchCloudUsers"})}})}searchCloudGroupMembers(s){return pA(this,void 0,void 0,function*(){try{const{count:n=sR,keywordListMatchType:g}=s,u=Do(s,["count","keywordListMatchType"]),E=Object.assign({count:n,keywordListMatchType:g===hB.AND?1:0},u),m=yield function(RA){return pA(this,void 0,void 0,function*(){const{count:kA,keywordList:xA,keywordListMatchType:LA,groupTypeList:SA,cursor:OA,groupIDList:JA}=RA,ae={Count:kA,Keywords:xA,KeywordMatchType:LA,Cursor:OA,GroupType:SA,GroupIdList:JA};return Ag.core.common.buildAndSendPacket({servcmd:"group_member_search.query",data:ae})})}(E);if(!m)return{code:0,data:{}};const{ErrorCode:D,ErrorInfo:M,GroupMembers:T=[],Cursor:P,TotalCount:W}=m;if(D!==0)throw{errorCode:D,errorInfo:M};const iA=`keywordList:${s.keywordList} keywordListMatchType:${s.keywordListMatchType} cursor:${s.cursor} count:${s.count} res: totalCount:${W}`,EA=new Map;return T.forEach(RA=>{const{GroupID:kA,GroupName:xA,GroupType:LA,GroupFaceUrl:SA,GroupMemberUserName:OA,GroupMemberUserID:JA,GroupMemberNameCard:ae,GroupMemberAvatar:se=""}=RA,_i={groupID:kA,name:xA,type:LA,avatar:SA},Ti={userID:JA,nick:OA,nameCard:ae,avatar:se};if(EA.has(kA)){const Ft=EA.get(kA);Ft.memberList.push(Ti),EA.set(kA,Ft)}else EA.set(kA,{groupInfo:_i,memberList:[Ti]})}),{code:0,data:{searchResultList:[...EA.values()],cursor:P,totalCount:W},successLog:{message:iA}}}catch(n){const{errorCode:g,errorInfo:u}=n||{};this._handleError({errorCode:g,errorInfo:u,searchType:CB,functionName:"searchCloudGroupMembers"})}})}searchCloudGroups(s){return pA(this,void 0,void 0,function*(){try{const{count:n=vI,keywordListMatchType:g}=s,u=Do(s,["count","keywordListMatchType"]),E=Object.assign({count:n,keywordListMatchType:g===hB.AND?1:0},u),m=yield function(EA){return pA(this,void 0,void 0,function*(){const{count:RA,keywordList:kA,keywordListMatchType:xA,groupTypeList:LA,cursor:SA}=EA,OA={Count:RA,Keywords:kA,KeywordMatchType:xA,Cursor:SA,GroupType:LA};return Ag.core.common.buildAndSendPacket({servcmd:"group_search.query",data:OA})})}(E);if(!m)return{code:0,data:{}};const{ErrorCode:D,ErrorInfo:M,Groups:T,Cursor:P,TotalCount:W}=m;if(D!==0)throw{errorCode:D,errorInfo:M};const iA=`keywordList:${s.keywordList} keywordListMatchType:${s.keywordListMatchType} cursor:${s.cursor} count:${s.count} res: totalCount:${W}`;return{code:0,data:{searchResultList:T?.map(EA=>function(RA){const{GroupFaceUrl:kA,GroupID:xA,GroupIntroduction:LA,GroupMemberNum:SA,GroupName:OA,GroupOwnerTinyID:JA,GroupOwnerUserID:ae,GroupOwnerUserName:se,GroupType:_i,GroupAddOption:Ti,GroupInviteOption:Ft}=RA;return{avatar:kA,groupID:xA,introduction:LA,memberCount:SA,name:OA,ownerTinyID:JA,ownerID:ae,ownerNick:se,type:_i,joinOption:Ti,inviteOption:Ft}}(EA))||[],cursor:P,totalCount:W},successLog:{message:iA}}}catch(n){const{errorCode:g,errorInfo:u}=n||{};this._handleError({errorCode:g,errorInfo:u,searchType:CB,functionName:"searchCloudGroups"})}})}_setTimeRangeParams(s,{timePeriod:n,timePosition:g}){n&&n>0&&(s.startTime=g&&g>0?g-n:this._core.helper.timeManager.getServerTimeSeconds()-n),s.startTime&&s.startTime<0&&(s.startTime=void 0),g&&g>0&&(s.endTime=g)}_handleError({errorCode:s,errorMessage:n,searchType:g}){const{helper:u}=this._core;let E=s;throw s===60020?E="SearchUnable":g!==Ym&&s===27003?E="SearchParamsError":g!==Ym&&s===60018&&(E="SearchOverLimit"),new u.ChatError({code:E,message:n})}_isSearchingAllConversations(s){return this._core.helper.isEmpty(s.conversationID)}_setBirthdayRangeParams(s,n){const{miniBirthday:g,maxBirthday:u}=n;g!==void 0&&(s.miniBirthday=g,u===void 0&&(s.maxBirthday=4294967295)),u!==void 0&&(s.maxBirthday=u)}};function mh(s,n){return Math.round(Number(s)*Math.pow(10,n))/Math.pow(10,n)}const gR="qualityStat",bD="im-ssolog-quality-stat";var kD;(function(s){s[s.ONLINE=8]="ONLINE"})(kD||(kD={}));const qm="networkRTT",fh="messageE2EDelay",BB="sendMessageC2C",yh="sendMessageGroup",Dh="sendMessageGroupAV",QB="sendMessageRichMedia",pB="cosUpload",MC="messageReceivedGroup",JQ="messageReceivedGroupAVPush",HQ="messageReceivedGroupAVPull",JT={[qm]:2,[fh]:3,[BB]:4,[yh]:5,[Dh]:6,[QB]:7,[MC]:8,[JQ]:9,[HQ]:10,[pB]:11},cR=[BB,yh,Dh,QB,pB],Sh=[MC,JQ,HQ],mB=[qm,fh,BB,yh,Dh,QB,pB,MC,JQ,HQ],LD={ERR_SVR_COMM_SENSITIVE_TEXT:80001,ERR_SVR_COMM_BODY_SIZE_LIMIT:80002,OPEN_SERVICE_OVERLOAD_ERROR:60022,ERR_SVR_MSG_PKG_PARSE_FAILED:20001,ERR_SVR_MSG_INTERNAL_AUTH_FAILED:20002,ERR_SVR_MSG_INVALID_ID:20003,ERR_SVR_MSG_PUSH_DENY:20006,ERR_SVR_MSG_IN_PEER_BLACKLIST:20007,ERR_SVR_MSG_BOTH_NOT_FRIEND:20009,ERR_SVR_MSG_NOT_PEER_FRIEND:20010,ERR_SVR_MSG_NOT_SELF_FRIEND:20011,ERR_SVR_MSG_SHUTUP_DENY:20012,ERR_SVR_GROUP_INVALID_PARAMETERS:10004,ERR_SVR_GROUP_PERMISSION_DENY:10007,ERR_SVR_GROUP_NOT_FOUND:10010,ERR_SVR_GROUP_INVALID_GROUPID:10015,ERR_SVR_GROUP_REJECT_FROM_THIRDPARTY:10016,ERR_SVR_GROUP_SHUTUP_DENY:10017,MSG_SEND_FAIL:2100,OVER_FREQUENCY_LIMIT:2996},Km="quality_stat";var qQ=new class{constructor(){this._messageStatsMap=new Map,this._userSideErrorCodes=new Set(Object.values(LD))}init(s){this._core=s,Object.values(cR).forEach(n=>{this._messageStatsMap.set(n,{totalCount:0,successCount:0,failedCountOfUserSide:0,costSum:0,costCount:0,fileSizeSum:0})})}dispatchSendStats(s){const{name:n,message:g,error:u,startTs:E}=s,{SEND_MESSAGE_STAT:m}=this._core.constants;switch(n){case m.TOTAL_COUNT:this._handleTotalCount(g);break;case m.SUCCESS_COUNT:this._handleSuccessCount(g);break;case m.FAILED_COUNT:this._handleFailedCount(g,u);break;case m.SEND_COST:this._handleSendCost(g,E)}}getStatResult(s){const n=this._messageStatsMap.get(s);if(!n||n.totalCount===0)return null;const{totalCount:g,successCount:u,failedCountOfUserSide:E}=n,m=mh(u/g*100,2),D=u+E,M=mh(D/g*100,2),T=this._calcAverageValue(n,s);return this._resetStat(s),{total_count:g,success_count_business:u,percent_business:m,success_count_platform:D,percent_platform:M,average_value:T}}_handleTotalCount(s){const n=this._getSendMessageSpecifiedKey(s),g=n&&this._messageStatsMap.get(n);g&&g.totalCount++}_handleSuccessCount(s){const n=this._getSendMessageSpecifiedKey(s),g=n&&this._messageStatsMap.get(n);g&&g.successCount++}_handleFailedCount(s,n){var g;const u=(g=n?.code)!==null&&g!==void 0?g:n?.errorCode;if(this._isUserSideError(u)){const E=this._getSendMessageSpecifiedKey(s),m=E&&this._messageStatsMap.get(E);m&&m.failedCountOfUserSide++}}_handleSendCost(s,n){const g=this._getSendMessageSpecifiedKey(s),u=g&&this._messageStatsMap.get(g);u&&(u.costSum+=Date.now()-n,u.costCount++)}_isUserSideError(s){return this._userSideErrorCodes.has(s)||s>=120001&&s<=13e4||s>=10100&&s<=10200}_getSendMessageSpecifiedKey(s){const{MSG_IMAGE:n,MSG_AUDIO:g,MSG_VIDEO:u,MSG_FILE:E,CONV_C2C:m,CONV_GROUP:D,GRP_AVCHATROOM:M}=this._core.OuterConstant;if([n,g,u,E].includes(s.type))return QB;if(s.conversationType===m)return BB;if(s.conversationType===D){const{groupStore:T}=this._core.appStore,P=T.getGroup(s.to);if(!P)return;const{type:W}=P;return W===M?Dh:yh}}_calcAverageValue(s,n){return s.costCount===0?0:Math.round(n===pB?1e3*s.fileSizeSum/s.costSum:s.costSum/s.costCount)}_resetStat(s){const n=this._messageStatsMap.get(s);n&&(n.totalCount=0,n.successCount=0,n.failedCountOfUserSide=0,n.costSum=0,n.costCount=0,n.fileSizeSum=0)}},KQ=new class{constructor(){this._lastCycleStats=new Map,this._currentCycleStats=new Map}init(s){this._core=s;const{OuterEvent:n,notificationCenter:g}=s;this._initStatsMap(),g.subscribeOuterEvent(n.MESSAGE_RECEIVED,this._onMessageReceived,this)}addMessageSequence(s){const n=this._getReceivedMessageSpecifiedKey(s),{utils:{isUndefined:g},OuterConstant:{CONV_GROUP:u},ssoLog:E}=this._core;if(g(n)||!this._currentCycleStats.has(n))return void E.debug("addMessageSequence",`${gR}.addMessageSequence invalid key:${n}`);const{conversationID:m,sequence:D}=s,M=m.replace(u,""),T=this._lastCycleStats.get(n);if(T.size===0||!T.has(M))return void this._addToCurrentCycle(n,M,D);const P=T.get(M);D>P.minSeq&&D{const{sortedSequences:m,minSeq:D,maxSeq:M}=E;m.length>0&&(u+=m.length,g+=M-D+1)}),g===0?null:(this._transferCycleDataOptimized(s),{total_count:g,success_count_business:u,percent_business:mh(u/g*100,2)})}reset(){this._lastCycleStats.clear(),this._currentCycleStats.clear()}dispose(){const{notificationCenter:s,OuterEvent:{MESSAGE_RECEIVED:n}}=this._core;s.unSubscribeOuterEvent(n,this._onMessageReceived,this),this.reset()}_initStatsMap(){Object.values(Sh).forEach(s=>{this._lastCycleStats.set(s,new Map),this._currentCycleStats.set(s,new Map)})}_onMessageReceived(s){const{data:n=[]}=s;n.forEach(g=>{this.addMessageSequence(g)})}_transferCycleDataOptimized(s){const n=this._currentCycleStats.get(s);if(!n)return;const g=new Map;n.forEach((u,E)=>{const m=u.dirty?[...u.sortedSequences].sort((D,M)=>D-M):u.sortedSequences;g.set(E,{sortedSequences:m,minSeq:u.minSeq,maxSeq:u.maxSeq,dirty:!1})}),this._lastCycleStats.set(s,g),this._currentCycleStats.set(s,new Map)}_getReceivedMessageSpecifiedKey(s){const{OuterConstant:{CONV_GROUP:n,GRP_AVCHATROOM:g}}=this._core;if(s.conversationType===n&&s?._onlineOnlyFlag!==!0){const{groupStore:u}=this._core.appStore,E=u.getGroup(s.to);if(!E)return null;const{type:m}=E;return m===g?HQ:MC}}_insertToLastCycle(s,n){n.dirty&&(n.sortedSequences.sort((u,E)=>u-E),n.dirty=!1);const g=this._findInsertPos(n.sortedSequences,s);n.sortedSequences.splice(g,0,s),n.minSeq=Math.min(n.minSeq,s),n.maxSeq=Math.max(n.maxSeq,s)}_findInsertPos(s,n){let g=0,u=s.length-1;for(;g<=u;){const E=Math.floor((g+u)/2);if(s[E]===n)return E;s[E]0&&(this._totalDelay+=g,this._totalCount++,g<=1?this._countLessThan1s++:g<=3&&this._countLessThan3s++)}getStatResult(){if(this._totalCount===0)return null;const s={total_count:this._totalCount,success_count_business:this._countLessThan1s,success_count_platform:this._countLessThan3s,percent_business:this._calculatePercentage(this._countLessThan1s,this._totalCount),percent_platform:this._calculatePercentage(this._countLessThan3s,this._totalCount),average_value:this._calculateAverageDelay(this._totalCount)};return this.reset(),s}reset(){this._totalDelay=0,this._totalCount=0,this._countLessThan1s=0,this._countLessThan3s=0}dispose(){const{notificationCenter:s,OuterEvent:{MESSAGE_RECEIVED:n}}=this._core;s.unSubscribeOuterEvent(n,this._onMessageReceived,this),this.reset()}_onMessageReceived(s){const{data:n=[]}=s,{OuterConstant:{MSG_GRP_TIP:g,MSG_GRP_SYS_NOTICE:u}}=this._core,E=[g,u];n.forEach(m=>{!E.includes(m.type)&&m.clientTime>0&&this.addMessageDelay(m.clientTime)})}_calculateAverageDelay(s){return s===0?0:mh(this._totalDelay/s,1)}_calculatePercentage(s,n){return mh(s/n*100,2)}},lR=new class{init(s){this.core=s}},HT=new class{constructor(){this.name="MessageQualityStat",this._reportIndex=0,this._wholePeriod=!1,this._pendingReports=[],this._failedLogsCache=new Map}install(s){this._core=s;const{helper:n,notificationCenter:g,InnerEvent:{QUALITY_STAT:u,LOGOUT:E,DESTROY:m},constants:{WORKFLOW_NAME:D,WORKFLOW_STEP:M}}=s;lR.init(s),qQ.init(s),KQ.init(s),jQ.init(s),n.registerWorkflowStep(D.SYNC_SERVER_INFO_AFTER_LOGIN,M.QUALITY_REPORT,this.handleLoginSuccess,this),g.subscribeInnerEvent(u,this._handleQualityStat,this),g.subscribeInnerEvent(E,this._reset,this),g.subscribeInnerEvent(m,this._dispose,this)}handleLoginSuccess(){const{store:s,helper:n,utils:{isUndefined:g}}=this._core,u=s.get("cloudConfig")||{},{q_rpt_interval:E}=u,m=g(E)?12e4:Number(E);n.taskScheduler.addTask({id:Km,intervalMs:m,callback:this.report,context:this})}report(){this._wholePeriod=!0;const s=[...mB.map(n=>{const g=this._buildQualityReportItem(n);return g?Object.assign(Object.assign({},g),{report_index:this._reportIndex,whole_period:this._wholePeriod}):null}).filter(Boolean),...this._pendingReports];this._pendingReports=[],this._needSkipReport()||this._uploadQualityReports(s)}_handleQualityStat(s){const{constants:{QUALITY_METRICS:n}}=this._core,{label:g,data:u}=s;g===n.MESSAGE_SEND_SUCCESS_RATE&&qQ.dispatchSendStats(u)}_needSkipReport(){return this._isSDKAppIDInBlacklist()&&!this._isTinyIDInWhitelist()}_isSDKAppIDInBlacklist(){const{store:s,utils:n}=this._core,g=s.get("cloudConfig")||{},u=s.get("instance")||{},{sdkAppId:E}=u,{q_rpt_sdkappid_bl:m=[]}=g;if(!n.isEmpty(m))return m.split(",").map(D=>Number(D)).includes(E)}_isTinyIDInWhitelist(){const{store:s,utils:n}=this._core,g=s.get("cloudConfig")||{},u=s.get("login")||{},E=Number(u.tinyID),{q_rpt_tinyid_wl:m=[]}=g;if(!n.isEmpty(m))return m.split(",").includes(E)}_buildQualityReportItem(s){const n=this._getStatResultByKey(s);if(n===null)return null;const g={quality_type:JT[s],timestamp:Date.now(),network_type:kD.ONLINE,extension:""};return Object.assign(Object.assign({},g),n)}_getStatResultByKey(s){switch(s){case fh:return jQ.getStatResult();case BB:case yh:case Dh:case QB:case pB:return qQ.getStatResult(s);case MC:case JQ:case HQ:return KQ.getStatResult(s);default:return null}}_uploadQualityReports(s){return pA(this,void 0,void 0,function*(){try{const n={header:this._core.common.getCommonHead(),quality:s};yield function(g){const{common:u,channel:E}=lR.core,m="imopenstat.tim_web_report_v2",D=u.generateSSOLogProtocolData({servcmd:m,data:g}),M=`${D.head.seq}${m}`;return E.sendPacket(D,{requestId:M})}(n),this._reportIndex++,this._wholePeriod=!1}catch(n){console.warn("doReport failed. error:",n),this._pendingReports=this._pendingReports.concat(s),this._cacheFailedLogs()}})}_cacheFailedLogs(){const s=this._pendingReports,n=`${gR}._cacheFailedLogs`;let g=[...this._failedLogsCache.get(bD)||[],...s];g.length>10&&(g=g.slice(g.length-10),console.log(`${n} logs overflow, keeping last 10 items`)),this._failedLogsCache.set(bD,g),console.log(`${n} count: ${g.length}`),this._pendingReports=[]}_reset(){const{helper:s}=this._core;s.taskScheduler.removeTask(Km)}_dispose(){const{notificationCenter:s,InnerEvent:{QUALITY_STAT:n,LOGOUT:g,DESTROY:u}}=this._core;s.unSubscribeInnerEvent(n,this._handleQualityStat,this),s.unSubscribeInnerEvent(g,this._reset,this),s.unSubscribeInnerEvent(u,this._dispose,this),this._reset(),jQ.dispose(),KQ.dispose()}};const ll=new class{init(s){this.core=s}};function IR(s){return pA(this,void 0,void 0,function*(){var n;const{message:g,user:u,appStore:E,constants:{OuterConstant:m}}=ll.core,D=E.conversationStore.getConversationMap();if(D.has(s)){const T=(n=D.get(s))===null||n===void 0?void 0:n.userProfile;if(T&&s.startsWith(m.CONV_C2C)){const{avatar:P,nick:W}=T;ll.core.message.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:s,latestAvatar:P,latestNick:W,isSentByMe:!1})}}const{data:M}=(yield u.userProfile.getMyProfile())||{};if(M){const{avatar:T,nick:P}=M;g.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:s,latestAvatar:T,latestNick:P,isSentByMe:!0})}})}function uR(s){return pA(this,void 0,void 0,function*(){const n=s.map(g=>g.revoker);try{const g=yield function(u){return pA(this,void 0,void 0,function*(){var E,m;const D=yield(E=ll.core.user.userProfile)===null||E===void 0?void 0:E.getUserProfile({userIDList:u});return D?.data?(m=D.data)===null||m===void 0?void 0:m.reduce((M,{userID:T,nick:P,avatar:W})=>(M[T]={nick:P||"",avatar:W||""},M),{}):null})}(n);g&&s.forEach(u=>{const{revoker:E}=u;g[E]&&(u.revokerInfo.nick=g[E].nick||"",u.revokerInfo.avatar=g[E].avatar||"",u.revokerInfo.userID=E)})}catch(g){console.debug(g)}})}const UD=1,ER=2,Mh=20,WQ=2500,dR=1,vh=300;function zQ(s){return pA(this,void 0,void 0,function*(){var n,g;const{appStore:u,utils:{isEmpty:E},common:{getCurrentUserID:m},notificationCenter:D,OuterEvent:M,OuterConstant:{CONV_C2C:T}}=ll.core,{messageList:P,conversationID:W}=s,iA=u.conversationStore.getConversationMap();let EA=(n=iA.get(W))===null||n===void 0?void 0:n.peerReadTime;if(!EA){const kA=W.replace(T,""),xA=yield function(LA){return pA(this,void 0,void 0,function*(){const SA={To_Account:LA};return ll.core.common.buildAndSendPacket({servcmd:"openim.get_peer_read_time",data:SA})})}([kA]);if(xA){const{ReadTime:LA}=xA;EA=LA?.[0],iA.has(W)&&(iA.get(W).peerReadTime=EA)}}if(iA.has(W)){const kA=(g=iA.get(W))===null||g===void 0?void 0:g.lastMessage;E(kA)||kA.fromAccount===m()&&kA.lastTime<=EA&&!kA.isPeerRead&&(kA.isPeerRead=!0,u.conversationStore.updateConversation(W,{lastMessage:kA}))}const RA=[];P.forEach(kA=>{kA.time<=EA&&!kA.isPeerRead&&kA.flow==="out"&&(kA.isPeerRead=!0,RA.push(kA))}),RA.length>0&&D.emitOuterEvent(M.MESSAGE_READ_BY_PEER,{name:M.MESSAGE_READ_BY_PEER,data:RA})})}var CR=new class{init(s){this._core=s,s.helper.registerApi({apiName:"getMessageList",context:this}),s.helper.registerApi({apiName:"getMessageListHopping",context:this}),s.helper.registerApi({apiName:"clearHistoryMessage",context:this})}getMessageList(s){return pA(this,void 0,void 0,function*(){try{const{message:n,OuterConstant:{Direction:g,CONV_C2C:u,CONV_GROUP:E},InnerEvent:{HISTORY_MESSAGE_FETCHED:m},notificationCenter:D}=this._core,{conversationID:M,nextReqMessageID:T}=s,P=Mh;if(M==="@TIM#SYSTEM")return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}};const W=this._getAvailableLocalMessagesCount({conversationID:M,nextReqMessageID:T});if(this._needFetchHistoryMessageList({conversationID:M,availableLocalMessagesCount:W,targetCount:P})){let iA=null;if(M.startsWith(E)?iA=yield n.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:M,sequence:Number(T),count:P,direction:g.FORWARD,shouldMarkCompleted:!0}):M.startsWith(u)&&(iA=yield n.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:M,messageID:T,count:P,direction:g.FORWARD,shouldMarkCompleted:!0})),iA){const{nextReqMessageIDFromServer:EA,hasNoMoreHistoryMessage:RA,messageList:kA}=iA,xA=n.messageDataHandler.prependLocalMessageList({messageList:kA,conversationID:M});(function(ae){const{appStore:se,message:_i,OuterConstant:Ti}=ll.core,Ft=se.conversationStore.getConversation(ae),Ni=_i.messageDataHandler.getLocalMessageList(ae);if(!Ft||Ni.length===0||ae===Ti.CONV_SYSTEM)return;const cs=[];for(let mt=0;mtUA.isRevoked).length;Se=cs.length-Ft.unreadCount-mt}else Se=cs.length-Ft.unreadCount;for(let mt=0;mtae.isRevoked);yield uR(SA),D.emitInnerEvent(m,xA);const OA={nextReqMessageID:RA?"":String(EA),messageList:LA,isCompleted:RA},JA=LA.map(ae=>ae.sequence);return{code:0,data:OA,successLog:{message:`conversationID: ${M} nextReqMessageID: ${T} availableLocalMessagesCount: ${W} sequenceList: ${JSON.stringify(JA)}`}}}return{code:0,data:{messageList:[],isCompleted:!1,nextReqMessageID:""}}}return{code:0,data:yield this._getMessageListFromMemory({conversationID:M,nextReqMessageID:T,count:P}),successLog:{message:`conversationID: ${M} nextReqMessageID: ${T} availableLocalMessagesCount: ${W}}`}}}catch(n){const{code:g,message:u}=n||{};throw new this._core.helper.ChatError({code:g,message:u,moreMessage:`options: ${this._core.utils.safeStringify(s)}`})}})}getMessageListHopping(s){return pA(this,void 0,void 0,function*(){var n,g;const{OuterConstant:{Direction:u,CONV_C2C:E,CONV_GROUP:m},utils:{safeStringify:D}}=this._core,{conversationID:M,sequence:T,time:P,direction:W=u.FORWARD}=s,{utils:{isEmpty:iA},message:EA,notificationCenter:RA,InnerEvent:{HISTORY_MESSAGE_FETCHED:kA}}=this._core;if(![u.BACKWARD,u.FORWARD].includes(W))throw new this._core.helper.ChatError({message:"direction must be 0 or 1",moreMessage:`options: ${D(s)}`});let{count:xA=Mh}=s;xA=xA>Mh?Mh:xA;let LA=null;if(M.startsWith(m)){if(LA=yield EA.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:M,sequence:T,count:xA,direction:W}),LA){const{nextReqMessageIDFromServer:SA,hasNoMoreHistoryMessage:OA,messageList:JA,invisibleSequenceList:ae}=LA;if(this._core.message.messageDataHandler.storeSparseMessageList(JA),RA.emitInnerEvent(kA,JA),W===u.FORWARD){const se=OA&&SA<1;return{code:0,data:{messageList:JA,isCompleted:se,nextMessageSeq:se?"":SA}}}if(W===u.BACKWARD){if(iA(JA)&&iA(ae))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};const se=((n=JA?.[JA.length-1])===null||n===void 0?void 0:n.sequence)||0,_i=((g=ae?.[ae.length-1])===null||g===void 0?void 0:g.sequence)||0;return{code:0,data:{messageList:JA.filter(Ti=>Ti.sequence>=T),isCompleted:!OA,nextMessageSeq:OA?Math.max(se,_i)+1:""}}}return{code:0,data:LA}}}else if(M.startsWith(E)&&(LA=yield EA.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:M,count:xA+1,time:P,direction:W}),LA)){const{messageList:SA,lastMessageTime:OA,hasNoMoreHistoryMessage:JA}=LA;return RA.emitInnerEvent(kA,SA),JA||(W===u.FORWARD?SA.shift():SA.pop()),EA.messageDataHandler.storeSparseMessageList(SA),yield zQ({messageList:SA,conversationID:M}),{code:0,data:{messageList:SA,isCompleted:JA,nextMessageTime:JA?"":OA}}}})}clearHistoryMessage(s){return pA(this,void 0,void 0,function*(){var n;const{appStore:g,common:{ChatError:u,getCurrentUserID:E},OuterConstant:{CONV_C2C:m,CONV_GROUP:D},apiMap:M,message:T}=this._core,P=g.conversationStore.getConversation(s);if(!P)throw new u({code:WQ});const W={fromAccount:E()},{type:iA}=P;iA===m?(W.type=UD,W.toAccount=s.replace(m,"")):iA===D&&(W.type=ER,W.toGroupID=s.replace(D,""));try{return yield(n=M?.setMessageRead)===null||n===void 0?void 0:n.call(M,{conversationID:s}),(yield function(RA){return pA(this,void 0,void 0,function*(){const{fromAccount:kA,type:xA,toAccount:LA,toGroupID:SA}=RA,OA={From_Account:kA,Type:xA,To_Account:LA,ToGroupid:SA};return ll.core.common.buildAndSendPacket({servcmd:"recentcontact.clear_msg",data:OA})})}(W))&&(T.messageDataHandler.deleteConversationMessageList(s),T.messageHistory.completedHistoryConversations.delete(s),T.messageHistory.clearHistoryMessageListFetchAnchors(s),this._updateConversationLastMessage(s)),{code:0,data:{conversationID:s},successLog:{message:`convID:${s}`}}}catch(EA){const{errorCode:RA}=EA;throw new this._core.helper.ChatError({functionName:"clearHistoryMessage",code:RA,moreMessage:`convID:${s}`})}})}_updateConversationLastMessage(s){const{appStore:n}=this._core;n.conversationStore.updateConversation(s,{lastMessage:this._generateLastMessage()},{needSort:!0})}_getAvailableLocalMessagesCount({conversationID:s,nextReqMessageID:n}){const{OuterConstant:{CONV_C2C:g,CONV_GROUP:u}}=this._core,E=this._core.message.messageDataHandler.getLocalMessageList(s),{length:m}=E;if(!n)return m;let D=-1;return s?.startsWith(g)?D=E.findIndex(M=>M.ID===n):s?.startsWith(u)&&(D=E.findIndex(M=>n.includes("-")?M.ID===n:String(M.sequence)===n)),D===-1?0:D}_needFetchHistoryMessageList({conversationID:s,availableLocalMessagesCount:n,targetCount:g}){const{message:u}=this._core;return nn.startsWith(E)?EA.ID===g:String(EA.sequence)===g),W=iA>u?iA-u:0,T=iA):W=M>u?M-u:0,P.messageList=D.slice(W,iA),P.isCompleted=T<=u&&m.messageHistory.completedHistoryConversations.has(n),P.isCompleted?P.nextReqMessageID="":P.nextReqMessageID=this._generateNextReqMessageID({conversationID:n,targetIndex:W}),n.startsWith(E)&&(yield IR(n),yield zQ({messageList:P.messageList,conversationID:n})),P})}_generateNextReqMessageID({conversationID:s,targetIndex:n}){const g=this._core.message.messageDataHandler.getLocalMessageList(s);return s.startsWith("C2C")?g[n].ID:String(g[n].sequence)}_generateLastMessage(){return{lastTime:0,lastSequence:0,fromAccount:"",messageForShow:"",payload:null,type:"",isRevoked:!1,cloudCustomData:"",onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:!1,revoker:null}}},fB=new class{constructor(){this._lastMessageSequenceMapOnDisconnect=new Map,this._lastMessageTimeMapOnDisconnect=new Map}init(s){this._core=s;const{common:{workflowManager:n},constants:{WORKFLOW_NAME:g,WORKFLOW_STEP:u,InnerEvent:E}}=s;n.registerWorkflowStep(g.SYNC_SERVER_INFO_AFTER_RE_ONLINE,u.HISTORY_MESSAGE_RECOVER,this._syncGroupOfflineMessage,this),n.registerWorkflowStep(g.SYNC_SERVER_INFO_AFTER_RE_ONLINE,u.C2C_HISTORY_MESSAGE_RECOVER,this._syncC2COfflineMessage,this),s.notificationCenter.subscribeInnerEvent(E.SOCKET_DISCONNECTED,this._updateLastMessageSequenceMapOnDisconnect,this)}_syncGroupOfflineMessage(s){const{conversationList:n}=s?.result||{},{OuterConstant:g,utils:{isArray:u}}=this._core;if(u(n)){const E=n.filter(m=>m.type===g.CONV_GROUP&&m.groupProfile.type!==g.GRP_AVCHATROOM);return this._recoverGroupHistoryMessage(E)}}_recoverGroupHistoryMessage(s){return pA(this,void 0,void 0,function*(){const{OuterConstant:n}=this._core,g=[],u=[];return yield Promise.all(s?.map(E=>pA(this,void 0,void 0,function*(){const{groupProfile:{groupID:m}={},lastMessage:{lastSequence:D}={}}=E,M=`${n.CONV_GROUP}${m}`;let T=this._getLocalLastMessageSequence(M);this._shouldRecoverHistory({localLastMessageSequence:T,serverLastMessageSequence:D})&&(yield this._recoverGroupHistoryForConversation({conversationID:M,localLastMessageSequence:T,serverLastMessageSequence:D,groupTipList:u})),g.push(M.replace(n.CONV_GROUP,""))}))),{recoverRevokeNoticeGroupIDList:g,groupTipList:u}})}_recoverGroupHistoryForConversation(s){return pA(this,arguments,void 0,function*({conversationID:n,localLastMessageSequence:g,serverLastMessageSequence:u,groupTipList:E}){try{const{utils:{isArray:m,isObject:D,isEmpty:M},OuterEvent:T,OuterConstant:P,notificationCenter:W,message:iA,appStore:EA,common:{getMessagePreviewText:RA,buildLastMessage:kA}}=this._core,xA=u-g,LA=Math.min(20,xA),SA={},OA=yield iA.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:n,sequence:g+LA,direction:P.Direction.FORWARD,count:LA}),{nextReqMessageIDFromServer:JA,hasNoMoreHistoryMessage:ae,messageList:se,serverGroupTipList:_i}=OA;m(_i)&&E.push(..._i);const Ti=ae&&JA<0,Ft=[];if(m(se)&&(se.forEach(Ni=>{iA.messageReceiver.groupMessageReceiver.updateMessageProfile(Ni),Ni.from===P.CONV_SYSTEM&&(Ni.isSystemMessage=!1),iA.messageDataHandler.storeConversationMessage(Ni)&&!M(Ni.payload)&&(Ft.push(Ni),Ni._isExcludedFromLastMessage||(SA.lastMessage=kA(Ni)))}),Ft.length>0&&W.emitOuterEvent(T.MESSAGE_RECEIVED,{name:T.MESSAGE_RECEIVED,data:Ft})),!Ti&&se.length>0){const Ni=se[se.length-1].sequence;yield this._recoverGroupHistoryForConversation({conversationID:n,localLastMessageSequence:Ni,serverLastMessageSequence:u,groupTipList:E})}D(SA.lastMessage)&&(SA.lastMessage.messageForShow=RA(SA.lastMessage.type,SA.lastMessage.payload),EA.conversationStore.updateConversation(n,SA))}catch(m){this._core.ssoLog.error("_recoverGroupHistoryForConversation",`Recovery failed for conversation:${n}`,{error:m})}})}_updateLastMessageSequenceMapOnDisconnect(){const{message:s}=this._core,n=s.messageDataHandler.getContinuousMessagesByConversation();for(const[g,u]of n){const E=Array.from(u.values());if(E?.length>0){const m=E[E.length-1];g.startsWith("C2C")?this._lastMessageTimeMapOnDisconnect.set(g,m.time):g.startsWith("GROUP")&&this._lastMessageSequenceMapOnDisconnect.set(g,m.sequence)}}}_getLocalLastMessageSequence(s){const{message:n}=this._core;if(this._lastMessageSequenceMapOnDisconnect.has(s))return this._lastMessageSequenceMapOnDisconnect.get(s);const g=n.messageDataHandler.getLocalMessageList(s),u=g[g.length-1];return u?.sequence}_shouldRecoverHistory(s){const{localLastMessageSequence:n,serverLastMessageSequence:g}=s;if(typeof n!="number"||typeof g!="number")return!1;const u=g-n;return g!==0&&n>0&&u>=dR&&u{m.type===g.CONV_C2C&&E.push(m)}),this._recoverC2CHistoryMessage(E)}}_recoverC2CHistoryMessage(s){return pA(this,void 0,void 0,function*(){yield Promise.all(s?.map(n=>pA(this,void 0,void 0,function*(){const{conversationID:g,lastMessage:{lastTime:u}={}}=n,E=this._getLocalLastMessageTime(g);this._shouldRecoverC2CHistory({localLastMessageTime:E,serverLastMessageTime:u})&&(yield this._recoverHistoryForC2CConversation({conversationID:g,localLastMessageTime:E,serverLastMessageTime:u}))})))})}_shouldRecoverC2CHistory(s){const{localLastMessageTime:n,serverLastMessageTime:g}=s,u=g-n;return n>0&&u>=1&&u<=600}_recoverHistoryForC2CConversation(s){return pA(this,void 0,void 0,function*(){var n;const{conversationID:g,localLastMessageTime:u,serverLastMessageTime:E}=s,{utils:{isArray:m,isObject:D,isEmpty:M,safeStringify:T},OuterEvent:P,OuterConstant:W,notificationCenter:iA,message:EA,appStore:RA,common:{getMessagePreviewText:kA,buildLastMessage:xA}}=this._core;try{const LA={},SA=yield EA.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:g,direction:W.Direction.BACKWARD,time:u,count:20});if(M(SA))return;const{hasNoMoreHistoryMessage:OA,messageList:JA}=SA,ae=[];m(JA)&&(JA.forEach(_i=>{EA.messageDataHandler.storeConversationMessage(_i)&&!M(_i.payload)&&(ae.push(_i),_i._isExcludedFromLastMessage||(LA.lastMessage=xA(_i)))}),ae.length>0&&iA.emitOuterEvent(P.MESSAGE_RECEIVED,{name:P.MESSAGE_RECEIVED,data:ae}));const se=(n=JA[JA.length-1])===null||n===void 0?void 0:n.time;!OA&&se>E&&(yield this._recoverHistoryForC2CConversation({conversationID:g,localLastMessageTime:se,serverLastMessageTime:E})),D(LA.lastMessage)&&(LA.lastMessage.messageForShow=kA(LA.lastMessage.type,LA.lastMessage.payload),RA.conversationStore.updateConversation(g,LA))}catch(LA){this._core.ssoLog.error("_recoverHistoryForC2CConversation",`Recovery failed for conversation:${g} error: ${T(LA)}`)}})}_getLocalLastMessageTime(s){const{message:n}=this._core;if(this._lastMessageTimeMapOnDisconnect.has(s))return this._lastMessageTimeMapOnDisconnect.get(s);const g=n.messageDataHandler.getLocalMessageList(s),u=g[g.length-1];return u?.time}reset(){this._lastMessageSequenceMapOnDisconnect.clear(),this._lastMessageTimeMapOnDisconnect.clear()}dispose(){this.reset()}},yB=new class{constructor(){this.name="HistoryMessage"}install(s){this._core=s,ll.init(s),CR.init(s),fB.init(s),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.LOGOUT,this._reset,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this.dispose,this)}dispose(){const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(n.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(n.DESTROY,this.dispose,this),fB.dispose()}_reset(){fB.reset()}},FD=new class{init(s){this.core=s}},vC=new class{constructor(){this._reportedAtomicStoreIDs=new Set}init(s){const{helper:{registerExperimentalAPI:n}}=s;this._core=s,n("reportModalView",this),n("reportTUIFeatureUsage",this),n("reportRoomEngineEvent",this)}reportModalView(s){const{ssoLog:n,utils:{safeStringify:g,isString:u}}=this._core;try{if(!u(s))throw new Error("reportModalView data is not a string");n.createSSOLogData({method:"reportModalView",message:s,eventType:30}).end(!0)}catch(E){n.debug(`reportModalView Report failed: ${g(E)}`)}}reportTUIFeatureUsage(s){const{ssoLog:n,utils:{safeStringify:g,isEmpty:u}}=this._core,{atomicStoreID:E}=s;try{u(E)||this._reportedAtomicStoreIDs.has(E)||(this._core.ssoLog.info("reportTUIFeatureUsage",`atomicStoreID: ${s.atomicStoreID}`,{method:"reportTUIFeatureUsage",eventType:31,code:E}),this._reportedAtomicStoreIDs.add(E))}catch(m){n.debug(`reportTUIFeatureUsage Report failed: ${g(m)}`)}}reportRoomEngineEvent(s){const{utils:{safeStringify:n},ssoLog:g}=this._core;try{g.debug(`reportRoomEngineEvent Report: ${n(s)}`);const{eventId:u,eventCode:E,eventResult:m,eventMessage:D,moreMessage:M,extensionMessage:T}=s;g.createSSOLogData({method:T,code:u,message:D,eventType:30,costTime:E,uiPlatform:m,moreMessage:M}).end(!0)}catch(u){g.debug(`reportRoomEngineEvent Report failed: ${n(u)}`)}}reset(){this._reportedAtomicStoreIDs.clear()}dispose(){this.reset()}},ZQ=new class{constructor(){this.name="DataReport"}install(s){this._core=s;const{notificationCenter:n,InnerEvent:{LOGOUT:g,DESTROY:u}}=s;FD.init(s),vC.init(s),n.subscribeInnerEvent(g,this._reset,this),n.subscribeInnerEvent(u,this._dispose,this)}_reset(){vC.reset()}_dispose(){const{notificationCenter:s,InnerEvent:{LOGOUT:n,DESTROY:g}}=this._core;s.unSubscribeInnerEvent(n,this._reset,this),s.unSubscribeInnerEvent(g,this._dispose,this),vC.dispose()}};let jm=nr.STANDARD,DB=[];jm=nr.STANDARD,DB=[ah,IC,uC,EC,Rc,HT,yB,ZQ,PE,vi,jn,UT,xm,GD,XI];function SB(s,n){const{operationType:g,memberInfoList:u,operatorInfo:E}=s||{};let m={};if(Rs(u)?Rs(E)||(m=E):g!==Tg.JOINED&&g!==Tg.KICKED&&g!==Tg.ADMIN_SET&&g!==Tg.ADMIN_CANCELED||(m=Object.assign({},u[0])),!Rs(m)){const{nick:D="",avatar:M=""}=m;n.nick=D,n.avatar=M}}const XQ=s=>({lastTime:s?.time||s?.lastTime||0,lastSequence:s?.sequence||s?.lastSequence||0,fromAccount:s?.from||s?.fromAccount||"",messageForShow:Zc(s?.type,s?.payload),payload:s?.payload||null,type:s?.type||"",isRevoked:s?.isRevoked||!1,cloudCustomData:s?.cloudCustomData||"",onlineOnlyFlag:s?._onlineOnlyFlag||!1,nick:s?.nick||"",nameCard:s?.nameCard||"",version:s?.version||0,isPeerRead:s?.isPeerRead||!1,revoker:s?.revoker||null});var $Q=Object.freeze({__proto__:null,ChatError:gs,WorkflowManager:ws,buildAndSendPacket:gg,buildLastMessage:XQ,get builtInPlugins(){return DB},checkBusinessCapabilityBits:tn,deepMerge:Cd,getCurrentUserID:Ar,getErrorMessage:rs,getMessagePreviewText:Zc,isC2CConv:s=>l(s)&&s.slice(0,3)===ka.CONV_C2C,isCommunity:Xr,isGroupConv:s=>l(s)&&s.slice(0,5)===ka.CONV_GROUP,isInternational:wl,isTopic:zc,isUnlimitedAVChatRoom:function(){var s;return!!(!((s=fe.store.get("instance"))===null||s===void 0)&&s.unlimitedAVChatRoom)},liteChatInstanceMap:Ca,registerInterceptor:Mc,registerValidateConfig:Wc,requireAuth:ud,get sdkEdition(){return jm},setGroupTipsUserInfo:SB,t:ku,updateGroupAtInfo:(s,n)=>{const{CONV_AT_ME:g,CONV_AT_ALL:u,CONV_AT_ALL_AT_ME:E}=Lo;if(function(M,T){const{CONV_AT_ME:P,CONV_AT_ALL:W,CONV_AT_ALL_AT_ME:iA}=Lo,{groupID:EA,sequence:RA}=M;let kA=!1;return Xr({groupID:EA})&&T.forEach(xA=>{xA.messageSequence===RA&&(xA.atTypeArray.includes(P)&&M.groupAtType.includes(W)&&(xA.atTypeArray=[iA]),xA.atTypeArray.includes(W)&&M.groupAtType.includes(P)&&(xA.atTypeArray=[iA],xA.__random=M.__random,xA.__sequence=M.__sequence),kA=!0)}),kA}(s,n))return;let m=[...s.groupAtType];m.includes(g)&&m.includes(u)&&(m=[E]);const D={from:s.from,groupID:s.groupID,topicID:s.topicID,messageSequence:s.sequence,atTypeArray:m,__random:s.__random,__sequence:s.__sequence};n.push(D)},validateAndExecute:Sr,validateParameters:II});class au{constructor(){this._builtInPlugins=new Set,this._externalPlugins=new Set}static getInstance(){return au._instance||(au._instance=new au),au._instance}static setInstance(n){au._instance=n}installBuiltInPlugin(n){n&&this._installPlugin(n,this._builtInPlugins)}installExternalPlugin(n){n&&this._installPlugin(n,this._externalPlugins)}clear(){this._builtInPlugins=new Set,this._externalPlugins=new Set}_installPlugin(n,g){let u=[];u=h(n)?n:[n];const E=u.findIndex(D=>D?.name==="AVChatRoom"),m=E>-1?u.splice(E,1):[];u.forEach(D=>{this._isPluginInstalled(D.name)||(D&&vg(D.install)?(g.add(D.name),vg(D.getInstalledSubPlugins)?(m?.forEach(M=>g.add(M?.name)),D.install(Cr.getInstance().exposeApiForPlugin(),m)):D.install(Cr.getInstance().exposeApiForPlugin()),vg(D.handleLoginSuccess)&&this._isLoggedIn()&&D.handleLoginSuccess()):vg(D)?(g.add(D.name),D(Cr.getInstance().exposeApiForPlugin()),vg(D.handleLoginSuccess)&&this._isLoggedIn()&&D.handleLoginSuccess()):console.warn('A plugin must either be a function or an object with an "install" function.'))})}_isPluginInstalled(n){return this._builtInPlugins.has(n)||this._externalPlugins.has(n)}_isLoggedIn(){var n;return((n=fe.store.get("login"))===null||n===void 0?void 0:n.isLoggedIn)===!0}}var MB=new class{constructor(){this._conversationMap=new Map}getConversationMap(){return this._conversationMap}getConversation(s){return this._conversationMap.get(s)}updateConversation(s,n,g){const{emit:u=!0,needSort:E=!1}=g||{},m=this._conversationMap.get(s);m&&!Rs(n)&&(Object.keys(n).forEach(D=>{m[D]=n[D]}),u&&fe.notificationCenter.emitInnerEvent(no.CONVERSATION_UPDATED,{needSort:E}))}deleteConversation(s){this._conversationMap.has(s)&&(this._conversationMap.delete(s),fe.notificationCenter.emitInnerEvent(no.CONVERSATION_UPDATED))}},Ap=new class{constructor(){this._groupMap=new Map}getGroupMap(){return this._groupMap}getGroup(s){return this._groupMap.get(s)}updateGroup(s,n){const g=this._groupMap.get(s);g&&!Rs(n)&&Object.keys(n).forEach(u=>{g[u]=n[u]})}},ep=new class{constructor(){this._messagesByConversation=new Map}updateMessage(s,n,g){var u;const{operation:E,updateUnreadCount:m=!0}=g,D=Do(g,["operation","updateUnreadCount"]),M=[];for(const T of n){const P=(u=this._messagesByConversation.get(s))===null||u===void 0?void 0:u.get(T);if(!P)return!1;Object.keys(D).forEach(W=>{P[W]=D[W]}),M.push(P)}return this._emitMessageStoreOperationEvent(E,{conversationID:s,messageList:M,updateUnreadCount:m}),M}getMessagesByConversation(s){var n;return[...((n=this._messagesByConversation.get(s))===null||n===void 0?void 0:n.values())||[]]}getMessages(){return this._messagesByConversation}_emitMessageStoreOperationEvent(s,n){const{conversationID:g}=n;zc(g)?fe.notificationCenter.emitInnerEvent(_u[s],n):fe.notificationCenter.emitInnerEvent(s,n)}},rc=new class{constructor(){this.userProfileMap=new Map,this.friendMap=new Map}getUserProfileMap(){return this.userProfileMap}getFriendMap(){return this.friendMap}getUserProfile(s){return this.userProfileMap.get(s)}getFriend(s){return this.friendMap.get(s)}},OD=Object.freeze({__proto__:null,conversationStore:MB,groupStore:Ap,messageStore:ep,userStore:rc});class Cr{static getInstance(){return Cr._instance||(Cr._instance=new Cr),Cr._instance}static setInstance(n){Cr._instance=n}constructor(){this._experimentalApiMap={statTUIKeyFeatures:this.statKeyFeatureUsage.bind(this),setApplicationID:this.setApplicationID.bind(this)},this._apiHandlersMap={},this._apiMap={on:fe.notificationCenter.subscribeOuterEvent.bind(fe.notificationCenter),off:fe.notificationCenter.unSubscribeOuterEvent.bind(fe.notificationCenter),destroy:this.destroy.bind(this),callExperimentalAPI:this.callExperimentalAPI.bind(this),use:au.getInstance().installExternalPlugin.bind(au.getInstance()),registerPlugin:this.registerPlugin.bind(this),setLogLevel:this.setLogLevel.bind(this)}}registerPlugin(n){fe.ssoLog.debug("registerPlugin",n)}statKeyFeatureUsage(n){fe.ssoLog.debug("statTUIKeyFeatures",n)}setLogLevel(n){fe.ssoLog.debug("setLogLevel",n),fe.ssoLog.setLogLevel(n)}setApplicationID(n){fe.store.set("instance",{applicationID:n})}getApiMap(){return this._apiMap}setApiMap(n){this._apiMap=n}registerApi(n){const{common:{timeManager:g},utils:{safeStringify:u}}=fe,{apiName:E,context:m,methodName:D=E,matcher:M}=n;this._apiHandlersMap[E]||(this._apiHandlersMap[E]=[]),this._apiHandlersMap[E].push({context:m,methodName:D,matcher:M}),this._apiMap[E]&&this._apiHandlersMap[E].length!==1||(this._apiMap[E]=(...T)=>{const P=g.getServerTimeMs();let W=0;E==="login"&&(W=4),qI.includes(E)&&fe.ssoLog.debug(E,`${E} start params: ${u(T)}`),Sr(D,T);const iA=this._apiHandlersMap[E];for(const EA of iA)if(!EA.matcher||EA.matcher(T))try{const RA=EA.context[EA.methodName].bind(EA.context)(...T);return this._isPromiseLike(RA)?this._handleAsyncResult(RA,E,W,P):(this._reportApiSuccessLog({result:RA,apiName:E,eventType:W,startTime:P}),RA)}catch(RA){throw fe.ssoLog.error(E,`${E} fail ${RA?.message||RA?.errorMessage})`,{error:RA,costTime:g.getServerTimeMs()-P,eventType:W,method:E}),RA}})}registerExperimentalAPI(n,g,u){const E=u||n;this._experimentalApiMap[n]=g[E].bind(g)}destroy(){return pA(this,void 0,void 0,function*(){var n,g;try{!((n=fe.store.get("login"))===null||n===void 0)&&n.isLogin&&(yield this._apiMap.logout()),fe.notificationCenter.emitInnerEvent(no.DESTROY)}catch(u){console.debug("destroy error: ",u)}finally{fe.notificationCenter.emitOuterEvent(Dr.SDK_DESTROY,{SDKAppID:(g=fe.store.get("instance"))===null||g===void 0?void 0:g.sdkAppId}),Ca.clear(),au.getInstance().clear(),ws.getInstance().destroy(),fe.destroy()}})}exposeApiForClient(){return this._apiMap}exposeApiForPlugin(){return Object.assign(Object.assign({InnerEvent:no,InnerEventSubType:fe.notificationCenter.InnerEventSubType,OuterEvent:Dr,OuterConstant:Lo,SignalingEvent:qc,helper:Object.assign(Object.assign(Object.assign({},fe.utils),fe.common),{registerApi:this.registerApi.bind(this),registerExperimentalAPI:this.registerExperimentalAPI.bind(this),registerInterceptor:Mc,registerValidateConfig:Wc,checkBusinessCapabilityBits:tn,registerWorkflowStep:ws.getInstance().registerWorkflowStep.bind(ws.getInstance()),ChatError:gs}),apiMap:this._apiMap},fe),{constants:Object.assign(Object.assign({},za),fe.constants),common:Object.assign(Object.assign(Object.assign({},$Q),fe.common),{workflowManager:ws.getInstance()}),utils:fe.utils,appStore:OD})}callExperimentalAPI(n,g){return fe.ssoLog.debug(`callExperimentalAPI.${n} start params: ${fe.utils.safeStringify(g)}`),this._experimentalApiMap[n]?this._experimentalApiMap[n](g):(fe.ssoLog.error("callExperimentalAPI",`callExperimentalAPI.${n} not found, params: ${fe.utils.safeStringify(g)}`),Promise.reject(new gs({code:da.INVALID_OPERATION})))}_isPromiseLike(n){return n!==null&&typeof n=="object"&&typeof n.then=="function"}_handleAsyncResult(n,g,u,E){return n.then(m=>(this._reportApiSuccessLog({result:m,apiName:g,eventType:u,startTime:E}),m)).catch(m=>{throw fe.ssoLog.error(g,`${g} fail ${m?.message||m?.errorMessage})`,{error:m,costTime:fe.common.timeManager.getServerTimeMs()-E,eventType:u,method:g,startTime:E}),m})}_reportApiSuccessLog(n){let{result:g,apiName:u,startTime:E,eventType:m}=n;const{timeManager:D}=fe.common,{successLog:{message:M,moreMessage:T}={message:"",moreMessage:""}}=g||{},P=D.getServerTimeMs();u==="login"&&(E+=D.getTimeOffsetWithServer()),qI.includes(u)&&fe.ssoLog.info(u,`${u} success ${M} ${T}`,{costTime:P-E,eventType:m,message:M,moreMessage:T,startTime:E}),g?.successLog&&delete g.successLog}}class hR{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120,this._customLoginInfo=""}init(){const{notificationCenter:n,store:g}=fe;g.set("login",{isReady:!1}),Cr.getInstance().registerApi({apiName:"login",context:this}),Cr.getInstance().registerApi({apiName:"logout",context:this}),Cr.getInstance().registerApi({apiName:"getLoginUser",context:this}),Cr.getInstance().registerApi({apiName:"isReady",context:this}),Cr.getInstance().registerApi({apiName:"getServerTime",context:this}),Cr.getInstance().registerExperimentalAPI("setCustomLoginInfo",this),n.subscribeInnerEvent(no.RECONNECTED,this._reLogin,this),fe.notificationCenter.subscribeInnerEvent(no.DESTROY,this._dispose,this)}login(n){return pA(this,void 0,void 0,function*(){var g;const{sdkEdition:u}=fe.store.get("instance")||{};try{if(this._isLoginIn())return this._createRepeatLoginResponse();if(this._isLoginFrequencyExceeded())throw new gs({functionName:"login",code:da.REPEAT_LOGIN});const E=yield this._performLogin(n);this._validateAfterLogin(E),this._handleLoginSuccess(E),yield this._ensureAsyncComplete(),this._updateAndEmitSDKReady(),this._latestLoginAt=0;const m=(g=fe.channel.getSocketAdapter())===null||g===void 0?void 0:g.getId(),{appId:D,href:M}=fe.store.get("instance")||{},{instanceID:T,customStatus:P}=E||{};return{code:0,data:E,successLog:{message:u,moreMessage:`socketID:${m} instanceID:${T} customStatus:${P} href: ${M} appId: ${D}`}}}catch(E){const{errorCode:m}=E;m!==da.REPEAT_LOGIN&&(this._latestLoginAt=0);const D=new gs({functionName:"login",code:m});throw console.error(D),D}})}_reLogin(){return pA(this,void 0,void 0,function*(){var n;try{if(!this._isLoginIn())return;const g=yield bu(this._customLoginInfo);if(g){const{instanceID:u,customStatus:E}=g;fe.store.set("login",{statusInstanceId:u}),ws.getInstance().executeWorkflow(Vt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,{customStatus:E,statusType:SE.USER_STATUS_ONLINE});const m=(n=fe.channel.getSocketAdapter())===null||n===void 0?void 0:n.getId();fe.ssoLog.info("reLogin",`socketId:${m} instanceId:${u}`)}}catch(g){console.warn(g)}})}logout(){return pA(this,arguments,void 0,function*(n=na.USER_INITIATED){const{ssoLog:g}=fe;g.debug("logout",`logout start logoutReason: ${n}`);try{yield this._performLogout(n),g.info("logout","logout success"),fe.ssoLog.uploadSSOLogData()}catch(u){const{errorCode:E}=u;throw new gs({functionName:"logout",code:E})}finally{this.handleLogoutCompleted()}return{code:0,data:{}}})}getLoginUser(){return this._isLoginIn()?Ar():""}isReady(){var n;return(n=fe.store.get("login"))===null||n===void 0?void 0:n.isReady}setCustomLoginInfo(n=""){this._customLoginInfo=n}handleLogoutCompleted(){this._updateAndEmitSDKNotReady(),this._reset(),ws.getInstance().reset(),fe.notificationCenter.emitInnerEvent("logout")}getServerTime(){const{timeManager:n}=fe.common;return n.getServerTimeMs()}_updateAndEmitSDKReady(){fe.store.set("login",{isReady:!0}),setTimeout(()=>{fe.notificationCenter.emitOuterEvent(Dr.SDK_READY,{name:Dr.SDK_READY})},1)}_updateAndEmitSDKNotReady(){fe.store.set("login",{isReady:!1}),fe.notificationCenter.emitOuterEvent(Dr.SDK_NOT_READY,{name:Dr.SDK_NOT_READY})}_validateAfterLogin(n){const g="login";if(!n)throw new gs({functionName:g,message:"login response is empty"});const{tinyID:u,a2Key:E}=n||{};if(!u)throw new gs({functionName:g,code:da.NO_TINYID});if(!E)throw new gs({functionName:g,code:da.NO_A2KEY})}_createRepeatLoginResponse(){var n;return{code:0,data:{actionStatus:"OK",errorCode:0,errorInfo:rs({code:"RepeatLogin",replacement1:(n=fe.store.get("login"))===null||n===void 0?void 0:n.userId}),repeatLogin:!0}}}_performLogin(n){return pA(this,void 0,void 0,function*(){const{userID:g,userSig:u}=n;return fe.store.set("login",{userId:g,userSig:u}),this._latestLoginAt=Date.now(),bu(this._customLoginInfo)})}_ensureAsyncComplete(){return pA(this,void 0,void 0,function*(){yield new Promise(n=>{setTimeout(()=>n(null),1)})})}_handleLoginSuccess(n){const{timeManager:g}=fe.common,{helloInterval:u,timeStamp:E,customStatus:m,purchaseBits:D}=n,M=1e3*E;g.calculateTimeOffsetWithServer(this._latestLoginAt,M),this._helloInterval=u||120,this._updateLoginStore(n),fe.user.userStatus.setCustomStatus(m),ws.getInstance().executeWorkflow(Vt.SYNC_SERVER_INFO_AFTER_LOGIN,{purchaseBits:D}),fe.common.taskScheduler.addTask({id:Gg,intervalMs:1e3*this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this})}_performLogout(n){return function(g){return pA(this,void 0,void 0,function*(){const{logoutReason:u}=g,E="im_open_status.wslogout",m=fe.common.generateProtocolData({servcmd:E,data:{wslogout_type:u,isWebUniapp:0}}),D=`${m.head.seq}${E}`;return yield fe.channel.sendPacket(m,{requestId:D})})}({logoutReason:n})}_updateLoginStore(n){const{a2Key:g,tinyID:u,instanceID:E,authKey:m}=n;fe.store.set("login",{a2Key:g,tinyID:u,statusInstanceId:E,authKey:m,isLoggedIn:!0})}_sendOnlinePresenceRequest(){return pA(this,void 0,void 0,function*(){this._latestSendOnlinePresenceRequestTime=Date.now();try{yield function(){const n="im_open_status.wshello",g=fe.common.generateProtocolData({servcmd:n,data:{isWebUniapp:0}}),u=`${g.head.seq}${n}`;return fe.channel.sendPacket(g,{requestId:u})}()}catch(n){fe.ssoLog.warn("_sendOnlinePresenceRequest",` error:${n.message}`)}})}_isLoginIn(){var n;return((n=fe.store.get("login"))===null||n===void 0?void 0:n.isLoggedIn)===!0}_isLoginFrequencyExceeded(){return Date.now()-this._latestLoginAt<=15e3}_reset(){fe.common.taskScheduler.removeTask(Gg),this._helloInterval=120,this._latestSendOnlinePresenceRequestTime=0,this._latestLoginAt=0,this._customLoginInfo="",fe.store.clear("login"),fe.store.set("login",{isReady:!1}),fe.store.set("instance",{applicationID:0})}_dispose(){this._reset();const{notificationCenter:n}=fe;n.unSubscribeInnerEvent(no.RECONNECTED,this._reLogin,this),n.unSubscribeInnerEvent(no.DESTROY,this._dispose,this)}}const BR={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}},qT={logout:!0};class Rh{constructor(){this.loginAction=new hR,this.kickedOutHandler=new Gu,this.loginAction.init(),this.kickedOutHandler.init(),Wc({auth:qT,params:BR})}}var Kr,$u,KE;(function(s){s.CONV_C2C="C2C",s.CONV_GROUP="GROUP",s.CONV_TOPIC="TOPIC",s.CONV_SYSTEM="@TIM#SYSTEM"})(Kr||(Kr={})),function(s){s.MSG_PRIORITY_HIGH="High",s.MSG_PRIORITY_NORMAL="Normal",s.MSG_PRIORITY_LOW="Low",s.MSG_PRIORITY_LOWEST="Lowest"}($u||($u={})),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 PD={1:$u.MSG_PRIORITY_HIGH,2:$u.MSG_PRIORITY_NORMAL,3:$u.MSG_PRIORITY_LOW,4:$u.MSG_PRIORITY_LOWEST},xD=0,QR=1;var AE;(function(s){s.IN="in",s.OUT="out"})(AE||(AE={}));const pR=2,tp={};function gu(s){if(!s)return 0;if(tp[s]===void 0){const n=new Date,g=`3${n.getHours()}`.slice(-2),u=`0${n.getMinutes()}`.slice(-2),E=`0${n.getSeconds()}`.slice(-2);tp[s]=parseInt([g,u,E,"0001"].join(""),10),console.log(`autoIncrementIndex start index:${tp[s]}`)}else tp[s]+=1;return tp[s]}class jE{constructor(n){this.ID="",this.random=0,this.sequence=0,this.nameCard="",this.isRead=!1,this.isPeerRead=!1,this.isDeleted=!1,this.isResend=!1,this.hasRiskContent=!1,this._onlineOnlyFlag=!1,this.atUserList=[],this._groupAtInfoList=[],this.isBroadcastMessage=!1,this.priority=$u.MSG_PRIORITY_NORMAL,this._relayFlag=!1;const{clientTime:g=fe.common.timeManager.getServerTimeSeconds()||0,senderTinyID:u,currentUser:E,needReadReceipt:m,isSupportExtension:D,customModerationConfigurationId:M,to:T,from:P,nick:W="",avatar:iA="",time:EA,messageControlInfo:RA,tinyID:kA,cloudCustomData:xA="",messageLifeTime:LA,messageVersion:SA=0,conversationType:OA,sequence:JA,checkResult:ae=0,isPlaceMessage:se=0,messageFlagBits:_i,receiverList:Ti,isSystemMessage:Ft=!1,status:Ni=Yr.SUCCESS,revokeReason:cs="",conversationSubType:Se,clientSequence:mt,protocol:UA="JSON",revokerInfo:ri={userID:"",nick:"",avatar:""},readReceiptInfo:_s={readCount:void 0,unreadCount:void 0,isPeerRead:void 0,timestamp:0},random:Gi,groupProfile:Or,atUserList:xi,flow:gr,isRead:Gt=!1,priority:bt=$u.MSG_PRIORITY_NORMAL,onlineOnlyFlag:tE=!1,nameCard:ln="",quoteInfo:Bo}=n;var Il;this.clientTime=g,this.senderTinyID=u||kA,this.needReadReceipt=m===!0||m===1,this.isSupportExtension=D===!0||D===1,this._cmConfigID=M,this.to=T,this.nick=W,this.avatar=iA,this.protocol=UA,this.random=Gi===void 0?(Il=Il||99999999,Math.round(Math.random()*Il)):Gi,this.time=EA||Math.ceil(Date.now()/1e3),this._isExcludedFromLastMessage=!!RA?.excludedFromLastMessage,this._isExcludedFromUnreadCount=!!RA?.excludedFromUnreadCount,this.isModified=!!SA,this.cloudCustomData=xA,this.messageLifeTime=LA,this.from=P||null,this.sequence=JA||0,this.conversationType=OA||Kr.CONV_C2C,this.hasRiskContent=ae>1,this.version=SA,this.isPlaceMessage=se,this.isRevoked=se===2||_i===8,this.isSystemMessage=Ft,this.readReceiptInfo=_s,this.revokeReason=cs,this.revokerInfo=ri,this._receiverList=Ti,this.conversationSubType=Se,this.revoker=ri?.revoker||"",this.clientSequence=mt||JA||0,this.status=Ni,this.atUserList=xi||[],this.flow=gr,this.isRead=Gt,this.priority=bt,this._onlineOnlyFlag=tE,this.nameCard=ln,this.quoteInfo=Bo,this.reInitialize(E),this._initC2CReadReceiptInfo(n),this._extractGroupInfo(Or)}getElements(){return this._elements}isOnlineMessage(){return this.messageLifeTime===0}setElement(n){Array.isArray(n)?this._elements=n:this._elements=[n],this._updatePayloadAndType()}transformElementsToServerFormat(){return this._elements?Array.isArray(this._elements)?this._elements.map(n=>n.transformToServerFormat()):this._elements.transformToServerFormat():null}setRelayFlag(n){this._relayFlag=n}validateBeforeSend(){var n,g,u;return this._relayFlag?{isValid:!0}:((n=this._elements)===null||n===void 0?void 0:n.length)>0?(u=(g=this._elements[0])===null||g===void 0?void 0:g.validateBeforeSend)===null||u===void 0?void 0:u.call(g):{isValid:!1}}_updatePayloadAndType(){this._elements[0]&&(this.payload=this._elements[0].content,this.type=this._elements[0].type)}_initC2CReadReceiptInfo(n){const{readReceiptSentByPeer:g,timestamp:u=0}=n;this.conversationType===Kr.CONV_C2C&&this.needReadReceipt===!0&&(this.readReceiptInfo.isPeerRead=g===1,this.readReceiptInfo.timestamp=u)}_extractGroupInfo(n){if(!n)return;const{From_AccountNick:g,From_AccountHeadurl:u,MsgFrom_AccountExtraInfo:E,GroupType:m}=n,{NameCard:D}=E||{};typeof g=="string"&&(this.nick=g),typeof u=="string"&&(this.avatar=u),typeof D=="string"&&(this.nameCard=D),this.conversationSubType=m}reInitialize(n){n===this.from&&(this.isRead=!0),this._initSequence(n),this._concatConversationID(n),this.generateMessageID()}_concatConversationID(n){let g="";const u=this.conversationType;u!==Kr.CONV_SYSTEM?(g=u===Kr.CONV_C2C?n===this.from?this.to:this.from:this.to,this.conversationID=g?`${u}${g}`:null):this.conversationID=Kr.CONV_SYSTEM}_initSequence(n){this.clientSequence===0&&n&&(this.clientSequence=gu(n)),this.sequence===0&&this.conversationType===Kr.CONV_C2C&&(this.sequence=this.clientSequence)}generateMessageID(){this.from===Kr.CONV_SYSTEM&&(this.senderTinyID="144115198244471703"),this.ID=`${this.senderTinyID}-${this.clientTime}-${this.random}`}setIsRead(n){this.isRead=n}}class Td{static parseServerPushElement(n){const{MsgContent:g={}}=n,{Data:u,Ext:E,Desc:m}=g;return new Td({data:u,description:m,extension:E})}constructor(n){this.type=KE.MSG_CUSTOM;const{data:g="",description:u="",extension:E=""}=n;this.content={data:g,description:u,extension:E}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},u=g?this.payload:this.content,{data:E,description:m,extension:D}=u;return{MsgType:this.type,MsgContent:{Data:E,Ext:D,Desc:m}}}validateBeforeSend(){const{isEmpty:n}=fe.utils,g=[this.content.data,this.content.description,this.content.extension].some(u=>!n(u));return{isValid:g,error:g?null:{message:"content can not be empty"}}}}class Nd{static parseServerPushElement(n){const{MsgContent:g={Text:""}}=n,{Text:u}=g;return new Nd({text:u})}constructor(n){this.type=wg.MSG_TEXT,this.content={text:n.text||""}}validateBeforeSend(){var n,g;return((g=(n=this.content)===null||n===void 0?void 0:n.text)===null||g===void 0?void 0:g.length)>0?{isValid:!0}:{isValid:!1,error:{message:"content can not be empty"}}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},u=g?this.payload:this.content,{text:E}=u;return{MsgType:this.type,MsgContent:{Text:E}}}}var Wm=new class{constructor(){this._elementClassMap={[KE.MSG_CUSTOM]:Td,[KE.MSG_TEXT]:Nd}}init(){Cr.getInstance().registerApi({apiName:"createCustomMessage",context:this}),Cr.getInstance().registerApi({apiName:"createTextMessage",context:this})}registerElementClass(s,n){var g;(g=n).prototype!==void 0&&"constructor"in g.prototype&&(this._elementClassMap[s]=n)}getElementClass(s){return this._elementClassMap[s]}createMessage(s){const{from:n,flow:g=AE.OUT}=s,{userId:u}=fe.store.get("login")||{};this._isSendByCurrentInstance({from:n,flow:g,currentUser:u})?this._updateWithSenderInfo(s):this._isMultiEndpointSyncMessage({from:n,flow:g,currentUser:u})&&(s.flow=AE.OUT);const E=Object.assign(Object.assign({},s),{currentUser:u});return new jE(E)}createCustomMessage(s){const n=Ar(),g=this.createMessage(Object.assign(Object.assign({},s),{from:n})),u=this._elementClassMap[KE.MSG_CUSTOM];if(!g)return null;if(u){const E=new u(s.payload);g.setElement(E)}return g}createTextMessage(s){var n;if(!s)return null;const g=typeof s.payload=="string"?s.payload:((n=s?.payload)===null||n===void 0?void 0:n.text)||"",u=new Nd({text:g}),E=Ar(),m=fe.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:E}));return m.setElement(u),m}_updateWithSenderInfo(s){var n,g;const{nick:u,avatar:E,conversationType:m,to:D}=s,{userId:M,tinyID:T}=fe.store.get("login")||{},P=rc.getUserProfile(M);return s.nick=u||P?.nick||"",s.avatar=E||P?.avatar||"",s.tinyID=s.tinyID||T||"",s.from=M,s.status=Yr.UNSENT,s.flow=AE.OUT,m===ka.CONV_GROUP&&(s.nameCard=(g=(n=Ap.getGroup(D))===null||n===void 0?void 0:n.selfInfo)===null||g===void 0?void 0:g.nameCard),s}_isMultiEndpointSyncMessage(s){const{from:n,flow:g,currentUser:u}=s;return n===u&&g===AE.IN}_isSendByCurrentInstance(s){const{from:n,flow:g,currentUser:u}=s;return n===u&&g===AE.OUT}};const mR={PushFlag:0,Title:"",Desc:"",Ext:"",ApnsInfo:{Sound:"",BadgeMode:0,IsVoipPush:void 0,Image:"",InterruptionLevel:"active",ContentAvailable:0},AndroidInfo:{Sound:"",XiaoMiChannelID:"",OPPOChannelID:"",GoogleChannelID:"",VIVOClassification:1,VIVOCategory:"",HuaWeiCategory:"",OPPOCategory:"",HuaWeiImage:"",HonorImage:"",GoogleImage:"",HonorImportance:"",MeizuNotifyType:void 0}},Gd={HonorImportance:{range:["LOW","NORMAL"],defaultValue:void 0},MeizuNotifyType:{range:[0,1],defaultValue:void 0}},YD={enableIOSBackgroundNotification:{range:[!0,!1],defaultValue:!1},interruptionLevel:{range:["passive","active","time-sensitive","critical"],defaultValue:"active"}};function fR(s,n){return Object.keys(n).forEach(g=>{const{range:u,defaultValue:E}=n[g];s[g]=u.includes(s[g])?s[g]:E}),s}function ip(s){const n=s.lastIndexOf(".");return n===-1?s:s.slice(0,n)}function yR(s){const{androidInfo:n={},androidOPPOChannelID:g=""}=s,u=n.OPPOChannelID||g,E=fR(n,Gd),{sound:m="",FCMChannelID:D=""}=E,M=Do(E,["sound","FCMChannelID"]);return Object.assign(Object.assign({},M),{Sound:ip(m),OPPOChannelID:u,GoogleChannelID:D})}function DR(s){const{apnsInfo:n={},ignoreIOSBadge:g=!1,disableVoipPush:u}=s,E=fR(n,YD),{ignoreIOSBadge:m,disableVoipPush:D,enableIOSBackgroundNotification:M}=E,T=Do(E,["ignoreIOSBadge","disableVoipPush","enableIOSBackgroundNotification"]),P=m===!0||g===!0?1:0;let W;return r(u)||(W=u===!1?1:0),r(D)||(W=D===!1?1:0),Object.assign(Object.assign({},T),{BadgeMode:P,IsVoipPush:W,ContentAvailable:M?1:0})}function VD(s){return fe.utils.isPlainObject(s)?{PushFlag:s.disablePush===!0?1:0,Title:s.title||"",Desc:s.description||"",Ext:s.extension||"",ApnsInfo:DR(s),AndroidInfo:yR(s)}:mR}function zm(s){const{From_AccountHeadurl:n,From_AccountNick:g,IsNeedReadReceipt:u,IsPeerRead:E,IsSyncMsg:m,MsgBody:D,MsgClientTime:M,MsgLifeTime:T,MsgRandom:P,MsgSeq:W,MsgTimeStamp:iA,SendMsgControl:EA,SupportMessageExtension:RA,TinyId:kA,MsgCheckResult:xA,CloudCustomData:LA,MsgVersion:SA,MsgFlagBits:OA,RevokerInfo:JA,InnerSdkCustomData:ae}=s;let se,{From_Account:_i,To_Account:Ti}=s;if(m===1){const Ft=Ti;Ti=_i,_i=Ft}if(JA){const{Reason:Ft,Revoker_Account:Ni,Revoker_FromUin:cs}=JA;se={reason:Ft,revoker:Ni,revokerFromUin:cs,userID:Ni}}return{from:_i,avatar:n,nick:g,needReadReceipt:u===1,isSyncMessage:m,clientTime:M,messageLifeTime:T,random:P,sequence:W,time:iA,messageControlInfo:{excludedFromLastMessage:EA?.NoLastMsg===1,excludedFromUnreadCount:EA?.NoUnread===1},isSupportExtension:RA,to:Ti,tinyID:kA,checkResult:xA,cloudCustomData:LA,revokerInfo:se,messageVersion:SA,messageFlagBits:OA,readReceiptSentByPeer:E,elements:RC(D),onlineOnlyFlag:T===0,quoteInfo:op(ae)}}function Zm(s){const{From_Account:n,MsgBody:g,MsgClientTime:u,MsgRandom:E,MsgSeq:m,MsgTimeStamp:D,To_Account:M,MsgVersion:T,CloudCustomData:P,MsgCheckResult:W}=s;return{from:n,clientTime:u,random:E,sequence:m,time:D,to:M,elements:RC(g),messageVersion:T,cloudCustomData:P,checkResult:W}}function JD(s){const{ClientSeq:n,From_Account:g,GroupInfo:u,MsgBody:E,MsgClientTime:m,MsgRandom:D,MsgSeq:M,MsgTimeStamp:T,SendMsgControl:P,SupportMessageExtension:W,TinyId:iA,CloudCustomData:EA,MsgVersion:RA,MsgCheckResult:kA,NeedReadReceipt:xA,IsPlaceMsg:LA,RevokerInfo:SA,GroupAtInfo:OA,OnlineOnlyFlag:JA,InnerSdkCustomData:ae}=s;let se,_i=$u.MSG_PRIORITY_NORMAL;if(Object.keys(PD).includes(String(s.MsgPriority))&&(_i=PD[s.MsgPriority]),SA){const{Reason:Ft,Revoker_Account:Ni,Revoker_FromUin:cs}=SA;se={reason:Ft,revoker:Ni,revokerFromUin:cs,userID:Ni}}const Ti=function(Ft){const Ni=[];return Array.isArray(Ft)&&Ft.forEach(cs=>{cs.GroupAtAllFlag===xD?Ni.push(cs.GroupAt_Account):cs.GroupAtAllFlag===QR&&Ni.push(Lo.MSG_AT_ALL)}),Ni}(OA);return{clientSequence:n,from:g,groupProfile:u,clientTime:m,priority:_i,random:D,sequence:M,time:T,messageControlInfo:{excludedFromLastMessage:P?.NoLastMsg===1,excludedFromUnreadCount:P?.NoUnread===1},isSupportExtension:W,tinyID:iA,cloudCustomData:EA,messageVersion:RA,checkResult:kA,needReadReceipt:xA,isPlaceMessage:LA,revokerInfo:se,atUserList:Ti,elements:RC(E),to:KT(s),onlineOnlyFlag:JA===1,quoteInfo:op(ae)}}function KT(s){const{utils:{isEmpty:n},constants:{IS_TOPIC_MESSAGE:g}}=fe,{ToGroupId:u,GroupInfo:{MillionGroupFlag:E=0,TopicId:m}={}}=s;return E!==g||n(m)?u:m}function RC(s){if(!s)return null;if(Array.isArray(s))return s.map(g=>{const u=fe.message.messageFactory.getElementClass(g.MsgType);return u?.parseServerPushElement(g)});const n=fe.message.messageFactory.getElementClass(s.MsgType);return n?.parseServerPushElement(s)}function HD(s){const{From_Account:n,MsgBody:g,MsgClientTime:u,MsgRandom:E,MsgSeq:m,MsgTimeStamp:D,GroupId:M,TopicId:T,MsgVersion:P,CloudCustomData:W,MsgCheckResult:iA}=s;return{from:n,clientTime:u,random:E,sequence:m,time:D,groupID:M,topicID:T,elements:RC(g),messageVersion:P,cloudCustomData:W,checkResult:iA}}function op(s){const{utils:{isString:n,safeStringify:g},ssoLog:u}=fe;if(!n(s))return null;try{const{messageID:E,messageTime:m,messageSequence:D}=JSON.parse(s).businessQuote;return{msgID:E,messageTime:m,messageSequence:D}}catch(E){return u.debug("_parseServerQuoteInfo",g(E)),null}}function sp({conversationUpdateFields:s,message:n}){const{conversationID:g,conversationType:u,conversationSubType:E,flow:m,_isExcludedFromUnreadCount:D,_isExcludedFromLastMessage:M}=n,T=M?"":XQ(n),P=!D&&m===AE.IN;s.has(g)?(s.get(g).lastMessage=T,P&&s.get(g).unreadCount++):s.set(g,{conversationID:g,type:u,subType:E,unreadCount:P?1:0,lastMessage:T})}function vB(s){return s.filter(n=>{const g=!Rs(n?._elements),u=n?.isPlaceMessage===1;return g||fe.ssoLog.error("emptyMessageBody",`from:${n.from} to:${n.to} sequence:${n.sequence}`),g&&!u})}function RB(s){const{messageDataHandler:n}=fe.message;return!n.isInMessageList(s)&&!n.isMessageSentByCurrentInstance(s)}var SR=Object.freeze({__proto__:null,autoIncrementIndex:gu,createAndroidPushInfo:yR,createApnsPushInfo:DR,createOfflinePushInfo:VD,filterValidMessages:vB,getAndroidSoundName:ip,parseServerGroupMessage:JD,parseServerPushC2CModifyMessage:Zm,parseServerPushGroupModifyMessage:HD,parseServerPushMessage:zm,parseServerPushMessageElement:RC,shouldStoreMessage:RB,updateConversationFields:sp});const{isPlainObject:MR}=fe.utils;function np(s,n={}){const{onlineUserOnly:g,messageControlInfo:u}=n;let{offlinePushInfo:E}=n;s.conversationType===Kr.CONV_C2C&&g===!0&&(E?E.disablePush=!0:E={disablePush:!0});let m="";typeof s.cloudCustomData=="string"&&s.cloudCustomData.length>0&&(m=s.cloudCustomData);const D=[];if(u&&MR(u)){const{excludedFromUnreadCount:M,excludedFromLastMessage:T,excludedFromContentModeration:P}=u;M===!0&&D.push("NoUnread"),T===!0&&D.push("NoLastMsg"),P===!0&&D.push("NoMsgCheck")}return{onlineUserOnly:g,cloudCustomData:m,messageControlInfo:D,offlinePushInfo:E}}function qD(s){const{webhookInfo:{disableCloudMessagePreHook:n=!1,disableCloudMessagePostHook:g=!1}={}}=s||{};if(!n&&!g)return;const u=[];return n&&u.push("ForbidBeforeSendMsgCallback"),g&&u.push("ForbidAfterSendMsgCallback"),u}function wh(s,n){return pA(this,void 0,void 0,function*(){const g=s.conversationType===Kr.CONV_GROUP?function(E,m){var D;const M=np(E,m),{onlineUserOnly:T,cloudCustomData:P,messageControlInfo:W,offlinePushInfo:iA}=M,EA=JSON.parse(JSON.stringify(E.transformElementsToServerFormat()));let RA;return h(E._receiverList)&&E._receiverList.length>0&&(RA=E._receiverList,E._receiverList.length>50&&(RA=E._receiverList.slice(0,50),console.warn("ReceiverListLimit"))),{servcmd:"group_open_http_svc.send_group_msg",data:{From_Account:(D=fe.store.get("login"))===null||D===void 0?void 0:D.userId,GroupId:E.to,MsgBody:EA,CloudCustomData:P,Random:E.random,MsgPriority:E.priority,ClientSeq:E.clientSequence,GroupAtInfo:E._groupAtInfoList,OnlineOnlyFlag:T?1:0,MsgClientTime:E.clientTime,OfflinePushInfo:VD(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:qD(m),InnerSdkCustomData:_B(E)}}}(s,n):function(E,m){var D;const M=np(E,m),{onlineUserOnly:T,cloudCustomData:P,messageControlInfo:W,offlinePushInfo:iA}=M,EA=T===!0?0:void 0,RA=JSON.parse(JSON.stringify(E.transformElementsToServerFormat()));return{servcmd:"openim.sendmsg",data:{From_Account:(D=fe.store.get("login"))===null||D===void 0?void 0:D.userId,To_Account:E.to,MsgBody:RA,CloudCustomData:P,MsgSeq:E.sequence,MsgRandom:E.random,MsgLifeTime:EA,From_AccountNick:E.nick,From_AccountHeadurl:E.avatar,SendMsgControl:EA!==0?W:void 0,MsgClientTime:E.clientTime,IsNeedReadReceipt:E.needReadReceipt===!0?1:0,SupportMessageExtension:E.isSupportExtension===!0?1:0,IsRelayMsg:E._relayFlag===!0?1:0,CustomModerationConfigID:E._cmConfigID,OfflinePushInfo:VD(iA),ForbidCallbackControl:qD(m),InnerSdkCustomData:_B(E)}}}(s,n),u=yield gg(g);return u?{time:u.MsgTime,messageDropReason:u.MsgDropReason,sequence:u.MsgSeq}:null})}function _h(s){return pA(this,void 0,void 0,function*(){const{from:n,to:g,version:u=0,sequence:E,random:m,time:D,type:M,cloudCustomData:T}=s,P={From_Account:n,To_Account:g,MsgVersion:u,MsgSeq:E,MsgRandom:m,MsgTime:D,MsgType:M,MsgBody:s.transformElementsToServerFormat(),CloudCustomData:T},W=yield gg({servcmd:"openim.modify_c2c_msg",data:P});if(W){const{MsgBody:iA,MsgVersion:EA,CloudCustomData:RA}=W;return{elements:RC(iA),messageVersion:EA,cloudCustomData:RA}}})}function wB(s){return pA(this,void 0,void 0,function*(){const{to:n,version:g=0,sequence:u,cloudCustomData:E}=s,m={GroupId:n,MsgVersion:g,MsgSeq:u,MsgBody:s.transformElementsToServerFormat(),CloudCustomData:E},D=yield gg({servcmd:"openim.modify_group_msg",data:m});if(D){const{MsgBody:M,MsgVersion:T,CloudCustomData:P}=D;return{elements:RC(M),messageVersion:T,cloudCustomData:P}}})}function Th(s){return pA(this,void 0,void 0,function*(){const{groupID:n,count:g,messageSequence:u,messageSequenceList:E,getType:m}=s,D={GroupId:n,ReqMsgNumber:g,WithRecalledMsg:1,Version:1,GetType:m};return u&&(D.ReqMsgSeq=u),h(E)&&E.length>0&&(D.ReqMsgSeqList=E),yield gg({servcmd:"group_open_http_svc.group_msg_get",data:D})})}function Xm(s){return pA(this,void 0,void 0,function*(){const{peerAccount:n,count:g,lastMessageTime:u,messageKey:E,direction:m}=s;return gg({servcmd:"openim.getroammsg",data:{Peer_Account:n,MaxCnt:g,WithRecalledMsg:1,LastMsgTime:u,MsgKey:E,GetDirection:m}})})}function _B(s){if(fe.utils.isObject(s.quoteInfo)){const{msgID:n,messageSequence:g,messageTime:u}=s.quoteInfo;return JSON.stringify({businessQuote:{messageID:n,messageSequence:g,messageTime:u}})}}var KD=Object.freeze({__proto__:null,createMessagePackOptions:np,generateForbidCallbackControl:qD,getC2CRoamingMessagesByAnchor:Xm,getGroupRoamingMessagesByAnchor:Th,getRoamingMessages:function(s){return pA(this,void 0,void 0,function*(){const{peerAccount:n,count:g,lastMessageTime:u,messageKey:E}=s;return(yield gg({servcmd:"openim.getroammsg",data:{Peer_Account:n,MaxCnt:g||15,LastMsgTime:u||0,MsgKey:E,GetDirection:0,WithRecalledMsg:1}}))||[]})},modifyC2CMessage:_h,modifyGroupMessage:wB,sendMessage:wh});const{isPlainObject:jT}=fe.utils,{MSG_AUDIO:jD,MSG_FILE:WD,MSG_IMAGE:vR,MSG_VIDEO:RR,MSG_MERGER:wR}=Lo;class $m{constructor(){this._sendProtocolMap=new Map}init(){Cr.getInstance().registerApi({apiName:"sendMessage",context:this,matcher:n=>![jD,WD,vR,RR,wR].includes(n[0].type)})}registerSendProtocol(n,g,u){this._sendProtocolMap.set(n,g.bind(u))}sendMessage(n,g){return pA(this,void 0,void 0,function*(){const{TOTAL_COUNT:u,SEND_COST:E,SUCCESS_COUNT:m,FAILED_COUNT:D}=rr;if(!(n instanceof jE))throw new gs({code:da.MSG_INSTANCE_REQUIRED});const M=n.validateBeforeSend();if(!M.isValid){const{code:W,message:iA=""}=M.error||{};throw new gs({code:W,message:iA})}this._reportMessageSendQuality({name:u,message:n});let T=!1;const{messageDataHandler:P}=fe.message||{};try{const{messageControlInfo:W}=g||{};let iA=null;P.addRandomOfSentMessage(n.random);const EA=Date.now(),RA=this._getSendProtocol(n);if(n.conversationType===Kr.CONV_C2C?(T=g?.onlineUserOnly===!0,iA=yield RA(n,g)):n.conversationType===Kr.CONV_GROUP&&(yield this._validateBeforeSendGroupMessage(n),iA=yield RA(n,g)),iA){const{messageDropReason:kA,sequence:xA,time:LA}=iA;if(this._updateNickAndAvatarOfSentMessageByMe(n),kA&&this._logRateLimitInfo(n,xA,kA),this._reportMessageSendQuality({name:m,message:n}),this._reportMessageSendQuality({name:E,message:n,startTs:EA}),n.isResend===!0){const SA=P.findMessage(n.ID);SA&&(fe.ssoLog.debug("sendMessage",`sendMessage resend ok. ID:${SA.ID}`),P.deleteConversationMessage(SA))}return n.status=Yr.SUCCESS,n.time=LA,n.conversationType===Kr.CONV_GROUP&&(n.sequence=xA),T?n._onlineOnlyFlag=!0:(P.storeConversationMessage(n),this._applySentMessageControlInfo(n,W),this._emitOnlineMessageSent(n)),n.type===wg.MSG_STREAM?{code:0,data:{message:n,streamMessageID:iA.streamMessageID}}:{code:0,data:{message:n}}}}catch(W){n.status=Yr.FAIL,P.removeRandomOfSentMessage(n.random);let{errorCode:iA}=W||{},EA=W?.errorInfo||W?.message||"";throw this._hasRiskContent(iA)&&(n.hasRiskContent=!0),T||this._isRejectedByRestApi(iA)||P.storeConversationMessage(n),this._reportMessageSendQuality({name:D,message:n,error:W}),new gs({code:iA,message:EA,data:{message:n},moreMessage:`type:${n.type} from:${n.from} to:${n.to}`})}})}_hasRiskContent(n){return n===80001||n===80004}_isRejectedByRestApi(n){return n>=10100&&n<=10200||n>=120001&&n<=13e4}_emitOnlineMessageSent(n){const g=n._isExcludedFromLastMessage?"":n,{conversationID:u,conversationType:E}=n,m=zc(u)?no.TOPIC_NEW_MESSAGE:no.NEW_MESSAGE;fe.notificationCenter.emitInnerEvent(m,{result:{conversationUpdateFieldList:[{conversationID:u,type:E,message:n,lastMessage:g,unreadCount:0}]}})}_applySentMessageControlInfo(n,g){g&&jT(g)&&(g.excludedFromLastMessage===!0&&(n._isExcludedFromLastMessage=!0),g.excludedFromUnreadCount===!0&&(n._isExcludedFromUnreadCount=!0))}_logRateLimitInfo(n,g,u){const E=`from:${n.from} to:${n.to} sequence:${g} messageDropReason:${u}`;fe.ssoLog.warn("messageDropReason",E)}_updateNickAndAvatarOfSentMessageByMe(n){const{messageDataHandler:g}=fe.message||{};let u=!1;const{conversationID:E}=n,m=g.getLatestMsgSentByMe(E);if(m){const{nick:D,avatar:M}=m;D===n.nick&&M===n.avatar||(u=!0),u&&g.updateNickAndAvatarOfSentMessage({conversationID:E,latestNick:n.nick,latestAvatar:n.avatar,isSentByMe:!0})}}_validateBeforeSendGroupMessage(n){return pA(this,void 0,void 0,function*(){var g,u,E;const{to:m,from:D}=n;let M=m,T=Ap.getGroup(M);if(Xr({groupID:M})&&T?.isSupportTopic)throw new gs({code:da.MSG_SEND_GRP_WITH_TOPIC_FAIL});if(zc(m)&&([M]=m.split(sa.TOPIC),T=Ap.getGroup(M)),!T&&typeof((g=Cr.getInstance().getApiMap())===null||g===void 0?void 0:g.getGroupProfile)=="function"){const P=yield Cr.getInstance().getApiMap().getGroupProfile({groupID:M});if(((E=(u=P?.data)===null||u===void 0?void 0:u.group)===null||E===void 0?void 0:E.type)===Lo.GRP_AVCHATROOM){const W=rs({code:da.MSG_SEND_FAIL_NOT_IN_AV,replacement1:D,replacement2:M});throw new gs({code:da.MSG_SEND_FAIL_NOT_IN_AV,message:W})}}return!0})}_reportMessageSendQuality(n){fe.notificationCenter.emitInnerEvent(no.QUALITY_STAT,{label:cI.MESSAGE_SEND_SUCCESS_RATE,data:n})}_getSendProtocol(n){return this._sendProtocolMap.get(n.type)||wh}}var WT=new class{constructor(){this._sparseMessagesByConversation=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new Set}init(){fe.notificationCenter.subscribeInnerEvent(no.LOGOUT,this._reset,this),fe.notificationCenter.subscribeInnerEvent(no.DESTROY,this._dispose,this)}get _messagesByConversation(){return ep.getMessages()}storeConversationMessage(s,n=!1){if(an)return!0;const{conversationID:g}=s;if(!g||(this._messagesByConversation.has(g)||this._messagesByConversation.set(g,new Map),this._shouldSkipStoreMessage(s,n)))return!1;const u=this._getUniqueIdOfMessage(s);return this._messagesByConversation.get(g).set(u,s),this._updateLatestMessageMap(s),!0}_updateLatestMessageMap(s){const{conversationID:n}=s;s.flow==="out"?this._setLatestMsgSentByMe(n,s):n.startsWith("C2C")&&this._setLatestMsgSentByPeer(n,s)}_shouldSkipStoreMessage(s,n){const g=this._getUniqueIdOfMessage(s),u=this._messagesByConversation.get(s.conversationID);if(u?.has(g)){const E=u?.get(g);if(!n||E?.isModified===!0)return!0}return!1}deleteConversationMessage(s){var n;const{conversationID:g=""}=s,u=this._getUniqueIdOfMessage(s);this._messagesByConversation.has(g)&&((n=this._messagesByConversation.get(g))===null||n===void 0||n.delete(u))}modifyConversationMessage(s,n){var g;if(!this._messagesByConversation.has(s)&&!this._sparseMessagesByConversation.has(s))return{isUpdated:!1,message:null};const u=this._getUniqueIdOfMessage(n),E=this._getMessageFromLocalMessage(s,u);if(E){const{messageVersion:m,elements:D,cloudCustomData:M,checkResult:T=0}=n,P=T>1;if(fe.ssoLog.debug("modifyConversationMessage",`conversationToMessageMap modifyConversationMessage localVersion:${E.version} remoteVersion:${m}`),E.versionE.ID===s)||null,n)break;if(!n){const u=Array.from(this._sparseMessagesByConversation.values());for(const E of u)if(n=E.get(s)||null,n)break}return n}deleteConversationMessageList(s){this._messagesByConversation.has(s)&&(this._messagesByConversation.delete(s),this._latestMessageSentByMeMap.delete(s),this._latestMessageSentByPeerMap.delete(s)),this._sparseMessagesByConversation.has(s)&&this._sparseMessagesByConversation.delete(s)}revokeMessage({conversationID:s,sequence:n,random:g,revoker:u}){const E=this._messagesByConversation.get(s);let m=null;if(E){const D=Array.from(E.values());if(m=this._findMessageBySequenceAndRandom({messageList:D,random:g,sequence:n}),m){const M=this._getUniqueIdOfMessage(m);return ep.updateMessage(s,[M],{isRevoked:!0,revoker:u,operation:yc.revoke}),m}}if(this._sparseMessagesByConversation.has(s)){const D=Array.from(this._sparseMessagesByConversation.get(s).values());if(m=this._findMessageBySequenceAndRandom({messageList:D,random:g,sequence:n}),m)return m.isRevoked=!0,m.revoker=u,m}}_findMessageBySequenceAndRandom({messageList:s,sequence:n,random:g}){for(let u=0;u0){const D=new Map([...E,...m.entries()]);this._messagesByConversation.set(g,D),this._updateLatestMessageSentByMe(g),this._updateLatestMessageSentByPeer(g)}return u}storeSparseMessageList(s){if(s.length===0)return;const{conversationID:n}=s[0],g=s.length;this._sparseMessagesByConversation.has(n)||this._sparseMessagesByConversation.set(n,new Map);const u=this._sparseMessagesByConversation.get(n);for(let E=0;E=0;u--)if(g[u].flow==="out"){this._setLatestMsgSentByMe(s,g[u]);break}}}_updateLatestMessageSentByPeer(s){var n;const g=Array.from(((n=this._messagesByConversation.get(s))===null||n===void 0?void 0:n.values())||[]);if(g.length!==0&&s.startsWith("C2C")){for(let u=g.length-1;u>=0;u--)if(g[u].flow==="in"){this._setLatestMsgSentByPeer(s,g[u]);break}}}_getUniqueIdOfMessage(s){const{from:n,to:g,random:u,sequence:E,time:m}=s;return`${n}-${g}-${u}-${E}-${m}`}_setLatestMsgSentByPeer(s,n){this._latestMessageSentByPeerMap.set(s,n)}_setLatestMsgSentByMe(s,n){this._latestMessageSentByMeMap.set(s,n)}getLatestMsgSentByPeer(s){return this._latestMessageSentByPeerMap.get(s)}getLatestMsgSentByMe(s){return this._latestMessageSentByMeMap.get(s)}addRandomOfSentMessage(s){this._randomOfSentMessageList.add(s)}removeRandomOfSentMessage(s){this._randomOfSentMessageList.delete(s)}updateNickAndAvatarOfSentMessage(s){const{conversationID:n="",latestAvatar:g,latestNick:u,isSentByMe:E=!0}=s,m=this._messagesByConversation.get(n);if(!m)return;const D=Array.from(m.values()),M=E?"out":"in";D.forEach(T=>{const{nick:P,avatar:W,flow:iA}=T;iA===M&&(P!==u&&(T.nick=u),W!==g&&(T.avatar=g))})}isInMessageList(s){var n;const{conversationID:g}=s;if(!g||!this._messagesByConversation.has(g))return!1;const u=this._getUniqueIdOfMessage(s);return(n=this._messagesByConversation.get(g))===null||n===void 0?void 0:n.has(u)}isMessageSentByCurrentInstance(s){const{random:n}=s;return this._randomOfSentMessageList.has(n)}getContinuousMessagesByConversation(){return this._messagesByConversation}getLocalMessageList(s){const n=this._messagesByConversation.get(s);return n?[...n.values()]:[]}getSparseMessageList(s){const n=this._sparseMessagesByConversation.get(s);return n?[...n.values()]:[]}_reset(){this._messagesByConversation.clear(),this._latestMessageSentByPeerMap.clear(),this._latestMessageSentByMeMap.clear(),this._randomOfSentMessageList.clear()}_dispose(){this._reset(),fe.notificationCenter.unSubscribeInnerEvent(no.LOGOUT,this._reset,this),fe.notificationCenter.unSubscribeInnerEvent(no.DESTROY,this._dispose,this)}};function Af(s,n){const g=MB.getConversation(s);if(g?.lastMessage){const{lastMessage:u}=g,{lastTime:E,lastSequence:m,version:D}=u,{time:M,sequence:T,messageVersion:P,elements:W,cloudCustomData:iA}=n;E===M&&m===T&&D!==P&&(u.type=W[0].type,u.payload=W[0].content,u.messageForShow=Zc(u.type,u.payload),u.cloudCustomData=iA,u.version=P,MB.updateConversation(s,{lastMessage:u}))}}class _R{init(){Cr.getInstance().registerApi({apiName:"modifyMessage",context:this})}modifyMessage(n){return pA(this,void 0,void 0,function*(){const{to:g,payload:u,sequence:E,conversationType:m,random:D,time:M,from:T,type:P}=n;if(this._canModifyMessageElement(P)){const W=n?._elements||[];W.length>=1&&(W[0].type=P,W[0].content=u)}try{let W=null,iA=null;if(m===Kr.CONV_C2C?W=yield _h(n):m===Kr.CONV_GROUP&&(W=yield wB(n)),W){let EA=`${m}${g}`;return g===Ar()&&m===Kr.CONV_C2C&&(EA=`${m}${T}`),iA={conversationType:m,from:T,to:g,time:M,random:D,sequence:E,elements:W?.elements,cloudCustomData:W?.cloudCustomData,messageVersion:W?.messageVersion,conversationID:EA},this._handleModifyMessageSuccess(iA),{code:0,data:{message:n},successLog:{message:`to:${g}`}}}}catch(W){const{errorCode:iA}=W||{};throw new gs({functionName:"modifyMessage",code:iA,moreMessage:`to:${g}`})}})}_handleModifyMessageSuccess(n){const{conversationID:g}=n,{isUpdated:u,message:E}=fe.message.messageDataHandler.modifyConversationMessage(g,n);u===!0&&fe.notificationCenter.emitOuterEvent(Dr.MESSAGE_MODIFIED,{name:Dr.MESSAGE_MODIFIED,data:[E]}),fe.notificationCenter.emitInnerEvent(no.MESSAGE_MODIFIED,{conversationID:g,message:E}),Af(g,n)}_canModifyMessageElement(n){return[KE.MSG_TEXT,KE.MSG_CUSTOM,KE.MSG_LOCATION,KE.MSG_FACE].includes(n)}}class Nh{init(){const{notificationCenter:n}=fe,{InnerEventSubType:g}=n;ws.getInstance().registerWorkflowStep(Vt.RECEIVE_C2C_NEW_MESSAGE,Kt.HANDLE_C2C_NEW_MESSAGE,this._handleC2CMessagePush,this),ws.getInstance().registerWorkflowStep(Vt.RECEIVE_C2C_NEW_MESSAGE,Kt.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterReceiveNewMessage,this),ws.getInstance().registerWorkflowStep(Vt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Kt.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterSyncUnreadMessage,this),n.subscribeInnerEvent(no.MESSAGE_PUSH,g.C2C_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),n.subscribeInnerEvent(no.MESSAGE_PUSH,g.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),n.subscribeInnerEvent(no.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(n){ws.getInstance().executeWorkflow(Vt.RECEIVE_C2C_NEW_MESSAGE,n)}_handleC2CMessagePush(n){const g=n.data||{},{messageDataHandler:u}=fe.message||{},E=[],m=new Map;return g.C2cMsgArray.forEach(D=>{const M=this._generateC2CMessage(D);this._updateMessageProfile(M);let T=M.isModified===1;u.isMessageSentByCurrentInstance(M)?M.isModified=T:T=!1,M._onlineOnlyFlag?u.isMessageSentByCurrentInstance(M)||E.push(M):RB(M)&&(u.storeConversationMessage(M)&&sp({conversationUpdateFields:m,message:M}),u.isMessageSentByCurrentInstance(M)&&!T||E.push(M))}),{conversationUpdateFieldList:[...m.values()],messages:E}}_emitMessageEventsAfterReceiveNewMessage(n){var g;const{messages:u=[]}=((g=n.result)===null||g===void 0?void 0:g[Kt.HANDLE_C2C_NEW_MESSAGE])||{};this._emitMessageEvents(u)}_emitMessageEventsAfterSyncUnreadMessage(n){var g;const{messages:u=[]}=((g=n.result)===null||g===void 0?void 0:g[Kt.UNREAD_MESSAGE_SYNC])||{};this._emitMessageEvents(u)}_emitMessageEvents(n){const g=n?.filter(E=>E?.isModified===!0)||[];g.length>0&&fe.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:g});const u=n?.filter(E=>!E?.isModified);u.length>0&&fe.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:u})}_generateC2CMessage(n){const g=Kr.CONV_C2C,u=zm(n),E=fe.message.messageFactory.createMessage(Object.assign(Object.assign({},u),{conversationType:g,flow:AE.IN})),{elements:m}=u;return E.setElement(m),E}_updateMessageProfile(n){var g;const{messageDataHandler:u}=fe.message||{},E=(g=fe.store.get("login"))===null||g===void 0?void 0:g.userId,{from:m,nick:D,avatar:M,conversationID:T=""}=n;if(m!==E){const P=u.getLatestMsgSentByPeer(T);if(P){const{nick:W,avatar:iA}=P;r(D)||r(M)?(n.nick=l(W)?W:n.nick,n.avatar=l(iA)?iA:n.avatar):D===W&&M===iA||(u.updateNickAndAvatarOfSentMessage({conversationID:T,latestNick:D,latestAvatar:M,isSentByMe:!1}),this._updateConversationUserProfile({conversationID:T,nick:D,avatar:M}))}}else{const P=u.getLatestMsgSentByMe(T);!P||D===P.nick&&M===P.avatar||u.updateNickAndAvatarOfSentMessage({conversationID:T,latestNick:D,latestAvatar:M,isSentByMe:!0})}}_updateConversationUserProfile(n){const{conversationID:g,nick:u,avatar:E}=n,m=MB.getConversation(g),{userProfile:D={}}=m||{};D.avatar===E&&D.nick===u||MB.updateConversation(g,{userProfile:Object.assign(Object.assign({},D),{nick:u,avatar:E})})}_updateMessageListDueToModify(n){const{conversationID:g}=n,{isUpdated:u,message:E}=fe.message.messageDataHandler.modifyConversationMessage(g,n);u===!0&&fe.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[E]}),fe.notificationCenter.emitInnerEvent("ModifyMessageSuccess",n),Af(g,n)}_handleC2CMessageModify(n){n.C2cMsgModNotifys.forEach(g=>{var u;const E=Kr.CONV_C2C;let m=Zm(g);const{to:D,from:M}=m;let T=`${E}${D}`;D===((u=fe.store.get("login"))===null||u===void 0?void 0:u.userId)&&(T=`${E}${M}`),m=Object.assign({conversationType:E,conversationID:T},m),this._updateMessageListDueToModify(m)})}_dispose(){const{notificationCenter:n}=fe,{InnerEventSubType:g}=n;fe.notificationCenter.unSubscribeInnerEvent(no.MESSAGE_PUSH,g.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),fe.notificationCenter.unSubscribeInnerEvent(no.MESSAGE_PUSH,g.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),fe.notificationCenter.unSubscribeInnerEvent(no.DESTROY,this._dispose,this)}}class Gh{init(){const{notificationCenter:n}=fe,{InnerEventSubType:g}=n;ws.getInstance().registerWorkflowStep(Vt.RECEIVE_GROUP_NEW_MESSAGE,Kt.HANDLE_GROUP_NEW_MESSAGE,this._handleGroupMessagePush,this),ws.getInstance().registerWorkflowStep(Vt.RECEIVE_GROUP_NEW_MESSAGE,Kt.EMIT_GROUP_MESSAGE_EVENT,this._emitMessageEvents,this),n.subscribeInnerEvent(no.MESSAGE_PUSH,g.GROUP_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),n.subscribeInnerEvent(no.MESSAGE_PUSH,g.GROUP_MESSAGE_MODIFIED,this._handleGroupMessageModify,this),n.subscribeInnerEvent(no.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(n){this._canExecuteReceiverNewMessageWorkFlow(n)&&ws.getInstance().executeWorkflow(Vt.RECEIVE_GROUP_NEW_MESSAGE,n)}_handleGroupMessagePush(n){const g=n.data||{},{messageDataHandler:u}=fe.message,E=[],m=new Map,D=g?.GroupMsgArray;return D?.forEach(M=>{if(M.GroupInfo.NotVisible===1)return;const T=this._generateGroupMessage(M);this.updateMessageProfile(T);let P=T.isModified===1;u.isMessageSentByCurrentInstance(T)?T.isModified=P:P=!1,T._onlineOnlyFlag?u.isMessageSentByCurrentInstance(T)||E.push(T):RB(T)&&u.storeConversationMessage(T)&&(E.push(T),sp({conversationUpdateFields:m,message:T}))}),{conversationUpdateFieldList:[...m.values()],messages:E}}_emitMessageEvents(n){var g;const{messages:u}=((g=n.result)===null||g===void 0?void 0:g[Kt.HANDLE_GROUP_NEW_MESSAGE])||{},E=u?.filter(D=>D?.isModified===!0)||[];E.length>0&&fe.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:E});const m=u?.filter(D=>!D?.isModified)||[];m.length>0&&fe.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:m})}_generateGroupMessage(n){const g=Kr.CONV_GROUP,u=JD(n),E=fe.message.messageFactory.createMessage(Object.assign(Object.assign({},u),{conversationType:g,flow:AE.IN})),{elements:m}=u;return E.setElement(m),E}updateMessageProfile(n){var g;const{messageDataHandler:u}=fe.message||{},E=(g=fe.store.get("login"))===null||g===void 0?void 0:g.userId,{from:m,nick:D,avatar:M,conversationID:T="",_elements:P}=n;if(m===E){const W=u.getLatestMsgSentByMe(T);!W||D===W.nick&&M===W.avatar||u.updateNickAndAvatarOfSentMessage({conversationID:T,latestNick:D,latestAvatar:M,isSentByMe:!0})}else if(m===Lo.CONV_SYSTEM){const{operationType:W,memberInfoList:iA,operatorInfo:EA}=P;let RA={};if(Rs(iA)?Rs(EA)||(RA=EA):[Tg.JOINED,Tg.KICKED,Tg.ADMIN_SET,Tg.ADMIN_CANCELED].includes(W)&&(RA=Object.assign({},iA[0])),!Rs(RA)){const{nick:kA="",avatar:xA=""}=RA;n.nick=kA,n.avatar=xA}}}_updateMessageListDueToModify(n){const{conversationID:g}=n,{isUpdated:u,message:E}=fe.message.messageDataHandler.modifyConversationMessage(g,n);u===!0&&fe.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[E]}),Af(g,n)}_handleGroupMessageModify(n){n.GroupMsgModNotifys.forEach(g=>{const u=Kr.CONV_GROUP;let E=HD(g);const{topicID:m,groupID:D}=E,M=m||D,T=`${u}${M}`;E=Object.assign({conversationType:u,conversationID:T,to:M},E),this._updateMessageListDueToModify(E)})}_dispose(){const{notificationCenter:n}=fe,{InnerEventSubType:{GROUP_REALTIME_MESSAGE:g,GROUP_MESSAGE_MODIFIED:u}}=n;n.unSubscribeInnerEvent(no.MESSAGE_PUSH,g,this._handleGroupMessagePush,this),n.unSubscribeInnerEvent(no.MESSAGE_PUSH,u,this._handleGroupMessageModify,this),n.unSubscribeInnerEvent(no.DESTROY,this._dispose,this)}_canExecuteReceiverNewMessageWorkFlow(n){var g,u;const{GroupId:E,GroupType:m}=((u=(g=n?.GroupMsgArray)===null||g===void 0?void 0:g[0])===null||u===void 0?void 0:u.GroupInfo)||{},D=m===La.GRP_AVCHATROOM;return!(!Ap.getGroup(E)&&D)}}var zD=new class{constructor(){this.c2cMessageReceiver=new Nh,this.groupMessageReceiver=new Gh}init(){this.c2cMessageReceiver.init(),this.groupMessageReceiver.init()}};const TR={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)}}},zT={createCustomMessage:!0,sendMessage:!0,modifyMessage:!0};var ZT=new class{constructor(){this._historyMessageListFetchAnchors=new Map,this.completedHistoryConversations=new Set}getGroupRoamingMessagesByAnchor(s){return pA(this,void 0,void 0,function*(){try{const{conversationID:n,count:g,direction:u,sequence:E,messageSequenceList:m,shouldMarkCompleted:D=!1,getType:M}=s,T=n.replace(ka.CONV_GROUP,""),P=[];let W=E;if(u===Kc.BACKWARD){if(typeof E!="number")return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};W=E+g-1}const iA=yield Th({groupID:T,count:g,messageSequence:W,messageSequenceList:m,getType:M});if(iA){const{RspMsgList:EA=[],NextReqMsgSeq:RA=0,IsFinished:kA,InvisibleMsgSeq:xA}=iA,LA=`groupID:${T} sequence:${E} reqSeq:${W} direction:${u} complete:${kA} nextSequence:${RA} remoteMsgCount:${EA.length} invisibleSequenceList:${xA}`,SA=[];for(let ae=0;ae=E),OA&&D&&this.completedHistoryConversations.add(n);const JA=vB(SA);return fe.ssoLog.info("getGroupRoamingMessagesByAnchor",LA),{messageList:JA,invisibleSequenceList:xA,nextReqMessageIDFromServer:RA,hasNoMoreHistoryMessage:OA,serverGroupTipList:P}}}catch(n){const{errorCode:g,errorInfo:u}=n||{};throw new gs({code:g,message:u})}})}clearHistoryMessageListFetchAnchors(s){this._historyMessageListFetchAnchors.delete(s)}isHistoryMessageFetchCompleted(s){return this.completedHistoryConversations.has(s)}_parseMessage(s){var n;const g=ka.CONV_GROUP;s.Event===4&&(s.MsgBody.MsgType=Lo.MSG_GRP_TIP);const u=JD(s),E=Wm.createMessage(Object.assign(Object.assign({},u),{conversationType:g,flow:"in"}));return SB(((n=u.elements)===null||n===void 0?void 0:n.content)||{},E),E.setElement(u.elements),E}getC2CRoamingMessagesByAnchor(s){return pA(this,void 0,void 0,function*(){var n;try{const{conversationID:g,count:u,messageID:E,time:m,direction:D,shouldMarkCompleted:M=!1}=s;let T=m,P="";if(!m){const EA=E?fe.message.messageDataHandler.findMessage(E):null;if(T=EA?.time||0,E&&this._historyMessageListFetchAnchors.has(g)){const RA=this._historyMessageListFetchAnchors.get(g);T=RA.lastMessageTime,P=RA.messageKey}}const W=g.replace(ka.CONV_C2C,""),iA=yield Xm({count:u,lastMessageTime:T,messageKey:P,peerAccount:W,direction:D});if(iA){const{MsgList:EA=[],Complete:RA,MsgKey:kA,LastMsgTime:xA}=iA;this._historyMessageListFetchAnchors.set(g,{messageKey:kA,lastMessageTime:xA});const LA=[];for(let ae=0;ae{const{tag:E,value:m}=u;E&&E.indexOf(XD)>-1?g.profileCustomField.push({key:E,value:m}):bd.has(E)&&(g[bd.get(E)]=m)}),Object.assign(Object.assign({},ef),g)}parseProfileItem(s=[]){const n=[];return s.forEach(g=>{n.push({tag:g.Tag,value:g.Value})}),n}parseProfileList(s=[]){const n=[];return s.forEach(g=>{n.push({tag:g.Tag,value:g.ValueBytes})}),n}convertParamsToProfile(s){const n=[];return Object.keys(s).forEach(g=>{g!==$D&&n.push({tag:xl[g.toUpperCase()],value:s[g]})}),s.profileCustomField&&h(s.profileCustomField)&&s.profileCustomField.forEach(g=>{n.push({tag:g.key,value:g.value})}),n}normalizeProfileFields(s){const n={},g=[];return s.forEach(u=>{const{tag:E,value:m}=u;if(E&&E.indexOf(XD)>-1&&g.push({key:E,value:m}),bd.has(E)&&m!==void 0){const D=bd.get(E);n[D]=m}}),g.length>0&&(n.profileCustomField=g),n}};const{generateProtocolData:GR}=fe.common;function bR(s){return pA(this,void 0,void 0,function*(){const n="profile.portrait_get_all",g={From_Account:Ar(),UserItem:[]};s.forEach(D=>{g.UserItem.push({CustomSequence:0,StandardSequence:0,To_Account:D})});const u=GR({servcmd:n,data:g}),E=`${u.head.seq}${n}`,m=yield fe.channel.sendPacket(u,{requestId:E});if(m)return function(D){const{ActionStatus:M,ErrorCode:T,ErrorDisplay:P,ErrorInfo:W,UserProfileItem:iA}=D,EA=[];return iA.map(RA=>{const{To_Account:kA,CustomSequence:xA,ResultCode:LA,ResultInfo:SA,StandardSequence:OA,ProfileItem:JA}=RA,ae=eE.parseProfileItem(JA);EA.push({userId:kA,customSequence:xA,resultCode:LA,resultInfo:SA,standardSequence:OA,profileItem:ae})}),{actionStatus:M,errorCode:T,errorDisplay:P,errorInfo:W,userProfile:EA}}(m)})}function WE(s){return rc.getFriendMap().has(s)}const{isEmpty:AS}=fe.utils;class tf{constructor(){this._strangerProfileMap=new Map}init(){Cr.getInstance().registerApi({apiName:"getMyProfile",context:this}),Cr.getInstance().registerApi({apiName:"getUserProfile",context:this}),Cr.getInstance().registerApi({apiName:"updateMyProfile",context:this}),this.createProfile=eE.createProfile.bind(eE);const{notificationCenter:n}=fe;ws.getInstance().registerWorkflowStep(Vt.SYNC_SERVER_INFO_AFTER_LOGIN,Kt.USER_PROFILE_SYNC,this.getMyProfileCacheThenServer,this),n.subscribeInnerEvent(no.MESSAGE_PUSH,n.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),n.subscribeInnerEvent(no.LOGOUT,this._reset,this),n.subscribeInnerEvent(no.DESTROY,this._dispose,this)}getMyProfile(){return pA(this,void 0,void 0,function*(){try{const n=Ar(),g=yield bR([n]);if(g){const u=this._handleProfileFormResponse(g)[0];return rc.getUserProfileMap().set(n,u),{code:0,data:u}}}catch(n){const{errorCode:g,errorInfo:u}=n;throw new gs({functionName:"getMyProfile",code:g,message:u})}})}getUserProfile(n){return pA(this,void 0,void 0,function*(){try{let{userIDList:g}=n;const{userIdListToRequest:u,profileFromCache:E}=this._filterRequestAndCacheUsers(g);if(u.length===0)return{code:0,data:E,successLog:{message:`userIDList.length:${g.length}`}};u.length>NR&&(fe.ssoLog.warn("getUserProfile","userIdListToRequest.length > 1000"),u.length=NR);const{data:m,error:D}=yield this._batchFetchUserProfiles(u),M=u.length,T=m.length,P=M-T;if(E.length===0&&M===P&&!AS(D))throw D;if(h(m))return m.forEach(iA=>{WE(iA.userID)?rc.getUserProfileMap().set(iA.userID,iA):this._strangerProfileMap.set(iA.userID,iA)}),{code:0,data:m.concat(E),successLog:{message:`getUserProfile query:${M} success:${T} fail:${P} from cache:${E.length}`}}}catch(g){throw new gs(g)}})}getMyProfileCacheThenServer(){return pA(this,void 0,void 0,function*(){const n=Ar(),g=rc.getUserProfileMap().has(n);return g?{code:0,data:g}:this.getMyProfile()})}updateMyProfile(n){return pA(this,void 0,void 0,function*(){const g=Ar(),u={};for(const m in n)n[m]!==void 0&&(u[m]=n[m]);const E=eE.convertParamsToProfile(u);try{yield function(P){return pA(this,void 0,void 0,function*(){const W="profile.portrait_set",iA=GR({servcmd:W,data:P}),EA=`${iA.head.seq}${W}`,RA=yield fe.channel.sendPacket(iA,{requestId:EA});if(RA){const{ActionStatus:kA,ErrorCode:xA,ErrorDisplay:LA,ErrorInfo:SA}=RA;return{actionStatus:kA,errorCode:xA,errorDisplay:LA,errorInfo:SA}}})}({From_Account:g,ProfileItem:E});const D=rc.getUserProfile(g);let M;M=D?Object.assign(Object.assign({},D),u):eE.createProfile(g,E);const T=!rg(D,M,["lastUpdatedTime"]);return M.lastUpdatedTime=Date.now(),rc.getUserProfileMap().set(g,M),T&&this._emitProfileUpdated(M),{code:0,data:M,successLog:{message:`profileArray: ${fe.utils.safeStringify(E)}`}}}catch(m){const{errorCode:D,errorInfo:M}=m;throw new gs({functionName:"updateMyProfile",code:D,message:M,moreMessage:`params: ${fe.utils.safeStringify(n)}`})}})}updateMyNickAndAvatar(n){return pA(this,void 0,void 0,function*(){const g=Ar(),u=Date.now(),E=rc.getUserProfile(g);let m={};m=E?Object.assign(E,n):eE.createProfile(g,n),m.lastUpdatedTime=u,rc.getUserProfileMap().set(g,m)})}_onProfileDataModify(n){const g=function(m){const{Profile_Account:D,PushType:M,ProfileList:T}=m;return{userId:D,pushType:M,profileList:eE.parseProfileList(T)}}(n.ProfileDataMod[0]);if(AS(g))return;const{isProfileUpdated:u,profile:E}=this._handleProfileModified(g);u&&this._emitProfileUpdated(E)}_emitProfileUpdated(n){fe.notificationCenter.emitInnerEvent(no.PROFILE_UPDATE,{name:no.PROFILE_UPDATE,data:[n]}),fe.notificationCenter.emitOuterEvent(Dr.PROFILE_UPDATED,{name:Dr.PROFILE_UPDATED,data:[n]}),MB.updateConversation(`C2C${n?.userID}`,{userProfile:n})}_dispose(){const{notificationCenter:n}=fe;n.unSubscribeInnerEvent(no.LOGOUT,this._reset,this),n.unSubscribeInnerEvent(no.MESSAGE_PUSH,n.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),n.unSubscribeInnerEvent(no.DESTROY,this._dispose,this),this._reset()}_handleProfileModified(n){const{userId:g,profileList:u}=n,E=rc.getUserProfile(g);if(!(Ar()===g||WE(g)&&E))return{isProfileUpdated:!1,profile:null};const m=eE.normalizeProfileFields(u),D=Object.keys(m).some(W=>W===$D?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,$D)?this._mergeProfileCustomField(E.profileCustomField,m.profileCustomField):E.profileCustomField,P=Object.assign(Object.assign(Object.assign({},E),m),{profileCustomField:T,lastUpdatedTime:M});return rc.getUserProfileMap().set(g,P),{isProfileUpdated:D,profile:P}}_filterRequestAndCacheUsers(n){const g=[],u=[];return n.forEach(E=>{const m=rc.getUserProfileMap().has(E);WE(E)&&m?u.push(rc.getUserProfile(E)):this._isStrangerAndProfileValid(E)?u.push(this._strangerProfileMap.get(E)):g.push(E)}),{userIdListToRequest:g,profileFromCache:u}}_handleProfileFormResponse(n){const{userProfile:g}=n;if(!Array.isArray(g))return[];const u=g.filter(m=>m.userId!=="@TLS#NOT_FOUND"&&m.userId!==""&&!AS(m.profileItem)),E=Date.now();return u.map(m=>{const D=eE.createProfile(m.userId,m.profileItem);return D.lastUpdatedTime=E,D})}_isStrangerAndProfileValid(n){var g;if(!WE(n)){const{lastUpdatedTime:u=0}=this._strangerProfileMap.get(n)||{},E=((g=fe.store.get("cloudConfig"))===null||g===void 0?void 0:g.stranger_profile_expiration_time)||6e5;return Date.now()-u<=E}return!1}_chunkUserIDList(n,g){return Array.from({length:Math.ceil(n.length/g)},(u,E)=>n.slice(E*g,(E+1)*g))}_batchFetchUserProfiles(n){return pA(this,void 0,void 0,function*(){const g=[],u=[];let E={};return this._chunkUserIDList(n,100).forEach(m=>{g.push(bR(m))}),(yield Promise.allSettled(g)).forEach(m=>{if(m.status==="fulfilled"){const D=m.value,M=this._handleProfileFormResponse(D);h(M)&&u.push(...M)}else if(m.status==="rejected"){const{code:D,message:M}=m.reason||{};E={errorCode:D,message:M}}}),{data:u,error:E}})}_isCustomFieldChanged(n=[],g=[]){if(!h(g)||g.length===0)return!1;if(!h(n)||n.length===0)return!0;const u=new Map(n.map(E=>[E.key,E.value]));return g.some(E=>u.get(E.key)!==E.value)}_mergeProfileCustomField(n=[],g=[]){const u=h(n)?n.map(E=>Object.assign({},E)):[];return h(g)&&g.length!==0&&g.forEach(({key:E,value:m})=>{const D=u.find(M=>M.key===E);D?D.value=m:u.push({key:E,value:m})}),u}_reset(){rc.getUserProfileMap().clear(),this._strangerProfileMap.clear()}}const of=new Map,eS=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let s=0,n=eS.length;s>(-2*m&6)):0)E="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(E);try{return decodeURIComponent(escape(g))}catch(u){return console.warn(u),""}}const{isEmpty:$T}=fe.utils,{generateProtocolData:sf}=fe.common;function kR(s){return pA(this,void 0,void 0,function*(){const n="im_open_status.ws_get_user_status",g=sf({servcmd:n,data:{To_Account:s}}),u=`${g.head.seq}${n}`,E=yield fe.channel.sendPacket(g,{requestId:u});if(E)return function(m){const{ErrorCode:D,ErrorInfo:M,ErrorList:T=[],UserStatusList:P=[]}=m,W=P.map(EA=>{const{To_Account:RA,Status:kA,CustomStatus:xA,Detail:LA=[]}=EA;return{userID:RA,statusType:kA,customStatus:rp(xA),onlineDevices:AN(LA)}}),iA=T.map(EA=>{const{To_Account:RA,Invalid_Account:kA,ErrorCode:xA,ErrorInfo:LA}=EA;return{userID:$T(kA)?RA:kA,code:xA,message:LA}});return{errorCode:D,errorInfo:M,successUserList:W,failureUserList:iA}}(E)})}function AN(s){const n=[];return s?.forEach(g=>{const{Platform:u,Status:E}=g;E==="Online"&&n.push(u)}),n}class eN{constructor(){this._customStatus=""}init(){const{notificationCenter:n}=fe;Cr.getInstance().registerApi({apiName:"getUserStatus",context:this}),Cr.getInstance().registerApi({apiName:"setSelfStatus",context:this}),Cr.getInstance().registerApi({apiName:"subscribeUserStatus",context:this}),Cr.getInstance().registerApi({apiName:"unsubscribeUserStatus",context:this}),ws.getInstance().registerWorkflowStep(Vt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Kt.USER_STATUS_UPDATE,this._onReOnline,this),n.subscribeInnerEvent(no.MESSAGE_PUSH,n.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),n.subscribeInnerEvent(no.LOGOUT,this._reset,this),n.subscribeInnerEvent(no.DESTROY,this._dispose,this)}setSelfStatus(n){return pA(this,void 0,void 0,function*(){const g=Ar(),{customStatus:u}=n;try{return yield function(E){return pA(this,void 0,void 0,function*(){const m="im_open_status.ws_set_custom_status",D=sf({servcmd:m,data:{CustomStatus:E}}),M=`${D.head.seq}${m}`,T=yield fe.channel.sendPacket(D,{requestId:M});if(T){const{ErrorCode:P,ErrorInfo:W}=T;return{errorCode:P,errorInfo:W}}})}(u),this._customStatus=u,{code:0,data:{userID:g,statusType:bh,customStatus:u},successLog:{message:`customStatus: ${u}`}}}catch(E){const{errorCode:m,errorInfo:D}=E;throw new gs({functionName:"setSelfStatus",code:m,message:D})}})}getUserStatus(n){return pA(this,void 0,void 0,function*(){const{userIDList:g=[]}=n;if(this._isOnlyMeInArray(g))return this._getMyStatus();const u=yield this._getUserStatus(g);return Object.assign(Object.assign({},u),{successLog:{message:`userIDList length: ${g.length}`}})})}setCustomStatus(n){const g=rp(n);this._customStatus=g}subscribeUserStatus(n){return pA(this,void 0,void 0,function*(){try{const{userIDList:g=[]}=n;this._checkBusinessCapabilityBits("subscribeUserStatus");const u=this._getMaxUserCount("subscribe"),E=this._sliceUserIDList(g,u),m=yield function(M){return pA(this,void 0,void 0,function*(){const{channel:T}=fe,P="im_open_status.ws_status_subscribe",W=sf({servcmd:P,data:{To_Account:M}}),iA=`${W.head.seq}${P}`;return yield T.sendPacket(W,{requestId:iA})})}(E),D=this._parseResponse(m);return{code:0,data:{failureUserList:D},successLog:{message:`userID length:${g.length} failCount: ${D.length}`}}}catch(g){const{errorCode:u}=g;throw new gs({functionName:"subscribeUserStatus",code:u})}})}unsubscribeUserStatus(n){return pA(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("unsubscribeUserStatus");const{userIDList:g=[]}=n,u=this._getMaxUserCount("unsubscribe"),E=this._sliceUserIDList(g,u),m=yield function(M){return pA(this,void 0,void 0,function*(){const{channel:T}=fe,P="im_open_status.ws_status_unsubscribe";let W={};W=M.length===0?{UnsubscribeAll:1}:{To_Account:M};const iA=sf({servcmd:P,data:W}),EA=`${iA.head.seq}${P}`;return yield T.sendPacket(iA,{requestId:EA})})}(E),D=this._parseResponse(m);return{code:0,data:{failureUserList:D},successLog:{message:`userID length:${g.length} failCount: ${D.length}`}}}catch(g){const{errorCode:u}=g;throw new gs({functionName:"unsubscribeUserStatus",code:u})}})}_onUserStatusUpdate(n){const{UserStatusList:g=[]}=n||{},u=g.map(E=>{const{To_Account:m,Status:D,CustomStatus:M,Platform:T}=E,P={userID:m,statusType:D,customStatus:rp(M)};return T&&(P.onlineDevices=T),P});this._emitUserStatusUpdatedEvent(u)}_onReOnline(n){const g=rp(n.data.customStatus);if(this._customStatus===g)return;this._customStatus=g;const u={userID:Ar(),statusType:bh,customStatus:g};this._emitUserStatusUpdatedEvent(u)}_emitUserStatusUpdatedEvent(n){fe.notificationCenter.emitOuterEvent(Dr.USER_STATUS_UPDATED,{name:Dr.USER_STATUS_UPDATED,data:n})}_sliceUserIDList(n,g){return n.slice(0,g)}_parseResponse(n){const{ErrorList:g=[]}=n;return g.map(u=>{const{To_Account:E,Invalid_Account:m,ErrorCode:D,ErrorInfo:M}=u;return{userID:fe.utils.isEmpty(m)?E:m,code:D,message:M}})}_checkBusinessCapabilityBits(n){if(!fe.store.get("commercialConfig").get(XT))throw new gs({functionName:n,code:da.NO_USE,replacement1:n})}_getMaxUserCount(n){const g=fe.store.get("cloudConfig")||{},u={query:{key:"status_query_count",default:500},subscribe:{key:"status_sub_count",default:100},unsubscribe:{key:"status_unsub_count",default:100}},{key:E,default:m}=u[n],D=g[E]||m;return parseInt(D,10)}_getMyStatus(){return{code:0,data:{successUserList:[{userID:Ar(),statusType:bh,customStatus:this._customStatus}],failureUserList:[]}}}_getUserStatus(n){return pA(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("getUserStatus");const g=this._getMaxUserCount("query"),u=this._sliceUserIDList(n,g),E=yield kR(u),{successUserList:m,failureUserList:D}=E||{};return{code:0,data:{successUserList:m,failureUserList:D}}}catch(g){const{errorCode:u}=g;throw new gs({functionName:"getUserStatus",code:u})}})}_isOnlyMeInArray(n){const g=Ar();return n.length===1&&n.indexOf(g)>-1}_dispose(){const{notificationCenter:n}=fe;n.unSubscribeInnerEvent(no.MESSAGE_PUSH,n.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),n.unSubscribeInnerEvent(no.DESTROY,this._dispose,this),n.unSubscribeInnerEvent(no.LOGOUT,this._reset,this),this._reset()}_reset(){this._customStatus=""}}const tS={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(XD))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}}},tN={getMyProfile:!0,getUserProfile:!0,updateMyProfile:!0,setSelfStatus:!0,getUserStatus:!0,subscribeUserStatus:!0,unsubscribeUserStatus:!0};class iN{constructor(){this.userProfile=new tf,this.userStatus=new eN,this.userProfile.init(),this.userStatus.init(),Wc({auth:tN,params:tS})}}function iS(s){const n=[];if(!l(s))return n;const g=s.length;if(g===0)return n;for(let u=g-1;u>=0;u--)s[u]==="1"&&n.push(2**(g-u-1));return n}var kd,wC,Ld;(function(s){s.NOT_START="notStart",s.PENDING="pending",s.RESOLVED="resolved",s.REJECTED="rejected"})(kd||(kd={})),function(s){s[s.C2C=1]="C2C",s[s.GROUP=2]="GROUP"}(wC||(wC={})),function(s){s[s.C2C=8]="C2C",s[s.GROUP=2]="GROUP"}(Ld||(Ld={}));class oS{constructor(){this._name="SyncConversationHandler",this._pagingStatus=kd.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}init(){const{notificationCenter:n}=fe;ws.getInstance().registerWorkflowStep(Vt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Kt.CONVERSATION_RECOVER,this._syncConversationList,this),ws.getInstance().registerWorkflowStep(Vt.SYNC_SERVER_INFO_AFTER_LOGIN,Kt.CONVERSATION_LIST_SYNC,this._syncConversationListAfterLogin,this),n.subscribeInnerEvent(no.LOGOUT,this._reset,this),n.subscribeInnerEvent(no.DESTROY,this._dispose,this),fe.ssoLog.debug(`${this._name}.init`)}isSyncCompleted(){return this._pagingStatus===kd.RESOLVED}_syncConversationListAfterLogin(){return pA(this,void 0,void 0,function*(){return this._pagingStatus=kd.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0,this._syncConversationList()})}_syncConversationList(){return pA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g}}=fe;n.debug("_syncConversationList","start");try{const u=yield this._pagingGetConversationList(!0);this._pagingStatus=kd.RESOLVED;const{conversationList:E=[]}=u||{};return n.info("_syncConversationList",`success count:${E.length}`),u}catch(u){const E=new gs(u);n.error("_syncConversationList",`fail ${g(u)}`,{error:E})}})}_pagingGetConversationList(n){return pA(this,void 0,void 0,function*(){try{const g=[];this._pagingStatus=kd.PENDING;const u=yield function(iA){return pA(this,void 0,void 0,function*(){const{fromAccount:EA,pagingTimeStamp:RA,pagingStartIndex:kA,pagingPinnedTimeStamp:xA,pagingPinnedStartIndex:LA}=iA;return gg({servcmd:"recentcontact.page_get",data:{AssistFlags:31,MsgAssistFlags:15,OrderType:1,From_Account:EA,StartIndex:kA,TimeStamp:RA,TopStartIndex:LA,TopTimeStamp:xA}})})}({fromAccount:Ar(),pagingTimeStamp:n?this._pagingTimeStamp:0,pagingStartIndex:n?this._pagingStartIndex:0,pagingPinnedTimeStamp:n?this._pagingPinnedTimeStamp:0,pagingPinnedStartIndex:n?this._pagingPinnedStartIndex:0}),{CompleteFlag:E,SessionItem:m=[],TimeStamp:D,StartIndex:M,TopTimeStamp:T,TopStartIndex:P}=u||{};let W=[];if(E===1&&(this._pagingStatus=kd.RESOLVED),m.length>0&&(W=this._getConversationOptions(m),g.push(...W)),fe.notificationCenter.emitInnerEvent(no.SYNC_CONVERSATION_LIST,{conversationUpdateFieldList:W}),this._pagingTimeStamp=D,this._pagingStartIndex=M,this._pagingPinnedTimeStamp=T,this._pagingPinnedStartIndex=P,E!==1){const{conversationList:iA}=yield this._pagingGetConversationList(n);g.push(...iA)}return{conversationList:g}}catch(g){throw g}})}_getConversationOptions(n){const{utils:{isUndefined:g}}=fe,u=this._convertConversationKey(n);return this._filterValidConversations(u).map(E=>(g(E.lastMsg)&&(E.lastMsg={elements:[]}),E.type===wC.C2C?this._assembleC2COption(E):this._assembleGroupOption(E)))}_filterValidConversations(n){return n.filter(({type:g,userID:u})=>g===wC.C2C&&!function(E){let m;return E.startsWith(Lo.CONV_C2C)&&(m=E.replace(Lo.CONV_C2C,"")),m==="@TLS#ERROR"||m==="@TLS#NOT_FOUND"}(u)||g===2)}_assembleC2COption(n){var g,u,E,m,D,M,T,P;const W=this._createUserprofile(n);return{conversationID:`${Lo.CONV_C2C}${n.userID}`,type:Lo.CONV_C2C,lastMessage:{lastTime:n.time,lastSequence:n.sequence,fromAccount:n.lastC2CMsgFromAccount,type:!((g=n.lastMsg)===null||g===void 0)&&g.elements[0]?(u=n.lastMsg)===null||u===void 0?void 0:u.elements[0].type:null,payload:!((E=n.lastMsg)===null||E===void 0)&&E.elements[0]?this._amendLayersOverLimitProp(n.lastMsg.elements[0].content):null,cloudCustomData:((M=(D=(m=n.lastMsg)===null||m===void 0?void 0:m.elements)===null||D===void 0?void 0:D[0])===null||M===void 0?void 0:M.cloudCustomData)||"",isRevoked:n.lastMessageFlag===Ld.C2C,onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:this._computeIsPeerRead(n),revoker:((P=(T=n.lastMsg)===null||T===void 0?void 0:T.revokerInfo)===null||P===void 0?void 0:P.revoker)||null},unreadCount:0,userProfile:W,peerReadTime:n.peerReadTime,isPinned:n.isPinned===1,customData:n.customMark||"",markList:iS(n.standardMark),conversationGroupList:[],remark:n.friendRemark||"",messageRemindType:this._transMsgRemindType(n.messageRemindType)}}_createUserprofile(n){var g;const{userID:u,nick:E,peerAvatar:m}=n,D=[{tag:"Tag_Profile_IM_Nick",value:E},{tag:"Tag_Profile_IM_Image",value:m}];return(g=fe.user.userProfile)===null||g===void 0?void 0:g.createProfile(u,D)}_computeIsPeerRead(n){const g=Ar(),{lastC2CMsgFromAccount:u,time:E,c2cPeerReadTime:m}=n;return u===g&&E<=m}_assembleGroupOption(n){var g,u,E,m,D;return{conversationID:`${Lo.CONV_GROUP}${n.groupID}`,type:Lo.CONV_GROUP,lastMessage:Object.assign(Object.assign({lastTime:n.time,lastSequence:n.sequence,fromAccount:n.msgGroupFromAccount},this._patchTypeAndPayload(n)),{cloudCustomData:((E=(u=(g=n.lastMsg)===null||g===void 0?void 0:g.elements)===null||u===void 0?void 0:u[0])===null||E===void 0?void 0:E.cloudCustomData)||"",isRevoked:n.lastMessageFlag===Ld.GROUP,onlineOnlyFlag:!1,nick:n.msgGroupFromNickName||"",nameCard:n.msgGroupFromCardName||"",revoker:((D=(m=n.lastMsg)===null||m===void 0?void 0:m.revokerInfo)===null||D===void 0?void 0:D.revoker)||null}),groupProfile:{groupID:n.groupID,name:n.groupNick,avatar:n.groupImage,type:n.groupType,nextMessageSeq:n.nextMessageSeq},unreadCount:this._computeGroupUnreadCount(n),peerReadTime:0,isPinned:n.isPinned===1,version:0,customData:n.customMark||"",markList:iS(n.standardMark),conversationGroupList:[],messageRemindType:this._transMsgRemindType(n.messageRemindType),subType:n.groupType}}_convertConversationKey(n){return n.map(g=>({type:g.Type,userID:g.To_Account,nick:g.C2cNick,peerAvatar:g.C2cImage,time:g.MsgTimeStamp,sequence:g.MsgSeq,lastC2CMsgFromAccount:g.LastC2cMsgFrom_Account,lastMsg:this._convertLastMsgKey(g.LastMsg),lastMessageFlag:g.LastMsgFlags,c2cPeerReadTime:g.C2cPeerReadTime,peerReadTime:g.C2cPeerReadTime,friendRemark:g.C2cRemark,isPinned:g.TopFlags,standardMark:g.StandardMark,customMark:g.CustomMark,messageRemindType:g.MsgRecvOption,groupID:g.ToAccount,groupNick:g.GroupNick,groupImage:g.GroupImage,groupType:g.GroupType,nextMessageSeq:g.GroupNextMsgSeq,msgGroupFromAccount:g.MsgGroupFrom_Account,msgGroupFromNickName:g.MsgGroupFromNickName,msgGroupFromCardName:g.MsgGroupFromCardName,unreadCount:g.UnreadMsgCount,noUnreadCount:g.GroupIgnoredUnreadSeqCount}))}_convertLastMsgKey(n){var g,u,E;const{utils:{isEmpty:m}}=fe;if(m(n))return null;let D="",M=null;if(!m(n.GroupTips)){const{From_Account:T,GroupName:P}=((g=n.GroupTips)===null||g===void 0?void 0:g.GroupInfo)||{};D=Lo.MSG_GRP_TIP,M=Object.assign(Object.assign({},this._parseContent(D,n.GroupTips.MsgBody)),{groupProfile:{from:T,groupName:P}})}return n.MsgBody&&(D=(u=n.MsgBody[0])===null||u===void 0?void 0:u.MsgType,M=this._parseContent(D,n.MsgBody[0])),{event:n.Event,elements:[{type:D,content:M,cloudCustomData:n.CloudCustomData}],revokerInfo:{revoker:(E=n.RevokerInfo)===null||E===void 0?void 0:E.Revoker_Account}}}_parseContent(n,g){var u;if(!g)return g;const E=fe.message.messageFactory.getElementClass(n);return E?(u=E.parseServerPushElement(g))===null||u===void 0?void 0:u.content:g}_amendLayersOverLimitProp(n){const{LayersOverLimit:g}=n;return Do(n,["LayersOverLimit"]).layersOverLimit=g===1,n}_transMsgRemindType(n){let g="";return n===0?g=Lo.MSG_REMIND_ACPT_AND_NOTE:n===1?g=Lo.MSG_REMIND_DISCARD:n===2?g=Lo.MSG_REMIND_ACPT_NOT_NOTE:n===3&&(g=Lo.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),g}_patchTypeAndPayload(n){var g;const{utils:{isUndefined:u}}=fe,{event:E,elements:m=[]}=n.lastMsg||{};return u(E)?{type:m[0]?m[0].type:null,payload:m[0]?this._amendLayersOverLimitProp(m[0].content):null}:{type:Lo.MSG_GRP_TIP,payload:((g=m?.[0])===null||g===void 0?void 0:g.content)||{}}}_computeGroupUnreadCount(n){const{unreadCount:g=0,noUnreadCount:u=0}=n,E=g-u;return E>0?E:0}_reset(){this._pagingStatus=kd.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}_dispose(){this._reset();const{notificationCenter:n}=fe;n.unSubscribeInnerEvent(no.LOGOUT,this._reset,this),n.unSubscribeInnerEvent(no.DESTROY,this._dispose,this)}}class sS{constructor(){this.syncConversationHandler=new oS,this.syncConversationHandler.init()}}console.log(`TencentCloudLiteChat.VERSION:${Zr}`);var nS={create:function(s){var n,g;const{SDKAppID:u,testEnv:E=!1,devMode:m=!1,unlimitedAVChatRoom:D=!1,scene:M="",oversea:T=!1,instance:P,disableIndependentDomain:W=!1,proxyServer:iA=""}=s;let EA=u;if(!function(kA){if(typeof kA=="number")return!0;const xA=Number(kA);return!Number.isNaN(xA)}(EA))return console.error("Create SDK instance failed. Failed to parse the SDKAppID, please check the arguments"),null;if(EA=Number(EA),Ca.has(EA))return Ca.get(EA);let RA=null;if(P)RA=P,RA._workflowManager&&ws.setInstance(RA._workflowManager),RA._pluginManager&&RA._pluginManager.installBuiltInPlugin(DB),P.isReady()&&((g=(n=ws.getInstance()).executeWorkflow)===null||g===void 0||g.call(n,Vt.SYNC_SERVER_INFO_AFTER_LOGIN));else{const kA=function(){function ae(){return(65536*(1+Math.random())|0).toString(16).substring(1)}return`${ae()+ae()}${ae()}${ae()}${ae()}${ae()}${ae()}${ae()}`}();fe.init({sdkAppId:EA,instanceId:kA,testEnv:E,devMode:m,unlimitedAVChatRoom:D,disableIndependentDomain:W,scene:M,oversea:T,sdkEdition:jm,version:Zr,proxyServer:iA}),ws.getInstance().init(),fe.message=new ZD,fe.user=new iN,fe.login=new Rh,fe.conversation=new sS,au.getInstance().installBuiltInPlugin(DB),RA=Cr.getInstance().exposeApiForClient(),RA._workflowManager=ws.getInstance(),RA._pluginManager=au.getInstance();const{utils:{IS_WORKER_AVAILABLE:xA,USER_AGENT:LA,getPlatformType:SA,isIOSWebView:OA}}=fe,JA=`instanceID:${kA} SDKAppID:${u} platform:${HA} host:${SA()} isIOSWebView:${OA} workerAvailable:${xA} UserAgent:${LA}`;fe.ssoLog.info("sdkConstruct",JA)}return Ca.set(EA,RA),RA},TSignaling:qc,EVENT:Dr,VERSION:Zr,TYPES:Lo};return nS})}(z1)),z1.exports}var KoA=qoA();const ig=yW(KoA);var Z1={exports:{}},joA=Z1.exports,a8;function WoA(){return a8||(a8=1,function(t,i){(function(r,l){t.exports=l()})(joA,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 yt=0;yt"u"&&typeof uni.requireNativePlugin=="function",WA=TA&&uni.getDeviceInfo().platform.toLocaleLowerCase()==="ios",ue=(TA&&uni.getDeviceInfo().platform.toLocaleLowerCase(),lA||sA||mA||IA||cA||TA),Ce=U!==void 0&&(U.nativeModuleProxy!==void 0||U.ReactNative!==void 0),xe=sA?qq:mA?tt:IA?swan:cA?my:lA?wx:TA?uni:{},Qe=function(re){if(G(re)!=="object"||re===null)return!1;var qe=Object.getPrototypeOf(re);if(qe===null)return!0;for(var yt=qe;Object.getPrototypeOf(yt)!==null;)yt=Object.getPrototypeOf(yt);return qe===yt};function ut(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(Qe(re)){for(var qe in re)if(Object.prototype.hasOwnProperty.call(re,qe))return!1;return!0}return!1}var ft=function(){return I(function re(){r(this,re),this._n="WebRequest"},[{key:"request",value:function(re,qe){var yt=this,Me="".concat(this._n,".request"),Oe=re.downloadUrl||"",gt=(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(Me," URL:").concat(Fi)),re.qs){var To=function(ki){var ns=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"&",jo=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"=";return ut(ki)?"":Qe(ki)?Object.keys(ki).map(function(Ao){var Zt=encodeURIComponent(Ao)+jo;return Array.isArray(ki[Ao])?ki[Ao].map(function(oo){return Zt+encodeURIComponent(oo)}).join(ns):Zt+encodeURIComponent(ki[Ao])}).filter(Boolean).join(ns):void 0}(re.qs);To&&(Fi+="".concat(Fi.indexOf("?")===-1?"?":"&").concat(To))}var io=new XMLHttpRequest;io.open(gt,Fi,!0),io.responseType=re.dataType||"text";var Eo=re.headers||{};if(re.uploadByIP&&(Eo=w(w({},Eo),{},{host:re.uploadIP})),!ut(Eo))for(var Vs in Eo)Eo.hasOwnProperty(Vs)&&Vs.toLowerCase()!=="content-length"&&Vs.toLowerCase()!=="user-agent"&&Vs.toLowerCase()!=="origin"&&Vs.toLowerCase()!=="host"&&io.setRequestHeader(Vs,Eo[Vs]);return io.onload=function(){if(io.status===200)qe(null,yt._xhrRes(io,yt._xhrBody(io,Oe,re.uploadByIP&&re.uploadIP),Eo));else{if(re.uploadIP&&re.url.indexOf(re.uploadIP)===-1)return re.url=function(ns,jo){return ns.replace(/^http(s)?:\/\/(.*?)\//,"https://".concat(jo,"/"))}(re.url,re.uploadIP),re.uploadByIP=!0,yt.request(re,qe);var ki={code:io.status,message:JSON.stringify(io.responseText)};qe(ki,yt._xhrRes(io,yt._xhrBody(io,Oe,re.uploadByIP&&re.uploadIP),Eo))}},io.onerror=function(ki){var ns=yt._xhrBody(io,Oe,re.uploadByIP&&re.uploadIP),jo={code:io.status,message:JSON.stringify(io.responseText)};ns||io.statusText||io.status!==0||(ki.message="CORS blocked or network error"),qe(jo,yt._xhrRes(io,ns)),jo=null},re.onProgress&&io.upload&&(io.upload.onprogress=function(ki){var ns=ki.total,jo=ki.loaded,Ao=Math.floor(100*jo/ns);re.onProgress({total:ns,loaded:jo,percent:(Ao>=100?100:Ao)/100})}),io.send(re.resources),io}},{key:"_xhrRes",value:function(re,qe){var yt={};return re.getAllResponseHeaders().trim().split(`
-`).forEach(function(Me){if(Me){var Oe=Me.indexOf(":"),gt=Me.substr(0,Oe).trim().toLowerCase(),Fi=Me.substr(Oe+1).trim();yt[gt]=Fi}}),{statusCode:re.status,statusMessage:re.statusText,headers:yt,data:qe}}},{key:"_xhrBody",value:function(re,qe,yt){return re.status===200&&qe?{location:qe,uploadIP:yt}:{response:re.responseText,uploadIP:yt}}}])}(),je=["unknown","image","video","audio","log"],Mt=["name"],jt=function(){return I(function re(){r(this,re)},[{key:"request",value:function(re,qe){var yt=this,Me=re.resources,Oe=Me===void 0?"":Me,gt=re.headers,Fi=gt===void 0?{}:gt,To=re.url,io=re.downloadUrl,Eo=io===void 0?"":io,Vs=To,ki=null,ns=Eo.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/),jo=decodeURIComponent(ns[3]),Ao=jo.indexOf("?")>-1?jo.split("?")[0]:jo,Zt={key:re.fileKey?re.fileKey:Ao,success_action_status:200,"Content-Type":""},oo={};if(WA){var bi=To.split("?sign=");if(bi.length>1){var vs=bi[1];Vs="".concat(bi[0],"?sign=").concat(encodeURIComponent("".concat(vs))),oo.sign=decodeURIComponent(vs),oo.signature=decodeURIComponent(vs)}}var HA={url:Vs,header:Fi,name:"file",filePath:Oe,formData:w(w({},Zt),oo),timeout:re.timeout||3e5};if(cA){var ce=HA;ce.name,HA=w(w({},function(Ve,Ot){if(Ve==null)return{};var nt,It,ei=function(be,Ze){if(be==null)return{};var wt={};for(var Nt in be)if({}.hasOwnProperty.call(be,Nt)){if(Ze.includes(Nt))continue;wt[Nt]=be[Nt]}return wt}(Ve,Ot);if(Object.getOwnPropertySymbols){var ti=Object.getOwnPropertySymbols(Ve);for(It=0;It=3e4&&(this.systemClockOffset=To-Fi,qe=!0)}else Math.floor(re.statusCode/100)===5&&(qe=!0)}return qe}}],[{key:"getVersion",value:function(){return"1.4.3"}}])}()})}(Z1)),Z1.exports}var zoA=WoA();const ZoA=yW(zoA);/**
+`],{type:"application/javascript"});this._worker=new Worker(URL.createObjectURL(g)),this._worker.postMessage({type:Dr,url:r})}send(r){var g,u;try{(g=this._worker)===null||g===void 0||g.postMessage({type:Us,data:r})}catch(E){(u=this._onSendFail)===null||u===void 0||u.call(this,E)}}bindSocketHandlers(r){const{onOpen:g,onMessage:u,onClose:E,onError:m,onSendFail:D}=r;if(this._worker){const M={[fs]:g,[as]:u,[wu]:E,[Wa]:m,[hs]:D};this._onSendFail=D,this._worker.onmessage=T=>{var P;const{type:W}=T?.data||{};typeof M[W]=="function"&&((P=M[W])===null||P===void 0||P.call(M,T?.data))}}}unbindSocketHandlers(){this._worker&&(this._worker.onmessage=null)}disconnect(){this._worker&&(this._worker.postMessage({type:Jc}),this._worker.terminate(),this._worker=null),this._blobUrl&&(URL.revokeObjectURL(this._blobUrl),this._blobUrl=null)}}class qI{}var es,eo=new class{constructor(){this._store=new Map}get(s){return this._store.get(s)}getStorage(s){return Gi?oi?my.getStorageSync({key:s}).data:Ao.getStorageSync(s):this._canUseLocalStorage()?localStorage.getItem(s):{}}set(s,r){const g=this._store.get(s)||{};r instanceof Map?this._store.set(s,r):this._store.set(s,Object.assign(Object.assign({},g),r))}setStorage(s,r){Gi?oi?my.setStorageSync({key:s,data:JSON.stringify(r)}):Ao.setStorageSync(s,JSON.stringify(r)):this._canUseLocalStorage()&&localStorage.setItem(s,JSON.stringify(r))}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(r){return this._socket=Ao.connectSocket({url:r,header:{"content-type":"application/json"},multiple:!0,complete:()=>{}}),this._socket}send(r){var g;(g=this._socket)===null||g===void 0||g.send({data:r,fail:this._onSendFail})}bindSocketHandlers(r){const{onOpen:g,onMessage:u,onClose:E,onError:m,onSendFail:D}=r;this._socket&&(this._socket.onClose(E),this._socket.onOpen(g),this._socket.onMessage(M=>u(M?.data)),this._socket.onError(()=>m),this._onSendFail=D)}unbindSocketHandlers(){this._socket&&(this._socket.onClose(()=>{}),this._socket.onOpen(()=>{}),this._socket.onMessage(()=>{}),this._socket.onError(()=>{}))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}(function(s){s[s.CONNECTED=0]="CONNECTED",s[s.CONNECTING=1]="CONNECTING",s[s.DISCONNECTED=2]="DISCONNECTED"})(es||(es={}));class ng{constructor(r){this._url="",this._readyState=es.DISCONNECTED,this._url=r,this._id=L(),this._emitter=new Pn,oi?this._socket=new pc:ct||Co||Dt||Ve||Ni||Pt?this._socket=new cn({onError:this._onError.bind(this)}):an?this._socket=new qI:this._canUseWebWorker()?this._socket=new sg:this._socket=new Ml,this.connect()}connect(){this.doOpen(),this._bindSocketHandlers()}doOpen(){[es.CONNECTED,es.CONNECTING].includes(this._readyState)||(this._readyState=es.CONNECTING,this._ws=this._socket.connectSocket(this._url))}send(r){this._readyState!==es.CONNECTED?this.reconnect():this._socket.send(r)}reconnect(){[es.CONNECTED,es.CONNECTING].includes(this._readyState)||(this.disconnect(),this.doOpen())}getId(){return this._id}on(r,g,u){this._emitter.on(r,g,u)}off(r,g,u){this._emitter.off(r,g,u)}isConnected(){return this._readyState===es.CONNECTED}disconnect(){this._readyState=es.DISCONNECTED,this._unbindSocketHandlers(),this._socket.disconnect()}_onOpen(r){this._readyState===es.CONNECTING&&(this._readyState=es.CONNECTED,this._emitter.emit("connect",{socketId:this._id,event:r}))}_onMessage(r){this._emitter.emit("message",r)}_onClose(r){this._readyState=es.DISCONNECTED,this._emitter.emit("close",{socketId:this._id,event:r})}_onError(r){this._readyState=es.DISCONNECTED,this._emitter.emit("error",{socketId:this._id,error:r})}_onSendFail(r){this._readyState=es.DISCONNECTED,this._emitter.emit("sendFail",{socketId:this._id,error:r})}_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 r=eo.get("cloudConfig")||{};return(n(r.isWorkerEnabled)||r.isWorkerEnabled==="1")&&Go}}const Dg={[gt.SINGAPORE]:[[2e7,3e7],[172e7,173e7]],[gt.KOREA]:[[3e7,4e7],[173e7,174e7]],[gt.GERMANY]:[[4e7,5e7],[174e7,175e7]],[gt.IND]:[[5e7,6e7],[175e7,176e7]],[gt.JPN]:[[6e7,7e7],[176e7,177e7]],[gt.USA]:[[7e7,8e7],[177e7,178e7]],[gt.INDONESIA]:[[8e7,9e7],[178e7,179e7]],[gt.KSA]:[[9e7,1e8],[179e7,18e8]]};function ua(s){var r;if(!((r=eo.get("instance"))===null||r===void 0)&&r.oversea)return gt.OVERSEA;for(const g of Object.keys(Dg))for(const[u,E]of Dg[g])if(s>=u&&s`${oA}=${W[oA]}`).join("&"));var W;return g?`${s}/binfo?${P}&compress=gzip`:`${s}/info?${P}`}function Hs(s){const r=eo.get("instance"),{sdkAppId:g,testEnv:u,proxyServer:E}=r,m=ua(g);if(u)return Kn(dt.TEST[m].DEFAULT,{isBinary:s});if(!Rs(E))return Kn(E,{isBinary:s});const D=dt.PRODUCTION[m],M=zt&&D.ANYCAST,T=zt,P=!!D.BACKUP_CN;return Kn({[bo.INITIAL]:()=>(To=bo.DEFAULT,D.DEFAULT),[bo.DEFAULT]:()=>(To=bo.IPV6,D.IPV6),[bo.IPV6]:()=>(To=bo.BACKUP,D.BACKUP),[bo.BACKUP]:()=>T?(To=bo.BACKUP_WEB_ONLY,function(W){const oA=Math.floor(10001*Math.random())+1e4;return W.replace("*",String(oA))}(D.BACKUP_WEB_ONLY)):P?(To=bo.BACKUP_CN,D.BACKUP_CN):M?(To=bo.ANYCAST,D.ANYCAST):D.DEFAULT,[bo.BACKUP_WEB_ONLY]:()=>P?(To=bo.BACKUP_CN,D.BACKUP_CN):M?(To=bo.ANYCAST,D.ANYCAST):D.DEFAULT,[bo.BACKUP_CN]:()=>(To=M?bo.ANYCAST:bo.DEFAULT,D[To]),[bo.ANYCAST]:()=>(To=bo.DEFAULT,D.ANYCAST="",D.DEFAULT)}[To](),{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,r){const g=Date.now(),u=g-s;this._timeOffsetWithServer=r+u-g}};const mc=16;var fn=new class{constructor(){this._tasks=[],this._timer=null,this._taskMap=new Map}_addTaskToScheduler(s){const{id:r}=s;this.removeTask(r),this._tasks.push(s),this._taskMap.set(r,s),this._sort(),this._scheduleNextTask()}_createTask(s){const{id:r,callback:g,context:u,isOnce:E=!1,intervalMs:m=mc}=s,D=Math.max(m,mc);return{id:r,nextExecuteTime:Date.now()+D,intervalMs:m,callback:g,context:u,isOnce:E}}addTask(s){const r=this._createTask(s);this._addTaskToScheduler(r)}addOnceTask(s){const r=this._createTask(Object.assign(Object.assign({},s),{isOnce:!0}));this._addTaskToScheduler(r)}removeTask(s){const r=this._tasks.findIndex(g=>g.id===s);r>-1&&(this._tasks.splice(r,1),this._taskMap.delete(s),this._scheduleNextTask())}updateTaskInterval(s,r){const g=this._taskMap.get(s);g&&(g.intervalMs=r,g.nextExecuteTime=Date.now()+r,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,r)=>s.nextExecuteTime-r.nextExecuteTime)}_scheduleNextTask(){this._timer&&(clearTimeout(this._timer),this._timer=null);const s=this._tasks[0];if(s){const r=Math.max(0,s.nextExecuteTime-Date.now());this._timer=setTimeout(()=>this._execute(),r)}}_execute(){const s=Date.now();for(;this._tasks.length&&this._tasks[0].nextExecuteTime<=s;){const r=this._tasks[0];try{r.context?r.callback.call(r.context):r.callback(),r.isOnce?this.removeTask(r.id):(r.nextExecuteTime=s+r.intervalMs,this._sort())}catch(g){console.warn(`Task ${r.id} execution failed:`,g),r.isOnce&&this.removeTask(r.id)}}this._scheduleNextTask()}};function Ga(s){const r=[];for(let g=0;g=55296&&u<=56319){const E=s.charCodeAt(++g)-56320+(u-55296<<10)+65536;r.push(240|E>>18,128|E>>12&63,128|E>>6&63,128|63&E)}else u<=127?r.push(u):u<=2047?r.push(192|u>>6,128|63&u):r.push(224|u>>12,128|u>>6&63,128|63&u)}return new Uint8Array(r)}function In(s){const r=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"?r[g]=s[g]:r[g]=In(s[g]));return r}function ys(s,r){if(BA.includes(s))return 0;const g=Ga(JSON.stringify(r));let u=4294967295;const{length:E}=g;for(let m=0;m>>=1:u=u>>>1^3988292384}return(4294967295^u)>>>0}function Ea(s){const{servcmd:r,data:g}=s,u=function(m){const D=eo.get("login")||{},M=eo.get("instance")||{};return{servcmd:m,ver:"v4",platform:VA,websdkappid:537048168,websdkversion:"1.7.3",a2:D.a2Key||void 0,tinyid:D.tinyID||void 0,status_instid:D.statusInstanceId||0,sdkappid:M.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:D.a2Key?void 0:D.userId,usersig:D.a2Key?void 0:D.userSig,sdkability:478343027,sdkability_ext:lA(""),cappid:M.applicationID||0,tjgID:"",seq:Sa(),cs:0}}(r),E=In(g);return u.cs=ys(r,E),{head:u,body:E}}function yn(s){const{servcmd:r,data:g}=s,u=function(m){const D=eo.get("login")||{},M=eo.get("instance")||{};return{servcmd:m,ver:"v4",platform:VA,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:M.sdkAppId,contenttype:"",reqtime:Math.floor(Date.now()/1e3),identifier:"",usersig:"",status_instid:D.statusInstanceId||0,sdkability:478343027,sdkability_ext:lA(""),cappid:M.applicationID||0,seq:Sa(),cs:0}}(r),E=In(g);return u.cs=ys(r,E),{head:u,body:E}}let ba=L();function Sa(){return ba=ba<2415919103?ba+1:L(),ba}function $(){var s;const r=eo.get("login")||{},g=eo.get("instance")||{};return{sdk_type:30,sdk_app_id:g.sdkAppId,sdk_version:"1.6.18",tiny_id:Number(r.tinyID),user_id:r.userId||((s=eo.get("webPush"))===null||s===void 0?void 0:s.userId),platform:VA,instance_id:g.instanceId,trace_id:new Date().getTime()}}var j,vA=Object.freeze({__proto__:null,calcBodyCRC:ys,filterProtocolDataInvalidFields:In,generateCosSpecifiedData:function(s){const{servcmd:r,data:g}=s,u=function(m){const D=eo.get("login")||{},M=eo.get("instance")||{};return{servcmd:m,ver:"v4",platform:VA,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:M.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:D.userId,usersig:D.userSig,status_instid:D.statusInstanceId||0,sdkability:478343027,sdkability_ext:lA(""),cappid:M.applicationID||0,seq:Sa(),cs:0}}(r),E=In(g);return u.cs=ys(r,E),{head:u,body:E}},generateProtocolData:Ea,generateSSOLogProtocolData:yn,generateSequence:Sa,getCommonHead:$,getHostSite:ua,taskScheduler:fn,timeManager:Sg});(function(s){s[s.info=4]="info",s[s.warning=5]="warning",s[s.error=6]="error"})(j||(j={}));const jA={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 oe{constructor(r){this.level=j.info,this._canSendLog=!0,this._logCreatedAt=Sg.getServerTimeMs(),this.timestamp=0,this.networkType=8,this.code=0,this.moreMessage="",this.method="",this.message="",this.costTime=0,this.duplicate=!1,this.eventType=0,this.uiPlatform=this._getUiPlatform(),this._sdkEdition=this._getSDKEdition();const{method:g,eventType:u=0,message:E="",costTime:m=0,error:D,uiPlatform:M,moreMessage:T="",code:P=0,startTime:W=0}=r||{};this.eventType=u,this.method=g,this.message=E,this.costTime=m,this.moreMessage=`${T} startTime:${W}`,this.code=P,D&&this.setError(D),Rs(M)||(this.uiPlatform=M)}setMoreMessage(r){this.moreMessage=`${this.moreMessage} ${r}`}updateLogCreatedAtByTimeOffset(){this._logCreatedAt+=Sg.getTimeOffsetWithServer()}end(r=!1){this._canSendLog&&(this._canSendLog=!1,this.timestamp=Sg.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe()),r&&this._ssoLogModule.uploadSSOLogData())}setError(r){var g;return r instanceof Error?this._canSendLog?(!((g=eo.get("netWorkMonitor"))===null||g===void 0)&&g.isNetworkOnline&&(r.errorCode&&(this.code=r.errorCode),r.errorMessage&&this.setMoreMessage(r.errorMessage)),this.level=j.error,this):this:(console.warn("SSOLogData.setError value not instanceof Error, please check!"),this)}setLogInfo(r){return Object.keys(r).forEach(g=>{Object.keys(jA).includes(g)&&(this[g]=r[g])}),this}setSSOLogModule(r){this._ssoLogModule=r}_convertSSOLogDataKeyToServe(){const r={};return Object.keys(this).forEach(g=>{const u=g;jA[u]&&(r[jA[u]]=this[u])}),r}_getUiPlatform(){var r;const g=(r=eo.get("instance"))===null||r===void 0?void 0:r.scene;if(typeof g=="string"){const u=Number(g);return isNaN(u)?void 0:u}}_getSDKEdition(){var r;return(r=eo.get("instance"))===null||r===void 0?void 0:r.sdkEdition}}var ye;(function(s){s.RECONNECTED="reconnected",s.CLOUD_CONFIG_UPDATE="cloud_config_update",s.SOCKET_DISCONNECTED="socket_disconnected"})(ye||(ye={}));var He=ye;const Pe=20,rt=6e4,ht=[4,5,6],_t="report-logger";var Vt=new class{constructor(){this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._reportLevel=[4,5,6],this._minThreshold=Pe,this._maxThreshold=100,this._waitingTime=rt,this._lastReportAt=Date.now(),this._ssoLogMap=new Map,this._logLevel=IA.DEBUG,this._throttleConfig={global:{throttleTime:me,maxCount:ae},single:{throttleTime:ZA,maxCount:KA}},this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap=new Map,gn.subscribeInnerEvent(He.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),fn.addTask({id:_t,intervalMs:1e3,callback:this._checkAndReportIfDue,context:this}),this._logQueue=[],this._savePlatFormInfo()}_handleCloudConfigUpdate(s){const{evt_rpt_threshold:r=Pe,evt_rpt_waiting:g=rt,evt_rpt_level:u=ht,evt_rpt_sdkappid_bl:E="",evt_rpt_tinyid_wl:m="",evt_rpt_global_throttle_time:D=me,evt_rpt_global_throttle_count:M=ae,evt_rpt_single_throttle_time:T=ZA,evt_rpt_single_throttle_count:P=KA}=s||{};this._sdkAppIdBlackList=E.split(",").map(W=>Number(W)),this._waitingTime=Number(g),this._minThreshold=r,this._reportLevel=u,this._tinyIdWhiteList=m.split(","),this._throttleConfig={global:{throttleTime:D,maxCount:M},single:{throttleTime:T,maxCount:P}}}createSSOLogData(s){const r=new oe(s);return r.setSSOLogModule(this),this._ssoLogMap.set(s.method,r),r}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,r="",g){this._log(IA.DEBUG,s,r,g)}info(s,r="",g){this._log(IA.INFO,s,r,g)}warn(s,r="",g){this._log(IA.WARN,s,r,g)}error(s,r="",g){this._log(IA.ERROR,s,r,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 r=this._filterLogs(s);if(r.length===0)return void(this._lastReportAt=Date.now());const g={Header:$(),Event:r};Rs(g.Header.user_id)||(yield function(u){const E="imopenstat.tim_web_report_v2",m=yn({servcmd:E,data:u}),D=`${m.head.seq}${E}`;return Se.sendPacket(m,{requestId:D})}(g))}catch(r){this._requeueFailedLogs(s),this.debug("uploadSSOLogData",en(r))}finally{this._lastReportAt=Date.now()}})}_requeueFailedLogs(s){this._logQueue=s.concat(this._logQueue);const r=this._logQueue.length-200;r>0&&(this._logQueue.splice(0,r),this.debug("uploadSSOLogData",`log queue overflow, dropped ${r} oldest logs`))}_savePlatFormInfo(){var s,r;if(ct){const g=(r=(s=wx.getAccountInfoSync)===null||s===void 0?void 0:s.call(wx))===null||r===void 0?void 0:r.miniProgram;if(g){const{appId:u,envVersion:E}=g;eo.set("instance",{appId:u,envVersion:E})}}else zt&&eo.set("instance",{href:window.location.href})}_filterLogs(s){const{tinyID:r}=eo.get("login")||{},{sdkAppId:g}=eo.get("instance")||{};return this._sdkAppIdBlackList.includes(g)&&!this._tinyIdWhiteList.includes(r)?[]:s.filter(u=>this._reportLevel.includes(u.level))}_checkThrottle(s){return!!this._checkGlobalThrottle()||this._checkSingleThrottle(s)}_checkGlobalThrottle(){const s=Date.now();if(s-this._globalThrottle.startTime>=this._throttleConfig.global.throttleTime)this._globalThrottle.count=1,this._globalThrottle.startTime=s;else if(this._globalThrottle.count++,this._globalThrottle.count>this._throttleConfig.global.maxCount)return!0;return!1}_checkSingleThrottle(s){const r=Date.now(),g=this._singleThrottleMap.get(s);return g?r-g.startTime>=this._throttleConfig.single.throttleTime?(g.count=1,g.startTime=r,!1):g.count>=this._throttleConfig.single.maxCount||(g.count++,!1):(this._singleThrottleMap.set(s,{count:1,startTime:r}),!1)}_shouldLog(s){return s>=this._logLevel&&this._logLevel!==IA.NONE}_shouldReport(s){return this._reportLevel.includes(HA[s])}_formatLog(s,r,g,u){const E=new Date,m=`${E.getHours()}:${E.getMinutes()}:${E.getSeconds()}:${E.getMilliseconds()}`,D=`<${IA[s]}>`;return ve||Gi?[`${gA} [${m}] ${D} [${r}] ${g}`]:["%c%s%c%s","background:#0abf5b; padding:1px; border-radius:3px; color: #fff",gA,"",`[${m}] ${D} [${r}] ${g} params: ${en(u)}`]}_log(s,r,g,u){if(this._shouldLog(s)){const E=this._formatLog(s,r,g,u);RA[s].apply(console,E)}if(this._shouldReport(s)){const E=this._getThrottleKey(r,g,u);this._checkThrottle(E)||this.createSSOLogData(Object.assign(Object.assign({message:g},u),{method:r})).end()}}_getThrottleKey(s,r,g){const u=`${s}${r}${en(Object.assign(Object.assign({},g),{costTime:""}))}`,E=Ga(JSON.stringify(u));let m=4294967295;const{length:D}=E;for(let M=0;M>>=1:m=m>>>1^3988292384}return`${(4294967295^m)>>>0}`}reset(){console.log("SSO_LOG_MODULE.reset"),fn.removeTask(_t),gn.unSubscribeInnerEvent(He.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),this._lastReportAt=0,this.uploadSSOLogData(),this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._minThreshold=Pe,this._maxThreshold=100,this._waitingTime=rt,this._logQueue=[],this._logLevel=IA.DEBUG,this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap.clear()}};const ui=15e3,It="Channel",Yt="channel_schedule_task",qi="channel_reconnect_task",Wi="connected",qs="connecting",vi="disconnected",zo=1e3,Mg="network_status_change",ar="activity_status_change",Sr="send_fail",Yn="reconnect_failed",vl="socket_error",Ks="socket_close";function gI(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(r){return typeof r}:function(r){return r&&typeof Symbol=="function"&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r},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 _u,Ma={exports:{}},Rl=(_u||(_u=1,function(s){s.exports=function r(g,u,E){function m(T,P){if(!u[T]){if(!g[T]){if(!P&&fc)return fc(T);if(D)return D(T,!0);var W=new Error("Cannot find module '"+T+"'");throw W.code="MODULE_NOT_FOUND",W}var oA=u[T]={exports:{}};g[T][0].call(oA.exports,function(EA){return m(g[T][1][EA]||EA)},oA,oA.exports,r,g,u,E)}return u[T].exports}for(var D=fc,M=0;M>>6:(EA<65536?oA[xA++]=224|EA>>>12:(oA[xA++]=240|EA>>>18,oA[xA++]=128|EA>>>12&63),oA[xA++]=128|EA>>>6&63),oA[xA++]=128|63&EA);return oA},u.buf2binstring=function(W){return P(W,W.length)},u.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)},u.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(r,g,u){g.exports=function(E,m,D,M){for(var T=65535&E,P=E>>>16&65535,W=0;D!==0;){for(D-=W=2e3>>1:m>>>1;D[M]=m}return D}();g.exports=function(m,D,M,T){var P=E,W=T+M;m^=-1;for(var oA=T;oA>>8^P[255&(m^D[oA])];return-1^m}},{}],6:[function(r,g,u){g.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],7:[function(r,g,u){g.exports=function(E,m){var D,M,T,P,W,oA,EA,wA,kA,xA,LA,SA,OA,qA,Ie,le,bi,ki,Ot,Li,cs,Re,St,UA,ai;D=E.state,M=E.next_in,UA=E.input,T=M+(E.avail_in-5),P=E.next_out,ai=E.output,W=P-(m-E.avail_out),oA=P+(E.avail_out-257),EA=D.dmax,wA=D.wsize,kA=D.whave,xA=D.wnext,LA=D.window,SA=D.hold,OA=D.bits,qA=D.lencode,Ie=D.distcode,le=(1<>>=Ot=ki>>>24,OA-=Ot,(Ot=ki>>>16&255)==0)ai[P++]=65535&ki;else{if(!(16&Ot)){if(!(64&Ot)){ki=qA[(65535&ki)+(SA&(1<>>=Ot,OA-=Ot),OA<15&&(SA+=UA[M++]<>>=Ot=ki>>>24,OA-=Ot,!(16&(Ot=ki>>>16&255))){if(!(64&Ot)){ki=Ie[(65535&ki)+(SA&(1<>>=Ot,OA-=Ot,(Ot=P-W)>3,SA&=(1<<(OA-=Li<<3))-1,E.next_in=M,E.next_out=P,E.avail_in=M>>24&255)+(Re>>>8&65280)+((65280&Re)<<8)+((255&Re)<<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(Re){var St;return Re&&Re.state?(St=Re.state,Re.total_in=Re.total_out=St.total=0,Re.msg="",St.wrap&&(Re.adler=1&St.wrap),St.mode=wA,St.last=0,St.havedict=0,St.dmax=32768,St.head=null,St.hold=0,St.bits=0,St.lencode=St.lendyn=new E.Buf32(kA),St.distcode=St.distdyn=new E.Buf32(xA),St.sane=1,St.back=-1,oA):EA}function qA(Re){var St;return Re&&Re.state?((St=Re.state).wsize=0,St.whave=0,St.wnext=0,OA(Re)):EA}function Ie(Re,St){var UA,ai;return Re&&Re.state?(ai=Re.state,St<0?(UA=0,St=-St):(UA=1+(St>>4),St<48&&(St&=15)),St&&(St<8||15=Ui.wsize?(E.arraySet(Ui.window,St,UA-Ui.wsize,Ui.wsize,0),Ui.wnext=0,Ui.whave=Ui.wsize):(ai<(_s=Ui.wsize-Ui.wnext)&&(_s=ai),E.arraySet(Ui.window,St,UA-ai,_s,Ui.wnext),(ai-=_s)?(E.arraySet(Ui.window,St,UA-ai,ai,0),Ui.wnext=ai,Ui.whave=Ui.wsize):(Ui.wnext+=_s,Ui.wnext===Ui.wsize&&(Ui.wnext=0),Ui.whave>>8&255,UA.check=D(UA.check,dg,2,0),Gt=Nt=0,UA.mode=2;break}if(UA.flags=0,UA.head&&(UA.head.done=!1),!(1&UA.wrap)||(((255&Nt)<<8)+(Nt>>8))%31){Re.msg="incorrect header check",UA.mode=30;break}if((15&Nt)!=8){Re.msg="unknown compression method",UA.mode=30;break}if(Gt-=4,Va=8+(15&(Nt>>>=4)),UA.wbits===0)UA.wbits=Va;else if(Va>UA.wbits){Re.msg="invalid window size",UA.mode=30;break}UA.dmax=1<>8&1),512&UA.flags&&(dg[0]=255&Nt,dg[1]=Nt>>>8&255,UA.check=D(UA.check,dg,2,0)),Gt=Nt=0,UA.mode=3;case 3:for(;Gt<32;){if(Vi===0)break A;Vi--,Nt+=ai[Ui++]<>>8&255,dg[2]=Nt>>>16&255,dg[3]=Nt>>>24&255,UA.check=D(UA.check,dg,4,0)),Gt=Nt=0,UA.mode=4;case 4:for(;Gt<16;){if(Vi===0)break A;Vi--,Nt+=ai[Ui++]<>8),512&UA.flags&&(dg[0]=255&Nt,dg[1]=Nt>>>8&255,UA.check=D(UA.check,dg,2,0)),Gt=Nt=0,UA.mode=5;case 5:if(1024&UA.flags){for(;Gt<16;){if(Vi===0)break A;Vi--,Nt+=ai[Ui++]<>>8&255,UA.check=D(UA.check,dg,2,0)),Gt=Nt=0}else UA.head&&(UA.head.extra=null);UA.mode=6;case 6:if(1024&UA.flags&&(Vi<(Qo=UA.length)&&(Qo=Vi),Qo&&(UA.head&&(Va=UA.head.extra_len-UA.length,UA.head.extra||(UA.head.extra=new Array(UA.head.extra_len)),E.arraySet(UA.head.extra,ai,Ui,Qo,Va)),512&UA.flags&&(UA.check=D(UA.check,ai,Qo,Ui)),Vi-=Qo,Ui+=Qo,UA.length-=Qo),UA.length))break A;UA.length=0,UA.mode=7;case 7:if(2048&UA.flags){if(Vi===0)break A;for(Qo=0;Va=ai[Ui+Qo++],UA.head&&Va&&UA.length<65536&&(UA.head.name+=String.fromCharCode(Va)),Va&&Qo>9&1,UA.head.done=!0),Re.adler=UA.check=0,UA.mode=12;break;case 10:for(;Gt<32;){if(Vi===0)break A;Vi--,Nt+=ai[Ui++]<>>=7&Gt,Gt-=7&Gt,UA.mode=27;break}for(;Gt<3;){if(Vi===0)break A;Vi--,Nt+=ai[Ui++]<>>=1)){case 0:UA.mode=14;break;case 1:if(Li(UA),UA.mode=20,St!==6)break;Nt>>>=2,Gt-=2;break A;case 2:UA.mode=17;break;case 3:Re.msg="invalid block type",UA.mode=30}Nt>>>=2,Gt-=2;break;case 14:for(Nt>>>=7&Gt,Gt-=7≫Gt<32;){if(Vi===0)break A;Vi--,Nt+=ai[Ui++]<>>16^65535)){Re.msg="invalid stored block lengths",UA.mode=30;break}if(UA.length=65535&Nt,Gt=Nt=0,UA.mode=15,St===6)break A;case 15:UA.mode=16;case 16:if(Qo=UA.length){if(Vi>>=5,Gt-=5,UA.ndist=1+(31&Nt),Nt>>>=5,Gt-=5,UA.ncode=4+(15&Nt),Nt>>>=4,Gt-=4,286>>=3,Gt-=3}for(;UA.have<19;)UA.lens[cS[UA.have++]]=0;if(UA.lencode=UA.lendyn,UA.lenbits=7,TI={bits:UA.lenbits},Vl=T(0,UA.lens,0,19,UA.lencode,0,UA.work,TI),UA.lenbits=TI.bits,Vl){Re.msg="invalid code lengths set",UA.mode=30;break}UA.have=0,UA.mode=19;case 19:for(;UA.have>>16&255,_I=65535&Yg,!((Tr=Yg>>>24)<=Gt);){if(Vi===0)break A;Vi--,Nt+=ai[Ui++]<>>=Tr,Gt-=Tr,UA.lens[UA.have++]=_I;else{if(_I===16){for(oE=Tr+2;Gt>>=Tr,Gt-=Tr,UA.have===0){Re.msg="invalid bit length repeat",UA.mode=30;break}Va=UA.lens[UA.have-1],Qo=3+(3&Nt),Nt>>>=2,Gt-=2}else if(_I===17){for(oE=Tr+3;Gt>>=Tr)),Nt>>>=3,Gt-=3}else{for(oE=Tr+7;Gt>>=Tr)),Nt>>>=7,Gt-=7}if(UA.have+Qo>UA.nlen+UA.ndist){Re.msg="invalid bit length repeat",UA.mode=30;break}for(;Qo--;)UA.lens[UA.have++]=Va}}if(UA.mode===30)break;if(UA.lens[256]===0){Re.msg="invalid code -- missing end-of-block",UA.mode=30;break}if(UA.lenbits=9,TI={bits:UA.lenbits},Vl=T(P,UA.lens,0,UA.nlen,UA.lencode,0,UA.work,TI),UA.lenbits=TI.bits,Vl){Re.msg="invalid literal/lengths set",UA.mode=30;break}if(UA.distbits=6,UA.distcode=UA.distdyn,TI={bits:UA.distbits},Vl=T(W,UA.lens,UA.nlen,UA.ndist,UA.distcode,0,UA.work,TI),UA.distbits=TI.bits,Vl){Re.msg="invalid distances set",UA.mode=30;break}if(UA.mode=20,St===6)break A;case 20:UA.mode=21;case 21:if(6<=Vi&&258<=Ir){Re.next_out=Or,Re.avail_out=Ir,Re.next_in=Ui,Re.avail_in=Vi,UA.hold=Nt,UA.bits=Gt,M(Re,ln),Or=Re.next_out,_s=Re.output,Ir=Re.avail_out,Ui=Re.next_in,ai=Re.input,Vi=Re.avail_in,Nt=UA.hold,Gt=UA.bits,UA.mode===12&&(UA.back=-1);break}for(UA.back=0;xg=(Yg=UA.lencode[Nt&(1<>>16&255,_I=65535&Yg,!((Tr=Yg>>>24)<=Gt);){if(Vi===0)break A;Vi--,Nt+=ai[Ui++]<>ac)])>>>16&255,_I=65535&Yg,!(ac+(Tr=Yg>>>24)<=Gt);){if(Vi===0)break A;Vi--,Nt+=ai[Ui++]<>>=ac,Gt-=ac,UA.back+=ac}if(Nt>>>=Tr,Gt-=Tr,UA.back+=Tr,UA.length=_I,xg===0){UA.mode=26;break}if(32&xg){UA.back=-1,UA.mode=12;break}if(64&xg){Re.msg="invalid literal/length code",UA.mode=30;break}UA.extra=15&xg,UA.mode=22;case 22:if(UA.extra){for(oE=UA.extra;Gt>>=UA.extra,Gt-=UA.extra,UA.back+=UA.extra}UA.was=UA.length,UA.mode=23;case 23:for(;xg=(Yg=UA.distcode[Nt&(1<>>16&255,_I=65535&Yg,!((Tr=Yg>>>24)<=Gt);){if(Vi===0)break A;Vi--,Nt+=ai[Ui++]<>ac)])>>>16&255,_I=65535&Yg,!(ac+(Tr=Yg>>>24)<=Gt);){if(Vi===0)break A;Vi--,Nt+=ai[Ui++]<>>=ac,Gt-=ac,UA.back+=ac}if(Nt>>>=Tr,Gt-=Tr,UA.back+=Tr,64&xg){Re.msg="invalid distance code",UA.mode=30;break}UA.offset=_I,UA.extra=15&xg,UA.mode=24;case 24:if(UA.extra){for(oE=UA.extra;Gt>>=UA.extra,Gt-=UA.extra,UA.back+=UA.extra}if(UA.offset>UA.dmax){Re.msg="invalid distance too far back",UA.mode=30;break}UA.mode=25;case 25:if(Ir===0)break A;if(Qo=ln-Ir,UA.offset>Qo){if((Qo=UA.offset-Qo)>UA.whave&&UA.sane){Re.msg="invalid distance too far back",UA.mode=30;break}Qo>UA.wnext?(Qo-=UA.wnext,Il=UA.wsize-Qo):Il=UA.wnext-Qo,Qo>UA.length&&(Qo=UA.length),GC=UA.window}else GC=_s,Il=Or-UA.offset,Qo=UA.length;for(Irbi?(Ot=Il[GC+xA[St]],Li=Gt[iE+xA[St]]):(Ot=96,Li=0),SA=1<>Or)+(OA-=SA)]=ki<<24|Ot<<16|Li,OA!==0;);for(SA=1<>=1;if(SA!==0?(Nt&=SA-1,Nt+=SA):Nt=0,St++,--ln[Re]==0){if(Re===ai)break;Re=W[oA+xA[St]]}if(_s{const M=new Uint8Array(D).slice(4);let T;try{T=Rl.inflate(M,{to:"string"})}catch(P){console.error("inflate error",P)}return T})(s.data):function(D){const M=new Uint8Array(D);let T="",P=0;const{length:W}=M;for(;P0)for(let kA=0;kA{var u;const{uplinkData:E,canResend:m,resolve:D,reject:M,timeout:T}=r;if(m){this._pendingRequests.set(g,{resolve:D,reject:M,timestamp:Date.now(),uplinkData:E,timeout:T,canResend:m});const P=this._isBinarySupported?Ga(E).buffer:E;(u=this._socketAdapter)===null||u===void 0||u.send(P)}else this._pendingRequests.delete(g)})}_onConnect(s){const{socketId:r,event:g={}}=s||{};this._connectionId=r,this._connectionEstablishedTime=Date.now();const u=Date.now()-this._connectionStartTime,E=`${It}.onConnect cost:${u} ms. socketID:${r} res:${JSON.stringify(g)}`;if(this._ssoLog({method:"onConnect",message:E}),this._checkPendingRequestsAndResend(),this._sendHeartbeatIfReady(),this._isReconnecting){const m=`${It}.reconnect success`;this._ssoLog({method:"reconnectSuccess",message:m}),gn.emitInnerEvent(He.RECONNECTED),this._isReconnecting=!1}this._resetReconnectDelay(),this._handleConnectStateChange({state:Wi,shouldEmitEvent:!0,shouldAttemptReconnect:!1})}_sendAck(s){const r=Ea({servcmd:"openim.ws_msg_push_ack",data:{SessionData:s}});this.sendPacket(r)}_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 r=Ea({servcmd:"heartbeat.alive",data:{}});try{const g=`${r.head.seq}${r.head.servcmd}`;yield this.sendPacket(r,{requestId:g,timeout:3e3})}catch(g){const u=(s=eo.get("netWorkMonitor"))===null||s===void 0?void 0:s.isNetworkOnline,E=`${It}.sendHeartbeat failed. isNetWorkOnline:${u} error: ${en(g)}`;this._ssoLog({method:"sendHeartbeatError",message:E}),this._handleConnectStateChange({state:vi,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=Co?Date.now()+5e3:Date.now()+1e4}_handleNetworkStatusChange(s){const r=`${It}.networkStatusChange ${JSON.stringify(s)}`;this._ssoLog({method:"networkStatusChange",message:r});const{isNetworkOnline:g,networkType:u}=s;g&&u!=="none"?this._handleConnectStateChange({state:Wi,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Mg}):this._handleConnectStateChange({state:vi,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Mg})}isPrivateNetWork(){const s=eo.get("instance")||{};return s.proxyServer&&!s.fileDownloadProxy}_handleConnectStateChange(s){const{state:r,shouldAttemptReconnect:g,shouldEmitEvent:u,reason:E}=s,m=`${It}._handleConnectStateChange currentConnectState: ${this._currentConnectState} shouldAttemptReconnect: ${g} shouldEmitEvent: ${u} reason: ${E}`;this._currentConnectState!==r&&(this._ssoLog({method:"handleConnectStateChange",message:m}),u&&(Vt.info("_handleConnectStateChange",` from ${this._currentConnectState} to ${r}`),gn.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:r}}),this._currentConnectState=r,r===vi&&gn.emitInnerEvent(He.SOCKET_DISCONNECTED)),g&&(this._resetReconnectDelay(),fn.addTask({id:qi,intervalMs:this._intendedDelay,callback:this._scheduleReconnectWithBackoff,context:this})))}_handleActivityStatusChange(s){var r,g;const u=(g=(r=this._socketAdapter)===null||r===void 0?void 0:r._ws)===null||g===void 0?void 0:g.readyState,E=`${It}.activityStatusChange ${JSON.stringify(s)} readyState: ${u}`;Vt.debug("activityStatusChange",E),u===3&&this._handleConnectStateChange({state:vi,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:ar})}_resetReconnectDelay(){var s;Vt.debug(`${It}._resetReconnectDelay`),fn.removeTask(qi);const r=(s=eo.get("activityMonitor"))===null||s===void 0?void 0:s.isActive;this._intendedDelay=r?zo:1e3}_scheduleReconnectWithBackoff(){var s;const r=(s=eo.get("activityMonitor"))===null||s===void 0?void 0:s.isActive;this._intendedDelay=r?Math.min(5e3,Math.max(zo,1.5*this._intendedDelay)):Math.min(3e5,Math.max(1e3,1.5*this._intendedDelay));const g=new Date().toTimeString().slice(0,8),u=`${It}.scheduleReconnectWithBackoff timeStr: ${g} intendedDelay: ${this._intendedDelay}`;Vt.debug(u),this.reconnect(),fn.updateTaskInterval(qi,this._intendedDelay)}_ssoLog(s){const{method:r,message:g}=s;Vt.info(r,g)}_diagnose(){this.isPrivateNetWork()||(this._lastDiagnoseAt=Date.now(),function(s){mA(this,void 0,void 0,function*(){const r=s.split("/")[2];if(!r.startsWith("ws"))return;const g=`https://${r}/v3/netcheck/getconninfo?${s.slice(s.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield Yi({method:"GET",url:g,data:{}})}catch(u){Vt.warn("diagnoseBySSO",`diagnoseBySSO failed. error:${u.message}`)}})}(this._url),function(s){mA(this,void 0,void 0,function*(){const r=`https://boce-cdn.my-imcloud.com/v3/netcheck/getconninfo?${s.slice(s.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield Yi({method:"GET",url:r,data:{}})}catch(g){Vt.warn(`diagnoseByCDN', 'diagnoseByCDN failed. error:${g.message}`)}})}(this._url),this._beforeSendInterceptors=[])}_clearTimeoutRequest(){for(const[s,r]of this._pendingRequests.entries()){const{reject:g,timestamp:u,timeout:E}=r;Date.now()-u>=E&&(this._pendingRequests.delete(s),Date.now()-this._lastDiagnoseAt>=3e4&&this._diagnose(),g({errorCode:mr,errorInfo:"NETWORK_TIMEOUT",data:{requestId:s}}))}}_updateIsBinarySupported(){var s;if(!((s=eo.get("instance"))===null||s===void 0)&&s.devMode)return void(this._isBinarySupported=!1);const r=ds();if((oi||ct&&r==="windows"||ks)&&(this._isBinarySupported=!1),Co){const{uniRuntimeVersion:g=""}=Ao.getSystemInfoSync();(function(u){const E=u.split(".").map(Number),[m=0,D=0,M=0]=E;return m>2||!(m<2)&&(D>2||!(D<2)&&M>=6)})(g)||(this._isBinarySupported=!1)}}_isCompressedData(s){const r=new Uint8Array(s);return r[0]===67&&r[1]===79&&r[2]===77&&r[3]===80}};const De={init:function(s){eo.set("instance",s),Se.init()},destroy:function(){Se.dispose(),eo.clear(),fn.dispose()},notificationCenter:gn,channel:Se,store:eo,ssoLog:Vt,utils:yg,common:vA,constants:lt},vg=s=>typeof s=="function";function rg(s,r,g){const u=g||[];if(!s||!r)return!1;const E=Object.keys(s).filter(D=>!u.includes(D)),m=Object.keys(r).filter(D=>!u.includes(D));return E.length===m.length&&E.every(D=>!!r.hasOwnProperty(D)&&(typeof s[D]=="object"&&s[D]!==null?rg(s[D],r[D],g):s[D]===r[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,Mr=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 Ei,ro=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"})(Ei||(Ei={}));var qc=Ei;const zg=Object.assign({},{KICKED_OUT_MULT_ACCOUNT:"multipleAccount",KICKED_OUT_MULT_DEVICE:"multipleDevice",KICKED_OUT_USERSIG_EXPIRED:"userSigExpired",KICKED_OUT_REST_API:"REST_API_Kick"}),wg={MSG_TEXT:"TIMTextElem",MSG_IMAGE:"TIMImageElem",MSG_AUDIO:"TIMSoundElem",MSG_FILE:"TIMFileElem",MSG_FACE:"TIMFaceElem",MSG_VIDEO:"TIMVideoFileElem",MSG_LOCATION:"TIMLocationElem",MSG_GRP_TIP:"TIMGroupTipElem",MSG_GRP_SYS_NOTICE:"TIMGroupSystemNoticeElem",MSG_CUSTOM:"TIMCustomElem",MSG_MERGER:"TIMRelayElem",MSG_STREAM:"TIMStreamElem"};var Yr;(function(s){s.UNSENT="unSend",s.SUCCESS="success",s.FAIL="fail"})(Yr||(Yr={}));const yc={modify:ro.MESSAGE_MODIFIED,delete:ro.MESSAGE_DELETED,revoke:ro.MESSAGE_REVOKED};var Kc;(function(s){s[s.FORWARD=0]="FORWARD",s[s.BACKWARD=1]="BACKWARD"})(Kc||(Kc={}));const ag=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},wg),{MSG_PRIORITY_HIGH:"High",MSG_PRIORITY_NORMAL:"Normal",MSG_PRIORITY_LOW:"Low",MSG_PRIORITY_LOWEST:"Lowest"}),{RECEIVE_WITH_OFFLINE_PUSH_EXCEPT_AT:"AcceptNotNotifyExceptAt",NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT:"AcceptNotNotifyExceptAt",NOT_RECEIVE_MSG_EXCEPT_AT:"NotReceiveMsgExceptAt",MSG_AT_ALL:"__kImSDK_MesssageAtALL__"}),{MSG_REMIND_ACPT_AND_NOTE:"AcceptAndNotify",MSG_REMIND_ACPT_NOT_NOTE:"AcceptNotNotify",MSG_REMIND_DISCARD:"Discard"}),{MessageStatus:Yr,Direction:Kc}),Tu={[yc.modify]:ro.TOPIC_MESSAGE_MODIFIED,[yc.delete]:ro.TOPIC_MESSAGE_DELETED,[yc.revoke]:ro.TOPIC_MESSAGE_REVOKED},DE={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({},DE),ka={CONV_C2C:"C2C",CONV_GROUP:"GROUP",CONV_TOPIC:"TOPIC",CONV_SYSTEM:"@TIM#SYSTEM"},Dc=Object.assign(Object.assign(Object.assign(Object.assign({},ka),{CONV_AT_ME:1,CONV_AT_ALL:2,CONV_AT_ALL_AT_ME:3}),{CONV_MARK_TYPE_STAR:1,CONV_MARK_TYPE_UNREAD:2,CONV_MARK_TYPE_FOLD:4,CONV_MARK_TYPE_HIDE:8}),{READ_ALL_C2C_MSG:"readAllC2CMessage",READ_ALL_GROUP_MSG:"readAllGroupMessage",READ_ALL_MSG:"readAllMessage"}),SE=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},{SNS_TYPE_NO_RELATION:"CheckResult_Type_NoRelation",SNS_TYPE_A_WITH_B:"CheckResult_Type_AWithB",SNS_TYPE_B_WITH_A:"CheckResult_Type_BWithA",SNS_TYPE_BOTH_WAY:"CheckResult_Type_BothWay"}),{ALLOW_TYPE_ALLOW_ANY:"AllowType_Type_AllowAny",ALLOW_TYPE_NEED_CONFIRM:"AllowType_Type_NeedConfirm",ALLOW_TYPE_DENY_ANY:"AllowType_Type_DenyAny"}),{SNS_ADD_TYPE_SINGLE:"Add_Type_Single",SNS_ADD_TYPE_BOTH:"Add_Type_Both"}),{SNS_DELETE_TYPE_SINGLE:"Delete_Type_Single",SNS_DELETE_TYPE_BOTH:"Delete_Type_Both"}),{SNS_APPLICATION_TYPE_BOTH:"Pendency_Type_Both",SNS_APPLICATION_SENT_TO_ME:"Pendency_Type_ComeIn",SNS_APPLICATION_SENT_BY_ME:"Pendency_Type_SendOut",SNS_APPLICATION_AGREE:"Response_Action_Agree",SNS_APPLICATION_AGREE_AND_ADD:"Response_Action_AgreeAndAdd"}),{SNS_CHECK_TYPE_BOTH:"CheckResult_Type_Both",SNS_CHECK_TYPE_SINGLE:"CheckResult_Type_Single"}),{FORBID_TYPE_NONE:"AdminForbid_Type_None",FORBID_TYPE_SEND_OUT:"AdminForbid_Type_SendOut"}),La={GRP_WORK:"Private",GRP_PUBLIC:"Public",GRP_MEETING:"ChatRoom",GRP_AVCHATROOM:"AVChatRoom",GRP_COMMUNITY:"Community",GRP_ROOM:"Room",GRP_LIVE:"Live"},na={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},cI=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},La),{GRP_MBR_ROLE_OWNER:"Owner",GRP_MBR_ROLE_ADMIN:"Admin",GRP_MBR_ROLE_MEMBER:"Member",GRP_MBR_ROLE_CUSTOM:"Custom"}),{GRP_TIP_MBR_JOIN:1,GRP_TIP_MBR_QUIT:2,GRP_TIP_MBR_KICKED_OUT:3,GRP_TIP_MBR_SET_ADMIN:4,GRP_TIP_MBR_CANCELED_ADMIN:5,GRP_TIP_GRP_PROFILE_UPDATED:6,GRP_TIP_MBR_PROFILE_UPDATED:7,GRP_TIP_BAN_AVCHATROOM_MEMBER:10,GRP_TIP_UNBAN_AVCHATROOM_MEMBER:11}),{JOIN_OPTIONS_FREE_ACCESS:"FreeAccess",JOIN_OPTIONS_NEED_PERMISSION:"NeedPermission",JOIN_OPTIONS_DISABLE_APPLY:"DisableApply",JOIN_STATUS_SUCCESS:"JoinedSuccess",JOIN_STATUS_ALREADY_IN_GROUP:"AlreadyInGroup",JOIN_STATUS_WAIT_APPROVAL:"WaitAdminApproval"}),{INVITE_OPTIONS_DISABLE_INVITE:"DisableInvite",INVITE_OPTIONS_NEED_PERMISSION:"NeedPermission",INVITE_OPTIONS_FREE_ACCESS:"FreeAccess"}),{GRP_PROFILE_OWNER_ID:"ownerID",GRP_PROFILE_CREATE_TIME:"createTime",GRP_PROFILE_LAST_INFO_TIME:"lastInfoTime",GRP_PROFILE_MEMBER_NUM:"memberNum",GRP_PROFILE_MAX_MEMBER_NUM:"maxMemberNum",GRP_PROFILE_JOIN_OPTION:"joinOption",GRP_PROFILE_INVITE_OPTION:"inviteOption",GRP_PROFILE_INTRODUCTION:"introduction",GRP_PROFILE_NOTIFICATION:"notification",GRP_PROFILE_MUTE_ALL_MBRS:"muteAllMembers"}),{GROUP_ID_PREFIX:na,GROUP_TIPS_OPERATION_TYPE:Tg}),Bs={IOS_OFFLINE_PUSH_NO_SOUND:"push.no_sound",IOS_OFFLINE_PUSH_DEFAULT_SOUND:"default"},Uo=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},zg),ag),_g),Dc),SE),cI),Bs),{NET_STATE_CONNECTING:"connecting",NET_STATE_DISCONNECTED:"disconnected",NET_STATE_CONNECTED:"connected"}),da={NO_SDKAPPID:2e3,NO_TINYID:2022,NO_A2KEY:2023,USER_NOT_LOGGED_IN:2024,REPEAT_LOGIN:2025,MSG_SEND_FAIL:2100,MSG_SEND_FAIL_NOT_IN_AV:2101,MSG_SEND_GRP_WITH_TOPIC_FAIL:2115,MSG_INSTANCE_REQUIRED:2105,MSG_INVALID_CONV_TYPE:2106,MSG_REVOKE_FAIL:2110,MSG_DELETE_FAIL:2111,MSG_UNREAD_ALL_FAIL:2112,READ_RECEIPT_MSG_LIST_EMPTY:2114,CANNOT_DELETE_GRP_SYSTEM_NOTICE:2116,NOT_MY_FRIEND:2700,NETWORK_ERROR:2800,NETWORK_TIMEOUT:2801,NO_NETWORK:2805,UNCAUGHT_ERROR:2903,INVALID_OPERATION:2905,SDK_IS_NOT_READY:2999,LOGGING_IN:3e3,LOGIN_FAILED:3001,KICKED_OUT_MULT_DEVICE:3002,KICKED_OUT_MULT_ACCOUNT:3003,KICKED_OUT_USERSIG_EXPIRED:3004,LOGGED_OUT:3005,KICKED_OUT_REST_API:3006,NO_USE:3122,OPTIONS_IS_EMPTY:3153,MSG_A2KEY_EXPIRED:20002,ACCOUNT_A2KEY_EXPIRED:70001,HELLO_ANSWER_KICKED_OUT:1002,OPEN_SERVICE_OVERLOAD_ERROR:60022},gr={BASIC:"1",STANDARD:"2",PROFESSIONAL:"3",NODE:"4"},Jt={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"},Wt={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={[Jt.SYNC_SERVER_INFO_AFTER_RE_ONLINE]:[{stepId:Wt.USER_STATUS_UPDATE},{stepId:Wt.GROUP_ATTRIBUTE_CACHE_CLEAR},{stepId:Wt.UNREAD_MESSAGE_SYNC,dependency:Wt.C2C_HISTORY_MESSAGE_RECOVER},{stepId:Wt.CONVERSATION_RECOVER},{stepId:Wt.HISTORY_MESSAGE_RECOVER,dependency:Wt.CONVERSATION_RECOVER},{stepId:Wt.BLACKLIST_RECOVER},{stepId:Wt.FRIEND_RECOVER},{stepId:Wt.FRIEND_APPLICATION_LIST_RECOVER},{stepId:Wt.GROUP_REVOKED_NOTICE_RECOVER,dependency:Wt.HISTORY_MESSAGE_RECOVER},{stepId:Wt.GROUP_TIPS_RECOVER,dependency:Wt.HISTORY_MESSAGE_RECOVER},{stepId:Wt.TOPIC_REQUEST_INFO_RESET},{stepId:Wt.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,dependency:Wt.UNREAD_MESSAGE_SYNC},{stepId:Wt.HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD,dependency:Wt.UNREAD_MESSAGE_SYNC},{stepId:Wt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Wt.UNREAD_MESSAGE_SYNC,Wt.CONVERSATION_RECOVER]},{stepId:Wt.EMIT_C2C_MESSAGE_EVENT,dependency:[Wt.UNREAD_MESSAGE_SYNC,Wt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED],skipIfDependencyMissing:!1},{stepId:Wt.C2C_HISTORY_MESSAGE_RECOVER,dependency:Wt.CONVERSATION_RECOVER},{stepId:Wt.STREAM_MESSAGE_RECOVER}],[Jt.SYNC_SERVER_INFO_AFTER_LOGIN]:[{stepId:Wt.COMMERCIAL_CONFIG_UPDATE},{stepId:Wt.CLOUD_CONFIG_SYNC},{stepId:Wt.USER_PROFILE_SYNC},{stepId:Wt.UNREAD_MESSAGE_SYNC},{stepId:Wt.FRIEND_AND_BLACKLIST_SYNC},{stepId:Wt.GROUP_LIST_SYNC},{stepId:Wt.CONVERSATION_LIST_SYNC},{stepId:Wt.SIGNALING_MESSAGE_RECOVER,dependency:Wt.UNREAD_MESSAGE_SYNC},{stepId:Wt.UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED,dependency:[Wt.UNREAD_MESSAGE_SYNC]},{stepId:Wt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Wt.UNREAD_MESSAGE_SYNC,Wt.CONVERSATION_LIST_SYNC]},{stepId:Wt.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,dependency:[Wt.GROUP_LIST_SYNC,Wt.CONVERSATION_LIST_SYNC]},{stepId:Wt.CONVERSATION_GROUP_LIST_SYNC},{stepId:Wt.CONVERSATION_GROUP_UPDATE,dependency:[Wt.CONVERSATION_LIST_SYNC,Wt.CONVERSATION_GROUP_LIST_SYNC]},{stepId:Wt.QUALITY_REPORT}],[Jt.RECEIVE_C2C_NEW_MESSAGE]:[{stepId:Wt.HANDLE_C2C_NEW_MESSAGE},{stepId:Wt.UNREAD_MESSAGE_SYNC},{stepId:Wt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Wt.HANDLE_C2C_NEW_MESSAGE},{stepId:Wt.EMIT_C2C_MESSAGE_EVENT,dependency:[Wt.HANDLE_C2C_NEW_MESSAGE,Wt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1},{stepId:Wt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Wt.UNREAD_MESSAGE_SYNC]}],[Jt.RECEIVE_GROUP_NEW_MESSAGE]:[{stepId:Wt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Wt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Wt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Wt.UPDATE_GROUP_NEXT_SEQUENCE,dependency:Wt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Wt.UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE,dependency:Wt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Wt.EMIT_GROUP_MESSAGE_EVENT,dependency:[Wt.HANDLE_GROUP_NEW_MESSAGE,Wt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1}],[Jt.RECEIVE_GROUP_TIPS_NOTIFICATION]:[{stepId:Wt.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:Wt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Wt.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:Wt.EMIT_GROUP_TIPS_EVENT,dependency:[Wt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,Wt.HANDLE_GROUP_TIPS_NOTIFICATION],skipIfDependencyMissing:!1}]},lI={MESSAGE_SEND_SUCCESS_RATE:"messageSendSuccessRate"},cr={TOTAL_COUNT:"sendMessageTotalCount",SUCCESS_COUNT:"sendMessageSuccessCount",FAILED_COUNT:"sendMessageFailedCount",SEND_COST:"sendMessageCost"},KI=["login","getMyProfile","getUserProfile","updateMyProfile","setSelfStatus","getUserStatus","subscribeUserStatus","unsubscribeUserStatus","modifyMessage","deleteGroupMember","dismissGroup","getGroupMemberList","getGroupOnlineMemberCount","joinGroup","markGroupMemberList","quitGroup","searchCloudMessages","searchCloudGroups","searchCloudGroupMembers","searchCloudUsers","getMyFollowingList","getMyFollowersList","getMutualFollowersList","followUser","unfollowUser","getUserFollowInfo","checkFollowType","getFriendProfile","addFriend","deleteFriend","updateFriend","checkFriend","setFriendApplicationRead","createFriendGroup","deleteFriendGroup","addToFriendGroup","removeFromFriendGroup","renameFriendGroup","changeGroupOwner","createGroup","dismissGroup","getGroupList","getGroupOnlineMemberCount","getGroupProfile","searchGroupByID","updateGroupProfile","handleGroupApplication","deleteGroupAttributes","getGroupAttributes","initGroupAttributes","setGroupAttributes","addGroupMember","deleteGroupMember","getGroupMemberList","getGroupMemberProfile","setGroupMemberMuteTime","setGroupMemberNameCard","setGroupMemberRole","deleteMessage","revokeMessage","setMessageExtensions","getMessageExtensions","deleteMessageExtensions","getMessageList","addMessageReaction","removeMessageReaction","clearHistoryMessage","sendMessageReadReceipt","getMessageReadReceiptList","getGroupMessageReadMemberList","createMergerMessage","invite","accept","cancel","reject","modifyInvitation","deleteConversation","pinConversation","setMessageRead","setAllMessageRead","getConversationList","getTotalUnreadMessageCount","renameConversationGroup","deleteConversationGroup","markConversation","setConversationCustomData","deleteConversationsFromGroup","addConversationsToGroup","createConversationGroup"];var za=Object.freeze({__proto__:null,ERROR_CODE:da,InnerEvent:ro,NEED_LOG_API:KI,OuterConstant:Uo,OuterEvent:Mr,PUSH:Bs,QUALITY_METRICS:lI,SDK_EDITION:gr,SDK_INFO:{VERSION:"1.7.3",APPID:537048168},SEND_MESSAGE_STAT:cr,SignalingEvent:qc,WEB_PUSH_ACCOUNT_TYPE:1,WORKFLOW_DEFINITIONS:Ng,WORKFLOW_NAME:Jt,WORKFLOW_STEP:Wt}),ra,un,Sn;(function(s){s[s.USER_INITIATED=0]="USER_INITIATED",s[s.KICKED_OUT=1]="KICKED_OUT"})(ra||(ra={})),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 Nu={[un.multipleAccount]:"multipleAccount",[un.multipleDevice]:"multipleDevice",[un.restApi]:"REST_API_Kick",[Sn.multipleAccount]:"multipleAccount",[Sn.multipleDevice]:"multipleDevice",[Sn.restApi]:"REST_API_Kick",[Sn.usersigExpired]:"userSigExpired"},Gg="login_online_presence_task",{ERROR:Ua,DESTROY:jc,FORCE_OFFLINE:jI}=ro,{KICKED_OUT_MULT_ACCOUNT:ME,KICKED_OUT_MULT_DEVICE:II,KICKED_OUT_REST_API:Gu,ACCOUNT_A2KEY_EXPIRED:wl,MSG_A2KEY_EXPIRED:Sc}=da;class bu{init(){const{notificationCenter:r}=De;r.subscribeInnerEvent(jI,this._handleForceOfflineFromServerPush,this),r.subscribeInnerEvent(Ua,Sc,this._handleForceOfflineFromResponse,this,this._isChatLoginEvent),r.subscribeInnerEvent(Ua,wl,this._handleForceOfflineFromResponse,this,this._isChatLoginEvent),r.subscribeInnerEvent(Ua,ME,this._handleForceOfflineFromResponse,this),r.subscribeInnerEvent(Ua,II,this._handleForceOfflineFromResponse,this),r.subscribeInnerEvent(Ua,Gu,this._handleForceOfflineFromResponse,this),r.subscribeInnerEvent(jc,this._dispose,this)}_handleForceOfflineFromServerPush(r){var g;if(((g=De.store.get("login"))===null||g===void 0?void 0:g.isLoggedIn)===!0){const{EventArray:u=[]}=r?.body||{};this._extractKickedOutMessages(u).forEach(E=>{const{KickoutMsgNotify:{KickType:m,NewInstInfo:D,Instid:M}}=E;this._isCurrentInstanceKickedOut(M)&&this._processKickedOutReasonInfo({kickedOutReasonCode:m,newInstanceInfo:D})})}}_extractKickedOutMessages(r){return r.reduce((g,u)=>[...g,...u.C2cNotifyMsgArray||[]],[]).filter(g=>{var u;return this._isKickedOut((u=g?.KickoutMsgNotify)===null||u===void 0?void 0:u.KickType)})}_handleForceOfflineFromResponse(r){const{errorCode:g}=r;this._processKickedOutReasonInfo({kickedOutReasonCode:g})}_processKickedOutReasonInfo(r){return mA(this,void 0,void 0,function*(){const{kickedOutReasonCode:g}=r,{ssoLog:u,utils:{safeStringify:E}}=De;try{this._logKickedOutEvent(r),this._shouldLogoutAfterKickedOut(g)?yield De.login.loginAction.logout(ra.KICKED_OUT):De.login.loginAction.handleLogoutCompleted()}catch(m){u.debug("_processKickedOutReasonInfo",` fail ${E(m)}`)}finally{De.notificationCenter.emitOuterEvent(Mr.KICKED_OUT,{data:{type:Nu[g]},name:Mr.KICKED_OUT})}})}_logKickedOutEvent(r){const{kickedOutReasonCode:g,newInstanceInfo:u={}}=r,E=`type:${Nu[g]} newInstanceInfo: ${JSON.stringify(u)}`;De.ssoLog.warn("kickedOut",E)}_isKickedOut(r){return[un.multipleAccount,un.multipleDevice,un.restApi].includes(r)}_isChatLoginEvent(r){const{requestHead:g}=r||{};return g?.idtype!==1}_shouldLogoutAfterKickedOut(r){return![Sn.usersigExpired,un.restApi].includes(r)}_isCurrentInstanceKickedOut(r){const{isLoggedIn:g,statusInstanceId:u}=De.store.get("login")||{};return g===!0&&r===u}_dispose(){const{notificationCenter:r}=De;r.unSubscribeInnerEvent(jI,this._handleForceOfflineFromServerPush,this),r.unSubscribeInnerEvent(Ua,wl,this._handleForceOfflineFromResponse,this),r.unSubscribeInnerEvent(Ua,Sc,this._handleForceOfflineFromResponse,this),r.unSubscribeInnerEvent(Ua,ME,this._handleForceOfflineFromResponse,this),r.unSubscribeInnerEvent(Ua,II,this._handleForceOfflineFromResponse,this),r.unSubscribeInnerEvent(Ua,Gu,this._handleForceOfflineFromResponse,this),r.unSubscribeInnerEvent(jc,this._dispose,this)}}function ku(s){return mA(this,void 0,void 0,function*(){const r="im_open_status.wslogin",g=De.common.generateProtocolData({servcmd:r,data:{State:"Online",is_web_uniapp:0,InstType:0,CustomInfo:s}}),u=`${g.head.seq}${r}`,E=yield De.channel.sendPacket(g,{timeout:9e4,requestId:u});if(E){const{HelloInterval:m,InstId:D,TinyId:M,TimeStamp:T,CustomStatus:P,PurchaseBits:W,A2Key:oA,RichMsgAuthKey:EA,ErrorCode:wA,ErrorInfo:kA,ActionStatus:xA}=E;return{helloInterval:m,instanceID:D,tinyID:M,timeStamp:T,customStatus:P,purchaseBits:W,a2Key:oA,authKey:EA,errorCode:wA,errorInfo:kA,actionStatus:xA}}})}function _l(){const{store:s}=De;return ua(s.get("instance").sdkAppId)!==gt.CHINA}function rs(s){var r;try{const g=eo.getStorage("errorMessage");if(!s||!g)return"";const u=((r=JSON.parse(g))===null||r===void 0?void 0:r.errorMessage)||{},{code:E,replacement1:m="",replacement2:D=""}=s;if(!E)return"";const M=_l()?`${E}_en`:`${E}_cn`;let T=u[u[M]?M:E]||"";return T&&(m&&(T=T.replace("$replacement1",m)),D&&(T=T.replace("$replacement2",D))),T}catch(g){return console.warn("Error parsing stored error messages:",g),""}}class gs extends Error{constructor(r={}){r.code=r.code||r.errorCode;let{functionName:g="Unknown",code:u,message:E="",data:m="",moreMessage:D="",errorMessage:M=""}=r;M=(u?rs(r):"")||M||E;let T=u?`${g} failed. error: {"message": ${M}, "code": ${u}}`:`${g} failed. error: {"message": ${M}}`;T=`${T} ${D}`,super(),this.code=u,this.errorCode=u,this.errorMessage=M,this.message=T,this.data=m}}function ud(s,r){var g;if(s&&((g=De.store.get("login"))===null||g===void 0?void 0:g.isLoggedIn)!==!0)throw new gs({code:da.USER_NOT_LOGGED_IN,functionName:r})}function uI(s,r,g){if(Array.isArray(s))for(let u=0;u{return P===(W=u,Object.prototype.toString.call(W).match(/^\[object (.*)\]$/)[1].toLowerCase());var W})){for(let W=0;W{const{interceptor:E,context:m}=u;E.apply(m,[g])})}(s)}function Mc(s,r){vE.push({interceptor:s,context:r})}function Wc(s){const{params:r,auth:g}=s;r&&typeof r=="object"&&Object.assign(Tl,r),g&&typeof g=="object"&&Object.assign(Ed,g)}function tn(s){return De.store.get("commercialConfig").get(s)}class ws{constructor(){this._handlers=new Map,this._activeWorkflows=new Map,this._stepStartTimes=new Map,this._logHandlers={start:(r,g)=>{const u=Date.now();g?(this._stepStartTimes.set(`${r}-${g}`,u),De.ssoLog.debug("_executeWorkflowStep",`[Workflow ${r}] Step ${g} started at ${new Date(u).toISOString()}`)):(this._workflowStartTimes.set(r,u),De.ssoLog.debug("_executeWorkflowStep",`[Workflow ${r}] started at ${new Date(u).toISOString()}`))},success:(r,g)=>{const u=Date.now();if(g){const E=this._stepStartTimes.get(`${r}-${g}`),m=E?u-E:0;this._stepStartTimes.delete(`${r}-${g}`),De.ssoLog.debug("_executeWorkflowStep",`[Workflow ${r}] Step ${g} completed successfully at ${new Date(u).toISOString()} (${m}ms)`)}else{const E=this._workflowStartTimes.get(r),m=E?u-E:0;this._workflowStartTimes.delete(r),De.ssoLog.debug("_executeWorkflowStep",`[Workflow ${r}] completed successfully at ${new Date(u).toISOString()} (${m}ms)`)}},error:(r,g,u)=>{const{ssoLog:E,utils:{safeStringify:m}}=De,D=Date.now();if(g){const M=this._stepStartTimes.get(`${r}-${g}`),T=M?D-M:0;this._stepStartTimes.delete(`${r}-${g}`),E.error("_executeWorkflowStep",`[Workflow ${r}] Step ${g} failed at ${new Date(D).toISOString()} (${T}ms) ${m(u)}`,{error:u})}else{const M=this._workflowStartTimes.get(r),T=M?D-M:0;this._workflowStartTimes.delete(r),E.error("_executeWorkflowStep",`[Workflow ${r}] failed at ${new Date(D).toISOString()} (${T}ms) ${m(u)}`,{error:u})}}}}static getInstance(){return ws._instance||(ws._instance=new ws),ws._instance}static setInstance(r){ws._instance=r}init(){this._initializeWorkflows()}registerWorkflowStep(r,g,u,E){if(!this._handlers.has(r))return void De.ssoLog.debug("registerWorkflowStep",`Workflow '${r}' not defined in core`);if(!Ng[r].find(D=>D.stepId===g))return void De.ssoLog.debug("registerWorkflowStep",`Step '${g}' not defined in workflow '${r}'`);const m=this._handlers.get(r);m.has(g)||m.set(g,E?u.bind(E):u)}executeWorkflow(r,g){return mA(this,void 0,void 0,function*(){if(!this._validateWorkflow(r))return;De.ssoLog.debug("executeWorkflow",`[Workflow ${r}] Started execution at ${new Date().toISOString()}`);const u=Ng[r],E={},m={cancelled:!1};this._activeWorkflows.set(r,{cancelToken:m});try{const D=new Map;u.forEach(T=>{D.set(T.stepId,T)});const M={workflowName:r,pendingSteps:new Set(u.map(T=>T.stepId)),completedSteps:new Set,runningSteps:new Set,stepMap:D,stepResults:E,data:g,cancelToken:m};yield new Promise((T,P)=>{const W=()=>{if(m.cancelled)return void T();this._getExecutableSteps({pendingSteps:M.pendingSteps,completedSteps:M.completedSteps,stepMap:M.stepMap,workflowName:r}).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:r}).filter(EA=>!M.runningSteps.has(EA)).length===0&&M.runningSteps.size===0&&(De.ssoLog.debug("executeWorkflow",`Workflow ${r} completed with some steps skipped due to dependency failures`),T())},onError:P,onStepComplete:W})})};W()}),De.ssoLog.debug("executeWorkflow",`[Workflow ${r}] Completed execution at ${new Date().toISOString()}`)}catch(D){De.ssoLog.error("executeWorkflow",`[Workflow ${r}] Failed execution at ${new Date().toISOString()}`,{error:D})}finally{this._activeWorkflows.delete(r)}})}_executeWorkflowStep(r,g,u){return mA(this,void 0,void 0,function*(){const{workflowName:E,runningSteps:m,stepMap:D,stepResults:M,data:T}=g;m.add(r),this._logWorkflowExecution(E,r,"start");try{const P=D.get(r);let W=null;P?.dependency&&(c(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(r);if(oA){const EA=yield Promise.resolve(oA({data:T,result:W}));M[r]=EA,this._logWorkflowExecution(E,r,"success")}g.completedSteps.add(r)}catch(P){const W=`[Workflow].${E}.${r}`,{errorCode:oA,errorInfo:EA=`${W} failed`}=P||{},wA=new gs({functionName:W,code:oA,message:EA});De.ssoLog.error(W,EA,{error:wA}),this._logWorkflowExecution(E,r,"error",P),u.onError(P)}finally{m.delete(r),g.pendingSteps.delete(r),u.onStepComplete(),u.onComplete()}})}reset(){this._cancelAllWorkflows()}destroy(){this.reset(),this._handlers.clear()}_initializeWorkflows(){Object.keys(Ng).forEach(r=>{this._handlers.has(r)||this._handlers.set(r,new Map)})}_cancelWorkFlow(r){const g=this._activeWorkflows.get(r);if(!g)return;const{cancelToken:u}=g;u.cancelled=!0,this._activeWorkflows.delete(r)}_cancelAllWorkflows(){Object.keys(Ng).forEach(r=>{this._cancelWorkFlow(r)})}_validateWorkflow(r){return Ng[r]?!!this._handlers.get(r):!1}_getExecutableSteps(r){const{pendingSteps:g,completedSteps:u,stepMap:E,workflowName:m}=r;return Array.from(g).filter(D=>{const M=E.get(D)||{},{dependency:T,skipIfDependencyMissing:P=!0}=M;if(!T)return!0;if(c(T))return this._isStepRegistered({workflowName:m,stepId:T})?u.has(T):!P;if(C(T)){if(T.filter(W=>!this._isStepRegistered({workflowName:m,stepId:W})).length>0&&P)return!1;for(const W of T)if(!u.has(W))return!1;return!0}return!1})}_isStepRegistered(r){var g;const{workflowName:u,stepId:E}=r;return(g=this._handlers.get(u))===null||g===void 0?void 0:g.has(E)}_logWorkflowExecution(r,g,u,E){this._logHandlers[u](r,g)}}const Ca=new Map,$r=({type:s,groupID:r})=>s===Uo.GRP_COMMUNITY||`${r}`.startsWith(na.COMMUNITY)&&!`${r}`.includes(na.TOPIC),zc=(s="")=>{const r=s.startsWith("GROUP")?s.replace("GROUP",""):s;return r.startsWith(na.COMMUNITY)&&`${r}`.includes(na.TOPIC)},dd="openim",Zg="million_group_open_http_svc";function gg(s){return mA(this,void 0,void 0,function*(){const{servcmd:r,data:g}=function(m){const{data:D}=m;return RE(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:oA=""}=W;const EA=oA;return[oA]=EA.split(na.TOPIC),{servcmd:jn(P),data:Object.assign(Object.assign({},W),{GroupId:oA,TopicId:EA})}}(m):(RE(M)&&(D=jn(D)),{servcmd:D,data:M})}(s):s,u=De.common.generateProtocolData({servcmd:r,data:g}),E=`${u.head.seq}${r}`;return De.channel.sendPacket(u,{requestId:E,timeout:s.timeout})})}function RE(s){const{Type:r,GroupId:g,GroupIdList:u=[]}=s,E=g||u[0]||"";return $r({type:r,groupID:E})}function Xg(s){const{GroupId:r=""}=s;return zc(r)}function jn(s){if(s.includes(dd))return s;const r=s.split(".")[1];return`${Zg}.${r}`}function ir(){var s;return(s=De.store.get("login"))===null||s===void 0?void 0:s.userId}const Fa=s=>C(s)||f(s),Cd=(s,r,g,u)=>{if(!Fa(s)||!Fa(r))return 0;let E=0;const m=Object.keys(r);let D;for(let M=0,T=m.length;M{if(n(r))return"";if(s===Uo.MSG_TEXT)return r.text||"";const g=WI[s];return g?Lu(g):""},Xc=[{cmd:"ws_get_user_status",interval:5,count:20},{cmd:"ws_status_subscribe",interval:5,count:20},{cmd:"ws_status_unsubscribe",interval:5,count:20},{cmd:"get_group_self_member_info",interval:5,count:20},{cmd:"modify_group_base_info",interval:1,count:8},{cmd:"get_pendency",interval:1,count:15},{cmd:"set_group_attr",interval:5,count:10},{cmd:"modify_group_attr",interval:5,count:10},{cmd:"delete_group_attr",interval:5,count:10},{cmd:"clear_group_attr",interval:5,count:10},{cmd:"get_group_attr",interval:5,count:20},{cmd:"update_group_counter",interval:5,count:20},{cmd:"get_group_counter",interval:5,count:20},{cmd:"get_topic",interval:1,count:10},{cmd:"read_all_unread_msg",interval:1,count:1},{cmd:"query",interval:5,count:20}],zI="im_sdk_config_mgr.fetch_config",dI="im_sdk_config_mgr.push_configv2",$c="cloud-config",Al=2996,va=new class{init(s){this.core=s}};function bg(s){return mA(this,void 0,void 0,function*(){const{sdkAppId:r}=va.core.store.get("instance")||{},g=va.core.helper.generateProtocolData({servcmd:zI,data:{uint32_sdkappid:r,uint64_version:s}}),u=`${g.head.seq}${zI}`;return va.core.channel.sendPacket(g,{requestId:u})})}var Ds=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:r,InnerEvent:g,helper:u,constants:{WORKFLOW_NAME:E,WORKFLOW_STEP:m},channel:D}=s;r.subscribeInnerEvent(dI,this._handlePushedConfig,this),u.registerWorkflowStep(E.SYNC_SERVER_INFO_AFTER_LOGIN,m.CLOUD_CONFIG_SYNC,this._handleLoginSuccess,this),r.subscribeInnerEvent(g.LOGOUT,this._reset,this),r.subscribeInnerEvent(g.DESTROY,this._dispose,this),u.registerExperimentalAPI("getServerConfig",this),this._updateCmdFreqLimitMap(Xc),D.registerBeforeSendInterceptor(this.checkMethodCallOverLimit,this)}getServerConfig(s){return mA(this,void 0,void 0,function*(){var r;const g={code:0,data:""};return s&&(g.data=((r=this._core.store.get("cloudConfig"))===null||r===void 0?void 0:r[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:r,interval:g}=this._cmdFrequencyLimitMap.get(s);let{startTime:u,methodCallCounter:E}=this._methodCallFrequencyMap.get(s);if(Date.now()-u>1e3*g)this._methodCallFrequencyMap.set(s,{startTime:Date.now(),methodCallCounter:1});else if(E+=1,this._methodCallFrequencyMap.set(s,{startTime:u,methodCallCounter:E}),E>r)throw new this._core.helper.ChatError({code:Al,replacement1:s})}_handlePushedConfig(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r,utils:{safeStringify:g}}=this._core;r.info("_handlePushedConfig",g(s)),yield this._updateCloudConfig(s)})}_handleLoginSuccess(){return mA(this,void 0,void 0,function*(){const{ssoLog:s,utils:{safeStringify:r}}=this._core;try{if(this._canFetch()){const g=yield bg(this._version);s.info("_fetchCloudConfigIfLogin",r(g)),yield this._updateCloudConfig(g)}this._core.helper.taskScheduler.addTask({id:$c,intervalMs:1e3,callback:this._fetchCloudConfigIfReady,context:this})}catch(g){s.debug("_fetchCloudConfigIfLogin",r(g))}})}_fetchCloudConfigIfReady(){return mA(this,void 0,void 0,function*(){const{ssoLog:s,utils:{safeStringify:r}}=this._core;if(this._canFetch())try{const g=yield bg(this._version);s.info("_fetchCloudConfigIfReady",r(g)),yield this._updateCloudConfig(g)}catch(g){s.error("_fetchCloudConfigIfReady",r(g))}})}_updateCloudConfig(s){return mA(this,void 0,void 0,function*(){const r=this._parseCloudConfig(s);r&&(this._core.store.set("cloudConfig",r),yield this._parseCmdFreqLimit(),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.CLOUD_CONFIG_UPDATE,r),this._core.notificationCenter.emitOuterEvent(this._core.OuterEvent.SERVER_CONFIG_UPDATED,{name:this._core.OuterEvent.SERVER_CONFIG_UPDATED,data:{config:r}}))})}_canFetch(){const{isLoggedIn:s}=this._core.store.get("login")||{};return s&&!this._isFetching&&Date.now()>=this._expirationTime}_parseCloudConfig(s){const{int32_error_code:r,str_error_message:g,str_json_config:u,uint32_expired_time:E,uint32_sdkappid:m,uint64_version:D}=s;let M=null;if(r===0){if(this._version!==D)try{M=JSON.parse(u),this._version=D}catch{}this._expirationTime=Date.now()+1e3*E}else this._expirationTime=r===void 0?Date.now()+36e5:Date.now()+12e4;return M}_parseCmdFreqLimit(){return mA(this,void 0,void 0,function*(){var s;let r=(s=yield this.getServerConfig("cmd_frequency_limit"))===null||s===void 0?void 0:s.data;const{isEmpty:g}=this._core.utils;if(!g(r))try{r=JSON.parse(r),this._updateCmdFreqLimitMap(r)}catch(u){console.warn(u)}})}_updateCmdFreqLimitMap(s){s.forEach(r=>{this._cmdFrequencyLimitMap.set(r.cmd,{interval:r.interval,count:r.count})})}_reset(){this._core.helper.taskScheduler.removeTask($c),this._core.store.clear("cloudConfig"),this._updateCmdFreqLimitMap(Xc),this._methodCallFrequencyMap.clear(),this._expirationTime=0,this._version=0,this._isFetching=!1}_dispose(){const{notificationCenter:s,InnerEvent:r}=this._core;s.unSubscribeInnerEvent(dI,this._handlePushedConfig,this),s.unSubscribeInnerEvent(r.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this),this._reset()}};class Wn{constructor(r=0,g=0){this.high=r,this.low=g}equal(r){return r!==null&&this.low===r.low&&this.high===r.high}toString(){const r=Number(this.high).toString(16);let g=Number(this.low).toString(16);if(g.length<8){let u=8-g.length;for(;u;)g=`0${g}`,u--}return r+g}}const vc={SEARCH_GRP_SNS:new Wn(0,Math.pow(2,1)).toString(),AV_HISTORY_MSG:new Wn(0,Math.pow(2,2)).toString(),GRP_COMMUNITY:new Wn(0,Math.pow(2,3)).toString(),MSG_TO_SPECIFIED_GRP_MBR:new Wn(0,Math.pow(2,4)).toString(),AV_MBR_LIST:new Wn(0,Math.pow(2,6)).toString(),USER_STATUS:new Wn(0,Math.pow(2,7)).toString(),CONV_MARK:new Wn(0,Math.pow(2,9)).toString(),CONV_GROUP:new Wn(0,Math.pow(2,10)).toString(),AV_BAN_MBR:new Wn(0,Math.pow(2,11)).toString(),MSG_EXT:new Wn(0,Math.pow(2,13)).toString(),GRP_COUNTER:new Wn(0,Math.pow(2,15)).toString(),PLUGIN_TRANSLATE:new Wn(Math.pow(2,6)).toString(),PLUGIN_VOICE_TO_TEXT:new Wn(Math.pow(2,7)).toString(),PLUGIN_CS:new Wn(Math.pow(2,8)).toString(),PLUGIN_PUSH:new Wn(Math.pow(2,9)).toString(),PLUGIN_BOT:new Wn(Math.pow(2,10)).toString(),MSG_REACTION:new Wn(Math.pow(2,16)).toString(),FOLLOW:new Wn(Math.pow(2,20)).toString()},ZI="CommercialConfig",XI="commercial-config";var wE=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:r,notificationCenter:g,constants:{WORKFLOW_NAME:u,WORKFLOW_STEP:E,InnerEvent:m}}=s;g.subscribeInnerEvent(m.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),g.subscribeInnerEvent(m.LOGOUT,this._handleLogout,this),g.subscribeInnerEvent(m.DESTROY,this._dispose,this),r.registerWorkflowStep(u.SYNC_SERVER_INFO_AFTER_LOGIN,E.COMMERCIAL_CONFIG_UPDATE,this._syncCommercialConfig,this),s.helper.registerExperimentalAPI("isCommercialAbilityEnabled",this),s.helper.registerExperimentalAPI("queryCommercialAbility",this)}isCommercialAbilityEnabled(s){return mA(this,void 0,void 0,function*(){const r=parseInt(s,10).toString(2),{length:g}=r;let u,E=!0;for(let m=g-1,D=0;m>=0;m--,D++)if(r.charAt(m)==="1"&&(u=D<32?new Wn(0,2**D).toString():new Wn(2**(D-32),0).toString(),!this._featureMap.get(u))){E=!1;break}return this._core.ssoLog.debug("isFeatureEnabled",`${ZI}.isFeatureEnabled decimalNumber:${s} key:${u} ret:${E}`),{code:0,data:{enabled:E}}})}queryCommercialAbility(){return this._purchaseBits}_fetchAndParseCommercialConfig(){return mA(this,void 0,void 0,function*(){var s;const{ssoLog:r,utils:{safeStringify:g},common:{buildAndSendPacket:u}}=this._core;try{this._isFetching=!0;const E=yield u({servcmd:"im_sdk_config_mgr.fetch_imsdk_purchase_bitsv2",data:{uint32_sdkappid:(s=this._core.store.get("instance"))===null||s===void 0?void 0:s.sdkAppId}});E&&(this._parseCommercialConfig(E),this._core.store.set("commercialConfig",this._methodKeyMap))}catch(E){r.error("_fetchAndParseCommercialConfig",g(E))}finally{this._isFetching=!1}})}_syncCommercialConfig(s){return mA(this,void 0,void 0,function*(){const{purchaseBits:r}=s?.data||{};r&&(this._parsePurchaseBits(r),this._core.store.set("commercialConfig",this._methodKeyMap)),this._canFetch()&&(yield this._fetchAndParseCommercialConfig()),this._core.helper.taskScheduler.addTask({id:XI,intervalMs:1e3,callback:this._fetchCommercialConfigIfReady,context:this})})}_canFetch(){var s;const r=(s=this._core.store.get("login"))===null||s===void 0?void 0:s.isLoggedIn,g=Date.now()>=this._expirationTime;return r&&!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:r}=this._core;if(typeof s!="object")return;const{int32_error_code:g,str_error_message:u,str_purchase_bits:E,uint32_expired_time:m}=s;g===0?(this._parsePurchaseBits(E),this._expirationTime=Date.now()+1e3*m):g===void 0?(r.warn("_parseCommercialConfig",`${ZI}._parseCommercialConfig failed. Invalid message format:`,s),this._expirationTime=Date.now()+36e5):(r.warn("_parseCommercialConfig",`${ZI}._parseCommercialConfig errorCode:${g} errorMessage:${u}`),this._expirationTime=Date.now()+12e4)}_isValidPurchaseBits(s){return s&&typeof s=="string"&&s.length>=1&&s.length<=64&&/[01]{1,64}/.test(s)}_parsePurchaseBits(s){const{ssoLog:r,utils:{safeStringify:g}}=this._core;if(this._isValidPurchaseBits(s)){this._purchaseBits=s,this._featureMap.clear(),this._methodKeyMap.clear();let u=null;for(let E=s.length-1,m=0;E>=0;E--,m++)if(u=m<32?new Wn(0,2**m).toString():new Wn(2**(m-32),0).toString(),s[E]==="1"){this._featureMap.set(u,!0);const D=this._getKeyByValue(vc,u);D&&this._methodKeyMap.set(D,!0)}else{this._featureMap.set(u,!1);const D=this._getKeyByValue(vc,u);D&&this._methodKeyMap.set(D,!1)}}else r.warn("_parsePurchaseBits",`${ZI}.parsePurchaseBits invalid purchases:${g(s)}`)}_getKeyByValue(s,r){const g=Object.entries(s).find(([u,E])=>E===r);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(XI),this._core.store.set("commercialConfig",{}),this._expirationTime=0,this._isFetching=!1,this._featureMap.clear(),this._purchaseBits="0"}},ch=new class{constructor(){this._core=null,this._serverOverloadInfoMap=new Map}install(s){this._core=s;const{notificationCenter:r,InnerEvent:g,channel:u}=this._core;r.subscribeInnerEvent(g.OVERLOAD_PUSH,this._handleOverLoadPush,this),r.subscribeInnerEvent(g.LOGOUT,this._reset,this),r.subscribeInnerEvent(g.DESTROY,this._dispose,this),u.registerBeforeSendInterceptor(this.checkServerOverload,this)}checkServerOverload(s){if(!this._serverOverloadInfoMap.has(s))return;const{overloadStartTimestamp:r,delaySeconds:g}=this._serverOverloadInfoMap.get(s);if(Date.now()-r<=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:r,DelaySecs:g}=s;this._serverOverloadInfoMap.set(r,{overloadStartTimestamp:Date.now(),delaySeconds:g})}_reset(){this._serverOverloadInfoMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:r}=this._core;s.unSubscribeInnerEvent(r.OVERLOAD_PUSH,this._handleOverLoadPush,this),s.unSubscribeInnerEvent(r.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this)}},dC=new class{constructor(){this.name="ConfigCenter"}install(s){va.init(s),Ds.install(s),wE.install(s),ch.install(s)}},lh=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 r=yield this._fetchErrorMessage();if(!r)return;const g=this._parseResponse(r);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:r}=s;return r&&new Date().getTime()-r>=6048e5}_parseResponse(s){if(typeof s=="string"){const r=s.split(`;
+`),g={},u=new RegExp(/'/g);for(let E=0;E{var qA,Ie,le;const bi=function(ki,Ot){const{From_Account:Li,From_AccountHeadurl:cs,From_AccountNick:Re,IsNeedReadReceipt:St,MsgBody:UA,MsgClientTime:ai,MsgRandom:_s,MsgSeq:Ui,MsgTimeStamp:Or,SendMsgControl:Vi,SupportMessageExtension:Ir,To_Account:Nt,TinyId:Gt,MsgCheckResult:iE,CloudCustomData:ln,IsPeerRead:Qo,MsgFlagBits:Il,MsgVersion:GC,EventArray:Tr}=ki;return{from:Li,avatar:cs,nick:Re,needReadReceipt:St===1,readReceiptSentByPeer:Qo,clientTime:ai,messageFlagBits:Il,random:_s,sequence:Ui,time:Or,messageControlInfo:Vi,isSupportExtension:Ir,to:Nt,tinyID:Gt,checkResult:iE,cloudCustomData:ln,messageVersion:GC,eventArray:Tr,elements:Ot.message.messageHelper.parseServerPushMessageElement(UA)}}(OA,xA);if(!((le=(Ie=(qA=OA?.EventArray)===null||qA===void 0?void 0:qA[0])===null||Ie===void 0?void 0:Ie.hasOwnProperty)===null||le===void 0)&&le.call(Ie,"C2cNotifyMsgArray"))SA.push(...function(ki){var Ot;const Li=[];return(Ot=ki.EventArray)===null||Ot===void 0||Ot.forEach(cs=>{var Re,St;const{C2cNotifyMsgArray:UA}=cs,ai=(St=(Re=UA?.[0])===null||Re===void 0?void 0:Re.WithdrawC2cMsgNotify)===null||St===void 0?void 0:St.C2cWithdrawInfoArray;Array.isArray(ai)&&Li.push(...ai)}),Li}(OA));else{const ki=xA.message.messageFactory.createMessage(Object.assign(Object.assign({},bi),{conversationType:"C2C",flow:"in"})),{elements:Ot}=bi;ki.setElement(Ot),LA.push(ki)}}),{unreadMessageList:LA,revokedMessageList:SA}}(T.MsgList,r);return{syncFlag:T?.SyncFlag,unreadMessageList:EA,revokedMessageList:wA,unreadCountList:P,overflowUnreadCountList:W,cookie:T?.Cookie,groupTipList:oA}}catch(T){console.warn(T)}})}var kg,ao;(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"}(ao||(ao={}));var CC=new class{constructor(){this.name="UnreadMessageSynchronizer",this._unreadDBMessageMap=new Map,this._cookie="",this._localConversationIDListBeforeDisconnect=[]}install(s){this._core=s;const{constants:r}=s;s.helper.registerWorkflowStep(r.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,r.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterReOnline,this),s.helper.registerWorkflowStep(r.WORKFLOW_NAME.RECEIVE_C2C_NEW_MESSAGE,r.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterNewMessageReceived,this),s.helper.registerWorkflowStep(r.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_LOGIN,r.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:r=!1,isAfterNewMessageReceived:g=!1,isAfterLogin:u=!1}=s||{};let E=kg.START_SYNC;const m=[],D=[],M=[],T=[];for(;this._canContinueSync({cookie:this._cookie,syncFlag:E});){const P=yield this._fetchUnreadDBMessage({cookie:this._cookie,syncFlag:E,syncTriggerEvent:g?ao.NEW_MESSAGE_RECEIVED:ao.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),r){const{messages:xA}=this._handleNewMessageList(W);T.push(...xA)}}return r?{conversationUpdateFieldList:m,revokedMessageList:M,unreadMessageMap:this._unreadDBMessageMap,groupTipList:D,messages:T,isUnreadC2CMessage:!0}:{conversationUpdateFieldList:m,isInstantMessage:!u,isUnreadC2CMessage:!0,revokedMessageList:M,unreadMessageMap:this._unreadDBMessageMap,groupTipList:D}})}_syncUnreadDBMessageAfterLogin(){return 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:r,overflowUnreadCountList:g,conversationUpdateFieldList:u}=s,{constants:{OuterConstant:{CONV_C2C:E,CONV_SYSTEM:m}}}=this._core;r?.forEach(D=>{const{From_Account:M,UnreadCount:T}=D;if(M!==m){const P=u.find(({conversationID:W})=>W===`${E}${M}`);P?P.unreadCount=T:u.push({conversationID:`${E}${M}`,unreadCount:T,type:E})}}),g?.forEach(D=>{const{From_Account:M,LastMsgTime:T}=D;M!==m&&(u.find(({conversationID:P})=>P===`${E}${M}`)||u.push({conversationID:`${E}${M}`,type:E,lastMsgTime:T}))})}_syncUnreadDBMessageAfterReOnline(){return mA(this,void 0,void 0,function*(){return this._syncUnreadMessage({isAfterReOnline:!0})})}_updateMessageProfile(s){var r;const{messageDataHandler:g}=this._core.message||{},u=(r=this._core.store.get("login"))===null||r===void 0?void 0:r.userId,{from:E,nick:m,avatar:D,conversationID:M=""}=s;if(E!==u){const T=g.getLatestMsgSentByPeer(M);if(T){const{nick:P,avatar:W}=T;m&&D?m===P&&D===W||g.updateNickAndAvatarOfSentMessage({conversationID:M,latestNick:m,latestAvatar:D,isSentByMe:!1}):(s.nick=P,s.avatar=W)}}else{const T=g.getLatestMsgSentByMe(M);!T||m===T.nick&&D===T.avatar||g.updateNickAndAvatarOfSentMessage({conversationID:M,latestNick:m,latestAvatar:D,isSentByMe:!0})}}_handleNewMessageList(s){const{messageDataHandler:r}=this._core.message||{},g=new Map,u=[];return s.forEach(E=>{this._updateMessageProfile(E);let m=E.isModified===1;if(r.isMessageSentByCurrentInstance(E)?E.isModified=m:m=!1,E.isOnlineMessage())E._onlineOnlyFlag=!0,r.isMessageSentByCurrentInstance(E)||u.push(E);else if(this._shouldStoreUnreadMessage(E)){if(r.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})}r.isMessageSentByCurrentInstance(E)&&!m||u.push(E)}}),{messages:u,conversationOptions:g}}_shouldStoreUnreadMessage(s){var r;const{conversationID:g}=s,{message:u,appStore:E,utils:{isEmpty:m}}=this._core||{},D=Array.from(((r=E.conversationStore.getConversationMap())===null||r===void 0?void 0:r.keys())||[]),M=this._getLocalLastMessageTime(g);return!u.messageDataHandler.isInMessageList(s)&&D.includes(g)&&this._localConversationIDListBeforeDisconnect.includes(g)&&!m(M)}_fetchUnreadDBMessage(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r,utils:{safeStringify:g}}=this._core;try{r.debug("_fetchUnreadDBMessage",`unread-message-synchronizer._fetchUnreadDBMessage options:${g(s)}`);const E=yield el(s,this._core);if(!E)return null;const{syncFlag:m,unreadMessageList:D,revokedMessageList:M,cookie:T,unreadCountList:P,overflowUnreadCountList:W,groupTipList:oA}=E;return this._parseAndSaveUnreadMessageList(D),{syncFlag:m,cookie:T,unreadMessageList:D,revokedMessageList:M,unreadCountList:P,overflowUnreadCountList:W,groupTipList:oA}}catch(u){console.log(u)}})}_canContinueSync({cookie:s,syncFlag:r}){var g;return r===kg.START_SYNC||r===kg.SYNCING&&!(!((g=this._core)===null||g===void 0)&&g.helper.isEmpty(s))}_parseAndSaveUnreadMessageList(s){s.forEach(r=>{const{ID:g}=r;this._unreadDBMessageMap.set(g,r)})}_handleDisconnect(){var s;const{appStore:r}=this._core;this._localConversationIDListBeforeDisconnect=Array.from(((s=r.conversationStore.getConversationMap())===null||s===void 0?void 0:s.keys())||[])}_getLocalLastMessageTime(s){const{message:r}=this._core,g=r.messageDataHandler.getLocalMessageList(s),u=g[g.length-1];return u?.time}_reset(){this._cookie="",this._unreadDBMessageMap.clear()}_dispose(){var s,r;(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),(r=this._core)===null||r===void 0||r.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),this._reset()}},_E=new class{init(s){var r;this._core=s,this._visibilityChangeHandler=this._handleVisibilityChange.bind(this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this),document?.addEventListener("visibilitychange",this._visibilityChangeHandler),(r=this._core)===null||r===void 0||r.store.set("activityMonitor",{isActive:!0})}_handleVisibilityChange(){var s,r;const g=document?.visibilityState==="visible";(s=this._core)===null||s===void 0||s.store.set("activityMonitor",{isActive:g}),(r=this._core)===null||r===void 0||r.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:r}=this._core;s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this),this._reset()}},TE=new class{init(s){var r;this._core=s,this._bindAppActivityEvent(),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this),(r=this._core)===null||r===void 0||r.store.set("activityMonitor",{isActive:!0})}_bindAppActivityEvent(){var s,r,g,u,E;const{MINI_APP_NAMESPACE:m,IN_TT_MINI_GAME:D,IN_WX_MINI_GAME:M}=((s=this._core)===null||s===void 0?void 0:s.utils)||{};D||M?((r=m?.onShow)===null||r===void 0||r.call(m,()=>{var T,P;(T=this._core)===null||T===void 0||T.store.set("activityMonitor",{isActive:!0}),(P=this._core)===null||P===void 0||P.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})}),(g=m?.onHide)===null||g===void 0||g.call(m,()=>{var T,P;(T=this._core)===null||T===void 0||T.store.set("activityMonitor",{isActive:!1}),(P=this._core)===null||P===void 0||P.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})})):((u=m?.onAppShow)===null||u===void 0||u.call(m,()=>{var T,P;(T=this._core)===null||T===void 0||T.store.set("activityMonitor",{isActive:!0}),(P=this._core)===null||P===void 0||P.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})}),(E=m?.onAppHide)===null||E===void 0||E.call(m,()=>{var T,P;(T=this._core)===null||T===void 0||T.store.set("activityMonitor",{isActive:!1}),(P=this._core)===null||P===void 0||P.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})}))}_reset(){var s;(s=this._core)===null||s===void 0||s.store.clear("activityMonitor")}_dispose(){const{notificationCenter:s,InnerEvent:r}=this._core;s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this),this._reset()}},hd=new class{init(s){const{IN_MINI_APP:r,IN_WX_MINI_PLUGIN:g}=s.helper;g||(r?TE.init(s):_E.init(s))}};const NE="none",tl="online";var CI=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 r,g;const{isConnected:u,networkType:E}=s;(r=this._core)===null||r===void 0||r.store.set("netWorkMonitor",{isNetworkOnline:u,networkType:E}),(g=this._core)===null||g===void 0||g.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:u,networkType:E})}_onOnline(){this._onNetworkStatusChange({isConnected:!0,networkType:tl})}_onOffline(){this._onNetworkStatusChange({isConnected:!1,networkType:NE})}_reset(){var s;this._deactivateNetworkMonitoring(),(s=this._core)===null||s===void 0||s.store.clear("netWorkMonitor")}_dispose(){var s,r;(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent((r=this._core)===null||r===void 0?void 0:r.InnerEvent.DESTROY,this._dispose,this),this._reset()}},Uu=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 r,g;const{isConnected:u,networkType:E}=s;(r=this._core)===null||r===void 0||r.store.set("netWorkMonitor",{isNetworkOnline:u,networkType:E}),(g=this._core)===null||g===void 0||g.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:u,networkType:E})}_reset(){var s;this._deactivateNetworkMonitoring(),(s=this._core)===null||s===void 0||s.store.clear("netWorkMonitor")}_dispose(){var s,r;(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent((r=this._core)===null||r===void 0?void 0:r.InnerEvent.DESTROY,this._dispose,this),this._reset()}},Fu=new class{init(s){const{IN_MINI_APP:r}=s.utils;r?Uu.init(s):CI.init(s)}},hC=new class{constructor(){this.name="SystemStateMonitor"}install(s){hd.init(s),Fu.init(s)}};const wr=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=wr}install(s){this._core=s;const{notificationCenter:r,InnerEvent:g,helper:u}=s;r.subscribeInnerEvent(g.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),r.subscribeInnerEvent(g.LOGOUT,this._reset,this),r.subscribeInnerEvent(g.DESTROY,this._dispose,this),r.subscribeInnerEvent("im_open_push.msg_push",r.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this),u.registerExperimentalAPI("sendTRTCCustomData",this,"transferBusinessCommand"),u.registerExperimentalAPI("sendRoomCustomData",this,"transferBusinessCommand")}transferBusinessCommand(s){return mA(this,void 0,void 0,function*(){const r="transferBusinessCommand";try{const{serviceCommand:g=cg}=s||{};if(!this._isValidTransferredCommand(g))throw new this._core.helper.ChatError({code:2995,functionName:r});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(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:r})}})}_onCloudConfigUpdate(s={}){try{if(typeof s.rtc_cmd!="string")return;const r=JSON.parse(s.rtc_cmd);Array.isArray(r)&&(this._transferredCommands=new Set([...this._transferredCommands,...r]))}catch(r){console.log(r)}}_isValidTransferredCommand(s=""){const r=`${s?.split(".")[0]}.*`;return this._transferredCommands.has(r)}_onServerPushBusinessCommand(s){const{OuterEvent:r,notificationCenter:g}=this._core,{MsgContent:u}=s||{},{ROOM_CUSTOM_DATA_RECEIVED:E}=r;g.emitOuterEvent(E,{name:E,data:u})}_reset(){this._transferredCommands=wr}_dispose(){const{notificationCenter:s,InnerEvent:r}=this._core;this._reset(),s.unSubscribeInnerEvent(r.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),s.unSubscribeInnerEvent(r.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this),s.unSubscribeInnerEvent("im_open_push.msg_push",s.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this)}};const Ou=1,Nl=2,Bd=3,Aa=4,hI=5,_n="TIMCustomElem",BC="C2C",il="GROUP",Qd="invite",BI="accept",Oa="cancel",QC="reject",Pa="modifyInvitation",hr="signaling",pd=8010,Pu="signaling-timeout";function Br(s){return s.filter(r=>{if(r.type===_n){const{cloudCustomData:g="",payload:{data:u=""}={}}=r,E=g.match(/"type":"tsignaling"/),m=u.match(/inviteID/),D=u.match(/actionType/);return E||m&&D}return!1})}function wc(s){const{data:r}=s.payload;try{return JSON.parse(r)}catch(g){return console.error(g),null}}function ol(s,r){return s.toString(16).padStart(r,"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 r=`${hr}.updateSignaling`,{inviteID:g,inviter:u,inviteeList:E,groupID:m}=s;if(console.log(`${r} inviteID:${g} inviter:${u} groupID:${m}`),m&&this.hasSignaling(g)){const D=E[0],{inviteeList:M}=this._onlineSignalingMap.get(g);M.includes(D)&&(M.splice(M.indexOf(D),1),console.log(`${r} 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,r;this._reset(),(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),(r=this._core)===null||r===void 0||r.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 r=this._generateInviteID(),g=this._createInviteSignalingData(Object.assign(Object.assign({},s),{inviteID:r})),{groupID:u,inviteeList:E}=g,m=u||E[0];return{signaling:this._createSignaling(g,m),signalingData:g,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createAcceptSignaling(s){const r=this._createAcceptSignalingData(s),{groupID:g,inviter:u}=r,E=g||u;return{signaling:this._createSignaling(r,E),signalingData:r,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createCancelSignaling(s){const r=this._createCancelSignalingData(s),{groupID:g,inviteeList:u}=r,E=g||u[0];return{signaling:this._createSignaling(r,E),signalingData:r,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createRejectSignaling(s){const r=this._createRejectSignalingData(s),{groupID:g,inviter:u}=r,E=g||u;return{signaling:this._createSignaling(r,E),signalingData:r,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createTimeoutSignaling(s){const{isInviter:r=!1}=s,g=this._createTimeoutSignalingData(s),{groupID:u,inviteeList:E,inviter:m}=g,D=u||(r?E[0]:m);return{signaling:this._createSignaling(g,D),signalingData:g,signalingExtensionOptions:this._createSignalingExtensionOptions(g)}}_createSignalingExtensionOptions(s){var r,g;const{data:u="",onlineUserOnly:E,inviteID:m="",offlinePushInfo:D,actionType:M}=s,T=((g=(r=Po.getSignaling(m))===null||r===void 0?void 0:r.signaling)===null||g===void 0?void 0:g._onlineOnlyFlag)||!1;return{onlineUserOnly:E||T,offlinePushInfo:D,messageControlInfo:this._createMessageControlInfo(u,M)}}_createMessageControlInfo(s,r){const g=r===hI&&!!s.match(/excludeTimeoutSignalingFromHistoryMessage/),u=!!s.match(/excludeFromHistoryMessage/)||!!s.match(/excludeOriginalSignalingFromHistoryMessage/);return{excludedFromContentModeration:!0,excludedFromUnreadCount:g||u,excludedFromLastMessage:g||u}}_createInviteSignalingData(s){const r=`${hr}._createInviteSignalingData`,{userID:g,timeout:u=0,groupID:E="",inviteeList:m=[]}=s,D=this._core.common.getCurrentUserID(),M=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:Ou,inviter:D,inviteeList:E?m:[g],timeout:u});return console.log(`${r} signalingData:`,M),M}_createAcceptSignalingData(s){const r=`${hr}._createAcceptSignalingData`,{inviteID:g}=s,u=this._core.common.getCurrentUserID(),{inviter:E,groupID:m}=Po.getSignaling(g),D=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:Bd,groupID:m,inviter:E,inviteeList:[u]});return console.log(`${r} signalingData:`,D),D}_createCancelSignalingData(s){const r=`${hr}._createCancelSignalingData`,{inviteID:g}=s,u=this._core.common.getCurrentUserID(),{inviteeList:E,groupID:m}=Po.getSignaling(g),D=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:Nl,groupID:m,inviter:u,inviteeList:E});return console.log(`${r} signalingData:`,D),D}_createRejectSignalingData(s){const r=`${hr}._createRejectSignalingData`,{inviteID:g}=s,u=this._core.common.getCurrentUserID(),{inviter:E,groupID:m}=Po.getSignaling(g),D=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:Aa,groupID:m,inviter:E,inviteeList:[u]});return console.log(`${r} signalingData:`,D),D}_createTimeoutSignalingData(s){const r=`${hr}._createTimeoutSignalingData`,{isInviter:g=!1,inviteID:u}=s,{inviteeList:E,inviter:m}=Po.getSignaling(u),D=this._core.common.getCurrentUserID(),M=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:hI,inviter:m,inviteeList:g?E:[D]});return console.log(`${r} signalingData:`,M),M}_createSignaling(s,r){var g,u,E;const{groupID:m=""}=s,D={to:r,conversationType:m?il:BC,priority:"High",payload:{data:JSON.stringify(s)}};return(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageFactory)===null||E===void 0?void 0:E.createCustomMessage(D)}_generateInviteID(){return[ol(Lg(32),8),ol(Lg(16),4),ol(16384|Lg(12),4),ol(32768|Lg(14),4),ol(Lg(48),12)].join("-")}_generateBaseSignalData(s){const{data:r="",inviteID:g="",groupID:u=""}=s;return{businessID:1,timeout:0,data:r,inviteID:g,groupID:u}}},Za=new class{constructor(){this._isProcessingSignaling=!1}init(s){this._core=s,s.helper.registerApi({apiName:"invite",context:this}),s.helper.registerApi({apiName:"accept",context:this}),s.helper.registerApi({apiName:"cancel",context:this}),s.helper.registerApi({apiName:"reject",context:this}),s.helper.registerApi({apiName:"modifyInvitation",context:this}),s.helper.registerApi({apiName:"getSignalingInfo",context:this}),s.helper.registerApi({apiName:"addSignalingListener",context:this}),s.helper.registerApi({apiName:"removeSignalingListener",context:this}),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.LOGOUT,this._reset,this)}invite(s){return mA(this,void 0,void 0,function*(){var r;try{this._validateBeforeInvite(s);const{signaling:g,signalingData:u,signalingExtensionOptions:E}=$g.createInviteSignaling(s),m=yield this._sendSignaling(g,E);if(m?.code===0){const{inviteID:D,timeout:M}=u;return Po.saveSignaling(D,Object.assign(Object.assign({},u),{signaling:g})),M>0&&((r=this._core)===null||r===void 0||r.helper.taskScheduler.addOnceTask({id:`${Pu}-${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:r}=s;this._validateBeforeAccept(r),this._isProcessingSignaling=!0;const{signaling:g,signalingData:u,signalingExtensionOptions:E}=$g.createAcceptSignaling(s),m=yield this._sendSignaling(g,E);return m?.code===0?(Po.updateSignaling(u),Object.assign(Object.assign({},m),{inviteID:r})):m}catch(r){throw r}finally{this._isProcessingSignaling=!1}})}cancel(s){return mA(this,void 0,void 0,function*(){try{const{inviteID:r}=s;this._validateBeforeCancel(r),this._isProcessingSignaling=!0;const{signaling:g,signalingExtensionOptions:u}=$g.createCancelSignaling(s),E=yield this._sendSignaling(g,u);return E?.code===0?(Po.removeSignaling(r),Object.assign(Object.assign({},E),{inviteID:r})):E}catch(r){throw r}finally{this._isProcessingSignaling=!1}})}reject(s){return mA(this,void 0,void 0,function*(){try{const{inviteID:r}=s;this._validateBeforeReject(r),this._isProcessingSignaling=!0;const{signaling:g,signalingExtensionOptions:u}=$g.createRejectSignaling(s),E=yield this._sendSignaling(g,u);return E?.code===0?(Po.removeSignaling(r),Object.assign(Object.assign({},E),{inviteID:r})):E}catch(r){throw r}finally{this._isProcessingSignaling=!1}})}modifyInvitation(s){return mA(this,void 0,void 0,function*(){var r,g;const{inviteID:u,data:E}=s;let m="";try{this._validateBeforeModifyInvitation(u);const D=Po.getSignaling(u),{signaling:M}=D,T=So(D,["signaling"]);m=M.payload.data,T.data=E,M.payload.data=JSON.stringify(T);const P=yield(g=(r=this._core)===null||r===void 0?void 0:r.message.messageAction)===null||g===void 0?void 0:g.modifyMessage(M);return Po.hasSignaling(u)&&Po.saveSignaling(u,Object.assign(Object.assign({},T),{signaling:M})),P}catch(D){if(m){const{signaling:M}=Po.getSignaling(u);M.payload.data=m}throw D}})}getSignalingInfo(s){const{ssoLog:r,utils:{safeStringify:g}}=this._core;if(Br([s]).length===0)return;const u=wc(s),E={businessID:u.businessID||1,inviteID:u.inviteID,groupID:u.groupID||"",inviter:u.inviter||"",inviteeList:u.inviteeList||[],data:u.data||"",actionType:u.actionType||Ou,timeout:u.timeout||0};return r.debug(`${hr} getSignalingInfo ${g(E)}`),E}addSignalingListener(s,r,g){var u,E;s===((u=this._core)===null||u===void 0?void 0:u.SignalingEvent.NEW_INVITATION_RECEIVED)&&Po.setSignalingListenStatus(!0),(E=this._core)===null||E===void 0||E.notificationCenter.subscribeOuterEvent(s,r,g)}removeSignalingListener(s,r,g){var u,E;s===((u=this._core)===null||u===void 0?void 0:u.SignalingEvent.NEW_INVITATION_RECEIVED)&&Po.setSignalingListenStatus(!1),(E=this._core)===null||E===void 0||E.notificationCenter.unSubscribeOuterEvent(s,r,g)}handleInvitationExpiryTimer(s){const r=Po.getOnlineSignalingMap(),g=this._core.common.getCurrentUserID();if(!r.has(s))return;const u=r.get(s).inviter===g;this._sendTimeoutNotice({inviteID:s,isInviter:u})}_sendSignaling(s,r){return mA(this,void 0,void 0,function*(){var g,u,E;return(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageSender)===null||E===void 0?void 0:E.sendMessage(s,r)})}_sendTimeoutNotice(s){return mA(this,void 0,void 0,function*(){var r,g,u;this._core.ssoLog.debug("_sendTimeoutNotice",`${hr}._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:oA,inviteeList:EA,inviter:wA}=M;(r=this._core)===null||r===void 0||r.notificationCenter.emitOuterEvent((g=this._core)===null||g===void 0?void 0:g.SignalingEvent.INVITATION_TIMEOUT,{name:(u=this._core)===null||u===void 0?void 0:u.SignalingEvent.INVITATION_TIMEOUT,data:{data:W,groupID:oA,inviteID:m,inviteeList:EA,inviter:wA,isSelfTimeout:!0,message:D}}),E?Po.removeSignaling(m):Po.updateSignaling(M)}})}_validateInviteId(s,r){if(!Po.hasSignaling(r))throw new this._core.helper.ChatError({functionName:s,code:pd})}_validateProcessStatus(s){if(this._isProcessingSignaling)throw new this._core.helper.ChatError({functionName:s,message:"processing other signaling operations"})}_validateBeforeInvite(s){const r=Qd,{userID:g}=s,u=this._core.common.getCurrentUserID();if(g===u)throw new this._core.helper.ChatError({functionName:r,message:`cannot invite yourself, currentUserId:${u}, inviteeId:${g}`})}_validateBeforeAccept(s){const r=BI;this._validateInviteId(r,s),this._validateProcessStatus(r);const g=this._core.common.getCurrentUserID(),{inviteeList:u}=Po.getSignaling(s);if(!u.includes(g)){const E=`userID:${g} not in inviteeList. inviteID:${s}`;throw new this._core.helper.ChatError({functionName:r,message:E})}}_validateBeforeCancel(s){const r=Oa;this._validateInviteId(r,s),this._validateProcessStatus(r);const g=this._core.common.getCurrentUserID(),{inviter:u}=Po.getSignaling(s);if(u!==g){const E=`unmatched inviter:${u} and my userID:${g}`;throw new this._core.helper.ChatError({functionName:r,message:E})}}_validateBeforeReject(s){const r=QC;this._validateInviteId(r,s),this._validateProcessStatus(r);const g=this._core.common.getCurrentUserID(),{inviteeList:u}=Po.getSignaling(s);if(!u.includes(g)){const E=`userID:${g} not in inviteeList. inviteID:${s}`;throw new this._core.helper.ChatError({functionName:r,message:E})}}_validateBeforeModifyInvitation(s){const r=Pa;this._validateInviteId(r,s)}_dispose(){var s,r;this._reset(),(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),(r=this._core)===null||r===void 0||r.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this)}_reset(){this._isProcessingSignaling=!1}},Gl=new class{constructor(){this._actionProcessor=new Map([[Ou,this._onNewInvitationReceived.bind(this)],[Aa,this._onInviteeRejected.bind(this)],[Bd,this._onInviteeAccepted.bind(this)],[Nl,this._onInvitationCancelled.bind(this)],[hI,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(r=>{const g=wc(r);if(g){const u=this._actionProcessor.get(g.actionType);u?.(g,r)}})}_handleMessageReceived(s){if(!Po.getSignalingListenStatus())return;const r=Br(s.data);r.length!==0&&this.handleActionSignaling(r)}_handleMessageModified(s){if(!Po.getSignalingListenStatus())return;const r=Br(s.data);r.length>0&&r.forEach(g=>{const u=wc(g);u&&this._onInvitationModified(u,g)})}_onNewInvitationReceived(s,r){var g,u;const E=`${hr}._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-r.time;P>0&&W>0&&P>W&&(P-=W);const oA=Po.getSignaling(m);oA!==s&&(oA||Po.saveSignaling(m,Object.assign(Object.assign({},s),{signaling:r})),P>0&&((g=this._core)===null||g===void 0||g.helper.taskScheduler.addOnceTask({id:`${Pu}-${m}`,intervalMs:1e3*P,callback:Za.handleInvitationExpiryTimer.bind(Za,m)})),this._emitEvent({name:(u=this._core)===null||u===void 0?void 0:u.SignalingEvent.NEW_INVITATION_RECEIVED,data:Object.assign(Object.assign({},this._generateBaseEmitData(s)),{inviteeList:D})}))}_onInviteeRejected(s){var r;const g=`${hr}._onInviteeRejected`,{inviteID:u,inviter:E,groupID:m,inviteeList:D}=s,M=Po.hasSignaling(u);this._core.ssoLog.debug("_onInviteeRejected",`${g} inviteID:${u} hasInviteID:${M} inviter:${E} groupID:${m}`),M&&(Po.updateSignaling(s),this._emitEvent({name:(r=this._core)===null||r===void 0?void 0:r.SignalingEvent.INVITEE_REJECTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(s)),{invitee:D[0]})}))}_onInviteeAccepted(s){var r;const g=`${hr}._onInviteeAccepted`,{inviteID:u,inviter:E,groupID:m,inviteeList:D}=s,M=Po.hasSignaling(u);this._core.ssoLog.debug("_onInviteeAccepted",`${g} inviteID:${u} hasInviteID:${M} inviter:${E} groupID:${m}`),M&&(Po.updateSignaling(s),this._emitEvent({name:(r=this._core)===null||r===void 0?void 0:r.SignalingEvent.INVITEE_ACCEPTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(s)),{invitee:D[0]})}))}_onInvitationCancelled(s){var r;const g=`${hr}._onInvitationCancelled`,{inviteID:u,inviter:E,groupID:m}=s,D=Po.hasSignaling(u);this._core.ssoLog.debug("_onInvitationCancelled",`${g} inviteID:${u} hasInviteID:${D} inviter:${E} groupID:${m}`),D&&(Po.removeSignaling(u),this._emitEvent({name:(r=this._core)===null||r===void 0?void 0:r.SignalingEvent.INVITATION_CANCELLED,data:this._generateBaseEmitData(s)}))}_onInvitationTimeout(s){var r;const g=`${hr}._onInvitationTimeout`,{inviteID:u,inviteeList:E}=s,m=Po.hasSignaling(u);this._core.ssoLog.debug("_onInvitationTimeout",`${g} inviteID:${u} hasInviteID:${m} data:${s.data}`),m&&(Po.updateSignaling(s),this._emitEvent({name:(r=this._core)===null||r===void 0?void 0:r.SignalingEvent.INVITATION_TIMEOUT,data:Object.assign(Object.assign({},this._generateBaseEmitData(s)),{inviteeList:E,isSelfTimeout:!1})}))}_onInvitationModified(s,r){var g;const u=`${hr}._onInvitationModified`,{inviteID:E,data:m}=s,D=Po.hasSignaling(E);this._core.ssoLog.debug("_onInvitationModified",`${u} inviteID:${E} data:${m}`),D&&(Po.saveSignaling(E,Object.assign(Object.assign({},s),{signaling:r})),this._emitEvent({name:(g=this._core)===null||g===void 0?void 0:g.SignalingEvent.INVITATION_MODIFIED,data:{inviteID:E,data:m}}))}_emitEvent(s){var r;(r=this._core)===null||r===void 0||r.notificationCenter.emitOuterEvent(s.name,s)}_generateBaseEmitData(s){const{inviteID:r,inviter:g,groupID:u,data:E}=s;return{inviteID:r,inviter:g,groupID:u,data:E||""}}_dispose(){var s,r,g;(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),(r=this._core)===null||r===void 0||r.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)}},ea=new class{constructor(){this._offlineSignalingMap=new Map}init(s){this._core=s;const{notificationCenter:r,helper:g,constants:{InnerEvent:u,WORKFLOW_STEP:E,WORKFLOW_NAME:m}}=s;r.subscribeInnerEvent(u.DESTROY,this._dispose,this),r.subscribeInnerEvent(u.LOGOUT,this._reset,this),g.registerWorkflowStep(m.SYNC_SERVER_INFO_AFTER_LOGIN,E.SIGNALING_MESSAGE_RECOVER,this._handleC2COfflineMessage,this)}_handleC2COfflineMessage(s){const{result:{unreadMessageMap:r}={}}=s||{};if(!(r?.size!==0&&Po.getSignalingListenStatus()))return;const g=Br([...r.values()]);if(g.length!==0&&(g.forEach(u=>{this._handleC2CActionType(u)}),this._offlineSignalingMap.size>0)){const u=this._sortOfflineSignalingByTime();Gl.handleActionSignaling(u)}}_handleC2CActionType(s){const r=wc(s);if(!r)return;const{actionType:g}=r;g===Ou?this._saveValidOfflineInvite(r,s):this._removeOfflineInvite(r)}_saveValidOfflineInvite(s,r){const{inviteID:g,inviteeList:u=[],timeout:E=0}=s,m=this._core.common.getCurrentUserID();if(!u.includes(m))return;const D=Date.now()/1e3-r.time;E>0&&D>E&&E!==0||this._offlineSignalingMap.set(g,Object.assign(Object.assign({},s),{signalingList:[r]}))}_removeOfflineInvite(s){const{inviteID:r=""}=s;this._offlineSignalingMap.has(r)&&this._offlineSignalingMap.delete(r)}_sortOfflineSignalingByTime(){let s=[];return this._offlineSignalingMap.forEach(r=>{s=[...s,...r.signalingList]}),s.sort((r,g)=>r.time-g.time)}_dispose(){var s,r;this._reset(),(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),(r=this._core)===null||r===void 0||r.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._offlineSignalingMap.clear()}};const Ih={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 $I=new class{constructor(){this.name="Signaling"}install(s){Za.init(s),Gl.init(s),$g.init(s),Po.init(s),ea.init(s),s.helper.registerValidateConfig({auth:js,params:Ih})}};const Fs=new class{init(s){this.core=s}};function _c(s){let r;const{message:g}=Fs.core,{conversationID:u,messageID:E}=s;return r=g.messageDataHandler.getLocalMessageList(u).find(m=>m.ID===E),!r&&(r=g.messageDataHandler.getSparseMessageList(u).find(m=>m.ID===E)),r}function Ac(s){return s.map(r=>{const{from:g,to:u,cloudCustomData:E,avatar:m,nick:D,ID:M,clientSequence:T,clientTime:P,messageRandom:W,messageSequence:oA,time:EA}=r;return{ClientSeq:T,CloudCustomData:E,From_Account:g,From_AccountHeadurl:m,From_AccountNick:D,Id:M,MsgBody:JSON.parse(JSON.stringify(r.transformElementsToServerFormat())),MsgClientTime:P,MsgRandom:W,Random:W,MsgSeq:oA,MsgTimeStamp:EA,ReceiverId:u,SenderId:g,To_Account:u}})}function Qr(s){var r;const{From_Account:g,From_AccountHeadurl:u,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:u,nick:E,clientTime:D,time:P,tinyID:W,random:oA,sequence:EA,to:T,groupID:m,clientSequence:M,_elements:(r=s.MsgBody)===null||r===void 0?void 0:r.map(wA=>{const{MsgType:kA}=wA;return Fs.core.message.messageFactory.getElementClass(kA).parseServerPushElement(wA)})}}var Vr,Xa;(function(s){s.MSG_TEXT="TIMTextElem",s.MSG_CUSTOM="TIMCustomElem",s.MSG_LOCATION="TIMLocationElem",s.MSG_FACE="TIMFaceElem",s.MSG_STREAM="TIMStreamElem"})(Vr||(Vr={})),function(s){s[s.FORWARD=0]="FORWARD",s[s.BACKWARD=1]="BACKWARD"}(Xa||(Xa={}));const GE="MSG_REACTION",pC="MSG_EXT",uh=0,go=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"},bl="16k_zh",mC="16k_en",fC="16k_yue",kl="16k_ja",Au="16k_zh-PY",QI={[Tc.ZH_CN]:bl,[Tc.EN_US]:mC,[Tc.YUE_HK]:fC,[Tc.JA_JP]:kl,[Tc.ZH_PY]:Au},pI=/\.(wav|pcm|ogg-opus|speex|silk|mp3|m4a|aac|amr)/,bE={READ:0,UNREAD:1},Ll=1,Ul=2,Ug=3;var ec;(function(s){s.IN="in",s.OUT="out"})(ec||(ec={}));const md=16,kE=17;var Nc;(function(s){s[s.DATA=0]="DATA",s[s.REVOKED=1]="REVOKED"})(Nc||(Nc={}));var eu;(function(s){s[s.NORMAL=0]="NORMAL",s[s.TIMEOUT=1]="TIMEOUT"})(eu||(eu={}));const Io="StreamMsg.PushStreamHttp";var LE=new class{constructor(){this._reactionsMap=new Map}init(s){this._core=s;const{helper:r,notificationCenter:g,InnerEvent:{MESSAGE_PUSH:u},InnerEventSubType:{MESSAGE_REACTION_UPDATED:E,MESSAGE_REACTION_UPDATED_SYNC:m}}=s;r.registerApi({apiName:"addMessageReaction",context:this}),r.registerApi({apiName:"removeMessageReaction",context:this}),r.registerApi({apiName:"getMessageReactions",context:this}),r.registerApi({apiName:"getAllUserListOfMessageReaction",context:this}),g.subscribeInnerEvent(u,E,this._handleReactionUpdated,this),g.subscribeInnerEvent(u,m,this._handleReactionSync,this)}addMessageReaction(s,r){return mA(this,void 0,void 0,function*(){const{OuterConstant:g,ssoLog:u,helper:E}=this._core;this._validateMessageReactionBusinessCapability();const{conversationID:m,ID:D,conversationType:M,from:T,to:P,clientSequence:W,random:oA,time:EA,sequence:wA}=s,kA=`conversationID:${m} messageID:${D} reactionID:${r}`;try{return this._recordMessageReactedByMe(D,r),M===g.CONV_C2C?yield function(xA,LA){return mA(this,void 0,void 0,function*(){var SA;const{from:OA,to:qA,clientSequence:Ie,random:le,time:bi,reactionID:ki}=xA,Ot={From_Account:OA,To_Account:qA,MsgKey:`${Ie}_${le}_${bi}`,Reaction:ki,Add_Account:[(SA=LA.store.get("login"))===null||SA===void 0?void 0:SA.userId]};return Fs.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_add",data:Ot})})}({from:T,to:P,clientSequence:W,random:oA,time:EA,reactionID:r},this._core):M===g.CONV_GROUP&&(yield function(xA,LA){return mA(this,void 0,void 0,function*(){var SA;const{to:OA,reactionID:qA,sequence:Ie}=xA,le={GroupId:OA,MsgSeq:Ie,Reaction:qA,Add_Account:[(SA=LA.store.get("login"))===null||SA===void 0?void 0:SA.userId]};return Fs.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_add",data:le})})}({to:P,reactionID:r,sequence:wA},this._core)),{code:0,successLog:{message:kA}}}catch(xA){this._removeMyReactionRecord(D,r);const{errorCode:LA}=xA||{};throw new E.ChatError({functionName:"addMessageReaction",code:LA,moreMessage:kA})}})}removeMessageReaction(s,r){return mA(this,void 0,void 0,function*(){const{OuterConstant:g,helper:u}=this._core;this._validateMessageReactionBusinessCapability();const{conversationID:E,ID:m,conversationType:D,from:M,to:T,clientSequence:P,random:W,time:oA,sequence:EA}=s,wA=`conversationID:${E} messageID:${m} reactionID:${r}`;try{return this._removeMyReactionRecord(m,r),D===g.CONV_C2C?yield function(kA,xA){return mA(this,void 0,void 0,function*(){var LA;const{from:SA,to:OA,clientSequence:qA,random:Ie,time:le,reactionID:bi}=kA,ki={From_Account:SA,To_Account:OA,MsgKey:`${qA}_${Ie}_${le}`,Reaction:bi,Del_Account:[(LA=xA.store.get("login"))===null||LA===void 0?void 0:LA.userId]};return Fs.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_del",data:ki})})}({from:M,to:T,clientSequence:P,random:W,time:oA,reactionID:r},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:qA}=kA,Ie={GroupId:SA,MsgSeq:qA,Reaction:OA,Del_Account:[(LA=xA.store.get("login"))===null||LA===void 0?void 0:LA.userId]};return Fs.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_del",data:Ie},xA)})}({to:T,reactionID:r,sequence:EA},this._core)),{code:0,successLog:{message:wA}}}catch(kA){const{errorCode:xA}=kA||{};throw new u.ChatError({functionName:"removeMessageReaction",code:xA,moreMessage:wA})}})}getAllUserListOfMessageReaction(s){return mA(this,void 0,void 0,function*(){this._validateMessageReactionBusinessCapability();const{message:r,reactionID:g,nextSeq:u=0}=s,E=s.count>100?100:s.count,{conversationID:m}=r,{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:oA,nextSeq:EA,reactionID:wA,count:kA}=W,{from:xA,to:LA,clientSequence:SA,random:OA,time:qA}=oA,Ie={Reaction:wA,NextSeq:EA,Count:kA,From_Account:xA,To_Account:LA,MsgKey:`${SA}_${OA}_${qA}`};return Fs.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_iterate",data:Ie})})}({message:r,reactionID:g,nextSeq:u,count:E}):yield function(W){return mA(this,void 0,void 0,function*(){const{message:oA,nextSeq:EA,reactionID:wA,count:kA}=W,{sequence:xA,to:LA}=oA,SA={Reaction:wA,NextSeq:EA,GroupId:LA,Count:kA,MsgSeq:xA};return Fs.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_iterate",data:SA})})}({message:r,reactionID:g,nextSeq:u,count:E}),P){const{Reaction_Account:W,NextSeq:oA}=P,EA=yield this._getUserProfileList(W);return{code:0,data:{nextSeq:oA,isCompleted:u===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:r}=this._core;this._validateMessageReactionBusinessCapability();const{messageList:g,maxUserCountPerReaction:u=10}=s,E=g[0];let m=null;const D=new Map,{from:M,to:T,conversationType:P}=E,W=this._generateMessageKeyList(g,D);P===r.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,qA={From_Account:xA,To_Account:LA,MsgKeyList:SA,Count:OA};return Fs.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_multi_stat",data:qA})})}({from:M,to:T,messageKeyList:W,maxUserCountPerReaction:u}):P===r.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 Fs.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_multi_stat",data:OA})})}({groupId:T,messageSequenceList:W,maxUserCountPerReaction:u}));const{Results:oA=[]}=m||{},EA=this._extractUserIDsFromReactionResults(oA),wA=yield this._getUserProfileMap(EA);return{code:0,data:{resultList:oA.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:qA,Count:Ie,Reaction_Account:le,ReactedByMe:bi}=OA;return{reactionID:qA,totalUserCount:Ie,partialUserList:this._generatePartialUserInfo({userIDList:le,userProfileMap:wA}),reactedByMyself:bi===1}})}})}}})}dispose(){this._reactionsMap.clear()}_extractUserIDsFromReactionResults(s){const r=[];return s?.forEach(g=>{const{ReactionList:u=[]}=g;u.forEach(E=>{E.Reaction_Account&&r.push(...E.Reaction_Account)})}),r}_getUserProfileList(s){return mA(this,void 0,void 0,function*(){var r;try{const g=yield(r=this._core.user.userProfile)===null||r===void 0?void 0:r.getUserProfile({userIDList:s});return g?g.data:[]}catch{return[]}})}_getUserProfileMap(s){return mA(this,void 0,void 0,function*(){const r=new Map;return(yield this._getUserProfileList(s)).forEach(g=>{const{nick:u,avatar:E,userID:m}=g;r.set(m,{nick:u,avatar:E,userID:m})}),r})}_recordMessageReactedByMe(s,r){const g=`${s}-${r}`;this._reactionsMap.has(g)?this._reactionsMap.get(g).reactedByMe=!0:this._reactionsMap.set(g,{reactedByMe:!0})}_removeMyReactionRecord(s,r){const g=`${s}-${r}`;this._reactionsMap.has(g)&&(this._reactionsMap.get(g).reactedByMe=!1)}_recordMessageReactionInfo(s){const{messageID:r,reactionID:g,reactionInfo:u}=s,E=`${r}-${g}`,m=this._reactionsMap.get(E)||{};this._reactionsMap.set(E,Object.assign(Object.assign({},m),u))}_validateMessageReactionBusinessCapability(){const{helper:s,constants:r}=this._core;if(!s.checkBusinessCapabilityBits(GE))throw new s.ChatError({functionName:"addMessageReaction",code:r.ERROR_CODE.NO_USE,replacement1:"addMessageReaction"})}_handleReactionUpdated(s){const{MsgReactionNotifyList:r}=s,{notificationCenter:g,constants:u}=this._core;r.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),oA=`${T}-${P}-${W}`,EA=this._extractUserIDsFromReactionResults([{ReactionList:M}]),wA=yield this._getUserProfileMap(EA),kA=M.map(xA=>{var LA;const{Reaction:SA,Reaction_Account:OA}=xA,qA=this._generatePartialUserInfo({userIDList:OA,userProfileMap:wA}),Ie=OA?xA.Count:0,le=((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:Ie,partialUserList:qA}}),{reactionID:SA,totalUserCount:Ie,partialUserList:qA,reactedByMyself:le}});g.emitOuterEvent(u.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:u.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:oA,reactionList:kA}})}))}_handleReactionSync(s){var r;const{notificationCenter:g,constants:u}=this._core,{C2CMsgInfo:E={},GroupMsgInfo:m={},Reaction:D,OperateType:M}=s.MsgReactionNotify,{TinyId:T="",MsgClientTime:P=0,MsgRandom:W=0}=Object.assign(Object.assign({},E),m),oA=`${T}-${P}-${W}`,EA=`${oA}-${D}`;if(M===1?this._recordMessageReactedByMe(oA,D):this._removeMyReactionRecord(oA,D),(r=this._reactionsMap.get(EA))===null||r===void 0?void 0:r.reactionID){const wA=this._reactionsMap.get(EA);wA.reactedByMyself=M===1,g.emitOuterEvent(u.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:u.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:oA,reactionList:[wA]}})}}_generatePartialUserInfo({userIDList:s,userProfileMap:r}){const g=[];return s?.forEach(u=>{r.has(u)&&g.push(r.get(u))}),g}_generateMessageID(s){const{messageSequence:r,messageKey:g,messageIDMap:u}=s;return g?u.get(g):u.get(r)}_generateMessageKeyList(s,r){const{constants:g}=this._core,u=s[0],{conversationType:E}=u;let m=[];return E===g.OuterConstant.CONV_C2C?m=s.map(D=>{const{clientSequence:M,random:T,time:P,ID:W}=D,oA=`${M}_${T}_${P}`;return r.set(oA,W),oA}):E===g.OuterConstant.CONV_GROUP&&(m=s.map(D=>{const{ID:M,sequence:T}=D;return r.set(T,M),T})),m}},$a=new class{init(s){this._core=s;const{helper:r,InnerEvent:{MESSAGE_PUSH:g},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:u,GROUP_MESSAGE_READ_RECEIPT:E},notificationCenter:m}=s;r.registerApi({apiName:"sendMessageReadReceipt",context:this}),r.registerApi({apiName:"getMessageReadReceiptList",context:this}),r.registerApi({apiName:"getGroupMessageReadMemberList",context:this}),m.subscribeInnerEvent(g,u,this._handleC2CMessageReadReceipt,this),m.subscribeInnerEvent(g,E,this._handleGroupMessageReadReceipt,this)}sendMessageReadReceipt(s){return mA(this,void 0,void 0,function*(){var r;const{common:g,constants:u}=this._core,E=this._filterValidMessageSendByOther(s);if(E.length===0)throw new g.ChatError({code:u.ERROR_CODE.READ_RECEIPT_MSG_LIST_EMPTY});try{const{conversationType:m}=E[0];return m===u.OuterConstant.CONV_C2C?yield function(D){return mA(this,void 0,void 0,function*(){const{common:M,constants:T}=Fs.core,P=D[0].conversationID.replace(T.OuterConstant.CONV_C2C,""),W=D.map(EA=>{const{from:wA,to:kA,sequence:xA,random:LA,time:SA,clientTime:OA}=EA;return{From_Account:wA,To_Account:kA,MsgSeq:xA,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 mA(this,void 0,void 0,function*(){const{common:M,constants:T}=Fs.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:${(r=E?.[0])===null||r===void 0?void 0:r.conversationID}`})}})}getMessageReadReceiptList(s){return mA(this,void 0,void 0,function*(){const{common:r,constants:g}=this._core;try{const{conversationType:u}=s[0];if(u===g.OuterConstant.CONV_GROUP){const E=this._filterValidMessageSendByMe(s);if(E?.length>0){const m=yield function(M){return mA(this,void 0,void 0,function*(){const{common:T,constants:P}=Fs.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(u){const{errorCode:E,errorInfo:m}=u;throw new r.ChatError({code:E,message:m})}})}getGroupMessageReadMemberList(s){return mA(this,void 0,void 0,function*(){const{constants:r,common:g}=this._core,{message:u,filter:E=bE.READ,cursor:m=""}=s,{conversationID:D,sequence:M,ID:T}=u,P=D.replace(r.OuterConstant.CONV_GROUP,""),W=s.count>=100?100:s.count;try{const oA=yield function(EA){return mA(this,void 0,void 0,function*(){const{sequence:wA,groupID:kA,filter:xA,cursor:LA,count:SA}=EA,OA={MsgSeq:wA,GroupId:kA,Filter:xA,Cursor:LA,Num:SA};return Fs.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:xA}=oA,LA={cursor:EA,isCompleted:wA===1,messageID:T,unreadUserIDList:[],readUserIDList:[]};return E===bE.READ?LA.readUserIDList=xA.map(SA=>SA.Read_Account):E===bE.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 r=[],{constants:g,helper:u}=this._core,{C2cMsgInfo:E,PeerReadTime:m,Peer_Account:D}=s;if(u.isEmpty(E))return;const M=`${g.OuterConstant.CONV_C2C}${D}`;E?.forEach(T=>{const{TinyId:P,MsgClientTime:W,MsgRandom:oA}=T,EA=`${P}-${W}-${oA}`,wA=_c({conversationID:M,messageID:EA});wA&&!wA.readReceiptInfo.isPeerRead&&(wA.readReceiptInfo.isPeerRead=!0,wA.readReceiptInfo.timestamp=m,r.push({userID:D,messageID:EA,isPeerRead:!0,timestamp:m}))}),this._emitReadReceiptEventIfNeed(r)}_updateGroupMessagesReadReceiptInfo(s){const{messageList:r,readReceiptList:g}=s,u=new Map;r.forEach(E=>{u.set(E.sequence,E)}),g?.forEach(E=>{if(E.Code===0){const{MsgSeq:m,ReadNum:D,UnreadNum:M}=E,T=u.get(m);T&&(T.readReceiptInfo.readCount=D,T.readReceiptInfo.unreadCount=M)}})}_handleGroupMessageReadReceipt(s){const r=[],{constants:g}=this._core,{GroupTips:u}=s;u.forEach(E=>{const{MsgBody:{GroupMsgReceiptList:m},GroupInfo:{GroupId:D}}=E,M=`${g.OuterConstant.CONV_GROUP}${D}`;m?.forEach(T=>{const{TinyId:P,MsgClientTime:W,MsgRandom:oA,ReadNum:EA,UnreadNum:wA}=T,kA=`${P}-${W}-${oA}`,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 wA=="number"&&(xA.readReceiptInfo.unreadCount=wA,LA.unreadCount=wA),r.push(LA))})}),this._emitReadReceiptEventIfNeed(r)}_emitReadReceiptEventIfNeed(s){const{notificationCenter:r,OuterEvent:g}=this._core;s.length>0&&r.emitOuterEvent(g.MESSAGE_READ_RECEIPT_RECEIVED,{name:g.MESSAGE_READ_RECEIPT_RECEIVED,data:s})}_filterValidMessageSendByOther(s){return this._filterNeedReadReceiptMessages(s).filter(r=>{const{from:g}=r;return g!==this._core.common.getCurrentUserID()})}_filterValidMessageSendByMe(s){const{OuterConstant:r}=this._core.constants;return this._filterNeedReadReceiptMessages(s).filter(g=>{const{from:u,status:E}=g;return u===this._core.common.getCurrentUserID()&&E===r.MessageStatus.SUCCESS})}_filterNeedReadReceiptMessages(s){return s.filter(r=>r.needReadReceipt===!0)}dispose(){const{InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:r,GROUP_MESSAGE_READ_RECEIPT:g},notificationCenter:u}=this._core;u.unSubscribeInnerEvent(s,r,this._handleC2CMessageReadReceipt,this),u.unSubscribeInnerEvent(s,g,this._handleGroupMessageReadReceipt,this)}};function tu(s,r,g){return mA(this,void 0,void 0,function*(){const{common:{buildAndSendPacket:u}}=Fs.core,{from:E,to:m,clientSequence:D,random:M,time:T}=s;return u({servcmd:"openim_msg_ext_http_svc.set_key_values",data:{From_Account:E,To_Account:m,MsgKey:`${D}_${M}_${T}`,OperateType:g,ExtensionList:r}})})}function xu(s,r,g){return mA(this,void 0,void 0,function*(){const{common:{buildAndSendPacket:u}}=Fs.core,{to:E,sequence:m}=s;return u({servcmd:"openim_msg_ext_http_svc.group_set_key_values",data:{GroupId:E,MsgSeq:m,OperateType:g,ExtensionList:r}})})}var Gc=new class{constructor(){this._messageExtensionsMap=new Map,this._extensionsLatestSequenceMap=new Map,this._completedFetchExtensions=new Set}init(s){this._core=s;const{notificationCenter:r,helper:{registerApi:g},InnerEvent:{MESSAGE_PUSH:u,LOGOUT:E},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:m}}=s;g({apiName:"setMessageExtensions",context:this}),g({apiName:"getMessageExtensions",context:this}),g({apiName:"deleteMessageExtensions",context:this}),r.subscribeInnerEvent(u,m,this._handleMessageExtensionsNotify,this),r.subscribeInnerEvent(E,this.reset,this)}setMessageExtensions(s,r){return mA(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("setMessageExtensions");const{constants:{OuterConstant:g},ssoLog:u}=this._core,{ID:E,conversationID:m,sequence:D,time:M,conversationType:T}=s;let P=r;r.length>20&&(P=r.slice(0,20),u.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 tu(s,W,Ll):T===g.CONV_GROUP&&(EA=yield xu(s,W,Ll)),EA){const{resultList:wA,successCount:kA,failureCount:xA}=this._handleModifyMessageExtensions(s,EA);return{code:0,data:{extensions:wA},successLog:{message:`${oA} successCount:${kA} failCount:${xA}`}}}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 mA(this,void 0,void 0,function*(){const{utils:{isUndefined:r}}=this._core;this._validateMessageExtensionBusinessCapability("getMessageExtensions");const{conversationID:g,ID:u,sequence:E,time:m}=s,D=`convID:${g} messageID:${u} sequence:${E} time:${m}`;try{let M;this._completedFetchExtensions.has(u)&&(M=this._extensionsLatestSequenceMap.get(u));const T=yield this._fetchMessageExtensions(s,M);return r(M)&&T.length>1&&this._completedFetchExtensions.add(u),{code:0,data:{extensions:T},successLog:{message:D}}}catch(M){const{errorCode:T,errorInfo:P=""}=M||{};throw new this._core.common.ChatError({code:T,message:P,moreMessage:D})}})}deleteMessageExtensions(s,r){return mA(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("deleteMessageExtensions");const{utils:{isEmpty:g},constants:{OuterConstant:u}}=this._core,{conversationType:E,conversationID:m,sequence:D,ID:M,time:T}=s;let P=Ug;const W=[];g(r)||(P=Ul,r?.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===u.CONV_C2C?wA=yield tu(s,EA,P):E===u.CONV_GROUP&&(wA=yield xu(s,EA,P)),wA){const{resultList:kA,successCount:xA,failureCount:LA}=this._handleModifyMessageExtensions(s,wA);return{code:0,data:{extensions:kA},successLog:{message:`${oA}successCount:${xA} 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:r,LOGOUT:g},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:u}}=this._core;s.unSubscribeInnerEvent(r,u,this._handleMessageExtensionsNotify,this),s.subscribeInnerEvent(g,this.reset,this)}_handleModifyMessageExtensions(s,r){const{ID:g}=s,{Seq:u}=r,E=r.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,u),T.length>0&&this._updateLocalExtensions(s.ID,T),{resultList:m,successCount:D,failureCount:M}}_updateLocalExtensions(s,r){this._messageExtensionsMap.has(s)||this._messageExtensionsMap.set(s,new Map);const g=this._messageExtensionsMap.get(s);r?.forEach(u=>{const{key:E,seq:m,value:D=""}=u;g?.set(E,{value:D,seq:m})})}_fetchMessageExtensions(s,r){return mA(this,void 0,void 0,function*(){const{constants:{OuterConstant:g},utils:{isEmpty:u}}=this._core;try{let E;const{conversationType:m,ID:D}=s;if(m===g.CONV_C2C?E=yield function(M,T){const{common:{buildAndSendPacket:P}}=Fs.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,r):m===g.CONV_GROUP&&(E=yield function(M,T){const{common:{buildAndSendPacket:P}}=Fs.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,r)),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:xA}=wA;u(xA)||oA.push({key:kA,value:xA})})}return oA}}catch(E){throw E}})}_clearLocationExtensions(s,r){if(!(r<=0)&&this._messageExtensionsMap.has(s)){const g=this._messageExtensionsMap.get(s);g?.forEach((u,E)=>{u.seq<=r&&g.delete(E)})}}_generateServerExtensions(s,r){const{ID:g}=s;if(this._messageExtensionsMap.has(g)){const u=this._messageExtensionsMap.get(g);return r.map(E=>{var m;const{key:D,value:M}=E;let T=0;return u?.has(D)&&(T=(m=u.get(D))===null||m===void 0?void 0:m.seq),{Key:D,Value:M,Seq:T}})}return r.map(u=>({Key:u.key,Value:u.value,Seq:0}))}_validateMessageExtensionBusinessCapability(s){const{helper:r,constants:g}=this._core;if(!r.checkBusinessCapabilityBits(pC))throw new r.ChatError({functionName:s,code:g.ERROR_CODE.NO_USE,replacement1:s})}_handleMessageExtensionsNotify(s){const{SetKVInfo:r,DeleteKVInfo:g,ClearKVInfo:u,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===Ll?this._handleMessageExtensionsUpdated({messageID:EA,updateMessageExtensionsInfo:r}):E===Ul?this._handleMessageExtensionsDeleted({messageID:EA,deleteMessageExtensionsInfo:g}):E===Ug&&this._handleMessageExtensionsCleared({messageID:EA,clearMessageExtensionsInfo:u})}_handleMessageExtensionsUpdated(s){const{notificationCenter:r,OuterEvent:g}=this._core,{messageID:u,updateMessageExtensionsInfo:E=[]}=s,m=[];E.forEach(D=>{const{MsgKeyValue:M=[]}=D,T=M.map(P=>(m.push({key:P.Key,value:P.Value}),{key:P.Key,value:P.Value,seq:P.Seq}));this._updateLocalExtensions(u,T)}),r.emitOuterEvent(g.MESSAGE_EXTENSIONS_UPDATED,{name:g.MESSAGE_EXTENSIONS_UPDATED,data:{messageID:u,extensions:m}})}_handleMessageExtensionsDeleted(s){const{notificationCenter:r,OuterEvent:g}=this._core,{messageID:u,deleteMessageExtensionsInfo:E=[]}=s,m=[];E.forEach(D=>{const{MsgKeyValue:M=[]}=D,T=M.map(P=>(m.push(P.Key),{key:P.Key,seq:P.Seq}));this._updateLocalExtensions(u,T)}),r.emitOuterEvent(g.MESSAGE_EXTENSIONS_DELETED,{name:g.MESSAGE_EXTENSIONS_DELETED,data:{messageID:u,keyList:m}})}_handleMessageExtensionsCleared(s){const{notificationCenter:r,OuterEvent:{MESSAGE_EXTENSIONS_DELETED:g},utils:{isEmpty:u}}=this._core,{messageID:E,clearMessageExtensionsInfo:m=[]}=s,D=[];m.forEach(M=>{const{ClearMsgSeq:T}=M;this._messageExtensionsMap.has(E)&&(this._messageExtensionsMap.get(E)||[]).forEach((P,W)=>{P.seq<=T&&!u(P.value)&&D.push(W)}),this._clearLocationExtensions(E,T)}),r.emitOuterEvent(g,{name:g,data:{messageID:E,keyList:D}})}};const mI={key:"message",required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>{const{constants:{OuterConstant:r}}=Fs.core;return s.status!==r.MessageStatus.SUCCESS?"message is not success":s.isSupportExtension===!0||"message is not support extension"}},sl={setMessageExtensions:[mI,{key:"extensions",required:!0,rules:["array"],allowEmpty:!1}],getMessageExtensions:[mI],deleteMessageExtensions:[mI]},nl=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({deleteMessage:[{required:!0,rules:["array"],allowEmpty:!1}],revokeMessage:[{required:!0,rules:["object"],allowEmpty:!1}],resendMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"options",required:!1,rules:["object"],allowEmpty:!1}],getMessageList:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},nextReqMessageID:{required:!1,rules:["string"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}},getMessageListHopping:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},sequence:{required:!1,rules:["number"],allowEmpty:!0},direction:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}},createTextAtMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>{const r=function(g){var u;return typeof g?.text!="string"||typeof g.text=="string"&&((u=g?.text)===null||u===void 0?void 0:u.length)===0?"payload.text is invalid.":!0}(s);return r!==!0?r:!(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:r,isNumber:g}}=Fs.core;return r(s?.description)?g(s?.longitude)?!!g(s?.latitude)||"payload.latitude must be a number.":"payload.longitude must be a number.":"payload.description must be a string."}}}},{addMessageReaction:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"reactionID",required:!0,rules:["string"],allowEmpty:!1}],removeMessageReaction:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"reactionID",required:!0,rules:["string"],allowEmpty:!1}],getMessageReactions:{messageList:{required:!0,rules:["array"],allowEmpty:!1},maxUserCountPerReaction:{required:!1,rules:["number"],allowEmpty:!0,customValidator:s=>typeof s!="number"?"maxUserCountPerReaction is invalid.":!(s<0||s>10)||"maxUserCountPerReaction should between [0, 10]."}},getAllUserListOfMessageReaction:{message:{required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>s.status==="success"||"message is invalid."},reactionID:{required:!0,rules:["string"],allowEmpty:!1},nextSeq:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}}}),{sendMessageReadReceipt:[{required:!0,rules:["array"],allowEmpty:!1}],getMessageReadReceiptList:[{required:!0,rules:["array"],allowEmpty:!1}],getGroupMessageReadMemberList:{message:{required:!0,rules:["object"],allowEmpty:!1},filter:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0},cursor:{required:!1,rules:["string"],allowEmpty:!0}}}),sl),{pinGroupMessage:{groupID:{required:!0,rules:["string"],allowEmpty:!1},message:{required:!0,rules:["object"],allowEmpty:!1},isPinned:{required:!0,rules:["boolean"],allowEmpty:!1}},getPinnedGroupMessageList:[{key:"groupID",required:!0,rules:["string"],allowEmpty:!1}]}),{createQuoteMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"quotedMessage",required:!0,rules:["object"],allowEmpty:!1}]}),xa=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({deleteMessage:!0,revokeMessage:!0,resendMessage:!0,getMessageList:!0,getMessageListHopping:!0,createTextAtMessage:!0,findMessage:!0,translateText:!0,createForwardMessage:!0,createLocationMessage:!0},{addMessageReaction:!0,removeMessageReaction:!0,getMessageReactions:!0,getAllUserListOfMessageReaction:!0}),{sendMessageReadReceipt:!0,getMessageReadReceiptList:!0,getGroupMessageReadMemberList:!0}),{setMessageExtensions:!0,getMessageExtensions:!0,deleteMessageExtensions:!0}),{pinGroupMessage:!0,getPinnedGroupMessageList:!0}),{createQuoteMessage:!0});class UE{constructor(r){this._core=r}deleteMessage(r){return mA(this,void 0,void 0,function*(){const{to:g,messageIdentifiers:u}=r,E={From_Account:this._core.common.getCurrentUserID(),To_Account:g,MsgKeyList:u};return this._core.common.buildAndSendPacket({servcmd:"openim.delete_c2c_msg_ramble",data:E})})}revokeMessage(r){return mA(this,void 0,void 0,function*(){const{to:g,from:u,sequence:E,time:m,random:D}=r,M={MsgInfo:{From_Account:u,To_Account:g,MsgSeq:E,MsgRandom:D,MsgTimeStamp:m}};return this._core.common.buildAndSendPacket({servcmd:"openim.msgwithdraw",data:M})})}}class aa{constructor(r){this._core=r}deleteMessage(r){return mA(this,void 0,void 0,function*(){const{to:g,messageIdentifiers:u}=r,E={GroupId:g,Deleter_Account:this._core.common.getCurrentUserID(),Seqs:u};return this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_ramble_msg_by_seq",data:E})})}revokeMessage(r){return mA(this,void 0,void 0,function*(){const{to:g,sequence:u}=r,E={GroupId:g,MsgSeqList:[{MsgSeq:u}]};return this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_recall",data:E})})}}const Mn=2116;class kr{constructor(r){this._core=r}generateRevokeMessage(r){const{conversationID:g,sequence:u,random:E,tinyID:m,clientTime:D,revokeReason:M,revoker:T}=r;let P={};const{messageDataHandler:W}=this._core.message;return P=W.revokeMessage({conversationID:g,sequence:u,random:E,revoker:T}),P||(P={conversationID:g,sequence:u},m&&D&&E&&(P.ID=`${m}-${D}-${E}`)),P.revoker=T,P.revokeReason=M,P.revokerInfo={userID:T,nick:"",avatar:""},P}updateRevokerInfo(r){return mA(this,void 0,void 0,function*(){const g=r.map(u=>u.revoker);try{const u=yield this._fetchUserInfos(g);u&&r.forEach(E=>{const{revoker:m}=E;u[m]&&(E.revokerInfo.nick=u[m].nick||"",E.revokerInfo.avatar=u[m].avatar||"",E.revokerInfo.userID=m)})}catch(u){console.debug(u)}})}_fetchUserInfos(r){return mA(this,void 0,void 0,function*(){var g,u;const E=yield(g=this._core.user.userProfile)===null||g===void 0?void 0:g.getUserProfile({userIDList:r});return E?.data?(u=E.data)===null||u===void 0?void 0:u.reduce((m,{userID:D,nick:M,avatar:T})=>(m[D]={nick:M||"",avatar:T||""},m),{}):null})}}var rl=new class{constructor(){this._core=null,this._c2cMessageAction=null,this._groupMessageAction=null}init(s){this._core=s,this._groupMessageAction=new aa(s),this._c2cMessageAction=new UE(s),this._messageHelper=new kr(s);const{helper:r}=s;r.registerApi({apiName:"deleteMessage",context:this}),r.registerApi({apiName:"revokeMessage",context:this}),r.registerApi({apiName:"resendMessage",context:this}),r.registerApi({apiName:"findMessage",context:this}),r.registerApi({apiName:"createQuoteMessage",context:this})}deleteMessage(s){return mA(this,void 0,void 0,function*(){let r=[],g=[];const{conversationID:u,conversationType:E}=s[0],m=u.replace(E,"");if(E==="@TIM#SYSTEM")throw new this._core.helper.ChatError({code:Mn});if(s.forEach(D=>{const{conversationID:M,conversationType:T,status:P,_onlineOnlyFlag:W,sequence:oA,random:EA,time:wA}=D||{};if(P==="success"&&M===u&&T===E){if(!W){const kA=T==="C2C"?`${oA}_${EA}_${wA}`:String(oA);r.push(kA)}g.push(D)}}),r.length===0)return this._handleDeleteMessageSuccess(g),{code:0,data:{messageList:g}};r.length>30&&(r=r.slice(0,30),g=g.slice(0,30));try{return E==="C2C"?yield this._c2cMessageAction.deleteMessage({to:m,messageIdentifiers:r}):yield this._groupMessageAction.deleteMessage({to:m,messageIdentifiers:r}),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(r)}`})}})}revokeMessage(s){return mA(this,void 0,void 0,function*(){var r;const{conversationType:g,isRevoked:u,ID:E,type:m,from:D,to:M}=s;let T=null;const P=`type:${m} from:${D} to:${M} ID:${E}`;if(g==="@TIM#SYSTEM")throw new this._core.helper.ChatError({message:"system message cannot be revoked"});if(u)throw new this._core.helper.ChatError({message:"message has been revoked",moreMessage:P});try{if(T=g==="C2C"?yield this._c2cMessageAction.revokeMessage(s):yield this._groupMessageAction.revokeMessage(s),T){const{RecallRetList:W}=T,oA=((r=W?.[0])===null||r===void 0?void 0:r.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,r){return mA(this,void 0,void 0,function*(){var g,u;return s.isResend=!0,s.status="unSend",(u=(g=this._core)===null||g===void 0?void 0:g.apiMap)===null||u===void 0?void 0:u.sendMessage(s,r)})}findMessage(s){return this._core.message.messageDataHandler.findMessage(s)}createQuoteMessage(s,r){const{ID:g,time:u,sequence:E}=r;return s.quoteInfo={msgID:g,messageTime:u,messageSequence:E},s}_handleDeleteMessageSuccess(s){if(s.length===0)return;const{message:{messageDataHandler:r},common:{isTopic:g},notificationCenter:u,InnerEvent:E}=this._core;s.forEach(D=>{D.isDeleted=!0;const M=r.getLocalMessageList(D.conversationID);M?.forEach(T=>{T.ID===D.ID&&(T.isDeleted=!0)})});const{conversationID:m=""}=s[0];g(m)?u.emitInnerEvent(E.TOPIC_MESSAGE_DELETED,m):u.emitInnerEvent(E.MESSAGE_DELETED,m)}_handleRevokeMessageSuccess(s){return mA(this,void 0,void 0,function*(){var r;const g=(r=this._core.store.get("login"))===null||r===void 0?void 0:r.userId,{conversationID:u,sequence:E,random:m}=s;this._core.message.messageDataHandler.revokeMessage({conversationID:u,sequence:E,random:m,revoker:g}),yield this._messageHelper.updateRevokerInfo([s])})}};class Fl{static parseServerPushElement(r){const{MsgContent:g={}}=r,{Index:u,Data:E}=g;return new Fl({index:u,data:E})}constructor(r){this.type=Vr.MSG_FACE;const{index:g,data:u}=r;this.content={index:g,data:u}}validateBeforeSend(){var r,g;return typeof((r=this.content)===null||r===void 0?void 0:r.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(r){const{isMergerMessage:g=!1}=r||{},u=g?this.payload:this.content,{index:E,data:m}=u;return{MsgType:this.type,MsgContent:{Index:E,Data:m}}}}class bc{static parseServerPushElement(r){const{MsgContent:g={}}=r,{Desc:u,Longitude:E,Latitude:m}=g;return new bc({description:u,longitude:E,latitude:m})}constructor(r){this.type=Vr.MSG_LOCATION;const{description:g,longitude:u,latitude:E}=r;this.content={description:g,longitude:u,latitude:E}}validateBeforeSend(){return{isValid:!0}}transformToServerFormat(r){const{isMergerMessage:g=!1}=r||{},u=g?this.payload:this.content,{description:E,longitude:m,latitude:D}=u;return{MsgType:this.type,MsgContent:{Desc:E,Longitude:m,Latitude:D}}}}class FE{static parseServerPushElement(r){const{MsgContent:g={}}=r,{StreamMsgID:u,CompatibleText:E,Markdown:m,BinaryData:D,ErrorCode:M,ErrorMsg:T}=g;return new FE({streamMessageID:u,compatibleText:E,markdown:m,binaryData:D,errorCode:M,errorMessage:T})}constructor(r){this.type=Vr.MSG_STREAM,this.content={streamMessageID:"",compatibleText:"",errorCode:0,errorMessage:"",isStreamEnded:!1},this._chunks=[],this._latestIndex=0;const{streamMessageID:g,compatibleText:u,markdown:E,binaryData:m,errorCode:D=0,errorMessage:M="",isStreamEnded:T=!1,chunks:P=[],latestIndex:W=0}=r;this.content.streamMessageID=g,this.content.compatibleText=u,this.content.markdown=E,this.content.binaryData=m,this.content.errorCode=D,this.content.errorMessage=M,this.content.isStreamEnded=T,this.content.chunks=P,this.content.latestIndex=W}updateChunks(r){if(!r||r.length===0)return;const g=r.sort((m,D)=>m.index-D.index),u=this._getMaxRevokedChunkIndex(g);u>=0&&(this._chunks=[],this._latestIndex=u,this._updateContent());const E=this._getValidChunks(g);if(E.length!==0&&(this._mergeAndSortChunks(E),this._chunks.length>0)){const m=this._chunks[this._chunks.length-1];this._latestIndex=m.index,this._updateContent(),this.content.isStreamEnded=m.isLast}}getLatestIndex(){return this._latestIndex}transformToServerFormat(r){const{isMergerMessage:g=!1}=r||{},u=g?this.payload:this.content,{streamMessageID:E,chunks:m}=u,D=m?.map(M=>({EventType:M.eventType||"data",Index:M.index,Markdown:M.markdown,IsLast:M.isLast}));return{MsgType:this.type,MsgContent:{StreamMsgID:E,Chunks:D}}}validateBeforeSend(){var r,g;return((g=(r=this.content)===null||r===void 0?void 0:r.chunks)===null||g===void 0?void 0:g.length)>0?{isValid:!0}:{isValid:!1,error:{message:"content is invalid"}}}_filterContinuousChunks(r,g){if(r.length===0)return[];const u=[];let E=g;for(const m of r){if(m.index>E)break;m.index===E&&(u.push(m),E++)}return u}_mergeAndSortChunks(r){const g=new Map;this._chunks.forEach(u=>{g.set(u.index,u)}),r.forEach(u=>{g.set(u.index,u)}),this._chunks=Array.from(g.values()).sort((u,E)=>u.index-E.index)}_updateContent(){this.content.markdown=this._chunks.map(g=>g.markdown).join("");const r=this._chunks.map(g=>g.binaryData).filter(g=>g?.length>0);if(r.length===0)this.content.binaryData=new Uint8Array(0);else if(r.length===1)this.content.binaryData=r[0];else{const g=r.reduce((m,D)=>m+D.length,0),u=new Uint8Array(g);let E=0;for(const m of r)u.set(m,E),E+=m.length;this.content.binaryData=u}}_getMaxRevokedChunkIndex(r){let g=-1;for(let u=0;ug&&(g=E.index)}return g}_getValidChunks(r){const g=r.filter(u=>u.eventType===Nc.DATA&&u.index>this._latestIndex);return this._filterContinuousChunks(g,this._latestIndex+1)}}var kc=new class{init(s){this._core=s,s.message.messageFactory.registerElementClass(Vr.MSG_FACE,Fl),s.message.messageFactory.registerElementClass(Vr.MSG_LOCATION,bc),s.message.messageFactory.registerElementClass(Vr.MSG_STREAM,FE),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:r,data:g}=s?.payload||{},u=new Fl({index:r,data:g}),E=this._core.common.getCurrentUserID(),m=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:E}));return m.setElement(u),m}createTextAtMessage(s){const{atUserList:r}=s?.payload||{},g=this._core.apiMap.createTextMessage(s),{OuterConstant:u}=this._core;if(!g)return null;if(Array.isArray(r)){const E=[],m=[];r.forEach(D=>{D!==u.MSG_AT_ALL?(E.push({GroupAtAllFlag:uh,GroupAt_Account:D}),m.push(D)):(E.push({GroupAtAllFlag:go}),m.push(u.MSG_AT_ALL))}),g._groupAtInfoList=E,g.atUserList=m}return g}createForwardMessage(s){const{helper:r,OuterConstant:g}=this._core,{to:u,conversationType:E,priority:m,payload:D,needReadReceipt:M,receiverList:T,cloudCustomData:P="",isSupportExtension:W=!1}=s;if(!Array.isArray(D._elements))throw new r.ChatError({functionName:"createForwardMessage",code:2454});if(D.type===g.MSG_GRP_TIP)throw new r.ChatError({functionName:"createForwardMessage",code:2453});const oA=this._core.common.getCurrentUserID(),EA=this._core.message.messageFactory.createMessage({to:u,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:r,longitude:g,latitude:u}=s?.payload||{},E=new bc({description:r,longitude:g,latitude:u}),m=this._core.common.getCurrentUserID(),D=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:m}));return D.setElement(E),D}};let Yu=class{init(s){this._messageHelper=new kr(s),this._core=s;const{notificationCenter:r,InnerEvent:{MESSAGE_PUSH:g},InnerEventSubType:{C2C_REVOKED_MESSAGE:u},helper:{registerWorkflowStep:E},constants:{WORKFLOW_NAME:m,WORKFLOW_STEP:D}}=s;r.subscribeInnerEvent(g,u,this._handleC2CNotifyMessage,this),E(m.SYNC_SERVER_INFO_AFTER_RE_ONLINE,D.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,this._handleC2CRevokeMessagesFromUnreadMessageSync,this)}_handleC2CNotifyMessage(s){const{C2cNotifyMsgArray:r}=s;r?.forEach(g=>{Object.keys(g).includes("WithdrawC2cMsgNotify")&&this._handleC2CRevokeMessage(g)})}_handleC2CRevokeMessage(s){return mA(this,void 0,void 0,function*(){try{const{WithdrawC2cMsgNotify:{C2cWithdrawInfoArray:r}}=s;yield this._parseAndEmitC2CRevokedMessages(r)}catch(r){console.debug(r)}})}_parseAndEmitC2CRevokedMessages(s){return mA(this,void 0,void 0,function*(){const r=[],{notificationCenter:g,OuterEvent:u,common:{getCurrentUserID:E}}=this._core;s.forEach(m=>{var D;const{MsgRand:M,MsgSeq:T,To_Account:P,From_Account:W,RevokerInfo:{Revoker_Account: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,xA=this._messageHelper.generateRevokeMessage({conversationID:wA,sequence:T,random:M,revoker:oA,revokeReason:kA});r.push(xA)}),r.length>0&&(yield this._messageHelper.updateRevokerInfo(r),g.emitOuterEvent(u.MESSAGE_REVOKED,{name:u.MESSAGE_REVOKED,data:r}))})}_handleC2CRevokeMessagesFromUnreadMessageSync(s){return mA(this,void 0,void 0,function*(){const{revokedMessageList:r}=s.result;yield this._parseAndEmitC2CRevokedMessages(r)})}dispose(){const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:r},InnerEventSubType:{C2C_REVOKED_MESSAGE:g}}=this._core;s.unSubscribeInnerEvent(r,g,this._handleC2CNotifyMessage,this)}},yC=class{init(s){this._messageHelper=new kr(s),this._core=s;const{notificationCenter:r,InnerEvent:{MESSAGE_PUSH:g},InnerEventSubType:{GROUP_MESSAGE_REVOKED:u}}=s;r.subscribeInnerEvent(g,u,this._handleGroupNotifyMessage,this)}_handleGroupNotifyMessage(s){const{GroupTips:r}=s;r?.forEach(g=>{var u;Array.isArray((u=g?.MsgBody)===null||u===void 0?void 0:u.GroupWithdrawInfoArray)&&this._handleGroupRevokeMessage(g)})}_handleGroupRevokeMessage(s){return mA(this,void 0,void 0,function*(){try{const{RevokerInfo:r,MsgBody:{GroupWithdrawInfoArray:g},GroupInfo:u}=s,E=[],m=[],{notificationCenter:D,OuterEvent:M,utils:{isEmpty:T},common:{isCommunity:P}}=this._core;let W=!1;u&&(W=P({groupID:u.GroupId})||!T(u.TopicId)),g.forEach(oA=>{const{Random:EA,MsgSeq:wA,GroupId:kA,MsgClientTime:xA,TinyId:LA,TopicId:SA,RevokerInfo:{Revoker_Account:OA=r?.Revoker_Account||"",Reason:qA=r?.Reason||""}}=oA,Ie=SA?`GROUP${SA}`:`GROUP${kA}`,le=this._messageHelper.generateRevokeMessage({conversationID:Ie,sequence:wA,random:EA,tinyID:LA,clientTime:xA,revoker:OA,revokeReason:qA});W?(le.revokerInfo.nick=u.From_AccountNick,le.revokerInfo.avatar=u.From_AccountHeadurl,E.push(le)):m.push(le)}),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(r){console.debug(r)}})}dispose(){const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:r},InnerEventSubType:{GROUP_MESSAGE_REVOKED:g}}=this._core;s.unSubscribeInnerEvent(r,g,this._handleGroupNotifyMessage,this)}};var iu=new class{constructor(){this._c2cMessageReceiver=new Yu,this._groupMessageReceiver=new yC}init(s){this._c2cMessageReceiver.init(s),this._groupMessageReceiver.init(s)}dispose(){this._c2cMessageReceiver.dispose(),this._groupMessageReceiver.dispose()}},Eh=new class{constructor(){this._core=null}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"translateText",context:this})}translateText(s){return mA(this,void 0,void 0,function*(){try{const{sourceLanguage:r,sourceTextList:g,targetLanguage:u}=s,E=yield function(m,D){return mA(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},xA=yield wA.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:r,sourceTextList:g,targetLanguage:u},this._core);if(E){const{cmdErrorCode:{ErrorCode:m,ErrorInfo:D},translatedTextList:M}=E;if(m===0)return{code:0,data:{translatedTextList:M}};throw{errorCode:m,errorInfo:D,message:D}}}catch(r){const{errorCode:g,errorInfo:u}=r||{};throw new this._core.helper.ChatError({functionName:"translateText",code:g,message:u})}})}},Vu=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 r;const{message:g,language:u=Tc.ZH_PY}=s;let{url:E}=g.payload||{};const m=this._core.common.getCurrentUserID();g.from===m&&g.flow==="out"&&(E=g.payload.remoteAudioUrl),this._validateVoiceFormat(E);const D=((r=pI.exec(E))===null||r===void 0?void 0:r[1])||"mp3",M=QI[u]||Au;try{const T=yield function(P){var W;const{store:oA,common:EA}=Fs.core,{url:wA,format:kA,serverLanguageType:xA}=P,LA={BytesUrl:wA,BytesEngServiceType:xA,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(!pI.test(s))throw new this._core.common.ChatError({code:2119})}};class fI{constructor(r){const{constants:g,common:u,utils:E}=Fs.core,{CONV_C2C:m,CONV_GROUP:D}=g.OuterConstant,{ID:M,tinyID:T,from:P,to:W,clientTime:oA=u.timeManager.getServerTimeSeconds()||0,random:EA,sequence:wA,cloudCustomData:kA="",nick:xA="",avatar:LA="",clientSequence:SA,conversationType:OA,groupID:qA,_elements:Ie,time:le}=r;this.ID=M||`${T}-${oA}-${EA}`,this.messageRandom=EA,this.from=P,this.messageSender=P,this.time=le,this.messageSequence=wA,this.clientSequence=SA||wA,this.clientTime=oA,this.cloudCustomData=kA,this.messageReceiver=W,this.avatar=LA,this.nick=xA;const bi=E.deepCopyWithMethods(Ie);bi.forEach(ki=>{ki.payload=ki.content,delete ki.content}),this.messageBody=bi,M?OA.startsWith(m)?this.receiverUserID=W:OA.startsWith(D)&&(this.receiverGroupID=W):qA?(this.receiverGroupID=qA,this.messageReceiver=qA):W&&(this.receiverUserID=W,this.messageReceiver=W)}transformElementsToServerFormat(){return this.messageBody?Array.isArray(this.messageBody)?this.messageBody.map(r=>r.transformToServerFormat({isMergerMessage:!0})):this.messageBody.transformToServerFormat({isMergerMessage:!0}):null}}class al{static parseServerPushElement(r){const{MsgContent:g}=r,{MsgList:u=[],CompatibleText:E,AbstractList:m,Title:D,PbMsgKey:M,JsonMsgKey:T}=g||{},P=u.map(W=>Qr(W));return new al({messageList:P,title:D,abstractList:m,compatibleText:E,pbDownloadKey:M,downloadKey:T})}constructor(r){this.type=Fs.core.constants.OuterConstant.MSG_MERGER;const{messageList:g,title:u,abstractList:E,compatibleText:m,pbDownloadKey:D="",downloadKey:M="",version:T=0,layersOverLimit:P=!1}=r,W=[];g.forEach(oA=>{if(oA){const EA=new fI(oA);W.push(EA)}}),this.content={messageList:W,title:u,abstractList:E,compatibleText:m,version:T,downloadKey:M,pbDownloadKey:D,layersOverLimit:P}}validateBeforeSend(){const{isEmpty:r}=Fs.core.helper;return r(this.content.messageList)?{isValid:!1,error:{message:"content is invalid"}}:{isValid:!0}}transformToServerFormat(r){const{isMergerMessage:g=!1}=r||{},u=g?this.payload:this.content,{abstractList:E,compatibleText:m,downloadKey:D,layersOverLimit:M,pbDownloadKey:T,title:P,version:W,messageList:oA}=u;return{MsgType:this.type,MsgContent:{AbstractList:E,CompatibleText:m,JsonMsgKey:D,LayersOverLimit:M,PbMsgKey:T,Title:P,Version:W,MsgList:Ac(oA)}}}}var DC=new class{init(s){this._core=s;const{message:r,helper:g,constants:{OuterConstant:u}}=s;r.messageFactory.registerElementClass(u.MSG_MERGER,al),g.registerApi({apiName:"createMergerMessage",context:this}),g.registerApi({apiName:"sendMessage",context:this,matcher:E=>E[0].type===u.MSG_MERGER}),g.registerApi({apiName:"downloadMergerMessage",context:this})}createMergerMessage(s){const{common:r}=this._core;if(!s)return null;const g=new al(s.payload),u=r.getCurrentUserID(),E=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:u}));return E.setRelayFlag(!0),E.setElement(g),E}sendMessage(s,r){return mA(this,void 0,void 0,function*(){var g,u,E;try{const m=function(P){let W="utf-8";Fs.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 mA(this,void 0,void 0,function*(){const{payload:{messageList:wA}}=EA,kA={MsgList:Ac(wA)};return Fs.core.common.buildAndSendPacket({servcmd:"im_long_msg.save_relay_json_msg",data:kA})})}(D),{payload:oA}=D;M=new al(Object.assign(Object.assign({},oA),{messageList:[],downloadKey:P,pbDownloadKey:W})),D.setElement(M)}catch(P){console.error(P)}}const{data:{message:T}}=yield(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageSender)===null||E===void 0?void 0:E.sendMessage(D,r);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:r}=this._core,g=s.payload,{downloadKey:u,pbDownload:E,type:m,messageList:D}=g,M=So(g,["downloadKey","pbDownload","type","messageList"]);try{const T=yield function(oA){return mA(this,void 0,void 0,function*(){return Fs.core.common.buildAndSendPacket({servcmd:"im_long_msg.get_relay_json_msg",data:{JsonMsgKey:oA}})})}(u),{MsgList:P}=T||{},W=P?.map(oA=>{const EA=Qr(oA);return new fI(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=""),r.info("downloadMergerMessage",` success downloadKey:${u}`),s}catch(T){const{errorCode:P}=T;throw new this._core.helper.ChatError({functionName:"downloadMergerMessage",code:P,moreMessage:u})}})}},ga=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:r,message:g,common:{getCurrentUserID:u},utils:{isArray:E}}=this._core,{GroupId:m,To_Account:D}=s;s.From_Account=s.From_Account||u();let M=null;if(m){M=this._generateGroupMessage(Object.assign(Object.assign({},s),{ToGroupId:m}));const T=r.userStore.getUserProfile(u());M.level=T?.level||0,E(D)&&D.length>0&&(M._receiverList=D)}else D&&(M=this._generateC2CMessage(s));return g.messageSender.sendMessage(M,s)})}_generateC2CMessage(s){const{message:r,OuterConstant:{CONV_C2C:g}}=this._core,u=g,E=r.messageHelper.parseServerPushMessage(s),m=r.messageFactory.createMessage(Object.assign(Object.assign({},E),{conversationType:u,flow:ec.OUT})),{elements:D}=E;return m.setElement(D),m}_generateGroupMessage(s){const{message:r,OuterConstant:{CONV_GROUP:g}}=this._core,u=g,E=r.messageHelper.parseServerGroupMessage(s),m=r.messageFactory.createMessage(Object.assign(Object.assign({},E),{conversationType:u,flow:ec.OUT})),{elements:D}=E;return m.setElement(D),m}},tc=new class{init(s){this._core=s;const{helper:r,notificationCenter:g,InnerEvent:{MESSAGE_PUSH:u},InnerEventSubType:{GROUP_MESSAGE_PINNED:E}}=s;g.subscribeInnerEvent(u,E,this._handleGroupMessagePinned,this),r.registerApi({apiName:"pinGroupMessage",context:this}),r.registerApi({apiName:"getPinnedGroupMessageList",context:this})}pinGroupMessage(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r,common:{isTopic:g},OuterConstant:{GROUP_ID_PREFIX:u},helper:{ChatError:E}}=this._core;let{groupID:m,message:D,isPinned:M}=s;const{sequence:T}=D;try{return yield function(P){return mA(this,void 0,void 0,function*(){const{common:{buildAndSendPacket:W,getCurrentUserID:oA}}=Fs.core,{groupID:EA,sequence:wA,isPinned:kA}=P,xA=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=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:oA}=P||{};throw new E({code:W,message:oA})}})}getPinnedGroupMessageList(s){return mA(this,void 0,void 0,function*(){let r=[];try{const g=yield function(u){return mA(this,void 0,void 0,function*(){const{groupID:E}=u,{common:{buildAndSendPacket:m}}=Fs.core;return m({servcmd:"group_open_http_svc.get_pinned_messages",data:{GroupId:E}})})}({groupID:s});if(g){const{PinnedMsgList:u=[]}=g;r=yield this._updatePinnedMessageInfo({serverPinnedMessageList:u,groupID:s})}return{code:0,data:{messageList:r}}}catch(g){throw g}})}_handleGroupMessagePinned(s){const{message:{messageHelper:r,messageFactory:g},notificationCenter:u,OuterEvent:E,OuterConstant:m}=this._core;s.GroupTips.forEach(D=>{const{ToGroupId:M,MsgBody:{PinnedMsg:T,OpType:P,MsgOperatorMemberExtraInfo:W,SdkGroupMessageId:oA}}=D,{UserId:EA,NickName:wA="",ImageUrl:kA=""}=W;let xA=null,LA=!1;if(P===md){LA=!0;const SA=r.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:wA,avatar:kA}}else if(P===kE){const{ClientTime:SA,Random:OA,SenderTinyId:qA,ServerTime:Ie,MsgSeq:le}=oA;xA={ID:`${qA}-${SA}-${OA}`,sequence:le,random:OA,time:Ie,clientTime:SA}}xA&&u.emitOuterEvent(E.PINNED_GROUP_MESSAGE_UPDATED,{name:E.PINNED_GROUP_MESSAGE_UPDATED,data:{groupID:M,message:xA,isPinned:LA,operatorInfo:{userID:EA,nick:wA,avatar:kA}}})})}_findMessageBySequence(s,r){const{message:{messageDataHandler:g}}=this._core;return[...g.getLocalMessageList(s),...g.getSparseMessageList(s)].find(u=>u.sequence===r)}_updatePinnedMessageInfo(s){return mA(this,arguments,void 0,function*({serverPinnedMessageList:r,groupID:g}){const{OuterConstant:{CONV_GROUP:u},utils:{isEmpty:E}}=this._core,m=[],D=[],M=[],T=new Map,P=`${u}${g}`;for(let oA=0;oA{const{sequence:kA}=wA,xA=T.get(kA),LA=oA[xA]||{userID:xA,nick:"",avatar:""};wA.pinnerInfo=LA}),m.sort((wA,kA)=>wA.sequence-kA.sequence),m}return[]})}_fetchPinnedMessageInfo(s){return mA(this,void 0,void 0,function*(){var r,g;const{message:{messageHistory:u},user:{userProfile:E},utils:{isArray:m}}=this._core,{conversationID:D,messageSequenceList:M,pinnerIDList:T}=s,P=yield Promise.all([this._fetchMessageBySequence({conversationID:D,messageSequenceList:M}),E?.getUserProfile({userIDList:T})]);if(m(P)){const W={};return(((r=P[1])===null||r===void 0?void 0:r.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 mA(this,void 0,void 0,function*(){const{utils:{isEmpty:r},message:{messageHistory:g}}=this._core,{conversationID:u,messageSequenceList:E}=s;return r(E)?[]:g.getGroupRoamingMessagesByAnchor({conversationID:u,messageSequenceList:E,getType:3})})}};class lg{constructor(r){this.eventType=Nc.DATA,this.index=0,this.markdown="",this.isLast=!1,this.binaryData=null;const{EventType:g,Index:u,Markdown:E,IsLast:m,BinaryData:D}=r;this.eventType=g,this.index=u,this.markdown=E,this.isLast=m,this.binaryData=D}}var yI=new class{constructor(){this._messageMap=new Map,this._retryCountMap=new Map}init(s){this._core=s;const{notificationCenter:r,OuterEvent:{MESSAGE_RECEIVED:g},InnerEvent:{HISTORY_MESSAGE_FETCHED:u},common:{workflowManager:E},constants:{WORKFLOW_NAME:m,WORKFLOW_STEP:D}}=s;r.subscribeInnerEvent(Io,this._handleStreamMessageChunkPush,this),r.subscribeOuterEvent(g,this._handleMessageReceived,this),r.subscribeInnerEvent(u,this.processHistoryMessage,this),E.registerWorkflowStep(m.SYNC_SERVER_INFO_AFTER_RE_ONLINE,D.STREAM_MESSAGE_RECOVER,this._recoverStreamMessage,this)}processHistoryMessage(s){const{utils:{isEmpty:r,safeStringify:g},ssoLog:u}=this._core;try{s?.forEach(E=>{var m;if(this._isValidStreamMessage(E)){const D=(m=E?._elements)===null||m===void 0?void 0:m[0],{streamMessageID:M,markdown:T,binaryData:P}=D?.content||{};r(T)&&r(P)?(this._messageMap.set(M,E),this._fetchStreamMessageChunks(E)):D.content.isStreamEnded=!0}})}catch(E){u.error("processHistoryMessage.error",g(E))}}_handleMessageReceived(s){const r=s.data;r?.forEach(g=>{var u,E;if(this._isValidStreamMessage(g)){const{streamMessageID:m}=((E=(u=g?._elements)===null||u===void 0?void 0:u[0])===null||E===void 0?void 0:E.content)||{};m&&(this._messageMap.set(m,g),this._fetchStreamMessageChunks(g))}})}_isValidStreamMessage(s){var r,g;const{utils:{isEmpty:u}}=this._core,{streamMessageID:E}=((g=(r=s?._elements)===null||r===void 0?void 0:r[0])===null||g===void 0?void 0:g.content)||{};return s.type===Vr.MSG_STREAM&&!u(E)}_fetchStreamMessageChunks(s){return mA(this,void 0,void 0,function*(){var r,g;const{constants:{ERROR_CODE:u},ssoLog:E,utils:{safeStringify:m}}=this._core,D=(r=s._elements)===null||r===void 0?void 0:r[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 mA(this,void 0,void 0,function*(){const{from:wA,to:kA,streamMessageID:xA,index:LA}=EA,SA={From_Account:wA,To_Account:kA,StreamMsgID:xA,AckIndex:LA};return Fs.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===u.NETWORK_TIMEOUT&&this._shouldRetryFetch(M)){const P=this._retryCountMap.get(M)||0;E.debug("_fetchStreamMessageChunks.timeout",`error: ${m(T)} retried: ${P}`),this._retryCountMap.set(M,P+1),this._fetchStreamMessageChunks(s)}else E.error("_fetchStreamMessageChunks.error",m(T))}})}_shouldRetryFetch(s){const{utils:{isNumber:r}}=this._core;if(!this._retryCountMap.has(s))return this._retryCountMap.set(s,1),!0;const g=this._retryCountMap.get(s);return!!(r(g)&&g<=3)}_onStreamEnded(s,r,g){const{ssoLog:u}=this._core;g.content.isStreamEnded=!0,g.stopReason=r,this._messageMap.delete(s),u.debug("_onStreamEnded",`streamMessage end, StopReason: ${r}`)}_handleStreamMessageChunkPush(s){var r;const{ssoLog:g}=this._core,{StopReason:u,Chunks:E,StreamID:m}=s?.body||{},D=this._messageMap.get(m);if(!D)return void g.warn(`_handleStreamMessageChunkPush, unfounded message: ${m}`);const M=(r=D._elements)===null||r===void 0?void 0:r[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:oA},ssoLog:EA,channel:wA}=Fs.core,kA={StreamMsgID:T,AckIndex:P};try{const xA=W({servcmd:"StreamMsg.AckHttp",data:kA});wA.sendPacket(xA)}catch(xA){EA.debug("sendStreamChunkAck",oA(xA))}})}(m,M.getLatestIndex()),M.content.isStreamEnded&&this._onStreamEnded(m,u,M)}}_emitMessageModify(s){const{notificationCenter:r,OuterEvent:{MESSAGE_MODIFIED:g}}=this._core;r.emitOuterEvent(g,{name:g,data:[s]})}_validateExpectedChunk(s,r){const g=s.getLatestIndex()+1;let u=!1;for(let E=0;Em.Index).join(", ")}]`),!1}return!0}_recoverStreamMessage(){this._retryCountMap.clear();const{ssoLog:s,utils:{safeStringify:r}}=this._core;try{const g=Array.from(this._messageMap.entries());for(let u=Math.max(0,g.length-300);u{const LA=this._getResponseBody(kA,E,oA&&EA),SA=this._buildResponse(kA,LA);if(kA.status===200)r(null,SA);else{if(EA&&!wA.includes(EA))return s.url=this._domainName2IP(wA,EA),s.uploadByIP=!0,this.request(s,r);r({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)};r(OA,SA)},s.onProgress&&kA.upload&&(kA.upload.onprogress=LA=>{const{total:SA,loaded:OA}=LA,qA=Math.min(Math.floor(100*OA/SA),100);s.onProgress({total:SA,loaded:OA,percent:qA/100})}),kA.send(P),kA})}_buildResponse(s,r){const g={};return s.getAllResponseHeaders().trim().split(`
+`).forEach(u=>{if(u){const[E,m]=u.split(":").map(D=>D.trim());g[E.toLowerCase()]=m}}),{statusCode:s.status,statusMessage:s.statusText,headers:g,data:r}}_getResponseBody(s,r,g){return s.status===200&&r?{location:r,uploadIP:g}:{response:s.responseText,uploadIP:g}}_queryString(s,r="&",g="="){var u;const{isEmpty:E,isPlainObject:m}=(u=this._core)===null||u===void 0?void 0:u.utils;return E(s)?"":m(s)?Object.keys(s).map(D=>{const M=encodeURIComponent(D)+g;return Array.isArray(s[D])?s[D].map(T=>M+encodeURIComponent(T)).join(r):M+encodeURIComponent(s[D])}).filter(Boolean).join(r):void 0}_domainName2IP(s,r){return s.replace(/^http(s)?:\/\/(.*?)\//,`https://${r}/`)}};const Hu=["unknown","image","video","audio","log"];var DI=new class{init(s){this._core=s}request(s,r){var g;const{MINI_APP_NAMESPACE:u,IN_ALIPAY_MINI_APP:E,isUniIOSApp:m}=(g=this._core)===null||g===void 0?void 0:g.utils,{resources:D="",headers:M={},url:T,downloadUrl:P=""}=s;let W=T,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||"",xA={key:s.fileKey||kA,success_action_status:200,"Content-Type":""},LA={};if(m()){const[OA,qA]=T.split("?sign=");qA&&(W=`${OA}?sign=${encodeURIComponent(qA)}`,LA.sign=decodeURIComponent(qA),LA.signature=decodeURIComponent(qA))}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,qA=So(SA,["name"]);SA=Object.assign(Object.assign({},qA),{fileName:"file",fileType:s.fileType?Hu[s.fileType]:"image"})}return oA=u.uploadFile(Object.assign(Object.assign({},SA),{success:OA=>{this._handleResponse({response:OA,downloadUrl:P,callback:r})},fail:OA=>{this._handleResponse({response:OA,downloadUrl:P,callback:r})}})),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:r,response:g,callback:u}=s,E={};if(g.header)for(const D in g.header)g.header.hasOwnProperty(D)&&(E[D.toLowerCase()]=g.header[D]);const m=+g.statusCode;m===200?u(null,{statusCode:m,headers:E,data:Object.assign(Object.assign({},g.data),{location:r})}):u({code:m,message:JSON.stringify(g.data)},{statusCode:m,headers:E,data:void 0})}};function gl(s){return function(r){return Object.prototype.toString.call(r).match(/^\[object (.*)\]$/)[1].toLowerCase()}(s)==="file"}function Lr(s){const r=s||99999999;return Math.round(Math.random()*r)}function Ur(s,r=!0,g=!0){const u=Date.now();return r?g?u-s+" ms":`${Math.round((u-s)/1e3)} s`:g?u-s:Math.round((u-s)/1e3)}function Ig(s){return`${Array.from({length:8},()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1)).join("")}-${s}`}function lr(s,r){return Math.round(Number(s)*10**r)/10**r}function _r(s){return s<=1048576?`${lr(s/1024,1)}KB/s`:`${lr(s/1048576,1)}MB/s`}const ic="TIMImageElem",Fg="TIMSoundElem",Ya="TIMFileElem",Ol="TIMVideoFileElem",ha="RichMediaMessagePlugin",SI=["rich.my-imcloud.com","imrich.qcloud.com"],ou=1,Ba=2,cl=3,PE=255;var su;(function(s){s.UNSENT="unSend",s.SUCCESS="success",s.FAIL="fail"})(su||(su={}));const xE={wechat:/^(wxfile:\/\/tmp_|http:\/\/temp\/|cloud:\/\/temp-)/,alipay:/^(https:\/\/resource\/|alipayfile:\/\/tmp\/)/,baidu:/^(http:\/\/tmp\/|swanfile:\/\/tmp_)/,bytedance:/^(ttfile:\/\/tmp_|\/(var|tmp)\/|tttemp:\/\/)/,qq:/^(qqfile:\/\/tmp_|http:\/\/qtemp\/)/},Jr=Symbol("isCustomUpload");var nu,xt=new class{init(s){this._core=s}addAuthToUrl(s=""){if(this._isMiniProgramTempFile(s))return s;const r=function(g){return g?g.startsWith("https://")?g:g.startsWith("http://")?g.replace("http://","https://"):g:""}(s);return this.processResourceUrl(r)}removeAuthToUrl(s){return function(r,g){const[u,E]=r.split("?");if(!E)return u;const m=E.split("&").reduce((M,T)=>{const[P,W]=T.split("=");return P&&P!==g&&(M[P]=W||""),M},{}),D=Object.keys(m).map(M=>`${M}${m[M]?`=${m[M]}`:""}`).join("&");return D?`${u}?${D}`:u}(s,"authKey")}_isMiniProgramTempFile(s){return!!this.getPlatformFlags().IN_MINI_APP&&Object.values(xE).some(r=>r.test(s))}extractFileFromInput(s){const{utils:{isArray:r}}=this._core;return gl(s)?s:function(g){if(typeof g!="object"||g===null)return!1;const u=Object.getPrototypeOf(g);if(u===null)return!0;let E=u;for(;Object.getPrototypeOf(E)!==null;)E=Object.getPrototypeOf(E);return u===E}(s)&&typeof uni<"u"?r(s.tempFiles)&&s.tempFiles.length>0?s.tempFiles[0]:r(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 r;const{IN_MINI_APP:g,IN_BROWSER:u}=((r=this._core)===null||r===void 0?void 0:r.utils)||{};return this._shouldSkipProbing()?{width:0,height:0}:u?this._probeImageDimensionsWeb(s):g?this._probeImageDimensionsMiniApp(s):void 0})}isSimpleCos(){var s;const r=((s=this._core)===null||s===void 0?void 0:s.store.get("cloudConfig"))||{},{simple_cos:g}=r;return g!=="0"}getFileDNList(){var s;let r=SI;const g=((s=this._core)===null||s===void 0?void 0:s.store.get("cloudConfig"))||{},{file_dn_list:u}=g;if(u===void 0)return r;try{JSON.parse(u).forEach(E=>{r.includes(E)||r.push(E)})}catch(E){console.warn(E),r=SI}return r}getPlatform(){var s;return(s=this._core)===null||s===void 0?void 0:s.utils.platform}generateUUID(s,r){var g;let u=`${this.getSDKAppID()}-${this.getCurrentUserID()}-${(g=this._core)===null||g===void 0?void 0:g.utils.randomString()}`;if(r)return`${u}.${r}`;const E=s.name||s.value||s.url||s.tempFilePath,m=E&&E.slice(E.lastIndexOf(".")+1);return m&&(u=`${u}.${m}`),u}processResourceUrl(s){if(!s)return"";let r=s;const g=this.getFileDownloadProxy(),u=this.getAuthKey(),E=this.getFileDNList();return g&&(s.startsWith("http://")?r=s.replace(/^http:\/\/[^/]+/,g):s.startsWith("https://")&&(r=s.replace(/^https:\/\/[^/]+/,g))),u&&r.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?`${r}&authKey=${u}`:`${r}?authKey=${u}`),r}getCurrentUserID(){var s,r;return(r=(s=this._core)===null||s===void 0?void 0:s.store.get("login"))===null||r===void 0?void 0:r.userId}getSDKAppID(){var s,r;return(r=(s=this._core)===null||s===void 0?void 0:s.store.get("instance"))===null||r===void 0?void 0:r.sdkAppId}getFileDownloadProxy(){var s,r;return((r=(s=this._core)===null||s===void 0?void 0:s.store.get("instance"))===null||r===void 0?void 0:r.fileDownloadProxy)||""}getFileUploadProxy(){var s,r;return((r=(s=this._core)===null||s===void 0?void 0:s.store.get("instance"))===null||r===void 0?void 0:r.fileUploadProxy)||""}getAuthKey(){var s,r;return((r=(s=this._core)===null||s===void 0?void 0:s.store.get("login"))===null||r===void 0?void 0:r.authKey)||""}isPrivateNetWork(){var s,r;return(r=(s=this._core)===null||s===void 0?void 0:s.store.get("instance"))===null||r===void 0?void 0:r.proxyServer}getPlatformFlags(){var s;const{IN_BROWSER:r,IN_MINI_APP:g,IN_RN_APP:u,IN_UNI_NATIVE_APP:E}=(s=this._core)===null||s===void 0?void 0:s.utils;return{IN_BROWSER:r,IN_MINI_APP:g,IN_RN_APP:u,IN_UNI_NATIVE_APP:E}}isEmpty(s){var r;const{isEmpty:g}=(r=this._core)===null||r===void 0?void 0:r.utils;return g(s)}generateURL(s,r){const{needAddAuthToUrl:g=!0}=r||{};return g?this.addAuthToUrl(s):s}_probeImageDimensionsMiniApp(s){var r;const{MINI_APP_NAMESPACE:g}=((r=this._core)===null||r===void 0?void 0:r.utils)||{};return new Promise(u=>{g.getImageInfo({src:s,success:E=>u({width:E.width,height:E.height}),fail:()=>u({width:0,height:0})})})}_shouldSkipProbing(){var s;const{IN_RN_APP:r,IS_IE:g,IE_VERSION:u,IN_WX_MINI_GAME:E}=((s=this._core)===null||s===void 0?void 0:s.utils)||{};return r||g&&u===9||E}_probeImageDimensionsWeb(s){return new Promise(r=>{const g=new Image,u=()=>{g.onload=null,g.onerror=null,g.src=""};g.onload=()=>{r({width:g.width,height:g.height}),u()},g.onerror=()=>{r({width:0,height:0}),u()},g.src=s})}},qu={exports:{}},Ku=(nu||(nu=1,function(s){s.exports=function(r){var g=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];function u(LA,SA){var OA=LA[0],qA=LA[1],Ie=LA[2],le=LA[3];qA=((qA+=((Ie=((Ie+=((le=((le+=((OA=((OA+=(qA&Ie|~qA&le)+SA[0]-680876936|0)<<7|OA>>>25)+qA|0)&qA|~OA&Ie)+SA[1]-389564586|0)<<12|le>>>20)+OA|0)&OA|~le&qA)+SA[2]+606105819|0)<<17|Ie>>>15)+le|0)&le|~Ie&OA)+SA[3]-1044525330|0)<<22|qA>>>10)+Ie|0,qA=((qA+=((Ie=((Ie+=((le=((le+=((OA=((OA+=(qA&Ie|~qA&le)+SA[4]-176418897|0)<<7|OA>>>25)+qA|0)&qA|~OA&Ie)+SA[5]+1200080426|0)<<12|le>>>20)+OA|0)&OA|~le&qA)+SA[6]-1473231341|0)<<17|Ie>>>15)+le|0)&le|~Ie&OA)+SA[7]-45705983|0)<<22|qA>>>10)+Ie|0,qA=((qA+=((Ie=((Ie+=((le=((le+=((OA=((OA+=(qA&Ie|~qA&le)+SA[8]+1770035416|0)<<7|OA>>>25)+qA|0)&qA|~OA&Ie)+SA[9]-1958414417|0)<<12|le>>>20)+OA|0)&OA|~le&qA)+SA[10]-42063|0)<<17|Ie>>>15)+le|0)&le|~Ie&OA)+SA[11]-1990404162|0)<<22|qA>>>10)+Ie|0,qA=((qA+=((Ie=((Ie+=((le=((le+=((OA=((OA+=(qA&Ie|~qA&le)+SA[12]+1804603682|0)<<7|OA>>>25)+qA|0)&qA|~OA&Ie)+SA[13]-40341101|0)<<12|le>>>20)+OA|0)&OA|~le&qA)+SA[14]-1502002290|0)<<17|Ie>>>15)+le|0)&le|~Ie&OA)+SA[15]+1236535329|0)<<22|qA>>>10)+Ie|0,qA=((qA+=((Ie=((Ie+=((le=((le+=((OA=((OA+=(qA&le|Ie&~le)+SA[1]-165796510|0)<<5|OA>>>27)+qA|0)&Ie|qA&~Ie)+SA[6]-1069501632|0)<<9|le>>>23)+OA|0)&qA|OA&~qA)+SA[11]+643717713|0)<<14|Ie>>>18)+le|0)&OA|le&~OA)+SA[0]-373897302|0)<<20|qA>>>12)+Ie|0,qA=((qA+=((Ie=((Ie+=((le=((le+=((OA=((OA+=(qA&le|Ie&~le)+SA[5]-701558691|0)<<5|OA>>>27)+qA|0)&Ie|qA&~Ie)+SA[10]+38016083|0)<<9|le>>>23)+OA|0)&qA|OA&~qA)+SA[15]-660478335|0)<<14|Ie>>>18)+le|0)&OA|le&~OA)+SA[4]-405537848|0)<<20|qA>>>12)+Ie|0,qA=((qA+=((Ie=((Ie+=((le=((le+=((OA=((OA+=(qA&le|Ie&~le)+SA[9]+568446438|0)<<5|OA>>>27)+qA|0)&Ie|qA&~Ie)+SA[14]-1019803690|0)<<9|le>>>23)+OA|0)&qA|OA&~qA)+SA[3]-187363961|0)<<14|Ie>>>18)+le|0)&OA|le&~OA)+SA[8]+1163531501|0)<<20|qA>>>12)+Ie|0,qA=((qA+=((Ie=((Ie+=((le=((le+=((OA=((OA+=(qA&le|Ie&~le)+SA[13]-1444681467|0)<<5|OA>>>27)+qA|0)&Ie|qA&~Ie)+SA[2]-51403784|0)<<9|le>>>23)+OA|0)&qA|OA&~qA)+SA[7]+1735328473|0)<<14|Ie>>>18)+le|0)&OA|le&~OA)+SA[12]-1926607734|0)<<20|qA>>>12)+Ie|0,qA=((qA+=((Ie=((Ie+=((le=((le+=((OA=((OA+=(qA^Ie^le)+SA[5]-378558|0)<<4|OA>>>28)+qA|0)^qA^Ie)+SA[8]-2022574463|0)<<11|le>>>21)+OA|0)^OA^qA)+SA[11]+1839030562|0)<<16|Ie>>>16)+le|0)^le^OA)+SA[14]-35309556|0)<<23|qA>>>9)+Ie|0,qA=((qA+=((Ie=((Ie+=((le=((le+=((OA=((OA+=(qA^Ie^le)+SA[1]-1530992060|0)<<4|OA>>>28)+qA|0)^qA^Ie)+SA[4]+1272893353|0)<<11|le>>>21)+OA|0)^OA^qA)+SA[7]-155497632|0)<<16|Ie>>>16)+le|0)^le^OA)+SA[10]-1094730640|0)<<23|qA>>>9)+Ie|0,qA=((qA+=((Ie=((Ie+=((le=((le+=((OA=((OA+=(qA^Ie^le)+SA[13]+681279174|0)<<4|OA>>>28)+qA|0)^qA^Ie)+SA[0]-358537222|0)<<11|le>>>21)+OA|0)^OA^qA)+SA[3]-722521979|0)<<16|Ie>>>16)+le|0)^le^OA)+SA[6]+76029189|0)<<23|qA>>>9)+Ie|0,qA=((qA+=((Ie=((Ie+=((le=((le+=((OA=((OA+=(qA^Ie^le)+SA[9]-640364487|0)<<4|OA>>>28)+qA|0)^qA^Ie)+SA[12]-421815835|0)<<11|le>>>21)+OA|0)^OA^qA)+SA[15]+530742520|0)<<16|Ie>>>16)+le|0)^le^OA)+SA[2]-995338651|0)<<23|qA>>>9)+Ie|0,qA=((qA+=((le=((le+=(qA^((OA=((OA+=(Ie^(qA|~le))+SA[0]-198630844|0)<<6|OA>>>26)+qA|0)|~Ie))+SA[7]+1126891415|0)<<10|le>>>22)+OA|0)^((Ie=((Ie+=(OA^(le|~qA))+SA[14]-1416354905|0)<<15|Ie>>>17)+le|0)|~OA))+SA[5]-57434055|0)<<21|qA>>>11)+Ie|0,qA=((qA+=((le=((le+=(qA^((OA=((OA+=(Ie^(qA|~le))+SA[12]+1700485571|0)<<6|OA>>>26)+qA|0)|~Ie))+SA[3]-1894986606|0)<<10|le>>>22)+OA|0)^((Ie=((Ie+=(OA^(le|~qA))+SA[10]-1051523|0)<<15|Ie>>>17)+le|0)|~OA))+SA[1]-2054922799|0)<<21|qA>>>11)+Ie|0,qA=((qA+=((le=((le+=(qA^((OA=((OA+=(Ie^(qA|~le))+SA[8]+1873313359|0)<<6|OA>>>26)+qA|0)|~Ie))+SA[15]-30611744|0)<<10|le>>>22)+OA|0)^((Ie=((Ie+=(OA^(le|~qA))+SA[6]-1560198380|0)<<15|Ie>>>17)+le|0)|~OA))+SA[13]+1309151649|0)<<21|qA>>>11)+Ie|0,qA=((qA+=((le=((le+=(qA^((OA=((OA+=(Ie^(qA|~le))+SA[4]-145523070|0)<<6|OA>>>26)+qA|0)|~Ie))+SA[11]-1120210379|0)<<10|le>>>22)+OA|0)^((Ie=((Ie+=(OA^(le|~qA))+SA[2]+718787259|0)<<15|Ie>>>17)+le|0)|~OA))+SA[9]-343485551|0)<<21|qA>>>11)+Ie|0,LA[0]=OA+LA[0]|0,LA[1]=qA+LA[1]|0,LA[2]=Ie+LA[2]|0,LA[3]=le+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,qA,Ie,le,bi,ki=LA.length,Ot=[1732584193,-271733879,-1732584194,271733878];for(SA=64;SA<=ki;SA+=64)u(Ot,E(LA.substring(SA-64,SA)));for(OA=(LA=LA.substring(SA-64)).length,qA=[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(qA[SA>>2]|=128<<(SA%4<<3),SA>55)for(u(Ot,qA),SA=0;SA<16;SA+=1)qA[SA]=0;return Ie=(Ie=8*ki).toString(16).match(/(.*?)(.{0,8})$/),le=parseInt(Ie[2],16),bi=parseInt(Ie[1],16)||0,qA[14]=le,qA[15]=bi,u(Ot,qA),Ot}function M(LA){var SA,OA,qA,Ie,le,bi,ki=LA.length,Ot=[1732584193,-271733879,-1732584194,271733878];for(SA=64;SA<=ki;SA+=64)u(Ot,m(LA.subarray(SA-64,SA)));for(OA=(LA=SA-64>2]|=LA[SA]<<(SA%4<<3);if(qA[SA>>2]|=128<<(SA%4<<3),SA>55)for(u(Ot,qA),SA=0;SA<16;SA+=1)qA[SA]=0;return Ie=(Ie=8*ki).toString(16).match(/(.*?)(.{0,8})$/),le=parseInt(Ie[2],16),bi=parseInt(Ie[1],16)||0,qA[14]=le,qA[15]=bi,u(Ot,qA),Ot}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 qA,Ie,le,bi,ki=this.byteLength,Ot=LA(SA,ki),Li=ki;return OA!==r&&(Li=LA(OA,ki)),Ot>Li?new ArrayBuffer(0):(qA=Li-Ot,Ie=new ArrayBuffer(qA),le=new Uint8Array(Ie),bi=new Uint8Array(this,Ot,qA),le.set(bi),Ie)}}(),xA.prototype.append=function(LA){return this.appendBinary(W(LA)),this},xA.prototype.appendBinary=function(LA){this._buff+=LA,this._length+=LA.length;var SA,OA=this._buff.length;for(SA=64;SA<=OA;SA+=64)u(this._hash,E(this._buff.substring(SA-64,SA)));return this._buff=this._buff.substring(SA-64),this},xA.prototype.end=function(LA){var SA,OA,qA=this._buff,Ie=qA.length,le=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(SA=0;SA>2]|=qA.charCodeAt(SA)<<(SA%4<<3);return this._finish(le,Ie),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,qA,Ie,le=SA;if(LA[le>>2]|=128<<(le%4<<3),le>55)for(u(this._hash,LA),le=0;le<16;le+=1)LA[le]=0;OA=(OA=8*this._length).toString(16).match(/(.*?)(.{0,8})$/),qA=parseInt(OA[2],16),Ie=parseInt(OA[1],16)||0,LA[14]=qA,LA[15]=Ie,u(this._hash,LA)},xA.hash=function(LA,SA){return xA.hashBinary(W(LA),SA)},xA.hashBinary=function(LA,SA){var OA=P(D(LA));return SA?kA(OA):OA},xA.ArrayBuffer=function(){this.reset()},xA.ArrayBuffer.prototype.append=function(LA){var SA,OA=wA(this._buff.buffer,LA),qA=OA.length;for(this._length+=LA.byteLength,SA=64;SA<=qA;SA+=64)u(this._hash,m(OA.subarray(SA-64,SA)));return this._buff=SA-64>2]|=qA[SA]<<(SA%4<<3);return this._finish(le,Ie),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=oA(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}()}(qu)),qu.exports),SC=gI(Ku),K=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 r;this._core=s;const{IN_MINI_APP:g}=s.utils;this.httpRequest=g?DI:Ju,(r=this.httpRequest)===null||r===void 0||r.init(s)}uploadToCOS(s){return mA(this,void 0,void 0,function*(){const r=`${ha} uploadToCOS`,{ssoLog:g,utils:{safeStringify:u}}=this._core,{file:E}=s;this.uploadFileType=s.uploadFileType,g.debug("uploadToCOS",`${r} options:${u(s)}`);try{const m=Date.now(),D=yield this._createCosOptions(s),M=D.fileExistsInCOS?{data:{location:D.downloadUrl}}:yield this._uploadFile(D);this._handleUploadError(M,s);const T=this._createUploadResult(E,M),P=Date.now()-m,W=function(EA){return EA<1024?`${EA}B`:EA<1048576?`${Math.floor(EA/1024)}KB`:`${Math.floor(EA/1048576)}MB`}(E.size),oA=`size:${W} time:${P}ms speed:${_r(1e3*E.size/P)}`;return g.debug("uploadToCOS",`${r} ok. name:${E.name} ${oA}`),{uploadOptions:D,response:T}}catch(m){throw g.warn("uploadToCOS",`${r} failed, error:${u(m)}`),m}})}_handleUploadError(s,r){var g,u;const{ChatError:E}=(g=this._core)===null||g===void 0?void 0:g.helper;if(s.statusCode===403)throw r.url,!((u=s?.data)===null||u===void 0)&&u.uploadIP&&s.data.uploadIP,new E({message:"Upload failed with status 403"})}_createUploadResult(s,r){return{fileName:s.name,fileSize:s.size,fileType:s.type.slice(s.type.indexOf("/")+1).toLowerCase(),location:r.data.location||"",uploadTime:Ur(Date.now(),!1),uploadSpeed:_r(1e3*s.size/Ur(Date.now(),!1))}}_createCosOptions(s){return mA(this,void 0,void 0,function*(){const{fileName:r,resources:g,uploadMethod:u}=yield this._prepareUploadParams(s),E=this._isC2CConversation(s.message.conversationID)?1:2;try{const m=yield this._fetchCosSignatureUrl({fileType:this.uploadFileType,fileName:r,uploadMethod:u,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=!xt.isPrivateNetWork()&&m.uploadIP;return{url:this._getRawOrUploadProxyUrl(D),fileType:this.uploadFileType,fileName:r,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 mA(this,void 0,void 0,function*(){const{ssoLog:r,utils:{safeStringify:g,isEmpty:u}}=this._core;r.debug("_prepareUploadParams",` prepareUploadParams:${g(s)}`);const{file:E}=s,{IN_MINI_APP:m,IN_RN_APP:D}=xt.getPlatformFlags(),M=m||D,T=M&&s.message.type!==Ya,{name:P}=E,W=P.slice(P.lastIndexOf(".")),oA=`${Lr(999999)}${W}`,EA=T?E.name:oA,wA=yield this._generateHashFileName(E);return{fileName:u(wA)?Ig(EA):`${wA}${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:r,IN_BROWSER:g,IN_UNI_NATIVE_APP:u,isArray:E},ssoLog:m}=this._core,D=Date.now();let M="";return g&&(M=yield this._generateHashFileNameInWeb(s)),r&&(E(s.tempFiles)&&(s=s.tempFiles[0]),u||(M=yield this._generateFileNameInMiniProgram(s)),u&&(M=yield this._generateFileNameInUNINativeApp(s))),m.info("_generateHashFileName",`hashFileName:${M} costTime:${Date.now()-D}`),M})}_generateHashFileNameInWeb(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r,utils:{safeStringify:g}}=this._core;let u="";try{u=yield new Promise((E,m)=>{const D=File.prototype.slice||File.prototype.mozSlice||File.prototype.webkitSlice;D||(r.warn("_generateHashFileNameInWeb","Browser does not support file slicing"),E(""));const M=10485760,T=Math.ceil(s.size/M);let P=0;const W=new SC.ArrayBuffer,oA=new FileReader,EA=setTimeout(()=>{oA.abort(),r.warn("_generateHashFileNameInWeb","File hash generation timeout"),E("")},2e3);function wA(){const kA=P*M,xA=kA+M>=s.size?s.size:kA+M;oA.readAsArrayBuffer(D.call(s,kA,xA))}oA.onload=kA=>{r.debug("_generateHashFileNameInWeb",`read chunk nr ${P+1} of ${T}`),W.append(kA.target.result),P++,P{clearTimeout(EA),m(kA)},wA()})}catch(E){r.warn("_generateHashFileNameInWeb",g(E))}return u})}_generateFileNameInMiniProgram(s){return mA(this,void 0,void 0,function*(){const{utils:{MINI_APP_NAMESPACE:r,safeStringify:g,isEmpty:u},ssoLog:E}=this._core;let m="";if(u(s.url))return E.warn("_generateFileNameInMiniProgram","file.url is empty"),m;if(typeof r?.getFileSystemManager!="function")return E.warn("_generateFileNameInUNINativeApp","getFileSystemManager is not a function"),m;try{m=yield new Promise((D,M)=>{r.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 r;const{utils:{safeStringify:g,isEmpty:u},ssoLog:E}=this._core;let m="";if(u(s.url))return E.warn("_generateFileNameInUNINativeApp","file.url is empty"),m;if(typeof((r=plus==null?void 0:plus.io)===null||r===void 0?void 0:r.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,r){if(typeof r.onProgress=="function")try{r.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:r,utils:{safeStringify:g}}=this._core,u=xt.isSimpleCos(),E=this._prepareCosRequestData(s),m=u?"im_cos_msg.simple_sig":"im_cos_msg.pre_sig";try{const D=yield function(T,P,W){return mA(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 r.debug("_fetchCosSignatureUrl",` ok. isSimpleCos:${u} data:${g(M)}`),M||{}}catch(D){if(this.fetchCosTryCount<1)return this.fetchCosTryCount++,this._fetchCosSignatureUrl(s);throw this.fetchCosTryCount=0,D}})}_processResponse(s){var r;const g=xt.isSimpleCos(),u=g?(r=s?.rpt_pre_sig)===null||r===void 0?void 0:r[0]:s;if(!u)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:xA,str_snapshot_url:LA,str_file_key:SA}=u;return{uploadIP:W,preSig:oA,fileID:EA,existFlag:wA,downloadUrl:kA,uploadUrl:xA,requestSnapshotUrl:LA,fileKey:SA}}const{upload_url:E,download_url:m,snapshot_url:D,thumb_url:M,large_url:T,file_key:P}=u;return{uploadUrl:E,downloadUrl:m,requestSnapshotUrl:D,thumbUrl:M,largeUrl:T,fileKey:P}}_prepareCosRequestData(s){return xt.isSimpleCos()?{uint32_upload_method:s.uploadMethod,uint32_platform:xt.getPlatform(),uint32_sdkappid:xt.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((r,g)=>{this.httpRequest.request(s,(u,E)=>{u&&this.uploadFileTryCount=3e4}_syncSystemClock(s){var r,g,u;const E=((r=s.headers)===null||r===void 0?void 0:r.date)||((g=s.headers)===null||g===void 0?void 0:g.Date)||((u=s.error)===null||u===void 0?void 0:u.ServerTime);if(E){const m=Date.now(),D=Date.parse(E);this.systemClockOffset=D-m}}_getRawOrUploadProxyUrl(s){const r=xt.getFileUploadProxy();let g=s;return r&&(g=s.replace(/^https:\/\/[^/]+/,r)),g}_isC2CConversation(s){return s.slice(0,3)==="C2C"}};const U=2108,sA=2251,b=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,ee=2;class fe{constructor(r,g){this.instanceID=Lr(9999999),this.sizeType=r.type||0,this.type=0,this.size=r.size||0,this.width=r.width||0,this.height=r.height||0,this.imageUrl=xt.addAuthToUrl(r.imageUrl||r.url||""),this.url=xt.addAuthToUrl(r.url||g)}setSizeType(r){this.sizeType=r}setType(r){this.type=r}setImageUrl(r){r&&(this.imageUrl=xt.addAuthToUrl(r))}getImageUrl(){return this.imageUrl}}function p(s){const{originUrl:r,originWidth:g,originHeight:u,min:E=198}=s,m=parseInt(g)||0,D=parseInt(u)||0,M={url:void 0,width:0,height:0};if((m<=D?m:D)<=E)M.url=r,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=r&&r.indexOf("?")>-1?`${r}&`:`${r}?`;M.url=E===198?`${T}imageView2/3/w/198/h/198`:`${T}imageView2/3/w/720/h/720`}if(r===void 0){const{url:T}=M;return So(M,["url"])}return M}class B{constructor(r){this._imageMemoryURL="",this._percent=0,this.type=ic;const{uuid:g,file:u,imageFormat:E,imageInfoArray:m=[],isCustomUpload:D=!1}=r;this._imageMemoryURL=this.createImageDataAsURL(u),this.content={imageFormat:E,uuid:g,imageInfoArray:[]},this[Jr]=D,this.initImageInfoArray(m),this.autoFixUrl()}static parseServerPushElement(r){const{MsgContent:g}=r,{ImageFormat:u,ImageInfoArray:E,UUID:m}=g,D=function(M){return M.map(T=>({size:T.Size,type:T.Type,width:T.Width,height:T.Height,url:T.URL}))}(E);return new B({imageFormat:u,imageInfoArray:D,uuid:m})}createImageDataAsURL(r){let g="";const{IN_MINI_APP:u,IN_RN_APP:E,IN_BROWSER:m}=xt.getPlatformFlags();return r&&((u||E)&&(g=r.url),m&&(g=window.URL.createObjectURL(r))),g}initImageInfoArray(r=[]){const g={type:0,size:0,width:0,height:0,url:""};for(let u=0;u<3;u++){const E=r[u]||Object.assign({},g),m=new fe(E,this._imageMemoryURL);m.setSizeType(u+1),m.setType(u),this.addImageInfo(m)}this.updateAccessSideImageInfoArray()}autoFixUrl(){const r=["http","https"];this.content.imageInfoArray.forEach(g=>{if(!g.url||g.imageUrl==="")return;const[u,...E]=g.imageUrl.split("://"),m=E.join("://");r.includes(u)||g.setImageUrl(`https://${m}`)})}updatePercent(r){this._percent=Math.min(r,1)}updateImageFormat(r){this.content.imageFormat=uA[r.toUpperCase()]||uA.UNKNOWN}addImageInfo(r){this.content.imageInfoArray.length>=3||this.content.imageInfoArray.push(r)}updateImageInfoArray(r){const g=this.content.imageInfoArray.length;let u;for(let E=0;E({InstanceId:g.instanceID,Type:g.sizeType,MsgType:g.type,Size:g.size,Width:g.width,Height:g.height,URL:xt.removeAuthToUrl(g.imageUrl)}))}}const v=new class{init(s){this.core=s}},G={[ou]:"i",[cl]:"a",[Ba]:"v",[PE]:"f"};let O=null,z=null;function X(s){var r;const{store:g,utils:{isNumber:u,safeStringify:E},ssoLog:m}=v.core;try{const D=((r=g.get("cloudConfig"))===null||r===void 0?void 0:r.upload_size_limit)||"";D!==z&&(z=D,O=JSON.parse(D)||{});const M=O?.[G[s]];if(u(M))return 1024*M*1024}catch(D){m.debug("getCloudControlUploadSizeLimit",E(D))}return null}var rA=new class{constructor(){this._messageOptionsMap=new Map}init(s){var r;this._core=s;const{notificationCenter:g,helper:u,InnerEvent:E,message:m}=s;u.registerApi({apiName:"createImageMessage",context:this}),u.registerExperimentalAPI("createImageMessage",this,"createCustomUploadImageMessage"),(r=m?.messageFactory)===null||r===void 0||r.registerElementClass(ic,B),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createImageMessage(s){var r,g,u;try{const E=(r=this._core.store.get("login"))===null||r===void 0?void 0:r.userId,m=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:E})),D=this._processImage(s);s.payload.file=D;const M={imageFormat:uA.UNKNOWN,uuid:xt.generateUUID(D),file:D,imageInfoArray:[]},T=new B(M);return m.setElement(T),this._messageOptionsMap.set(m.clientSequence,s),m}catch(E){throw E}}createCustomUploadImageMessage(s){var r,g,u,E;const{store:m,utils:{isEmpty:D}}=this._core,M=(r=m.get("login"))===null||r===void 0?void 0:r.userId,T=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:M})),{largeImageUuid:P,largeFileSize:W,largeImageWidth:oA,largeImageHeight:EA,largeImageUrl:wA,originImageUuid:kA,originFileSize:xA,originImageWidth:LA,originImageHeight:SA,originImageUrl:OA,thumbImageUuid:qA,thumbFileSize:Ie,thumbImageWidth:le,thumbImageHeight:bi,thumbImageUrl:ki}=((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 Ot=new B({imageFormat:uA.UNKNOWN,uuid:kA,imageInfoArray:[{instanceID:kA,size:xA,width:LA,height:SA,imageUrl:OA,url:OA},{instanceID:P,size:W,width:oA,height:EA,imageUrl:wA,url:wA},{instanceID:qA,size:Ie,width:le,height:bi,imageUrl:ki,url:ki}],isCustomUpload:!0});return T.setElement(Ot),this._messageOptionsMap.set(T.clientSequence,s),T._skipUpload=!0,T}upload(s){return mA(this,void 0,void 0,function*(){const r=s.getElements()[0],{file:g}=this._messageOptionsMap.get(s.clientSequence).payload;this._validateBeforeUploadImage(g);const u=yield this._performImageUpload(r,s,g),E=this._generateImageInfo(u);return r.updateImageFormat(u?.fileType),r.updateImageInfoArray(E),this._updateImageType(r.content.imageInfoArray),s})}_performImageUpload(s,r,g){return mA(this,void 0,void 0,function*(){const{to:u}=r,E={uploadFileType:ou,file:g,to:u,message:r,onProgress:M=>{var T,P;s.updatePercent(M),(P=(T=this._messageOptionsMap.get(r.clientSequence))===null||T===void 0?void 0:T.onProgress)===null||P===void 0||P.call(T,M)}},{uploadOptions:m,response:D}=yield K.uploadToCOS(E);return this._parseResponse(m,D)})}_generateImageInfo(s){const{location:r,fileSize:g,width:u,height:E,smallImageUrl:m,smallImageWidth:D,smallImageHeight:M,largeImageUrl:T,largeImageWidth:P,largeImageHeight:W,imageInfoArray:oA}=s,EA=xt.addAuthToUrl(r),wA={size:g,url:EA,width:u,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,u,E,720),this._generateThumbInfo(EA,u,E,198)]}_generateThumbInfo(s,r,g,u){return p({originUrl:s,originWidth:r,originHeight:g,min:u})}_processImageInfoArray(s,r){let g,u,E;for(const m of s)m.type===1?(u=m,u.size=r):m.type===2?(E=m,E.size=r):(g=m,g.size=r);return[Object.assign({},g),Object.assign({},E),Object.assign({},u)]}_parseResponse(s,r){return mA(this,void 0,void 0,function*(){try{const{thumbUrl:g,largeUrl:u,downloadUrl:E}=s;if(g&&u&&(yield this._getImageInfoByUrl(g,r,"thumb"),yield this._getImageInfoByUrl(u,r,"large")),xt.isSimpleCos()&&!xt.isPrivateNetWork()&&(yield this._getImageInfoArray(E,r),r?.uploadIP)){const m=this._extractDomainFromUrl(E);m&&(yield this._getDownloadIP(m,r))}return r}catch(g){throw g}})}_extractDomainFromUrl(s){var r;try{const g=s.match(/:\/\/([^\/]+)/);return g?g[1]:null}catch(g){return(r=this._core)===null||r===void 0||r.ssoLog.warn("_extractDomainFromUrl",`Failed to extract domain from URL:${g.message}`),null}}_getImageInfoByUrl(s,r,g){return mA(this,void 0,void 0,function*(){var u;try{const E=xt.addAuthToUrl(s),{width:m=0,height:D=0}=yield xt.probeImageWidthHeight(E);r.width=m,r.height=D,g==="thumb"?(r.smallImageUrl=s,r.smallImageWidth=m,r.smallImageHeight=D):(r.largeImageUrl=s,r.largeImageWidth=m,r.largeImageHeight=D)}catch(E){(u=this._core)===null||u===void 0||u.ssoLog.warn("_getImageInfoByUrl",`Failed to get ${g} image info:${E.message}`)}})}_validateBeforeUploadImage(s){var r;const{ChatError:g}=(r=this._core)===null||r===void 0?void 0:r.helper;if(!s)throw new g({code:sA});this._checkImageType(s),this._checkImageSize(s)}_processImage(s){var r;try{const{IN_MINI_APP:g}=(r=this._core)===null||r===void 0?void 0:r.utils;let{file:u}=s.payload;return u=g?this._processMiniAppImageFile(u):this._processWebImageFile(u),u}catch(g){throw g}}_processMiniAppImageFile(s){gl(s)&&console.warn("FileUnsupportedInMiniApp","createImageMessage");const r=s.tempFiles[0].path||s.tempFiles[0].tempFilePath;return{url:r,name:r.slice(r.lastIndexOf("/")+1),size:s.tempFiles&&s.tempFiles[0].size||1,type:r.slice(r.lastIndexOf(".")+1).toLowerCase()}}_processWebImageFile(s){var r;const{ChatError:g}=(r=this._core)===null||r===void 0?void 0:r.helper,u=xt.extractFileFromInput(s);if(!u)throw new g({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return u}_getDownloadIP(s,r){return mA(this,void 0,void 0,function*(){const g=`${ha} getDownloadIP domainName: ${s}`;try{const u=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},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(!u||!u.str_final_ip)return;console.log(`${g} ok. downloadIP:${u}`);const E=r.location.split("/");E[0]=u.str_final_ip,r.location=E.join("/")}catch(u){console.warn(u)}})}_getImageInfoArray(s,r){return mA(this,void 0,void 0,function*(){try{const g=yield function(u,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:u},P=m.generateProtocolData({servcmd:M,data:T}),W=`${P.head.seq}${M}`;return yield D.sendPacket(P,{requestId:W})}catch(m){throw console.warn("getImageInfo error:",m),m}})}(s,this._core);return r.imageInfoArray=this._processImageInfoResponse(g),r}catch(g){throw r.imageInfoArray=void 0,g}})}_processImageInfoResponse(s){if(!s)return[];const{rpt_msg_image_info:r}=s;return r.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:r,helper:g}=this._core;let u="";if(r.IN_MINI_APP&&(u=s.url.slice(s.url.lastIndexOf(".")+1)),r.IN_BROWSER&&(u=s.name.slice(s.name.lastIndexOf(".")+1)),iA.indexOf(u.toLowerCase())<0)throw new g.ChatError({code:b})}_checkImageSize(s){const{utils:r,helper:g,store:u}=this._core;let E=0;if(E=(r.IN_MINI_APP,s.size),E===0)throw new g.ChatError({code:U});if(E>=(X(ou)||20971520))throw new g.ChatError({code:x})}_updateImageType(s){s[1].type=ee,s[2].type=_A}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:r}=this._core;s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this)}};const DA=2108,GA=2401,JA=2402,ne="2.5.0",he="1.18.0";function Ze(s,r){const g=s.split("."),u=r.split("."),E=Math.max(g.length,u.length);for(;g.lengthM)return 1;if(D0;return{isValid:r,error:r?null:{message:"content can not be empty"}}}transformToServerFormat(r){const{isMergerMessage:g=!1}=r||{},u=g?this.payload:this.content,{uuid:E,downloadFlag:m,fileUrl:D,fileName:M,fileSize:T}=u;return{MsgType:this.type,MsgContent:{Download_Flag:m,Url:xt.removeAuthToUrl(D),FileName:M,FileSize:T,UUID:E}}}_getFileInfo(r){const{utils:{IN_UNI_NATIVE_APP:g}}=v.core;if(r.fileName&&r.fileSize)return{size:r.fileSize,name:r.fileName};const{file:u}=r;return u?(g&&this._processNativeAppFile(u),{size:u.size,name:u.name}):{size:0,name:""}}_processNativeAppFile(r){if(r.path&&r.path.includes(".")){const g=r.path.slice(r.path.lastIndexOf(".")+1).toLowerCase();r.type=g,r.name||(r.name=`${Lr(999999)}.${g}`)}r.name||(r.type="",r.name=r.path.slice(r.path.lastIndexOf("/")+1).toLowerCase()),r.suffix&&(r.type=r.suffix),r.url||(r.url=r.path)}}st=Jr;var Ft=new class{constructor(){this._messageOptionsMap=new Map}init(s){var r;this._core=s;const{notificationCenter:g,helper:u,InnerEvent:E,message:m}=s;u.registerApi({apiName:"createFileMessage",context:this}),u.registerExperimentalAPI("createFileMessage",this,"createCustomUploadFileMessage"),(r=m?.messageFactory)===null||r===void 0||r.registerElementClass(Ya,at),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createFileMessage(s){var r,g,u;try{this._checkVersion();const E=this._processFile(s.payload.file);s.payload.file=E;const m=(r=this._core.store.get("login"))===null||r===void 0?void 0:r.userId,D=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:m})),M={uuid:xt.generateUUID(E),file:E},T=new at(M);return D.setElement(T),this._messageOptionsMap.set(D.clientSequence,s),D}catch(E){throw E}}createCustomUploadFileMessage(s){var r,g,u;try{const{store:E,message:m,utils:{isEmpty:D}}=this._core,M=(r=E.get("login"))===null||r===void 0?void 0:r.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=(u=m.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:M})),wA=new at({url:T,uuid:P,file:{size:W,name:oA},isCustomUpload:!0});return EA.setElement(wA),EA}catch(E){throw E}}upload(s){return mA(this,void 0,void 0,function*(){const{file:r}=this._messageOptionsMap.get(s.clientSequence).payload;this._validateBeforeUploadFile(r);const g=s.getElements()[0],u=yield this._performFileUpload(g,s,r),E=xt.addAuthToUrl(u?.location);return g.updateFileUrl(E),s})}_validateBeforeUploadFile(s){const{helper:{ChatError:r}}=this._core;if(!s)throw new r({code:GA});const g=X(PE)||104857600;if(s.size>g)throw new r({code:JA});if(s.size===0)throw new r({code:DA})}_performFileUpload(s,r,g){return mA(this,void 0,void 0,function*(){const{to:u}=r,E={uploadFileType:PE,file:g,to:u,message:r,onProgress:D=>{var M,T;s.updatePercent(D),(T=(M=this._messageOptionsMap.get(r.clientSequence))===null||M===void 0?void 0:M.onProgress)===null||T===void 0||T.call(M,D)}},{response:m}=yield K.uploadToCOS(E);return m})}_processFile(s){var r,g;const{IN_BROWSER:u,IN_RN_APP:E,IN_WX_MINI_APP:m,IN_QQ_MINI_APP:D,IN_UNI_NATIVE_APP:M}=(r=this._core)===null||r===void 0?void 0:r.utils,{ChatError:T}=(g=this._core)===null||g===void 0?void 0:g.helper;if(u||M){const P=xt.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,r;const{MINI_APP_NAMESPACE:g,IN_MINI_APP:u,IN_WX_MINI_APP:E,IN_QQ_MINI_APP:m,IN_UNI_NATIVE_APP:D}=(s=this._core)===null||s===void 0?void 0:s.utils,{ChatError:M}=(r=this._core)===null||r===void 0?void 0:r.helper;if(u){if(!(E||m||D))throw new M({message:"Unsupported mini app environment"});const T=g.getSystemInfoSync().SDKVersion;if(E&&Ze(T,ne)<0)throw new M({message:`WXChooseMessageFile requires SDK version ${ne} or higher`});if(m&&Ze(T,he)<0)throw new M({message:`QQChooseMessageFile requires SDK version ${he} or higher`})}}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:r}=this._core;s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this)}};const Ht=2108,Pi=2351,co=2352,Xi=["mp4","quicktime","mov","video"];var di;class xo{constructor(r){this.type=Ol,this.uploadProgress=0,this[di]=!1;const g=typeof r?.videoSecond=="number"?r?.videoSecond:0;this[Jr]=r.isCustomUpload||!1,this.content={remoteVideoUrl:xt.addAuthToUrl(r.remoteVideoUrl||r.videoUrl||""),videoFormat:r.videoFormat,videoSecond:parseInt(g?.toString(),10),videoSize:r.videoSize,videoUrl:xt.addAuthToUrl(r.videoUrl),videoDownloadFlag:2,videoUUID:r.videoUUID,thumbUUID:r.thumbUUID,thumbFormat:r.thumbFormat,thumbWidth:r.thumbWidth,snapshotWidth:r.thumbWidth,thumbHeight:r.thumbHeight,snapshotHeight:r.thumbHeight,thumbSize:r.thumbSize,snapshotSize:r.thumbSize,thumbDownloadFlag:2,thumbUrl:xt.addAuthToUrl(r.thumbUrl),snapshotUrl:xt.addAuthToUrl(r.thumbUrl)}}static parseServerPushElement(r){const{MsgContent:g}=r,{VideoUrl:u,VideoFormat:E,VideoSecond:m,VideoSize:D,VideoDownloadFlag:M,VideoUUID:T,ThumbUUID:P,ThumbFormat:W,ThumbWidth:oA,SnapshotWidth:EA,ThumbHeight:wA,SnapshotHeight:kA,ThumbSize:xA,SnapshotSize:LA,ThumbDownloadFlag:SA,ThumbUrl:OA,SnapshotUrl:qA}=g;return new xo({videoUrl:u,videoFormat:E,videoSecond:m,videoSize:D,videoDownloadFlag:M,videoUUID:T,thumbUUID:P,thumbFormat:W,thumbWidth:oA,snapshotWidth:EA,thumbHeight:wA,snapshotHeight:kA,thumbSize:xA,snapshotSize:LA,thumbDownloadFlag:SA,thumbUrl:OA,snapshotUrl:qA})}updatePercent(r){this.uploadProgress=Math.min(r,1)}updateVideoUrl(r){r&&(this.content.remoteVideoUrl=r)}updateSnapshotInfo(r){const{snapshotUrl:g,snapshotWidth:u,snapshotHeight:E}=r;xt.isEmpty(g)||(this.content.thumbUrl=this.content.snapshotUrl=g),xt.isEmpty(u)||(this.content.thumbWidth=this.content.snapshotWidth=Number(u)),xt.isEmpty(E)||(this.content.thumbHeight=this.content.snapshotHeight=Number(E))}validateBeforeSend(){if(this[Jr])return{isValid:!0};const r=this.content.remoteVideoUrl!=="";return{isValid:r,error:r?null:{message:"content can not be empty"}}}transformToServerFormat(r){const{isMergerMessage:g=!1}=r||{},u=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:xA,thumbSize:LA,snapshotSize:SA,thumbDownloadFlag:OA,thumbUrl:qA,snapshotUrl:Ie}=u;return{MsgType:this.type,MsgContent:{VideoUrl:xt.removeAuthToUrl(E),VideoFormat:m,VideoSecond:D,VideoSize:M,VideoDownloadFlag:T,VideoUUID:P,ThumbUUID:W,ThumbFormat:oA,ThumbWidth:EA,SnapshotWidth:wA,ThumbHeight:kA,SnapshotHeight:xA,ThumbSize:LA,SnapshotSize:SA,ThumbDownloadFlag:OA,ThumbUrl:xt.removeAuthToUrl(qA),SnapshotUrl:xt.removeAuthToUrl(Ie)}}}}di=Jr;var ts,mi=new class{constructor(){this._messageOptionsMap=new Map}init(s){var r;this._core=s;const{notificationCenter:g,helper:u,InnerEvent:E,message:m}=s;u.registerApi({apiName:"createVideoMessage",context:this}),u.registerExperimentalAPI("createVideoMessage",this,"createCustomUploadVideoMessage"),(r=m?.messageFactory)===null||r===void 0||r.registerElementClass(Ol,xo),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createVideoMessage(s){var r,g,u;try{const E=this._processVideo(s);s.payload.file=E;const m=(r=this._core.store.get("login"))===null||r===void 0?void 0:r.userId,D=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:m})),M={videoFormat:E.videoFile.type,videoSecond:lr(E.videoFile.second,0),videoSize:E.videoFile.size,remoteVideoUrl:"",videoUrl:E.videoFile.url,videoUUID:xt.generateUUID(E.videoFile),thumbUUID:xt.generateUUID(E.videoFile,"jpg"),thumbWidth:E.width||200,thumbHeight:E.height||200,thumbUrl:E.thumbUrl,thumbSize:E.thumbSize,thumbFormat:"jpg"},T=new xo(M);return D.setElement(T),this._messageOptionsMap.set(D.clientSequence,s),D}catch(E){throw E}}createCustomUploadVideoMessage(s){var r,g,u;try{const{store:E,message:m}=this._core;this._validateCustomUploadVideoMessage(s);const D=(r=E.get("login"))===null||r===void 0?void 0:r.userId,{videoUrl:M,videoUuid:T,duration:P,snapshotUrl:W,snapshotUuid:oA,videoFileSize:EA,videoType:wA,snapshotWidth:kA,snapshotHeight:xA,snapshotFileSize:LA,snapshotType:SA="jpg"}=((g=s?.payload)===null||g===void 0?void 0:g.file)||{},OA=(u=m.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:D})),qA=new xo({videoFormat:wA,videoSecond:P||0,videoSize:EA,remoteVideoUrl:M,videoUrl:M,videoUUID:T,thumbUUID:oA,thumbWidth:kA||200,thumbHeight:xA||200,thumbUrl:W,thumbSize:LA,thumbFormat:SA,isCustomUpload:!0});return OA.setElement(qA),this._messageOptionsMap.set(OA.clientSequence,s),OA}catch(E){throw E}}upload(s){return mA(this,void 0,void 0,function*(){const r=s.getElements()[0],{file:g}=this._messageOptionsMap.get(s.clientSequence).payload;this._validateBeforeUploadVideo(g);const u=yield this._performVideoUpload(r,s,g),{location:E,snapshotInfo:m}=u,D=xt.addAuthToUrl(E);return r.updateVideoUrl(D),xt.isEmpty(m)||r.updateSnapshotInfo(m),s})}_validateBeforeUploadVideo(s){const{helper:{ChatError:r}}=this._core,g=X(Ba)||104857600;if(s.videoFile.size>g)throw new r({code:Pi});if(s.videoFile.size===0)throw new r({code:Ht});if(Xi.indexOf(s.videoFile.type)===-1)throw new r({code:co})}_validateCustomUploadVideoMessage(s){var r;const{utils:{isEmpty:g,isNumber:u}}=this._core,{videoUrl:E,videoUuid:m,duration:D,snapshotUrl:M,snapshotUuid:T}=((r=s?.payload)===null||r===void 0?void 0:r.file)||{};if(g(E)||g(m)||!u(D)||g(M)||g(T))throw new Error("Invalid video message options: missing required fields (videoUrl, videoUuid, duration, snapshotUrl, snapshotUuid)")}_performVideoUpload(s,r,g){return mA(this,void 0,void 0,function*(){const{to:u}=r,E={uploadFileType:Ba,file:g,to:u,message:r,onProgress:M=>{var T,P;s.updatePercent(M),(P=(T=this._messageOptionsMap.get(r.clientSequence))===null||T===void 0?void 0:T.onProgress)===null||P===void 0||P.call(T,M)}},{response:m,uploadOptions:D}=yield K.uploadToCOS(E);return{snapshotInfo:yield this._getSnapshotInfoByUrl(D.requestSnapshotUrl),location:m.location}})}_processVideo(s){var r,g;try{const{ChatError:u}=(r=this._core)===null||r===void 0?void 0:r.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=xt.extractFileFromInput(D);if(!T)throw new u({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});D=T,M=this._processWebVideoFile(D)}return D.videoFile=M,D.thumbUrl="",D.thumbSize=0,D}catch(u){throw console.warn(`${ha} _processFile error:`,u),u}}_processMiniVideoFile(s){const{utils:{IN_UNI_NATIVE_APP:r},helper:{ChatError:g}}=this._core;if(gl(s))throw new g({message:"FileUnsupportedInMiniApp"});Array.isArray(s.tempFiles)&&(s=s.tempFiles[0]);let u=s.tempFilePath.slice(s.tempFilePath.lastIndexOf(".")+1).toLowerCase();return r&&(u=s.fileType||u),{url:s.tempFilePath,name:s.tempFilePath.slice(s.tempFilePath.lastIndexOf("/")+1),size:s.size||1,second:s.duration||0,type:u}}_processWebVideoFile(s){const{name:r,size:g=1,duration:u=0,type:E}=s,m=E.split("/")[1];return{url:window.URL.createObjectURL(s),name:r,size:g,second:u,type:m}}_getSnapshotInfoByUrl(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r}=this._core;try{r.debug("_getSnapshotInfoByUrl",`${ha} _getSnapshotInfoByUrl url:${s}`);const g={version:1,platform:xt.getPlatform(),cover_name:Ig(Lr(99999)),snapshot_url:s},u=yield function(T,P){return mA(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}=u||{};if(r.debug("_getSnapshotInfoByUrl",`${ha} _getSnapshotInfoByUrl OK snapshotUrl:${E}`),xt.isEmpty(E))return{};const m=xt.addAuthToUrl(E),{width:D=0,height:M=0}=yield xt.probeImageWidthHeight(m);return{snapshotUrl:m,snapshotWidth:D,snapshotHeight:M}}catch(g){throw g}})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:r}=this._core;s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this)}};class zi{constructor(r){this.uploadProgress=0,this.type=Fg,this[ts]=!1,this[Jr]=r.isCustomUpload||!1,this.content={downloadFlag:2,second:r.second,size:r.size,url:xt.generateURL(r.url,{needAddAuthToUrl:!this[Jr]}),remoteAudioUrl:xt.addAuthToUrl(r.url||""),uuid:r.uuid}}static parseServerPushElement(r){const{MsgContent:g}=r,{Url:u,Download_Flag:E,Second:m,Size:D,UUID:M}=g;return new zi({url:u,downloadFlag:E,second:m,size:D,uuid:M})}updatePercent(r){this.uploadProgress=Math.min(r,1)}updateAudioUrl(r){this.content.remoteAudioUrl=r}validateBeforeSend(){if(this[Jr])return{isValid:!0};const r=this.content.remoteAudioUrl!=="";return{isValid:r,error:r?null:{message:"content can not be empty"}}}transformToServerFormat(r){const{isMergerMessage:g=!1}=r||{},u=g?this.payload:this.content,{uuid:E,downloadFlag:m,remoteAudioUrl:D,size:M,second:T}=u;return{MsgType:this.type,MsgContent:{Url:xt.removeAuthToUrl(D),Download_Flag:m,Second:T,Size:M,UUID:E}}}}ts=Jr;const Ws=2108,Ne=2300,Tt=2301;var FA=new class{constructor(){this._messageOptionsMap=new Map}init(s){var r;this._core=s;const{notificationCenter:g,helper:u,InnerEvent:E,message:m}=s;u.registerApi({apiName:"createAudioMessage",context:this}),u.registerExperimentalAPI("createAudioMessage",this,"createCustomUploadAudioMessage"),(r=m?.messageFactory)===null||r===void 0||r.registerElementClass(Fg,zi),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createAudioMessage(s){var r,g,u;try{let{file:E}=s.payload;E=this._processAudioFile(s.payload.file),s.payload.file=E;const m=(r=this._core.store.get("login"))===null||r===void 0?void 0:r.userId,D=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:m})),M={second:Math.max(1,Math.round((E.duration||E.second)/1e3)),size:E.fileSize||E.size||1,url:E.tempFilePath||E.uri||E.url,uuid:xt.generateUUID(E)},T=new zi(M);return D.setElement(T),this._messageOptionsMap.set(D.clientSequence,s),D}catch(E){throw E}}createCustomUploadAudioMessage(s){var r,g,u;try{this._validateCustomUploadOptions(s);const{store:E,message:m}=this._core,D=(r=E.get("login"))===null||r===void 0?void 0:r.userId,{url:M,uuid:T,duration:P,fileSize:W}=((g=s?.payload)===null||g===void 0?void 0:g.file)||{},oA=(u=m.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:D})),EA=new zi({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 mA(this,void 0,void 0,function*(){const{ssoLog:r,utils:{safeStringify:g}}=this._core;r.debug("upload",`${ha} uploadAudio message:${g(s)}`);const{file:u}=this._messageOptionsMap.get(s.clientSequence).payload;this._validateBeforeUploadAudio(u);const E=s.getElements()[0],m=yield this._performAudioUpload(E,s,u),D=xt.addAuthToUrl(m?.location);return E.updateAudioUrl(D),s})}_validateBeforeUploadAudio(s){const{helper:{ChatError:r},store:g}=this._core;if(!s)throw new r({code:Ne});const u=X(cl)||20971520;if(s.size>u)throw new r({code:Tt});if(s.size===0)throw new r({code:Ws})}_performAudioUpload(s,r,g){return mA(this,void 0,void 0,function*(){const{to:u}=r,E={uploadFileType:cl,file:g,to:u,message:r,onProgress:D=>{var M,T;s.updatePercent(D),(T=(M=this._messageOptionsMap.get(r.clientSequence))===null||M===void 0?void 0:M.onProgress)===null||T===void 0||T.call(M,D)}},{response:m}=yield K.uploadToCOS(E);return m})}_processAudioFile(s){var r;const{IN_MINI_APP:g,IN_BROWSER:u}=(r=this._core)===null||r===void 0?void 0:r.utils;return g?this._processMiniFile(s):u?this._processWebFile(s):void 0}_processMiniFile(s){return{url:s.tempFilePath,name:s.tempFilePath.slice(s.tempFilePath.lastIndexOf("/")+1),size:s.fileSize,second:s.duration,type:s.tempFilePath.slice(s.tempFilePath.lastIndexOf(".")+1).toLowerCase()}}_processWebFile(s){if(s.tempFilePath||s.uri)return s;const r=URL.createObjectURL(s);return s.tempFilePath=r,s}_validateCustomUploadOptions(s){var r;const{utils:{isEmpty:g}}=this._core,{url:u,uuid:E,duration:m}=((r=s?.payload)===null||r===void 0?void 0:r.file)||{};if(g(u)||g(E)||g(m))throw new Error("Invalid audio message options")}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:r}=this._core;s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this)}};const Ai={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:Ai,createAudioMessage:Ai,createVideoMessage:Ai,createFileMessage:Ai},ii={createImageMessage:!0,createAudioMessage:!0,createVideoMessage:!0,createFileMessage:!0},us={[ic]:rA,[Ya]:Ft,[Ol]:mi,[Fg]:FA};var wi=new class{constructor(){this.name="RichMediaMessage"}install(s){this._core=s;const{constants:{OuterConstant:{MSG_AUDIO:r,MSG_FILE:g,MSG_IMAGE:u,MSG_VIDEO:E}}}=s;v.init(s),rA.init(s),Ft.init(s),mi.init(s),FA.init(s),K.init(s),xt.init(s),s.helper.registerApi({apiName:"sendMessage",context:this,matcher:m=>[r,g,u,E].includes(m[0].type)}),s.helper.registerValidateConfig({auth:ii,params:En})}sendMessage(s,r){return mA(this,void 0,void 0,function*(){var g,u,E;try{return this._isCustomUpload(s)||(yield this._upload(s)),yield(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageSender)===null||E===void 0?void 0:E.sendMessage(s,r)}catch(m){throw m}})}_upload(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r,utils:{safeStringify:g}}=this._core;if(r.debug("_upload",` uploadFile message:${g(s)}`),s._relayFlag!==!0)try{const u=us[s.type];u&&(yield u.upload(s),r.info("_upload",` type:${s.type}`))}catch(u){throw s.status=su.FAIL,u instanceof Error&&(u.data={message:s}),this._core.message.messageDataHandler.storeConversationMessage(s),u}})}_isCustomUpload(s){var r,g;return((g=(r=s._elements)===null||r===void 0?void 0:r[0])===null||g===void 0?void 0:g[Jr])===!0}};const Bo=new class{init(s){this.core=s}};class Bt{constructor(r){this.conversationID=r.conversationID||"",this.unreadCount=r.unreadCount||0,this.type=r.type||"",this.lastMessage=Bo.core.common.buildLastMessage(r.lastMessage),this.peerReadTime=r.peerReadTime||0,this.groupAtInfoList=[],this.remark=r.remark||"",this.isPinned=r.isPinned||!1,this.messageRemindType=r.messageRemindType,this.markList=r.markList||[],this.customData=r.customData||"",this.conversationGroupList=r.conversationGroupList||[],this.draftText=r.draftText||"",this.userProfile=r.userProfile,this.groupProfile=r.groupProfile,this.subType=r.subType||"",this._isInfoCompleted=!1,this._init()}_init(){var r;const{core:{OuterConstant:g,utils:{isUndefined:u}}}=Bo;u(this.userProfile)&&this.type===g.CONV_C2C?this.userProfile={userID:this.conversationID.replace(g.CONV_C2C,"")}:this.type===g.CONV_GROUP&&(!this.subType&&(!((r=this.groupProfile)===null||r===void 0)&&r.type)&&(this.subType=this.groupProfile.type),u(this.groupProfile)&&(this.groupProfile={groupID:this.conversationID.replace(g.CONV_GROUP,""),selfInfo:{},lastMessage:{},type:this.subType}))}updateUnreadCount(r){var g;const{core:{OuterConstant:u,utils:{isUndefined:E},store:m}}=Bo,{nextUnreadCount:D,isFromGetConversations:M,isUnreadC2CMessage:T}=r;if(E(D))return;if(this.subType===u.GRP_AVCHATROOM)return void(this.unreadCount=0);if(M&&this.type===u.CONV_GROUP)return void(this.unreadCount=D);if(T&&this.type===u.CONV_C2C)return void(this.unreadCount=D);const P=((g=m.get("cloudConfig"))===null||g===void 0?void 0:g.support_unread_count_for_meeting)==="1";this.subType!==u.GRP_MEETING||P?this.unreadCount+=D:this.unreadCount=0}updateLastMessage(r){this.lastMessage=Bo.core.common.buildLastMessage(r)}reduceUnreadCount(){return this.unreadCount>=1&&(this.unreadCount-=1,!0)}isLastMessageRevoked(r){const{core:{OuterConstant:g}}=Bo,{sequence:u,time:E}=r;return this.type===g.CONV_C2C&&u===this.lastMessage.lastSequence&&E===this.lastMessage.lastTime||this.type===g.CONV_GROUP&&u===this.lastMessage.lastSequence}setLastMessageRevoked(r){this.lastMessage.isRevoked=r}setLastMessageRevoker(r){this.lastMessage.revoker=r}setDraftText(r){this.draftText=r}updateGroupAtInfoList(r){const{core:{common:{updateGroupAtInfo:g}}}=Bo;g(r,this.groupAtInfoList)}clearGroupAtInfoList(){this.groupAtInfoList.length=0}getProfileCompleted(){return this._isInfoCompleted}setProfileCompleted(){this._isInfoCompleted=!0}}const mt=s=>{const{core:{OuterConstant:r,utils:{isString:g}}}=Bo;return g(s)&&s.slice(0,3)===r.CONV_C2C},ug=s=>{const{core:{OuterConstant:r,utils:{isString:g}}}=Bo;return g(s)&&s.slice(0,5)===r.CONV_GROUP},Ls=s=>{const{core:{OuterConstant:r,utils:{isString:g}}}=Bo;return g(s)&&s===r.CONV_SYSTEM};function Zi(s){const{OuterConstant:r}=Bo.core;let g="";return s===0?g=r.MSG_REMIND_ACPT_AND_NOTE:s===1?g=r.MSG_REMIND_DISCARD:s===2?g=r.MSG_REMIND_ACPT_NOT_NOTE:s===3&&(g=r.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),g}function Hr(s){const{OuterConstant:r}=Bo.core;let g;return s.startsWith(r.CONV_C2C)&&(g=s.replace(r.CONV_C2C,"")),g==="@TLS#ERROR"||g==="@TLS#NOT_FOUND"}function oc(s,r){const{helper:g}=Bo.core,u=new g.ChatError({functionName:s,code:r?.errorCode||r?.code,message:r?.errorInfo||r?.message});throw console.error(`${s} fail:`,u),u}var os,ca;(function(s){s[s.OFF=0]="OFF",s[s.ON=1]="ON"})(os||(os={})),function(s){s[s.ONLY_CONVERSATIONID=1]="ONLY_CONVERSATIONID"}(ca||(ca={}));var Qa;(function(s){s[s.CONV_NOT_FOUND=2500]="CONV_NOT_FOUND",s[s.USER_OR_GRP_NOT_FOUND=2501]="USER_OR_GRP_NOT_FOUND",s[s.CONV_UN_RECORDED_TYPE=2502]="CONV_UN_RECORDED_TYPE"})(Qa||(Qa={}));const ta=0,H=1;var QA=new class{constructor(){this._name="GetC2CMessageRemindType"}init(s){this._core=s}get(s){return mA(this,void 0,void 0,function*(){try{const{common:r}=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:r.getCurrentUserID(),userIDList:s},this._core),{MuteNotificationsList:u=[]}=g||{};u.forEach(E=>{const{Peer_Account:m,MuteNotifications:D}=E,M=`${this._core.OuterConstant.CONV_C2C}${m}`,T=Zi(D);NA.patchMessageRemindType([M],T)})}catch(r){console.error(`${this._name}.get fail:`,r)}})}},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 r=yield function(u,E){return mA(this,void 0,void 0,function*(){const{groupIDList:m,responseFilter:D}=u,M={GroupIdList:m,ResponseFilter:D};return E.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_self_member_info",data:M})})}({groupIDList:s,responseFilter:{MemberInfoFilter:["MsgFlag"]}},this._core),{GroupInfo:g=[]}=r||{};g.forEach(u=>{var E;const{GroupId:m,MemberList:D}=u,M=((E=D[0])===null||E===void 0?void 0:E.MsgFlag)||"",T=`${this._core.OuterConstant.CONV_GROUP}${m}`;NA.patchMessageRemindType([T],M)})}catch(r){console.error(`${this._name}.get fail:`,r)}})}},NA=new class{constructor(){this._name="ConversationDataHandler",this._totalUnreadCount=0,this._groupAtTipsList=[]}init(s){this._core=s;const{helper:r,notificationCenter:g,appStore:{conversationStore:u},constants:{WORKFLOW_NAME:E,WORKFLOW_STEP:m},InnerEvent:{SYNC_CONVERSATION_LIST:D,MESSAGE_PUSH:M,NEW_MESSAGE:T,MESSAGE_DELETED:P,MESSAGE_REVOKED:W,MESSAGE_MODIFIED:oA,CONVERSATION_UPDATED:EA,LOGOUT:wA,DESTROY:kA},InnerEventSubType:{C2C_MESSAGE_PEER_READ:xA}}=s;this._conversationStore=u,r.registerWorkflowStep(E.SYNC_SERVER_INFO_AFTER_LOGIN,m.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),r.registerWorkflowStep(E.SYNC_SERVER_INFO_AFTER_LOGIN,m.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,this._handleGroupListSyncFinished,this),r.registerWorkflowStep(E.RECEIVE_C2C_NEW_MESSAGE,m.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),r.registerWorkflowStep(E.RECEIVE_C2C_NEW_MESSAGE,m.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),r.registerWorkflowStep(E.RECEIVE_GROUP_NEW_MESSAGE,m.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),r.registerWorkflowStep(E.SYNC_SERVER_INFO_AFTER_RE_ONLINE,m.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),r.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,xA,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:r}}=this._core,{conversationUpdateFieldList:g=[],groupTipList:u=[],isUnreadC2CMessage:E}=s.result[r.UNREAD_MESSAGE_SYNC]||{};let m=!1;g.forEach(D=>{const{conversationID:M,unreadCount:T}=D,P=this.getLocalConversation(M);P&&P.unreadCount!==T&&(P.updateUnreadCount({nextUnreadCount:T,isUnreadC2CMessage:E}),m=!0)}),m&&this.emitConversationListUpdate(),this._handleGroupAtTipsSynced(u)}_handleGroupAtTipsSynced(s){var r;for(let g=0;g0&&this._handleNewGroupAtTips({GroupTips:M._groupAtInfoList}),m=!0}m&&this.emitConversationListUpdate()}_handleNewMessage(s){const{conversationUpdateFieldList:r=[],isInstantMessage:g=!0,isUnreadC2CMessage:u=!1,updateUnreadCount:E=!0}=s.result||{};if(r.length===0)return;const{common:{isTopic:m}}=this._core;m(r[0].conversationID)||(this.updateLocalConversationList({conversationUpdateFieldList:r,isInstantMessage:g,isUnreadC2CMessage:u,isFromGetConversations:!1,updateUnreadCount:E}),r.filter(D=>this._isConversationNeedShow(D.conversationID)).length>0&&this.emitConversationListUpdate())}_handleNewGroupAtTips(s){const{GroupTips:r=[]}=s;r.forEach(g=>{const{GroupAtTips:u,MsgBody:E,MsgRandom:m,ClientSeq:D}=g;let M={};u?M=this._convertGroupAtTipsKey(u):E?M=Object.assign({},this._convertGroupAtTipsKey(E)):g.groupAtType&&(M=Object.assign({},g)),M.__random=m,M.__sequence=D,this._groupAtTipsList.push(M)}),console.log(`${this._name}._handleNewGroupAtTips groupAtTipsList: ${JSON.stringify(this._groupAtTipsList)}`),this._updateGroupAtInfoList()}_convertGroupAtTipsKey(s){const{From_Account:r,GroupId:g,MsgSeq:u,GroupAtType:E}=s;return{from:r,groupID:g,sequence:u,groupAtType:E}}_updateGroupAtInfoList(){if(this._groupAtTipsList.length===0)return;const{common:s,OuterConstant:r}=this._core,g=s.getCurrentUserID();let u=!1;this._groupAtTipsList.forEach(E=>{const{groupID:m,from:D}=E;if(D!==g){const M=this.getLocalConversation(`${r.CONV_GROUP}${m}`);M&&(M.updateGroupAtInfoList(E),u=!0)}}),u&&this.emitConversationListUpdate(),this._groupAtTipsList.length=0}_handleMessageDeleted(s){var r,g;console.log(`${this._name}._handleMessageDeleted, conversationID:`,s);const{message:{messageDataHandler:u},OuterConstant:E}=this._core,m=u?.getLocalMessageList(s)||[];let D={};for(let P=(m.length||0)-1;P>=0;P--)if(!m[P].isDeleted&&m[P]._isExcludedFromLastMessage!==!0){D=m[P];break}const M=this.getLocalConversation(s);if(!M)return;let T=!1;M.lastMessage.lastSequence===D.sequence&&M.lastMessage.lastTime===D.time||(!((g=(r=this._core)===null||r===void 0?void 0:r.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:r=[],updateUnreadCount:g=!0}=s;if(console.log(`${this._name}._handleMessageRevoked messageList:${r.length}`),r.length===0)return;let u=null,E=!1;r.forEach(m=>{u=this.getLocalConversation(m.conversationID),u&&(g&&u.reduceUnreadCount()&&(E=!0),u.isLastMessageRevoked({sequence:m.sequence,time:m.time})&&(u.setLastMessageRevoked(!0),u.setLastMessageRevoker(m.revoker),E=!0))}),E&&this.emitConversationListUpdate()}_handleMessageModified(s){const{utils:{isEmpty:r},common:{getMessagePreviewText:g},ssoLog:u}=this._core;u.debug(`${this._name}._handleMessageModified`,JSON.stringify(s));const{conversationID:E,messageList:m}=s,D=this.getLocalConversation(E);if(r(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:r}=s,{newConversationList:g}=this._getTmpConversationListMapping(s);this._sortConversationList(),r||this._updateNewConversationProfile(g),this._core.ssoLog.debug("updateLocalConversationList",` newConversationList: ${g.length}`)}_getTmpConversationListMapping(s){const{OuterConstant:r}=this._core,{conversationUpdateFieldList:g,isFromGetConversations:u,isInstantMessage:E,isUnreadC2CMessage:m=!1,updateUnreadCount:D}=s,M=[],T=g?.length;for(let P=0;P{M[1].isPinned===!0?s(M[1].lastMessage.lastTime)?u.push(M):g.push(M):s(M[1].lastMessage.lastTime)?m.push(M):E.push(M)});const D=g.sort((M,T)=>T[1].lastMessage.lastTime-M[1].lastMessage.lastTime).concat(u).concat(E.sort((M,T)=>T[1].lastMessage.lastTime-M[1].lastMessage.lastTime)).concat(m);this._updateConversationMapFromList(D)}_updateNewConversationProfile(s){if(s.length===0)return;const r=[],g=[],{OuterConstant:{CONV_GROUP:u,CONV_C2C:E}}=this._core;s.forEach(m=>{const{conversationID:D,type:M}=m;if(M===E){const T=D.replace(E,"");r.push(T)}else if(M===u){const T=D.replace(u,"");g.push(T)}}),r.length>0&&this._updateC2CConversation(r),g.length>0&&this._updateGroupConversation(g)}_updateC2CConversation(s){var r;const{OuterConstant:{CONV_C2C:g},appStore:{userStore:u},user:E}=this._core;let m=!1;(r=E.userProfile)===null||r===void 0||r.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=u.getFriend(P))===null||T===void 0?void 0:T.remark)||"";W.remark=oA,W.userProfile=M,m=!0}}),m&&this.emitConversationListUpdate()}).catch(D=>{}),QA.get(s)}_updateGroupConversation(s){return mA(this,void 0,void 0,function*(){const{OuterConstant:{CONV_GROUP:r},appStore:{groupStore:g},utils:{safeStringify:u},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(`${r}${M}`);T&&P&&(P.groupProfile=T,D=!0),P&&!P.getProfileCompleted()&&typeof m=="function"&&(yield m({groupID:M}))}))),yA.get(s),D&&this.emitConversationListUpdate()}catch(M){E.debug("_updateGroupConversation",u(M))}})}_handleMessageRead(s){const{OuterConstant:{CONV_C2C:r}}=this._core,{C2cNotifyMsgArray:g=[]}=s||{};g.forEach(u=>{const{To_Account:E,UinPairReadArray:m=[]}=u?.C2cReadedReceipt||{};m?.forEach(D=>{const{LastReadTime:M}=D,T=`${r}${E}`;this._updateConversationReadInfo({conversationID:T,peerReadTime:M}),this._updateMessageListPeerRead({conversationID:T,peerReadTime:M})})})}_updateConversationReadInfo(s){const{appStore:r,utils:{isEmpty:g},common:{getCurrentUserID:u}}=this._core,{conversationID:E,peerReadTime:m}=s,D=r.conversationStore.getConversationMap();if(D.has(E)){const M=D.get(E);M.peerReadTime=m;const T=M?.lastMessage;g(T)||T.fromAccount===u()&&T.lastTime<=m&&!T.isPeerRead&&(T.isPeerRead=!0,r.conversationStore.updateConversation(E,{lastMessage:T}))}}_updateMessageListPeerRead(s){const{notificationCenter:r,OuterEvent:g,message:u}=this._core,{conversationID:E,peerReadTime:m}=s,D=u.messageDataHandler.getLocalMessageList(E),M=u.messageDataHandler.getSparseMessageList(E),T=[];D.forEach(P=>{P.time<=m&&!P.isPeerRead&&P.flow==="out"&&(P.isPeerRead=!0,T.push(P))}),M.forEach(P=>{P.time<=m&&!P.isPeerRead&&P.flow==="out"&&(P.isPeerRead=!0,T.push(P))}),r.emitOuterEvent(g.MESSAGE_READ_BY_PEER,{name:g.MESSAGE_READ_BY_PEER,data:T})}_isConversationNeedShow(s){var r,g;const{OuterConstant:{CONV_GROUP:u,GRP_ROOM:E,GRP_LIVE:m},utils:{isUndefined:D}}=this._core,M=this.getLocalConversation(s);if(D(M))return!0;const T=M.type===u&&((r=M.groupProfile)===null||r===void 0?void 0:r.type)===E,P=M.type===u&&((g=M.groupProfile)===null||g===void 0?void 0:g.type)===m;return!(T||P)}updateUnreadCount(s,r=!0){var g,u;let E=!1;const m=this.getLocalConversation(s),D=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageDataHandler)===null||u===void 0?void 0:u.getLocalMessageList(s);if(!m)return E;const M=m.unreadCount,T=D?.filter(P=>!P.isRead&&!P._onlineOnlyFlag&&!P.isDeleted).length;return console.log(`${this._name}._updateUnreadCount conversationID:${s} currentUnreadCount:${M} newUnreadCount:${T}`),M!==T&&(m.unreadCount=T,E=!0,r===!0&&this.emitConversationListUpdate()),E}emitConversationListUpdate(s=!1){var r,g;s&&this._sortConversationList();const{OuterEvent:{CONVERSATION_LIST_UPDATED:u},conversation:E}=this._core,m=this.getLocalConversationList();this._emitEvent({name:u,data:m,isSyncCompleted:(g=(r=E?.syncConversationHandler)===null||r===void 0?void 0:r.isSyncCompleted)===null||g===void 0?void 0:g.call(r)}),this._emitTotalUnreadCountUpdate()}_emitTotalUnreadCountUpdate(){var s;const r=this.getTotalUnreadMessageCount();this._totalUnreadCount!==r&&(this._core.ssoLog.debug("_emitTotalUnreadCountUpdate",` from ${this._totalUnreadCount} to ${r}`),this._totalUnreadCount=r,this._emitEvent({name:(s=this._core)===null||s===void 0?void 0:s.OuterEvent.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED,data:r}))}_emitEvent(s){var r;(r=this._core)===null||r===void 0||r.notificationCenter.emitOuterEvent(s.name,s)}getTotalUnreadMessageCount(){const{OuterConstant:s,utils:{isEmpty:r}}=this._core,g=this.getLocalConversationList();let u=0;return g.forEach(E=>{E.type!==s.CONV_SYSTEM&&(r(E.messageRemindType)||E.messageRemindType===s.MSG_REMIND_ACPT_AND_NOTE)&&(u+=E.unreadCount)}),u}getLocalConversationList(){return[...this._conversationStore.getConversationMap().values()].filter(s=>this._isConversationNeedShow(s.conversationID))}hasLocalConversation(s){return this._conversationStore.getConversationMap().has(s)}getLocalConversation(s){return this._conversationStore.getConversationMap().get(s)}setLocalConversation(s,r){return this._conversationStore.getConversationMap().set(s,r)}deleteLocalConversation(s){this._conversationStore.getConversationMap().delete(s)}_updateConversationMapFromList(s){this._clearConversationMap();for(const[r,g]of s)this.setLocalConversation(r,g)}_clearConversationMap(){this._conversationStore.getConversationMap().clear()}patchMessageRemindType(s,r){let g=!1;s.forEach(u=>{const E=this.getLocalConversation(u);E?.messageRemindType!==r&&(E.messageRemindType=r,g=!0)}),console.log(`${this._name}.patchMessageRemindType conversationIDList:${s} messageRemindType:${r} hasUpdated:${g}`),g&&this.emitConversationListUpdate()}markMessageAsRead(s){const{message:{messageDataHandler:r}}=this._core,{conversationID:g,lastReadTime:u=0,lastReadSequence:E=0}=s,m=r?.getLocalMessageList(g);if(m.length===0)return;const{length:D}=m;for(let M=D-1;M>=0;M--){const T=m[M],P=u&&T.time>u,W=E&&T.sequence>E;if(!P&&!W){if(T.flow==="in"&&T.isRead)break;T.setIsRead(!0)}}}appendToPinnedConversation(s){const r=[...this._conversationStore.getConversationMap().entries()],g=r.findIndex(u=>u[1].isPinned===!1);r.splice(g,0,[s.conversationID,s]),this._updateConversationMapFromList(r),this.emitConversationListUpdate()}_reset(){this._clearConversationMap(),this._totalUnreadCount=0,this._groupAtTipsList=[]}_dispose(){const{notificationCenter:s,InnerEvent:{NEW_MESSAGE:r,MESSAGE_DELETED:g,MESSAGE_REVOKED:u,MESSAGE_MODIFIED:E,CONVERSATION_UPDATED:m,LOGOUT:D,DESTROY:M,SYNC_CONVERSATION_LIST:T}}=this._core,{InnerEventSubType:{GROUP_AT_TIPS:P}}=s;s.unSubscribeInnerEvent(r,this._handleNewMessage,this),s.unSubscribeInnerEvent(r,P,this._handleNewGroupAtTips,this),s.unSubscribeInnerEvent(g,this._handleMessageDeleted,this),s.unSubscribeInnerEvent(u,this._handleMessageRevoked,this),s.unSubscribeInnerEvent(E,this._handleMessageModified,this),s.unSubscribeInnerEvent(m,this._handleConversationUpdated,this),s.unSubscribeInnerEvent(T,this._handleConversationSynced,this),s.unSubscribeInnerEvent(D,this._reset,this),s.unSubscribeInnerEvent(M,this._dispose,this)}},XA=new class{constructor(){this._name="GetConversationList"}init(s){this._core=s;const{helper:r}=s;r.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:r,isArray:g,isPlainObject:u}}=this._core;if(r(s))return NA.getLocalConversationList();if(g(s))return s.length===0?[]:NA.getLocalConversationList().filter(E=>s.includes(E.conversationID));if(u(s)){const{type:E,markType:m,groupName:D,hasUnreadCount:M,hasGroupAtInfo:T}=s;return NA.getLocalConversationList().filter(P=>this._filterType(P,E)&&this._filterMarkType(P,m)&&this._filterGroupName(P,D)&&this._filterUnreadCount(P,M)&&this._filterGroupAtInfo(P,T))}return[]}_filterType(s,r){const{OuterConstant:g}=this._core;return r!==g.CONV_C2C&&r!==g.CONV_GROUP||s.type===r}_filterGroupName(s,r){const{utils:{isString:g}}=this._core;return!g(r)||(r===""?s.conversationGroupList.length===0:s.conversationGroupList.includes(r))}_filterMarkType(s,r){const{utils:{isNumber:g}}=this._core;return!g(r)||(r===0?s.markList.length===0:s.markList.includes(r))}_filterUnreadCount(s,r){let g=!0;return r===!0?g=s.unreadCount>=1:r===!1&&(g=s.unreadCount===0),g}_filterGroupAtInfo(s,r){let g=!0;return r===!0?g=s.groupAtInfoList.length>=1:r===!1&&(g=s.groupAtInfoList.length===0),g}},Te=new class{constructor(){this._name="GetConversationProfile"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"getConversationProfile",context:this})}getConversationProfile(s){return mA(this,void 0,void 0,function*(){const{OuterConstant:{CONV_C2C:r,CONV_GROUP:g,GRP_AVCHATROOM:u},appStore:{groupStore:E},utils:{isEmpty:m}}=this._core,D={code:0,data:{}};let M=NA.getLocalConversation(s);if(Ls(s))return D.data.conversation=M,D;let T=!1;const P=mt(s)?r:g;if(m(M)&&(T=!0,M=new Bt({conversationID:s,type:P})),console.log(`${this._name}.getConversationProfile conversationID:${s} isNewConversation:${T}`),D.data.conversation=M,M?.getProfileCompleted())return D;if(P===r){const W=s.replace(r,"");yield this._handleC2CConversation(M,W),T&&(yield QA.get([W]))}if(P===g){const W=s.replace(g,"");if(!E.getGroup(W))return D;yield this._handleGroupConversation(M,W),T&&M.groupProfile.type!==u&&(yield yA.get([W]))}return D})}_handleC2CConversation(s,r){return mA(this,void 0,void 0,function*(){var g,u;const{user:E,helper:m,utils:{isEmpty:D},appStore:{conversationStore:M,userStore:T}}=this._core,{conversationID:P}=s,W=yield(g=E.userProfile)===null||g===void 0?void 0:g.getUserProfile({userIDList:[r]});if(W?.data.length===0)throw new m.ChatError({code:Qa.USER_OR_GRP_NOT_FOUND});s.userProfile=W?.data[0];const oA=(u=T.getFriend(r))===null||u===void 0?void 0:u.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,r){return mA(this,void 0,void 0,function*(){const{apiMap:{getGroupProfile:g},appStore:{conversationStore:u}}=this._core,{conversationID:E}=s,m=yield g({groupID:r});s.groupProfile=m?.data.group,s.setProfileCompleted();const D=NA.hasLocalConversation(E);console.log(`${this._name}._handleGroupConversation conversationID:${E} hasLocalConversation: ${D}`),D?u.updateConversation(E,s):NA.appendToPinnedConversation(s)})}},de=new class{init(s){const{helper:r}=s;r.registerApi({apiName:"getTotalUnreadMessageCount",context:this})}getTotalUnreadMessageCount(){return NA.getTotalUnreadMessageCount()}},ke=new class{constructor(){this._serverGroupConversationLastReadSeqMap=new Map,this._name="SetMessageRead"}init(s){this._core=s;const{helper:r,common:{isTopic:g},notificationCenter:u,InnerEvent:{MESSAGE_PUSH:E},InnerEventSubType:{ALL_MESSAGE_READ:m}}=s;r.registerApi({apiName:"setMessageRead",context:this,matcher:D=>!g(D[0].conversationID)}),r.registerApi({apiName:"setAllMessageRead",context:this}),u.subscribeInnerEvent(E,m,this._handleAllMessageRead,this)}handleC2CMessageReadSync(s){const{helper:{isEmpty:r},OuterConstant:g}=this._core;s.forEach(u=>{const{ReadC2cMsgNotify:E}=u;if(!r(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:r,utils:{isUndefined:g}}=this._core;s.forEach(u=>{const{GroupReadInfoArray:E}=u.MsgBody;g(E)||E.forEach(m=>{const{GroupId:D,LastReadMsgSeq:M}=m,T=`${r.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 r,g;const{OuterConstant:u}=this._core,{conversationID:E}=s,m={code:0,data:{}},D=NA.getLocalConversation(E);let M=`${this._name}.setMessageRead conversationID:${E} unreadCount:${D?.unreadCount||0}`;if(m.successLog={message:M},!D)return m;const T=!(!((g=(r=this._core)===null||r===void 0?void 0:r.helper)===null||g===void 0)&&g.isEmpty(D.groupAtInfoList));if(D.type===u.CONV_GROUP&&T&&this._deleteGroupAtTips(E),D.unreadCount===0)return m;const{helper:{ChatError:P}}=this._core;try{if(D.type===u.CONV_C2C){const W=this._getLocalMessageMaxTime(D);M+=`lastMessageTime:${W}`,yield this._setC2CMessageRead(E,W)}if(D.type===u.CONV_GROUP){const W=this._getLocalMessageMaxSequence(D);M+=`lastMessageSequence:${W}`,yield this._setGroupMessageRead(E,W)}}catch(W){const{errorCode:oA,errorInfo:EA}=W;throw new P({functionName:"setMessageRead",code:oA,message:EA,moreMessage:M})}return D.type===u.CONV_SYSTEM&&(D.unreadCount=0),NA.emitConversationListUpdate(),Object.assign(Object.assign({},m),{successLog:{message:M}})})}setAllMessageRead(){return mA(this,arguments,void 0,function*(s={}){const{OuterConstant:{READ_ALL_MSG:r},utils:{safeStringify:g}}=this._core;let u=`scope:${s.scope}`;s.scope||(s.scope=r);const{scope:E}=s,m=this._generateSetAllMessageReadRequestData(E);if(m.allC2CMessageReadStatus===ta&&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 Bo.core.common.buildAndSendPacket({servcmd:"openim.read_all_unread_msg",data:W})})}(m);if(D){const{GroupReadInfoArray:M,C2CReadAllMsg:T}=D,P=this._parseGroupReadInfo(M);this._updateAllConversationReadStatus({allC2CMessageReadStatus:T})>0&&NA.emitConversationListUpdate(),u+=`failureGroupInfoList:${g(P)}`}return{code:0,successLog:{message:u}}}catch(D){const{errorCode:M}=D;throw new this._core.helper.ChatError({functionName:"setAllMessageRead",code:M,moreMessage:u})}})}_handleAllMessageRead(s){const{GroupReadInfoArray:r,C2CReadAllMsg:g}=s;this._parseGroupReadInfo(r),this._updateAllConversationReadStatus({allC2CMessageReadStatus:g})>0&&NA.emitConversationListUpdate()}_updateAllConversationReadStatus(s){const{OuterConstant:{CONV_C2C:r,CONV_GROUP:g},appStore:u}=this._core,E=u.conversationStore.getConversationMap(),{allC2CMessageReadStatus:m}=s;let D=0;for(const[M,T]of E)if(T.unreadCount>=1){if(m===H&&T.type===r){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:r,CONV_GROUP:g,READ_ALL_C2C_MSG:u},appStore:E}=this._core,m={allC2CMessageReadStatus:ta,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===r&&m.allC2CMessageReadStatus===ta){if(m.allC2CMessageReadStatus=H,s===u)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:r}}=this._core,g=[];return s?.forEach(u=>{const{GroupId:E,MsgSeq:m,RetCode:D,LastReadMsgSeq:M}=u;r(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 r=NA.getLocalConversation(s);if(!r)return;const g=r?.groupAtInfoList||[];if(g.length!==0)try{const{common:{getCurrentUserID:u,isCommunity:E},OuterConstant:{CONV_GROUP:m,CONV_AT_ALL:D}}=this._core;let M=[...g];if(E({groupID:s.replace(m,"")})&&(M=g.filter(P=>!P.atTypeArray.includes(D)),M.length===0))return void this._clearGroupAtInfoList(s,!1);const T=M.map(P=>({From_Account:P.from,To_Account:u(),MsgSeq:P.__sequence,MsgRandom:P.__random,GroupId:P.groupID}));yield function(P,W){return mA(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(u){console.error(`${this._name}._deleteGroupAtTips fail:`,u)}})}_clearGroupAtInfoList(s,r=!0){const g=NA.getLocalConversation(s);g&&(g.groupAtInfoList.length>0&&(g.clearGroupAtInfoList(),console.log(`${this._name}._clearGroupAtInfoList conversationID:${s} needEmitConversationUpdate:${r}`)),r&&NA.emitConversationListUpdate())}_getLocalMessageMaxTime(s){var r;const{conversationID:g}=s,u=this._core.message.messageDataHandler.getLocalMessageList(g),E=Math.max(...u.map(D=>D.time));let m=((r=s?.lastMessage)===null||r===void 0?void 0:r.lastTime)||0;return E>m&&(console.log(`${this._name}._getLocalMessageMaxTime update lastMessageTime from ${m} to ${E}`),m=E),m}_getLocalMessageMaxSequence(s){var r;const{conversationID:g}=s,u=this._core.message.messageDataHandler.getLocalMessageList(g),E=Math.max(...u.map(D=>D.sequence));let m=((r=s?.lastMessage)===null||r===void 0?void 0:r.lastSequence)||0;return E>m&&(console.log(`${this._name}._getLocalMessageMaxSequence update lastMessageSequence from ${m} to ${E}`),m=E),m}_setC2CMessageRead(s,r){return mA(this,void 0,void 0,function*(){try{yield function(g,u){return mA(this,void 0,void 0,function*(){return u.common.buildAndSendPacket({servcmd:"openim.msgreaded",data:g})})}({C2CMsgReaded:{Cookie:"",C2CMsgReadedItem:[{To_Account:s.replace("C2C",""),LastedMsgTime:r,Receipt:1}]}},this._core),console.log(`${this._name}._setC2CMessageRead ok, lastReadTime:${r}`),NA.markMessageAsRead({conversationID:s,lastReadTime:r}),NA.updateUnreadCount(s)}catch(g){throw console.warn(`${this._name}._setC2CMessageRead fail:`,g),g}})}_setGroupMessageRead(s,r){return mA(this,void 0,void 0,function*(){try{yield function(g,u){return mA(this,void 0,void 0,function*(){const{groupID:E,lastMessageSequence:m}=g,D={GroupId:E,MsgReadedSeq:m};return u.common.buildAndSendPacket({servcmd:"group_open_http_svc.msg_read_report",data:D})})}({groupID:s.replace("GROUP",""),lastMessageSequence:r},this._core),console.log(`${this._name}._setGroupMessageRead ok, lastReadSequence:${r}`),NA.markMessageAsRead({conversationID:s,lastReadSequence:r}),NA.updateUnreadCount(s)}catch(g){throw console.warn(`${this._name}._setGroupMessageRead fail:`,g),g}})}_shouldSetAllMessageRead(s){const{OuterConstant:{CONV_C2C:r,CONV_GROUP:g,READ_ALL_MSG:u,READ_ALL_C2C_MSG:E,READ_ALL_GROUP_MSG:m}}=this._core,{type:D,scope:M,unreadCount:T}=s;return!(T<=0)&&(!(D!==r||![u,E].includes(M))||!(D!==g||![u,m].includes(M)))}},ue=new class{constructor(){this._name="PinConversation"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"pinConversation",context:this})}handleConversationPinned(s,r){const{utils:{isArray:g}}=this._core;if(!g(s))return;const{OuterConstant:u}=this._core;let E=!1;s.forEach(m=>{const{Type:D,Peer_Account:M,GroupId:T}=m;let P;D===1?P=NA.getLocalConversation(`${u.CONV_C2C}${M}`):D===2&&(P=NA.getLocalConversation(`${u.CONV_GROUP}${T}`)),P&&(console.log(`${this._name}.handleConversationPinned conversationID:${P.conversationID} localPinned:${P.isPinned} remotePinned:${r}`),r&&!P.isPinned&&(P.isPinned=!0,E=!0),!r&&P.isPinned&&(P.isPinned=!1,E=!0))}),E&&NA.emitConversationListUpdate(!0)}pinConversation(s){return mA(this,void 0,void 0,function*(){const{OuterConstant:r,common:g,helper:{ChatError:u}}=this._core,{conversationID:E,isPinned:m}=s,D={code:0,data:{conversationID:E}},M=NA.getLocalConversation(E);if(M&&M.isPinned===m)return D;if(Ls(E))return M&&(M.isPinned=m),NA.emitConversationListUpdate(!0),D;const T=`conversationID:${E} isPinned:${m}`;try{let P=null;if(mt(E)?P={Type:1,To_Account:E.replace(r.CONV_C2C,"")}:ug(E)&&(P={Type:2,GroupId:E.replace(r.CONV_GROUP,"")}),yield function(oA,EA){return mA(this,void 0,void 0,function*(){const{fromAccount:wA,operationType:kA,itemList:xA}=oA,LA={From_Account:wA,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 oA=new Bt({conversationID:E,type:mt(E)?r.CONV_C2C:r.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 u({functionName:"pinConversation",code:W,message:oA,moreMessage:T})}})}},Oe=new class{constructor(){this._name="DeleteConversation"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"deleteConversation",context:this})}handleConversationDeleted(s){const{utils:{isArray:r}}=this._core;if(!r(s))return;const{OuterConstant:g}=this._core,u=[];s.forEach(E=>{const{Type:m,Peer_Account:D,GroupId:M}=E;m===1&&u.push(`${g.CONV_C2C}${D}`),m===2&&u.push(`${g.CONV_GROUP}${M}`)}),console.log(`${this._name}.handleConversationDeleted conversationIDList:${u}`),this._deleteLocalConversationList(u)}deleteConversation(s){return mA(this,void 0,void 0,function*(){const{utils:{isString:r}}=this._core;if(r(s))return this._deleteConversation({conversationIDList:[s],flag:ca.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:r,clearHistoryMessage:g=!0,flag:u=0}=s,{helper:{ChatError:E}}=this._core,m=`conversationIDList:${r} clearHistoryMessage:${g}`;try{const D=yield Promise.all([this._deleteConversationFromLocal(r),this._deleteConversationFromServer(r,g)]),M=[...D[0],...D[1]];if(M.length===0)throw new this._core.helper.ChatError({code:Qa.CONV_NOT_FOUND});return{code:0,data:u===ca.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:r}=this._core;return s.filter(g=>{var u;if(!NA.hasLocalConversation(g))return!1;const E=(u=NA.getLocalConversation(g))===null||u===void 0?void 0:u.type;return E!==r.CONV_GROUP||this._hasLocalGroup(g)?E===r.CONV_SYSTEM&&(this._deleteLocalConversation(g),!0):(this._deleteLocalConversation(g),!0)})}_deleteConversationFromServer(s,r){return mA(this,void 0,void 0,function*(){const{OuterConstant:g,common:u}=this._core,E={fromAccount:u.getCurrentUserID(),conversationList:[],clearHistoryMessage:r?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,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 r=!1;s.forEach(g=>{NA.hasLocalConversation(g)&&(this._deleteLocalConversation(g,!1),r=!0)}),console.log(`${this._name}._deleteLocalConversationList isUpdate:${r}`),r&&NA.emitConversationListUpdate()}_deleteLocalConversation(s,r=!0){const g=NA.hasLocalConversation(s);console.log(`${this._name}._deleteLocalConversation conversationID:${s} has:${g}`),g&&(NA.deleteLocalConversation(s),this._deleteConversationLocalMessage(s),r&&NA.emitConversationListUpdate())}_hasLocalGroup(s){const{OuterConstant:{CONV_GROUP:r},appStore:{groupStore:g}}=this._core,u=s.replace(r,"");return!!g.getGroup(u)}_deleteConversationLocalMessage(s){console.log(`${this._name}._deleteConversationLocalMessage conversationID:${s}`),this._core.message.messageDataHandler.deleteConversationMessageList(s),this._core.message.messageHistory.completedHistoryConversations.delete(s)}},Rt=new class{constructor(){this._name="SetConversationDraft"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"setConversationDraft",context:this})}setConversationDraft(s){return mA(this,void 0,void 0,function*(){const{conversationID:r,draftText:g}=s;if(console.log(`${this._name} conversationID:${r} draftText:${g}`),!NA.hasLocalConversation(r))throw new this._core.helper.ChatError({code:Qa.CONV_NOT_FOUND});const u=NA.getLocalConversation(r);return u?.setDraftText(g),NA.emitConversationListUpdate(),{code:0,data:{conversation:u}}})}},Xt=new class{constructor(){this._name="SetC2CMessageRemindType"}init(s){this._core=s}set(s,r){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:oA}=Bo.core.OuterConstant;return{[P]:0,[W]:1,[oA]:2}}()[r],u=yield function(P,W){return mA(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=[]}=u||{},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,r),{code:0,data:{successUserIDList:D,failureUserIDList:m}}})}},li=new class{constructor(){this._name="SetGroupMessageRemindType"}init(s){this._core=s}set(s,r){return mA(this,void 0,void 0,function*(){const{common:{getCurrentUserID:g,isTopic:u},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:r},this._core),!u(s)){const m=`${E.CONV_GROUP}${s}`;NA.patchMessageRemindType([m],r)}return{code:0,data:{groupID:s,messageRemindType:r}}})}},Mt=new class{constructor(){this._name="SetMessageRemindType"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"setMessageRemindType",context:this})}handleC2CMessageRemindTypeSync(s){const{helper:{isEmpty:r},OuterConstant:g,ssoLog:u}=this._core;s.forEach(E=>{const{MuteNotificationsSync:m}=E;if(!r(m)){const{To_Account:D,MuteNotifications:M}=m,T=D.map(W=>`${g.CONV_C2C}${W}`),P=Zi(M);u.debug(`${this._name}.handleC2CMessageRemindTypeSync conversationIDList:${T} messageRemindType:${P}`),NA.patchMessageRemindType(T,P)}})}setMessageRemindType(s){return mA(this,void 0,void 0,function*(){const r="setMessageRemindType",{groupID:g,userIDList:u,messageRemindType:E}=s,{helper:m,utils:{isUndefined:D},ssoLog:M}=this._core;try{if(!D(g))return M.debug(`${this._name}.${r} groupID:${g} messageRemindType:${E}`),yield li.set(g,E);if(!D(u))return M.debug(`${this._name}.${r} userIDList:${u} messageRemindType:${E}`),yield Xt.set(u,E);throw new m.ChatError({functionName:r,message:"userIDList or groupID is required"})}catch(T){throw new m.ChatError({functionName:r,code:T?.errorCode,message:T?.errorInfo,moreMessage:`groupID:${g} userIDList:${u} messageRemindType:${E}`})}})}},pi=new class{init(s){s.ssoLog.debug("ConversationAction.init"),this._core=s,XA.init(s),Te.init(s),de.init(s),ke.init(s),ue.init(s),Oe.init(s),Rt.init(s),Mt.init(s);const{notificationCenter:r,InnerEvent:{MESSAGE_PUSH:g,DESTROY:u}}=this._core,{InnerEventSubType:{CONV_MODIFIED:E,C2C_MESSAGE_READ_SYNC:m,GROUP_MESSAGE_READ_SYNC:D,C2C_REMIND_TYPE_SYNC:M}}=r;r.subscribeInnerEvent(g,E,this._onConversationModified,this),r.subscribeInnerEvent(g,m,this._onC2CMessageReadSync,this),r.subscribeInnerEvent(g,M,this._onC2CMessageRemindTypeSync,this),r.subscribeInnerEvent(g,D,this._onGroupMessageReadSync,this),r.subscribeInnerEvent(u,this._dispose,this)}_onConversationModified(s){const{constants:{ConvModifyPushType:r}}=this._core,{RecentContactMod:g=[]}=s;g.forEach(u=>{const{PushType:E}=u;if(E===r.CONV_DELETED){const{RecentContactList:m}=u.RecentContactDeleteItem;Oe.handleConversationDeleted(m)}if(E===r.CONV_PINED){const{RecentContactList:m}=u.RecentContactTopItem;ue.handleConversationPinned(m,!0)}if(E===r.CONV_UNPINED){const{RecentContactList:m}=u.RecentContactTopItem;ue.handleConversationPinned(m,!1)}})}_onC2CMessageReadSync(s){const{C2cNotifyMsgArray:r=[]}=s;ke.handleC2CMessageReadSync(r)}_onC2CMessageRemindTypeSync(s){const{C2cNotifyMsgArray:r=[]}=s;Mt.handleC2CMessageRemindTypeSync(r)}_onGroupMessageReadSync(s){const{GroupTips:r=[]}=s;ke.handleGroupMessageReadSync(r)}_dispose(){const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:r,DESTROY:g}}=this._core,{InnerEventSubType:{CONV_MODIFIED:u,C2C_MESSAGE_READ_SYNC:E,GROUP_MESSAGE_READ_SYNC:m,C2C_REMIND_TYPE_SYNC:D}}=s;s.unSubscribeInnerEvent(r,u,this._onConversationModified,this),s.unSubscribeInnerEvent(r,E,this._onC2CMessageReadSync,this),s.unSubscribeInnerEvent(r,D,this._onC2CMessageRemindTypeSync,this),s.unSubscribeInnerEvent(r,m,this._onGroupMessageReadSync,this),s.unSubscribeInnerEvent(g,this._dispose,this)}},io=new class{init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"setAllReceiveMessageOpt",context:this})}setAllReceiveMessageOpt(s){return mA(this,void 0,void 0,function*(){try{const{OuterConstant:{MSG_REMIND_ACPT_NOT_NOTE:r}}=this._core,{messageRemindType:g=r,isRepeated:u=!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}=Bo.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:u?os.ON:os.OFF});return{code:0,data:{errorCode:D.ErrorCode,errorInfo:D.ErrorInfo}}}catch(r){oc("setAllReceiveMessageOpt",r)}})}_calcStartAndEndTime(s){const{startHour:r=0,startMinute:g=0,startSecond:u=0,duration:E=0,isRepeated:m=!0}=s,D=new Date,M=new Date(D.getFullYear(),D.getMonth(),D.getDate(),r,g,u),T=Math.round(M.getTime()/1e3);let P=T+E;return m&&E>=86400&&(P=T+86400),{startTime:T,endTime:P}}_getType(s){const{OuterConstant:r}=this._core;return{[r.MSG_REMIND_ACPT_AND_NOTE]:0,[r.MSG_REMIND_DISCARD]:1,[r.MSG_REMIND_ACPT_NOT_NOTE]:2}[s]}},Is=new class{init(s){this._core=s;const{helper:r,notificationCenter:g,InnerEvent:u}=s;r.registerApi({apiName:"getAllReceiveMessageOpt",context:this}),g.subscribeInnerEvent(u.MESSAGE_PUSH,g.InnerEventSubType.ALL_RECEIVE_MESSAGE_OPTION,this.onAllReceiveMsgOptionNotify,this)}onAllReceiveMsgOptionNotify(s){const r=this._handleResult(s),{notificationCenter:g,OuterEvent:{ALL_RECEIVE_MESSAGE_OPT_UPDATED:u}}=this._core;g.emitOuterEvent(u,{name:u,data:r})}getAllReceiveMessageOpt(){return mA(this,void 0,void 0,function*(){try{const s=yield function(){return mA(this,void 0,void 0,function*(){const{common:r}=Bo.core,g={To_Account:r.getCurrentUserID()};return r.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:r}=this._core,{MSG_REMIND_ACPT_AND_NOTE:g,MSG_REMIND_DISCARD:u,MSG_REMIND_ACPT_NOT_NOTE:E}=r,m={0:g,1:u,2:E},{Level:D,StartTime:M,EndTime:T,IsRepeated:P}=s;return{messageRemindType:m[D]||g,startTime:M,endTime:T,isRepeated:P===os.ON}}},Fo=new class{init(s){s.ssoLog.debug("ReceiveMessageOptions.init"),this._core=s,Xt.init(s),li.init(s),QA.init(s),yA.init(s),io.init(s),Is.init(s)}};const ni=s=>!mt(s)&&!ug(s)&&!Ls(s),Fr={getConversationProfile:[{key:"conversationID",required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!ni(s)||"conversationID is invalid."}],setMessageRead:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!ni(s)||"conversationID is invalid."}},pinConversation:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!ni(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:r,isObject:g,isString:u}}}=Bo;if(!u(s)&&!g(s))return"options is String or Object.";if(u(s)&&ni(s))return"conversationID is invalid.";if(g(s)){if(!r(s.conversationIDList))return"conversationIDList is not Array.";if(s.conversationIDList.length===0)return"conversationIDList is empty.";if(s.conversationIDList.some(E=>{if(ni(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=>!(!mt(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 zn=new class{constructor(){this.name="Conversation"}install(s){Bo.init(s),pi.init(s),Fo.init(s),NA.init(s),s.helper.registerValidateConfig({auth:Zo,params:Fr})}};const Zn=new class{init(s){this.core=s}},ia="AVChatRoom",qr="AV_HISTORY_MSG",sc="GRP_COUNTER",ju="Set",Dm="Increase",_i="Decrease",ri=0,Do=1,on=2,ss=["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"],Pl=["Role","JoinTime","MsgFlag","MsgSeq"],fd=["Role","JoinTime","MsgSeq","MsgFlag","NameCard"],Lc=0,Rr=1,MI="notStart",ru="resolved",Og="rejected",au=10018,vI=11e3,Uc=2,Wu=["Owner","Admin","Member"],Sm=["Role","JoinTime","NameCard","ShutUpUntil","OnlineStatus"],Mm=0,vm=1,Rm=2,uD=4,ED=1,xv=2,dD=3,CD=4,Yv=5,DT=1,yd=0,ST=4,hD=6,MT=400,BD=300,vT={from:!0,groupID:!0,groupName:!0,to:!0},Vv={from:!0,groupID:!0,groupName:!0,to:!0,type:!0},RT=2,Jv=4,wT=5,_T=7,QD=8,pD=15,bQ=20,wm=21,_m=2600,Dd=2602,TT=2603,NT=2620,Tm=2621,mD=2623,dh=2660,GT=2661,bT=2681,Nm=2683,Hv=2684,fD=2685,Gm=2687,qv=3122,kT=10018,LT={0:"DisableInvite",1:"NeedPermission",2:"FreeAccess"},Kv=s=>s===Zn.core.OuterConstant.GRP_PUBLIC,Sd=s=>s===Zn.core.OuterConstant.GRP_AVCHATROOM,bm=(s,r)=>{const{isArray:g}=Zn.core.utils;if(!g(s)||!g(r))return!1;let u=!1;return r.forEach(({key:E,value:m})=>{const D=s.find(M=>M.key===E);D?D.value!==m&&(D.value=m,u=!0):(s.push({key:E,value:m}),u=!0)}),u},Md=s=>{const r=[];if(!s)return r;for(let g=0,u=s.length;g{const r=[];for(let g=0,u=s.length;g0&&M.members.forEach(T=>{T.userID===this.selfInfo.userID&&D(this.selfInfo,T,["sequence"])})}updateSelfInfo(r){const{nameCard:g,joinTime:u,role:E,messageRemindType:m,readedSequence:D,excludedUnreadSequenceList:M}=r,{common:{deepMerge:T}}=Zn.core;T(this.selfInfo,{nameCard:g,joinTime:u,role:E,messageRemindType:m,readedSequence:D,excludedUnreadSequenceList:M},[],["",null,void 0,0,NaN])}setSelfNameCard(r){this.selfInfo.nameCard=r}}var Ji=new class{constructor(){this._name="GroupDataHandler"}init(s){this._core=s;const{appStore:{groupStore:r}}=s;this._groupMap=r.getGroupMap()}hasLocalGroup(s){return this._groupMap.has(s)}getLocalGroup(s){return this._groupMap.get(s)}updateLocalGroup(s){const{common:{getCurrentUserID:r}}=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 zu(E)),this._clearGroupLocalMessage(g))});const u=r();for(const[,E]of this._groupMap)E.selfInfo.userID=u,E.selfInfo.role==="Owner"&&(E.ownerID=u)}deleteLocalGroup(s){this._groupMap.delete(s)}getLocalGroupList(){const{OuterConstant:{GRP_ROOM:s,GRP_LIVE:r}}=this._core;return[...this._groupMap.values()].filter(g=>{const{type:u}=g;return u!==s&&u!==r})}clearLocalGroup(){this._groupMap.clear()}emitGroupListUpdate(){const s=this.getLocalGroupList(),{OuterEvent:{GROUP_LIST_UPDATED:r},notificationCenter:g}=this._core;g.emitOuterEvent(r,{name:r,data:s})}updateConversationGroupProfile(s){const{appStore:{conversationStore:r},OuterConstant:{CONV_GROUP:g}}=this._core,u=`${g}${s}`,E=r.getConversation(u);if(E){const m=this.getLocalGroup(s);E.setProfileCompleted(),r.updateConversation(u,{groupProfile:m})}}reset(){this.clearLocalGroup()}_clearGroupLocalMessage(s){const{message:{messageHistory:r,messageDataHandler:g},OuterConstant:{CONV_GROUP:u},ssoLog:E}=this._core;E.debug("_clearGroupLocalMessage",`groupID:${s}`);const m=`${u}${s}`;r.completedHistoryConversations.delete(m),g.deleteConversationMessageList(m)}};function Lm(s,r){return mA(this,void 0,void 0,function*(){const{type:g,limit:u,offset:E,supportTopic:m=0,memberAccount:D,responseFilter:M}=s,T={Type:g,Limit:u,Offset:E,Member_Account:D,ResponseFilter:M,SupportTopic:m,NeedAppDefineData:1};return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_joined_group_list",data:T})})}const dn=function(s,r){return{code:0,data:s||{},successLog:r}};var jv=new class{constructor(){this._name="GetGroupList",this._pagingStatus=MI,this.PAGING_GRP_COUNT_LIMIT=200}init(s){this._core=s;const{helper:r,constants:{WORKFLOW_NAME:g,WORKFLOW_STEP:u}}=s;r.registerApi({apiName:"getGroupList",context:this}),r.registerWorkflowStep(g.SYNC_SERVER_INFO_AFTER_LOGIN,u.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}),Ji.updateLocalGroup(g),Ji.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=Ji.getLocalGroupList();return dn({groupList:g,isSyncCompleted:this._isSyncCompleted()})}).catch(g=>{throw g});const r=Ji.getLocalGroupList();return dn({groupList:r,isSyncCompleted:this._isSyncCompleted()},{message:`return group count:${r.length}`})})}_syncGroupList(){return mA(this,void 0,void 0,function*(){this._pagingStatus===MI&&Ji.clearLocalGroup();const s=this.PAGING_GRP_COUNT_LIMIT,r=[];try{yield this._pagingGetGroupList({limit:s,offset:0,groupList:r}),this._pagingStatus=ru,this._groupListTreeShaking(r),Ji.updateLocalGroup(r);const g=Ji.getLocalGroupList();return this._core.ssoLog.debug("_syncGroupList",`${this._name}._syncGroupList ok, count:${g.length}`),Ji.emitGroupListUpdate(),g}catch(g){throw this._pagingStatus=Og,g}})}_pagingGetGroupList(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r}=this._core,{isCommunityRelay:g=!1,groupList:u}=s;let E,{limit:m,offset:D}=s;const M=[...ss];g&&(E=this._core.OuterConstant.GRP_COMMUNITY,M.push("AtInfoList"));try{const T=yield Lm({type:E,limit:m,offset:D,memberAccount:this._core.store.get("login").userId,responseFilter:{GroupBaseInfoFilter:M,SelfInfoFilter:[...Pl]}},this._core),{GroupIdList:P=[],TotalCount:W=0}=T||{},oA=this._convertGroupKey(P);u.push(...oA);const EA=D+m,wA=!(W>EA),kA=`offset:${D} limit:${m} total:${W} isCompleted:${wA} current:${u.length} isCommunityRelay:${g}`;return r.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList ok. ${kA}`),g?wA?u:(D=EA,this._pagingGetGroupList({isCommunityRelay:!0,limit:m,offset:D,groupList:u})):wA?(r.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList start to get community list`),D=0,this._pagingGetGroupList({isCommunityRelay:!0,limit:m,offset:D,groupList:u})):(D=EA,this._pagingGetGroupList({limit:m,offset:D,groupList:u}))}catch(T){if(T.ErrorCode===au)return r.warn("_pagingGetGroupList",`${this._name}._pagingGetGroupList response size exceeds the limit, request count:${m}`),m=50,this._pagingGetGroupList({isCommunityRelay:g,limit:m,offset:D,groupList:u});if(g)return T.code===vI&&r.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList ok. community unavailable`),u;throw T}})}_pagingGetJoinedCommunityList(s){return mA(this,void 0,void 0,function*(){const{common:{getCurrentUserID:r},OuterConstant:g,ssoLog:u}=this._core,{groupList:E}=s;let{limit:m,offset:D}=s;try{const M=yield Lm({limit:m,offset:D,type:g.GRP_COMMUNITY,memberAccount:r(),supportTopic:1,responseFilter:{GroupBaseInfoFilter:[...ss],SelfInfoFilter:[...Pl]}},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 u.debug("_pagingGetJoinedCommunityList",`${this._name}._pagingGetJoinedCommunityList ok. ${wA}`),EA?E:(D=oA,this._pagingGetJoinedCommunityList({limit:m,offset:D,groupList:E}))}catch(M){if(M.code===kT)return u.warn("_pagingGetJoinedCommunityList",`${this._name}._pagingGetJoinedCommunityList response size exceeds the limit, request count:${m}`),m=50,this._pagingGetJoinedCommunityList({limit:m,offset:D,groupList:E});throw M}})}_groupListTreeShaking(s){const r=new Map([...Ji.getLocalGroupList()]);for(let u=0,E=s.length;u{const{AtFlagList:E,AtMsgSeq:m,From_Account:D}=u;g.push({groupID:s,groupAtType:E,sequence:m,from:D})}),g}},Zu=new class{constructor(){this._name="CreateGroup"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"createGroup",context:this})}createGroup(s){return mA(this,void 0,void 0,function*(){var r;this._preCheckParams(s);const{helper:{ChatError:g}}=this._core;try{const{utils:{isEmpty:u},common:{getCurrentUserID:E},OuterConstant:{GRP_AVCHATROOM:m}}=this._core,D=yield function(oA,EA){return mA(this,void 0,void 0,function*(){const{name:wA,type:kA,groupID:xA,introduction:LA,notification:SA,avatar:OA,maxMemberNum:qA,joinOption:Ie,inviteOption:le,memberList:bi,groupCustomField:ki,isSupportTopic:Ot}=oA;let Li,cs;bi&&(Li=bi.map(St=>{const{userID:UA,memberCustomField:ai}=St;return{Member_Account:UA,AppMemberDefinedData:ai?YE(ai):void 0}})),ki&&(cs=YE(ki));const Re={Name:wA,Type:kA,GroupId:xA,Introduction:LA,Notification:SA,FaceUrl:OA,MaxMemberCount:qA,ApplyJoinOption:Ie,InviteJoinOption:le,MemberList:Li,AppDefinedData:cs,SupportTopic:Ot,webPushFlag:1};return EA.common.buildAndSendPacket({servcmd:"group_open_http_svc.create_group",data:Re})})}(Object.assign(Object.assign({},s),{ownerID:E()}),this._core),{GroupId:M,OverJoinedGroupLimit_Account:T=[]}=D||{},P=`${this._name}.createGroup ok, type:${s.type} groupID:${M} overLimitUserIDList:${T}`;if(u(s.memberList)||u(T)||(s.memberList=(r=s.memberList)===null||r===void 0?void 0:r.filter(oA=>T.includes(oA.userID))),s.type===m)return dn({group:new zu(Object.assign(Object.assign({},s),{groupID:M}))},{message:P});Ji.updateLocalGroup([Object.assign(Object.assign({},s),{groupID:M})]);const W=Ji.getLocalGroup(M);return this._notNeedSendCustomMessage(s)||(this._sendCustomMessage(M,s.type),Ji.emitGroupListUpdate()),dn({group:W},{message:P})}catch(u){const{errorCode:E,errorInfo:m}=u;throw new g({functionName:"createGroup",code:E,message:m,moreMessage:` groupID:${s.groupID}`})}})}_preCheckParams(s){const{type:r,groupID:g}=s,{utils:{isEmpty:u,isUndefined:E},common:{isCommunity:m}}=this._core,D=!u(g);if(!(()=>{const{GRP_PUBLIC:M,GRP_WORK:T,GRP_MEETING:P,GRP_AVCHATROOM:W,GRP_COMMUNITY:oA}=Zn.core.OuterConstant;return[M,T,P,W,oA]})().includes(r))throw new this._core.helper.ChatError({code:_m});if(!m({type:r})){if(D&&m({groupID:g}))throw new this._core.helper.ChatError({code:Dd});E(s.isSupportTopic)||(s.isSupportTopic=void 0)}if(this._canIUseMemberList(r)||E(s.memberList)||(s.memberList=void 0),this._canIUseJoinOption(r)||E(s.joinOption)||(s.joinOption=void 0),m({type:r})){if(D&&!m({groupID:g}))throw new this._core.helper.ChatError({code:Dd});s.isSupportTopic=this._canIUseTopic(s)?1:0}}_canIUseMemberList(s){return!Sd(s)}_canIUseJoinOption(s){return Kv(s)||this._core.common.isCommunity({type:s})}_canIUseTopic(s){const{isSupportTopic:r}=s;return r===!0}_notNeedSendCustomMessage(s){const{type:r,isSupportTopic:g}=s,{OuterConstant:{GRP_AVCHATROOM:u,GRP_COMMUNITY:E}}=this._core;return r===u||r===E&&g===1}_sendCustomMessage(s,r){var g,u,E,m,D,M;const{OuterConstant:T,common:{t:P}}=this._core;let W=P("CREATE_GROUP"),oA=Lc;r===T.GRP_COMMUNITY&&(W=P("CREATE_COMMUNITY"),oA=Rr);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=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageFactory)===null||E===void 0?void 0:E.createCustomMessage(EA);(M=(D=(m=this._core)===null||m===void 0?void 0:m.message)===null||D===void 0?void 0:D.messageSender)===null||M===void 0||M.sendMessage(wA,{})}},zs=new class{constructor(){this._name="AttributesDataHandler",this._groupAttributesCache=new Map,this._groupAttributesCacheValuesCopy={}}init(s){this._core=s;const{helper:r,constants:g}=s;r.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:r}}=s,{utils:{isEmpty:g,isUndefined:u}}=this._core;return!u(r)&&!g(r.groupAttributeOption)}handleGroupAttributesUpdated(s){const{groupID:r,groupAttributeOption:g}=s,{serverMainSequence:u,groupAttributeList:E=[],operation:m}=g;this._core.ssoLog.debug("handleGroupAttributesUpdated",`${this._name}.handleGroupAttributesUpdated groupID:${r} operation:${m}`);const{utils:{isUndefined:D}}=this._core;D(m)||(this.refreshGroupAttributesCache({groupID:r,serverMainSequence:u,groupAttributeList:E,operation:m}),this.emitGroupAttributesUpdated(r))}initGroupAttributesCache(s){const{groupID:r,avChatRoomKey:g}=s;this._groupAttributesCache.set(r,{lastUpdateTime:0,localMainSequence:0,serverMainSequence:0,avChatRoomKey:g,values:new Map}),this._core.ssoLog.debug("initGroupAttributesCache",`${this._name}.initGroupAttributesCache. groupID:${r} 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:r,serverMainSequence:g,groupAttributeList:u,operation:E}=s;if(this.hasGroupAttributesCache(r)){const m=this.getGroupAttributesCache(r),{localMainSequence:D}=m;E!==Yv&&g-D!==1||(m.serverMainSequence=g,m.localMainSequence=g,m.lastUpdateTime=Date.now(),this._updateGroupAttributesCacheValues({groupAttributes:m,groupAttributeList:u,operation:E})),g-D>1&&(m.serverMainSequence=g),this._groupAttributesCache.set(r,m),this._core.ssoLog.debug("refreshGroupAttributesCache",`${this._name}.refreshGroupAttributesCache. operation:${E} localMainSequence:${D} serverMainSequence:${g}`)}}_updateGroupAttributesCacheValues(s){const{groupAttributes:r,groupAttributeList:g=[],operation:u}=s;u!==dD?u!==CD?(u===ED&&r.values.clear(),g.forEach(E=>{const{key:m,value:D,sequence:M}=E;r.values.set(m,{value:D,sequence:M})})):g.forEach(E=>{r.values.delete(E.key)}):r.values.clear()}getGroupAttributesCacheValues(s){var r;const{groupID:g,keyList:u=[]}=s,E={};if(this.hasGroupAttributesCache(g)){const{values:m}=this.getGroupAttributesCache(g);if(u.length===0){for(const D of m.keys())E[D]=((r=m.get(D))===null||r===void 0?void 0:r.value)||"";return E}return u.forEach(D=>{var M;m.has(D)&&(E[D]=((M=m.get(D))===null||M===void 0?void 0:M.value)||"")}),E}return E}saveGroupAttributesCacheValuesCopy(s){this._groupAttributesCacheValuesCopy=this.getGroupAttributesCacheValues({groupID:s})}emitGroupAttributesUpdated(s){var r,g;const{OuterConstant:{GRP_ROOM:u,GRP_LIVE:E}}=this._core,m=this.getGroupAttributesCacheValues({groupID:s}),D=this._core.appStore.groupStore.getGroup(s),{updatedKeyList:M,deletedKeyList:T}=this._computeValuesChangedData(m);M.length===0&&T.length===0||([u,E].includes(D.type)?(this._core.ssoLog.debug("RICH_STATUS_CHANGED",`${this._name}.emitRichStatusChanged update count:${M.length}, delete count:${T.length}`),this._emitEvent({name:(r=this._core)===null||r===void 0?void 0:r.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:r}}=this._core,g=[],u=[];return Object.keys(s).forEach(E=>{s[E]!==this._groupAttributesCacheValuesCopy[E]&&g.push(E)}),Object.keys(this._groupAttributesCacheValuesCopy).forEach(E=>{r(s[E])&&u.push(E)}),this._groupAttributesCacheValuesCopy={},{updatedKeyList:g,deletedKeyList:u}}_emitEvent(s){var r;(r=this._core)===null||r===void 0||r.notificationCenter.emitOuterEvent(s.name,s)}convertKeyValueMapToList(s){const r=[];return Object.keys(s).forEach(g=>{r.push({key:g,value:s[g]})}),r}reset(){this._groupAttributesCache.clear(),this._groupAttributesCacheValuesCopy={}}},hh=new class{constructor(){this._name="DismissGroup"}init(s,r){this._core=s;const{helper:g}=s;g.registerApi({apiName:"dismissGroup",context:this,matcher:()=>!r.getInstalledSubPlugins().includes(ia)})}dismissGroup(s){return mA(this,void 0,void 0,function*(){const{helper:{ChatError:r}}=this._core;try{yield function(u,E){return mA(this,void 0,void 0,function*(){const m={GroupId:u};return E.common.buildAndSendPacket({servcmd:"group_open_http_svc.destroy_group",data:m})})}(s,this._core);const{type:g}=Ji.getLocalGroup(s);return Ji.deleteLocalGroup(s),Ji.emitGroupListUpdate(),zs.deleteGroupAttributesCache(s),dn({groupID:s,type:g},{message:s})}catch(g){const{errorCode:u,errorInfo:E}=g;throw new r({functionName:"dismissGroup",code:u,message:E})}})}},xl=new class{constructor(){this._name="GetGroupProfile"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"getGroupProfile",context:this})}getGroupProfile(s){return mA(this,void 0,void 0,function*(){const{groupID:r,groupCustomFieldFilter:g}=s,u={groupIDList:[r],responseFilter:{GroupBaseInfoFilter:[...ss],AppDefinedDataFilter_Group:g,MemberInfoFilter:[...fd]}},{helper:{ChatError:E}}=this._core;try{const m=yield this.getGroupProfileAdvance(u),{successGroupList:D,failureGroupList:M}=m;if(M.length>0)throw M[0];let T;return!Ji.hasLocalGroup(r)&&Sd(D[0].type)?T=new zu(D[0]):(Ji.updateLocalGroup(D),T=Ji.getLocalGroup(r)),T.isSupportTopic||Ji.updateConversationGroupProfile(r),dn({group:T},{message:`groupID:${r}`})}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:r}=s,{common:{isCommunity:g}}=this._core,u=r.filter(T=>!g({groupID:T})),E=r.filter(T=>g({groupID:T}));u.length>50&&(u.length=50),E.length>50&&(E.length=50);const m=yield Promise.all([this._getGroupProfileAdvance(Object.assign(Object.assign({},s),{groupIDList:u})),this._getGroupProfileAdvance(Object.assign(Object.assign({},s),{groupIDList:E,isCommunityProfile:!0}))]),D=[],M=[];return m.forEach(T=>{D.push(...T.successGroupList),M.push(...T.failureGroupList)}),{successGroupList:D,failureGroupList:M}})}_getGroupProfileAdvance(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r,utils:{isUndefined:g}}=this._core,{isCommunityProfile:u=!1}=s,E=So(s,["isCommunityProfile"]);if(E.groupIDList.length===0)return{successGroupList:[],failureGroupList:[]};try{const m=yield function(W,oA){return mA(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 r.debug("_getGroupProfileAdvance",`${this._name}._getGroupProfileAdvance ok, groupID:${E.groupIDList.join(",")}`),{successGroupList:T,failureGroupList:P}}catch(m){if(u)return{successGroupList:[],failureGroupList:[]};throw m}})}_convertGroupProfileKey(s){const r=[];for(let g=0,u=s.length;g0&&u{const{Key:T,Value:P=0}=M;E.set(T,P)}),this._groupCountersMap.set(r,{lastUpdateTime:Date.now(),groupCounterSeq:u,counters:E,avChatRoomKey:m})}}initGroupCountersCache(s){const{groupID:r,avChatRoomKey:g}=s;this._groupCountersMap.set(r,{lastUpdateTime:0,groupCounterSeq:0,counters:new Map,avChatRoomKey:g})}getLocalCounters(s,r){const g={};if(!this._hasLocalGroupCounters(s))return g;const{counters:u}=this.getLocalGroupCounters(s);if(r.length>0)r.forEach(E=>{u.has(E)&&(g[E]=u.get(E))});else for(const E of u.keys())g[E]=u.get(E);return g}deleteLocalGroupCounters(s){const{groupID:r,counterList:g=[],groupCounterSeq:u}=s;if(this._hasLocalGroupCounters(r)){const{counters:E,avChatRoomKey:m}=this.getLocalGroupCounters(r);g.forEach(D=>{E.delete(D.key)}),this._groupCountersMap.set(r,{lastUpdateTime:Date.now(),groupCounterSeq:u,counters:E,avChatRoomKey:m})}}setGroupCounters(s,r){if(!this._hasLocalGroupCounters(s))return;const g=this.getLocalGroupCounters(s),{counters:u}=g;let E=!1;Object.entries(r).forEach(([m,D])=>{u.has(m)&&u.get(m)!==D&&(u.set(m,D),E=!0)}),E&&this._groupCountersMap.set(s,Object.assign(Object.assign({},g),{lastUpdateTime:Date.now(),counters:u}))}_hasLocalGroupCounters(s){return this._groupCountersMap.has(s)}reset(){this._groupCountersMap.clear()}},VE=new class{constructor(){this._name="JoinGroup"}init(s,r){this._core=s;const{helper:g}=s;g.registerApi({apiName:"joinGroup",context:this,matcher:()=>!r.getInstalledSubPlugins().includes(ia)})}joinGroup(s){return mA(this,void 0,void 0,function*(){const{groupID:r}=s,{helper:{ChatError:g},OuterConstant:u,ssoLog:E}=this._core;try{if(Ji.hasLocalGroup(r))try{return yield xl.getGroupProfile({groupID:r}),dn({status:u.JOIN_STATUS_ALREADY_IN_GROUP,group:Ji.getLocalGroup(r)},{message:`groupID:${r} joinedStatus:${u.JOIN_STATUS_ALREADY_IN_GROUP}`})}catch{return E.warn("joinGroup",`${this._name}.joinGroup ${r} was unjoined, start to join!`),Ji.deleteLocalGroup(r),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:${r}`})}})}_applyJoinGroup(s){return mA(this,void 0,void 0,function*(){const{OuterConstant:r,helper:g,ssoLog:u}=this._core,{groupID:E}=s,m=Object.assign({},s),D=g.checkBusinessCapabilityBits(qr);D&&(m.historyMessageFlag=1);const M=yield function(SA,OA){return mA(this,void 0,void 0,function*(){const{groupID:qA,applyMessage:Ie,historyMessageFlag:le}=SA,bi={GroupId:qA,ApplyMsg:Ie,HugeGroupHistoryMsgFlag:le};return OA.common.buildAndSendPacket({servcmd:"group_open_http_svc.apply_join_group",data:bi})})}(m,this._core),{Type:T,JoinedStatus:P,LongPollingKey:W,StartSeq:oA,HugeGroupFlag:EA,AVChatRoomKey:wA,RspMsgList:kA=[]}=M||{},xA=`groupID:${E} joinedStatus:${P} longPollingKey:${W} startSeq:${oA} avChatRoomFlag:${EA} canGetAVChatRoomHistoryMsg:${D}, historyMessageCount:${kA.length}`;u.debug("_applyJoinGroup",`${this._name}._applyJoinGroup ok, ${xA}`);let LA=new zu({groupID:E,type:T});if(P===r.JOIN_STATUS_WAIT_APPROVAL)return dn({status:r.JOIN_STATUS_WAIT_APPROVAL,group:LA});if(P===r.JOIN_STATUS_SUCCESS){try{LA=(yield xl.getGroupProfile({groupID:E})).data.group}catch(SA){u.warn("_applyJoinGroup",`${this._name}._applyJoinGroup getGroupProfile failed, groupID: ${E}, errorCode:${SA?.code}`)}return this._handleJoinResult({group:LA,avChatRoomFlag:EA,longPollingKey:W,startSequence:oA,avChatRoomKey:wA,historyMessageList:kA})}throw new this._core.helper.ChatError({code:dh})})}_handleJoinResult(s){const{group:r,avChatRoomFlag:g,avChatRoomKey:u}=s;return g===1?(zs.initGroupAttributesCache({groupID:r.groupID,avChatRoomKey:u}),nc.initGroupCountersCache({groupID:r.groupID,avChatRoomKey:u}),dn(s)):(Ji.updateLocalGroup([r]),Ji.emitGroupListUpdate(),dn({status:this._core.OuterConstant.JOIN_STATUS_SUCCESS,group:r},{message:`groupID:${r.groupID}`}))}},kQ=new class{constructor(){this._name="QuitGroup"}init(s,r){this._core=s;const{helper:g}=s;g.registerApi({apiName:"quitGroup",context:this,matcher:()=>!r.getInstalledSubPlugins().includes(ia)})}quitGroup(s){return mA(this,void 0,void 0,function*(){if(!Ji.hasLocalGroup(s))throw new this._core.helper.ChatError({code:mD});const{helper:{ChatError:r}}=this._core;try{yield function(u,E){return mA(this,void 0,void 0,function*(){const m={GroupId:u};return E.common.buildAndSendPacket({servcmd:"group_open_http_svc.quit_group",data:m})})}(s,this._core);const{type:g}=Ji.getLocalGroup(s);return Ji.deleteLocalGroup(s),Ji.emitGroupListUpdate(),zs.deleteGroupAttributesCache(s),dn({groupID:s,type:g},{message:`groupID:${s}`})}catch(g){const{errorCode:u,errorInfo:E}=g;throw new r({functionName:"quitGroup",code:u,message:E,moreMessage:`groupID:${s}`})}})}},uB=new class{constructor(){this._name="SearchGroup"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"searchGroupByID",context:this})}searchGroupByID(s){return mA(this,void 0,void 0,function*(){try{const r=yield function(OA,qA){return mA(this,void 0,void 0,function*(){const Ie={GroupIdList:[OA],GroupBasePublicInfoFilter:[...Eg]};return qA.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_public_info",data:Ie})})}(s,this._core),{GroupInfo:g=[]}=r||{},{AppDefinedData:u=[],ApplyJoinOption:E,CreateTime:m,FaceUrl:D,Introduction:M,InviteJoinOption:T,MaxMemberNum:P,MemberNum:W,Name:oA,Owner_Account:EA,Type:wA,ErrorCode:kA,ErrorInfo:xA}=g[0];if(kA!==0)throw new this._core.helper.ChatError({code:kA,message:xA});const LA=Md(u),SA=new zu({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(r){const{errorCode:g,errorInfo:u}=r;throw new this._core.helper.ChatError({functionName:"searchGroupByID",code:g,message:u})}})}},UT=new class{constructor(){this._name="UpdateGroupProfile"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"updateGroupProfile",context:this})}updateGroupProfile(s){return mA(this,void 0,void 0,function*(){const{groupID:r}=s,{utils:{isUndefined:g,safeStringify:u},ssoLog:E,helper:m}=this._core;let D=Ji.getLocalGroup(r);if(D){const{type:M}=D;this._canIUseJoinOption(M)||g(s.joinOption)||(E.warn("updateGroupProfile",`${this._name}.updateGroupProfile groupID:${r} 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:oA,introduction:EA,notification:wA,muteAllMembers:kA,joinOption:xA,inviteOption:LA,groupCustomField:SA}=M,OA={GroupId:P,Name:W,FaceUrl:oA,Introduction:EA,Notification:wA,ShutUpAllMember:kA,ApplyJoinOption:xA,InviteJoinOption:LA,AppDefinedData:SA?YE(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),Ji.emitGroupListUpdate()):D=new zu(s),dn({group:D},{message:`groupID:${r}`})}catch(M){const{errorCode:T,errorInfo:P}=M;throw new m.ChatError({code:T,message:P,moreMessage:`options:${u(s)}`})}})}_canIUseJoinOption(s){return Kv(s)||this._core.common.isCommunity({type:s})}},FT=new class{constructor(){this._name="ChangeGroupOwner"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"changeGroupOwner",context:this})}changeGroupOwner(s){return mA(this,void 0,void 0,function*(){const r="changeGroupOwner",{groupID:g,newOwnerID:u}=s,E=Ji.getLocalGroup(g),{helper:m,OuterConstant:D,common:{getCurrentUserID:M}}=this._core;if(E?.type===D.GRP_AVCHATROOM)throw new m.ChatError({functionName:r,code:NT});if(u===M())throw new m.ChatError({functionName:r,code:Tm});try{return yield function(T,P){return mA(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=u,Ji.emitGroupListUpdate(),dn({group:E})}catch(T){throw new m.ChatError({functionName:r,code:T?.errorCode,message:T?.errorInfo})}})}},LQ=new class{constructor(){this._name="GetGroupOnlineMemberCount",this._onlineMemberCountMap=new Map}init(s,r){this._core=s;const{helper:g}=s;g.registerApi({apiName:"getGroupOnlineMemberCount",context:this,matcher:()=>!r.getInstalledSubPlugins().includes(ia)})}getGroupOnlineMemberCount(s){return mA(this,void 0,void 0,function*(){const r="getGroupOnlineMemberCount";if(!Ji.hasLocalGroup(s))return dn({memberCount:0});const g=Date.now();if(this._onlineMemberCountMap.has(s)){const u=this._onlineMemberCountMap.get(s),{lastReqTime:E=0,memberCount:m=0}=u||{};if(g-E<=6e4)return dn({memberCount:m})}try{const u=yield function(D,M){return 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}=u||{};this._onlineMemberCountMap.set(s,{lastReqTime:Date.now(),memberCount:E});const m=`${this._name}.${r} ok. groupID:${s} memberCount:${E}`;return dn({memberCount:E},{message:m})}catch(u){throw new this._core.helper.ChatError({functionName:r,code:u?.errorCode,message:u?.errorInfo})}})}},UQ=new class{init(s,r){s.ssoLog.debug("GroupAction.init"),jv.init(s),Zu.init(s),hh.init(s,r),VE.init(s,r),kQ.init(s,r),uB.init(s),xl.init(s),UT.init(s),FT.init(s),LQ.init(s,r)}dismissGroup(s){return hh.dismissGroup(s)}joinGroup(s){return VE.joinGroup(s)}quitGroup(s){return kQ.quitGroup(s)}getGroupOnlineMemberCount(s){return LQ.getGroupOnlineMemberCount(s)}},Wv=new class{constructor(){this._name="GetGroupApplicationList"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"getGroupApplicationList",context:this})}getGroupApplicationList(){return mA(this,void 0,void 0,function*(){const s="getGroupApplicationList";try{const r=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([...r[0],...r[1]]);return dn({applicationList:g})}catch(r){throw new this._core.helper.ChatError({functionName:s,code:r?.errorCode,message:r?.errorInfo})}})}_getGroupApplicationList(s){return mA(this,void 0,void 0,function*(){const{type:r,startTime:g=0,limit:u=20}=s||{},{common:E}=this._core;let m;try{m=yield function(P,W){return mA(this,void 0,void 0,function*(){const{type:oA,startTime:EA,limit:wA,handleAccount:kA}=P,xA={Type:oA,StartTime:EA,Limit:wA,Handle_Account:kA};return W.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_pendency",data:xA})})}({type:r,startTime:g,limit:u,handleAccount:E.getCurrentUserID()},this._core)}catch(P){if(P?.errorCode!==11e3)throw P;m={}}const{NextStartTime:D=0,PendencyList:M=[]}=m||{};if(D===0)return M;const T=yield this._getGroupApplicationList(Object.assign(Object.assign({},s),{startTime:D}));return[...M,...T]})}_handleGroupApplicationResult(s){const r=[];return s.forEach(g=>{const u=this._convertApplicationData(g),{handled:E}=u,m=So(u,["handled"]);E===0&&r.push(m)}),r}_convertApplicationData(s){const{Handled:r,AddTime:g,ApplyInviteMsg:u,Authentication:E,FromUserNickName:m,From_Account:D,GroupId:M,GroupName:T,PendencyType:P,To_Account:W}=s;return{handled:r,messageKey:g,applicant:D,applicantNick:m,groupID:M,groupName:T,authentication:E,applicationType:P,userID:W,note:u,addTime:g}}},zv=new class{constructor(){this._name="HandleGroupApplication"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"handleGroupApplication",context:this})}handleGroupApplication(s){return mA(this,void 0,void 0,function*(){const{application:r}=s,g=this._handleParams(s);try{r?.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: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 mA(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 u=Ji.getLocalGroup(g.groupID);return dn({group:u})}catch(u){throw new this._core.helper.ChatError({functionName:"handleGroupApplication",code:u?.errorCode,message:u?.errorInfo})}})}_handleParams(s){var r;const{handleAction:g,handleMessage:u,message:E,application:m}=s;let D,M,T,P,W;if(E){const{payload:oA}=E||{};D=oA.operatorID,M=(r=oA.groupProfile)===null||r===void 0?void 0:r.groupID,T=oA.authentication,P=oA.messageKey}else D=m?.applicant||"",M=m?.groupID||"",T=m?.authentication||"",P=m?.messageKey||0;return m?.applicationType===Uc&&(W=m.userID),{handleAction:g,handleMessage:u,applicant:D,invitee:W,groupID:M,authentication:T,messageKey:P}}},yD=new class{init(s){s.ssoLog.debug("GroupApplication.init"),Wv.init(s),zv.init(s)}};let vC=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:r},common:{deepMerge:g}}}=Zn;r(s.muteTime)||(this.muteUntil=Math.floor((Date.now()+1e3*s.muteTime)/1e3)),r(s.onlineStatus)||(this.isOnline=s.onlineStatus==="Online");const u=[null,void 0,"",0,NaN];s.memberCustomField&&bm(this.memberCustomField,s.memberCustomField),g(this,s,["memberCustomField","marks","onlineStatus","muteTime"],u)}};function EB(s,r){return mA(this,void 0,void 0,function*(){const{groupID:g,userID:u,muteTime:E,role:m,nameCard:D,memberCustomField:M}=s;let T;M&&(T=YE(M));const P={GroupId:g,Member_Account:u,ShutUpTime:E,Role:m,NameCard:D,AppMemberDefinedData:T};return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:P})})}var DD=new class{constructor(){this._name="GetGroupMemberList"}init(s,r){this._core=s;const{helper:g}=s;g.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>!r.getInstalledSubPlugins().includes(ia)})}getGroupMemberList(s){return mA(this,void 0,void 0,function*(){const r="getGroupMemberList",{groupID:g,offset:u=0,count:E=100,role:m="",filter:D=""}=s,M=Ji.getLocalGroup(g),T=E>100?100:E,P={groupID:g,offset:u,limit:T,memberRoleFilter:Wu.includes(m)?[m]:void 0,memberInfoFilter:Sm};try{const W=yield function(le,bi){return mA(this,void 0,void 0,function*(){const{isCommunity:ki}=bi.common,{groupID:Ot,offset:Li,limit:cs,memberRoleFilter:Re,memberInfoFilter:St}=le,UA={GroupId:Ot,Limit:cs,MemberRoleFilter:Re,MemberInfoFilter:St};return ki({groupID:Ot})?UA.Next=String(Li):UA.Offset=Li,bi.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}.${r} ok, totalMemberCount:${EA} next:${wA}`,{utils:{isArray:xA,isEmpty:LA},common:{isCommunity:SA}}=this._core;if(M&&(M.memberCount=EA),!xA(oA)||oA.length===0)return dn({memberList:[],offset:0},{message:kA});let OA=u+T;SA({groupID:g})&&(OA=LA(wA)?0:wA),oA.lengthD.userID),u=yield(r=this._core.user.userProfile)===null||r===void 0?void 0:r.getUserProfile({userIDList:g}),E=u?.data||[],m=new Map(E.map(D=>[D.userID,D]));return s.forEach(D=>{if(m.has(D.userID)){const{nick:M="",avatar:T=""}=m.get(D.userID);D.nick=M,D.avatar=T}}),s})}_generateGroupMember(s){const r=[];for(let g=0,u=s.length;g50&&(T.warn("getGroupMemberProfile",`${this._name}.${r} userIDList length:${u.length} exceeds limit 50`),u.splice(50));const P=`userIDList length:${u.length} groupID:${g}`;try{const W=yield function(kA,xA){return mA(this,void 0,void 0,function*(){const{groupID:LA,userIDList:SA,memberInfoFilter:OA,memberCustomFieldFilter:qA}=kA,Ie={GroupId:LA,Member_List_Account:SA,MemberInfoFilter:OA,AppDefinedDataFilter_GroupMember:qA};return xA.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_specified_group_member_info",data:Ie})})}({groupID:g,userIDList:u,memberCustomFieldFilter:E,memberInfoFilter:[...Sm]},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:r,code:W?.errorCode,message:W?.errorInfo,moreMessage:P})}})}_convertMemberInfo(s){const r=[];for(let g=0,u=s.length;gD.userID),u=yield(r=this._core.user.userProfile)===null||r===void 0?void 0:r.getUserProfile({userIDList:g}),E=u?.data||[],m=new Map(E.map(D=>[D.userID,D]));return s.forEach(D=>{if(m.has(D.userID)){const{nick:M="",avatar:T=""}=m.get(D.userID);D.nick=M,D.avatar=T}}),s})}_generateGroupMember(s){const r=[];for(let g=0,u=s.length;g({Member_Account:M}));try{const M=yield function(wA,kA){return mA(this,void 0,void 0,function*(){const{groupID:xA,userIDList:LA}=wA,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: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:r,code:M?.errorCode,message:M?.errorInfo})}})}_handleResult(s){const r=[],g=[],u=[],E=[];return s.forEach(m=>{const{Result:D,Member_Account:M}=m;D===Mm?r.push(M):D===vm?g.push(M):D===Rm?u.push(M):D===uD&&E.push(M)}),{failureUserIDList:r,successUserIDList:g,existedUserIDList:u,overLimitUserIDList:E}}},Rd=new class{constructor(){this._name="DeleteGroupMember"}init(s,r){this._core=s;const{helper:g}=s;g.registerApi({apiName:"deleteGroupMember",context:this,matcher:()=>!r.getInstalledSubPlugins().includes(ia)})}deleteGroupMember(s){return mA(this,void 0,void 0,function*(){const r="deleteGroupMember",{groupID:g,userIDList:u}=s,E=Ji.getLocalGroup(g),{helper:m,utils:{isUndefined:D},ssoLog:M}=this._core;if(D(E))throw new m.ChatError({functionName:r,code:TT});u.length>20&&(M.warn("deleteGroupMember",`${this._name}.${r} userIDList length:${u.length} exceeds limit 20`),u.splice(20));try{return yield function(T,P){return mA(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:u},this._core),dn({group:E,userIDList:u},{message:`groupID:${g} userIDList length:${u.length}`})}catch(T){throw new m.ChatError({functionName:r,code:T?.errorCode,message:T?.errorInfo})}})}},Zv=new class{constructor(){this._name="SetGroupMemberMuteTime"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"setGroupMemberMuteTime",context:this})}setGroupMemberMuteTime(s){return mA(this,void 0,void 0,function*(){const{helper:r}=this._core,{groupID:g,userID:u,muteTime:E}=s,m=` groupID:${g} userID:${u} muteTime:${E}`;this._preCheckSettingMuteParams(s);try{yield EB(s,this._core);const D=Ji.getLocalGroup(g),M=new vC({userID:u,muteTime:E});return dn({group:D,member:M},{message:m})}catch(D){throw new r.ChatError({functionName:"setGroupMemberMuteTime",code:D?.errorCode,message:D?.errorInfo,moreMessage:m})}})}_preCheckSettingMuteParams(s){const{userID:r}=s,{store:g,helper:u}=this._core;if(r===g.get("login").userId)throw new u.ChatError({functionName:"setGroupMemberMuteTime",code:fD})}},OQ=new class{constructor(){this._name="SetGroupMemberRole"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"setGroupMemberRole",context:this})}setGroupMemberRole(s){return mA(this,void 0,void 0,function*(){const r="setGroupMemberRole",{helper:g}=this._core,{groupID:u,userID:E,role:m}=s,D=`${this._name}.${r} ok, groupID:${u} userID:${E} role:${m}`;this._preCheckSettingRoleParams(s);try{yield EB(s,this._core);const M=Ji.getLocalGroup(u),T=new vC({userID:E,role:m});return dn({group:M,member:T},{message:D})}catch(M){throw new g.ChatError({functionName:r,code:M?.errorCode,message:M?.errorInfo,moreMessage:D})}})}_preCheckSettingRoleParams(s){var r;const{groupID:g,userID:u,role:E}=s,{store:m,helper:D,OuterConstant:M,common:{isCommunity:T}}=this._core,P=Ji.getLocalGroup(g);if(((r=P?.selfInfo)===null||r===void 0?void 0:r.role)!==M.GRP_MBR_ROLE_OWNER)throw new D.ChatError({functionName:"setGroupMemberRole",code:bT});if(u===m.get("login").userId)throw new D.ChatError({functionName:"setGroupMemberRole",code:Hv});const W=[...Wu];if(T({groupID:g})&&W.push(M.GRP_MBR_ROLE_CUSTOM),!W.includes(E))throw new D.ChatError({functionName:"setGroupMemberRole",code:Nm})}},SD=new class{constructor(){this._name="SetGroupMemberNameCard"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"setGroupMemberNameCard",context:this})}setGroupMemberNameCard(s){return mA(this,void 0,void 0,function*(){var r;const g="setGroupMemberNameCard",{helper:u,common:{getCurrentUserID:E}}=this._core,{groupID:m,userID:D=E(),nameCard:M}=s,T=`${this._name}.${g} ok, groupID:${m} userID:${D} nameCard:${M}`;this._preCheckSettingNameCardParams(s);try{yield EB({groupID:m,userID:D,nameCard:M},this._core);const W=Ji.getLocalGroup(m);D===((r=W?.selfInfo)===null||r===void 0?void 0:r.userID)&&(W.updateSelfInfo({nameCard:M}),Ji.emitGroupListUpdate(),Ji.updateConversationGroupProfile(m));const oA=new vC({userID:D,nameCard:M});return dn({group:W,member:oA},{message:T})}catch(P){throw new u.ChatError({functionName:g,code:P?.errorCode,message:P?.errorInfo,moreMessage:T})}})}_preCheckSettingNameCardParams(s){const{groupID:r}=s,{helper:g}=this._core,u=Ji.getLocalGroup(r);if(Sd(u?.type))throw new g.ChatError({functionName:"setGroupMemberNameCard",code:Gm})}},Um=new class{constructor(){this._name="SetGroupMemberCustomField"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"setGroupMemberCustomField",context:this})}setGroupMemberCustomField(s){return mA(this,void 0,void 0,function*(){const r="setGroupMemberCustomField",{helper:g,common:{getCurrentUserID:u}}=this._core;this._preCheckSettingCustomFiledParams(s);const{groupID:E,userID:m=u(),memberCustomField:D}=s,M=`${this._name}.${r} ok, groupID:${E}userID:${m} memberCustomField:${JSON.stringify(D)}`;try{yield EB({groupID:E,userID:m,memberCustomField:D},this._core);const P=Ji.getLocalGroup(E),W=new vC({userID:m,memberCustomField:D});return dn({group:P,member:W},{message:M})}catch(T){throw new g.ChatError({functionName:r,code:T?.errorCode,message:T?.errorInfo,moreMessage:M})}})}_preCheckSettingCustomFiledParams(s){const{groupID:r}=s,{helper:g}=this._core,u=Ji.getLocalGroup(r);if(Sd(u?.type))throw new g.ChatError({functionName:"setGroupMemberCustomField",code:Gm})}},Xv=new class{init(s,r){s.ssoLog.debug("GroupMember.init"),DD.init(s,r),FQ.init(s),vd.init(s),Rd.init(s,r),Zv.init(s),OQ.init(s),SD.init(s),Um.init(s)}getGroupMemberList(s){return DD.getGroupMemberList(s)}deleteGroupMember(s){return Rd.deleteGroupMember(s)}},OT=new class{init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"getGroupCounters",context:this})}getGroupCounters(s){return mA(this,void 0,void 0,function*(){const r="getGroupCounters";try{km(r,sc);const{groupID:g,keyList:u=[]}=s,{avChatRoomKey:E,lastUpdateTime:m}=nc.getLocalGroupCounters(g);if(!(Date.now()-m>=this._getExpireTime()))return{code:0,data:{counters:nc.getLocalCounters(g,u)}};const D=yield function(P){return mA(this,void 0,void 0,function*(){const{groupID:W,GroupCounterKeys:oA,avChatRoomKey:EA}=P,{common:wA}=Zn.core,kA={GroupId:W,keyList:oA,BytesKey:EA};return wA.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_counter",data:kA})})}({groupID:g,keyList:u,avChatRoomKey:E}),{GroupCounter:M=[],GroupCounterSeq:T}=D;return nc.updateLocalGroupCounters({groupID:g,counterList:M,groupCounterSeq:T}),{code:0,data:{counters:nc.getLocalCounters(g,u)}}}catch(g){MC(r,g)}})}_getExpireTime(){const{store:s,utils:{isUndefined:r}}=this._core,g=s.get("cloudConfig")||{},{grp_counter_expire_time:u}=g;return r(u)?3e4:Number(u)}},Fm=new class{init(s){const{helper:r}=s;r.registerApi({apiName:"setGroupCounters",context:this}),r.registerApi({apiName:"increaseGroupCounter",context:this}),r.registerApi({apiName:"decreaseGroupCounter",context:this})}setGroupCounters(s){return mA(this,void 0,void 0,function*(){return this._handleCounterOperation(ju,s)})}increaseGroupCounter(s){return mA(this,void 0,void 0,function*(){return this._handleCounterOperation(Dm,s)})}decreaseGroupCounter(s){return mA(this,void 0,void 0,function*(){return this._handleCounterOperation(_i,s)})}_handleCounterOperation(s,r){return mA(this,void 0,void 0,function*(){const g=`${s}GroupCounter`;try{km(g,sc);const{groupID:u,key:E,value:m=0}=r,{avChatRoomKey:D}=nc.getLocalGroupCounters(u),M=s===ju?this._convertObjectToList(r.counters):[{Key:E,Value:m}],T=yield this._updateGroupCounters({groupID:u,counterList:M,avChatRoomKey:D,mode:s});return nc.setGroupCounters(u,T),{code:0,data:{counters:T}}}catch(u){MC(g,u)}})}_updateGroupCounters(s){return mA(this,void 0,void 0,function*(){const r=yield function(E){const{groupID:m,counterList:D,mode:M,avChatRoomKey:T}=E,{common:P}=Zn.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=[]}=r,u={};return g.forEach(E=>{const{Key:m,Value:D=0}=E;u[m]=D}),u})}_convertObjectToList(s){return Object.entries(s).map(([r,g])=>({Key:r,Value:g||0}))}},dB=new class{init(s){this._core=s,OT.init(s),Fm.init(s)}isGroupCounterUpdated(s){const{elements:{groupCounterInfo:r}}=s,{utils:{isEmpty:g}}=this._core;return!g(r)}handleGroupCounterUpdated(s){const{to:r,elements:{groupCounterInfo:g}}=s;g.forEach(u=>{const{type:E,groupCounterSeq:m,counterList:D=[]}=u;E!==ri&&E!==on||this._processAndNotifyCounterUpdate(r,m,D),E===Do&&nc.deleteLocalGroupCounters({groupID:r,groupCounterSeq:m,counterList:D})})}_processAndNotifyCounterUpdate(s,r,g){const{OuterEvent:u,notificationCenter:E}=this._core;nc.updateLocalGroupCounters({groupID:s,groupCounterSeq:r,counterList:g}),g.forEach(({Key:m,Value:D=0})=>{E.emitOuterEvent(u.GROUP_COUNTER_UPDATED,{name:u.GROUP_COUNTER_UPDATED,data:{groupID:s,key:m,value:D}})})}reset(){nc.reset()}},Om=new class{constructor(){this._name="InitGroupAttributes"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"initGroupAttributes",context:this})}initGroupAttributes(s){return mA(this,void 0,void 0,function*(){const{groupID:r,groupAttributes:g}=s,{serverMainSequence:u,avChatRoomKey:E}=zs.getGroupAttributesCache(r),m=zs.convertKeyValueMapToList(g);try{const D=yield function(W,oA){return mA(this,void 0,void 0,function*(){const{groupID:EA,mainSequence:wA,groupAttributeList:kA,avChatRoomKey:xA}=W,LA={GroupId:EA,AttrMainSeq:wA,GroupAttr:kA,BytesKey:xA,AttrControl:["RaceConflict"]};return oA.common.buildAndSendPacket({servcmd:"group_open_http_svc.set_group_attr",data:LA})})}({groupID:r,avChatRoomKey:E,groupAttributeList:m,mainSequence:u},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 zs.saveGroupAttributesCacheValuesCopy(r),zs.refreshGroupAttributesCache({groupID:r,serverMainSequence:M,groupAttributeList:P,operation:ED}),zs.emitGroupAttributesUpdated(r),dn({groupAttributes:g},{message:` groupID:${r} serverMainSequence:${M}`})}catch(D){throw new this._core.helper.ChatError({functionName:"initGroupAttributes",code:D?.errorCode,message:D?.errorInfo})}})}},PT=new class{constructor(){this._name="SetGroupAttributes"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"setGroupAttributes",context:this}),r.registerExperimentalAPI("setRichStatus",this)}setGroupAttributes(s){return mA(this,void 0,void 0,function*(){const{groupID:r,groupAttributes:g,richStatusMode:u}=s,{serverMainSequence:E,avChatRoomKey:m,values:D}=zs.getGroupAttributesCache(r),M=zs.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 mA(this,void 0,void 0,function*(){const{groupID:kA,mainSequence:xA,groupAttributeList:LA,avChatRoomKey:SA,richStatusMode:OA}=EA,qA={GroupId:kA,AttrMainSeq:xA,GroupAttr:LA,BytesKey:SA,AttrControl:["RaceConflict"],AllowRoomEngineOpt:OA};return wA.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_attr",data:qA})})}({groupID:r,avChatRoomKey:m,groupAttributeList:M,mainSequence:E,richStatusMode:u},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 zs.saveGroupAttributesCacheValuesCopy(r),zs.refreshGroupAttributesCache({groupID:r,serverMainSequence:P,groupAttributeList:oA,operation:xv}),zs.emitGroupAttributesUpdated(r),dn({groupAttributes:g},{message:` groupID:${r} 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:r,richStatus:g}=s;return this.setGroupAttributes({groupID:r,groupAttributes:g,richStatusMode:!0})})}},MD=new class{constructor(){this._name="DeleteGroupAttributes"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"deleteGroupAttributes",context:this}),r.registerExperimentalAPI("deleteRichStatus",this)}deleteGroupAttributes(s){return mA(this,void 0,void 0,function*(){const r="deleteGroupAttributes",{groupID:g,keyList:u=[],richStatusMode:E}=s;try{let m;m=u.length===0?yield this._clearGroupAttributes(g,{richStatusMode:E}):yield this._deleteGroupAttributes(g,{keyList:u,richStatusMode:E});const{resultList:D,serverMainSequence:M,operation:T,groupAttributeList:P}=m||{},W=`${this._name}.${r} 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:r,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,r){return mA(this,void 0,void 0,function*(){const{serverMainSequence:g,avChatRoomKey:u,values:E}=zs.getGroupAttributesCache(s),{keyList:m,richStatusMode:D}=r,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 mA(this,void 0,void 0,function*(){const{groupID:wA,mainSequence:kA,groupAttributeList:xA,avChatRoomKey:LA,richStatusMode:SA}=oA,OA={GroupId:wA,AttrMainSeq:kA,GroupAttr:xA,BytesKey:LA,AttrControl:["RaceConflict"],AllowRoomEngineOpt:SA};return EA.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_attr",data:OA})})}({groupID:s,avChatRoomKey:u,groupAttributeList:T,mainSequence:g,richStatusMode:D},this._core),{AttrMainSeq:W}=P||{};return{resultList:M,serverMainSequence:W,groupAttributeList:T,operation:CD}})}_clearGroupAttributes(s,r){return mA(this,void 0,void 0,function*(){const{serverMainSequence:g,avChatRoomKey:u,values:E}=zs.getGroupAttributesCache(s),{richStatusMode:m}=r||{},D=[...E.keys()],M=yield function(P,W){return mA(this,void 0,void 0,function*(){const{groupID:oA,mainSequence:EA,avChatRoomKey:wA,richStatusMode:kA}=P,xA={GroupId:oA,AttrMainSeq:EA,BytesKey:wA,AttrControl:["RaceConflict"],AllowRoomEngineOpt:kA};return W.common.buildAndSendPacket({servcmd:"group_open_http_svc.clear_group_attr",data:xA})})}({groupID:s,avChatRoomKey:u,mainSequence:g,richStatusMode:m},this._core),{AttrMainSeq:T}=M||{};return{resultList:D,serverMainSequence:T,operation:dD}})}},vD=new class{constructor(){this._name="GetGroupAttributes"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"getGroupAttributes",context:this}),r.registerExperimentalAPI("getRichStatus",this,"getGroupAttributes")}getGroupAttributes(s){return mA(this,void 0,void 0,function*(){const{groupID:r}=s,{avChatRoomKey:g,lastUpdateTime:u,localMainSequence:E,serverMainSequence:m}=zs.getGroupAttributesCache(r),{helper:{ChatError:D}}=this._core,M=`groupID:${r} localMainSequence:${E} serverMainSequence:${m} keyList:${s.keyList}`;if(Date.now()-u>=3e4||E{const{key:oA,value:EA,seq:wA}=W;return{key:oA,value:EA,sequence:wA}});return zs.refreshGroupAttributesCache({groupID:u,serverMainSequence:M,groupAttributeList:P,operation:Yv}),{serverGroupAttributeList:T}})}},PQ=new class{init(s){s.ssoLog.debug("GroupAttribute.init"),Om.init(s),PT.init(s),MD.init(s),vD.init(s),zs.init(s)}isGroupAttributesUpdated(s){return zs.isGroupAttributesUpdated(s)}handleGroupAttributesUpdated(s){const{to:r,elements:{newGroupProfile:g}}=s,{groupAttributeOption:u}=g,{serverMainSequence:E,withChangedAttributeInfo:m}=u,{localMainSequence:D}=zs.getGroupAttributesCache(r),M=E-D;if(console.log(`GroupAttribute.handleGroupAttributesUpdated groupID:${r} withChangedAttributeInfo:${m} diffSequence:${M}`),M!==0)if(zs.saveGroupAttributesCacheValuesCopy(r),m!==1||M!==1){if(zs.hasGroupAttributesCache(r)){const{avChatRoomKey:T}=zs.getGroupAttributesCache(r);vD.getGroupAttributesFromServer({groupID:r,avChatRoomKey:T}).then(()=>{zs.emitGroupAttributesUpdated(r)}).catch(()=>{})}}else zs.handleGroupAttributesUpdated({groupID:r,groupAttributeOption:u})}reset(){zs.reset()}};function JE(s,r="tips"){const{ClientSeq:g,From_Account:u,MsgClientTime:E,MsgPriority:m,MsgRandom:D,MsgSeq:M,MsgTimeStamp:T,TinyId:P,ToGroupId:W,GroupInfo:oA,MsgBody:EA}=s,wA=function(kA){const{GroupCode:xA,GroupId:LA,GroupName:SA,GroupType:OA,MsgFrom_AccountExtraInfo:qA,From_Account:Ie,To_Account:le}=kA;return{groupCode:xA,groupID:LA,groupName:SA,type:OA,messageFromAccountExtraInformation:qA,from:Ie,to:le}}(oA);return{clientSequence:g,from:u,clientTime:E,priority:m,random:D,sequence:M,time:T,tinyID:P,to:W,groupProfile:wA,elements:r==="tips"?Xu(EA):Bh(EA)}}function Xu(s){const r={};return Object.keys(s).forEach(g=>{var u,E;switch(g){case"MemberNum":r.memberCount=s[g];break;case"OpType":r.operationType=s[g];break;case"Operator_Account":r.operatorID=s[g];break;case"List_Account":r.userIDList=s[g];break;case"MsgMemberExtraInfo":r.memberInfoList=(u=s[g])===null||u===void 0?void 0:u.map(m=>RD(m));break;case"MsgOperatorMemberExtraInfo":r.operatorInfo=RD(s[g]);break;case"MsgGroupNewInfo":r.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,xA=kA.map(LA=>{const{Key:SA,Val:OA,SubKeySeq:qA}=LA;return{key:SA,value:OA,sequence:qA}});return{changedKeyList:W,groupAttributeList:xA,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=LT[m[M]]||m[M]}var T}),D}(s[g]);break;case"MsgMemberInfo":r.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":r.onlineMemberInfo=function(m){const{ExpireTime:D,OnlineMemberNum:M}=m;return{expireTime:D,onlineMemberNum:M}}(s[g]);break;case"GroupCounterInfo":r.groupCounterInfo=function(m){return m.map(D=>{const{GroupCounterSeq:M,GroupCounter:T,Type:P}=D;return{type:P,groupCounterSeq:M,counterList:T}})}(s[g])}}),r}function RD(s){const{ImageUrl:r,NickName:g,Role:u,UserId:E}=s;return{avatar:r,nick:g,role:u,userID:E}}function Bh(s){const r={};return Object.keys(s).forEach(g=>{switch(g){case"MsgKey":r.messageKey=s[g];break;case"Operator_Account":r.operatorID=s[g];break;case"ReportType":r.operationType=s[g];break;case"Authentication":r.authentication=s[g];break;case"MsgFlag":r.messageRemindType=s[g];break;case"UserDefinedField":r.userDefinedField=s[g];break;case"RemarkInfo":r.remarkInfo=s[g];break;case"BanDuration":r.duration=s[g];break;case"MuteTime":r.muteTime=s[g];break;case"MsgMemberExtraInfoList":r.inviteeInfoList=(u=s[g]||[])==null?void 0:u.map(E=>{const{UserId:m,ImageUrl:D,NickName:M}=E;return{userID:m,avatar:D,nick:M}});break;case"MemberList_Account":r.inviteeList=s[g]}var u}),r}class Pm{constructor(r){this.type=Zn.core.OuterConstant.MSG_GRP_TIP,this.content={},this._initContent(r)}static parseServerPushElement(r){const g=Xu(r);return new Pm(g)}_initContent(r){Object.keys(r).forEach(g=>{switch(g){case"groupProfile":this._initGroupProfile(r[g]);break;case"operatorInfo":this._initOperatorInfo(r[g]);break;case"memberInfoList":case"msgMemberInfo":this._updateMemberList(r[g]);break;case"newGroupProfile":this._initNewGroupProfile(r[g]);break;case"memberExtraInfo":case"remarkInfo":case"onlineMemberInfo":break;default:this.content[g]=r[g]}}),this.content.userIDList||(this.content.userIDList=[this.content.operatorID])}_initGroupProfile(r){this.content.groupProfile={};const g=Object.keys(r);for(let u=0;u{r.forEach(u=>{g.userID===u.userID&&Object.assign(g,u)})}):this.content.memberList=r}_initNewGroupProfile(r){this.content.newGroupProfile={};const g=Object.keys(r);for(let u=0;u0&&this._handleGroupTipMessage(g),{conversationUpdateFieldList:u,messageList:g}}_emitGroupTipsEvent(s){var r;const{constants:{WORKFLOW_STEP:g}}=this._core,{messageList:u=[]}=((r=s?.result)===null||r===void 0?void 0:r[g.HANDLE_GROUP_TIPS_NOTIFICATION])||{};if(u.length>0){const{notificationCenter:E,OuterEvent:m}=this._core;E.emitOuterEvent(m.MESSAGE_RECEIVED,{name:m.MESSAGE_RECEIVED,data:u})}}_handleGroupTips(s,r=!0){const{Event:g,GroupTips:u}=s,E=new Map,m=[],D=[];for(let M=0,T=u.length;M{const{operationType:u}=g.payload;switch(u){case r.JOINED:this._handleNewMemberJoined(g);break;case r.QUITTED:this._handleMemberQuitted(g);break;case r.KICKED:this._handleMemberKicked(g);break;case r.GROUP_PROFILE_UPDATED:this._handleGroupProfileUpdated(g);break;case r.ADMIN_SET:this._handleMemberGrantAdmin(g);break;case r.ADMIN_CANCELED:this._handleMemberRevokeAdmin(g)}})}_handleNewMemberJoined(s){this._handleGroupMemberCountUpdated(s)}_handleMemberQuitted(s){this._handleGroupMemberCountUpdated(s)}_handleMemberKicked(s){this._handleGroupMemberCountUpdated(s)}_handleGroupProfileUpdated(s){var r;const{newGroupProfile:g,groupProfile:u,operatorInfo:E}=s.payload,{groupID:m}=u,D=Ji.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])?bm(D[T],g[T]):D[T]=g[T];break;default:D[T]=g[T]}});const{utils:{isUndefined:M}}=this._core;M(E)||((r=D?.selfInfo)===null||r===void 0?void 0:r.userID)!==E.userID||Object.keys(E).forEach(T=>{T==="nameCard"&&D.updateSelfInfo({nameCard:E[T]}),T==="role"&&this._updateSelfRole(D,E[T])}),Ji.emitGroupListUpdate(),Ji.updateConversationGroupProfile(m)}_handleGroupOwnerChanged(s,r){const{common:g,OuterConstant:u}=this._core,E=Ji.getLocalGroup(s),m=g.getCurrentUserID(),{ownerID:D}=r;m===D&&E.updateGroup({ownerID:D,selfInfo:{role:u.GRP_MBR_ROLE_OWNER}})}_updateSelfRole(s,r){const{OuterConstant:g}=this._core;let u=g.GRP_MBR_ROLE_MEMBER;r===MT?u=g.GRP_MBR_ROLE_OWNER:r===BD&&(u=g.GRP_MBR_ROLE_ADMIN),s.updateSelfInfo({role:u})}_handleGroupMemberCountUpdated(s){const{memberCount:r,groupProfile:{groupID:g}}=s.payload,u=Ji.getLocalGroup(g),{utils:{isNumber:E}}=this._core;u&&E(r)&&u.memberCount!==r&&(u.memberCount=r,Ji.emitGroupListUpdate(),Ji.updateConversationGroupProfile(g))}_handleGroupTipsRecover(s){const{utils:{isArray:r}}=this._core,{groupTipList:g}=s?.result||{};r(g)&&g.forEach(u=>{const{messageList:E}=this._handleGroupTips({Event:u.Event,GroupTips:[u]},!1);this._handleGroupTipMessage(E)})}_handleMemberGrantAdmin(s){const{OuterConstant:r}=this._core,{groupProfile:g,userIDList:u}=s.payload,E=this._core.common.getCurrentUserID(),{groupID:m}=g,D=Ji.getLocalGroup(m);D&&u.includes(E)&&(D.updateSelfInfo({role:r.GRP_MBR_ROLE_ADMIN}),Ji.emitGroupListUpdate(),Ji.updateConversationGroupProfile(m))}_handleMemberRevokeAdmin(s){const{OuterConstant:r}=this._core,{groupProfile:g,userIDList:u}=s.payload,E=this._core.common.getCurrentUserID(),{groupID:m}=g,D=Ji.getLocalGroup(m);D&&u.includes(E)&&(D.updateSelfInfo({role:r.GRP_MBR_ROLE_MEMBER}),Ji.emitGroupListUpdate(),Ji.updateConversationGroupProfile(m))}};class xQ{constructor(r){this.type=Zn.core.OuterConstant.MSG_GRP_SYS_NOTICE,this.content={},this._initContent(r)}static parseServerPushElement(r){const g=Bh(r);return new xQ(g)}_initContent(r){Object.keys(r).forEach(g=>{switch(g){case"remarkInfo":this.content.handleMessage=r[g];break;case"groupProfile":this._initGroupProfile(r[g]);break;case"memberInfoList":break;default:this.content[g]=r[g]}})}_initGroupProfile(r){this.content.groupProfile={};const g=Object.keys(r);for(let u=0;u0&&this._handleGroupSysTemMessage(g,E),g===!0&&E.length>0&&m.emitOuterEvent(D.MESSAGE_RECEIVED,{name:D.MESSAGE_RECEIVED,data:E})}_handleGroupSystemNotification(s,r){const g=[];let u={};for(let E=0;E0?[u]:[],messageList:g}}_assembleMessage(s){const{message:{messageFactory:r},OuterConstant:g,utils:{randomInt:u}}=this._core;s.flow="in",s.conversationType=g.CONV_SYSTEM,s.conversationSubType=s.groupProfile.type,s.conversationID=g.CONV_SYSTEM;const E=r.createMessage(s),m=new xQ(Object.assign(Object.assign({},s.elements),{groupProfile:Object.assign({},s.groupProfile)}));E.setElement(m),E.isSystemMessage=!0;const D=E.sequence===1&&E.random===1,M=E.sequence===2&&E.random===2;return(D||M)&&(E.sequence=u(),E.random=u(),E.generateMessageID()),E}_handleConversationOptions(s,r){const{OuterConstant:g}=this._core,u={conversationID:g.CONV_SYSTEM,unreadCount:0,type:g.CONV_SYSTEM,subType:s.conversationSubType,lastMessage:null};return r&&u.unreadCount++,u}_handleGroupSysTemMessage(s,r){s&&r.forEach(g=>{const{operationType:u}=g.payload;switch(u){case RT:this._handleGroupJoinResult(g);break;case Jv:this._handleMemberKicked(g);break;case wT:this._handleGroupDismissed(g);break;case _T:this._handleGroupInvitedResult(g);break;case QD:this._handleGroupQuitResult(g);break;case bQ:this._handleMessageRemindTypeSynced(g);break;case wm:this._handleAVChatRoomMemberBanned(g)}})}_handleGroupJoinResult(s){const{groupProfile:r}=s.payload,{groupID:g,type:u}=r,E=Ji.hasLocalGroup(g);this._core.ssoLog.debug("_handleGroupJoinResult",` groupID:${g} type:${u} hasLocalGroup:${E}`),E||Sd(u)||(Ji.updateLocalGroup([Object.assign({},r)]),Ji.emitGroupListUpdate())}_handleMemberKicked(s){const{groupProfile:{groupID:r,type:g}}=s.payload;Ji.hasLocalGroup(r)&&this._deleteLocalGroup(r,g),this._updateConversationProfile(r,{unreadCount:0})}_handleGroupDismissed(s){const{groupProfile:{groupID:r,type:g}}=s.payload;Ji.hasLocalGroup(r)&&this._deleteLocalGroup(r,g),this._updateConversationProfile(r,{unreadCount:0})}_handleGroupInvitedResult(s){const{groupProfile:r}=s.payload,{groupID:g}=r,u=Ji.hasLocalGroup(g);this._core.ssoLog.debug("_handleGroupInvitedResult",` groupID:${g} hasLocalGroup:${u}`),u||xl.getGroupProfile({groupID:g}).then(E=>{const{data:{group:m}}=E;Ji.updateLocalGroup([Object.assign({},m)]),Ji.emitGroupListUpdate()})}_handleGroupQuitResult(s){const{groupProfile:{groupID:r,type:g}}=s.payload,u=Ji.hasLocalGroup(r);this._core.ssoLog.debug("_handleGroupQuitResult",` groupID:${r} type:${g} hasLocalGroup:${u}`),u&&this._deleteLocalGroup(r,g),this._updateConversationProfile(r,{unreadCount:0})}_handleMessageRemindTypeSynced(s){const{groupProfile:{groupID:r},messageRemindType:g}=s.payload;this._updateConversationProfile(r,{messageRemindType:g})}_handleAVChatRoomMemberBanned(s){const{groupProfile:{groupID:r,type:g}}=s.payload;this._deleteLocalGroup(r,g)}_deleteLocalGroup(s,r){if(Sd(r)){const{appStore:{conversationStore:g},OuterConstant:{CONV_GROUP:u}}=this._core;g.deleteConversation(`${u}${s}`)}Ji.deleteLocalGroup(s),Ji.emitGroupListUpdate()}_updateConversationProfile(s,r){const{appStore:{conversationStore:g},OuterConstant:{CONV_GROUP:u}}=this._core,E=`${u}${s}`;g.getConversation(E)&&g.updateConversation(E,r)}},wD=new class{init(s){this._core=s,s.ssoLog.debug("GroupNotificationHandler.init"),$v.init(s),AR.init(s);const{notificationCenter:r,InnerEvent:g}=s,{InnerEventSubType:u}=r;r.subscribeInnerEvent(g.MESSAGE_PUSH,u.GROUP_TIPS_NOTIFICATION,this._onNewGroupTipsNotification,this),r.subscribeInnerEvent(g.MESSAGE_PUSH,u.GROUP_SYSTEM_NOTIFICATION,this._onNewGroupSystemNotification,this),r.subscribeInnerEvent(g.DESTROY,this._dispose,this)}_onNewGroupTipsNotification(s){const{common:{workflowManager:r},constants:{WORKFLOW_NAME:g}}=this._core;r.executeWorkflow(g.RECEIVE_GROUP_TIPS_NOTIFICATION,s)}_onNewGroupSystemNotification(s){AR.onNewGroupSystemNotification(s)}_dispose(){const{notificationCenter:s,InnerEvent:r}=this._core,{InnerEventSubType:g}=s;s.unSubscribeInnerEvent(r.MESSAGE_PUSH,g.GROUP_TIPS_NOTIFICATION,this._onNewGroupTipsNotification,this),s.unSubscribeInnerEvent(r.MESSAGE_PUSH,g.GROUP_SYSTEM_NOTIFICATION,this._onNewGroupSystemNotification,this)}};const vn={required:!0,rules:["string"],allowEmpty:!1},YQ={required:!0,rules:["number"],allowEmpty:!1},wd={required:!0,rules:["array"],allowEmpty:!1},_D={required:!0,rules:["object"],allowEmpty:!1},xT={createGroup:{name:vn,type:vn},dismissGroup:[Object.assign({key:"groupID"},vn)],joinGroup:{groupID:vn,applyMessage:{required:!1,rules:["string"],allowEmpty:!0}},quitGroup:[Object.assign({key:"groupID"},vn)],searchGroupByID:[Object.assign({key:"groupID"},vn)],getGroupProfile:{groupID:vn,groupCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},updateGroupProfile:{groupID:vn,muteAllMembers:{required:!1,rules:["boolean"],allowEmpty:!1}},changeGroupOwner:{groupID:vn,newOwnerID:vn},getGroupOnlineMemberCount:[Object.assign({key:"groupID"},vn)],handleGroupApplication:{handleAction:vn},getGroupMemberList:{groupID:vn},getGroupMemberProfile:{groupID:vn,userIDList:wd,memberCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},addGroupMember:{groupID:vn,userIDList:wd},deleteGroupMember:{groupID:vn,userIDList:wd},setGroupMemberMuteTime:{groupID:vn,userID:vn,muteTime:Object.assign(Object.assign({},YQ),{customValidator:s=>!(s<0)||"muteTime must be a non-negative number."})},setGroupMemberRole:{groupID:vn,userID:vn,role:vn},setGroupMemberNameCard:{groupID:vn,userID:{required:!1,rules:["string"],allowEmpty:!1},nameCard:vn},setGroupMemberCustomField:{groupID:vn,userID:{required:!1,rules:["string"],allowEmpty:!1},memberCustomField:wd},markGroupMemberList:{groupID:vn,markType:Object.assign(Object.assign({},YQ),{customValidator:s=>!(s<1e3)||"markType must be greater than or equal to 1000."}),enableMark:{required:!0,rules:["boolean"],allowEmpty:!1},userIDList:wd},initGroupAttributes:{groupID:vn,groupAttributes:_D},setGroupAttributes:{groupID:vn,groupAttributes:_D},deleteGroupAttributes:{groupID:vn,keyList:Object.assign(Object.assign({},wd),{allowEmpty:!0})},getGroupAttributes:{groupID:vn,keyList:Object.assign(Object.assign({},wd),{allowEmpty:!0})},getGroupCounters:{groupID:vn,keyList:{required:!1,rules:["array"],allowEmpty:!0}},setGroupCounters:{groupID:vn,counters:_D},increaseGroupCounter:{groupID:vn,key:vn,value:YQ},decreaseGroupCounter:{groupID:vn,key:vn,value:YQ}},YT={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 VT=new class{constructor(){this._installedSubPlugins=[],this.groupDataHandler=Ji,this.groupAction=UQ,this.groupAttribute=PQ,this.groupMember=Xv,this.groupCounter=dB,this.name="Group"}install(s,r=[]){this._core=s,Zn.init(s),Ji.init(s),UQ.init(s,this),Xv.init(s,this),yD.init(s),dB.init(s),PQ.init(s),wD.init(s),s.helper.registerValidateConfig({auth:YT,params:xT}),this._installSubPlugins(r);const{notificationCenter:g,InnerEvent:u}=s;g.subscribeInnerEvent(u.LOGOUT,this._reset,this),g.subscribeInnerEvent(u.DESTROY,this._dispose,this)}getInstalledSubPlugins(){return this._installedSubPlugins}_installSubPlugins(s){const{utils:{isArray:r}}=this._core;s&&r(s)&&s.forEach(g=>{var u;this._installedSubPlugins.includes(g.name)||((u=g.install)===null||u===void 0||u.call(g,this._core,this),this._installedSubPlugins.push(g.name))})}_reset(){Ji.reset(),PQ.reset(),dB.reset()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:r}=this._core;s.unSubscribeInnerEvent(r.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this)}};const CB=new class{init(s){this.core=s}},eR="AV_MBR_LIST",JT="AV_BAN_MBR",HE={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},Qh={GROUP_DISMISSED:5,QUIT_GROUP:8,AVCHATROOM_MEMBER_BANNED:21},TD=60,ND=2603,HT=2686,qT=2688,VQ=3122;class tR{constructor(r){const{core:g,manager:u,groupID:E,getRequestParams:m,onSuccess:D,onFail:M}=r;this._name="Polling",this._core=g,this._manager=u,this._timeoutID=-1,this._isRunning=!1,this._groupID=E,this._getRequestParams=m,this._onSuccess=D,this._onFail=M}start(){this._isRunning=!0,this._request(),console.log(`${this._name}.start pollingInterval:${this._manager.getCurrentPollingInterval(this._groupID)}`)}isRunning(){return this._isRunning}_request(){return mA(this,void 0,void 0,function*(){try{const r=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})})}(r,this._core);this._onSuccess(this._groupID,g);const u=this._manager.getCurrentPollingInterval(this._groupID);this._runNextPolling(u)}catch(r){this._onFail(this._groupID,r),this._runNextPolling(2e3)}})}_runNextPolling(r){this.isRunning()&&(this._timeoutID>-1&&clearTimeout(this._timeoutID),this._timeoutID=setTimeout(this._request.bind(this),r))}stop(){console.log(`${this._name}.stop timerID:${this._timeoutID}`),this._timeoutID>-1&&(clearTimeout(this._timeoutID),this._timeoutID=-1),this._isRunning=!1}}class ph{constructor(r){this._maxLength=r,this._map=new Map}set(r){var g;if(this._map.size>=this._maxLength){const u=((g=this._map.entries().next().value)===null||g===void 0?void 0:g[0])||"";this._map.delete(u)}this._map.set(r,1)}has(r){return this._map.has(r)}delete(r){this.has(r)&&this._map.delete(r)}clear(){this._map.clear()}}const $u=s=>s===HE.GROUP_TIPS_HAS_NO_ROAMING||s===HE.GROUP_TIPS_HAS_ROAMING,JQ=s=>s===HE.GROUP_SYSTEM_MESSAGE;function xm(s){const r=function(g){const{E:u,MCT:E,MR:m,MP:D,MTS:M,GId:T,MS:P,CCD:W,F_Account:oA,IsSys:EA,GInf:wA,MsgBody:kA}=g,xA=So(g,["E","MCT","MR","MP","MTS","GId","MS","CCD","F_Account","IsSys","GInf","MsgBody"]);return Object.assign({Event:u,MsgClientTime:E,MsgRandom:m,MsgPriority:D,MsgTimeStamp:M,ToGroupId:T,MsgSeq:P,CloudCustomData:W,From_Account:oA,IsSystemMsg:EA,GroupInfo:GD(wA),MsgBody:KT(kA)},xA)}(s);return function(g){const{Event:u}=g;($u(u)||JQ(u))&&(g.From_Account=g.From_Account||"@TIM#SYSTEM"),E=u,(E===HE.BROADCAST_MESSAGE||(m=>m===HE.NORMAL_MESSAGE)(u))&&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;$u(u)&&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),JQ(u)&&function(m){const{MsgOperatorMemberExtraInfo:D={},Operator_Account:M}=m.MsgBody||{};m.MsgBody.MsgMemberExtraInfo=Object.assign({UserId:M,ImageUrl:"",NickName:""},D),m.MsgBody=Object.assign({Authentication:"",RemarkInfo:"",MsgKey:1e3*m.MsgTimeStamp},m.MsgBody),m.MsgBody=Object.keys(m.MsgBody).filter(T=>T!=="MsgOperatorMemberExtraInfo").reduce((T,P)=>Object.assign(Object.assign({},T),{[P]:m.MsgBody[P]}),{})}(g)}(r),r}function GD(s){const r=s||{},{GN:g,GT:u,F_Hd:E,F_NN:m,F_Ll:D}=r,M=So(r,["GN","GT","F_Hd","F_NN","F_Ll"]),T=Object.assign({GroupName:g,GroupType:u},M);return E&&(T.From_AccountHeadurl=E),m&&(T.From_AccountNick=m),D&&(T.From_AccountLevel=D),T}function KT(s){let r=s;Array.isArray(s)||(r=[s]);const g=r.map(u=>{const{O_Account:E,Opt:m,L_Account:D,RT:M,UDF:T,OpInf:P,OnlineInf:W,MsgMemberExtraInfo:oA}=u,EA=So(u,["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:xA,NN:LA}=kA,SA=So(kA,["Img","NN"]);return Object.assign({ImageUrl:xA,NickName:LA},SA)}(P)),oA&&(wA.MsgMemberExtraInfo=function(kA){return kA?.map(xA=>{const{Img:LA,NN:SA}=xA,OA=So(xA,["Img","NN"]);return Object.assign({ImageUrl:LA,NickName:SA},OA)})}(oA)),W&&(wA.OnlineMemberInfo=function(kA){const{ET:xA,Num:LA}=kA;return{ExpireTime:xA,OnlineMemberNum:LA}}(W)),wA});return Array.isArray(s)?g:g[0]}var mh=new class{constructor(){this._name="MessageParser",this._sequenceList=new ph(200),this._messageIDList=new ph(100),this._broadcastMessageIDMap=new Map,this._reportMessageStackedCount=0}init(s,r){this._core=s,this._avChatRoomHandler=r}onMessageReceived(s,r,g=!1){this._sortServerMessageList({groupID:s,serverMessageList:r,isHistoryMessage:g});const u=this._handleMessageList(s,r);if(u.length===0)return;if(!g){const{appStore:{conversationStore:T},OuterConstant:{CONV_GROUP:P},common:{buildLastMessage:W}}=this._core,oA=W(u[u.length-1]);T.updateConversation(`${P}${s}`,{lastMessage:oA})}this._checkMessageStacked(u);const E=u.filter(T=>T.isModified===!0),m=u.filter(T=>T.isModified===!1),{OuterEvent:{MESSAGE_RECEIVED:D,MESSAGE_MODIFIED:M}}=this._core;E.length>0&&this._emitEvent({name:M,data:E}),m.length>0&&this._emitEvent({name:D,data:m})}_sortServerMessageList(s){const{groupID:r,serverMessageList:g,isHistoryMessage:u}=s;let E=[];this._avChatRoomHandler.isPollingSimplifiedMessage()&&!u?(g.sort((m,D)=>m.MS-D.MS),E=g.map(m=>m.MS)):(g.sort((m,D)=>m.MsgSeq-D.MsgSeq),E=g.map(m=>m.MsgSeq)),console.log(`${this._name}._sortServerMessageList groupID:${r} count:${E.length} sequenceList:${E}`),E.length=0}_handleMessageList(s,r){var g;const{message:{messageDataHandler:u,messageHelper:E}}=this._core,m=this._avChatRoomHandler.isPollingSimplifiedMessage(),D=[],M=r.length;for(let T=0;Tg===HE.MESSAGE_REVOKED)(r)?(this._handleMessageRevoked(s),null):(g=>g===HE.LIVE_CUSTOM_DATA)(r)?(this._onLiveCustomData(s),null):(g=>g===HE.MESSAGE_REACTION)(r)?null:s:(console.warn(`${this._name}.onMessageReceived unknown event:${r}`),null)}_createMessage(s){const{message:{messageFactory:r},OuterConstant:g}=this._core;let u=g.CONV_GROUP;s.elements.type===g.MSG_GRP_SYS_NOTICE&&(u=g.CONV_SYSTEM);const E=!!s.isSystemMessage,m=r.createMessage(Object.assign(Object.assign({},s),{conversationType:u,isSystemMessage:E,flow:"in"}));return m.setElement(s.elements),m}_filterDuplicateMessage(s){const{common:r}=this._core;if(!r.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:r,OuterEvent:{MESSAGE_REVOKED:g}}=this._core,{ToGroupId:u,MsgBody:{RevokeMsgList:E},RevokerInfo:{Revoker_Account:m,Reason:D=""}}=s,M=[];E.forEach(T=>{const{TinyId:P,MsgClientTime:W,Random:oA,MsgSeq:EA}=T,wA={conversationID:`${r.CONV_GROUP}${u}`,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:r}}=this._core,{ToGroupId:g,MsgSeq:u,MsgTimeStamp:E,MsgBody:m}=s,D=m?.Content||m?.MsgContent||"";this._emitEvent({name:r,data:D}),console.log(`${this._name}._onLiveCustomData groupID:${g} sequence:${u} time:${E} data:${D}`)}_onGroupDismissed(s){this._avChatRoomHandler.reset(s)}_checkMessageStacked(s){const{length:r}=s;if(r>=100&&this._reportMessageStackedCount<5){const g=this._avChatRoomHandler.getJoinedGroups();this._core.ssoLog.info("MessageStacked",`count:${r} groupID:${g.join(",")}`),this._reportMessageStackedCount+=1}}_emitEvent(s){this._core.notificationCenter.emitOuterEvent(s.name,s)}onBroadcastMessageReceived(s){const{message:{messageHelper:r},OuterEvent:{MESSAGE_RECEIVED:g}}=this._core,u=this._avChatRoomHandler.isPollingSimplifiedMessage(),E=[],m=s.length;for(let D=0;D0&&this._emitEvent({name:g,data:E})}_updateLocalOnlineMemberCountFromTips(s){const{utils:{isEmpty:r}}=this._core,{ToGroupId:g,MsgBody:{OnlineMemberInfo:u}}=s;if(r(u))return;const{OnlineMemberNum:E=0,ExpireTime:m=TD}=u,D=Date.now();let M=this._avChatRoomHandler.getLocalOnlineMemberCount(g);r(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 hB=s=>{const{core:{store:r}}=CB;return(r.get("cloudConfig")||{})[s]},fh=s=>{const{core:{utils:{isUndefined:r}}}=CB;return!r(s)},HQ=()=>{const s=hB("polling_interval");return fh(s)?parseInt(s,10):300},BB=()=>{const s=hB("polling_simplified_msg");return fh(s)?parseInt(s,10):0};var iR=new class{constructor(){this._name="GetAVChatRoomOnlineMemberCount"}init(s,r){this._core=s,this._parentPlugin=r;const{helper:g}=s;g.registerApi({apiName:"getGroupOnlineMemberCount",context:this,matcher:()=>r.getInstalledSubPlugins().length>0})}getGroupOnlineMemberCount(s){return mA(this,void 0,void 0,function*(){const{appStore:{groupStore:r},OuterConstant:g}=this._core,u=r.getGroup(s);return u?u.type===g.GRP_AVCHATROOM?this._getOnlineMemberCount(s):this._parentPlugin.groupAction.getGroupOnlineMemberCount(s):{code:0,data:{memberCount:0}}})}_getOnlineMemberCount(s){return mA(this,void 0,void 0,function*(){const r="_getOnlineMemberCount",{utils:{isEmpty:g}}=this._core,u=Pg.getLocalOnlineMemberCount(s);if(g(u)||this._isExpired(s)){const{memberCount:E=0}=yield this._getOnlineMemberCountFromServer(s);return console.log(`${this._name}.${r} ok, groupID:${s} memberCount:${E} from server.`),{code:0,data:{memberCount:E}}}return console.log(`${this._name}.${r} ok, groupID:${s} memberCount:${u.memberCount} from local.`),{code:0,data:{memberCount:u.memberCount}}})}_isExpired(s){const r=Pg.getLocalOnlineMemberCount(s),g=Date.now(),u=g-r.lastSyncTime>1e3*r.expireTime,E=g-r.latestUpdateTime>1e4,m=g-r.lastReqTime>3e3;return u&&E&&m}_getOnlineMemberCountFromServer(s){return mA(this,void 0,void 0,function*(){const r="_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:u=0,ExpireTime:E=TD}=g||{},m=Date.now(),D={lastSyncTime:m,latestUpdateTime:m,lastReqTime:m,memberCount:u,expireTime:E};return Pg.updateLocalOnlineMemberCount(s,D),{memberCount:u}}catch(g){const u=new this._core.helper.ChatError({functionName:r,code:g?.errorCode,message:g?.errorInfo});throw console.error(`${this._name}.${r} fail:`,u),u}})}},Pg=new class{constructor(){this._name="AVChatRoomHandler",this._joinedGroupMap=new Map,this._pollingRequestInfoMap=new Map,this._pollingInstanceMap=new Map,this._onlineMemberCountMap=new Map,this._pollingIntervalMap=new Map,this._pollingNoMessageCountMap=new Map,this._membersReqInfoMap=new Map,this._startBroadcastSequence=1}init(s,r){this._core=s,this._parentPlugin=r,mh.init(s,this),s.ssoLog.debug("AVChatRoomHandler.init")}onAVChatRoomSystemNotification(s){const{OuterConstant:{GRP_AVCHATROOM:r}}=this._core,{GroupTips:g=[]}=s;for(let u=0;u0&&(r=[...this._joinedGroupMap.values()].filter(g=>g.type===s)),r}handleJoinGroupResult(s){return mA(this,void 0,void 0,function*(){const{utils:{isUndefined:r},OuterConstant:{CONV_GROUP:g},apiMap:{getConversationProfile:u},OuterConstant:E}=this._core,{longPollingKey:m,group:D,historyMessageList:M=[]}=s,{groupID:T}=D;return yield this._preCheck(D),this._joinedGroupMap.set(T,D),this._parentPlugin.groupDataHandler.updateLocalGroup([D]),this._parentPlugin.groupDataHandler.emitGroupListUpdate(),u(`${g}${T}`),iR.getGroupOnlineMemberCount(T),M.length>0&&mh.onMessageReceived(T,M,!0),r(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:r,OuterConstant:g,helper:u,apiMap:{quitGroup:E},ssoLog:m}=this._core;if(r.isUnlimitedAVChatRoom()){if(this._pollingInstanceMap.size>(()=>{const T=hB("polling_count_limit");return fh(T)&&T>0?parseInt(T,10):20})())throw new u.ChatError({code:qT,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:r}=this._core,{longPollingKey:g,startSequence:u=1,group:E}=s,{groupID:m}=E;return this._pollingRequestInfoMap.set(m,{longPollingKey:g,startSequence:u}),this._pollingIntervalMap.set(m,HQ()),this._startPolling(m),this._reportLongPollingCount(),{status:r.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 r=new tR({core:this._core,manager:this,groupID:s,getRequestParams:this._handleRequestParams.bind(this),onSuccess:this._handleSuccess.bind(this),onFail:this._handleFailure.bind(this)});r.start(),this._pollingInstanceMap.set(s,r)}_handleRequestParams(s){const{longPollingKey:r,startSequence:g}=this._pollingRequestInfoMap.get(s)||{};return s===[...this._pollingInstanceMap.keys()][0]?{longPollingKey:r,startSequence:g,startBroadcastSeq:this._startBroadcastSequence,simplifiedMessage:BB()}:{longPollingKey:r,startSequence:g,simplifiedMessage:BB()}}_handleSuccess(s,r){const{ErrorCode:g}=r;if(g!==0){const{longPollingKey:u,startSequence:E}=this._pollingRequestInfoMap.get(s)||{};return void console.warn(`${this._name}._handleSuccess groupID:${s} key:${u} startSeq:${E} errorCode:${g}`)}this._hasJoinedAVChatRoom(s)&&this._handleResponseData(s,r)}_handleResponseData(s,r){const{Key:g,NextSeq:u,NextBroadcastSeq:E,RspMsgList:m=[],RspBroadcastMsgList:D=[]}=r;if(g&&u&&this._pollingRequestInfoMap.set(s,{longPollingKey:g,startSequence:u}),E&&E>this._startBroadcastSequence&&(this._startBroadcastSequence=E),m.length>0)this._getPollingNoMessageCount(s)!==0&&(this._updatePollingNoMessageCount(s,0),this._pollingIntervalMap.set(s,HQ())),mh.onMessageReceived(s,m);else{let M=this._getPollingNoMessageCount(s);if(M+=1,this._updatePollingNoMessageCount(s,M),M===(()=>{const T=hB("polling_no_msg_count");return fh(T)?parseInt(T,10):20})()){const T=HQ()+(()=>{const P=hB("polling_interval_plus");return fh(P)?parseInt(P,10):2e3})();this._pollingIntervalMap.set(s,T)}}D.length>0&&mh.onBroadcastMessageReceived(D)}_handleFailure(s,r){const{ssoLog:g,utils:{safeStringify:u}}=this._core;g.warn("polling",`${this._name}._handleFailure groupID:${s} error: ${u(r)}`)}_joinedAVChatRoomCount(){const{OuterConstant:s}=this._core;let r=[];return this._joinedGroupMap.size>0&&(r=this.getJoinedGroups().filter(g=>g.type===s.GRP_AVCHATROOM)),r.length}_hasJoinedAVChatRoom(s){return this._joinedGroupMap.has(s)}getJoinedGroups(){return[...this._joinedGroupMap.values()]}updateLocalLiveGroup(s,r){this._joinedGroupMap.set(s,r),this._parentPlugin.groupDataHandler.updateLocalGroup([r])}handleLiveHistoryMessages(s,r){mh.onMessageReceived(s,r,!0)}isOverFrequencyLimit(s){if(!this._membersReqInfoMap.has(s))return this._membersReqInfoMap.set(s,{startTime:Date.now(),requestCount:1}),!1;let{startTime:r,requestCount:g}=this._membersReqInfoMap.get(s);const{interval:u,count:E}=(()=>{const m=hB("av_members_freq_limit");if(fh(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()-r>1e3*u?(this._membersReqInfoMap.set(s,{startTime:Date.now(),requestCount:1}),!1):(g+=1,this._membersReqInfoMap.set(s,{startTime:r,requestCount:g}),g>E)}_stopPolling(s){if(this._core.ssoLog.debug("_stopPolling",`${this._name}._stopPolling groupID:${s}`),s){const{appStore:{conversationStore:r},OuterConstant:{CONV_GROUP:g}}=this._core;r.deleteConversation(`${g}${s}`);const u=this._pollingInstanceMap.get(s);return u?.stop(),this._parentPlugin.groupDataHandler.deleteLocalGroup(s),this._pollingInstanceMap.delete(s),this._pollingRequestInfoMap.delete(s),this._joinedGroupMap.delete(s),this._onlineMemberCountMap.delete(s),this._pollingIntervalMap.delete(s),this._pollingNoMessageCountMap.delete(s),void this._membersReqInfoMap.delete(s)}for(const r of this._pollingInstanceMap.values())r?.stop();this._pollingInstanceMap.clear(),this._pollingRequestInfoMap.clear(),this._joinedGroupMap.clear(),this._onlineMemberCountMap.clear(),this._pollingIntervalMap.clear(),this._pollingNoMessageCountMap.clear(),this._membersReqInfoMap.clear()}_updatePollingNoMessageCount(s,r){this._pollingNoMessageCountMap.set(s,r)}_getPollingNoMessageCount(s){return this._pollingNoMessageCountMap.get(s)||0}_reportLongPollingCount(){const s=this._joinedGroupMap.size;if(s>1){const{common:r,OuterConstant:g,ssoLog:u}=this._core,E=r.isUnlimitedAVChatRoom()?1:0,m=[],D=[];Array.from(this._joinedGroupMap.values()).forEach(({groupID:M,type:T})=>{T===g.GRP_LIVE?D.push(M):m.push(M)}),u.info("longPollingCount",String(s),{moreMessage:`av:${m.join(",")} live:${D.join(",")} code: ${E}`,eventType:29})}}reset(s){this._stopPolling(s),this._startBroadcastSequence=1,mh.reset()}},oR=new class{init(s,r){this._core=s,this._parentPlugin=r;const{helper:g}=s;g.registerApi({apiName:"joinGroup",context:this,matcher:()=>r.getInstalledSubPlugins().length>0})}joinGroup(s){return mA(this,void 0,void 0,function*(){const{OuterConstant:r}=this._core,g=yield this._parentPlugin.groupAction.joinGroup(s),{data:{status:u,group:{type:E}}}=g;return E===r.GRP_AVCHATROOM?u===r.JOIN_STATUS_ALREADY_IN_GROUP?g:Pg.handleJoinGroupResult(g.data):g})}},jT=new class{init(s,r){this._core=s,this._parentPlugin=r;const{helper:g}=s;g.registerApi({apiName:"quitGroup",context:this,matcher:()=>r.getInstalledSubPlugins().length>0})}quitGroup(s){return mA(this,void 0,void 0,function*(){const{OuterConstant:r}=this._core,g=yield this._parentPlugin.groupAction.quitGroup(s),{data:{type:u}}=g;return u===r.GRP_AVCHATROOM&&Pg.reset(s),g})}},sR=new class{init(s,r){this._core=s,this._parentPlugin=r;const{helper:g}=s;g.registerApi({apiName:"dismissGroup",context:this,matcher:()=>r.getInstalledSubPlugins().length>0})}dismissGroup(s){return mA(this,void 0,void 0,function*(){const{OuterConstant:r}=this._core,g=yield this._parentPlugin.groupAction.dismissGroup(s),{data:{type:u}}=g;return u===r.GRP_AVCHATROOM&&Pg.reset(s),g})}},Ym=new class{constructor(){this._name="GetAVChatRoomMemberList"}init(s,r){this._core=s,this._parentPlugin=r;const{helper:g}=s;g.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>r.getInstalledSubPlugins().length>0})}getGroupMemberList(s){return mA(this,void 0,void 0,function*(){const{appStore:{groupStore:r},helper:g,OuterConstant:u}=this._core,{groupID:E}=s,m=r.getGroup(E);if(m?.type===u.GRP_AVCHATROOM&&g.checkBusinessCapabilityBits(eR)){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 r="_getGroupMemberList",{helper:g}=this._core;try{const u=yield function(M,T){return mA(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}=u||{},D=this._handleMemberList(E);return console.log(`${this._name}.${r} ok, groupID:${s.groupID} count:${D.length} nextOffset:${m}`),{code:0,data:{memberList:D,offset:m}}}catch(u){const E=new g.ChatError({functionName:r,code:u?.errorCode,message:u?.errorInfo});throw console.error(`${this._name}.${r} fail:`,E),E}})}_handleMemberList(s){return s.map(r=>{const{Member_Account:g,NickName:u="",Avatar:E="",Remark:m="",JoinTime:D=0,Marks:M=[]}=r;return{userID:g,nick:u,avatar:E,remark:m,joinTime:D,marks:M,isOnline:!0}})}},Vm=new class{constructor(){this._name="DeleteAVChatRoomMember"}init(s,r){this._core=s,this._parentPlugin=r;const{helper:g}=s;g.registerApi({apiName:"deleteGroupMember",context:this,matcher:()=>r.getInstalledSubPlugins().length>0})}deleteGroupMember(s){return mA(this,void 0,void 0,function*(){const r="deleteGroupMember",{appStore:{groupStore:g},utils:{isUndefined:u},helper:E,OuterConstant:m}=this._core,{groupID:D}=s,M=g.getGroup(D);if(u(M))throw new E.ChatError({functionName:r,code:ND});if(M.type===m.GRP_AVCHATROOM){if(E.checkBusinessCapabilityBits(JT))return this._deleteGroupMember(s);throw new E.ChatError({functionName:r,code:VQ})}return this._parentPlugin.groupMember.deleteGroupMember(s)})}_deleteGroupMember(s){return mA(this,void 0,void 0,function*(){const r="_deleteGroupMember",{appStore:{groupStore:g},helper:u,ssoLog:E}=this._core,{groupID:m,duration:D=0,userIDList:M}=s;if(D===0)throw new u.ChatError({functionName:r,code:HT});try{return yield function(T,P){return mA(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(r,`${this._name}.${r} ok, groupID:${m}`),{code:0,data:{group:g.getGroup(m),userIDList:M}}}catch(T){throw new u.ChatError({functionName:r,code:T?.errorCode,message:T?.errorInfo})}})}},_d=new class{constructor(){this._name="MarkAVChatRoomMember"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"markGroupMemberList",context:this})}markGroupMemberList(s){return mA(this,void 0,void 0,function*(){const r="markGroupMemberList",{groupID:g,markType:u,enableMark:E,userIDList:m=[]}=s,D=this._generateRequestData(s);try{const M=yield function(oA,EA){return mA(this,void 0,void 0,function*(){const{groupID:wA,operationType:kA,memberList:xA}=oA,LA={GroupId:wA,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}.${r} ok, groupID:${g} markType:${u} enableMark:${E} success:${P.length} fail:${W.length}`}}}catch(M){throw new this._core.helper.ChatError({functionName:r,code:M?.errorCode,message:M?.errorInfo})}})}_generateRequestData(s){const{groupID:r,markType:g,enableMark:u,userIDList:E=[]}=s,m=u===!0?1:2,D=[...E];return D.length>500&&console.warn(`${this._name}._generateRequestData, the length of userIDList cannot exceed 500`),{groupID:r,operationType:m,memberList:D.map(M=>({Member_Account:M,Marks:[g]}))}}_handleResult(s,r){const g=[],u=[];return s.length===r.length?(g.push(...r),{successUserIDList:g,failureUserIDList:u}):(r.forEach(E=>{s.find(m=>m.Member_Account===E)?g.push(E):u.push(E)}),{successUserIDList:g,failureUserIDList:u})}},nR=new class{init(s,r){s.ssoLog.debug("AVChatRoomAction.init"),oR.init(s,r),jT.init(s,r),sR.init(s,r),Ym.init(s,r),iR.init(s,r),Vm.init(s,r),_d.init(s)}},rR=new class{constructor(){this._name="LiveHandler"}init(s){this._core=s;const{helper:r,ssoLog:g}=s;r.registerExperimentalAPI("startMessageLongPolling",this),r.registerExperimentalAPI("stopMessageLongPolling",this),g.debug("LiveHandler.init")}startMessageLongPolling(s){const{common:r,utils:{isEmpty:g},OuterConstant:u,ssoLog:E}=this._core,{groupID:m,longPollingKey:D,longPollingSequence:M=1}=s;if(g(D))return E.warn("startMessageLongPolling",`${this._name}.startMessageLongPolling longPollingKey is empty.`),Promise.resolve({});Pg.hasPollingInstance(m)&&this.stopMessageLongPolling({groupID:m});const T=Pg.getJoinedLiveList(),P=r.isUnlimitedAVChatRoom();!P&&T.length>0&&this.stopMessageLongPolling({groupID:T[0].groupID}),E.debug("startMessageLongPolling",`${this._name}.startMessageLongPolling isUnlimited:${P} groupID:${m} longPollingKey:${D} longPollingSequence:${M}`);const W={groupID:m,type:u.GRP_LIVE};return Pg.updateLocalLiveGroup(m,W),this._getLiveHistoryMessages({groupID:m,longPollingKey:D,startSequence:M}),Pg.startMessageLongPolling({group:W,longPollingKey:D,startSequence:M})}stopMessageLongPolling(s){const{groupID:r}=s;return Pg.reset(r),this._core.ssoLog.debug("stopMessageLongPolling",`${this._name}.stopMessageLongPolling ok, groupID:${r}`),Promise.resolve({groupID:r})}_getLiveHistoryMessages(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r}=this._core,{groupID:g}=s;try{const u=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=[]}=u||{};r.debug("_getLiveHistoryMessages",`${this._name}._getLiveHistoryMessages ok, groupID:${g} count:${E.length}`),E.length>0&&Pg.handleLiveHistoryMessages(g,E)}catch(u){r.debug("_getLiveHistoryMessages",`${this._name}._getLiveHistoryMessages failed, groupID:${g} info:${u.message}`)}})}},Jm=new class{constructor(){this.name="AVChatRoom"}install(s,r){this._core=s,CB.init(s),Pg.init(s,r),nR.init(s,r),rR.init(s);const{notificationCenter:g,InnerEvent:u}=s,{InnerEventSubType:E}=g;g.subscribeInnerEvent(u.MESSAGE_PUSH,E.GROUP_SYSTEM_NOTIFICATION,this._onAVChatRoomSystemNotification,this),g.subscribeInnerEvent(u.LOGOUT,this._reset,this),g.subscribeInnerEvent(u.DESTROY,this._dispose,this)}_onAVChatRoomSystemNotification(s){Pg.onAVChatRoomSystemNotification(s)}_reset(){Pg.reset()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:r}=this._core,{InnerEventSubType:g}=s;s.unSubscribeInnerEvent(r.MESSAGE_PUSH,g.GROUP_SYSTEM_NOTIFICATION,this._onAVChatRoomSystemNotification,this),s.unSubscribeInnerEvent(r.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this)}};const Ag=new class{init(s){this.core=s}},Hm="message",QB="user",pB={OR:"or",AND:"and"},RI=20,WT=20,aR=20,yh={required:!1,rules:["array"],allowEmpty:!0,customValidator:s=>!s||!!(Array.isArray(s)&&s.length<=5)||"keywordList should be an array and length <= 5"},qm={required:!1,rules:["string"],allowEmpty:!0,customValidator:s=>!s||!![pB.OR,pB.AND].includes(s)||"keywordListMatchType should be OR or AND"},RC={required:!1,rules:["number"],allowEmpty:!0,customValidator:s=>typeof s=="number"&&s>=1&&s<=100||"count must be a number between 1 and 100"},qQ={required:!1,rules:["string"],allowEmpty:!0},gR={required:!1,rules:["array"],allowEmpty:!0,customValidator:s=>{const{OuterConstant:r}=Ag.core;if(!Array.isArray(s))return"groupTypeList should be an array";const g=[r.GRP_PUBLIC,r.GRP_COMMUNITY,r.GRP_WORK,r.GRP_MEETING];let u=!1;for(let E=0;E{const{OuterConstant:r}=Ag.core,g=[r.MSG_TEXT,r.MSG_IMAGE,r.MSG_AUDIO,r.MSG_FILE,r.MSG_VIDEO,r.MSG_LOCATION,r.MSG_CUSTOM,r.MSG_MERGER];let u=!1;for(let E=0;E{const{OuterConstant:r}=Ag.core;return!(!s?.startsWith(r.CONV_C2C)&&!s?.startsWith(r.CONV_GROUP)&&s!==r.CONV_SYSTEM)||"conversationID is invalid"}},Km=s=>({required:!1,rules:["number"],allowEmpty:!0,customValidator:r=>typeof r=="number"&&r>=0||`${s} should be a number >= 0';`}),bD={required:!1,rules:["string"],allowEmpty:!0,customValidator:s=>{const{OuterConstant:r}=Ag.core;return!![r.GENDER_FEMALE,r.GENDER_MALE].includes(s)||"gender is invalid"}},jm={searchCloudMessages:{keywordList:yh,keywordListMatchType:qm,cursor:qQ,senderUserIDList:{required:!1,rules:["array"],allowEmpty:!0,customValidator:s=>!!(Array.isArray(s)&&s.length<=5)||"senderUserIDList should be an array and length <= 5"},messageTypeList:cR,conversationID:lR,timePosition:Km("timePosition"),timePeriod:Km("timePeriod")},searchCloudUsers:{keywordList:yh,keywordListMatchType:qm,cursor:qQ,count:RC,miniBirthday:Km("miniBirthday"),maxBirthday:Km("maxBirthday"),gender:bD},searchCloudGroupMembers:{keywordList:yh,keywordListMatchType:qm,cursor:qQ,count:RC,groupTypeList:gR,groupIDList:{required:!1,rules:["array"],allowEmpty:!0}},searchCloudGroups:{keywordList:yh,keywordListMatchType:qm,cursor:qQ,count:RC,groupTypeList:gR}},kD={searchCloudMessages:!0,searchCloudUsers:!0,searchCloudGroupMembers:!0,searchCloudGroups:!0};var LD=new class{constructor(){this.name="CloudSearch"}install(s){this._core=s,Ag.init(s),s.helper.registerApi({apiName:"searchCloudMessages",context:this}),s.helper.registerApi({apiName:"searchCloudUsers",context:this}),s.helper.registerApi({apiName:"searchCloudGroupMembers",context:this}),s.helper.registerApi({apiName:"searchCloudGroups",context:this}),s.helper.registerValidateConfig({auth:kD,params:jm})}searchCloudMessages(s){return mA(this,void 0,void 0,function*(){try{const{OuterConstant:r,helper:g}=this._core,{conversationID:u,timePeriod:E,timePosition:m}=s,D=So(s,["conversationID","timePeriod","timePosition"]),M=Object.assign({count:100},D);u&&(u.startsWith(r.CONV_C2C)?M.account=u.replace(r.CONV_C2C,""):u.startsWith(r.CONV_GROUP)&&(M.groupID=u.replace(r.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:qA,senderUserIDList:Ie,messageTypeList:le,endTime:bi,startTime:ki,cursor:Ot,account:Li,groupID:cs}=LA,Re={Count:SA,KeywordList:OA,MatchType:qA,SendUserIDList:Ie,MsgTypeList:le,EndTime:bi,StartTime:ki,Cursor:Ot,PeerAccount:Li,GroupID:cs};return Ag.core.common.buildAndSendPacket({servcmd:"message_search.query",data:Re})})}(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:qA,UserID:Ie}=LA,le=qA?`${r.CONV_GROUP}${qA}`:`${r.CONV_C2C}${Ie}`;if(this._isSearchingAllConversations(s)&&OA>1)return{conversationID:le,messageCount:OA,messageList:[]};const bi=SA.map(ki=>g.isEmpty(qA)?function(Ot,Li){const cs=Li.OuterConstant.CONV_C2C,Re=Li.message.messageHelper.parseServerPushMessage(Ot),St=Li.message.messageFactory.createMessage(Object.assign(Object.assign({},Re),{conversationType:cs,flow:"in"}));return St.setElement(Re.elements),St}(ki,this._core):function(Ot,Li){const cs=Li.OuterConstant.CONV_GROUP,Re=Li.message.messageHelper.parseServerGroupMessage(Ot),St=Li.message.messageFactory.createMessage(Object.assign(Object.assign({},Re),{conversationType:cs,flow:"in"}));return St.setElement(Re.elements),St}(ki,this._core));return{conversationID:le,messageCount:OA,messageList:bi}}),cursor:EA,totalCount:oA},successLog:{message:kA}}}catch(r){const{errorCode:g,errorInfo:u}=r||{};this._handleError({errorCode:g,errorInfo:u,searchType:Hm,functionName:"searchCloudMessages"})}})}searchCloudUsers(s){return mA(this,void 0,void 0,function*(){var r;try{const{keywordListMatchType:g,count:u=WT}=s,E=So(s,["keywordListMatchType","count"]),m=Object.assign({count:u,keywordListMatchType:g===pB.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:qA,cursor:Ie,gender:le}=kA,bi={Count:xA,Keywords:LA,KeywordMatchType:SA,Cursor:Ie,UserBirthStart:OA,UserBirthEnd:qA,Gender:le};return Ag.core.common.buildAndSendPacket({servcmd:"user_search.query",data:bi})})}(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,xA=oA.length;kA({tag:Ie.Tag,value:Ie.StrValue})),qA=(r=this._core.user.userProfile)===null||r===void 0?void 0:r.createProfile(LA,OA);wA.push(qA)}return{code:0,data:{searchResultList:wA,cursor:W,totalCount:P},successLog:{message:EA}}}catch(g){const{errorCode:u,errorInfo:E}=g||{};this._handleError({errorCode:u,errorInfo:E,searchType:QB,functionName:"searchCloudUsers"})}})}searchCloudGroupMembers(s){return mA(this,void 0,void 0,function*(){try{const{count:r=aR,keywordListMatchType:g}=s,u=So(s,["count","keywordListMatchType"]),E=Object.assign({count:r,keywordListMatchType:g===pB.AND?1:0},u),m=yield function(wA){return mA(this,void 0,void 0,function*(){const{count:kA,keywordList:xA,keywordListMatchType:LA,groupTypeList:SA,cursor:OA,groupIDList:qA}=wA,Ie={Count:kA,Keywords:xA,KeywordMatchType:LA,Cursor:OA,GroupType:SA,GroupIdList:qA};return Ag.core.common.buildAndSendPacket({servcmd:"group_member_search.query",data:Ie})})}(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:xA,GroupType:LA,GroupFaceUrl:SA,GroupMemberUserName:OA,GroupMemberUserID:qA,GroupMemberNameCard:Ie,GroupMemberAvatar:le=""}=wA,bi={groupID:kA,name:xA,type:LA,avatar:SA},ki={userID:qA,nick:OA,nameCard:Ie,avatar:le};if(EA.has(kA)){const Ot=EA.get(kA);Ot.memberList.push(ki),EA.set(kA,Ot)}else EA.set(kA,{groupInfo:bi,memberList:[ki]})}),{code:0,data:{searchResultList:[...EA.values()],cursor:P,totalCount:W},successLog:{message:oA}}}catch(r){const{errorCode:g,errorInfo:u}=r||{};this._handleError({errorCode:g,errorInfo:u,searchType:QB,functionName:"searchCloudGroupMembers"})}})}searchCloudGroups(s){return mA(this,void 0,void 0,function*(){try{const{count:r=RI,keywordListMatchType:g}=s,u=So(s,["count","keywordListMatchType"]),E=Object.assign({count:r,keywordListMatchType:g===pB.AND?1:0},u),m=yield function(EA){return mA(this,void 0,void 0,function*(){const{count:wA,keywordList:kA,keywordListMatchType:xA,groupTypeList:LA,cursor:SA}=EA,OA={Count:wA,Keywords:kA,KeywordMatchType:xA,Cursor:SA,GroupType:LA};return Ag.core.common.buildAndSendPacket({servcmd:"group_search.query",data:OA})})}(E);if(!m)return{code:0,data:{}};const{ErrorCode:D,ErrorInfo:M,Groups:T,Cursor:P,TotalCount:W}=m;if(D!==0)throw{errorCode:D,errorInfo:M};const 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:xA,GroupIntroduction:LA,GroupMemberNum:SA,GroupName:OA,GroupOwnerTinyID:qA,GroupOwnerUserID:Ie,GroupOwnerUserName:le,GroupType:bi,GroupAddOption:ki,GroupInviteOption:Ot}=wA;return{avatar:kA,groupID:xA,introduction:LA,memberCount:SA,name:OA,ownerTinyID:qA,ownerID:Ie,ownerNick:le,type:bi,joinOption:ki,inviteOption:Ot}}(EA))||[],cursor:P,totalCount:W},successLog:{message:oA}}}catch(r){const{errorCode:g,errorInfo:u}=r||{};this._handleError({errorCode:g,errorInfo:u,searchType:QB,functionName:"searchCloudGroups"})}})}_setTimeRangeParams(s,{timePeriod:r,timePosition:g}){r&&r>0&&(s.startTime=g&&g>0?g-r:this._core.helper.timeManager.getServerTimeSeconds()-r),s.startTime&&s.startTime<0&&(s.startTime=void 0),g&&g>0&&(s.endTime=g)}_handleError({errorCode:s,errorMessage:r,searchType:g}){const{helper:u}=this._core;let E=s;throw s===60020?E="SearchUnable":g!==Hm&&s===27003?E="SearchParamsError":g!==Hm&&s===60018&&(E="SearchOverLimit"),new u.ChatError({code:E,message:r})}_isSearchingAllConversations(s){return this._core.helper.isEmpty(s.conversationID)}_setBirthdayRangeParams(s,r){const{miniBirthday:g,maxBirthday:u}=r;g!==void 0&&(s.miniBirthday=g,u===void 0&&(s.maxBirthday=4294967295)),u!==void 0&&(s.maxBirthday=u)}};function Dh(s,r){return Math.round(Number(s)*Math.pow(10,r))/Math.pow(10,r)}const IR="qualityStat",UD="im-ssolog-quality-stat";var FD;(function(s){s[s.ONLINE=8]="ONLINE"})(FD||(FD={}));const Wm="networkRTT",Sh="messageE2EDelay",mB="sendMessageC2C",Mh="sendMessageGroup",vh="sendMessageGroupAV",fB="sendMessageRichMedia",yB="cosUpload",wC="messageReceivedGroup",KQ="messageReceivedGroupAVPush",jQ="messageReceivedGroupAVPull",zT={[Wm]:2,[Sh]:3,[mB]:4,[Mh]:5,[vh]:6,[fB]:7,[wC]:8,[KQ]:9,[jQ]:10,[yB]:11},uR=[mB,Mh,vh,fB,yB],Rh=[wC,KQ,jQ],DB=[Wm,Sh,mB,Mh,vh,fB,yB,wC,KQ,jQ],OD={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},zm="quality_stat";var WQ=new class{constructor(){this._messageStatsMap=new Map,this._userSideErrorCodes=new Set(Object.values(OD))}init(s){this._core=s,Object.values(uR).forEach(r=>{this._messageStatsMap.set(r,{totalCount:0,successCount:0,failedCountOfUserSide:0,costSum:0,costCount:0,fileSizeSum:0})})}dispatchSendStats(s){const{name:r,message:g,error:u,startTs:E}=s,{SEND_MESSAGE_STAT:m}=this._core.constants;switch(r){case m.TOTAL_COUNT:this._handleTotalCount(g);break;case m.SUCCESS_COUNT:this._handleSuccessCount(g);break;case m.FAILED_COUNT:this._handleFailedCount(g,u);break;case m.SEND_COST:this._handleSendCost(g,E)}}getStatResult(s){const r=this._messageStatsMap.get(s);if(!r||r.totalCount===0)return null;const{totalCount:g,successCount:u,failedCountOfUserSide:E}=r,m=Dh(u/g*100,2),D=u+E,M=Dh(D/g*100,2),T=this._calcAverageValue(r,s);return this._resetStat(s),{total_count:g,success_count_business:u,percent_business:m,success_count_platform:D,percent_platform:M,average_value:T}}_handleTotalCount(s){const r=this._getSendMessageSpecifiedKey(s),g=r&&this._messageStatsMap.get(r);g&&g.totalCount++}_handleSuccessCount(s){const r=this._getSendMessageSpecifiedKey(s),g=r&&this._messageStatsMap.get(r);g&&g.successCount++}_handleFailedCount(s,r){var g;const u=(g=r?.code)!==null&&g!==void 0?g:r?.errorCode;if(this._isUserSideError(u)){const E=this._getSendMessageSpecifiedKey(s),m=E&&this._messageStatsMap.get(E);m&&m.failedCountOfUserSide++}}_handleSendCost(s,r){const g=this._getSendMessageSpecifiedKey(s),u=g&&this._messageStatsMap.get(g);u&&(u.costSum+=Date.now()-r,u.costCount++)}_isUserSideError(s){return this._userSideErrorCodes.has(s)||s>=120001&&s<=13e4||s>=10100&&s<=10200}_getSendMessageSpecifiedKey(s){const{MSG_IMAGE:r,MSG_AUDIO:g,MSG_VIDEO:u,MSG_FILE:E,CONV_C2C:m,CONV_GROUP:D,GRP_AVCHATROOM:M}=this._core.OuterConstant;if([r,g,u,E].includes(s.type))return fB;if(s.conversationType===m)return mB;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?vh:Mh}}_calcAverageValue(s,r){return s.costCount===0?0:Math.round(r===yB?1e3*s.fileSizeSum/s.costSum:s.costSum/s.costCount)}_resetStat(s){const r=this._messageStatsMap.get(s);r&&(r.totalCount=0,r.successCount=0,r.failedCountOfUserSide=0,r.costSum=0,r.costCount=0,r.fileSizeSum=0)}},zQ=new class{constructor(){this._lastCycleStats=new Map,this._currentCycleStats=new Map}init(s){this._core=s;const{OuterEvent:r,notificationCenter:g}=s;this._initStatsMap(),g.subscribeOuterEvent(r.MESSAGE_RECEIVED,this._onMessageReceived,this)}addMessageSequence(s){const r=this._getReceivedMessageSpecifiedKey(s),{utils:{isUndefined:g},OuterConstant:{CONV_GROUP:u},ssoLog:E}=this._core;if(g(r)||!this._currentCycleStats.has(r))return void E.debug("addMessageSequence",`${IR}.addMessageSequence invalid key:${r}`);const{conversationID:m,sequence:D}=s,M=m.replace(u,""),T=this._lastCycleStats.get(r);if(T.size===0||!T.has(M))return void this._addToCurrentCycle(r,M,D);const P=T.get(M);D>P.minSeq&&D{const{sortedSequences:m,minSeq:D,maxSeq:M}=E;m.length>0&&(u+=m.length,g+=M-D+1)}),g===0?null:(this._transferCycleDataOptimized(s),{total_count:g,success_count_business:u,percent_business:Dh(u/g*100,2)})}reset(){this._lastCycleStats.clear(),this._currentCycleStats.clear()}dispose(){const{notificationCenter:s,OuterEvent:{MESSAGE_RECEIVED:r}}=this._core;s.unSubscribeOuterEvent(r,this._onMessageReceived,this),this.reset()}_initStatsMap(){Object.values(Rh).forEach(s=>{this._lastCycleStats.set(s,new Map),this._currentCycleStats.set(s,new Map)})}_onMessageReceived(s){const{data:r=[]}=s;r.forEach(g=>{this.addMessageSequence(g)})}_transferCycleDataOptimized(s){const r=this._currentCycleStats.get(s);if(!r)return;const g=new Map;r.forEach((u,E)=>{const m=u.dirty?[...u.sortedSequences].sort((D,M)=>D-M):u.sortedSequences;g.set(E,{sortedSequences:m,minSeq:u.minSeq,maxSeq:u.maxSeq,dirty:!1})}),this._lastCycleStats.set(s,g),this._currentCycleStats.set(s,new Map)}_getReceivedMessageSpecifiedKey(s){const{OuterConstant:{CONV_GROUP:r,GRP_AVCHATROOM:g}}=this._core;if(s.conversationType===r&&s?._onlineOnlyFlag!==!0){const{groupStore:u}=this._core.appStore,E=u.getGroup(s.to);if(!E)return null;const{type:m}=E;return m===g?jQ:wC}}_insertToLastCycle(s,r){r.dirty&&(r.sortedSequences.sort((u,E)=>u-E),r.dirty=!1);const g=this._findInsertPos(r.sortedSequences,s);r.sortedSequences.splice(g,0,s),r.minSeq=Math.min(r.minSeq,s),r.maxSeq=Math.max(r.maxSeq,s)}_findInsertPos(s,r){let g=0,u=s.length-1;for(;g<=u;){const E=Math.floor((g+u)/2);if(s[E]===r)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:r}}=this._core;s.unSubscribeOuterEvent(r,this._onMessageReceived,this),this.reset()}_onMessageReceived(s){const{data:r=[]}=s,{OuterConstant:{MSG_GRP_TIP:g,MSG_GRP_SYS_NOTICE:u}}=this._core,E=[g,u];r.forEach(m=>{!E.includes(m.type)&&m.clientTime>0&&this.addMessageDelay(m.clientTime)})}_calculateAverageDelay(s){return s===0?0:Dh(this._totalDelay/s,1)}_calculatePercentage(s,r){return Dh(s/r*100,2)}},ER=new class{init(s){this.core=s}},ZT=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:r,notificationCenter:g,InnerEvent:{QUALITY_STAT:u,LOGOUT:E,DESTROY:m},constants:{WORKFLOW_NAME:D,WORKFLOW_STEP:M}}=s;ER.init(s),WQ.init(s),zQ.init(s),ZQ.init(s),r.registerWorkflowStep(D.SYNC_SERVER_INFO_AFTER_LOGIN,M.QUALITY_REPORT,this.handleLoginSuccess,this),g.subscribeInnerEvent(u,this._handleQualityStat,this),g.subscribeInnerEvent(E,this._reset,this),g.subscribeInnerEvent(m,this._dispose,this)}handleLoginSuccess(){const{store:s,helper:r,utils:{isUndefined:g}}=this._core,u=s.get("cloudConfig")||{},{q_rpt_interval:E}=u,m=g(E)?12e4:Number(E);r.taskScheduler.addTask({id:zm,intervalMs:m,callback:this.report,context:this})}report(){this._wholePeriod=!0;const s=[...DB.map(r=>{const g=this._buildQualityReportItem(r);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:r}}=this._core,{label:g,data:u}=s;g===r.MESSAGE_SEND_SUCCESS_RATE&&WQ.dispatchSendStats(u)}_needSkipReport(){return this._isSDKAppIDInBlacklist()&&!this._isTinyIDInWhitelist()}_isSDKAppIDInBlacklist(){const{store:s,utils:r}=this._core,g=s.get("cloudConfig")||{},u=s.get("instance")||{},{sdkAppId:E}=u,{q_rpt_sdkappid_bl:m=[]}=g;if(!r.isEmpty(m))return m.split(",").map(D=>Number(D)).includes(E)}_isTinyIDInWhitelist(){const{store:s,utils:r}=this._core,g=s.get("cloudConfig")||{},u=s.get("login")||{},E=Number(u.tinyID),{q_rpt_tinyid_wl:m=[]}=g;if(!r.isEmpty(m))return m.split(",").includes(E)}_buildQualityReportItem(s){const r=this._getStatResultByKey(s);if(r===null)return null;const g={quality_type:zT[s],timestamp:Date.now(),network_type:FD.ONLINE,extension:""};return Object.assign(Object.assign({},g),r)}_getStatResultByKey(s){switch(s){case Sh:return ZQ.getStatResult();case mB:case Mh:case vh:case fB:case yB:return WQ.getStatResult(s);case wC:case KQ:case jQ:return zQ.getStatResult(s);default:return null}}_uploadQualityReports(s){return mA(this,void 0,void 0,function*(){try{const r={header:this._core.common.getCommonHead(),quality:s};yield function(g){const{common:u,channel:E}=ER.core,m="imopenstat.tim_web_report_v2",D=u.generateSSOLogProtocolData({servcmd:m,data:g}),M=`${D.head.seq}${m}`;return E.sendPacket(D,{requestId:M})}(r),this._reportIndex++,this._wholePeriod=!1}catch(r){console.warn("doReport failed. error:",r),this._pendingReports=this._pendingReports.concat(s),this._cacheFailedLogs()}})}_cacheFailedLogs(){const s=this._pendingReports,r=`${IR}._cacheFailedLogs`;let g=[...this._failedLogsCache.get(UD)||[],...s];g.length>10&&(g=g.slice(g.length-10),console.log(`${r} logs overflow, keeping last 10 items`)),this._failedLogsCache.set(UD,g),console.log(`${r} count: ${g.length}`),this._pendingReports=[]}_reset(){const{helper:s}=this._core;s.taskScheduler.removeTask(zm)}_dispose(){const{notificationCenter:s,InnerEvent:{QUALITY_STAT:r,LOGOUT:g,DESTROY:u}}=this._core;s.unSubscribeInnerEvent(r,this._handleQualityStat,this),s.unSubscribeInnerEvent(g,this._reset,this),s.unSubscribeInnerEvent(u,this._dispose,this),this._reset(),ZQ.dispose(),zQ.dispose()}};const ll=new class{init(s){this.core=s}};function dR(s){return mA(this,void 0,void 0,function*(){var r;const{message:g,user:u,appStore:E,constants:{OuterConstant:m}}=ll.core,D=E.conversationStore.getConversationMap();if(D.has(s)){const T=(r=D.get(s))===null||r===void 0?void 0:r.userProfile;if(T&&s.startsWith(m.CONV_C2C)){const{avatar:P,nick:W}=T;ll.core.message.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:s,latestAvatar:P,latestNick:W,isSentByMe:!1})}}const{data:M}=(yield u.userProfile.getMyProfile())||{};if(M){const{avatar:T,nick:P}=M;g.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:s,latestAvatar:T,latestNick:P,isSentByMe:!0})}})}function CR(s){return mA(this,void 0,void 0,function*(){const r=s.map(g=>g.revoker);try{const g=yield function(u){return mA(this,void 0,void 0,function*(){var E,m;const D=yield(E=ll.core.user.userProfile)===null||E===void 0?void 0:E.getUserProfile({userIDList:u});return D?.data?(m=D.data)===null||m===void 0?void 0:m.reduce((M,{userID:T,nick:P,avatar:W})=>(M[T]={nick:P||"",avatar:W||""},M),{}):null})}(r);g&&s.forEach(u=>{const{revoker:E}=u;g[E]&&(u.revokerInfo.nick=g[E].nick||"",u.revokerInfo.avatar=g[E].avatar||"",u.revokerInfo.userID=E)})}catch(g){console.debug(g)}})}const PD=1,hR=2,wh=20,XQ=2500,BR=1,_h=300;function $Q(s){return mA(this,void 0,void 0,function*(){var r,g;const{appStore:u,utils:{isEmpty:E},common:{getCurrentUserID:m},notificationCenter:D,OuterEvent:M,OuterConstant:{CONV_C2C:T}}=ll.core,{messageList:P,conversationID:W}=s,oA=u.conversationStore.getConversationMap();let EA=(r=oA.get(W))===null||r===void 0?void 0:r.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 ll.core.common.buildAndSendPacket({servcmd:"openim.get_peer_read_time",data:SA})})}([kA]);if(xA){const{ReadTime:LA}=xA;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,u.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 QR=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:r,OuterConstant:{Direction:g,CONV_C2C:u,CONV_GROUP:E},InnerEvent:{HISTORY_MESSAGE_FETCHED:m},notificationCenter:D}=this._core,{conversationID:M,nextReqMessageID:T}=s,P=wh;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 r.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:M,sequence:Number(T),count:P,direction:g.FORWARD,shouldMarkCompleted:!0}):M.startsWith(u)&&(oA=yield r.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:M,messageID:T,count:P,direction:g.FORWARD,shouldMarkCompleted:!0})),oA){const{nextReqMessageIDFromServer:EA,hasNoMoreHistoryMessage:wA,messageList:kA}=oA,xA=r.messageDataHandler.prependLocalMessageList({messageList:kA,conversationID:M});(function(Ie){const{appStore:le,message:bi,OuterConstant:ki}=ll.core,Ot=le.conversationStore.getConversation(Ie),Li=bi.messageDataHandler.getLocalMessageList(Ie);if(!Ot||Li.length===0||Ie===ki.CONV_SYSTEM)return;const cs=[];for(let St=0;StUA.isRevoked).length;Re=cs.length-Ot.unreadCount-St}else Re=cs.length-Ot.unreadCount;for(let St=0;StIe.isRevoked);yield CR(SA),D.emitInnerEvent(m,xA);const OA={nextReqMessageID:wA?"":String(EA),messageList:LA,isCompleted:wA},qA=LA.map(Ie=>Ie.sequence);return{code:0,data:OA,successLog:{message:`conversationID: ${M} nextReqMessageID: ${T} availableLocalMessagesCount: ${W} sequenceList: ${JSON.stringify(qA)}`}}}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(r){const{code:g,message:u}=r||{};throw new this._core.helper.ChatError({code:g,message:u,moreMessage:`options: ${this._core.utils.safeStringify(s)}`})}})}getMessageListHopping(s){return mA(this,void 0,void 0,function*(){var r,g;const{OuterConstant:{Direction:u,CONV_C2C:E,CONV_GROUP:m},utils:{safeStringify:D}}=this._core,{conversationID:M,sequence:T,time:P,direction:W=u.FORWARD}=s,{utils:{isEmpty:oA},message:EA,notificationCenter:wA,InnerEvent:{HISTORY_MESSAGE_FETCHED:kA}}=this._core;if(![u.BACKWARD,u.FORWARD].includes(W))throw new this._core.helper.ChatError({message:"direction must be 0 or 1",moreMessage:`options: ${D(s)}`});let{count:xA=wh}=s;xA=xA>wh?wh: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:qA,invisibleSequenceList:Ie}=LA;if(this._core.message.messageDataHandler.storeSparseMessageList(qA),wA.emitInnerEvent(kA,qA),W===u.FORWARD){const le=OA&&SA<1;return{code:0,data:{messageList:qA,isCompleted:le,nextMessageSeq:le?"":SA}}}if(W===u.BACKWARD){if(oA(qA)&&oA(Ie))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};const le=((r=qA?.[qA.length-1])===null||r===void 0?void 0:r.sequence)||0,bi=((g=Ie?.[Ie.length-1])===null||g===void 0?void 0:g.sequence)||0;return{code:0,data:{messageList:qA.filter(ki=>ki.sequence>=T),isCompleted:!OA,nextMessageSeq:OA?Math.max(le,bi)+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:qA}=LA;return wA.emitInnerEvent(kA,SA),qA||(W===u.FORWARD?SA.shift():SA.pop()),EA.messageDataHandler.storeSparseMessageList(SA),yield $Q({messageList:SA,conversationID:M}),{code:0,data:{messageList:SA,isCompleted:qA,nextMessageTime:qA?"":OA}}}})}clearHistoryMessage(s){return mA(this,void 0,void 0,function*(){var r;const{appStore:g,common:{ChatError:u,getCurrentUserID:E},OuterConstant:{CONV_C2C:m,CONV_GROUP:D},apiMap:M,message:T}=this._core,P=g.conversationStore.getConversation(s);if(!P)throw new u({code:XQ});const W={fromAccount:E()},{type:oA}=P;oA===m?(W.type=PD,W.toAccount=s.replace(m,"")):oA===D&&(W.type=hR,W.toGroupID=s.replace(D,""));try{return yield(r=M?.setMessageRead)===null||r===void 0?void 0:r.call(M,{conversationID:s}),(yield function(wA){return mA(this,void 0,void 0,function*(){const{fromAccount:kA,type:xA,toAccount:LA,toGroupID:SA}=wA,OA={From_Account:kA,Type:xA,To_Account:LA,ToGroupid:SA};return ll.core.common.buildAndSendPacket({servcmd:"recentcontact.clear_msg",data:OA})})}(W))&&(T.messageDataHandler.deleteConversationMessageList(s),T.messageHistory.completedHistoryConversations.delete(s),T.messageHistory.clearHistoryMessageListFetchAnchors(s),this._updateConversationLastMessage(s)),{code:0,data:{conversationID:s},successLog:{message:`convID:${s}`}}}catch(EA){const{errorCode:wA}=EA;throw new this._core.helper.ChatError({functionName:"clearHistoryMessage",code:wA,moreMessage:`convID:${s}`})}})}_updateConversationLastMessage(s){const{appStore:r}=this._core;r.conversationStore.updateConversation(s,{lastMessage:this._generateLastMessage()},{needSort:!0})}_getAvailableLocalMessagesCount({conversationID:s,nextReqMessageID:r}){const{OuterConstant:{CONV_C2C:g,CONV_GROUP:u}}=this._core,E=this._core.message.messageDataHandler.getLocalMessageList(s),{length:m}=E;if(!r)return m;let D=-1;return s?.startsWith(g)?D=E.findIndex(M=>M.ID===r):s?.startsWith(u)&&(D=E.findIndex(M=>r.includes("-")?M.ID===r:String(M.sequence)===r)),D===-1?0:D}_needFetchHistoryMessageList({conversationID:s,availableLocalMessagesCount:r,targetCount:g}){const{message:u}=this._core;return rr.startsWith(E)?EA.ID===g:String(EA.sequence)===g),W=oA>u?oA-u:0,T=oA):W=M>u?M-u:0,P.messageList=D.slice(W,oA),P.isCompleted=T<=u&&m.messageHistory.completedHistoryConversations.has(r),P.isCompleted?P.nextReqMessageID="":P.nextReqMessageID=this._generateNextReqMessageID({conversationID:r,targetIndex:W}),r.startsWith(E)&&(yield dR(r),yield $Q({messageList:P.messageList,conversationID:r})),P})}_generateNextReqMessageID({conversationID:s,targetIndex:r}){const g=this._core.message.messageDataHandler.getLocalMessageList(s);return s.startsWith("C2C")?g[r].ID:String(g[r].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}}},SB=new class{constructor(){this._lastMessageSequenceMapOnDisconnect=new Map,this._lastMessageTimeMapOnDisconnect=new Map}init(s){this._core=s;const{common:{workflowManager:r},constants:{WORKFLOW_NAME:g,WORKFLOW_STEP:u,InnerEvent:E}}=s;r.registerWorkflowStep(g.SYNC_SERVER_INFO_AFTER_RE_ONLINE,u.HISTORY_MESSAGE_RECOVER,this._syncGroupOfflineMessage,this),r.registerWorkflowStep(g.SYNC_SERVER_INFO_AFTER_RE_ONLINE,u.C2C_HISTORY_MESSAGE_RECOVER,this._syncC2COfflineMessage,this),s.notificationCenter.subscribeInnerEvent(E.SOCKET_DISCONNECTED,this._updateLastMessageSequenceMapOnDisconnect,this)}_syncGroupOfflineMessage(s){const{conversationList:r}=s?.result||{},{OuterConstant:g,utils:{isArray:u}}=this._core;if(u(r)){const E=r.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:r}=this._core,g=[],u=[];return yield Promise.all(s?.map(E=>mA(this,void 0,void 0,function*(){const{groupProfile:{groupID:m}={},lastMessage:{lastSequence:D}={}}=E,M=`${r.CONV_GROUP}${m}`;let T=this._getLocalLastMessageSequence(M);this._shouldRecoverHistory({localLastMessageSequence:T,serverLastMessageSequence:D})&&(yield this._recoverGroupHistoryForConversation({conversationID:M,localLastMessageSequence:T,serverLastMessageSequence:D,groupTipList:u})),g.push(M.replace(r.CONV_GROUP,""))}))),{recoverRevokeNoticeGroupIDList:g,groupTipList:u}})}_recoverGroupHistoryForConversation(s){return mA(this,arguments,void 0,function*({conversationID:r,localLastMessageSequence:g,serverLastMessageSequence:u,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,xA=u-g,LA=Math.min(20,xA),SA={},OA=yield oA.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:r,sequence:g+LA,direction:P.Direction.FORWARD,count:LA}),{nextReqMessageIDFromServer:qA,hasNoMoreHistoryMessage:Ie,messageList:le,serverGroupTipList:bi}=OA;m(bi)&&E.push(...bi);const ki=Ie&&qA<0,Ot=[];if(m(le)&&(le.forEach(Li=>{oA.messageReceiver.groupMessageReceiver.updateMessageProfile(Li),Li.from===P.CONV_SYSTEM&&(Li.isSystemMessage=!1),oA.messageDataHandler.storeConversationMessage(Li)&&!M(Li.payload)&&(Ot.push(Li),Li._isExcludedFromLastMessage||(SA.lastMessage=kA(Li)))}),Ot.length>0&&W.emitOuterEvent(T.MESSAGE_RECEIVED,{name:T.MESSAGE_RECEIVED,data:Ot})),!ki&&le.length>0){const Li=le[le.length-1].sequence;yield this._recoverGroupHistoryForConversation({conversationID:r,localLastMessageSequence:Li,serverLastMessageSequence:u,groupTipList:E})}D(SA.lastMessage)&&(SA.lastMessage.messageForShow=wA(SA.lastMessage.type,SA.lastMessage.payload),EA.conversationStore.updateConversation(r,SA))}catch(m){this._core.ssoLog.error("_recoverGroupHistoryForConversation",`Recovery failed for conversation:${r}`,{error:m})}})}_updateLastMessageSequenceMapOnDisconnect(){const{message:s}=this._core,r=s.messageDataHandler.getContinuousMessagesByConversation();for(const[g,u]of r){const E=Array.from(u.values());if(E?.length>0){const m=E[E.length-1];g.startsWith("C2C")?this._lastMessageTimeMapOnDisconnect.set(g,m.time):g.startsWith("GROUP")&&this._lastMessageSequenceMapOnDisconnect.set(g,m.sequence)}}}_getLocalLastMessageSequence(s){const{message:r}=this._core;if(this._lastMessageSequenceMapOnDisconnect.has(s))return this._lastMessageSequenceMapOnDisconnect.get(s);const g=r.messageDataHandler.getLocalMessageList(s),u=g[g.length-1];return u?.sequence}_shouldRecoverHistory(s){const{localLastMessageSequence:r,serverLastMessageSequence:g}=s;if(typeof r!="number"||typeof g!="number")return!1;const u=g-r;return g!==0&&r>0&&u>=BR&&u<_h}_syncC2COfflineMessage(s){const{conversationList:r}=s?.result||{},{OuterConstant:g,utils:{isArray:u}}=this._core;if(u(r)){const E=[];return r.forEach(m=>{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(r=>mA(this,void 0,void 0,function*(){const{conversationID:g,lastMessage:{lastTime:u}={}}=r,E=this._getLocalLastMessageTime(g);this._shouldRecoverC2CHistory({localLastMessageTime:E,serverLastMessageTime:u})&&(yield this._recoverHistoryForC2CConversation({conversationID:g,localLastMessageTime:E,serverLastMessageTime:u}))})))})}_shouldRecoverC2CHistory(s){const{localLastMessageTime:r,serverLastMessageTime:g}=s,u=g-r;return r>0&&u>=1&&u<=600}_recoverHistoryForC2CConversation(s){return mA(this,void 0,void 0,function*(){var r;const{conversationID:g,localLastMessageTime:u,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:xA}}=this._core;try{const LA={},SA=yield EA.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:g,direction:W.Direction.BACKWARD,time:u,count:20});if(M(SA))return;const{hasNoMoreHistoryMessage:OA,messageList:qA}=SA,Ie=[];m(qA)&&(qA.forEach(bi=>{EA.messageDataHandler.storeConversationMessage(bi)&&!M(bi.payload)&&(Ie.push(bi),bi._isExcludedFromLastMessage||(LA.lastMessage=xA(bi)))}),Ie.length>0&&oA.emitOuterEvent(P.MESSAGE_RECEIVED,{name:P.MESSAGE_RECEIVED,data:Ie}));const le=(r=qA[qA.length-1])===null||r===void 0?void 0:r.time;!OA&&le>E&&(yield this._recoverHistoryForC2CConversation({conversationID:g,localLastMessageTime:le,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:r}=this._core;if(this._lastMessageTimeMapOnDisconnect.has(s))return this._lastMessageTimeMapOnDisconnect.get(s);const g=r.messageDataHandler.getLocalMessageList(s),u=g[g.length-1];return u?.time}reset(){this._lastMessageSequenceMapOnDisconnect.clear(),this._lastMessageTimeMapOnDisconnect.clear()}dispose(){this.reset()}},MB=new class{constructor(){this.name="HistoryMessage"}install(s){this._core=s,ll.init(s),QR.init(s),SB.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:r}=this._core;s.unSubscribeInnerEvent(r.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(r.DESTROY,this.dispose,this),SB.dispose()}_reset(){SB.reset()}},xD=new class{init(s){this.core=s}},_C=new class{constructor(){this._reportedAtomicStoreIDs=new Set}init(s){const{helper:{registerExperimentalAPI:r}}=s;this._core=s,r("reportModalView",this),r("reportTUIFeatureUsage",this),r("reportRoomEngineEvent",this)}reportModalView(s){const{ssoLog:r,utils:{safeStringify:g,isString:u}}=this._core;try{if(!u(s))throw new Error("reportModalView data is not a string");r.createSSOLogData({method:"reportModalView",message:s,eventType:30}).end(!0)}catch(E){r.debug(`reportModalView Report failed: ${g(E)}`)}}reportTUIFeatureUsage(s){const{ssoLog:r,utils:{safeStringify:g,isEmpty:u}}=this._core,{atomicStoreID:E}=s;try{u(E)||this._reportedAtomicStoreIDs.has(E)||(this._core.ssoLog.info("reportTUIFeatureUsage",`atomicStoreID: ${s.atomicStoreID}`,{method:"reportTUIFeatureUsage",eventType:31,code:E}),this._reportedAtomicStoreIDs.add(E))}catch(m){r.debug(`reportTUIFeatureUsage Report failed: ${g(m)}`)}}reportRoomEngineEvent(s){const{utils:{safeStringify:r},ssoLog:g}=this._core;try{g.debug(`reportRoomEngineEvent Report: ${r(s)}`);const{eventId:u,eventCode:E,eventResult:m,eventMessage:D,moreMessage:M,extensionMessage:T}=s;g.createSSOLogData({method:T,code:u,message:D,eventType:30,costTime:E,uiPlatform:m,moreMessage:M}).end(!0)}catch(u){g.debug(`reportRoomEngineEvent Report failed: ${r(u)}`)}}reset(){this._reportedAtomicStoreIDs.clear()}dispose(){this.reset()}},Ap=new class{constructor(){this.name="DataReport"}install(s){this._core=s;const{notificationCenter:r,InnerEvent:{LOGOUT:g,DESTROY:u}}=s;xD.init(s),_C.init(s),r.subscribeInnerEvent(g,this._reset,this),r.subscribeInnerEvent(u,this._dispose,this)}_reset(){_C.reset()}_dispose(){const{notificationCenter:s,InnerEvent:{LOGOUT:r,DESTROY:g}}=this._core;s.unSubscribeInnerEvent(r,this._reset,this),s.unSubscribeInnerEvent(g,this._dispose,this),_C.dispose()}};let Zm=gr.STANDARD,vB=[];Zm=gr.STANDARD,vB=[lh,dC,CC,hC,Rc,ZT,MB,Ap,OE,wi,zn,VT,Jm,LD,$I];function RB(s,r){const{operationType:g,memberInfoList:u,operatorInfo:E}=s||{};let m={};if(Rs(u)?Rs(E)||(m=E):g!==Tg.JOINED&&g!==Tg.KICKED&&g!==Tg.ADMIN_SET&&g!==Tg.ADMIN_CANCELED||(m=Object.assign({},u[0])),!Rs(m)){const{nick:D="",avatar:M=""}=m;r.nick=D,r.avatar=M}}const ep=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 tp=Object.freeze({__proto__:null,ChatError:gs,WorkflowManager:ws,buildAndSendPacket:gg,buildLastMessage:ep,get builtInPlugins(){return vB},checkBusinessCapabilityBits:tn,deepMerge:Cd,getCurrentUserID:ir,getErrorMessage:rs,getMessagePreviewText:Zc,isC2CConv:s=>c(s)&&s.slice(0,3)===ka.CONV_C2C,isCommunity:$r,isGroupConv:s=>c(s)&&s.slice(0,5)===ka.CONV_GROUP,isInternational:_l,isTopic:zc,isUnlimitedAVChatRoom:function(){var s;return!!(!((s=De.store.get("instance"))===null||s===void 0)&&s.unlimitedAVChatRoom)},liteChatInstanceMap:Ca,registerInterceptor:Mc,registerValidateConfig:Wc,requireAuth:ud,get sdkEdition(){return Zm},setGroupTipsUserInfo:RB,t:Lu,updateGroupAtInfo:(s,r)=>{const{CONV_AT_ME:g,CONV_AT_ALL:u,CONV_AT_ALL_AT_ME:E}=Uo;if(function(M,T){const{CONV_AT_ME:P,CONV_AT_ALL:W,CONV_AT_ALL_AT_ME:oA}=Uo,{groupID:EA,sequence:wA}=M;let kA=!1;return $r({groupID:EA})&&T.forEach(xA=>{xA.messageSequence===wA&&(xA.atTypeArray.includes(P)&&M.groupAtType.includes(W)&&(xA.atTypeArray=[oA]),xA.atTypeArray.includes(W)&&M.groupAtType.includes(P)&&(xA.atTypeArray=[oA],xA.__random=M.__random,xA.__sequence=M.__sequence),kA=!0)}),kA}(s,r))return;let m=[...s.groupAtType];m.includes(g)&&m.includes(u)&&(m=[E]);const D={from:s.from,groupID:s.groupID,topicID:s.topicID,messageSequence:s.sequence,atTypeArray:m,__random:s.__random,__sequence:s.__sequence};r.push(D)},validateAndExecute:vr,validateParameters:uI});class gu{constructor(){this._builtInPlugins=new Set,this._externalPlugins=new Set}static getInstance(){return gu._instance||(gu._instance=new gu),gu._instance}static setInstance(r){gu._instance=r}installBuiltInPlugin(r){r&&this._installPlugin(r,this._builtInPlugins)}installExternalPlugin(r){r&&this._installPlugin(r,this._externalPlugins)}clear(){this._builtInPlugins=new Set,this._externalPlugins=new Set}_installPlugin(r,g){let u=[];u=C(r)?r:[r];const E=u.findIndex(D=>D?.name==="AVChatRoom"),m=E>-1?u.splice(E,1):[];u.forEach(D=>{this._isPluginInstalled(D.name)||(D&&vg(D.install)?(g.add(D.name),vg(D.getInstalledSubPlugins)?(m?.forEach(M=>g.add(M?.name)),D.install(pr.getInstance().exposeApiForPlugin(),m)):D.install(pr.getInstance().exposeApiForPlugin()),vg(D.handleLoginSuccess)&&this._isLoggedIn()&&D.handleLoginSuccess()):vg(D)?(g.add(D.name),D(pr.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(r){return this._builtInPlugins.has(r)||this._externalPlugins.has(r)}_isLoggedIn(){var r;return((r=De.store.get("login"))===null||r===void 0?void 0:r.isLoggedIn)===!0}}var wB=new class{constructor(){this._conversationMap=new Map}getConversationMap(){return this._conversationMap}getConversation(s){return this._conversationMap.get(s)}updateConversation(s,r,g){const{emit:u=!0,needSort:E=!1}=g||{},m=this._conversationMap.get(s);m&&!Rs(r)&&(Object.keys(r).forEach(D=>{m[D]=r[D]}),u&&De.notificationCenter.emitInnerEvent(ro.CONVERSATION_UPDATED,{needSort:E}))}deleteConversation(s){this._conversationMap.has(s)&&(this._conversationMap.delete(s),De.notificationCenter.emitInnerEvent(ro.CONVERSATION_UPDATED))}},ip=new class{constructor(){this._groupMap=new Map}getGroupMap(){return this._groupMap}getGroup(s){return this._groupMap.get(s)}updateGroup(s,r){const g=this._groupMap.get(s);g&&!Rs(r)&&Object.keys(r).forEach(u=>{g[u]=r[u]})}},op=new class{constructor(){this._messagesByConversation=new Map}updateMessage(s,r,g){var u;const{operation:E,updateUnreadCount:m=!0}=g,D=So(g,["operation","updateUnreadCount"]),M=[];for(const T of r){const P=(u=this._messagesByConversation.get(s))===null||u===void 0?void 0:u.get(T);if(!P)return!1;Object.keys(D).forEach(W=>{P[W]=D[W]}),M.push(P)}return this._emitMessageStoreOperationEvent(E,{conversationID:s,messageList:M,updateUnreadCount:m}),M}getMessagesByConversation(s){var r;return[...((r=this._messagesByConversation.get(s))===null||r===void 0?void 0:r.values())||[]]}getMessages(){return this._messagesByConversation}_emitMessageStoreOperationEvent(s,r){const{conversationID:g}=r;zc(g)?De.notificationCenter.emitInnerEvent(Tu[s],r):De.notificationCenter.emitInnerEvent(s,r)}},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)}},YD=Object.freeze({__proto__:null,conversationStore:wB,groupStore:ip,messageStore:op,userStore:rc});class pr{static getInstance(){return pr._instance||(pr._instance=new pr),pr._instance}static setInstance(r){pr._instance=r}constructor(){this._experimentalApiMap={statTUIKeyFeatures:this.statKeyFeatureUsage.bind(this),setApplicationID:this.setApplicationID.bind(this)},this._apiHandlersMap={},this._apiMap={on:De.notificationCenter.subscribeOuterEvent.bind(De.notificationCenter),off:De.notificationCenter.unSubscribeOuterEvent.bind(De.notificationCenter),destroy:this.destroy.bind(this),callExperimentalAPI:this.callExperimentalAPI.bind(this),use:gu.getInstance().installExternalPlugin.bind(gu.getInstance()),registerPlugin:this.registerPlugin.bind(this),setLogLevel:this.setLogLevel.bind(this)}}registerPlugin(r){De.ssoLog.debug("registerPlugin",r)}statKeyFeatureUsage(r){De.ssoLog.debug("statTUIKeyFeatures",r)}setLogLevel(r){De.ssoLog.debug("setLogLevel",r),De.ssoLog.setLogLevel(r)}setApplicationID(r){De.store.set("instance",{applicationID:r})}getApiMap(){return this._apiMap}setApiMap(r){this._apiMap=r}registerApi(r){const{common:{timeManager:g},utils:{safeStringify:u}}=De,{apiName:E,context:m,methodName:D=E,matcher:M}=r;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),KI.includes(E)&&De.ssoLog.debug(E,`${E} start params: ${u(T)}`),vr(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 De.ssoLog.error(E,`${E} fail ${wA?.message||wA?.errorMessage})`,{error:wA,costTime:g.getServerTimeMs()-P,eventType:W,method:E}),wA}})}registerExperimentalAPI(r,g,u){const E=u||r;this._experimentalApiMap[r]=g[E].bind(g)}destroy(){return mA(this,void 0,void 0,function*(){var r,g;try{!((r=De.store.get("login"))===null||r===void 0)&&r.isLogin&&(yield this._apiMap.logout()),De.notificationCenter.emitInnerEvent(ro.DESTROY)}catch(u){console.debug("destroy error: ",u)}finally{De.notificationCenter.emitOuterEvent(Mr.SDK_DESTROY,{SDKAppID:(g=De.store.get("instance"))===null||g===void 0?void 0:g.sdkAppId}),Ca.clear(),gu.getInstance().clear(),ws.getInstance().destroy(),De.destroy()}})}exposeApiForClient(){return this._apiMap}exposeApiForPlugin(){return Object.assign(Object.assign({InnerEvent:ro,InnerEventSubType:De.notificationCenter.InnerEventSubType,OuterEvent:Mr,OuterConstant:Uo,SignalingEvent:qc,helper:Object.assign(Object.assign(Object.assign({},De.utils),De.common),{registerApi:this.registerApi.bind(this),registerExperimentalAPI:this.registerExperimentalAPI.bind(this),registerInterceptor:Mc,registerValidateConfig:Wc,checkBusinessCapabilityBits:tn,registerWorkflowStep:ws.getInstance().registerWorkflowStep.bind(ws.getInstance()),ChatError:gs}),apiMap:this._apiMap},De),{constants:Object.assign(Object.assign({},za),De.constants),common:Object.assign(Object.assign(Object.assign({},tp),De.common),{workflowManager:ws.getInstance()}),utils:De.utils,appStore:YD})}callExperimentalAPI(r,g){return De.ssoLog.debug(`callExperimentalAPI.${r} start params: ${De.utils.safeStringify(g)}`),this._experimentalApiMap[r]?this._experimentalApiMap[r](g):(De.ssoLog.error("callExperimentalAPI",`callExperimentalAPI.${r} not found, params: ${De.utils.safeStringify(g)}`),Promise.reject(new gs({code:da.INVALID_OPERATION})))}_isPromiseLike(r){return r!==null&&typeof r=="object"&&typeof r.then=="function"}_handleAsyncResult(r,g,u,E){return r.then(m=>(this._reportApiSuccessLog({result:m,apiName:g,eventType:u,startTime:E}),m)).catch(m=>{throw De.ssoLog.error(g,`${g} fail ${m?.message||m?.errorMessage})`,{error:m,costTime:De.common.timeManager.getServerTimeMs()-E,eventType:u,method:g,startTime:E}),m})}_reportApiSuccessLog(r){let{result:g,apiName:u,startTime:E,eventType:m}=r;const{timeManager:D}=De.common,{successLog:{message:M,moreMessage:T}={message:"",moreMessage:""}}=g||{},P=D.getServerTimeMs();u==="login"&&(E+=D.getTimeOffsetWithServer()),KI.includes(u)&&De.ssoLog.info(u,`${u} success ${M} ${T}`,{costTime:P-E,eventType:m,message:M,moreMessage:T,startTime:E}),g?.successLog&&delete g.successLog}}class pR{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120,this._customLoginInfo=""}init(){const{notificationCenter:r,store:g}=De;g.set("login",{isReady:!1}),pr.getInstance().registerApi({apiName:"login",context:this}),pr.getInstance().registerApi({apiName:"logout",context:this}),pr.getInstance().registerApi({apiName:"getLoginUser",context:this}),pr.getInstance().registerApi({apiName:"isReady",context:this}),pr.getInstance().registerApi({apiName:"getServerTime",context:this}),pr.getInstance().registerExperimentalAPI("setCustomLoginInfo",this),r.subscribeInnerEvent(ro.RECONNECTED,this._reLogin,this),De.notificationCenter.subscribeInnerEvent(ro.DESTROY,this._dispose,this)}login(r){return mA(this,void 0,void 0,function*(){var g;const{sdkEdition:u}=De.store.get("instance")||{};try{if(this._isLoginIn())return this._createRepeatLoginResponse();if(this._isLoginFrequencyExceeded())throw new gs({functionName:"login",code:da.REPEAT_LOGIN});const E=yield this._performLogin(r);this._validateAfterLogin(E),this._handleLoginSuccess(E),yield this._ensureAsyncComplete(),this._updateAndEmitSDKReady(),this._latestLoginAt=0;const m=(g=De.channel.getSocketAdapter())===null||g===void 0?void 0:g.getId(),{appId:D,href:M}=De.store.get("instance")||{},{instanceID:T,customStatus:P}=E||{};return{code:0,data:E,successLog:{message:u,moreMessage:`socketID:${m} instanceID:${T} customStatus:${P} href: ${M} appId: ${D}`}}}catch(E){const{errorCode:m}=E;m!==da.REPEAT_LOGIN&&(this._latestLoginAt=0);const D=new gs({functionName:"login",code:m});throw console.error(D),D}})}_reLogin(){return mA(this,void 0,void 0,function*(){var r;try{if(!this._isLoginIn())return;const g=yield ku(this._customLoginInfo);if(g){const{instanceID:u,customStatus:E}=g;De.store.set("login",{statusInstanceId:u}),ws.getInstance().executeWorkflow(Jt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,{customStatus:E,statusType:DE.USER_STATUS_ONLINE});const m=(r=De.channel.getSocketAdapter())===null||r===void 0?void 0:r.getId();De.ssoLog.info("reLogin",`socketId:${m} instanceId:${u}`)}}catch(g){console.warn(g)}})}logout(){return mA(this,arguments,void 0,function*(r=ra.USER_INITIATED){const{ssoLog:g}=De;g.debug("logout",`logout start logoutReason: ${r}`);try{yield this._performLogout(r),g.info("logout","logout success"),De.ssoLog.uploadSSOLogData()}catch(u){const{errorCode:E}=u;throw new gs({functionName:"logout",code:E})}finally{this.handleLogoutCompleted()}return{code:0,data:{}}})}getLoginUser(){return this._isLoginIn()?ir():""}isReady(){var r;return(r=De.store.get("login"))===null||r===void 0?void 0:r.isReady}setCustomLoginInfo(r=""){this._customLoginInfo=r}handleLogoutCompleted(){this._updateAndEmitSDKNotReady(),this._reset(),ws.getInstance().reset(),De.notificationCenter.emitInnerEvent("logout")}getServerTime(){const{timeManager:r}=De.common;return r.getServerTimeMs()}_updateAndEmitSDKReady(){De.store.set("login",{isReady:!0}),setTimeout(()=>{De.notificationCenter.emitOuterEvent(Mr.SDK_READY,{name:Mr.SDK_READY})},1)}_updateAndEmitSDKNotReady(){De.store.set("login",{isReady:!1}),De.notificationCenter.emitOuterEvent(Mr.SDK_NOT_READY,{name:Mr.SDK_NOT_READY})}_validateAfterLogin(r){const g="login";if(!r)throw new gs({functionName:g,message:"login response is empty"});const{tinyID:u,a2Key:E}=r||{};if(!u)throw new gs({functionName:g,code:da.NO_TINYID});if(!E)throw new gs({functionName:g,code:da.NO_A2KEY})}_createRepeatLoginResponse(){var r;return{code:0,data:{actionStatus:"OK",errorCode:0,errorInfo:rs({code:"RepeatLogin",replacement1:(r=De.store.get("login"))===null||r===void 0?void 0:r.userId}),repeatLogin:!0}}}_performLogin(r){return mA(this,void 0,void 0,function*(){const{userID:g,userSig:u}=r;return De.store.set("login",{userId:g,userSig:u}),this._latestLoginAt=Date.now(),ku(this._customLoginInfo)})}_ensureAsyncComplete(){return mA(this,void 0,void 0,function*(){yield new Promise(r=>{setTimeout(()=>r(null),1)})})}_handleLoginSuccess(r){const{timeManager:g}=De.common,{helloInterval:u,timeStamp:E,customStatus:m,purchaseBits:D}=r,M=1e3*E;g.calculateTimeOffsetWithServer(this._latestLoginAt,M),this._helloInterval=u||120,this._updateLoginStore(r),De.user.userStatus.setCustomStatus(m),ws.getInstance().executeWorkflow(Jt.SYNC_SERVER_INFO_AFTER_LOGIN,{purchaseBits:D}),De.common.taskScheduler.addTask({id:Gg,intervalMs:1e3*this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this})}_performLogout(r){return function(g){return mA(this,void 0,void 0,function*(){const{logoutReason:u}=g,E="im_open_status.wslogout",m=De.common.generateProtocolData({servcmd:E,data:{wslogout_type:u,isWebUniapp:0}}),D=`${m.head.seq}${E}`;return yield De.channel.sendPacket(m,{requestId:D})})}({logoutReason:r})}_updateLoginStore(r){const{a2Key:g,tinyID:u,instanceID:E,authKey:m}=r;De.store.set("login",{a2Key:g,tinyID:u,statusInstanceId:E,authKey:m,isLoggedIn:!0})}_sendOnlinePresenceRequest(){return mA(this,void 0,void 0,function*(){this._latestSendOnlinePresenceRequestTime=Date.now();try{yield function(){const r="im_open_status.wshello",g=De.common.generateProtocolData({servcmd:r,data:{isWebUniapp:0}}),u=`${g.head.seq}${r}`;return De.channel.sendPacket(g,{requestId:u})}()}catch(r){De.ssoLog.warn("_sendOnlinePresenceRequest",` error:${r.message}`)}})}_isLoginIn(){var r;return((r=De.store.get("login"))===null||r===void 0?void 0:r.isLoggedIn)===!0}_isLoginFrequencyExceeded(){return Date.now()-this._latestLoginAt<=15e3}_reset(){De.common.taskScheduler.removeTask(Gg),this._helloInterval=120,this._latestSendOnlinePresenceRequestTime=0,this._latestLoginAt=0,this._customLoginInfo="",De.store.clear("login"),De.store.set("login",{isReady:!1}),De.store.set("instance",{applicationID:0})}_dispose(){this._reset();const{notificationCenter:r}=De;r.unSubscribeInnerEvent(ro.RECONNECTED,this._reLogin,this),r.unSubscribeInnerEvent(ro.DESTROY,this._dispose,this)}}const mR={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}},XT={logout:!0};class Th{constructor(){this.loginAction=new pR,this.kickedOutHandler=new bu,this.loginAction.init(),this.kickedOutHandler.init(),Wc({auth:XT,params:mR})}}var Kr,AE,qE;(function(s){s.CONV_C2C="C2C",s.CONV_GROUP="GROUP",s.CONV_TOPIC="TOPIC",s.CONV_SYSTEM="@TIM#SYSTEM"})(Kr||(Kr={})),function(s){s.MSG_PRIORITY_HIGH="High",s.MSG_PRIORITY_NORMAL="Normal",s.MSG_PRIORITY_LOW="Low",s.MSG_PRIORITY_LOWEST="Lowest"}(AE||(AE={})),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"}(qE||(qE={}));const VD={1:AE.MSG_PRIORITY_HIGH,2:AE.MSG_PRIORITY_NORMAL,3:AE.MSG_PRIORITY_LOW,4:AE.MSG_PRIORITY_LOWEST},JD=0,fR=1;var eE;(function(s){s.IN="in",s.OUT="out"})(eE||(eE={}));const yR=2,sp={};function cu(s){if(!s)return 0;if(sp[s]===void 0){const r=new Date,g=`3${r.getHours()}`.slice(-2),u=`0${r.getMinutes()}`.slice(-2),E=`0${r.getSeconds()}`.slice(-2);sp[s]=parseInt([g,u,E,"0001"].join(""),10),console.log(`autoIncrementIndex start index:${sp[s]}`)}else sp[s]+=1;return sp[s]}class KE{constructor(r){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=AE.MSG_PRIORITY_NORMAL,this._relayFlag=!1;const{clientTime:g=De.common.timeManager.getServerTimeSeconds()||0,senderTinyID:u,currentUser:E,needReadReceipt:m,isSupportExtension:D,customModerationConfigurationId:M,to:T,from:P,nick:W="",avatar:oA="",time:EA,messageControlInfo:wA,tinyID:kA,cloudCustomData:xA="",messageLifeTime:LA,messageVersion:SA=0,conversationType:OA,sequence:qA,checkResult:Ie=0,isPlaceMessage:le=0,messageFlagBits:bi,receiverList:ki,isSystemMessage:Ot=!1,status:Li=Yr.SUCCESS,revokeReason:cs="",conversationSubType:Re,clientSequence:St,protocol:UA="JSON",revokerInfo:ai={userID:"",nick:"",avatar:""},readReceiptInfo:_s={readCount:void 0,unreadCount:void 0,isPeerRead:void 0,timestamp:0},random:Ui,groupProfile:Or,atUserList:Vi,flow:Ir,isRead:Nt=!1,priority:Gt=AE.MSG_PRIORITY_NORMAL,onlineOnlyFlag:iE=!1,nameCard:ln="",quoteInfo:Qo}=r;var Il;this.clientTime=g,this.senderTinyID=u||kA,this.needReadReceipt=m===!0||m===1,this.isSupportExtension=D===!0||D===1,this._cmConfigID=M,this.to=T,this.nick=W,this.avatar=oA,this.protocol=UA,this.random=Ui===void 0?(Il=Il||99999999,Math.round(Math.random()*Il)):Ui,this.time=EA||Math.ceil(Date.now()/1e3),this._isExcludedFromLastMessage=!!wA?.excludedFromLastMessage,this._isExcludedFromUnreadCount=!!wA?.excludedFromUnreadCount,this.isModified=!!SA,this.cloudCustomData=xA,this.messageLifeTime=LA,this.from=P||null,this.sequence=qA||0,this.conversationType=OA||Kr.CONV_C2C,this.hasRiskContent=Ie>1,this.version=SA,this.isPlaceMessage=le,this.isRevoked=le===2||bi===8,this.isSystemMessage=Ot,this.readReceiptInfo=_s,this.revokeReason=cs,this.revokerInfo=ai,this._receiverList=ki,this.conversationSubType=Re,this.revoker=ai?.revoker||"",this.clientSequence=St||qA||0,this.status=Li,this.atUserList=Vi||[],this.flow=Ir,this.isRead=Nt,this.priority=Gt,this._onlineOnlyFlag=iE,this.nameCard=ln,this.quoteInfo=Qo,this.reInitialize(E),this._initC2CReadReceiptInfo(r),this._extractGroupInfo(Or)}getElements(){return this._elements}isOnlineMessage(){return this.messageLifeTime===0}setElement(r){Array.isArray(r)?this._elements=r:this._elements=[r],this._updatePayloadAndType()}transformElementsToServerFormat(){return this._elements?Array.isArray(this._elements)?this._elements.map(r=>r.transformToServerFormat()):this._elements.transformToServerFormat():null}setRelayFlag(r){this._relayFlag=r}validateBeforeSend(){var r,g,u;return this._relayFlag?{isValid:!0}:((r=this._elements)===null||r===void 0?void 0:r.length)>0?(u=(g=this._elements[0])===null||g===void 0?void 0:g.validateBeforeSend)===null||u===void 0?void 0:u.call(g):{isValid:!1}}_updatePayloadAndType(){this._elements[0]&&(this.payload=this._elements[0].content,this.type=this._elements[0].type)}_initC2CReadReceiptInfo(r){const{readReceiptSentByPeer:g,timestamp:u=0}=r;this.conversationType===Kr.CONV_C2C&&this.needReadReceipt===!0&&(this.readReceiptInfo.isPeerRead=g===1,this.readReceiptInfo.timestamp=u)}_extractGroupInfo(r){if(!r)return;const{From_AccountNick:g,From_AccountHeadurl:u,MsgFrom_AccountExtraInfo:E,GroupType:m}=r,{NameCard:D}=E||{};typeof g=="string"&&(this.nick=g),typeof u=="string"&&(this.avatar=u),typeof D=="string"&&(this.nameCard=D),this.conversationSubType=m}reInitialize(r){r===this.from&&(this.isRead=!0),this._initSequence(r),this._concatConversationID(r),this.generateMessageID()}_concatConversationID(r){let g="";const u=this.conversationType;u!==Kr.CONV_SYSTEM?(g=u===Kr.CONV_C2C?r===this.from?this.to:this.from:this.to,this.conversationID=g?`${u}${g}`:null):this.conversationID=Kr.CONV_SYSTEM}_initSequence(r){this.clientSequence===0&&r&&(this.clientSequence=cu(r)),this.sequence===0&&this.conversationType===Kr.CONV_C2C&&(this.sequence=this.clientSequence)}generateMessageID(){this.from===Kr.CONV_SYSTEM&&(this.senderTinyID="144115198244471703"),this.ID=`${this.senderTinyID}-${this.clientTime}-${this.random}`}setIsRead(r){this.isRead=r}}class Td{static parseServerPushElement(r){const{MsgContent:g={}}=r,{Data:u,Ext:E,Desc:m}=g;return new Td({data:u,description:m,extension:E})}constructor(r){this.type=qE.MSG_CUSTOM;const{data:g="",description:u="",extension:E=""}=r;this.content={data:g,description:u,extension:E}}transformToServerFormat(r){const{isMergerMessage:g=!1}=r||{},u=g?this.payload:this.content,{data:E,description:m,extension:D}=u;return{MsgType:this.type,MsgContent:{Data:E,Ext:D,Desc:m}}}validateBeforeSend(){const{isEmpty:r}=De.utils,g=[this.content.data,this.content.description,this.content.extension].some(u=>!r(u));return{isValid:g,error:g?null:{message:"content can not be empty"}}}}class Nd{static parseServerPushElement(r){const{MsgContent:g={Text:""}}=r,{Text:u}=g;return new Nd({text:u})}constructor(r){this.type=wg.MSG_TEXT,this.content={text:r.text||""}}validateBeforeSend(){var r,g;return((g=(r=this.content)===null||r===void 0?void 0:r.text)===null||g===void 0?void 0:g.length)>0?{isValid:!0}:{isValid:!1,error:{message:"content can not be empty"}}}transformToServerFormat(r){const{isMergerMessage:g=!1}=r||{},u=g?this.payload:this.content,{text:E}=u;return{MsgType:this.type,MsgContent:{Text:E}}}}var Xm=new class{constructor(){this._elementClassMap={[qE.MSG_CUSTOM]:Td,[qE.MSG_TEXT]:Nd}}init(){pr.getInstance().registerApi({apiName:"createCustomMessage",context:this}),pr.getInstance().registerApi({apiName:"createTextMessage",context:this})}registerElementClass(s,r){var g;(g=r).prototype!==void 0&&"constructor"in g.prototype&&(this._elementClassMap[s]=r)}getElementClass(s){return this._elementClassMap[s]}createMessage(s){const{from:r,flow:g=eE.OUT}=s,{userId:u}=De.store.get("login")||{};this._isSendByCurrentInstance({from:r,flow:g,currentUser:u})?this._updateWithSenderInfo(s):this._isMultiEndpointSyncMessage({from:r,flow:g,currentUser:u})&&(s.flow=eE.OUT);const E=Object.assign(Object.assign({},s),{currentUser:u});return new KE(E)}createCustomMessage(s){const r=ir(),g=this.createMessage(Object.assign(Object.assign({},s),{from:r})),u=this._elementClassMap[qE.MSG_CUSTOM];if(!g)return null;if(u){const E=new u(s.payload);g.setElement(E)}return g}createTextMessage(s){var r;if(!s)return null;const g=typeof s.payload=="string"?s.payload:((r=s?.payload)===null||r===void 0?void 0:r.text)||"",u=new Nd({text:g}),E=ir(),m=De.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:E}));return m.setElement(u),m}_updateWithSenderInfo(s){var r,g;const{nick:u,avatar:E,conversationType:m,to:D}=s,{userId:M,tinyID:T}=De.store.get("login")||{},P=rc.getUserProfile(M);return s.nick=u||P?.nick||"",s.avatar=E||P?.avatar||"",s.tinyID=s.tinyID||T||"",s.from=M,s.status=Yr.UNSENT,s.flow=eE.OUT,m===ka.CONV_GROUP&&(s.nameCard=(g=(r=ip.getGroup(D))===null||r===void 0?void 0:r.selfInfo)===null||g===void 0?void 0:g.nameCard),s}_isMultiEndpointSyncMessage(s){const{from:r,flow:g,currentUser:u}=s;return r===u&&g===eE.IN}_isSendByCurrentInstance(s){const{from:r,flow:g,currentUser:u}=s;return r===u&&g===eE.OUT}};const DR={PushFlag:0,Title:"",Desc:"",Ext:"",ApnsInfo:{Sound:"",BadgeMode:0,IsVoipPush:void 0,Image:"",InterruptionLevel:"active",ContentAvailable:0},AndroidInfo:{Sound:"",XiaoMiChannelID:"",OPPOChannelID:"",GoogleChannelID:"",VIVOClassification:1,VIVOCategory:"",HuaWeiCategory:"",OPPOCategory:"",HuaWeiImage:"",HonorImage:"",GoogleImage:"",HonorImportance:"",MeizuNotifyType:void 0}},Gd={HonorImportance:{range:["LOW","NORMAL"],defaultValue:void 0},MeizuNotifyType:{range:[0,1],defaultValue:void 0}},HD={enableIOSBackgroundNotification:{range:[!0,!1],defaultValue:!1},interruptionLevel:{range:["passive","active","time-sensitive","critical"],defaultValue:"active"}};function SR(s,r){return Object.keys(r).forEach(g=>{const{range:u,defaultValue:E}=r[g];s[g]=u.includes(s[g])?s[g]:E}),s}function np(s){const r=s.lastIndexOf(".");return r===-1?s:s.slice(0,r)}function MR(s){const{androidInfo:r={},androidOPPOChannelID:g=""}=s,u=r.OPPOChannelID||g,E=SR(r,Gd),{sound:m="",FCMChannelID:D=""}=E,M=So(E,["sound","FCMChannelID"]);return Object.assign(Object.assign({},M),{Sound:np(m),OPPOChannelID:u,GoogleChannelID:D})}function vR(s){const{apnsInfo:r={},ignoreIOSBadge:g=!1,disableVoipPush:u}=s,E=SR(r,HD),{ignoreIOSBadge:m,disableVoipPush:D,enableIOSBackgroundNotification:M}=E,T=So(E,["ignoreIOSBadge","disableVoipPush","enableIOSBackgroundNotification"]),P=m===!0||g===!0?1:0;let W;return n(u)||(W=u===!1?1:0),n(D)||(W=D===!1?1:0),Object.assign(Object.assign({},T),{BadgeMode:P,IsVoipPush:W,ContentAvailable:M?1:0})}function qD(s){return De.utils.isPlainObject(s)?{PushFlag:s.disablePush===!0?1:0,Title:s.title||"",Desc:s.description||"",Ext:s.extension||"",ApnsInfo:vR(s),AndroidInfo:MR(s)}:DR}function $m(s){const{From_AccountHeadurl:r,From_AccountNick:g,IsNeedReadReceipt:u,IsPeerRead:E,IsSyncMsg:m,MsgBody:D,MsgClientTime:M,MsgLifeTime:T,MsgRandom:P,MsgSeq:W,MsgTimeStamp:oA,SendMsgControl:EA,SupportMessageExtension:wA,TinyId:kA,MsgCheckResult:xA,CloudCustomData:LA,MsgVersion:SA,MsgFlagBits:OA,RevokerInfo:qA,InnerSdkCustomData:Ie}=s;let le,{From_Account:bi,To_Account:ki}=s;if(m===1){const Ot=ki;ki=bi,bi=Ot}if(qA){const{Reason:Ot,Revoker_Account:Li,Revoker_FromUin:cs}=qA;le={reason:Ot,revoker:Li,revokerFromUin:cs,userID:Li}}return{from:bi,avatar:r,nick:g,needReadReceipt:u===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:ki,tinyID:kA,checkResult:xA,cloudCustomData:LA,revokerInfo:le,messageVersion:SA,messageFlagBits:OA,readReceiptSentByPeer:E,elements:TC(D),onlineOnlyFlag:T===0,quoteInfo:rp(Ie)}}function Af(s){const{From_Account:r,MsgBody:g,MsgClientTime:u,MsgRandom:E,MsgSeq:m,MsgTimeStamp:D,To_Account:M,MsgVersion:T,CloudCustomData:P,MsgCheckResult:W}=s;return{from:r,clientTime:u,random:E,sequence:m,time:D,to:M,elements:TC(g),messageVersion:T,cloudCustomData:P,checkResult:W}}function KD(s){const{ClientSeq:r,From_Account:g,GroupInfo:u,MsgBody:E,MsgClientTime:m,MsgRandom:D,MsgSeq:M,MsgTimeStamp:T,SendMsgControl:P,SupportMessageExtension:W,TinyId:oA,CloudCustomData:EA,MsgVersion:wA,MsgCheckResult:kA,NeedReadReceipt:xA,IsPlaceMsg:LA,RevokerInfo:SA,GroupAtInfo:OA,OnlineOnlyFlag:qA,InnerSdkCustomData:Ie}=s;let le,bi=AE.MSG_PRIORITY_NORMAL;if(Object.keys(VD).includes(String(s.MsgPriority))&&(bi=VD[s.MsgPriority]),SA){const{Reason:Ot,Revoker_Account:Li,Revoker_FromUin:cs}=SA;le={reason:Ot,revoker:Li,revokerFromUin:cs,userID:Li}}const ki=function(Ot){const Li=[];return Array.isArray(Ot)&&Ot.forEach(cs=>{cs.GroupAtAllFlag===JD?Li.push(cs.GroupAt_Account):cs.GroupAtAllFlag===fR&&Li.push(Uo.MSG_AT_ALL)}),Li}(OA);return{clientSequence:r,from:g,groupProfile:u,clientTime:m,priority:bi,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:xA,isPlaceMessage:LA,revokerInfo:le,atUserList:ki,elements:TC(E),to:$T(s),onlineOnlyFlag:qA===1,quoteInfo:rp(Ie)}}function $T(s){const{utils:{isEmpty:r},constants:{IS_TOPIC_MESSAGE:g}}=De,{ToGroupId:u,GroupInfo:{MillionGroupFlag:E=0,TopicId:m}={}}=s;return E!==g||r(m)?u:m}function TC(s){if(!s)return null;if(Array.isArray(s))return s.map(g=>{const u=De.message.messageFactory.getElementClass(g.MsgType);return u?.parseServerPushElement(g)});const r=De.message.messageFactory.getElementClass(s.MsgType);return r?.parseServerPushElement(s)}function jD(s){const{From_Account:r,MsgBody:g,MsgClientTime:u,MsgRandom:E,MsgSeq:m,MsgTimeStamp:D,GroupId:M,TopicId:T,MsgVersion:P,CloudCustomData:W,MsgCheckResult:oA}=s;return{from:r,clientTime:u,random:E,sequence:m,time:D,groupID:M,topicID:T,elements:TC(g),messageVersion:P,cloudCustomData:W,checkResult:oA}}function rp(s){const{utils:{isString:r,safeStringify:g},ssoLog:u}=De;if(!r(s))return null;try{const{messageID:E,messageTime:m,messageSequence:D}=JSON.parse(s).businessQuote;return{msgID:E,messageTime:m,messageSequence:D}}catch(E){return u.debug("_parseServerQuoteInfo",g(E)),null}}function ap({conversationUpdateFields:s,message:r}){const{conversationID:g,conversationType:u,conversationSubType:E,flow:m,_isExcludedFromUnreadCount:D,_isExcludedFromLastMessage:M}=r,T=M?"":ep(r),P=!D&&m===eE.IN;s.has(g)?(s.get(g).lastMessage=T,P&&s.get(g).unreadCount++):s.set(g,{conversationID:g,type:u,subType:E,unreadCount:P?1:0,lastMessage:T})}function _B(s){return s.filter(r=>{const g=!Rs(r?._elements),u=r?.isPlaceMessage===1;return g||De.ssoLog.error("emptyMessageBody",`from:${r.from} to:${r.to} sequence:${r.sequence}`),g&&!u})}function TB(s){const{messageDataHandler:r}=De.message;return!r.isInMessageList(s)&&!r.isMessageSentByCurrentInstance(s)}var RR=Object.freeze({__proto__:null,autoIncrementIndex:cu,createAndroidPushInfo:MR,createApnsPushInfo:vR,createOfflinePushInfo:qD,filterValidMessages:_B,getAndroidSoundName:np,parseServerGroupMessage:KD,parseServerPushC2CModifyMessage:Af,parseServerPushGroupModifyMessage:jD,parseServerPushMessage:$m,parseServerPushMessageElement:TC,shouldStoreMessage:TB,updateConversationFields:ap});const{isPlainObject:wR}=De.utils;function gp(s,r={}){const{onlineUserOnly:g,messageControlInfo:u}=r;let{offlinePushInfo:E}=r;s.conversationType===Kr.CONV_C2C&&g===!0&&(E?E.disablePush=!0:E={disablePush:!0});let m="";typeof s.cloudCustomData=="string"&&s.cloudCustomData.length>0&&(m=s.cloudCustomData);const D=[];if(u&&wR(u)){const{excludedFromUnreadCount:M,excludedFromLastMessage:T,excludedFromContentModeration:P}=u;M===!0&&D.push("NoUnread"),T===!0&&D.push("NoLastMsg"),P===!0&&D.push("NoMsgCheck")}return{onlineUserOnly:g,cloudCustomData:m,messageControlInfo:D,offlinePushInfo:E}}function WD(s){const{webhookInfo:{disableCloudMessagePreHook:r=!1,disableCloudMessagePostHook:g=!1}={}}=s||{};if(!r&&!g)return;const u=[];return r&&u.push("ForbidBeforeSendMsgCallback"),g&&u.push("ForbidAfterSendMsgCallback"),u}function Nh(s,r){return mA(this,void 0,void 0,function*(){const g=s.conversationType===Kr.CONV_GROUP?function(E,m){var D;const M=gp(E,m),{onlineUserOnly:T,cloudCustomData:P,messageControlInfo:W,offlinePushInfo:oA}=M,EA=JSON.parse(JSON.stringify(E.transformElementsToServerFormat()));let wA;return C(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=De.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:qD(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:WD(m),InnerSdkCustomData:GB(E)}}}(s,r):function(E,m){var D;const M=gp(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=De.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:qD(oA),ForbidCallbackControl:WD(m),InnerSdkCustomData:GB(E)}}}(s,r),u=yield gg(g);return u?{time:u.MsgTime,messageDropReason:u.MsgDropReason,sequence:u.MsgSeq}:null})}function Gh(s){return mA(this,void 0,void 0,function*(){const{from:r,to:g,version:u=0,sequence:E,random:m,time:D,type:M,cloudCustomData:T}=s,P={From_Account:r,To_Account:g,MsgVersion:u,MsgSeq:E,MsgRandom:m,MsgTime:D,MsgType:M,MsgBody:s.transformElementsToServerFormat(),CloudCustomData:T},W=yield gg({servcmd:"openim.modify_c2c_msg",data:P});if(W){const{MsgBody:oA,MsgVersion:EA,CloudCustomData:wA}=W;return{elements:TC(oA),messageVersion:EA,cloudCustomData:wA}}})}function NB(s){return mA(this,void 0,void 0,function*(){const{to:r,version:g=0,sequence:u,cloudCustomData:E}=s,m={GroupId:r,MsgVersion:g,MsgSeq:u,MsgBody:s.transformElementsToServerFormat(),CloudCustomData:E},D=yield gg({servcmd:"openim.modify_group_msg",data:m});if(D){const{MsgBody:M,MsgVersion:T,CloudCustomData:P}=D;return{elements:TC(M),messageVersion:T,cloudCustomData:P}}})}function bh(s){return mA(this,void 0,void 0,function*(){const{groupID:r,count:g,messageSequence:u,messageSequenceList:E,getType:m}=s,D={GroupId:r,ReqMsgNumber:g,WithRecalledMsg:1,Version:1,GetType:m};return u&&(D.ReqMsgSeq=u),C(E)&&E.length>0&&(D.ReqMsgSeqList=E),yield gg({servcmd:"group_open_http_svc.group_msg_get",data:D})})}function ef(s){return mA(this,void 0,void 0,function*(){const{peerAccount:r,count:g,lastMessageTime:u,messageKey:E,direction:m}=s;return gg({servcmd:"openim.getroammsg",data:{Peer_Account:r,MaxCnt:g,WithRecalledMsg:1,LastMsgTime:u,MsgKey:E,GetDirection:m}})})}function GB(s){if(De.utils.isObject(s.quoteInfo)){const{msgID:r,messageSequence:g,messageTime:u}=s.quoteInfo;return JSON.stringify({businessQuote:{messageID:r,messageSequence:g,messageTime:u}})}}var zD=Object.freeze({__proto__:null,createMessagePackOptions:gp,generateForbidCallbackControl:WD,getC2CRoamingMessagesByAnchor:ef,getGroupRoamingMessagesByAnchor:bh,getRoamingMessages:function(s){return mA(this,void 0,void 0,function*(){const{peerAccount:r,count:g,lastMessageTime:u,messageKey:E}=s;return(yield gg({servcmd:"openim.getroammsg",data:{Peer_Account:r,MaxCnt:g||15,LastMsgTime:u||0,MsgKey:E,GetDirection:0,WithRecalledMsg:1}}))||[]})},modifyC2CMessage:Gh,modifyGroupMessage:NB,sendMessage:Nh});const{isPlainObject:AN}=De.utils,{MSG_AUDIO:ZD,MSG_FILE:XD,MSG_IMAGE:_R,MSG_VIDEO:TR,MSG_MERGER:NR}=Uo;class tf{constructor(){this._sendProtocolMap=new Map}init(){pr.getInstance().registerApi({apiName:"sendMessage",context:this,matcher:r=>![ZD,XD,_R,TR,NR].includes(r[0].type)})}registerSendProtocol(r,g,u){this._sendProtocolMap.set(r,g.bind(u))}sendMessage(r,g){return mA(this,void 0,void 0,function*(){const{TOTAL_COUNT:u,SEND_COST:E,SUCCESS_COUNT:m,FAILED_COUNT:D}=cr;if(!(r instanceof KE))throw new gs({code:da.MSG_INSTANCE_REQUIRED});const M=r.validateBeforeSend();if(!M.isValid){const{code:W,message:oA=""}=M.error||{};throw new gs({code:W,message:oA})}this._reportMessageSendQuality({name:u,message:r});let T=!1;const{messageDataHandler:P}=De.message||{};try{const{messageControlInfo:W}=g||{};let oA=null;P.addRandomOfSentMessage(r.random);const EA=Date.now(),wA=this._getSendProtocol(r);if(r.conversationType===Kr.CONV_C2C?(T=g?.onlineUserOnly===!0,oA=yield wA(r,g)):r.conversationType===Kr.CONV_GROUP&&(yield this._validateBeforeSendGroupMessage(r),oA=yield wA(r,g)),oA){const{messageDropReason:kA,sequence:xA,time:LA}=oA;if(this._updateNickAndAvatarOfSentMessageByMe(r),kA&&this._logRateLimitInfo(r,xA,kA),this._reportMessageSendQuality({name:m,message:r}),this._reportMessageSendQuality({name:E,message:r,startTs:EA}),r.isResend===!0){const SA=P.findMessage(r.ID);SA&&(De.ssoLog.debug("sendMessage",`sendMessage resend ok. ID:${SA.ID}`),P.deleteConversationMessage(SA))}return r.status=Yr.SUCCESS,r.time=LA,r.conversationType===Kr.CONV_GROUP&&(r.sequence=xA),T?r._onlineOnlyFlag=!0:(P.storeConversationMessage(r),this._applySentMessageControlInfo(r,W),this._emitOnlineMessageSent(r)),r.type===wg.MSG_STREAM?{code:0,data:{message:r,streamMessageID:oA.streamMessageID}}:{code:0,data:{message:r}}}}catch(W){r.status=Yr.FAIL,P.removeRandomOfSentMessage(r.random);let{errorCode:oA}=W||{},EA=W?.errorInfo||W?.message||"";throw this._hasRiskContent(oA)&&(r.hasRiskContent=!0),T||this._isRejectedByRestApi(oA)||P.storeConversationMessage(r),this._reportMessageSendQuality({name:D,message:r,error:W}),new gs({code:oA,message:EA,data:{message:r},moreMessage:`type:${r.type} from:${r.from} to:${r.to}`})}})}_hasRiskContent(r){return r===80001||r===80004}_isRejectedByRestApi(r){return r>=10100&&r<=10200||r>=120001&&r<=13e4}_emitOnlineMessageSent(r){const g=r._isExcludedFromLastMessage?"":r,{conversationID:u,conversationType:E}=r,m=zc(u)?ro.TOPIC_NEW_MESSAGE:ro.NEW_MESSAGE;De.notificationCenter.emitInnerEvent(m,{result:{conversationUpdateFieldList:[{conversationID:u,type:E,message:r,lastMessage:g,unreadCount:0}]}})}_applySentMessageControlInfo(r,g){g&&AN(g)&&(g.excludedFromLastMessage===!0&&(r._isExcludedFromLastMessage=!0),g.excludedFromUnreadCount===!0&&(r._isExcludedFromUnreadCount=!0))}_logRateLimitInfo(r,g,u){const E=`from:${r.from} to:${r.to} sequence:${g} messageDropReason:${u}`;De.ssoLog.warn("messageDropReason",E)}_updateNickAndAvatarOfSentMessageByMe(r){const{messageDataHandler:g}=De.message||{};let u=!1;const{conversationID:E}=r,m=g.getLatestMsgSentByMe(E);if(m){const{nick:D,avatar:M}=m;D===r.nick&&M===r.avatar||(u=!0),u&&g.updateNickAndAvatarOfSentMessage({conversationID:E,latestNick:r.nick,latestAvatar:r.avatar,isSentByMe:!0})}}_validateBeforeSendGroupMessage(r){return mA(this,void 0,void 0,function*(){var g,u,E;const{to:m,from:D}=r;let M=m,T=ip.getGroup(M);if($r({groupID:M})&&T?.isSupportTopic)throw new gs({code:da.MSG_SEND_GRP_WITH_TOPIC_FAIL});if(zc(m)&&([M]=m.split(na.TOPIC),T=ip.getGroup(M)),!T&&typeof((g=pr.getInstance().getApiMap())===null||g===void 0?void 0:g.getGroupProfile)=="function"){const P=yield pr.getInstance().getApiMap().getGroupProfile({groupID:M});if(((E=(u=P?.data)===null||u===void 0?void 0:u.group)===null||E===void 0?void 0:E.type)===Uo.GRP_AVCHATROOM){const W=rs({code:da.MSG_SEND_FAIL_NOT_IN_AV,replacement1:D,replacement2:M});throw new gs({code:da.MSG_SEND_FAIL_NOT_IN_AV,message:W})}}return!0})}_reportMessageSendQuality(r){De.notificationCenter.emitInnerEvent(ro.QUALITY_STAT,{label:lI.MESSAGE_SEND_SUCCESS_RATE,data:r})}_getSendProtocol(r){return this._sendProtocolMap.get(r.type)||Nh}}var eN=new class{constructor(){this._sparseMessagesByConversation=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new Set}init(){De.notificationCenter.subscribeInnerEvent(ro.LOGOUT,this._reset,this),De.notificationCenter.subscribeInnerEvent(ro.DESTROY,this._dispose,this)}get _messagesByConversation(){return op.getMessages()}storeConversationMessage(s,r=!1){if(an)return!0;const{conversationID:g}=s;if(!g||(this._messagesByConversation.has(g)||this._messagesByConversation.set(g,new Map),this._shouldSkipStoreMessage(s,r)))return!1;const u=this._getUniqueIdOfMessage(s);return this._messagesByConversation.get(g).set(u,s),this._updateLatestMessageMap(s),!0}_updateLatestMessageMap(s){const{conversationID:r}=s;s.flow==="out"?this._setLatestMsgSentByMe(r,s):r.startsWith("C2C")&&this._setLatestMsgSentByPeer(r,s)}_shouldSkipStoreMessage(s,r){const g=this._getUniqueIdOfMessage(s),u=this._messagesByConversation.get(s.conversationID);if(u?.has(g)){const E=u?.get(g);if(!r||E?.isModified===!0)return!0}return!1}deleteConversationMessage(s){var r;const{conversationID:g=""}=s,u=this._getUniqueIdOfMessage(s);this._messagesByConversation.has(g)&&((r=this._messagesByConversation.get(g))===null||r===void 0||r.delete(u))}modifyConversationMessage(s,r){var g;if(!this._messagesByConversation.has(s)&&!this._sparseMessagesByConversation.has(s))return{isUpdated:!1,message:null};const u=this._getUniqueIdOfMessage(r),E=this._getMessageFromLocalMessage(s,u);if(E){const{messageVersion:m,elements:D,cloudCustomData:M,checkResult:T=0}=r,P=T>1;if(De.ssoLog.debug("modifyConversationMessage",`conversationToMessageMap modifyConversationMessage localVersion:${E.version} remoteVersion:${m}`),E.versionE.ID===s)||null,r)break;if(!r){const u=Array.from(this._sparseMessagesByConversation.values());for(const E of u)if(r=E.get(s)||null,r)break}return r}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:r,random:g,revoker:u}){const E=this._messagesByConversation.get(s);let m=null;if(E){const D=Array.from(E.values());if(m=this._findMessageBySequenceAndRandom({messageList:D,random:g,sequence:r}),m){const M=this._getUniqueIdOfMessage(m);return op.updateMessage(s,[M],{isRevoked:!0,revoker:u,operation:yc.revoke}),m}}if(this._sparseMessagesByConversation.has(s)){const D=Array.from(this._sparseMessagesByConversation.get(s).values());if(m=this._findMessageBySequenceAndRandom({messageList:D,random:g,sequence:r}),m)return m.isRevoked=!0,m.revoker=u,m}}_findMessageBySequenceAndRandom({messageList:s,sequence:r,random:g}){for(let u=0;u0){const D=new Map([...E,...m.entries()]);this._messagesByConversation.set(g,D),this._updateLatestMessageSentByMe(g),this._updateLatestMessageSentByPeer(g)}return u}storeSparseMessageList(s){if(s.length===0)return;const{conversationID:r}=s[0],g=s.length;this._sparseMessagesByConversation.has(r)||this._sparseMessagesByConversation.set(r,new Map);const u=this._sparseMessagesByConversation.get(r);for(let E=0;E=0;u--)if(g[u].flow==="out"){this._setLatestMsgSentByMe(s,g[u]);break}}}_updateLatestMessageSentByPeer(s){var r;const g=Array.from(((r=this._messagesByConversation.get(s))===null||r===void 0?void 0:r.values())||[]);if(g.length!==0&&s.startsWith("C2C")){for(let u=g.length-1;u>=0;u--)if(g[u].flow==="in"){this._setLatestMsgSentByPeer(s,g[u]);break}}}_getUniqueIdOfMessage(s){const{from:r,to:g,random:u,sequence:E,time:m}=s;return`${r}-${g}-${u}-${E}-${m}`}_setLatestMsgSentByPeer(s,r){this._latestMessageSentByPeerMap.set(s,r)}_setLatestMsgSentByMe(s,r){this._latestMessageSentByMeMap.set(s,r)}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:r="",latestAvatar:g,latestNick:u,isSentByMe:E=!0}=s,m=this._messagesByConversation.get(r);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!==u&&(T.nick=u),W!==g&&(T.avatar=g))})}isInMessageList(s){var r;const{conversationID:g}=s;if(!g||!this._messagesByConversation.has(g))return!1;const u=this._getUniqueIdOfMessage(s);return(r=this._messagesByConversation.get(g))===null||r===void 0?void 0:r.has(u)}isMessageSentByCurrentInstance(s){const{random:r}=s;return this._randomOfSentMessageList.has(r)}getContinuousMessagesByConversation(){return this._messagesByConversation}getLocalMessageList(s){const r=this._messagesByConversation.get(s);return r?[...r.values()]:[]}getSparseMessageList(s){const r=this._sparseMessagesByConversation.get(s);return r?[...r.values()]:[]}_reset(){this._messagesByConversation.clear(),this._latestMessageSentByPeerMap.clear(),this._latestMessageSentByMeMap.clear(),this._randomOfSentMessageList.clear()}_dispose(){this._reset(),De.notificationCenter.unSubscribeInnerEvent(ro.LOGOUT,this._reset,this),De.notificationCenter.unSubscribeInnerEvent(ro.DESTROY,this._dispose,this)}};function of(s,r){const g=wB.getConversation(s);if(g?.lastMessage){const{lastMessage:u}=g,{lastTime:E,lastSequence:m,version:D}=u,{time:M,sequence:T,messageVersion:P,elements:W,cloudCustomData:oA}=r;E===M&&m===T&&D!==P&&(u.type=W[0].type,u.payload=W[0].content,u.messageForShow=Zc(u.type,u.payload),u.cloudCustomData=oA,u.version=P,wB.updateConversation(s,{lastMessage:u}))}}class GR{init(){pr.getInstance().registerApi({apiName:"modifyMessage",context:this})}modifyMessage(r){return mA(this,void 0,void 0,function*(){const{to:g,payload:u,sequence:E,conversationType:m,random:D,time:M,from:T,type:P}=r;if(this._canModifyMessageElement(P)){const W=r?._elements||[];W.length>=1&&(W[0].type=P,W[0].content=u)}try{let W=null,oA=null;if(m===Kr.CONV_C2C?W=yield Gh(r):m===Kr.CONV_GROUP&&(W=yield NB(r)),W){let EA=`${m}${g}`;return g===ir()&&m===Kr.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:r},successLog:{message:`to:${g}`}}}}catch(W){const{errorCode:oA}=W||{};throw new gs({functionName:"modifyMessage",code:oA,moreMessage:`to:${g}`})}})}_handleModifyMessageSuccess(r){const{conversationID:g}=r,{isUpdated:u,message:E}=De.message.messageDataHandler.modifyConversationMessage(g,r);u===!0&&De.notificationCenter.emitOuterEvent(Mr.MESSAGE_MODIFIED,{name:Mr.MESSAGE_MODIFIED,data:[E]}),De.notificationCenter.emitInnerEvent(ro.MESSAGE_MODIFIED,{conversationID:g,message:E}),of(g,r)}_canModifyMessageElement(r){return[qE.MSG_TEXT,qE.MSG_CUSTOM,qE.MSG_LOCATION,qE.MSG_FACE].includes(r)}}class kh{init(){const{notificationCenter:r}=De,{InnerEventSubType:g}=r;ws.getInstance().registerWorkflowStep(Jt.RECEIVE_C2C_NEW_MESSAGE,Wt.HANDLE_C2C_NEW_MESSAGE,this._handleC2CMessagePush,this),ws.getInstance().registerWorkflowStep(Jt.RECEIVE_C2C_NEW_MESSAGE,Wt.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterReceiveNewMessage,this),ws.getInstance().registerWorkflowStep(Jt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Wt.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterSyncUnreadMessage,this),r.subscribeInnerEvent(ro.MESSAGE_PUSH,g.C2C_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),r.subscribeInnerEvent(ro.MESSAGE_PUSH,g.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),r.subscribeInnerEvent(ro.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(r){ws.getInstance().executeWorkflow(Jt.RECEIVE_C2C_NEW_MESSAGE,r)}_handleC2CMessagePush(r){const g=r.data||{},{messageDataHandler:u}=De.message||{},E=[],m=new Map;return g.C2cMsgArray.forEach(D=>{const M=this._generateC2CMessage(D);this._updateMessageProfile(M);let T=M.isModified===1;u.isMessageSentByCurrentInstance(M)?M.isModified=T:T=!1,M._onlineOnlyFlag?u.isMessageSentByCurrentInstance(M)||E.push(M):TB(M)&&(u.storeConversationMessage(M)&&ap({conversationUpdateFields:m,message:M}),u.isMessageSentByCurrentInstance(M)&&!T||E.push(M))}),{conversationUpdateFieldList:[...m.values()],messages:E}}_emitMessageEventsAfterReceiveNewMessage(r){var g;const{messages:u=[]}=((g=r.result)===null||g===void 0?void 0:g[Wt.HANDLE_C2C_NEW_MESSAGE])||{};this._emitMessageEvents(u)}_emitMessageEventsAfterSyncUnreadMessage(r){var g;const{messages:u=[]}=((g=r.result)===null||g===void 0?void 0:g[Wt.UNREAD_MESSAGE_SYNC])||{};this._emitMessageEvents(u)}_emitMessageEvents(r){const g=r?.filter(E=>E?.isModified===!0)||[];g.length>0&&De.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:g});const u=r?.filter(E=>!E?.isModified);u.length>0&&De.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:u})}_generateC2CMessage(r){const g=Kr.CONV_C2C,u=$m(r),E=De.message.messageFactory.createMessage(Object.assign(Object.assign({},u),{conversationType:g,flow:eE.IN})),{elements:m}=u;return E.setElement(m),E}_updateMessageProfile(r){var g;const{messageDataHandler:u}=De.message||{},E=(g=De.store.get("login"))===null||g===void 0?void 0:g.userId,{from:m,nick:D,avatar:M,conversationID:T=""}=r;if(m!==E){const P=u.getLatestMsgSentByPeer(T);if(P){const{nick:W,avatar:oA}=P;n(D)||n(M)?(r.nick=c(W)?W:r.nick,r.avatar=c(oA)?oA:r.avatar):D===W&&M===oA||(u.updateNickAndAvatarOfSentMessage({conversationID:T,latestNick:D,latestAvatar:M,isSentByMe:!1}),this._updateConversationUserProfile({conversationID:T,nick:D,avatar:M}))}}else{const P=u.getLatestMsgSentByMe(T);!P||D===P.nick&&M===P.avatar||u.updateNickAndAvatarOfSentMessage({conversationID:T,latestNick:D,latestAvatar:M,isSentByMe:!0})}}_updateConversationUserProfile(r){const{conversationID:g,nick:u,avatar:E}=r,m=wB.getConversation(g),{userProfile:D={}}=m||{};D.avatar===E&&D.nick===u||wB.updateConversation(g,{userProfile:Object.assign(Object.assign({},D),{nick:u,avatar:E})})}_updateMessageListDueToModify(r){const{conversationID:g}=r,{isUpdated:u,message:E}=De.message.messageDataHandler.modifyConversationMessage(g,r);u===!0&&De.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[E]}),De.notificationCenter.emitInnerEvent("ModifyMessageSuccess",r),of(g,r)}_handleC2CMessageModify(r){r.C2cMsgModNotifys.forEach(g=>{var u;const E=Kr.CONV_C2C;let m=Af(g);const{to:D,from:M}=m;let T=`${E}${D}`;D===((u=De.store.get("login"))===null||u===void 0?void 0:u.userId)&&(T=`${E}${M}`),m=Object.assign({conversationType:E,conversationID:T},m),this._updateMessageListDueToModify(m)})}_dispose(){const{notificationCenter:r}=De,{InnerEventSubType:g}=r;De.notificationCenter.unSubscribeInnerEvent(ro.MESSAGE_PUSH,g.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),De.notificationCenter.unSubscribeInnerEvent(ro.MESSAGE_PUSH,g.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),De.notificationCenter.unSubscribeInnerEvent(ro.DESTROY,this._dispose,this)}}class Lh{init(){const{notificationCenter:r}=De,{InnerEventSubType:g}=r;ws.getInstance().registerWorkflowStep(Jt.RECEIVE_GROUP_NEW_MESSAGE,Wt.HANDLE_GROUP_NEW_MESSAGE,this._handleGroupMessagePush,this),ws.getInstance().registerWorkflowStep(Jt.RECEIVE_GROUP_NEW_MESSAGE,Wt.EMIT_GROUP_MESSAGE_EVENT,this._emitMessageEvents,this),r.subscribeInnerEvent(ro.MESSAGE_PUSH,g.GROUP_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),r.subscribeInnerEvent(ro.MESSAGE_PUSH,g.GROUP_MESSAGE_MODIFIED,this._handleGroupMessageModify,this),r.subscribeInnerEvent(ro.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(r){this._canExecuteReceiverNewMessageWorkFlow(r)&&ws.getInstance().executeWorkflow(Jt.RECEIVE_GROUP_NEW_MESSAGE,r)}_handleGroupMessagePush(r){const g=r.data||{},{messageDataHandler:u}=De.message,E=[],m=new Map,D=g?.GroupMsgArray;return D?.forEach(M=>{if(M.GroupInfo.NotVisible===1)return;const T=this._generateGroupMessage(M);this.updateMessageProfile(T);let P=T.isModified===1;u.isMessageSentByCurrentInstance(T)?T.isModified=P:P=!1,T._onlineOnlyFlag?u.isMessageSentByCurrentInstance(T)||E.push(T):TB(T)&&u.storeConversationMessage(T)&&(E.push(T),ap({conversationUpdateFields:m,message:T}))}),{conversationUpdateFieldList:[...m.values()],messages:E}}_emitMessageEvents(r){var g;const{messages:u}=((g=r.result)===null||g===void 0?void 0:g[Wt.HANDLE_GROUP_NEW_MESSAGE])||{},E=u?.filter(D=>D?.isModified===!0)||[];E.length>0&&De.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:E});const m=u?.filter(D=>!D?.isModified)||[];m.length>0&&De.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:m})}_generateGroupMessage(r){const g=Kr.CONV_GROUP,u=KD(r),E=De.message.messageFactory.createMessage(Object.assign(Object.assign({},u),{conversationType:g,flow:eE.IN})),{elements:m}=u;return E.setElement(m),E}updateMessageProfile(r){var g;const{messageDataHandler:u}=De.message||{},E=(g=De.store.get("login"))===null||g===void 0?void 0:g.userId,{from:m,nick:D,avatar:M,conversationID:T="",_elements:P}=r;if(m===E){const W=u.getLatestMsgSentByMe(T);!W||D===W.nick&&M===W.avatar||u.updateNickAndAvatarOfSentMessage({conversationID:T,latestNick:D,latestAvatar:M,isSentByMe:!0})}else if(m===Uo.CONV_SYSTEM){const{operationType:W,memberInfoList:oA,operatorInfo:EA}=P;let wA={};if(Rs(oA)?Rs(EA)||(wA=EA):[Tg.JOINED,Tg.KICKED,Tg.ADMIN_SET,Tg.ADMIN_CANCELED].includes(W)&&(wA=Object.assign({},oA[0])),!Rs(wA)){const{nick:kA="",avatar:xA=""}=wA;r.nick=kA,r.avatar=xA}}}_updateMessageListDueToModify(r){const{conversationID:g}=r,{isUpdated:u,message:E}=De.message.messageDataHandler.modifyConversationMessage(g,r);u===!0&&De.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[E]}),of(g,r)}_handleGroupMessageModify(r){r.GroupMsgModNotifys.forEach(g=>{const u=Kr.CONV_GROUP;let E=jD(g);const{topicID:m,groupID:D}=E,M=m||D,T=`${u}${M}`;E=Object.assign({conversationType:u,conversationID:T,to:M},E),this._updateMessageListDueToModify(E)})}_dispose(){const{notificationCenter:r}=De,{InnerEventSubType:{GROUP_REALTIME_MESSAGE:g,GROUP_MESSAGE_MODIFIED:u}}=r;r.unSubscribeInnerEvent(ro.MESSAGE_PUSH,g,this._handleGroupMessagePush,this),r.unSubscribeInnerEvent(ro.MESSAGE_PUSH,u,this._handleGroupMessageModify,this),r.unSubscribeInnerEvent(ro.DESTROY,this._dispose,this)}_canExecuteReceiverNewMessageWorkFlow(r){var g,u;const{GroupId:E,GroupType:m}=((u=(g=r?.GroupMsgArray)===null||g===void 0?void 0:g[0])===null||u===void 0?void 0:u.GroupInfo)||{},D=m===La.GRP_AVCHATROOM;return!(!ip.getGroup(E)&&D)}}var $D=new class{constructor(){this.c2cMessageReceiver=new kh,this.groupMessageReceiver=new Lh}init(){this.c2cMessageReceiver.init(),this.groupMessageReceiver.init()}};const bR={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(r){var g;return typeof r?.text!="string"||typeof r.text=="string"&&((g=r?.text)===null||g===void 0?void 0:g.length)===0?"payload.text must be a string":!0}(s)}}},tN={createCustomMessage:!0,sendMessage:!0,modifyMessage:!0};var iN=new class{constructor(){this._historyMessageListFetchAnchors=new Map,this.completedHistoryConversations=new Set}getGroupRoamingMessagesByAnchor(s){return mA(this,void 0,void 0,function*(){try{const{conversationID:r,count:g,direction:u,sequence:E,messageSequenceList:m,shouldMarkCompleted:D=!1,getType:M}=s,T=r.replace(ka.CONV_GROUP,""),P=[];let W=E;if(u===Kc.BACKWARD){if(typeof E!="number")return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};W=E+g-1}const oA=yield bh({groupID:T,count:g,messageSequence:W,messageSequenceList:m,getType:M});if(oA){const{RspMsgList:EA=[],NextReqMsgSeq:wA=0,IsFinished:kA,InvisibleMsgSeq:xA}=oA,LA=`groupID:${T} sequence:${E} reqSeq:${W} direction:${u} complete:${kA} nextSequence:${wA} remoteMsgCount:${EA.length} invisibleSequenceList:${xA}`,SA=[];for(let Ie=0;Ie=E),OA&&D&&this.completedHistoryConversations.add(r);const qA=_B(SA);return De.ssoLog.info("getGroupRoamingMessagesByAnchor",LA),{messageList:qA,invisibleSequenceList:xA,nextReqMessageIDFromServer:wA,hasNoMoreHistoryMessage:OA,serverGroupTipList:P}}}catch(r){const{errorCode:g,errorInfo:u}=r||{};throw new gs({code:g,message:u})}})}clearHistoryMessageListFetchAnchors(s){this._historyMessageListFetchAnchors.delete(s)}isHistoryMessageFetchCompleted(s){return this.completedHistoryConversations.has(s)}_parseMessage(s){var r;const g=ka.CONV_GROUP;s.Event===4&&(s.MsgBody.MsgType=Uo.MSG_GRP_TIP);const u=KD(s),E=Xm.createMessage(Object.assign(Object.assign({},u),{conversationType:g,flow:"in"}));return RB(((r=u.elements)===null||r===void 0?void 0:r.content)||{},E),E.setElement(u.elements),E}getC2CRoamingMessagesByAnchor(s){return mA(this,void 0,void 0,function*(){var r;try{const{conversationID:g,count:u,messageID:E,time:m,direction:D,shouldMarkCompleted:M=!1}=s;let T=m,P="";if(!m){const EA=E?De.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(ka.CONV_C2C,""),oA=yield ef({count:u,lastMessageTime:T,messageKey:P,peerAccount:W,direction:D});if(oA){const{MsgList:EA=[],Complete:wA,MsgKey:kA,LastMsgTime:xA}=oA;this._historyMessageListFetchAnchors.set(g,{messageKey:kA,lastMessageTime:xA});const LA=[];for(let Ie=0;Ie{const{tag:E,value:m}=u;E&&E.indexOf(eS)>-1?g.profileCustomField.push({key:E,value:m}):bd.has(E)&&(g[bd.get(E)]=m)}),Object.assign(Object.assign({},sf),g)}parseProfileItem(s=[]){const r=[];return s.forEach(g=>{r.push({tag:g.Tag,value:g.Value})}),r}parseProfileList(s=[]){const r=[];return s.forEach(g=>{r.push({tag:g.Tag,value:g.ValueBytes})}),r}convertParamsToProfile(s){const r=[];return Object.keys(s).forEach(g=>{g!==tS&&r.push({tag:Yl[g.toUpperCase()],value:s[g]})}),s.profileCustomField&&C(s.profileCustomField)&&s.profileCustomField.forEach(g=>{r.push({tag:g.key,value:g.value})}),r}normalizeProfileFields(s){const r={},g=[];return s.forEach(u=>{const{tag:E,value:m}=u;if(E&&E.indexOf(eS)>-1&&g.push({key:E,value:m}),bd.has(E)&&m!==void 0){const D=bd.get(E);r[D]=m}}),g.length>0&&(r.profileCustomField=g),r}};const{generateProtocolData:LR}=De.common;function UR(s){return mA(this,void 0,void 0,function*(){const r="profile.portrait_get_all",g={From_Account:ir(),UserItem:[]};s.forEach(D=>{g.UserItem.push({CustomSequence:0,StandardSequence:0,To_Account:D})});const u=LR({servcmd:r,data:g}),E=`${u.head.seq}${r}`,m=yield De.channel.sendPacket(u,{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:xA,ResultCode:LA,ResultInfo:SA,StandardSequence:OA,ProfileItem:qA}=wA,Ie=tE.parseProfileItem(qA);EA.push({userId:kA,customSequence:xA,resultCode:LA,resultInfo:SA,standardSequence:OA,profileItem:Ie})}),{actionStatus:M,errorCode:T,errorDisplay:P,errorInfo:W,userProfile:EA}}(m)})}function jE(s){return rc.getFriendMap().has(s)}const{isEmpty:iS}=De.utils;class nf{constructor(){this._strangerProfileMap=new Map}init(){pr.getInstance().registerApi({apiName:"getMyProfile",context:this}),pr.getInstance().registerApi({apiName:"getUserProfile",context:this}),pr.getInstance().registerApi({apiName:"updateMyProfile",context:this}),this.createProfile=tE.createProfile.bind(tE);const{notificationCenter:r}=De;ws.getInstance().registerWorkflowStep(Jt.SYNC_SERVER_INFO_AFTER_LOGIN,Wt.USER_PROFILE_SYNC,this.getMyProfileCacheThenServer,this),r.subscribeInnerEvent(ro.MESSAGE_PUSH,r.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),r.subscribeInnerEvent(ro.LOGOUT,this._reset,this),r.subscribeInnerEvent(ro.DESTROY,this._dispose,this)}getMyProfile(){return mA(this,void 0,void 0,function*(){try{const r=ir(),g=yield UR([r]);if(g){const u=this._handleProfileFormResponse(g)[0];return rc.getUserProfileMap().set(r,u),{code:0,data:u}}}catch(r){const{errorCode:g,errorInfo:u}=r;throw new gs({functionName:"getMyProfile",code:g,message:u})}})}getUserProfile(r){return mA(this,void 0,void 0,function*(){try{let{userIDList:g}=r;const{userIdListToRequest:u,profileFromCache:E}=this._filterRequestAndCacheUsers(g);if(u.length===0)return{code:0,data:E,successLog:{message:`userIDList.length:${g.length}`}};u.length>kR&&(De.ssoLog.warn("getUserProfile","userIdListToRequest.length > 1000"),u.length=kR);const{data:m,error:D}=yield this._batchFetchUserProfiles(u),M=u.length,T=m.length,P=M-T;if(E.length===0&&M===P&&!iS(D))throw D;if(C(m))return m.forEach(oA=>{jE(oA.userID)?rc.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 gs(g)}})}getMyProfileCacheThenServer(){return mA(this,void 0,void 0,function*(){const r=ir(),g=rc.getUserProfileMap().has(r);return g?{code:0,data:g}:this.getMyProfile()})}updateMyProfile(r){return mA(this,void 0,void 0,function*(){const g=ir(),u={};for(const m in r)r[m]!==void 0&&(u[m]=r[m]);const E=tE.convertParamsToProfile(u);try{yield function(P){return mA(this,void 0,void 0,function*(){const W="profile.portrait_set",oA=LR({servcmd:W,data:P}),EA=`${oA.head.seq}${W}`,wA=yield De.channel.sendPacket(oA,{requestId:EA});if(wA){const{ActionStatus:kA,ErrorCode:xA,ErrorDisplay:LA,ErrorInfo:SA}=wA;return{actionStatus:kA,errorCode:xA,errorDisplay:LA,errorInfo:SA}}})}({From_Account:g,ProfileItem:E});const D=rc.getUserProfile(g);let M;M=D?Object.assign(Object.assign({},D),u):tE.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: ${De.utils.safeStringify(E)}`}}}catch(m){const{errorCode:D,errorInfo:M}=m;throw new gs({functionName:"updateMyProfile",code:D,message:M,moreMessage:`params: ${De.utils.safeStringify(r)}`})}})}updateMyNickAndAvatar(r){return mA(this,void 0,void 0,function*(){const g=ir(),u=Date.now(),E=rc.getUserProfile(g);let m={};m=E?Object.assign(E,r):tE.createProfile(g,r),m.lastUpdatedTime=u,rc.getUserProfileMap().set(g,m)})}_onProfileDataModify(r){const g=function(m){const{Profile_Account:D,PushType:M,ProfileList:T}=m;return{userId:D,pushType:M,profileList:tE.parseProfileList(T)}}(r.ProfileDataMod[0]);if(iS(g))return;const{isProfileUpdated:u,profile:E}=this._handleProfileModified(g);u&&this._emitProfileUpdated(E)}_emitProfileUpdated(r){De.notificationCenter.emitInnerEvent(ro.PROFILE_UPDATE,{name:ro.PROFILE_UPDATE,data:[r]}),De.notificationCenter.emitOuterEvent(Mr.PROFILE_UPDATED,{name:Mr.PROFILE_UPDATED,data:[r]}),wB.updateConversation(`C2C${r?.userID}`,{userProfile:r})}_dispose(){const{notificationCenter:r}=De;r.unSubscribeInnerEvent(ro.LOGOUT,this._reset,this),r.unSubscribeInnerEvent(ro.MESSAGE_PUSH,r.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),r.unSubscribeInnerEvent(ro.DESTROY,this._dispose,this),this._reset()}_handleProfileModified(r){const{userId:g,profileList:u}=r,E=rc.getUserProfile(g);if(!(ir()===g||jE(g)&&E))return{isProfileUpdated:!1,profile:null};const m=tE.normalizeProfileFields(u),D=Object.keys(m).some(W=>W===tS?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,tS)?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(r){const g=[],u=[];return r.forEach(E=>{const m=rc.getUserProfileMap().has(E);jE(E)&&m?u.push(rc.getUserProfile(E)):this._isStrangerAndProfileValid(E)?u.push(this._strangerProfileMap.get(E)):g.push(E)}),{userIdListToRequest:g,profileFromCache:u}}_handleProfileFormResponse(r){const{userProfile:g}=r;if(!Array.isArray(g))return[];const u=g.filter(m=>m.userId!=="@TLS#NOT_FOUND"&&m.userId!==""&&!iS(m.profileItem)),E=Date.now();return u.map(m=>{const D=tE.createProfile(m.userId,m.profileItem);return D.lastUpdatedTime=E,D})}_isStrangerAndProfileValid(r){var g;if(!jE(r)){const{lastUpdatedTime:u=0}=this._strangerProfileMap.get(r)||{},E=((g=De.store.get("cloudConfig"))===null||g===void 0?void 0:g.stranger_profile_expiration_time)||6e5;return Date.now()-u<=E}return!1}_chunkUserIDList(r,g){return Array.from({length:Math.ceil(r.length/g)},(u,E)=>r.slice(E*g,(E+1)*g))}_batchFetchUserProfiles(r){return mA(this,void 0,void 0,function*(){const g=[],u=[];let E={};return this._chunkUserIDList(r,100).forEach(m=>{g.push(UR(m))}),(yield Promise.allSettled(g)).forEach(m=>{if(m.status==="fulfilled"){const D=m.value,M=this._handleProfileFormResponse(D);C(M)&&u.push(...M)}else if(m.status==="rejected"){const{code:D,message:M}=m.reason||{};E={errorCode:D,message:M}}}),{data:u,error:E}})}_isCustomFieldChanged(r=[],g=[]){if(!C(g)||g.length===0)return!1;if(!C(r)||r.length===0)return!0;const u=new Map(r.map(E=>[E.key,E.value]));return g.some(E=>u.get(E.key)!==E.value)}_mergeProfileCustomField(r=[],g=[]){const u=C(r)?r.map(E=>Object.assign({},E)):[];return C(g)&&g.length!==0&&g.forEach(({key:E,value:m})=>{const D=u.find(M=>M.key===E);D?D.value=m:u.push({key:E,value:m})}),u}_reset(){rc.getUserProfileMap().clear(),this._strangerProfileMap.clear()}}const rf=new Map,oS=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let s=0,r=oS.length;s>(-2*m&6)):0)E="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(E);try{return decodeURIComponent(escape(g))}catch(u){return console.warn(u),""}}const{isEmpty:sN}=De.utils,{generateProtocolData:af}=De.common;function FR(s){return mA(this,void 0,void 0,function*(){const r="im_open_status.ws_get_user_status",g=af({servcmd:r,data:{To_Account:s}}),u=`${g.head.seq}${r}`,E=yield De.channel.sendPacket(g,{requestId:u});if(E)return function(m){const{ErrorCode:D,ErrorInfo:M,ErrorList:T=[],UserStatusList:P=[]}=m,W=P.map(EA=>{const{To_Account:wA,Status:kA,CustomStatus:xA,Detail:LA=[]}=EA;return{userID:wA,statusType:kA,customStatus:cp(xA),onlineDevices:nN(LA)}}),oA=T.map(EA=>{const{To_Account:wA,Invalid_Account:kA,ErrorCode:xA,ErrorInfo:LA}=EA;return{userID:sN(kA)?wA:kA,code:xA,message:LA}});return{errorCode:D,errorInfo:M,successUserList:W,failureUserList:oA}}(E)})}function nN(s){const r=[];return s?.forEach(g=>{const{Platform:u,Status:E}=g;E==="Online"&&r.push(u)}),r}class rN{constructor(){this._customStatus=""}init(){const{notificationCenter:r}=De;pr.getInstance().registerApi({apiName:"getUserStatus",context:this}),pr.getInstance().registerApi({apiName:"setSelfStatus",context:this}),pr.getInstance().registerApi({apiName:"subscribeUserStatus",context:this}),pr.getInstance().registerApi({apiName:"unsubscribeUserStatus",context:this}),ws.getInstance().registerWorkflowStep(Jt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Wt.USER_STATUS_UPDATE,this._onReOnline,this),r.subscribeInnerEvent(ro.MESSAGE_PUSH,r.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),r.subscribeInnerEvent(ro.LOGOUT,this._reset,this),r.subscribeInnerEvent(ro.DESTROY,this._dispose,this)}setSelfStatus(r){return mA(this,void 0,void 0,function*(){const g=ir(),{customStatus:u}=r;try{return yield function(E){return mA(this,void 0,void 0,function*(){const m="im_open_status.ws_set_custom_status",D=af({servcmd:m,data:{CustomStatus:E}}),M=`${D.head.seq}${m}`,T=yield De.channel.sendPacket(D,{requestId:M});if(T){const{ErrorCode:P,ErrorInfo:W}=T;return{errorCode:P,errorInfo:W}}})}(u),this._customStatus=u,{code:0,data:{userID:g,statusType:Uh,customStatus:u},successLog:{message:`customStatus: ${u}`}}}catch(E){const{errorCode:m,errorInfo:D}=E;throw new gs({functionName:"setSelfStatus",code:m,message:D})}})}getUserStatus(r){return mA(this,void 0,void 0,function*(){const{userIDList:g=[]}=r;if(this._isOnlyMeInArray(g))return this._getMyStatus();const u=yield this._getUserStatus(g);return Object.assign(Object.assign({},u),{successLog:{message:`userIDList length: ${g.length}`}})})}setCustomStatus(r){const g=cp(r);this._customStatus=g}subscribeUserStatus(r){return mA(this,void 0,void 0,function*(){try{const{userIDList:g=[]}=r;this._checkBusinessCapabilityBits("subscribeUserStatus");const u=this._getMaxUserCount("subscribe"),E=this._sliceUserIDList(g,u),m=yield function(M){return mA(this,void 0,void 0,function*(){const{channel:T}=De,P="im_open_status.ws_status_subscribe",W=af({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:u}=g;throw new gs({functionName:"subscribeUserStatus",code:u})}})}unsubscribeUserStatus(r){return mA(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("unsubscribeUserStatus");const{userIDList:g=[]}=r,u=this._getMaxUserCount("unsubscribe"),E=this._sliceUserIDList(g,u),m=yield function(M){return mA(this,void 0,void 0,function*(){const{channel:T}=De,P="im_open_status.ws_status_unsubscribe";let W={};W=M.length===0?{UnsubscribeAll:1}:{To_Account:M};const oA=af({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:u}=g;throw new gs({functionName:"unsubscribeUserStatus",code:u})}})}_onUserStatusUpdate(r){const{UserStatusList:g=[]}=r||{},u=g.map(E=>{const{To_Account:m,Status:D,CustomStatus:M,Platform:T}=E,P={userID:m,statusType:D,customStatus:cp(M)};return T&&(P.onlineDevices=T),P});this._emitUserStatusUpdatedEvent(u)}_onReOnline(r){const g=cp(r.data.customStatus);if(this._customStatus===g)return;this._customStatus=g;const u={userID:ir(),statusType:Uh,customStatus:g};this._emitUserStatusUpdatedEvent(u)}_emitUserStatusUpdatedEvent(r){De.notificationCenter.emitOuterEvent(Mr.USER_STATUS_UPDATED,{name:Mr.USER_STATUS_UPDATED,data:r})}_sliceUserIDList(r,g){return r.slice(0,g)}_parseResponse(r){const{ErrorList:g=[]}=r;return g.map(u=>{const{To_Account:E,Invalid_Account:m,ErrorCode:D,ErrorInfo:M}=u;return{userID:De.utils.isEmpty(m)?E:m,code:D,message:M}})}_checkBusinessCapabilityBits(r){if(!De.store.get("commercialConfig").get(oN))throw new gs({functionName:r,code:da.NO_USE,replacement1:r})}_getMaxUserCount(r){const g=De.store.get("cloudConfig")||{},u={query:{key:"status_query_count",default:500},subscribe:{key:"status_sub_count",default:100},unsubscribe:{key:"status_unsub_count",default:100}},{key:E,default:m}=u[r],D=g[E]||m;return parseInt(D,10)}_getMyStatus(){return{code:0,data:{successUserList:[{userID:ir(),statusType:Uh,customStatus:this._customStatus}],failureUserList:[]}}}_getUserStatus(r){return mA(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("getUserStatus");const g=this._getMaxUserCount("query"),u=this._sliceUserIDList(r,g),E=yield FR(u),{successUserList:m,failureUserList:D}=E||{};return{code:0,data:{successUserList:m,failureUserList:D}}}catch(g){const{errorCode:u}=g;throw new gs({functionName:"getUserStatus",code:u})}})}_isOnlyMeInArray(r){const g=ir();return r.length===1&&r.indexOf(g)>-1}_dispose(){const{notificationCenter:r}=De;r.unSubscribeInnerEvent(ro.MESSAGE_PUSH,r.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),r.unSubscribeInnerEvent(ro.DESTROY,this._dispose,this),r.unSubscribeInnerEvent(ro.LOGOUT,this._reset,this),this._reset()}_reset(){this._customStatus=""}}const sS={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 r of s){if(typeof r!="object")return"Each item in profileCustomField must be an object";if(typeof r?.key!="string")return"Each item.key in profileCustomField must be a string";if(!r?.key.startsWith(eS))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}}},aN={getMyProfile:!0,getUserProfile:!0,updateMyProfile:!0,setSelfStatus:!0,getUserStatus:!0,subscribeUserStatus:!0,unsubscribeUserStatus:!0};class gN{constructor(){this.userProfile=new nf,this.userStatus=new rN,this.userProfile.init(),this.userStatus.init(),Wc({auth:aN,params:sS})}}function nS(s){const r=[];if(!c(s))return r;const g=s.length;if(g===0)return r;for(let u=g-1;u>=0;u--)s[u]==="1"&&r.push(2**(g-u-1));return r}var kd,NC,Ld;(function(s){s.NOT_START="notStart",s.PENDING="pending",s.RESOLVED="resolved",s.REJECTED="rejected"})(kd||(kd={})),function(s){s[s.C2C=1]="C2C",s[s.GROUP=2]="GROUP"}(NC||(NC={})),function(s){s[s.C2C=8]="C2C",s[s.GROUP=2]="GROUP"}(Ld||(Ld={}));class rS{constructor(){this._name="SyncConversationHandler",this._pagingStatus=kd.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}init(){const{notificationCenter:r}=De;ws.getInstance().registerWorkflowStep(Jt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Wt.CONVERSATION_RECOVER,this._syncConversationList,this),ws.getInstance().registerWorkflowStep(Jt.SYNC_SERVER_INFO_AFTER_LOGIN,Wt.CONVERSATION_LIST_SYNC,this._syncConversationListAfterLogin,this),r.subscribeInnerEvent(ro.LOGOUT,this._reset,this),r.subscribeInnerEvent(ro.DESTROY,this._dispose,this),De.ssoLog.debug(`${this._name}.init`)}isSyncCompleted(){return this._pagingStatus===kd.RESOLVED}_syncConversationListAfterLogin(){return mA(this,void 0,void 0,function*(){return this._pagingStatus=kd.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0,this._syncConversationList()})}_syncConversationList(){return mA(this,void 0,void 0,function*(){const{ssoLog:r,utils:{safeStringify:g}}=De;r.debug("_syncConversationList","start");try{const u=yield this._pagingGetConversationList(!0);this._pagingStatus=kd.RESOLVED;const{conversationList:E=[]}=u||{};return r.info("_syncConversationList",`success count:${E.length}`),u}catch(u){const E=new gs(u);r.error("_syncConversationList",`fail ${g(u)}`,{error:E})}})}_pagingGetConversationList(r){return mA(this,void 0,void 0,function*(){try{const g=[];this._pagingStatus=kd.PENDING;const u=yield function(oA){return mA(this,void 0,void 0,function*(){const{fromAccount:EA,pagingTimeStamp:wA,pagingStartIndex:kA,pagingPinnedTimeStamp:xA,pagingPinnedStartIndex:LA}=oA;return gg({servcmd:"recentcontact.page_get",data:{AssistFlags:31,MsgAssistFlags:15,OrderType:1,From_Account:EA,StartIndex:kA,TimeStamp:wA,TopStartIndex:LA,TopTimeStamp:xA}})})}({fromAccount:ir(),pagingTimeStamp:r?this._pagingTimeStamp:0,pagingStartIndex:r?this._pagingStartIndex:0,pagingPinnedTimeStamp:r?this._pagingPinnedTimeStamp:0,pagingPinnedStartIndex:r?this._pagingPinnedStartIndex:0}),{CompleteFlag:E,SessionItem:m=[],TimeStamp:D,StartIndex:M,TopTimeStamp:T,TopStartIndex:P}=u||{};let W=[];if(E===1&&(this._pagingStatus=kd.RESOLVED),m.length>0&&(W=this._getConversationOptions(m),g.push(...W)),De.notificationCenter.emitInnerEvent(ro.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(r);g.push(...oA)}return{conversationList:g}}catch(g){throw g}})}_getConversationOptions(r){const{utils:{isUndefined:g}}=De,u=this._convertConversationKey(r);return this._filterValidConversations(u).map(E=>(g(E.lastMsg)&&(E.lastMsg={elements:[]}),E.type===NC.C2C?this._assembleC2COption(E):this._assembleGroupOption(E)))}_filterValidConversations(r){return r.filter(({type:g,userID:u})=>g===NC.C2C&&!function(E){let m;return E.startsWith(Uo.CONV_C2C)&&(m=E.replace(Uo.CONV_C2C,"")),m==="@TLS#ERROR"||m==="@TLS#NOT_FOUND"}(u)||g===2)}_assembleC2COption(r){var g,u,E,m,D,M,T,P;const W=this._createUserprofile(r);return{conversationID:`${Uo.CONV_C2C}${r.userID}`,type:Uo.CONV_C2C,lastMessage:{lastTime:r.time,lastSequence:r.sequence,fromAccount:r.lastC2CMsgFromAccount,type:!((g=r.lastMsg)===null||g===void 0)&&g.elements[0]?(u=r.lastMsg)===null||u===void 0?void 0:u.elements[0].type:null,payload:!((E=r.lastMsg)===null||E===void 0)&&E.elements[0]?this._amendLayersOverLimitProp(r.lastMsg.elements[0].content):null,cloudCustomData:((M=(D=(m=r.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:r.lastMessageFlag===Ld.C2C,onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:this._computeIsPeerRead(r),revoker:((P=(T=r.lastMsg)===null||T===void 0?void 0:T.revokerInfo)===null||P===void 0?void 0:P.revoker)||null},unreadCount:0,userProfile:W,peerReadTime:r.peerReadTime,isPinned:r.isPinned===1,customData:r.customMark||"",markList:nS(r.standardMark),conversationGroupList:[],remark:r.friendRemark||"",messageRemindType:this._transMsgRemindType(r.messageRemindType)}}_createUserprofile(r){var g;const{userID:u,nick:E,peerAvatar:m}=r,D=[{tag:"Tag_Profile_IM_Nick",value:E},{tag:"Tag_Profile_IM_Image",value:m}];return(g=De.user.userProfile)===null||g===void 0?void 0:g.createProfile(u,D)}_computeIsPeerRead(r){const g=ir(),{lastC2CMsgFromAccount:u,time:E,c2cPeerReadTime:m}=r;return u===g&&E<=m}_assembleGroupOption(r){var g,u,E,m,D;return{conversationID:`${Uo.CONV_GROUP}${r.groupID}`,type:Uo.CONV_GROUP,lastMessage:Object.assign(Object.assign({lastTime:r.time,lastSequence:r.sequence,fromAccount:r.msgGroupFromAccount},this._patchTypeAndPayload(r)),{cloudCustomData:((E=(u=(g=r.lastMsg)===null||g===void 0?void 0:g.elements)===null||u===void 0?void 0:u[0])===null||E===void 0?void 0:E.cloudCustomData)||"",isRevoked:r.lastMessageFlag===Ld.GROUP,onlineOnlyFlag:!1,nick:r.msgGroupFromNickName||"",nameCard:r.msgGroupFromCardName||"",revoker:((D=(m=r.lastMsg)===null||m===void 0?void 0:m.revokerInfo)===null||D===void 0?void 0:D.revoker)||null}),groupProfile:{groupID:r.groupID,name:r.groupNick,avatar:r.groupImage,type:r.groupType,nextMessageSeq:r.nextMessageSeq},unreadCount:this._computeGroupUnreadCount(r),peerReadTime:0,isPinned:r.isPinned===1,version:0,customData:r.customMark||"",markList:nS(r.standardMark),conversationGroupList:[],messageRemindType:this._transMsgRemindType(r.messageRemindType),subType:r.groupType}}_convertConversationKey(r){return r.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(r){var g,u,E;const{utils:{isEmpty:m}}=De;if(m(r))return null;let D="",M=null;if(!m(r.GroupTips)){const{From_Account:T,GroupName:P}=((g=r.GroupTips)===null||g===void 0?void 0:g.GroupInfo)||{};D=Uo.MSG_GRP_TIP,M=Object.assign(Object.assign({},this._parseContent(D,r.GroupTips.MsgBody)),{groupProfile:{from:T,groupName:P}})}return r.MsgBody&&(D=(u=r.MsgBody[0])===null||u===void 0?void 0:u.MsgType,M=this._parseContent(D,r.MsgBody[0])),{event:r.Event,elements:[{type:D,content:M,cloudCustomData:r.CloudCustomData}],revokerInfo:{revoker:(E=r.RevokerInfo)===null||E===void 0?void 0:E.Revoker_Account}}}_parseContent(r,g){var u;if(!g)return g;const E=De.message.messageFactory.getElementClass(r);return E?(u=E.parseServerPushElement(g))===null||u===void 0?void 0:u.content:g}_amendLayersOverLimitProp(r){const{LayersOverLimit:g}=r;return So(r,["LayersOverLimit"]).layersOverLimit=g===1,r}_transMsgRemindType(r){let g="";return r===0?g=Uo.MSG_REMIND_ACPT_AND_NOTE:r===1?g=Uo.MSG_REMIND_DISCARD:r===2?g=Uo.MSG_REMIND_ACPT_NOT_NOTE:r===3&&(g=Uo.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),g}_patchTypeAndPayload(r){var g;const{utils:{isUndefined:u}}=De,{event:E,elements:m=[]}=r.lastMsg||{};return u(E)?{type:m[0]?m[0].type:null,payload:m[0]?this._amendLayersOverLimitProp(m[0].content):null}:{type:Uo.MSG_GRP_TIP,payload:((g=m?.[0])===null||g===void 0?void 0:g.content)||{}}}_computeGroupUnreadCount(r){const{unreadCount:g=0,noUnreadCount:u=0}=r,E=g-u;return E>0?E:0}_reset(){this._pagingStatus=kd.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}_dispose(){this._reset();const{notificationCenter:r}=De;r.unSubscribeInnerEvent(ro.LOGOUT,this._reset,this),r.unSubscribeInnerEvent(ro.DESTROY,this._dispose,this)}}class aS{constructor(){this.syncConversationHandler=new rS,this.syncConversationHandler.init()}}console.log(`TencentCloudLiteChat.VERSION:${Xr}`);var gS={create:function(s){var r,g;const{SDKAppID:u,testEnv:E=!1,devMode:m=!1,unlimitedAVChatRoom:D=!1,scene:M="",oversea:T=!1,instance:P,disableIndependentDomain:W=!1,proxyServer:oA=""}=s;let EA=u;if(!function(kA){if(typeof kA=="number")return!0;const xA=Number(kA);return!Number.isNaN(xA)}(EA))return console.error("Create SDK instance failed. Failed to parse the SDKAppID, please check the arguments"),null;if(EA=Number(EA),Ca.has(EA))return Ca.get(EA);let wA=null;if(P)wA=P,wA._workflowManager&&ws.setInstance(wA._workflowManager),wA._pluginManager&&wA._pluginManager.installBuiltInPlugin(vB),P.isReady()&&((g=(r=ws.getInstance()).executeWorkflow)===null||g===void 0||g.call(r,Jt.SYNC_SERVER_INFO_AFTER_LOGIN));else{const kA=function(){function Ie(){return(65536*(1+Math.random())|0).toString(16).substring(1)}return`${Ie()+Ie()}${Ie()}${Ie()}${Ie()}${Ie()}${Ie()}${Ie()}`}();De.init({sdkAppId:EA,instanceId:kA,testEnv:E,devMode:m,unlimitedAVChatRoom:D,disableIndependentDomain:W,scene:M,oversea:T,sdkEdition:Zm,version:Xr,proxyServer:oA}),ws.getInstance().init(),De.message=new AS,De.user=new gN,De.login=new Th,De.conversation=new aS,gu.getInstance().installBuiltInPlugin(vB),wA=pr.getInstance().exposeApiForClient(),wA._workflowManager=ws.getInstance(),wA._pluginManager=gu.getInstance();const{utils:{IS_WORKER_AVAILABLE:xA,USER_AGENT:LA,getPlatformType:SA,isIOSWebView:OA}}=De,qA=`instanceID:${kA} SDKAppID:${u} platform:${VA} host:${SA()} isIOSWebView:${OA} workerAvailable:${xA} UserAgent:${LA}`;De.ssoLog.info("sdkConstruct",qA)}return Ca.set(EA,wA),wA},TSignaling:qc,EVENT:Mr,VERSION:Xr,TYPES:Uo};return gS})}(aY)),aY.exports}var fsA=msA();const ig=HW(fsA);var gY={exports:{}},ysA=gY.exports,T8;function DsA(){return T8||(T8=1,function(t,i){(function(n,c){t.exports=c()})(ysA,function(){function n(ce,Ve){if(!(ce instanceof Ve))throw new TypeError("Cannot call a class as a function")}function c(ce,Ve){for(var Dt=0;Dt"u"&&typeof uni.requireNativePlugin=="function",HA=RA&&uni.getDeviceInfo().platform.toLocaleLowerCase()==="ios",ZA=(RA&&uni.getDeviceInfo().platform.toLocaleLowerCase(),lA||tA||BA||IA||gA||RA),KA=L!==void 0&&(L.nativeModuleProxy!==void 0||L.ReactNative!==void 0),me=tA?qq:BA?tt:IA?swan:gA?my:lA?wx:RA?uni:{},ae=function(ce){if(N(ce)!=="object"||ce===null)return!1;var Ve=Object.getPrototypeOf(ce);if(Ve===null)return!0;for(var Dt=Ve;Object.getPrototypeOf(Dt)!==null;)Dt=Object.getPrototypeOf(Dt);return Ve===Dt};function gt(ce){if(ce==null)return!0;if(typeof ce=="boolean")return!1;if(typeof ce=="number")return ce===0;if(typeof ce=="string"||typeof ce=="function"||Array.isArray(ce))return ce.length===0;if(ce instanceof Error)return ce.message==="";if(ae(ce)){for(var Ve in ce)if(Object.prototype.hasOwnProperty.call(ce,Ve))return!1;return!0}return!1}var dt=function(){return I(function ce(){n(this,ce),this._n="WebRequest"},[{key:"request",value:function(ce,Ve){var Dt=this,ti="".concat(this._n,".request"),Pt=ce.downloadUrl||"",oi=(ce.method||"PUT").toUpperCase(),Ni=ce.url;if(console.log("%c tim-upload-plugin %c","background:#0abf5b; padding:1px; border-radius:3px; color: #fff","background:transparent","".concat(ti," URL:").concat(Ni)),ce.qs){var Co=function(Gi){var As=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"&",Lo=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"=";return gt(Gi)?"":ae(Gi)?Object.keys(Gi).map(function($i){var zt=encodeURIComponent($i)+Lo;return Array.isArray(Gi[$i])?Gi[$i].map(function(Ao){return zt+encodeURIComponent(Ao)}).join(As):zt+encodeURIComponent(Gi[$i])}).filter(Boolean).join(As):void 0}(ce.qs);Co&&(Ni+="".concat(Ni.indexOf("?")===-1?"?":"&").concat(Co))}var to=new XMLHttpRequest;to.open(oi,Ni,!0),to.responseType=ce.dataType||"text";var so=ce.headers||{};if(ce.uploadByIP&&(so=w(w({},so),{},{host:ce.uploadIP})),!gt(so))for(var ks in so)so.hasOwnProperty(ks)&&ks.toLowerCase()!=="content-length"&&ks.toLowerCase()!=="user-agent"&&ks.toLowerCase()!=="origin"&&ks.toLowerCase()!=="host"&&to.setRequestHeader(ks,so[ks]);return to.onload=function(){if(to.status===200)Ve(null,Dt._xhrRes(to,Dt._xhrBody(to,Pt,ce.uploadByIP&&ce.uploadIP),so));else{if(ce.uploadIP&&ce.url.indexOf(ce.uploadIP)===-1)return ce.url=function(As,Lo){return As.replace(/^http(s)?:\/\/(.*?)\//,"https://".concat(Lo,"/"))}(ce.url,ce.uploadIP),ce.uploadByIP=!0,Dt.request(ce,Ve);var Gi={code:to.status,message:JSON.stringify(to.responseText)};Ve(Gi,Dt._xhrRes(to,Dt._xhrBody(to,Pt,ce.uploadByIP&&ce.uploadIP),so))}},to.onerror=function(Gi){var As=Dt._xhrBody(to,Pt,ce.uploadByIP&&ce.uploadIP),Lo={code:to.status,message:JSON.stringify(to.responseText)};As||to.statusText||to.status!==0||(Gi.message="CORS blocked or network error"),Ve(Lo,Dt._xhrRes(to,As)),Lo=null},ce.onProgress&&to.upload&&(to.upload.onprogress=function(Gi){var As=Gi.total,Lo=Gi.loaded,$i=Math.floor(100*Lo/As);ce.onProgress({total:As,loaded:Lo,percent:($i>=100?100:$i)/100})}),to.send(ce.resources),to}},{key:"_xhrRes",value:function(ce,Ve){var Dt={};return ce.getAllResponseHeaders().trim().split(`
+`).forEach(function(ti){if(ti){var Pt=ti.indexOf(":"),oi=ti.substr(0,Pt).trim().toLowerCase(),Ni=ti.substr(Pt+1).trim();Dt[oi]=Ni}}),{statusCode:ce.status,statusMessage:ce.statusText,headers:Dt,data:Ve}}},{key:"_xhrBody",value:function(ce,Ve,Dt){return ce.status===200&&Ve?{location:Ve,uploadIP:Dt}:{response:ce.responseText,uploadIP:Dt}}}])}(),We=["unknown","image","video","audio","log"],lt=["name"],wt=function(){return I(function ce(){n(this,ce)},[{key:"request",value:function(ce,Ve){var Dt=this,ti=ce.resources,Pt=ti===void 0?"":ti,oi=ce.headers,Ni=oi===void 0?{}:oi,Co=ce.url,to=ce.downloadUrl,so=to===void 0?"":to,ks=Co,Gi=null,As=so.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/),Lo=decodeURIComponent(As[3]),$i=Lo.indexOf("?")>-1?Lo.split("?")[0]:Lo,zt={key:ce.fileKey?ce.fileKey:$i,success_action_status:200,"Content-Type":""},Ao={};if(HA){var Ri=Co.split("?sign=");if(Ri.length>1){var Es=Ri[1];ks="".concat(Ri[0],"?sign=").concat(encodeURIComponent("".concat(Es))),Ao.sign=decodeURIComponent(Es),Ao.signature=decodeURIComponent(Es)}}var VA={url:ks,header:Ni,name:"file",filePath:Pt,formData:w(w({},zt),Ao),timeout:ce.timeout||3e5};if(gA){var Ee=VA;Ee.name,VA=w(w({},function(Je,Ut){if(Je==null)return{};var ot,ut,$t=function(Ge,Xe){if(Ge==null)return{};var se={};for(var ve in Ge)if({}.hasOwnProperty.call(Ge,ve)){if(Xe.includes(ve))continue;se[ve]=Ge[ve]}return se}(Je,Ut);if(Object.getOwnPropertySymbols){var Zt=Object.getOwnPropertySymbols(Je);for(ut=0;ut=3e4&&(this.systemClockOffset=Co-Ni,Ve=!0)}else Math.floor(ce.statusCode/100)===5&&(Ve=!0)}return Ve}}],[{key:"getVersion",value:function(){return"1.4.3"}}])}()})}(gY)),gY.exports}var SsA=DsA();const MsA=HW(SsA);/**
* @vue/shared v3.5.13
* (c) 2018-present Yuxi (Evan) You and Vue contributors
* @license MIT
-**//*! #__NO_SIDE_EFFECTS__ */function DW(t){const i=Object.create(null);for(const r of t.split(","))i[r]=1;return r=>r in i}const Da={},H_=[],RQ=()=>{},XoA=()=>!1,$Y=t=>t.charCodeAt(0)===111&&t.charCodeAt(1)===110&&(t.charCodeAt(2)>122||t.charCodeAt(2)<97),SW=t=>t.startsWith("onUpdate:"),sI=Object.assign,MW=(t,i)=>{const r=t.indexOf(i);r>-1&&t.splice(r,1)},$oA=Object.prototype.hasOwnProperty,Wr=(t,i)=>$oA.call(t,i),Ms=Array.isArray,q_=t=>AV(t)==="[object Map]",Q6=t=>AV(t)==="[object Set]",$s=t=>typeof t=="function",fg=t=>typeof t=="string",Cm=t=>typeof t=="symbol",Na=t=>t!==null&&typeof t=="object",p6=t=>(Na(t)||$s(t))&&$s(t.then)&&$s(t.catch),m6=Object.prototype.toString,AV=t=>m6.call(t),AsA=t=>AV(t).slice(8,-1),f6=t=>AV(t)==="[object Object]",vW=t=>fg(t)&&t!=="NaN"&&t[0]!=="-"&&""+parseInt(t,10)===t,jL=DW(",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"),eV=t=>{const i=Object.create(null);return r=>i[r]||(i[r]=t(r))},esA=/-(\w)/g,sh=eV(t=>t.replace(esA,(i,r)=>r?r.toUpperCase():"")),tsA=/\B([A-Z])/g,rD=eV(t=>t.replace(tsA,"-$1").toLowerCase()),tV=eV(t=>t.charAt(0).toUpperCase()+t.slice(1)),Dj=eV(t=>t?`on${tV(t)}`:""),Wy=(t,i)=>!Object.is(t,i),X1=(t,...i)=>{for(let r=0;r{Object.defineProperty(t,i,{configurable:!0,enumerable:!1,writable:l,value:r})},p3=t=>{const i=parseFloat(t);return isNaN(i)?t:i},isA=t=>{const i=fg(t)?Number(t):NaN;return isNaN(i)?t:i};let g8;const iV=()=>g8||(g8=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{});function Br(t){if(Ms(t)){const i={};for(let r=0;r{if(r){const l=r.split(ssA);l.length>1&&(i[l[0].trim()]=l[1].trim())}}),i}function qi(t){let i="";if(fg(t))i=t;else if(Ms(t))for(let r=0;r!!(t&&t.__v_isRef===!0),oi=t=>fg(t)?t:t==null?"":Ms(t)||Na(t)&&(t.toString===m6||!$s(t.toString))?S6(t)?oi(t.value):JSON.stringify(t,M6,2):String(t),M6=(t,i)=>S6(i)?M6(t,i.value):q_(i)?{[`Map(${i.size})`]:[...i.entries()].reduce((r,[l,I],h)=>(r[Sj(l,h)+" =>"]=I,r),{})}:Q6(i)?{[`Set(${i.size})`]:[...i.values()].map(r=>Sj(r))}:Cm(i)?Sj(i):Na(i)&&!Ms(i)&&!f6(i)?String(i):i,Sj=(t,i="")=>{var r;return Cm(t)?`Symbol(${(r=t.description)!=null?r:i})`:t};/**
+**//*! #__NO_SIDE_EFFECTS__ */function qW(t){const i=Object.create(null);for(const n of t.split(","))i[n]=1;return n=>n in i}const Da={},j_=[],TQ=()=>{},vsA=()=>!1,uV=t=>t.charCodeAt(0)===111&&t.charCodeAt(1)===110&&(t.charCodeAt(2)>122||t.charCodeAt(2)<97),KW=t=>t.startsWith("onUpdate:"),nI=Object.assign,jW=(t,i)=>{const n=t.indexOf(i);n>-1&&t.splice(n,1)},RsA=Object.prototype.hasOwnProperty,Wr=(t,i)=>RsA.call(t,i),vs=Array.isArray,W_=t=>EV(t)==="[object Map]",V6=t=>EV(t)==="[object Set]",$s=t=>typeof t=="function",fg=t=>typeof t=="string",Qm=t=>typeof t=="symbol",Na=t=>t!==null&&typeof t=="object",J6=t=>(Na(t)||$s(t))&&$s(t.then)&&$s(t.catch),H6=Object.prototype.toString,EV=t=>H6.call(t),wsA=t=>EV(t).slice(8,-1),q6=t=>EV(t)==="[object Object]",WW=t=>fg(t)&&t!=="NaN"&&t[0]!=="-"&&""+parseInt(t,10)===t,tU=qW(",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"),dV=t=>{const i=Object.create(null);return n=>i[n]||(i[n]=t(n))},_sA=/-(\w)/g,gh=dV(t=>t.replace(_sA,(i,n)=>n?n.toUpperCase():"")),TsA=/\B([A-Z])/g,cD=dV(t=>t.replace(TsA,"-$1").toLowerCase()),CV=dV(t=>t.charAt(0).toUpperCase()+t.slice(1)),Oj=dV(t=>t?`on${CV(t)}`:""),zy=(t,i)=>!Object.is(t,i),cY=(t,...i)=>{for(let n=0;n{Object.defineProperty(t,i,{configurable:!0,enumerable:!1,writable:c,value:n})},L3=t=>{const i=parseFloat(t);return isNaN(i)?t:i},NsA=t=>{const i=fg(t)?Number(t):NaN;return isNaN(i)?t:i};let N8;const hV=()=>N8||(N8=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{});function Cr(t){if(vs(t)){const i={};for(let n=0;n{if(n){const c=n.split(bsA);c.length>1&&(i[c[0].trim()]=c[1].trim())}}),i}function xi(t){let i="";if(fg(t))i=t;else if(vs(t))for(let n=0;n!!(t&&t.__v_isRef===!0),Kt=t=>fg(t)?t:t==null?"":vs(t)||Na(t)&&(t.toString===H6||!$s(t.toString))?W6(t)?Kt(t.value):JSON.stringify(t,z6,2):String(t),z6=(t,i)=>W6(i)?z6(t,i.value):W_(i)?{[`Map(${i.size})`]:[...i.entries()].reduce((n,[c,I],C)=>(n[Pj(c,C)+" =>"]=I,n),{})}:V6(i)?{[`Set(${i.size})`]:[...i.values()].map(n=>Pj(n))}:Qm(i)?Pj(i):Na(i)&&!vs(i)&&!q6(i)?String(i):i,Pj=(t,i="")=>{var n;return Qm(t)?`Symbol(${(n=t.description)!=null?n:i})`:t};/**
* @vue/reactivity v3.5.13
* (c) 2018-present Yuxi (Evan) You and Vue contributors
* @license MIT
-**/let iC;class lsA{constructor(i=!1){this.detached=i,this._active=!0,this.effects=[],this.cleanups=[],this._isPaused=!1,this.parent=iC,!i&&iC&&(this.index=(iC.scopes||(iC.scopes=[])).push(this)-1)}get active(){return this._active}pause(){if(this._active){this._isPaused=!0;let i,r;if(this.scopes)for(i=0,r=this.scopes.length;i0)return;if(zL){let i=zL;for(zL=void 0;i;){const r=i.next;i.next=void 0,i.flags&=-9,i=r}}let t;for(;WL;){let i=WL;for(WL=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 _6(t){for(let i=t.deps;i;i=i.nextDep)i.version=-1,i.prevActiveLink=i.dep.activeLink,i.dep.activeLink=i}function T6(t){let i,r=t.depsTail,l=r;for(;l;){const I=l.prevDep;l.version===-1?(l===r&&(r=I),_W(l),usA(l)):i=l,l.dep.activeLink=l.prevActiveLink,l.prevActiveLink=void 0,l=I}t.deps=i,t.depsTail=r}function m3(t){for(let i=t.deps;i;i=i.nextDep)if(i.dep.version!==i.version||i.dep.computed&&(N6(i.dep.computed)||i.dep.version!==i.version))return!0;return!!t._dirty}function N6(t){if(t.flags&4&&!(t.flags&16)||(t.flags&=-17,t.globalVersion===dU))return;t.globalVersion=dU;const i=t.dep;if(t.flags|=2,i.version>0&&!t.isSSR&&t.deps&&!m3(t)){t.flags&=-3;return}const r=_a,l=sB;_a=t,sB=!0;try{_6(t);const I=t.fn(t._value);(i.version===0||Wy(I,t._value))&&(t._value=I,i.version++)}catch(I){throw i.version++,I}finally{_a=r,sB=l,T6(t),t.flags&=-3}}function _W(t,i=!1){const{dep:r,prevSub:l,nextSub:I}=t;if(l&&(l.nextSub=I,t.prevSub=void 0),I&&(I.prevSub=l,t.nextSub=void 0),r.subs===t&&(r.subs=l,!l&&r.computed)){r.computed.flags&=-5;for(let h=r.computed.deps;h;h=h.nextDep)_W(h,!0)}!i&&!--r.sc&&r.map&&r.map.delete(r.key)}function usA(t){const{prevDep:i,nextDep:r}=t;i&&(i.nextDep=r,t.prevDep=void 0),r&&(r.prevDep=i,t.nextDep=void 0)}let sB=!0;const G6=[];function aD(){G6.push(sB),sB=!1}function gD(){const t=G6.pop();sB=t===void 0?!0:t}function c8(t){const{cleanup:i}=t;if(t.cleanup=void 0,i){const r=_a;_a=void 0;try{i()}finally{_a=r}}}let dU=0;class EsA{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 TW{constructor(i){this.computed=i,this.version=0,this.activeLink=void 0,this.subs=void 0,this.map=void 0,this.key=void 0,this.sc=0}track(i){if(!_a||!sB||_a===this.computed)return;let r=this.activeLink;if(r===void 0||r.sub!==_a)r=this.activeLink=new EsA(_a,this),_a.deps?(r.prevDep=_a.depsTail,_a.depsTail.nextDep=r,_a.depsTail=r):_a.deps=_a.depsTail=r,b6(r);else if(r.version===-1&&(r.version=this.version,r.nextDep)){const l=r.nextDep;l.prevDep=r.prevDep,r.prevDep&&(r.prevDep.nextDep=l),r.prevDep=_a.depsTail,r.nextDep=void 0,_a.depsTail.nextDep=r,_a.depsTail=r,_a.deps===r&&(_a.deps=l)}return r}trigger(i){this.version++,dU++,this.notify(i)}notify(i){RW();try{for(let r=this.subs;r;r=r.prevSub)r.sub.notify()&&r.sub.dep.notify()}finally{wW()}}}function b6(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)b6(l)}const r=t.dep.subs;r!==t&&(t.prevSub=r,r&&(r.nextSub=t)),t.dep.subs=t}}const CY=new WeakMap,Qv=Symbol(""),f3=Symbol(""),CU=Symbol("");function pu(t,i,r){if(sB&&_a){let l=CY.get(t);l||CY.set(t,l=new Map);let I=l.get(r);I||(l.set(r,I=new TW),I.map=l,I.key=r),I.track()}}function lm(t,i,r,l,I,h){const f=CY.get(t);if(!f){dU++;return}const w=_=>{_&&_.trigger()};if(RW(),i==="clear")f.forEach(w);else{const _=Ms(t),G=_&&vW(r);if(_&&r==="length"){const U=Number(l);f.forEach((j,lA)=>{(lA==="length"||lA===CU||!Cm(lA)&&lA>=U)&&w(j)})}else switch((r!==void 0||f.has(void 0))&&w(f.get(r)),G&&w(f.get(CU)),i){case"add":_?G&&w(f.get("length")):(w(f.get(Qv)),q_(t)&&w(f.get(f3)));break;case"delete":_||(w(f.get(Qv)),q_(t)&&w(f.get(f3)));break;case"set":q_(t)&&w(f.get(Qv));break}}wW()}function dsA(t,i){const r=CY.get(t);return r&&r.get(i)}function f_(t){const i=br(t);return i===t?i:(pu(i,"iterate",CU),th(t)?i:i.map(mu))}function oV(t){return pu(t=br(t),"iterate",CU),t}const CsA={__proto__:null,[Symbol.iterator](){return vj(this,Symbol.iterator,mu)},concat(...t){return f_(this).concat(...t.map(i=>Ms(i)?f_(i):i))},entries(){return vj(this,"entries",t=>(t[1]=mu(t[1]),t))},every(t,i){return im(this,"every",t,i,void 0,arguments)},filter(t,i){return im(this,"filter",t,i,r=>r.map(mu),arguments)},find(t,i){return im(this,"find",t,i,mu,arguments)},findIndex(t,i){return im(this,"findIndex",t,i,void 0,arguments)},findLast(t,i){return im(this,"findLast",t,i,mu,arguments)},findLastIndex(t,i){return im(this,"findLastIndex",t,i,void 0,arguments)},forEach(t,i){return im(this,"forEach",t,i,void 0,arguments)},includes(...t){return Rj(this,"includes",t)},indexOf(...t){return Rj(this,"indexOf",t)},join(t){return f_(this).join(t)},lastIndexOf(...t){return Rj(this,"lastIndexOf",t)},map(t,i){return im(this,"map",t,i,void 0,arguments)},pop(){return QL(this,"pop")},push(...t){return QL(this,"push",t)},reduce(t,...i){return l8(this,"reduce",t,i)},reduceRight(t,...i){return l8(this,"reduceRight",t,i)},shift(){return QL(this,"shift")},some(t,i){return im(this,"some",t,i,void 0,arguments)},splice(...t){return QL(this,"splice",t)},toReversed(){return f_(this).toReversed()},toSorted(t){return f_(this).toSorted(t)},toSpliced(...t){return f_(this).toSpliced(...t)},unshift(...t){return QL(this,"unshift",t)},values(){return vj(this,"values",mu)}};function vj(t,i,r){const l=oV(t),I=l[i]();return l!==t&&!th(t)&&(I._next=I.next,I.next=()=>{const h=I._next();return h.value&&(h.value=r(h.value)),h}),I}const hsA=Array.prototype;function im(t,i,r,l,I,h){const f=oV(t),w=f!==t&&!th(t),_=f[i];if(_!==hsA[i]){const j=_.apply(t,h);return w?mu(j):j}let G=r;f!==t&&(w?G=function(j,lA){return r.call(this,mu(j),lA,t)}:r.length>2&&(G=function(j,lA){return r.call(this,j,lA,t)}));const U=_.call(f,G,l);return w&&I?I(U):U}function l8(t,i,r,l){const I=oV(t);let h=r;return I!==t&&(th(t)?r.length>3&&(h=function(f,w,_){return r.call(this,f,w,_,t)}):h=function(f,w,_){return r.call(this,f,mu(w),_,t)}),I[i](h,...l)}function Rj(t,i,r){const l=br(t);pu(l,"iterate",CU);const I=l[i](...r);return(I===-1||I===!1)&&bW(r[0])?(r[0]=br(r[0]),l[i](...r)):I}function QL(t,i,r=[]){aD(),RW();const l=br(t)[i].apply(t,r);return wW(),gD(),l}const BsA=DW("__proto__,__v_isRef,__isVue"),k6=new Set(Object.getOwnPropertyNames(Symbol).filter(t=>t!=="arguments"&&t!=="caller").map(t=>Symbol[t]).filter(Cm));function QsA(t){Cm(t)||(t=String(t));const i=br(this);return pu(i,"has",t),i.hasOwnProperty(t)}class L6{constructor(i=!1,r=!1){this._isReadonly=i,this._isShallow=r}get(i,r,l){if(r==="__v_skip")return i.__v_skip;const I=this._isReadonly,h=this._isShallow;if(r==="__v_isReactive")return!I;if(r==="__v_isReadonly")return I;if(r==="__v_isShallow")return h;if(r==="__v_raw")return l===(I?h?wsA:P6:h?O6:F6).get(i)||Object.getPrototypeOf(i)===Object.getPrototypeOf(l)?i:void 0;const f=Ms(i);if(!I){let _;if(f&&(_=CsA[r]))return _;if(r==="hasOwnProperty")return QsA}const w=Reflect.get(i,r,iI(i)?i:l);return(Cm(r)?k6.has(r):BsA(r))||(I||pu(i,"get",r),h)?w:iI(w)?f&&vW(r)?w:w.value:Na(w)?I?PI(w):dv(w):w}}class U6 extends L6{constructor(i=!1){super(!1,i)}set(i,r,l,I){let h=i[r];if(!this._isShallow){const _=Tv(h);if(!th(l)&&!Tv(l)&&(h=br(h),l=br(l)),!Ms(i)&&iI(h)&&!iI(l))return _?!1:(h.value=l,!0)}const f=Ms(i)&&vW(r)?Number(r)t,_1=t=>Reflect.getPrototypeOf(t);function DsA(t,i,r){return function(...l){const I=this.__v_raw,h=br(I),f=q_(h),w=t==="entries"||t===Symbol.iterator&&f,_=t==="keys"&&f,G=I[t](...l),U=r?y3:i?D3:mu;return!i&&pu(h,"iterate",_?f3:Qv),{next(){const{value:j,done:lA}=G.next();return lA?{value:j,done:lA}:{value:w?[U(j[0]),U(j[1])]:U(j),done:lA}},[Symbol.iterator](){return this}}}}function T1(t){return function(...i){return t==="delete"?!1:t==="clear"?void 0:this}}function SsA(t,i){const r={get(I){const h=this.__v_raw,f=br(h),w=br(I);t||(Wy(I,w)&&pu(f,"get",I),pu(f,"get",w));const{has:_}=_1(f),G=i?y3:t?D3:mu;if(_.call(f,I))return G(h.get(I));if(_.call(f,w))return G(h.get(w));h!==f&&h.get(I)},get size(){const I=this.__v_raw;return!t&&pu(br(I),"iterate",Qv),Reflect.get(I,"size",I)},has(I){const h=this.__v_raw,f=br(h),w=br(I);return t||(Wy(I,w)&&pu(f,"has",I),pu(f,"has",w)),I===w?h.has(I):h.has(I)||h.has(w)},forEach(I,h){const f=this,w=f.__v_raw,_=br(w),G=i?y3:t?D3:mu;return!t&&pu(_,"iterate",Qv),w.forEach((U,j)=>I.call(h,G(U),G(j),f))}};return sI(r,t?{add:T1("add"),set:T1("set"),delete:T1("delete"),clear:T1("clear")}:{add(I){!i&&!th(I)&&!Tv(I)&&(I=br(I));const h=br(this);return _1(h).has.call(h,I)||(h.add(I),lm(h,"add",I,I)),this},set(I,h){!i&&!th(h)&&!Tv(h)&&(h=br(h));const f=br(this),{has:w,get:_}=_1(f);let G=w.call(f,I);G||(I=br(I),G=w.call(f,I));const U=_.call(f,I);return f.set(I,h),G?Wy(h,U)&&lm(f,"set",I,h):lm(f,"add",I,h),this},delete(I){const h=br(this),{has:f,get:w}=_1(h);let _=f.call(h,I);_||(I=br(I),_=f.call(h,I)),w&&w.call(h,I);const G=h.delete(I);return _&&lm(h,"delete",I,void 0),G},clear(){const I=br(this),h=I.size!==0,f=I.clear();return h&&lm(I,"clear",void 0,void 0),f}}),["keys","values","entries",Symbol.iterator].forEach(I=>{r[I]=DsA(I,t,i)}),r}function NW(t,i){const r=SsA(t,i);return(l,I,h)=>I==="__v_isReactive"?!t:I==="__v_isReadonly"?t:I==="__v_raw"?l:Reflect.get(Wr(r,I)&&I in l?r:l,I,h)}const MsA={get:NW(!1,!1)},vsA={get:NW(!1,!0)},RsA={get:NW(!0,!1)};const F6=new WeakMap,O6=new WeakMap,P6=new WeakMap,wsA=new WeakMap;function _sA(t){switch(t){case"Object":case"Array":return 1;case"Map":case"Set":case"WeakMap":case"WeakSet":return 2;default:return 0}}function TsA(t){return t.__v_skip||!Object.isExtensible(t)?0:_sA(AsA(t))}function dv(t){return Tv(t)?t:GW(t,!1,msA,MsA,F6)}function NsA(t){return GW(t,!1,ysA,vsA,O6)}function PI(t){return GW(t,!0,fsA,RsA,P6)}function GW(t,i,r,l,I){if(!Na(t)||t.__v_raw&&!(i&&t.__v_isReactive))return t;const h=I.get(t);if(h)return h;const f=TsA(t);if(f===0)return t;const w=new Proxy(t,f===2?l:r);return I.set(t,w),w}function K_(t){return Tv(t)?K_(t.__v_raw):!!(t&&t.__v_isReactive)}function Tv(t){return!!(t&&t.__v_isReadonly)}function th(t){return!!(t&&t.__v_isShallow)}function bW(t){return t?!!t.__v_raw:!1}function br(t){const i=t&&t.__v_raw;return i?br(i):t}function GsA(t){return!Wr(t,"__v_skip")&&Object.isExtensible(t)&&y6(t,"__v_skip",!0),t}const mu=t=>Na(t)?dv(t):t,D3=t=>Na(t)?PI(t):t;function iI(t){return t?t.__v_isRef===!0:!1}function ze(t){return bsA(t,!1)}function bsA(t,i){return iI(t)?t:new ksA(t,i)}class ksA{constructor(i,r){this.dep=new TW,this.__v_isRef=!0,this.__v_isShallow=!1,this._rawValue=r?i:br(i),this._value=r?i:mu(i),this.__v_isShallow=r}get value(){return this.dep.track(),this._value}set value(i){const r=this._rawValue,l=this.__v_isShallow||th(i)||Tv(i);i=l?i:br(i),Wy(i,r)&&(this._rawValue=i,this._value=l?i:mu(i),this.dep.trigger())}}function aA(t){return iI(t)?t.value:t}const LsA={get:(t,i,r)=>i==="__v_raw"?t:aA(Reflect.get(t,i,r)),set:(t,i,r,l)=>{const I=t[i];return iI(I)&&!iI(r)?(I.value=r,!0):Reflect.set(t,i,r,l)}};function x6(t){return K_(t)?t:new Proxy(t,LsA)}function Gs(t){const i=Ms(t)?new Array(t.length):{};for(const r in t)i[r]=Y6(t,r);return i}class UsA{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 dsA(br(this._object),this._key)}}class FsA{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 wj(t,i,r){return iI(t)?t:$s(t)?new FsA(t):Na(t)&&arguments.length>1?Y6(t,i,r):ze(t)}function Y6(t,i,r){const l=t[i];return iI(l)?l:new UsA(t,i,r)}class OsA{constructor(i,r,l){this.fn=i,this.setter=r,this._value=void 0,this.dep=new TW(this),this.__v_isRef=!0,this.deps=void 0,this.depsTail=void 0,this.flags=16,this.globalVersion=dU-1,this.next=void 0,this.effect=this,this.__v_isReadonly=!r,this.isSSR=l}notify(){if(this.flags|=16,!(this.flags&8)&&_a!==this)return w6(this,!0),!0}get value(){const i=this.dep.track();return N6(this),i&&(i.version=this.dep.version),this._value}set value(i){this.setter&&this.setter(i)}}function PsA(t,i,r=!1){let l,I;return $s(t)?l=t:(l=t.get,I=t.set),new OsA(l,I,r)}const N1={},hY=new WeakMap;let av;function xsA(t,i=!1,r=av){if(r){let l=hY.get(r);l||hY.set(r,l=[]),l.push(t)}}function YsA(t,i,r=Da){const{immediate:l,deep:I,once:h,scheduler:f,augmentJob:w,call:_}=r,G=Ce=>I?Ce:th(Ce)||I===!1||I===0?Im(Ce,1):Im(Ce);let U,j,lA,sA,mA=!1,IA=!1;if(iI(t)?(j=()=>t.value,mA=th(t)):K_(t)?(j=()=>G(t),mA=!0):Ms(t)?(IA=!0,mA=t.some(Ce=>K_(Ce)||th(Ce)),j=()=>t.map(Ce=>{if(iI(Ce))return Ce.value;if(K_(Ce))return G(Ce);if($s(Ce))return _?_(Ce,2):Ce()})):$s(t)?i?j=_?()=>_(t,2):t:j=()=>{if(lA){aD();try{lA()}finally{gD()}}const Ce=av;av=U;try{return _?_(t,3,[sA]):t(sA)}finally{av=Ce}}:j=RQ,i&&I){const Ce=j,xe=I===!0?1/0:I;j=()=>Im(Ce(),xe)}const cA=IsA(),TA=()=>{U.stop(),cA&&cA.active&&MW(cA.effects,U)};if(h&&i){const Ce=i;i=(...xe)=>{Ce(...xe),TA()}}let WA=IA?new Array(t.length).fill(N1):N1;const ue=Ce=>{if(!(!(U.flags&1)||!U.dirty&&!Ce))if(i){const xe=U.run();if(I||mA||(IA?xe.some((Qe,ut)=>Wy(Qe,WA[ut])):Wy(xe,WA))){lA&&lA();const Qe=av;av=U;try{const ut=[xe,WA===N1?void 0:IA&&WA[0]===N1?[]:WA,sA];_?_(i,3,ut):i(...ut),WA=xe}finally{av=Qe}}}else U.run()};return w&&w(ue),U=new v6(j),U.scheduler=f?()=>f(ue,!1):ue,sA=Ce=>xsA(Ce,!1,U),lA=U.onStop=()=>{const Ce=hY.get(U);if(Ce){if(_)_(Ce,4);else for(const xe of Ce)xe();hY.delete(U)}},i?l?ue(!0):WA=U.run():f?f(ue.bind(null,!0),!0):U.run(),TA.pause=U.pause.bind(U),TA.resume=U.resume.bind(U),TA.stop=TA,TA}function Im(t,i=1/0,r){if(i<=0||!Na(t)||t.__v_skip||(r=r||new Set,r.has(t)))return t;if(r.add(t),i--,iI(t))Im(t.value,i,r);else if(Ms(t))for(let l=0;l{Im(l,i,r)});else if(f6(t)){for(const l in t)Im(t[l],i,r);for(const l of Object.getOwnPropertySymbols(t))Object.prototype.propertyIsEnumerable.call(t,l)&&Im(t[l],i,r)}return t}/**
+**/let iC;class PsA{constructor(i=!1){this.detached=i,this._active=!0,this.effects=[],this.cleanups=[],this._isPaused=!1,this.parent=iC,!i&&iC&&(this.index=(iC.scopes||(iC.scopes=[])).push(this)-1)}get active(){return this._active}pause(){if(this._active){this._isPaused=!0;let i,n;if(this.scopes)for(i=0,n=this.scopes.length;i0)return;if(oU){let i=oU;for(oU=void 0;i;){const n=i.next;i.next=void 0,i.flags&=-9,i=n}}let t;for(;iU;){let i=iU;for(iU=void 0;i;){const n=i.next;if(i.next=void 0,i.flags&=-9,i.flags&1)try{i.trigger()}catch(c){t||(t=c)}i=n}}if(t)throw t}function A9(t){for(let i=t.deps;i;i=i.nextDep)i.version=-1,i.prevActiveLink=i.dep.activeLink,i.dep.activeLink=i}function e9(t){let i,n=t.depsTail,c=n;for(;c;){const I=c.prevDep;c.version===-1?(c===n&&(n=I),XW(c),YsA(c)):i=c,c.dep.activeLink=c.prevActiveLink,c.prevActiveLink=void 0,c=I}t.deps=i,t.depsTail=n}function U3(t){for(let i=t.deps;i;i=i.nextDep)if(i.dep.version!==i.version||i.dep.computed&&(t9(i.dep.computed)||i.dep.version!==i.version))return!0;return!!t._dirty}function t9(t){if(t.flags&4&&!(t.flags&16)||(t.flags&=-17,t.globalVersion===DU))return;t.globalVersion=DU;const i=t.dep;if(t.flags|=2,i.version>0&&!t.isSSR&&t.deps&&!U3(t)){t.flags&=-3;return}const n=_a,c=aB;_a=t,aB=!0;try{A9(t);const I=t.fn(t._value);(i.version===0||zy(I,t._value))&&(t._value=I,i.version++)}catch(I){throw i.version++,I}finally{_a=n,aB=c,e9(t),t.flags&=-3}}function XW(t,i=!1){const{dep:n,prevSub:c,nextSub:I}=t;if(c&&(c.nextSub=I,t.prevSub=void 0),I&&(I.prevSub=c,t.nextSub=void 0),n.subs===t&&(n.subs=c,!c&&n.computed)){n.computed.flags&=-5;for(let C=n.computed.deps;C;C=C.nextDep)XW(C,!0)}!i&&!--n.sc&&n.map&&n.map.delete(n.key)}function YsA(t){const{prevDep:i,nextDep:n}=t;i&&(i.nextDep=n,t.prevDep=void 0),n&&(n.prevDep=i,t.nextDep=void 0)}let aB=!0;const i9=[];function lD(){i9.push(aB),aB=!1}function ID(){const t=i9.pop();aB=t===void 0?!0:t}function G8(t){const{cleanup:i}=t;if(t.cleanup=void 0,i){const n=_a;_a=void 0;try{i()}finally{_a=n}}}let DU=0;class VsA{constructor(i,n){this.sub=i,this.dep=n,this.version=n.version,this.nextDep=this.prevDep=this.nextSub=this.prevSub=this.prevActiveLink=void 0}}class $W{constructor(i){this.computed=i,this.version=0,this.activeLink=void 0,this.subs=void 0,this.map=void 0,this.key=void 0,this.sc=0}track(i){if(!_a||!aB||_a===this.computed)return;let n=this.activeLink;if(n===void 0||n.sub!==_a)n=this.activeLink=new VsA(_a,this),_a.deps?(n.prevDep=_a.depsTail,_a.depsTail.nextDep=n,_a.depsTail=n):_a.deps=_a.depsTail=n,o9(n);else if(n.version===-1&&(n.version=this.version,n.nextDep)){const c=n.nextDep;c.prevDep=n.prevDep,n.prevDep&&(n.prevDep.nextDep=c),n.prevDep=_a.depsTail,n.nextDep=void 0,_a.depsTail.nextDep=n,_a.depsTail=n,_a.deps===n&&(_a.deps=c)}return n}trigger(i){this.version++,DU++,this.notify(i)}notify(i){zW();try{for(let n=this.subs;n;n=n.prevSub)n.sub.notify()&&n.sub.dep.notify()}finally{ZW()}}}function o9(t){if(t.dep.sc++,t.sub.flags&4){const i=t.dep.computed;if(i&&!t.dep.subs){i.flags|=20;for(let c=i.deps;c;c=c.nextDep)o9(c)}const n=t.dep.subs;n!==t&&(t.prevSub=n,n&&(n.nextSub=t)),t.dep.subs=t}}const RY=new WeakMap,fv=Symbol(""),F3=Symbol(""),SU=Symbol("");function mu(t,i,n){if(aB&&_a){let c=RY.get(t);c||RY.set(t,c=new Map);let I=c.get(n);I||(c.set(n,I=new $W),I.map=c,I.key=n),I.track()}}function Em(t,i,n,c,I,C){const f=RY.get(t);if(!f){DU++;return}const w=_=>{_&&_.trigger()};if(zW(),i==="clear")f.forEach(w);else{const _=vs(t),N=_&&WW(n);if(_&&n==="length"){const L=Number(c);f.forEach((q,lA)=>{(lA==="length"||lA===SU||!Qm(lA)&&lA>=L)&&w(q)})}else switch((n!==void 0||f.has(void 0))&&w(f.get(n)),N&&w(f.get(SU)),i){case"add":_?N&&w(f.get("length")):(w(f.get(fv)),W_(t)&&w(f.get(F3)));break;case"delete":_||(w(f.get(fv)),W_(t)&&w(f.get(F3)));break;case"set":W_(t)&&w(f.get(fv));break}}ZW()}function JsA(t,i){const n=RY.get(t);return n&&n.get(i)}function S_(t){const i=br(t);return i===t?i:(mu(i,"iterate",SU),nh(t)?i:i.map(fu))}function BV(t){return mu(t=br(t),"iterate",SU),t}const HsA={__proto__:null,[Symbol.iterator](){return Yj(this,Symbol.iterator,fu)},concat(...t){return S_(this).concat(...t.map(i=>vs(i)?S_(i):i))},entries(){return Yj(this,"entries",t=>(t[1]=fu(t[1]),t))},every(t,i){return nm(this,"every",t,i,void 0,arguments)},filter(t,i){return nm(this,"filter",t,i,n=>n.map(fu),arguments)},find(t,i){return nm(this,"find",t,i,fu,arguments)},findIndex(t,i){return nm(this,"findIndex",t,i,void 0,arguments)},findLast(t,i){return nm(this,"findLast",t,i,fu,arguments)},findLastIndex(t,i){return nm(this,"findLastIndex",t,i,void 0,arguments)},forEach(t,i){return nm(this,"forEach",t,i,void 0,arguments)},includes(...t){return Vj(this,"includes",t)},indexOf(...t){return Vj(this,"indexOf",t)},join(t){return S_(this).join(t)},lastIndexOf(...t){return Vj(this,"lastIndexOf",t)},map(t,i){return nm(this,"map",t,i,void 0,arguments)},pop(){return SL(this,"pop")},push(...t){return SL(this,"push",t)},reduce(t,...i){return b8(this,"reduce",t,i)},reduceRight(t,...i){return b8(this,"reduceRight",t,i)},shift(){return SL(this,"shift")},some(t,i){return nm(this,"some",t,i,void 0,arguments)},splice(...t){return SL(this,"splice",t)},toReversed(){return S_(this).toReversed()},toSorted(t){return S_(this).toSorted(t)},toSpliced(...t){return S_(this).toSpliced(...t)},unshift(...t){return SL(this,"unshift",t)},values(){return Yj(this,"values",fu)}};function Yj(t,i,n){const c=BV(t),I=c[i]();return c!==t&&!nh(t)&&(I._next=I.next,I.next=()=>{const C=I._next();return C.value&&(C.value=n(C.value)),C}),I}const qsA=Array.prototype;function nm(t,i,n,c,I,C){const f=BV(t),w=f!==t&&!nh(t),_=f[i];if(_!==qsA[i]){const q=_.apply(t,C);return w?fu(q):q}let N=n;f!==t&&(w?N=function(q,lA){return n.call(this,fu(q),lA,t)}:n.length>2&&(N=function(q,lA){return n.call(this,q,lA,t)}));const L=_.call(f,N,c);return w&&I?I(L):L}function b8(t,i,n,c){const I=BV(t);let C=n;return I!==t&&(nh(t)?n.length>3&&(C=function(f,w,_){return n.call(this,f,w,_,t)}):C=function(f,w,_){return n.call(this,f,fu(w),_,t)}),I[i](C,...c)}function Vj(t,i,n){const c=br(t);mu(c,"iterate",SU);const I=c[i](...n);return(I===-1||I===!1)&&t4(n[0])?(n[0]=br(n[0]),c[i](...n)):I}function SL(t,i,n=[]){lD(),zW();const c=br(t)[i].apply(t,n);return ZW(),ID(),c}const KsA=qW("__proto__,__v_isRef,__isVue"),s9=new Set(Object.getOwnPropertyNames(Symbol).filter(t=>t!=="arguments"&&t!=="caller").map(t=>Symbol[t]).filter(Qm));function jsA(t){Qm(t)||(t=String(t));const i=br(this);return mu(i,"has",t),i.hasOwnProperty(t)}class n9{constructor(i=!1,n=!1){this._isReadonly=i,this._isShallow=n}get(i,n,c){if(n==="__v_skip")return i.__v_skip;const I=this._isReadonly,C=this._isShallow;if(n==="__v_isReactive")return!I;if(n==="__v_isReadonly")return I;if(n==="__v_isShallow")return C;if(n==="__v_raw")return c===(I?C?onA:c9:C?g9:a9).get(i)||Object.getPrototypeOf(i)===Object.getPrototypeOf(c)?i:void 0;const f=vs(i);if(!I){let _;if(f&&(_=HsA[n]))return _;if(n==="hasOwnProperty")return jsA}const w=Reflect.get(i,n,oI(i)?i:c);return(Qm(n)?s9.has(n):KsA(n))||(I||mu(i,"get",n),C)?w:oI(w)?f&&WW(n)?w:w.value:Na(w)?I?Ql(w):Bv(w):w}}class r9 extends n9{constructor(i=!1){super(!1,i)}set(i,n,c,I){let C=i[n];if(!this._isShallow){const _=bv(C);if(!nh(c)&&!bv(c)&&(C=br(C),c=br(c)),!vs(i)&&oI(C)&&!oI(c))return _?!1:(C.value=c,!0)}const f=vs(i)&&WW(n)?Number(n)t,P1=t=>Reflect.getPrototypeOf(t);function $sA(t,i,n){return function(...c){const I=this.__v_raw,C=br(I),f=W_(C),w=t==="entries"||t===Symbol.iterator&&f,_=t==="keys"&&f,N=I[t](...c),L=n?O3:i?P3:fu;return!i&&mu(C,"iterate",_?F3:fv),{next(){const{value:q,done:lA}=N.next();return lA?{value:q,done:lA}:{value:w?[L(q[0]),L(q[1])]:L(q),done:lA}},[Symbol.iterator](){return this}}}}function x1(t){return function(...i){return t==="delete"?!1:t==="clear"?void 0:this}}function AnA(t,i){const n={get(I){const C=this.__v_raw,f=br(C),w=br(I);t||(zy(I,w)&&mu(f,"get",I),mu(f,"get",w));const{has:_}=P1(f),N=i?O3:t?P3:fu;if(_.call(f,I))return N(C.get(I));if(_.call(f,w))return N(C.get(w));C!==f&&C.get(I)},get size(){const I=this.__v_raw;return!t&&mu(br(I),"iterate",fv),Reflect.get(I,"size",I)},has(I){const C=this.__v_raw,f=br(C),w=br(I);return t||(zy(I,w)&&mu(f,"has",I),mu(f,"has",w)),I===w?C.has(I):C.has(I)||C.has(w)},forEach(I,C){const f=this,w=f.__v_raw,_=br(w),N=i?O3:t?P3:fu;return!t&&mu(_,"iterate",fv),w.forEach((L,q)=>I.call(C,N(L),N(q),f))}};return nI(n,t?{add:x1("add"),set:x1("set"),delete:x1("delete"),clear:x1("clear")}:{add(I){!i&&!nh(I)&&!bv(I)&&(I=br(I));const C=br(this);return P1(C).has.call(C,I)||(C.add(I),Em(C,"add",I,I)),this},set(I,C){!i&&!nh(C)&&!bv(C)&&(C=br(C));const f=br(this),{has:w,get:_}=P1(f);let N=w.call(f,I);N||(I=br(I),N=w.call(f,I));const L=_.call(f,I);return f.set(I,C),N?zy(C,L)&&Em(f,"set",I,C):Em(f,"add",I,C),this},delete(I){const C=br(this),{has:f,get:w}=P1(C);let _=f.call(C,I);_||(I=br(I),_=f.call(C,I)),w&&w.call(C,I);const N=C.delete(I);return _&&Em(C,"delete",I,void 0),N},clear(){const I=br(this),C=I.size!==0,f=I.clear();return C&&Em(I,"clear",void 0,void 0),f}}),["keys","values","entries",Symbol.iterator].forEach(I=>{n[I]=$sA(I,t,i)}),n}function A4(t,i){const n=AnA(t,i);return(c,I,C)=>I==="__v_isReactive"?!t:I==="__v_isReadonly"?t:I==="__v_raw"?c:Reflect.get(Wr(n,I)&&I in c?n:c,I,C)}const enA={get:A4(!1,!1)},tnA={get:A4(!1,!0)},inA={get:A4(!0,!1)};const a9=new WeakMap,g9=new WeakMap,c9=new WeakMap,onA=new WeakMap;function snA(t){switch(t){case"Object":case"Array":return 1;case"Map":case"Set":case"WeakMap":case"WeakSet":return 2;default:return 0}}function nnA(t){return t.__v_skip||!Object.isExtensible(t)?0:snA(wsA(t))}function Bv(t){return bv(t)?t:e4(t,!1,zsA,enA,a9)}function rnA(t){return e4(t,!1,XsA,tnA,g9)}function Ql(t){return e4(t,!0,ZsA,inA,c9)}function e4(t,i,n,c,I){if(!Na(t)||t.__v_raw&&!(i&&t.__v_isReactive))return t;const C=I.get(t);if(C)return C;const f=nnA(t);if(f===0)return t;const w=new Proxy(t,f===2?c:n);return I.set(t,w),w}function z_(t){return bv(t)?z_(t.__v_raw):!!(t&&t.__v_isReactive)}function bv(t){return!!(t&&t.__v_isReadonly)}function nh(t){return!!(t&&t.__v_isShallow)}function t4(t){return t?!!t.__v_raw:!1}function br(t){const i=t&&t.__v_raw;return i?br(i):t}function anA(t){return!Wr(t,"__v_skip")&&Object.isExtensible(t)&&K6(t,"__v_skip",!0),t}const fu=t=>Na(t)?Bv(t):t,P3=t=>Na(t)?Ql(t):t;function oI(t){return t?t.__v_isRef===!0:!1}function xe(t){return gnA(t,!1)}function gnA(t,i){return oI(t)?t:new cnA(t,i)}class cnA{constructor(i,n){this.dep=new $W,this.__v_isRef=!0,this.__v_isShallow=!1,this._rawValue=n?i:br(i),this._value=n?i:fu(i),this.__v_isShallow=n}get value(){return this.dep.track(),this._value}set value(i){const n=this._rawValue,c=this.__v_isShallow||nh(i)||bv(i);i=c?i:br(i),zy(i,n)&&(this._rawValue=i,this._value=c?i:fu(i),this.dep.trigger())}}function aA(t){return oI(t)?t.value:t}const lnA={get:(t,i,n)=>i==="__v_raw"?t:aA(Reflect.get(t,i,n)),set:(t,i,n,c)=>{const I=t[i];return oI(I)&&!oI(n)?(I.value=n,!0):Reflect.set(t,i,n,c)}};function l9(t){return z_(t)?t:new Proxy(t,lnA)}function Gs(t){const i=vs(t)?new Array(t.length):{};for(const n in t)i[n]=I9(t,n);return i}class InA{constructor(i,n,c){this._object=i,this._key=n,this._defaultValue=c,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 JsA(br(this._object),this._key)}}class unA{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 Jj(t,i,n){return oI(t)?t:$s(t)?new unA(t):Na(t)&&arguments.length>1?I9(t,i,n):xe(t)}function I9(t,i,n){const c=t[i];return oI(c)?c:new InA(t,i,n)}class EnA{constructor(i,n,c){this.fn=i,this.setter=n,this._value=void 0,this.dep=new $W(this),this.__v_isRef=!0,this.deps=void 0,this.depsTail=void 0,this.flags=16,this.globalVersion=DU-1,this.next=void 0,this.effect=this,this.__v_isReadonly=!n,this.isSSR=c}notify(){if(this.flags|=16,!(this.flags&8)&&_a!==this)return $6(this,!0),!0}get value(){const i=this.dep.track();return t9(this),i&&(i.version=this.dep.version),this._value}set value(i){this.setter&&this.setter(i)}}function dnA(t,i,n=!1){let c,I;return $s(t)?c=t:(c=t.get,I=t.set),new EnA(c,I,n)}const Y1={},wY=new WeakMap;let lv;function CnA(t,i=!1,n=lv){if(n){let c=wY.get(n);c||wY.set(n,c=[]),c.push(t)}}function hnA(t,i,n=Da){const{immediate:c,deep:I,once:C,scheduler:f,augmentJob:w,call:_}=n,N=KA=>I?KA:nh(KA)||I===!1||I===0?dm(KA,1):dm(KA);let L,q,lA,tA,BA=!1,IA=!1;if(oI(t)?(q=()=>t.value,BA=nh(t)):z_(t)?(q=()=>N(t),BA=!0):vs(t)?(IA=!0,BA=t.some(KA=>z_(KA)||nh(KA)),q=()=>t.map(KA=>{if(oI(KA))return KA.value;if(z_(KA))return N(KA);if($s(KA))return _?_(KA,2):KA()})):$s(t)?i?q=_?()=>_(t,2):t:q=()=>{if(lA){lD();try{lA()}finally{ID()}}const KA=lv;lv=L;try{return _?_(t,3,[tA]):t(tA)}finally{lv=KA}}:q=TQ,i&&I){const KA=q,me=I===!0?1/0:I;q=()=>dm(KA(),me)}const gA=xsA(),RA=()=>{L.stop(),gA&&gA.active&&jW(gA.effects,L)};if(C&&i){const KA=i;i=(...me)=>{KA(...me),RA()}}let HA=IA?new Array(t.length).fill(Y1):Y1;const ZA=KA=>{if(!(!(L.flags&1)||!L.dirty&&!KA))if(i){const me=L.run();if(I||BA||(IA?me.some((ae,gt)=>zy(ae,HA[gt])):zy(me,HA))){lA&&lA();const ae=lv;lv=L;try{const gt=[me,HA===Y1?void 0:IA&&HA[0]===Y1?[]:HA,tA];_?_(i,3,gt):i(...gt),HA=me}finally{lv=ae}}}else L.run()};return w&&w(ZA),L=new Z6(q),L.scheduler=f?()=>f(ZA,!1):ZA,tA=KA=>CnA(KA,!1,L),lA=L.onStop=()=>{const KA=wY.get(L);if(KA){if(_)_(KA,4);else for(const me of KA)me();wY.delete(L)}},i?c?ZA(!0):HA=L.run():f?f(ZA.bind(null,!0),!0):L.run(),RA.pause=L.pause.bind(L),RA.resume=L.resume.bind(L),RA.stop=RA,RA}function dm(t,i=1/0,n){if(i<=0||!Na(t)||t.__v_skip||(n=n||new Set,n.has(t)))return t;if(n.add(t),i--,oI(t))dm(t.value,i,n);else if(vs(t))for(let c=0;c{dm(c,i,n)});else if(q6(t)){for(const c in t)dm(t[c],i,n);for(const c of Object.getOwnPropertySymbols(t))Object.prototype.propertyIsEnumerable.call(t,c)&&dm(t[c],i,n)}return t}/**
* @vue/runtime-core v3.5.13
* (c) 2018-present Yuxi (Evan) You and Vue contributors
* @license MIT
-**/function LU(t,i,r,l){try{return l?t(...l):t()}catch(I){sV(I,i,r)}}function rB(t,i,r,l){if($s(t)){const I=LU(t,i,r,l);return I&&p6(I)&&I.catch(h=>{sV(h,i,r)}),I}if(Ms(t)){const I=[];for(let h=0;h>>1,I=pE[l],h=hU(I);h=hU(r)?pE.push(t):pE.splice(JsA(i),0,t),t.flags|=1,J6()}}function J6(){BY||(BY=V6.then(q6))}function HsA(t){Ms(t)?j_.push(...t):Ly&&t.id===-1?Ly.splice(v_+1,0,t):t.flags&1||(j_.push(t),t.flags|=1),J6()}function I8(t,i,r=QQ+1){for(;rhU(r)-hU(l));if(j_.length=0,Ly){Ly.push(...i);return}for(Ly=i,v_=0;v_t.id==null?t.flags&2?-1:1/0:t.id;function q6(t){try{for(QQ=0;QQ{l._d&&M8(-1);const h=QY(i);let f;try{f=t(...I)}finally{QY(h),l._d&&M8(1)}return f};return l._n=!0,l._c=!0,l._d=!0,l}function Ta(t,i){if(tI===null)return t;const r=lV(tI),l=t.dirs||(t.dirs=[]);for(let I=0;It.__isTeleport,ZL=t=>t&&(t.disabled||t.disabled===""),u8=t=>t&&(t.defer||t.defer===""),E8=t=>typeof SVGElement<"u"&&t instanceof SVGElement,d8=t=>typeof MathMLElement=="function"&&t instanceof MathMLElement,S3=(t,i)=>{const r=t&&t.to;return fg(r)?i?i(r):null:r},W6={name:"Teleport",__isTeleport:!0,process(t,i,r,l,I,h,f,w,_,G){const{mc:U,pc:j,pbc:lA,o:{insert:sA,querySelector:mA,createText:IA,createComment:cA}}=G,TA=ZL(i.props);let{shapeFlag:WA,children:ue,dynamicChildren:Ce}=i;if(t==null){const xe=i.el=IA(""),Qe=i.anchor=IA("");sA(xe,r,l),sA(Qe,r,l);const ut=(je,Mt)=>{WA&16&&(I&&I.isCE&&(I.ce._teleportTarget=je),U(ue,je,Mt,I,h,f,w,_))},ft=()=>{const je=i.target=S3(i.props,mA),Mt=z6(je,i,IA,sA);je&&(f!=="svg"&&E8(je)?f="svg":f!=="mathml"&&d8(je)&&(f="mathml"),TA||(ut(je,Mt),$1(i,!1)))};TA&&(ut(r,Qe),$1(i,!0)),u8(i.props)?BE(()=>{ft(),i.el.__isMounted=!0},h):ft()}else{if(u8(i.props)&&!t.el.__isMounted){BE(()=>{W6.process(t,i,r,l,I,h,f,w,_,G),delete t.el.__isMounted},h);return}i.el=t.el,i.targetStart=t.targetStart;const xe=i.anchor=t.anchor,Qe=i.target=t.target,ut=i.targetAnchor=t.targetAnchor,ft=ZL(t.props),je=ft?r:Qe,Mt=ft?xe:ut;if(f==="svg"||E8(Qe)?f="svg":(f==="mathml"||d8(Qe))&&(f="mathml"),Ce?(lA(t.dynamicChildren,Ce,je,I,h,f,w),FW(t,i,!0)):_||j(t,i,je,Mt,I,h,f,w,!1),TA)ft?i.props&&t.props&&i.props.to!==t.props.to&&(i.props.to=t.props.to):G1(i,r,xe,G,1);else if((i.props&&i.props.to)!==(t.props&&t.props.to)){const jt=i.target=S3(i.props,mA);jt&&G1(i,jt,null,G,0)}else ft&&G1(i,Qe,ut,G,1);$1(i,TA)}},remove(t,i,r,{um:l,o:{remove:I}},h){const{shapeFlag:f,children:w,anchor:_,targetStart:G,targetAnchor:U,target:j,props:lA}=t;if(j&&(I(G),I(U)),h&&I(_),f&16){const sA=h||!ZL(lA);for(let mA=0;mA{t.isMounted=!0}),LW(()=>{t.isUnmounting=!0}),t}const JC=[Function,Array],Z6={mode:String,appear:Boolean,persisted:Boolean,onBeforeEnter:JC,onEnter:JC,onAfterEnter:JC,onEnterCancelled:JC,onBeforeLeave:JC,onLeave:JC,onAfterLeave:JC,onLeaveCancelled:JC,onBeforeAppear:JC,onAppear:JC,onAfterAppear:JC,onAppearCancelled:JC},X6=t=>{const i=t.subTree;return i.component?X6(i.component):i},WsA={name:"BaseTransition",props:Z6,setup(t,{slots:i}){const r=HnA(),l=jsA();return()=>{const I=i.default&&e9(i.default(),!0);if(!I||!I.length)return;const h=$6(I),f=br(t),{mode:w}=f;if(l.isLeaving)return _j(h);const _=C8(h);if(!_)return _j(h);let G=M3(_,f,l,r,j=>G=j);_.type!==mE&&BU(_,G);let U=r.subTree&&C8(r.subTree);if(U&&U.type!==mE&&!cv(_,U)&&X6(r).type!==mE){let j=M3(U,f,l,r);if(BU(U,j),w==="out-in"&&_.type!==mE)return l.isLeaving=!0,j.afterLeave=()=>{l.isLeaving=!1,r.job.flags&8||r.update(),delete j.afterLeave,U=void 0},_j(h);w==="in-out"&&_.type!==mE?j.delayLeave=(lA,sA,mA)=>{const IA=A9(l,U);IA[String(U.key)]=U,lA[Uy]=()=>{sA(),lA[Uy]=void 0,delete G.delayedLeave,U=void 0},G.delayedLeave=()=>{mA(),delete G.delayedLeave,U=void 0}}:U=void 0}else U&&(U=void 0);return h}}};function $6(t){let i=t[0];if(t.length>1){for(const r of t)if(r.type!==mE){i=r;break}}return i}const zsA=WsA;function A9(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 M3(t,i,r,l,I){const{appear:h,mode:f,persisted:w=!1,onBeforeEnter:_,onEnter:G,onAfterEnter:U,onEnterCancelled:j,onBeforeLeave:lA,onLeave:sA,onAfterLeave:mA,onLeaveCancelled:IA,onBeforeAppear:cA,onAppear:TA,onAfterAppear:WA,onAppearCancelled:ue}=i,Ce=String(t.key),xe=A9(r,t),Qe=(je,Mt)=>{je&&rB(je,l,9,Mt)},ut=(je,Mt)=>{const jt=Mt[1];Qe(je,Mt),Ms(je)?je.every(Et=>Et.length<=1)&&jt():je.length<=1&&jt()},ft={mode:f,persisted:w,beforeEnter(je){let Mt=_;if(!r.isMounted)if(h)Mt=cA||_;else return;je[Uy]&&je[Uy](!0);const jt=xe[Ce];jt&&cv(t,jt)&&jt.el[Uy]&&jt.el[Uy](),Qe(Mt,[je])},enter(je){let Mt=G,jt=U,Et=j;if(!r.isMounted)if(h)Mt=TA||G,jt=WA||U,Et=ue||j;else return;let re=!1;const qe=je[b1]=yt=>{re||(re=!0,yt?Qe(Et,[je]):Qe(jt,[je]),ft.delayedLeave&&ft.delayedLeave(),je[b1]=void 0)};Mt?ut(Mt,[je,qe]):qe()},leave(je,Mt){const jt=String(t.key);if(je[b1]&&je[b1](!0),r.isUnmounting)return Mt();Qe(lA,[je]);let Et=!1;const re=je[Uy]=qe=>{Et||(Et=!0,Mt(),qe?Qe(IA,[je]):Qe(mA,[je]),je[Uy]=void 0,xe[jt]===t&&delete xe[jt])};xe[jt]=t,sA?ut(sA,[je,re]):re()},clone(je){const Mt=M3(je,i,r,l,I);return I&&I(Mt),Mt}};return ft}function _j(t){if(rV(t))return t=eD(t),t.children=null,t}function C8(t){if(!rV(t))return j6(t.type)&&t.children?$6(t.children):t;const{shapeFlag:i,children:r}=t;if(r){if(i&16)return r[0];if(i&32&&$s(r.default))return r.default()}}function BU(t,i){t.shapeFlag&6&&t.component?(t.transition=i,BU(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 e9(t,i=!1,r){let l=[],I=0;for(let h=0;h1)for(let h=0;hpY(mA,i&&(Ms(i)?i[IA]:i),r,l,I));return}if(W_(l)&&!I){l.shapeFlag&512&&l.type.__asyncResolved&&l.component.subTree.component&&pY(t,i,r,l.component.subTree);return}const h=l.shapeFlag&4?lV(l.component):l.el,f=I?null:h,{i:w,r:_}=t,G=i&&i.r,U=w.refs===Da?w.refs={}:w.refs,j=w.setupState,lA=br(j),sA=j===Da?()=>!1:mA=>Wr(lA,mA);if(G!=null&&G!==_&&(fg(G)?(U[G]=null,sA(G)&&(j[G]=null)):iI(G)&&(G.value=null)),$s(_))LU(_,w,12,[f,U]);else{const mA=fg(_),IA=iI(_);if(mA||IA){const cA=()=>{if(t.f){const TA=mA?sA(_)?j[_]:U[_]:_.value;I?Ms(TA)&&MW(TA,h):Ms(TA)?TA.includes(h)||TA.push(h):mA?(U[_]=[h],sA(_)&&(j[_]=U[_])):(_.value=[h],t.k&&(U[t.k]=_.value))}else mA?(U[_]=f,sA(_)&&(j[_]=f)):IA&&(_.value=f,t.k&&(U[t.k]=f))};f?(cA.id=-1,BE(cA,r)):cA()}}}iV().requestIdleCallback;iV().cancelIdleCallback;const W_=t=>!!t.type.__asyncLoader,rV=t=>t.type.__isKeepAlive;function ZsA(t,i){i9(t,"a",i)}function XsA(t,i){i9(t,"da",i)}function i9(t,i,r=xI){const l=t.__wdc||(t.__wdc=()=>{let I=r;for(;I;){if(I.isDeactivated)return;I=I.parent}return t()});if(aV(i,l,r),r){let I=r.parent;for(;I&&I.parent;)rV(I.parent.vnode)&&$sA(l,i,r,I),I=I.parent}}function $sA(t,i,r,l){const I=aV(i,t,l,!0);Kg(()=>{MW(l[i],I)},r)}function aV(t,i,r=xI,l=!1){if(r){const I=r[t]||(r[t]=[]),h=i.__weh||(i.__weh=(...f)=>{aD();const w=UU(r),_=rB(i,r,t,f);return w(),gD(),_});return l?I.unshift(h):I.push(h),h}}const hm=t=>(i,r=xI)=>{(!mU||t==="sp")&&aV(t,(...l)=>i(...l),r)},AnA=hm("bm"),hc=hm("m"),enA=hm("bu"),tnA=hm("u"),LW=hm("bum"),Kg=hm("um"),inA=hm("sp"),onA=hm("rtg"),snA=hm("rtc");function nnA(t,i=xI){aV("ec",t,i)}const rnA="components";function anA(t,i){return cnA(rnA,t,!0,i)||t}const gnA=Symbol.for("v-ndc");function cnA(t,i,r=!0,l=!1){const I=tI||xI;if(I){const h=I.type;{const w=znA(h,!1);if(w&&(w===i||w===sh(i)||w===tV(sh(i))))return h}const f=h8(I[t]||h[t],i)||h8(I.appContext[t],i);return!f&&l?h:f}}function h8(t,i){return t&&(t[i]||t[sh(i)]||t[tV(sh(i))])}function yE(t,i,r,l){let I;const h=r,f=Ms(t);if(f||fg(t)){const w=f&&K_(t);let _=!1;w&&(_=!th(t),t=oV(t)),I=new Array(t.length);for(let G=0,U=t.length;Gi(w,_,void 0,h));else{const w=Object.keys(t);I=new Array(w.length);for(let _=0,G=w.length;_pU(i)?!(i.type===mE||i.type===vr&&!o9(i.children)):!0)?t:null}const v3=t=>t?y9(t)?lV(t):v3(t.parent):null,XL=sI(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=>v3(t.parent),$root:t=>v3(t.root),$host:t=>t.ce,$emit:t=>t.emit,$options:t=>n9(t),$forceUpdate:t=>t.f||(t.f=()=>{kW(t.update)}),$nextTick:t=>t.n||(t.n=Vy.bind(t.proxy)),$watch:t=>TnA.bind(t)}),Tj=(t,i)=>t!==Da&&!t.__isScriptSetup&&Wr(t,i),lnA={get({_:t},i){if(i==="__v_skip")return!0;const{ctx:r,setupState:l,data:I,props:h,accessCache:f,type:w,appContext:_}=t;let G;if(i[0]!=="$"){const sA=f[i];if(sA!==void 0)switch(sA){case 1:return l[i];case 2:return I[i];case 4:return r[i];case 3:return h[i]}else{if(Tj(l,i))return f[i]=1,l[i];if(I!==Da&&Wr(I,i))return f[i]=2,I[i];if((G=t.propsOptions[0])&&Wr(G,i))return f[i]=3,h[i];if(r!==Da&&Wr(r,i))return f[i]=4,r[i];R3&&(f[i]=0)}}const U=XL[i];let j,lA;if(U)return i==="$attrs"&&pu(t.attrs,"get",""),U(t);if((j=w.__cssModules)&&(j=j[i]))return j;if(r!==Da&&Wr(r,i))return f[i]=4,r[i];if(lA=_.config.globalProperties,Wr(lA,i))return lA[i]},set({_:t},i,r){const{data:l,setupState:I,ctx:h}=t;return Tj(I,i)?(I[i]=r,!0):l!==Da&&Wr(l,i)?(l[i]=r,!0):Wr(t.props,i)||i[0]==="$"&&i.slice(1)in t?!1:(h[i]=r,!0)},has({_:{data:t,setupState:i,accessCache:r,ctx:l,appContext:I,propsOptions:h}},f){let w;return!!r[f]||t!==Da&&Wr(t,f)||Tj(i,f)||(w=h[0])&&Wr(w,f)||Wr(l,f)||Wr(XL,f)||Wr(I.config.globalProperties,f)},defineProperty(t,i,r){return r.get!=null?t._.accessCache[i]=0:Wr(r,"value")&&this.set(t,i,r.value,null),Reflect.defineProperty(t,i,r)}};function B8(t){return Ms(t)?t.reduce((i,r)=>(i[r]=null,i),{}):t}let R3=!0;function InA(t){const i=n9(t),r=t.proxy,l=t.ctx;R3=!1,i.beforeCreate&&Q8(i.beforeCreate,t,"bc");const{data:I,computed:h,methods:f,watch:w,provide:_,inject:G,created:U,beforeMount:j,mounted:lA,beforeUpdate:sA,updated:mA,activated:IA,deactivated:cA,beforeDestroy:TA,beforeUnmount:WA,destroyed:ue,unmounted:Ce,render:xe,renderTracked:Qe,renderTriggered:ut,errorCaptured:ft,serverPrefetch:je,expose:Mt,inheritAttrs:jt,components:Et,directives:re,filters:qe}=i;if(G&&unA(G,l,null),f)for(const Oe in f){const gt=f[Oe];$s(gt)&&(l[Oe]=gt.bind(r))}if(I){const Oe=I.call(r,r);Na(Oe)&&(t.data=dv(Oe))}if(R3=!0,h)for(const Oe in h){const gt=h[Oe],Fi=$s(gt)?gt.bind(r,r):$s(gt.get)?gt.get.bind(r,r):RQ,To=!$s(gt)&&$s(gt.set)?gt.set.bind(r):RQ,io=Tt({get:Fi,set:To});Object.defineProperty(l,Oe,{enumerable:!0,configurable:!0,get:()=>io.value,set:Eo=>io.value=Eo})}if(w)for(const Oe in w)s9(w[Oe],l,r,Oe);if(_){const Oe=$s(_)?_.call(r):_;Reflect.ownKeys(Oe).forEach(gt=>{cd(gt,Oe[gt])})}U&&Q8(U,t,"c");function Me(Oe,gt){Ms(gt)?gt.forEach(Fi=>Oe(Fi.bind(r))):gt&&Oe(gt.bind(r))}if(Me(AnA,j),Me(hc,lA),Me(enA,sA),Me(tnA,mA),Me(ZsA,IA),Me(XsA,cA),Me(nnA,ft),Me(snA,Qe),Me(onA,ut),Me(LW,WA),Me(Kg,Ce),Me(inA,je),Ms(Mt))if(Mt.length){const Oe=t.exposed||(t.exposed={});Mt.forEach(gt=>{Object.defineProperty(Oe,gt,{get:()=>r[gt],set:Fi=>r[gt]=Fi})})}else t.exposed||(t.exposed={});xe&&t.render===RQ&&(t.render=xe),jt!=null&&(t.inheritAttrs=jt),Et&&(t.components=Et),re&&(t.directives=re),je&&t9(t)}function unA(t,i,r=RQ){Ms(t)&&(t=w3(t));for(const l in t){const I=t[l];let h;Na(I)?"default"in I?h=JI(I.from||l,I.default,!0):h=JI(I.from||l):h=JI(I),iI(h)?Object.defineProperty(i,l,{enumerable:!0,configurable:!0,get:()=>h.value,set:f=>h.value=f}):i[l]=h}}function Q8(t,i,r){rB(Ms(t)?t.map(l=>l.bind(i.proxy)):t.bind(i.proxy),i,r)}function s9(t,i,r,l){let I=l.includes(".")?B9(r,l):()=>r[l];if(fg(t)){const h=i[t];$s(h)&&Rr(I,h)}else if($s(t))Rr(I,t.bind(r));else if(Na(t))if(Ms(t))t.forEach(h=>s9(h,i,r,l));else{const h=$s(t.handler)?t.handler.bind(r):i[t.handler];$s(h)&&Rr(I,h,t)}}function n9(t){const i=t.type,{mixins:r,extends:l}=i,{mixins:I,optionsCache:h,config:{optionMergeStrategies:f}}=t.appContext,w=h.get(i);let _;return w?_=w:!I.length&&!r&&!l?_=i:(_={},I.length&&I.forEach(G=>mY(_,G,f,!0)),mY(_,i,f)),Na(i)&&h.set(i,_),_}function mY(t,i,r,l=!1){const{mixins:I,extends:h}=i;h&&mY(t,h,r,!0),I&&I.forEach(f=>mY(t,f,r,!0));for(const f in i)if(!(l&&f==="expose")){const w=EnA[f]||r&&r[f];t[f]=w?w(t[f],i[f]):i[f]}return t}const EnA={data:p8,props:m8,emits:m8,methods:wL,computed:wL,beforeCreate:dE,created:dE,beforeMount:dE,mounted:dE,beforeUpdate:dE,updated:dE,beforeDestroy:dE,beforeUnmount:dE,destroyed:dE,unmounted:dE,activated:dE,deactivated:dE,errorCaptured:dE,serverPrefetch:dE,components:wL,directives:wL,watch:CnA,provide:p8,inject:dnA};function p8(t,i){return i?t?function(){return sI($s(t)?t.call(this,this):t,$s(i)?i.call(this,this):i)}:i:t}function dnA(t,i){return wL(w3(t),w3(i))}function w3(t){if(Ms(t)){const i={};for(let r=0;r1)return r&&$s(i)?i.call(l&&l.proxy):i}}const a9={},g9=()=>Object.create(a9),c9=t=>Object.getPrototypeOf(t)===a9;function QnA(t,i,r,l=!1){const I={},h=g9();t.propsDefaults=Object.create(null),l9(t,i,I,h);for(const f in t.propsOptions[0])f in I||(I[f]=void 0);r?t.props=l?I:NsA(I):t.type.props?t.props=I:t.props=h,t.attrs=h}function pnA(t,i,r,l){const{props:I,attrs:h,vnode:{patchFlag:f}}=t,w=br(I),[_]=t.propsOptions;let G=!1;if((l||f>0)&&!(f&16)){if(f&8){const U=t.vnode.dynamicProps;for(let j=0;j{_=!0;const[lA,sA]=I9(j,i,!0);sI(f,lA),sA&&w.push(...sA)};!r&&i.mixins.length&&i.mixins.forEach(U),t.extends&&U(t.extends),t.mixins&&t.mixins.forEach(U)}if(!h&&!_)return Na(t)&&l.set(t,H_),H_;if(Ms(h))for(let U=0;Ut[0]==="_"||t==="$stable",UW=t=>Ms(t)?t.map(fQ):[fQ(t)],fnA=(t,i,r)=>{if(i._n)return i;const l=Li((...I)=>UW(i(...I)),r);return l._c=!1,l},E9=(t,i,r)=>{const l=t._ctx;for(const I in t){if(u9(I))continue;const h=t[I];if($s(h))i[I]=fnA(I,h,l);else if(h!=null){const f=UW(h);i[I]=()=>f}}},d9=(t,i)=>{const r=UW(i);t.slots.default=()=>r},C9=(t,i,r)=>{for(const l in i)(r||l!=="_")&&(t[l]=i[l])},ynA=(t,i,r)=>{const l=t.slots=g9();if(t.vnode.shapeFlag&32){const I=i._;I?(C9(l,i,r),r&&y6(l,"_",I,!0)):E9(i,l)}else i&&d9(t,i)},DnA=(t,i,r)=>{const{vnode:l,slots:I}=t;let h=!0,f=Da;if(l.shapeFlag&32){const w=i._;w?r&&w===1?h=!1:C9(I,i,r):(h=!i.$stable,E9(i,I)),f=i}else i&&(d9(t,i),f={default:1});if(h)for(const w in I)!u9(w)&&f[w]==null&&delete I[w]},BE=FnA;function SnA(t){return MnA(t)}function MnA(t,i){const r=iV();r.__VUE__=!0;const{insert:l,remove:I,patchProp:h,createElement:f,createText:w,createComment:_,setText:G,setElementText:U,parentNode:j,nextSibling:lA,setScopeId:sA=RQ,insertStaticContent:mA}=t,IA=(HA,ce,Ve,Ot=null,nt=null,It=null,ei=void 0,ti=null,be=!!ce.dynamicChildren)=>{if(HA===ce)return;HA&&!cv(HA,ce)&&(Ot=Ao(HA),Eo(HA,nt,It,!0),HA=null),ce.patchFlag===-2&&(be=!1,ce.dynamicChildren=null);const{type:Ze,ref:wt,shapeFlag:Nt}=ce;switch(Ze){case cV:cA(HA,ce,Ve,Ot);break;case mE:TA(HA,ce,Ve,Ot);break;case Gj:HA==null&&WA(ce,Ve,Ot,ei);break;case vr:Et(HA,ce,Ve,Ot,nt,It,ei,ti,be);break;default:Nt&1?xe(HA,ce,Ve,Ot,nt,It,ei,ti,be):Nt&6?re(HA,ce,Ve,Ot,nt,It,ei,ti,be):(Nt&64||Nt&128)&&Ze.process(HA,ce,Ve,Ot,nt,It,ei,ti,be,bi)}wt!=null&&nt&&pY(wt,HA&&HA.ref,It,ce||HA,!ce)},cA=(HA,ce,Ve,Ot)=>{if(HA==null)l(ce.el=w(ce.children),Ve,Ot);else{const nt=ce.el=HA.el;ce.children!==HA.children&&G(nt,ce.children)}},TA=(HA,ce,Ve,Ot)=>{HA==null?l(ce.el=_(ce.children||""),Ve,Ot):ce.el=HA.el},WA=(HA,ce,Ve,Ot)=>{[HA.el,HA.anchor]=mA(HA.children,ce,Ve,Ot,HA.el,HA.anchor)},ue=({el:HA,anchor:ce},Ve,Ot)=>{let nt;for(;HA&&HA!==ce;)nt=lA(HA),l(HA,Ve,Ot),HA=nt;l(ce,Ve,Ot)},Ce=({el:HA,anchor:ce})=>{let Ve;for(;HA&&HA!==ce;)Ve=lA(HA),I(HA),HA=Ve;I(ce)},xe=(HA,ce,Ve,Ot,nt,It,ei,ti,be)=>{ce.type==="svg"?ei="svg":ce.type==="math"&&(ei="mathml"),HA==null?Qe(ce,Ve,Ot,nt,It,ei,ti,be):je(HA,ce,nt,It,ei,ti,be)},Qe=(HA,ce,Ve,Ot,nt,It,ei,ti)=>{let be,Ze;const{props:wt,shapeFlag:Nt,transition:Oi,dirs:po}=HA;if(be=HA.el=f(HA.type,It,wt&&wt.is,wt),Nt&8?U(be,HA.children):Nt&16&&ft(HA.children,be,null,Ot,nt,Nj(HA,It),ei,ti),po&&ev(HA,null,Ot,"created"),ut(be,HA,HA.scopeId,ei,Ot),wt){for(const so in wt)so!=="value"&&!jL(so)&&h(be,so,null,wt[so],It,Ot);"value"in wt&&h(be,"value",null,wt.value,It),(Ze=wt.onVnodeBeforeMount)&&BQ(Ze,Ot,HA)}po&&ev(HA,null,Ot,"beforeMount");const No=vnA(nt,Oi);No&&Oi.beforeEnter(be),l(be,ce,Ve),((Ze=wt&&wt.onVnodeMounted)||No||po)&&BE(()=>{Ze&&BQ(Ze,Ot,HA),No&&Oi.enter(be),po&&ev(HA,null,Ot,"mounted")},nt)},ut=(HA,ce,Ve,Ot,nt)=>{if(Ve&&sA(HA,Ve),Ot)for(let It=0;It{for(let Ze=be;Ze{const ti=ce.el=HA.el;let{patchFlag:be,dynamicChildren:Ze,dirs:wt}=ce;be|=HA.patchFlag&16;const Nt=HA.props||Da,Oi=ce.props||Da;let po;if(Ve&&tv(Ve,!1),(po=Oi.onVnodeBeforeUpdate)&&BQ(po,Ve,ce,HA),wt&&ev(ce,HA,Ve,"beforeUpdate"),Ve&&tv(Ve,!0),(Nt.innerHTML&&Oi.innerHTML==null||Nt.textContent&&Oi.textContent==null)&&U(ti,""),Ze?Mt(HA.dynamicChildren,Ze,ti,Ve,Ot,Nj(ce,nt),It):ei||gt(HA,ce,ti,null,Ve,Ot,Nj(ce,nt),It,!1),be>0){if(be&16)jt(ti,Nt,Oi,Ve,nt);else if(be&2&&Nt.class!==Oi.class&&h(ti,"class",null,Oi.class,nt),be&4&&h(ti,"style",Nt.style,Oi.style,nt),be&8){const No=ce.dynamicProps;for(let so=0;so{po&&BQ(po,Ve,ce,HA),wt&&ev(ce,HA,Ve,"updated")},Ot)},Mt=(HA,ce,Ve,Ot,nt,It,ei)=>{for(let ti=0;ti{if(ce!==Ve){if(ce!==Da)for(const It in ce)!jL(It)&&!(It in Ve)&&h(HA,It,ce[It],null,nt,Ot);for(const It in Ve){if(jL(It))continue;const ei=Ve[It],ti=ce[It];ei!==ti&&It!=="value"&&h(HA,It,ti,ei,nt,Ot)}"value"in Ve&&h(HA,"value",ce.value,Ve.value,nt)}},Et=(HA,ce,Ve,Ot,nt,It,ei,ti,be)=>{const Ze=ce.el=HA?HA.el:w(""),wt=ce.anchor=HA?HA.anchor:w("");let{patchFlag:Nt,dynamicChildren:Oi,slotScopeIds:po}=ce;po&&(ti=ti?ti.concat(po):po),HA==null?(l(Ze,Ve,Ot),l(wt,Ve,Ot),ft(ce.children||[],Ve,wt,nt,It,ei,ti,be)):Nt>0&&Nt&64&&Oi&&HA.dynamicChildren?(Mt(HA.dynamicChildren,Oi,Ve,nt,It,ei,ti),(ce.key!=null||nt&&ce===nt.subTree)&&FW(HA,ce,!0)):gt(HA,ce,Ve,wt,nt,It,ei,ti,be)},re=(HA,ce,Ve,Ot,nt,It,ei,ti,be)=>{ce.slotScopeIds=ti,HA==null?ce.shapeFlag&512?nt.ctx.activate(ce,Ve,Ot,ei,be):qe(ce,Ve,Ot,nt,It,ei,be):yt(HA,ce,be)},qe=(HA,ce,Ve,Ot,nt,It,ei)=>{const ti=HA.component=JnA(HA,Ot,nt);if(rV(HA)&&(ti.ctx.renderer=bi),qnA(ti,!1,ei),ti.asyncDep){if(nt&&nt.registerDep(ti,Me,ei),!HA.el){const be=ti.subTree=Lt(mE);TA(null,be,ce,Ve)}}else Me(ti,HA,ce,Ve,nt,It,ei)},yt=(HA,ce,Ve)=>{const Ot=ce.component=HA.component;if(LnA(HA,ce,Ve))if(Ot.asyncDep&&!Ot.asyncResolved){Oe(Ot,ce,Ve);return}else Ot.next=ce,Ot.update();else ce.el=HA.el,Ot.vnode=ce},Me=(HA,ce,Ve,Ot,nt,It,ei)=>{const ti=()=>{if(HA.isMounted){let{next:Nt,bu:Oi,u:po,parent:No,vnode:so}=HA;{const an=h9(HA);if(an){Nt&&(Nt.el=so.el,Oe(HA,Nt,ei)),an.asyncDep.then(()=>{HA.isUnmounted||ti()});return}}let Go=Nt,An;tv(HA,!1),Nt?(Nt.el=so.el,Oe(HA,Nt,ei)):Nt=so,Oi&&X1(Oi),(An=Nt.props&&Nt.props.onVnodeBeforeUpdate)&&BQ(An,No,Nt,so),tv(HA,!0);const rn=D8(HA),Es=HA.subTree;HA.subTree=rn,IA(Es,rn,j(Es.el),Ao(Es),HA,nt,It),Nt.el=rn.el,Go===null&&UnA(HA,rn.el),po&&BE(po,nt),(An=Nt.props&&Nt.props.onVnodeUpdated)&&BE(()=>BQ(An,No,Nt,so),nt)}else{let Nt;const{el:Oi,props:po}=ce,{bm:No,m:so,parent:Go,root:An,type:rn}=HA,Es=W_(ce);tv(HA,!1),No&&X1(No),!Es&&(Nt=po&&po.onVnodeBeforeMount)&&BQ(Nt,Go,ce),tv(HA,!0);{An.ce&&An.ce._injectChildStyle(rn);const an=HA.subTree=D8(HA);IA(null,an,Ve,Ot,HA,nt,It),ce.el=an.el}if(so&&BE(so,nt),!Es&&(Nt=po&&po.onVnodeMounted)){const an=ce;BE(()=>BQ(Nt,Go,an),nt)}(ce.shapeFlag&256||Go&&W_(Go.vnode)&&Go.vnode.shapeFlag&256)&&HA.a&&BE(HA.a,nt),HA.isMounted=!0,ce=Ve=Ot=null}};HA.scope.on();const be=HA.effect=new v6(ti);HA.scope.off();const Ze=HA.update=be.run.bind(be),wt=HA.job=be.runIfDirty.bind(be);wt.i=HA,wt.id=HA.uid,be.scheduler=()=>kW(wt),tv(HA,!0),Ze()},Oe=(HA,ce,Ve)=>{ce.component=HA;const Ot=HA.vnode.props;HA.vnode=ce,HA.next=null,pnA(HA,ce.props,Ot,Ve),DnA(HA,ce.children,Ve),aD(),I8(HA),gD()},gt=(HA,ce,Ve,Ot,nt,It,ei,ti,be=!1)=>{const Ze=HA&&HA.children,wt=HA?HA.shapeFlag:0,Nt=ce.children,{patchFlag:Oi,shapeFlag:po}=ce;if(Oi>0){if(Oi&128){To(Ze,Nt,Ve,Ot,nt,It,ei,ti,be);return}else if(Oi&256){Fi(Ze,Nt,Ve,Ot,nt,It,ei,ti,be);return}}po&8?(wt&16&&jo(Ze,nt,It),Nt!==Ze&&U(Ve,Nt)):wt&16?po&16?To(Ze,Nt,Ve,Ot,nt,It,ei,ti,be):jo(Ze,nt,It,!0):(wt&8&&U(Ve,""),po&16&&ft(Nt,Ve,Ot,nt,It,ei,ti,be))},Fi=(HA,ce,Ve,Ot,nt,It,ei,ti,be)=>{HA=HA||H_,ce=ce||H_;const Ze=HA.length,wt=ce.length,Nt=Math.min(Ze,wt);let Oi;for(Oi=0;Oiwt?jo(HA,nt,It,!0,!1,Nt):ft(ce,Ve,Ot,nt,It,ei,ti,be,Nt)},To=(HA,ce,Ve,Ot,nt,It,ei,ti,be)=>{let Ze=0;const wt=ce.length;let Nt=HA.length-1,Oi=wt-1;for(;Ze<=Nt&&Ze<=Oi;){const po=HA[Ze],No=ce[Ze]=be?Fy(ce[Ze]):fQ(ce[Ze]);if(cv(po,No))IA(po,No,Ve,null,nt,It,ei,ti,be);else break;Ze++}for(;Ze<=Nt&&Ze<=Oi;){const po=HA[Nt],No=ce[Oi]=be?Fy(ce[Oi]):fQ(ce[Oi]);if(cv(po,No))IA(po,No,Ve,null,nt,It,ei,ti,be);else break;Nt--,Oi--}if(Ze>Nt){if(Ze<=Oi){const po=Oi+1,No=poOi)for(;Ze<=Nt;)Eo(HA[Ze],nt,It,!0),Ze++;else{const po=Ze,No=Ze,so=new Map;for(Ze=No;Ze<=Oi;Ze++){const Jn=ce[Ze]=be?Fy(ce[Ze]):fQ(ce[Ze]);Jn.key!=null&&so.set(Jn.key,Ze)}let Go,An=0;const rn=Oi-No+1;let Es=!1,an=0;const Do=new Array(rn);for(Ze=0;Ze=rn){Eo(Jn,nt,It,!0);continue}let Qr;if(Jn.key!=null)Qr=so.get(Jn.key);else for(Go=No;Go<=Oi;Go++)if(Do[Go-No]===0&&cv(Jn,ce[Go])){Qr=Go;break}Qr===void 0?Eo(Jn,nt,It,!0):(Do[Qr-No]=Ze+1,Qr>=an?an=Qr:Es=!0,IA(Jn,ce[Qr],Ve,null,nt,It,ei,ti,be),An++)}const pA=Es?RnA(Do):H_;for(Go=pA.length-1,Ze=rn-1;Ze>=0;Ze--){const Jn=No+Ze,Qr=ce[Jn],ds=Jn+1{const{el:It,type:ei,transition:ti,children:be,shapeFlag:Ze}=HA;if(Ze&6){io(HA.component.subTree,ce,Ve,Ot);return}if(Ze&128){HA.suspense.move(ce,Ve,Ot);return}if(Ze&64){ei.move(HA,ce,Ve,bi);return}if(ei===vr){l(It,ce,Ve);for(let Nt=0;Ntti.enter(It),nt);else{const{leave:Nt,delayLeave:Oi,afterLeave:po}=ti,No=()=>l(It,ce,Ve),so=()=>{Nt(It,()=>{No(),po&&po()})};Oi?Oi(It,No,so):so()}else l(It,ce,Ve)},Eo=(HA,ce,Ve,Ot=!1,nt=!1)=>{const{type:It,props:ei,ref:ti,children:be,dynamicChildren:Ze,shapeFlag:wt,patchFlag:Nt,dirs:Oi,cacheIndex:po}=HA;if(Nt===-2&&(nt=!1),ti!=null&&pY(ti,null,Ve,HA,!0),po!=null&&(ce.renderCache[po]=void 0),wt&256){ce.ctx.deactivate(HA);return}const No=wt&1&&Oi,so=!W_(HA);let Go;if(so&&(Go=ei&&ei.onVnodeBeforeUnmount)&&BQ(Go,ce,HA),wt&6)ns(HA.component,Ve,Ot);else{if(wt&128){HA.suspense.unmount(Ve,Ot);return}No&&ev(HA,null,ce,"beforeUnmount"),wt&64?HA.type.remove(HA,ce,Ve,bi,Ot):Ze&&!Ze.hasOnce&&(It!==vr||Nt>0&&Nt&64)?jo(Ze,ce,Ve,!1,!0):(It===vr&&Nt&384||!nt&&wt&16)&&jo(be,ce,Ve),Ot&&Vs(HA)}(so&&(Go=ei&&ei.onVnodeUnmounted)||No)&&BE(()=>{Go&&BQ(Go,ce,HA),No&&ev(HA,null,ce,"unmounted")},Ve)},Vs=HA=>{const{type:ce,el:Ve,anchor:Ot,transition:nt}=HA;if(ce===vr){ki(Ve,Ot);return}if(ce===Gj){Ce(HA);return}const It=()=>{I(Ve),nt&&!nt.persisted&&nt.afterLeave&&nt.afterLeave()};if(HA.shapeFlag&1&&nt&&!nt.persisted){const{leave:ei,delayLeave:ti}=nt,be=()=>ei(Ve,It);ti?ti(HA.el,It,be):be()}else It()},ki=(HA,ce)=>{let Ve;for(;HA!==ce;)Ve=lA(HA),I(HA),HA=Ve;I(ce)},ns=(HA,ce,Ve)=>{const{bum:Ot,scope:nt,job:It,subTree:ei,um:ti,m:be,a:Ze}=HA;y8(be),y8(Ze),Ot&&X1(Ot),nt.stop(),It&&(It.flags|=8,Eo(ei,HA,ce,Ve)),ti&&BE(ti,ce),BE(()=>{HA.isUnmounted=!0},ce),ce&&ce.pendingBranch&&!ce.isUnmounted&&HA.asyncDep&&!HA.asyncResolved&&HA.suspenseId===ce.pendingId&&(ce.deps--,ce.deps===0&&ce.resolve())},jo=(HA,ce,Ve,Ot=!1,nt=!1,It=0)=>{for(let ei=It;ei{if(HA.shapeFlag&6)return Ao(HA.component.subTree);if(HA.shapeFlag&128)return HA.suspense.next();const ce=lA(HA.anchor||HA.el),Ve=ce&&ce[K6];return Ve?lA(Ve):ce};let Zt=!1;const oo=(HA,ce,Ve)=>{HA==null?ce._vnode&&Eo(ce._vnode,null,null,!0):IA(ce._vnode||null,HA,ce,null,null,null,Ve),ce._vnode=HA,Zt||(Zt=!0,I8(),H6(),Zt=!1)},bi={p:IA,um:Eo,m:io,r:Vs,mt:qe,mc:ft,pc:gt,pbc:Mt,n:Ao,o:t};return{render:oo,hydrate:void 0,createApp:BnA(oo)}}function Nj({type:t,props:i},r){return r==="svg"&&t==="foreignObject"||r==="mathml"&&t==="annotation-xml"&&i&&i.encoding&&i.encoding.includes("html")?void 0:r}function tv({effect:t,job:i},r){r?(t.flags|=32,i.flags|=4):(t.flags&=-33,i.flags&=-5)}function vnA(t,i){return(!t||t&&!t.pendingBranch)&&i&&!i.persisted}function FW(t,i,r=!1){const l=t.children,I=i.children;if(Ms(l)&&Ms(I))for(let h=0;h>1,t[r[w]]0&&(i[l]=r[h-1]),r[h]=l)}}for(h=r.length,f=r[h-1];h-- >0;)r[h]=f,f=i[f];return r}function h9(t){const i=t.subTree.component;if(i)return i.asyncDep&&!i.asyncResolved?i:h9(i)}function y8(t){if(t)for(let i=0;iJI(wnA);function ET(t,i){return OW(t,null,i)}function Rr(t,i,r){return OW(t,i,r)}function OW(t,i,r=Da){const{immediate:l,deep:I,flush:h,once:f}=r,w=sI({},r),_=i&&l||!i&&h!=="post";let G;if(mU){if(h==="sync"){const sA=_nA();G=sA.__watcherHandles||(sA.__watcherHandles=[])}else if(!_){const sA=()=>{};return sA.stop=RQ,sA.resume=RQ,sA.pause=RQ,sA}}const U=xI;w.call=(sA,mA,IA)=>rB(sA,U,mA,IA);let j=!1;h==="post"?w.scheduler=sA=>{BE(sA,U&&U.suspense)}:h!=="sync"&&(j=!0,w.scheduler=(sA,mA)=>{mA?sA():kW(sA)}),w.augmentJob=sA=>{i&&(sA.flags|=4),j&&(sA.flags|=2,U&&(sA.id=U.uid,sA.i=U))};const lA=YsA(t,i,w);return mU&&(G?G.push(lA):_&&lA()),lA}function TnA(t,i,r){const l=this.proxy,I=fg(t)?t.includes(".")?B9(l,t):()=>l[t]:t.bind(l,l);let h;$s(i)?h=i:(h=i.handler,r=i);const f=UU(this),w=OW(I,h.bind(l),r);return f(),w}function B9(t,i){const r=i.split(".");return()=>{let l=t;for(let I=0;Ii==="modelValue"||i==="model-value"?t.modelModifiers:t[`${i}Modifiers`]||t[`${sh(i)}Modifiers`]||t[`${rD(i)}Modifiers`];function GnA(t,i,...r){if(t.isUnmounted)return;const l=t.vnode.props||Da;let I=r;const h=i.startsWith("update:"),f=h&&NnA(l,i.slice(7));f&&(f.trim&&(I=r.map(U=>fg(U)?U.trim():U)),f.number&&(I=r.map(p3)));let w,_=l[w=Dj(i)]||l[w=Dj(sh(i))];!_&&h&&(_=l[w=Dj(rD(i))]),_&&rB(_,t,6,I);const G=l[w+"Once"];if(G){if(!t.emitted)t.emitted={};else if(t.emitted[w])return;t.emitted[w]=!0,rB(G,t,6,I)}}function Q9(t,i,r=!1){const l=i.emitsCache,I=l.get(t);if(I!==void 0)return I;const h=t.emits;let f={},w=!1;if(!$s(t)){const _=G=>{const U=Q9(G,i,!0);U&&(w=!0,sI(f,U))};!r&&i.mixins.length&&i.mixins.forEach(_),t.extends&&_(t.extends),t.mixins&&t.mixins.forEach(_)}return!h&&!w?(Na(t)&&l.set(t,null),null):(Ms(h)?h.forEach(_=>f[_]=null):sI(f,h),Na(t)&&l.set(t,f),f)}function gV(t,i){return!t||!$Y(i)?!1:(i=i.slice(2).replace(/Once$/,""),Wr(t,i[0].toLowerCase()+i.slice(1))||Wr(t,rD(i))||Wr(t,i))}function D8(t){const{type:i,vnode:r,proxy:l,withProxy:I,propsOptions:[h],slots:f,attrs:w,emit:_,render:G,renderCache:U,props:j,data:lA,setupState:sA,ctx:mA,inheritAttrs:IA}=t,cA=QY(t);let TA,WA;try{if(r.shapeFlag&4){const Ce=I||l,xe=Ce;TA=fQ(G.call(xe,Ce,U,j,sA,lA,mA)),WA=w}else{const Ce=i;TA=fQ(Ce.length>1?Ce(j,{attrs:w,slots:f,emit:_}):Ce(j,null)),WA=i.props?w:bnA(w)}}catch(Ce){$L.length=0,sV(Ce,t,1),TA=Lt(mE)}let ue=TA;if(WA&&IA!==!1){const Ce=Object.keys(WA),{shapeFlag:xe}=ue;Ce.length&&xe&7&&(h&&Ce.some(SW)&&(WA=knA(WA,h)),ue=eD(ue,WA,!1,!0))}return r.dirs&&(ue=eD(ue,null,!1,!0),ue.dirs=ue.dirs?ue.dirs.concat(r.dirs):r.dirs),r.transition&&BU(ue,r.transition),TA=ue,QY(cA),TA}const bnA=t=>{let i;for(const r in t)(r==="class"||r==="style"||$Y(r))&&((i||(i={}))[r]=t[r]);return i},knA=(t,i)=>{const r={};for(const l in t)(!SW(l)||!(l.slice(9)in i))&&(r[l]=t[l]);return r};function LnA(t,i,r){const{props:l,children:I,component:h}=t,{props:f,children:w,patchFlag:_}=i,G=h.emitsOptions;if(i.dirs||i.transition)return!0;if(r&&_>=0){if(_&1024)return!0;if(_&16)return l?S8(l,f,G):!!f;if(_&8){const U=i.dynamicProps;for(let j=0;jt.__isSuspense;function FnA(t,i){i&&i.pendingBranch?Ms(t)?i.effects.push(...t):i.effects.push(t):HsA(t)}const vr=Symbol.for("v-fgt"),cV=Symbol.for("v-txt"),mE=Symbol.for("v-cmt"),Gj=Symbol.for("v-stc"),$L=[];let oC=null;function ie(t=!1){$L.push(oC=t?null:[])}function OnA(){$L.pop(),oC=$L[$L.length-1]||null}let QU=1;function M8(t,i=!1){QU+=t,t<0&&oC&&i&&(oC.hasOnce=!0)}function m9(t){return t.dynamicChildren=QU>0?oC||H_:null,OnA(),QU>0&&oC&&oC.push(t),t}function $e(t,i,r,l,I,h){return m9(ne(t,i,r,l,I,h,!0))}function Qi(t,i,r,l,I){return m9(Lt(t,i,r,l,I,!0))}function pU(t){return t?t.__v_isVNode===!0:!1}function cv(t,i){return t.type===i.type&&t.key===i.key}const f9=({key:t})=>t??null,AY=({ref:t,ref_key:i,ref_for:r})=>(typeof t=="number"&&(t=""+t),t!=null?fg(t)||iI(t)||$s(t)?{i:tI,r:t,k:i,f:!!r}:t:null);function ne(t,i=null,r=null,l=0,I=null,h=t===vr?0:1,f=!1,w=!1){const _={__v_isVNode:!0,__v_skip:!0,type:t,props:i,key:i&&f9(i),ref:i&&AY(i),scopeId:nV,slotScopeIds:null,children:r,component:null,suspense:null,ssContent:null,ssFallback:null,dirs:null,transition:null,el:null,anchor:null,target:null,targetStart:null,targetAnchor:null,staticCount:0,shapeFlag:h,patchFlag:l,dynamicProps:I,dynamicChildren:null,appContext:null,ctx:tI};return w?(PW(_,r),h&128&&t.normalize(_)):r&&(_.shapeFlag|=fg(r)?8:16),QU>0&&!f&&oC&&(_.patchFlag>0||h&6)&&_.patchFlag!==32&&oC.push(_),_}const Lt=PnA;function PnA(t,i=null,r=null,l=0,I=null,h=!1){if((!t||t===gnA)&&(t=mE),pU(t)){const w=eD(t,i,!0);return r&&PW(w,r),QU>0&&!h&&oC&&(w.shapeFlag&6?oC[oC.indexOf(t)]=w:oC.push(w)),w.patchFlag=-2,w}if(ZnA(t)&&(t=t.__vccOpts),i){i=xnA(i);let{class:w,style:_}=i;w&&!fg(w)&&(i.class=qi(w)),Na(_)&&(bW(_)&&!Ms(_)&&(_=sI({},_)),i.style=Br(_))}const f=fg(t)?1:p9(t)?128:j6(t)?64:Na(t)?4:$s(t)?2:0;return ne(t,i,r,l,I,f,h,!0)}function xnA(t){return t?bW(t)||c9(t)?sI({},t):t:null}function eD(t,i,r=!1,l=!1){const{props:I,ref:h,patchFlag:f,children:w,transition:_}=t,G=i?T3(I||{},i):I,U={__v_isVNode:!0,__v_skip:!0,type:t.type,props:G,key:G&&f9(G),ref:i&&i.ref?r&&h?Ms(h)?h.concat(AY(i)):[h,AY(i)]:AY(i):h,scopeId:t.scopeId,slotScopeIds:t.slotScopeIds,children:w,target:t.target,targetStart:t.targetStart,targetAnchor:t.targetAnchor,staticCount:t.staticCount,shapeFlag:t.shapeFlag,patchFlag:i&&t.type!==vr?f===-1?16:f|16:f,dynamicProps:t.dynamicProps,dynamicChildren:t.dynamicChildren,appContext:t.appContext,dirs:t.dirs,transition:_,component:t.component,suspense:t.suspense,ssContent:t.ssContent&&eD(t.ssContent),ssFallback:t.ssFallback&&eD(t.ssFallback),el:t.el,anchor:t.anchor,ctx:t.ctx,ce:t.ce};return _&&l&&BU(U,_.clone(U)),U}function Ia(t=" ",i=0){return Lt(cV,null,t,i)}function zt(t="",i=!1){return i?(ie(),Qi(mE,null,t)):Lt(mE,null,t)}function fQ(t){return t==null||typeof t=="boolean"?Lt(mE):Ms(t)?Lt(vr,null,t.slice()):pU(t)?Fy(t):Lt(cV,null,String(t))}function Fy(t){return t.el===null&&t.patchFlag!==-1||t.memo?t:eD(t)}function PW(t,i){let r=0;const{shapeFlag:l}=t;if(i==null)i=null;else if(Ms(i))r=16;else if(typeof i=="object")if(l&65){const I=i.default;I&&(I._c&&(I._d=!1),PW(t,I()),I._c&&(I._d=!0));return}else{r=32;const I=i._;!I&&!c9(i)?i._ctx=tI:I===3&&tI&&(tI.slots._===1?i._=1:(i._=2,t.patchFlag|=1024))}else $s(i)?(i={default:i,_ctx:tI},r=32):(i=String(i),l&64?(r=16,i=[Ia(i)]):r=8);t.children=i,t.shapeFlag|=r}function T3(...t){const i={};for(let r=0;rxI||tI;let fY,N3;{const t=iV(),i=(r,l)=>{let I;return(I=t[r])||(I=t[r]=[]),I.push(l),h=>{I.length>1?I.forEach(f=>f(h)):I[0](h)}};fY=i("__VUE_INSTANCE_SETTERS__",r=>xI=r),N3=i("__VUE_SSR_SETTERS__",r=>mU=r)}const UU=t=>{const i=xI;return fY(t),t.scope.on(),()=>{t.scope.off(),fY(i)}},v8=()=>{xI&&xI.scope.off(),fY(null)};function y9(t){return t.vnode.shapeFlag&4}let mU=!1;function qnA(t,i=!1,r=!1){i&&N3(i);const{props:l,children:I}=t.vnode,h=y9(t);QnA(t,l,h,i),ynA(t,I,r);const f=h?KnA(t,i):void 0;return i&&N3(!1),f}function KnA(t,i){const r=t.type;t.accessCache=Object.create(null),t.proxy=new Proxy(t.ctx,lnA);const{setup:l}=r;if(l){aD();const I=t.setupContext=l.length>1?WnA(t):null,h=UU(t),f=LU(l,t,0,[t.props,I]),w=p6(f);if(gD(),h(),(w||t.sp)&&!W_(t)&&t9(t),w){if(f.then(v8,v8),i)return f.then(_=>{R8(t,_)}).catch(_=>{sV(_,t,0)});t.asyncDep=f}else R8(t,f)}else D9(t)}function R8(t,i,r){$s(i)?t.type.__ssrInlineRender?t.ssrRender=i:t.render=i:Na(i)&&(t.setupState=x6(i)),D9(t)}function D9(t,i,r){const l=t.type;t.render||(t.render=l.render||RQ);{const I=UU(t);aD();try{InA(t)}finally{gD(),I()}}}const jnA={get(t,i){return pu(t,"get",""),t[i]}};function WnA(t){const i=r=>{t.exposed=r||{}};return{attrs:new Proxy(t.attrs,jnA),slots:t.slots,emit:t.emit,expose:i}}function lV(t){return t.exposed?t.exposeProxy||(t.exposeProxy=new Proxy(x6(GsA(t.exposed)),{get(i,r){if(r in i)return i[r];if(r in XL)return XL[r](t)},has(i,r){return r in i||r in XL}})):t.proxy}function znA(t,i=!0){return $s(t)?t.displayName||t.name:t.name||i&&t.__name}function ZnA(t){return $s(t)&&"__vccOpts"in t}const Tt=(t,i)=>PsA(t,i,mU);function XnA(t,i,r){const l=arguments.length;return l===2?Na(i)&&!Ms(i)?pU(i)?Lt(t,null,[i]):Lt(t,i):Lt(t,null,i):(l>3?r=Array.prototype.slice.call(arguments,2):l===3&&pU(r)&&(r=[r]),Lt(t,i,r))}const G3="3.5.13";/**
+**/function qU(t,i,n,c){try{return c?t(...c):t()}catch(I){QV(I,i,n)}}function cB(t,i,n,c){if($s(t)){const I=qU(t,i,n,c);return I&&J6(I)&&I.catch(C=>{QV(C,i,n)}),I}if(vs(t)){const I=[];for(let C=0;C>>1,I=mE[c],C=MU(I);C=MU(n)?mE.push(t):mE.splice(QnA(i),0,t),t.flags|=1,E9()}}function E9(){_Y||(_Y=u9.then(C9))}function pnA(t){vs(t)?Z_.push(...t):Oy&&t.id===-1?Oy.splice(__+1,0,t):t.flags&1||(Z_.push(t),t.flags|=1),E9()}function k8(t,i,n=fQ+1){for(;n