4 Commits
118 changed files with 45882 additions and 23418 deletions
+3
View File
@@ -0,0 +1,3 @@
VUE_APP_RUNTIME_ENV=local
VUE_APP_APP_SERVER_TARGET=http://18.141.44.165:8888
VUE_APP_WEB_API_TARGET=http://18.141.44.165:9000
+1
View File
@@ -0,0 +1 @@
VUE_APP_RUNTIME_ENV=production
+2
View File
@@ -7,3 +7,5 @@ yarn-error.log*
*.local
.env
.env.*
!.env.development
!.env.production
Binary file not shown.
-75
View File
@@ -1,75 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
CONFIG_FILE=${JC_WEB_IM_UPDATE_CONFIG:-/etc/jc-web-im-update.conf}
STATE_DIR=/var/lib/jc-web-im-update
LOCK_FILE=/run/lock/jc-web-im-update.lock
if [[ ! -r "$CONFIG_FILE" ]]; then
echo "Missing configuration: $CONFIG_FILE" >&2
exit 1
fi
# shellcheck source=/dev/null
source "$CONFIG_FILE"
: "${REPO_DIR:?REPO_DIR is required}"
: "${WEB_ROOT:?WEB_ROOT is required}"
: "${BRANCH:=main}"
case "$REPO_DIR" in
/opt/jc-web-im-release|/opt/jc-web-im-release-*) ;;
*) echo "Unsafe REPO_DIR: $REPO_DIR" >&2; exit 1 ;;
esac
case "$WEB_ROOT" in
/var/www/jc-web-im|/var/www/jc-web-im-*) ;;
*) echo "Unsafe WEB_ROOT: $WEB_ROOT" >&2; exit 1 ;;
esac
mkdir -p "$STATE_DIR"
exec 9>"$LOCK_FILE"
flock -n 9 || {
echo "Another update is already running"
exit 0
}
git -C "$REPO_DIR" fetch --quiet origin "$BRANCH"
TARGET_COMMIT=$(git -C "$REPO_DIR" rev-parse "origin/$BRANCH")
CURRENT_COMMIT=$(cat "$STATE_DIR/last_deployed" 2>/dev/null || true)
if [[ "$TARGET_COMMIT" == "$CURRENT_COMMIT" ]]; then
echo "Already current: $TARGET_COMMIT"
exit 0
fi
git -C "$REPO_DIR" reset --hard --quiet "$TARGET_COMMIT"
DIST_DIR="$REPO_DIR/dist"
[[ -f "$DIST_DIR/index.html" ]] || {
echo "Missing dist/index.html at $TARGET_COMMIT" >&2
exit 1
}
while IFS= read -r asset; do
[[ -f "$DIST_DIR/$asset" ]] || {
echo "Missing referenced asset: $asset" >&2
exit 1
}
done < <(grep -oE '(css|js)/[^"'"'"' ]+' "$DIST_DIR/index.html" | sort -u)
find "$DIST_DIR/api" -type f -name '*.php' -print0 |
xargs -0 -r -n1 php -l >/dev/null
BACKUP_DIR="/var/backups/jc-web-im/$(date +%Y%m%d-%H%M%S)"
mkdir -p "$BACKUP_DIR"
[[ -f "$WEB_ROOT/index.html" ]] && cp -a "$WEB_ROOT/index.html" "$BACKUP_DIR/"
[[ -f "$WEB_ROOT/config/runtime-config.js" ]] && {
mkdir -p "$BACKUP_DIR/config"
cp -a "$WEB_ROOT/config/runtime-config.js" "$BACKUP_DIR/config/"
}
mkdir -p "$WEB_ROOT"
rsync -a --exclude='/config/runtime-config.js' "$DIST_DIR/" "$WEB_ROOT/"
chown -R www-data:www-data "$WEB_ROOT"
printf '%s\n' "$TARGET_COMMIT" >"$STATE_DIR/last_deployed"
echo "Deployed: $TARGET_COMMIT -> $WEB_ROOT"
Binary file not shown.
+95
View File
@@ -0,0 +1,95 @@
<?php
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');
require __DIR__ . '/im_web_bootstrap.php';
$payload = readJsonPayload();
$userId = trim((string)($payload['userId'] ?? ''));
$keyword = trim((string)($payload['keyword'] ?? ''));
$reason = trim((string)($payload['reason'] ?? '添加联系人'));
if ($userId === '') {
respond(400, '缺少当前用户ID');
}
if ($keyword === '') {
respond(400, '请输入要添加的联系人');
}
function tryImUserInfo(array $payload): ?array
{
try {
$result = requireImSuccess(imAdminPost('/admin/user/get_info', $payload), '用户查询失败');
return $result ?: null;
} catch (Throwable $error) {
return null;
}
}
function normalizeUserInfo(array $user): array
{
$uid = (string)($user['userId'] ?? $user['uid'] ?? '');
return [
'uid' => $uid,
'name' => (string)($user['name'] ?? $uid),
'displayName' => (string)($user['displayName'] ?? $user['name'] ?? $uid),
'mobile' => (string)($user['mobile'] ?? ''),
'portrait' => (string)($user['portrait'] ?? ''),
'alias' => '',
];
}
try {
$target = tryImUserInfo(['userId' => $keyword]);
if (!$target && preg_match('/^\+?\d{5,32}$/', $keyword)) {
$target = tryImUserInfo(['mobile' => $keyword]);
}
if (!$target) {
$target = tryImUserInfo(['name' => $keyword]);
}
if (!$target) {
respond(404, '没有找到该用户');
}
$contact = normalizeUserInfo($target);
if ($contact['uid'] === '') {
respond(404, '没有找到该用户');
}
if ($contact['uid'] === $userId) {
respond(400, '不能添加自己为联系人');
}
$friendResult = requireImSuccess(
imAdminPost('/admin/friend/list', ['userId' => $userId]),
'好友列表检查失败'
);
$friendIds = array_values(array_filter($friendResult['list'] ?? [], 'is_string'));
if (in_array($contact['uid'], $friendIds, true)) {
respond(409, '该用户已经是联系人', ['contact' => $contact]);
}
requireImSuccess(
imAdminPost('/admin/friend/status', [
'userId' => $userId,
'friendUid' => $contact['uid'],
'status' => 0,
]),
'添加联系人失败'
);
requireImSuccess(
imAdminPost('/admin/friend/status', [
'userId' => $contact['uid'],
'friendUid' => $userId,
'status' => 0,
]),
'添加联系人失败'
);
respond(0, 'success', ['contact' => $contact, 'reason' => $reason]);
} catch (Throwable $error) {
respond(500, $error->getMessage() ?: '添加联系人服务暂不可用');
}
+71
View File
@@ -0,0 +1,71 @@
<?php
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');
require __DIR__ . '/im_web_bootstrap.php';
$payload = readJsonPayload();
$userId = trim((string)($payload['userId'] ?? $_GET['userId'] ?? ''));
if ($userId === '') {
respond(400, '缺少用户ID');
}
try {
$friendResult = requireImSuccess(
imAdminPost('/admin/friend/list', ['userId' => $userId]),
'联系人加载失败'
);
$friendIds = array_values(array_unique(array_filter(array_map(static function ($uid): string {
return trim((string)$uid);
}, $friendResult['list'] ?? []))));
if (!$friendIds) {
respond(0, 'success', ['contacts' => []]);
}
$usersResult = requireImSuccess(
imAdminPost('/admin/user/batch_get_infos', ['list' => $friendIds]),
'联系人资料加载失败'
);
try {
ensureWebImAppTables();
$remarkMap = fetchWebUserRemarkMap(imAppDb(), $userId, $friendIds);
} catch (Throwable) {
$remarkMap = [];
}
$contactsByUid = [];
foreach (array_values(array_filter($usersResult['userInfos'] ?? [], 'is_array')) as $user) {
$uid = (string)($user['userId'] ?? '');
if ($uid === '' || isset($contactsByUid[$uid])) {
continue;
}
$alias = '';
try {
$aliasResult = requireImSuccess(
imAdminPost('/admin/friend/get_alias', ['operator' => $userId, 'targetId' => $uid]),
'联系人备注加载失败'
);
$alias = trim((string)($aliasResult['alias'] ?? ''));
} catch (Throwable $error) {
$alias = '';
}
if ($alias === '') {
$alias = $remarkMap[$uid] ?? '';
}
$contactsByUid[$uid] = [
'uid' => $uid,
'name' => (string)($user['name'] ?? $uid),
'displayName' => (string)($user['displayName'] ?? $user['name'] ?? $uid),
'mobile' => (string)($user['mobile'] ?? ''),
'portrait' => (string)($user['portrait'] ?? ''),
'address' => (string)($user['address'] ?? ''),
'alias' => $alias,
];
}
respond(0, 'success', ['contacts' => array_values($contactsByUid)]);
} catch (Throwable $error) {
respond(500, $error->getMessage() ?: '联系人服务暂不可用');
}
File diff suppressed because it is too large Load Diff
+348
View File
@@ -0,0 +1,348 @@
<?php
declare(strict_types=1);
define('IM_ADMIN_URL', getenv('JC_WEB_IM_ADMIN_URL') ?: 'http://127.0.0.1:18080');
define('IM_ADMIN_SECRET', getenv('JC_WEB_IM_ADMIN_SECRET') ?: '123456');
const IM_DB_DSN = 'mysql:host=im-mysql-005.cbgumoq8g1ks.ap-southeast-1.rds.amazonaws.com;port=3306;dbname=zhongliao_wfchat;charset=utf8mb4';
const IM_DB_USER = 'zhongliaoMysql';
const IM_DB_PASSWORD = 'ZhongLiao@admin';
const IM_APP_DB_DSN = 'mysql:host=im-mysql-005.cbgumoq8g1ks.ap-southeast-1.rds.amazonaws.com;port=3306;dbname=zhongliao_app;charset=utf8mb4';
const IM_APP_DB_USER = 'zhongliaoMysql';
const IM_APP_DB_PASSWORD = 'ZhongLiao@admin';
const IM_DB_TIMEZONE = 'Asia/Shanghai';
function respond(int $code, string $message, array $result = []): void
{
echo json_encode([
'code' => $code,
'message' => $message,
'result' => $result,
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
exit;
}
function readJsonPayload(): array
{
$payload = json_decode(file_get_contents('php://input') ?: '[]', true);
return is_array($payload) ? $payload : [];
}
function imAdminPost(string $path, array $payload): array
{
$nonce = (string)random_int(1, 1000000);
$timestamp = (string)((int)floor(microtime(true) * 1000));
$sign = sha1($nonce . '|' . IM_ADMIN_SECRET . '|' . $timestamp);
$body = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$curl = curl_init(IM_ADMIN_URL . $path);
if ($curl === false) {
throw new RuntimeException('IM admin client init failed');
}
curl_setopt_array($curl, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $body,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_0,
CURLOPT_CONNECTTIMEOUT_MS => 1000,
CURLOPT_TIMEOUT_MS => 4000,
CURLOPT_FRESH_CONNECT => true,
CURLOPT_FORBID_REUSE => true,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json; charset=utf-8',
'Connection: close',
'nonce: ' . $nonce,
'timestamp: ' . $timestamp,
'sign: ' . $sign,
],
]);
$responseBody = curl_exec($curl);
$curlError = curl_error($curl);
curl_close($curl);
if ($responseBody === false || $responseBody === '') {
throw new RuntimeException($curlError ?: 'IM admin request failed');
}
$data = json_decode($responseBody, true);
if (!is_array($data)) {
throw new RuntimeException('Invalid IM admin response');
}
return $data;
}
function requireImSuccess(array $response, string $fallbackMessage): array
{
if (($response['code'] ?? -1) !== 0) {
throw new RuntimeException((string)($response['msg'] ?? $response['message'] ?? $fallbackMessage));
}
return is_array($response['result'] ?? null) ? $response['result'] : [];
}
function imDb(): PDO
{
static $pdo = null;
if ($pdo instanceof PDO) {
return $pdo;
}
$pdo = new PDO(IM_DB_DSN, IM_DB_USER, IM_DB_PASSWORD, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]);
return $pdo;
}
function imAppDb(): PDO
{
static $pdo = null;
if ($pdo instanceof PDO) {
return $pdo;
}
$pdo = new PDO(IM_APP_DB_DSN, IM_APP_DB_USER, IM_APP_DB_PASSWORD, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]);
return $pdo;
}
function ensureWebImAppTables(): void
{
static $ensured = false;
if ($ensured) {
return;
}
$ensured = true;
$db = imAppDb();
$db->exec(
"create table if not exists `t_web_groups` (
`id` bigint unsigned not null auto_increment,
`group_id` varchar(64) not null,
`category` varchar(20) not null default 'group',
`name` varchar(128) not null,
`portrait` varchar(1024) not null default '',
`owner_uid` varchar(64) not null,
`join_mode` varchar(20) not null default 'open',
`announcement` text null,
`native_group_id` varchar(64) not null default '',
`native_status` varchar(32) not null default 'pending',
`native_error` varchar(255) not null default '',
`created_by` varchar(64) not null,
`created_at_ms` bigint not null,
`updated_at_ms` bigint not null,
`deleted` tinyint not null default 0,
primary key (`id`),
unique key `uk_t_web_groups_group_id` (`group_id`),
key `idx_t_web_groups_owner` (`owner_uid`),
key `idx_t_web_groups_category` (`category`)
) engine=InnoDB default charset=utf8mb4 collate=utf8mb4_unicode_ci"
);
try {
$db->exec("alter table `t_web_groups` add column `welcome_text` text null after `announcement`");
} catch (Throwable) {
}
$db->exec(
"create table if not exists `t_web_group_members` (
`id` bigint unsigned not null auto_increment,
`group_id` varchar(64) not null,
`user_id` varchar(64) not null,
`role` varchar(20) not null default 'member',
`alias` varchar(128) not null default '',
`joined_at_ms` bigint not null,
`updated_at_ms` bigint not null,
`status` tinyint not null default 0,
primary key (`id`),
unique key `uk_t_web_group_members_gid_uid` (`group_id`, `user_id`),
key `idx_t_web_group_members_user` (`user_id`)
) engine=InnoDB default charset=utf8mb4 collate=utf8mb4_unicode_ci"
);
$db->exec(
"create table if not exists `t_web_group_messages` (
`id` bigint unsigned not null auto_increment,
`message_uid` varchar(64) not null,
`group_id` varchar(64) not null,
`sender_uid` varchar(64) not null,
`text` text not null,
`created_at_ms` bigint not null,
`edited_at_ms` bigint not null default 0,
`recalled` tinyint not null default 0,
primary key (`id`),
unique key `uk_t_web_group_messages_uid` (`message_uid`),
key `idx_t_web_group_messages_group_time` (`group_id`, `created_at_ms`),
key `idx_t_web_group_messages_sender` (`sender_uid`)
) engine=InnoDB default charset=utf8mb4 collate=utf8mb4_unicode_ci"
);
$db->exec(
"create table if not exists `t_web_message_attachments` (
`id` bigint unsigned not null auto_increment,
`message_uid` varchar(64) not null,
`conversation_type` varchar(16) not null default 'single',
`target_id` varchar(128) not null default '',
`sender_uid` varchar(64) not null default '',
`attachment_type` varchar(16) not null,
`url` varchar(1024) not null,
`name` varchar(255) not null default '',
`mime` varchar(128) not null default '',
`size_bytes` bigint not null default 0,
`created_at_ms` bigint not null,
primary key (`id`),
unique key `uk_t_web_message_attachments_uid` (`message_uid`),
key `idx_t_web_message_attachments_target` (`conversation_type`, `target_id`, `created_at_ms`)
) engine=InnoDB default charset=utf8mb4 collate=utf8mb4_unicode_ci"
);
$db->exec(
"create table if not exists `t_web_group_reads` (
`id` bigint unsigned not null auto_increment,
`group_id` varchar(64) not null,
`user_id` varchar(64) not null,
`read_at_ms` bigint not null default 0,
`updated_at_ms` bigint not null,
primary key (`id`),
unique key `uk_t_web_group_reads_gid_uid` (`group_id`, `user_id`)
) engine=InnoDB default charset=utf8mb4 collate=utf8mb4_unicode_ci"
);
$db->exec(
"create table if not exists `t_web_group_mute_rules` (
`id` bigint unsigned not null auto_increment,
`group_id` varchar(64) not null,
`mode` varchar(32) not null default 'off',
`schedule_type` varchar(16) not null default 'once',
`starts_at_ms` bigint not null default 0,
`ends_at_ms` bigint not null default 0,
`daily_start` varchar(8) not null default '',
`daily_end` varchar(8) not null default '',
`enabled` tinyint not null default 0,
`created_by` varchar(64) not null default '',
`updated_at_ms` bigint not null,
primary key (`id`),
unique key `uk_t_web_group_mute_rules_group` (`group_id`)
) engine=InnoDB default charset=utf8mb4 collate=utf8mb4_unicode_ci"
);
$db->exec(
"create table if not exists `t_web_broadcast_logs` (
`id` bigint unsigned not null auto_increment,
`sender_uid` varchar(64) not null,
`target_count` int not null default 0,
`success_count` int not null default 0,
`failed_count` int not null default 0,
`text` text not null,
`target_json` text null,
`result_json` text null,
`created_at_ms` bigint not null,
primary key (`id`),
key `idx_t_web_broadcast_logs_sender_time` (`sender_uid`, `created_at_ms`)
) engine=InnoDB default charset=utf8mb4 collate=utf8mb4_unicode_ci"
);
$db->exec(
"create table if not exists `t_web_user_remarks` (
`id` bigint unsigned not null auto_increment,
`owner_uid` varchar(64) not null,
`target_uid` varchar(64) not null,
`alias` varchar(128) not null default '',
`created_at_ms` bigint not null,
`updated_at_ms` bigint not null,
primary key (`id`),
unique key `uk_t_web_user_remarks_owner_target` (`owner_uid`, `target_uid`),
key `idx_t_web_user_remarks_target` (`target_uid`)
) engine=InnoDB default charset=utf8mb4 collate=utf8mb4_unicode_ci"
);
}
function webImPlaceholders(array $values): string
{
return implode(',', array_fill(0, count($values), '?'));
}
function fetchWebUserRemarkMap(PDO $db, string $ownerId, array $targetIds): array
{
$targetIds = array_values(array_unique(array_filter(array_map(static function ($targetId): string {
return trim((string)$targetId);
}, $targetIds))));
if ($ownerId === '' || !$targetIds) {
return [];
}
$statement = $db->prepare(
'select `target_uid`, `alias` from `t_web_user_remarks`'
. ' where `owner_uid` = ? and `target_uid` in (' . webImPlaceholders($targetIds) . ')'
);
$statement->execute(array_merge([$ownerId], $targetIds));
$remarks = [];
foreach ($statement->fetchAll() as $row) {
$remarks[(string)$row['target_uid']] = trim((string)($row['alias'] ?? ''));
}
return $remarks;
}
function saveWebUserRemark(PDO $db, string $ownerId, string $targetId, string $alias): void
{
if ($ownerId === '' || $targetId === '') {
return;
}
if ($alias === '') {
$delete = $db->prepare('delete from `t_web_user_remarks` where `owner_uid` = ? and `target_uid` = ?');
$delete->execute([$ownerId, $targetId]);
return;
}
$now = webImNowMs();
$statement = $db->prepare(
'insert into `t_web_user_remarks` (`owner_uid`, `target_uid`, `alias`, `created_at_ms`, `updated_at_ms`)'
. ' values (?, ?, ?, ?, ?)'
. ' on duplicate key update `alias` = values(`alias`), `updated_at_ms` = values(`updated_at_ms`)'
);
$statement->execute([$ownerId, $targetId, $alias, $now, $now]);
}
function webImNowMs(): int
{
return (int)floor(microtime(true) * 1000);
}
function webImMessageUid(): string
{
$timestampPart = (webImNowMs() - 1514736000000) << 21;
return (string)($timestampPart | random_int(1, 0x1FFFFF));
}
function javaStringHashCode(string $value): int
{
$hash = 0;
$length = strlen($value);
for ($i = 0; $i < $length; $i++) {
$hash = (31 * $hash + ord($value[$i])) & 0xFFFFFFFF;
if ($hash >= 0x80000000) {
$hash -= 0x100000000;
}
}
return $hash;
}
function imUserMessagesTable(string $userId): string
{
return 't_user_messages_' . (abs(javaStringHashCode($userId)) % 128);
}
function imMessageTable(string $messageId): string
{
$timestamp = ((int)$messageId >> 21) + 1514736000000;
$date = (new DateTimeImmutable('@' . (int)floor($timestamp / 1000)))
->setTimezone(new DateTimeZone(IM_DB_TIMEZONE));
$year = (int)$date->format('Y');
$month = (int)$date->format('n') - 1;
return 't_messages_' . (($year % 3) * 12 + $month);
}
+58
View File
@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
const WEB_MEDIA_ROOT = '/opt/im-server/media';
function failDownload(int $status, string $message): never
{
http_response_code($status);
header('Content-Type: text/plain; charset=utf-8');
echo $message;
exit;
}
function safeDownloadName(string $fileName, string $fallback): string
{
$name = basename(str_replace('\\', '/', $fileName));
$name = preg_replace('/[^\p{L}\p{N}._ -]+/u', '_', $name) ?: '';
$name = trim($name, " .\t\n\r\0\x0B");
if ($name === '') {
$name = $fallback;
}
return mb_substr($name, 0, 180, 'UTF-8');
}
$url = trim((string)($_GET['url'] ?? ''));
$requestedName = trim((string)($_GET['name'] ?? ''));
if ($url === '') {
failDownload(400, '缺少媒体地址');
}
$path = (string)(parse_url($url, PHP_URL_PATH) ?: $url);
$path = rawurldecode($path);
if (!preg_match('#^/fs/[0-9]+/[A-Za-z0-9_./ -]+$#', $path) || str_contains($path, '..')) {
failDownload(400, '媒体地址不合法');
}
$root = realpath(WEB_MEDIA_ROOT);
$fullPath = realpath(rtrim(WEB_MEDIA_ROOT, '/') . $path);
if ($root === false || $fullPath === false || !str_starts_with($fullPath, $root . DIRECTORY_SEPARATOR) || !is_file($fullPath)) {
failDownload(404, '媒体文件不存在');
}
$fallbackName = basename($fullPath);
$downloadName = safeDownloadName($requestedName, $fallbackName);
if (!pathinfo($downloadName, PATHINFO_EXTENSION)) {
$downloadName .= '.' . (pathinfo($fallbackName, PATHINFO_EXTENSION) ?: 'jpg');
}
$mime = mime_content_type($fullPath) ?: 'application/octet-stream';
header('Content-Type: ' . $mime);
header('Content-Length: ' . (string)filesize($fullPath));
header(
'Content-Disposition: attachment; filename="' . addcslashes($downloadName, "\\\"") . '"; filename*=UTF-8\'\''
. rawurlencode($downloadName)
);
header('Cache-Control: no-store');
readfile($fullPath);
+252
View File
@@ -0,0 +1,252 @@
<?php
declare(strict_types=1);
require __DIR__ . '/im_web_bootstrap.php';
const WEB_MEDIA_PROXY_MAX_BYTES = 15 * 1024 * 1024;
const WEB_MEDIA_PROXY_MAX_SECONDS = 25;
function mediaProxyEnv(string $name, string $default = ''): string
{
if (function_exists('webImEnv')) {
return (string)webImEnv($name, $default);
}
$value = getenv($name);
if ($value === false || trim((string)$value) === '') {
return $default;
}
return trim((string)$value);
}
function failMediaProxy(int $status, string $message): never
{
http_response_code($status);
header('Content-Type: text/plain; charset=utf-8');
header('Cache-Control: no-store');
header('X-Content-Type-Options: nosniff');
echo $message;
exit;
}
function mediaProxyAllowedHosts(): array
{
$configured = mediaProxyEnv('JC_WEB_IM_MEDIA_PROXY_HOSTS');
$hosts = array_map(
static fn(string $host): string => strtolower(rtrim(trim($host), '.')),
preg_split('/[,\s]+/', $configured) ?: []
);
$hosts[] = 'zhiyanim.dfpnm.cn';
return array_values(array_unique(array_filter($hosts)));
}
function validatedMediaProxyUrl(string $url): array
{
if ($url === '' || strlen($url) > 2048 || filter_var($url, FILTER_VALIDATE_URL) === false) {
failMediaProxy(400, '媒体地址不合法');
}
$parts = parse_url($url);
$scheme = strtolower((string)($parts['scheme'] ?? ''));
$host = strtolower(rtrim((string)($parts['host'] ?? ''), '.'));
$port = isset($parts['port']) ? (int)$parts['port'] : 443;
if (
$scheme !== 'https'
|| $host === ''
|| $port !== 443
|| isset($parts['user'])
|| isset($parts['pass'])
|| !in_array($host, mediaProxyAllowedHosts(), true)
) {
failMediaProxy(403, '媒体来源不允许代理');
}
return [$url, $host];
}
function mediaProxyCacheRoot(): string
{
$root = rtrim(mediaProxyEnv('JC_WEB_IM_MEDIA_CACHE_ROOT', '/var/cache/jc-web-im-media'), '/');
if ($root === '' || !is_dir($root) || !is_writable($root)) {
$root = rtrim(sys_get_temp_dir(), '/') . '/jc-web-im-media';
if (!is_dir($root) && !@mkdir($root, 0755, true) && !is_dir($root)) {
failMediaProxy(503, '媒体缓存目录不可用');
}
}
return $root;
}
function mediaProxyPreferredIps(): array
{
$configured = preg_split('/[,\s]+/', mediaProxyEnv('JC_WEB_IM_MEDIA_PROXY_IPS')) ?: [];
$ips = [];
foreach ($configured as $ip) {
$ip = trim($ip);
if (
$ip !== ''
&& filter_var(
$ip,
FILTER_VALIDATE_IP,
FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE
) !== false
) {
$ips[$ip] = $ip;
}
}
return array_values($ips);
}
function mediaProxyMime(string $path): string
{
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = $finfo !== false ? (string)(finfo_file($finfo, $path) ?: '') : '';
if ($finfo !== false) {
finfo_close($finfo);
}
return $mime;
}
function fetchMediaProxyImage(string $url, string $host, string $cacheFile): void
{
$deadline = microtime(true) + WEB_MEDIA_PROXY_MAX_SECONDS;
$lastError = '媒体源无响应';
$preferredIps = mediaProxyPreferredIps();
$targets = array_merge($preferredIps, array_fill(0, max(2, 6 - count($preferredIps)), null));
foreach ($targets as $index => $preferredIp) {
if (microtime(true) >= $deadline) {
break;
}
$attempt = $index + 1;
$temporaryFile = $cacheFile . '.tmp.' . getmypid() . '.' . $attempt;
$stream = @fopen($temporaryFile, 'x+b');
if ($stream === false) {
$lastError = '无法创建媒体缓存文件';
break;
}
$bytes = 0;
$tooLarge = false;
$curl = curl_init($url);
if ($curl === false) {
fclose($stream);
@unlink($temporaryFile);
$lastError = '无法初始化媒体请求';
break;
}
$remainingMs = max(1000, (int)floor(($deadline - microtime(true)) * 1000));
$curlOptions = [
CURLOPT_RETURNTRANSFER => false,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_CONNECTTIMEOUT_MS => min(2500, $remainingMs),
CURLOPT_TIMEOUT_MS => min(12000, $remainingMs),
CURLOPT_NOSIGNAL => true,
CURLOPT_DNS_CACHE_TIMEOUT => 0,
CURLOPT_FRESH_CONNECT => true,
CURLOPT_FORBID_REUSE => true,
CURLOPT_PROTOCOLS => CURLPROTO_HTTPS,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_USERAGENT => 'JC-Web-IM-Media-Proxy/1.0',
CURLOPT_HTTPHEADER => ['Accept: image/avif,image/webp,image/*,*/*;q=0.8'],
CURLOPT_WRITEFUNCTION => static function ($handle, string $chunk) use ($stream, &$bytes, &$tooLarge): int {
$length = strlen($chunk);
if ($bytes + $length > WEB_MEDIA_PROXY_MAX_BYTES) {
$tooLarge = true;
return 0;
}
$written = fwrite($stream, $chunk);
if ($written === false) {
return 0;
}
$bytes += $written;
return $written;
},
];
if (is_string($preferredIp) && $preferredIp !== '') {
$curlOptions[CURLOPT_RESOLVE] = [$host . ':443:' . $preferredIp];
}
curl_setopt_array($curl, $curlOptions);
$result = curl_exec($curl);
$status = (int)curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
$curlError = curl_error($curl);
curl_close($curl);
fflush($stream);
fclose($stream);
$mime = $bytes > 0 && is_file($temporaryFile) ? mediaProxyMime($temporaryFile) : '';
if ($result !== false && $status >= 200 && $status < 300 && !$tooLarge && str_starts_with($mime, 'image/')) {
if (!@rename($temporaryFile, $cacheFile)) {
@unlink($temporaryFile);
$lastError = '媒体缓存保存失败';
break;
}
@chmod($cacheFile, 0644);
return;
}
@unlink($temporaryFile);
$lastError = $tooLarge
? '图片超过代理大小限制'
: ($curlError !== '' ? $curlError : ($status > 0 ? '媒体源返回 HTTP ' . $status : '媒体源无响应'));
if ($attempt < count($targets) && microtime(true) < $deadline) {
usleep(150000);
}
}
error_log(sprintf('media_proxy fetch failed host=%s error=%s', $host, $lastError));
failMediaProxy(502, '图片源暂时不可用,请稍后重试');
}
function serveMediaProxyImage(string $cacheFile, string $etag): never
{
if (!is_file($cacheFile)) {
failMediaProxy(404, '媒体缓存不存在');
}
$mime = mediaProxyMime($cacheFile);
if (!str_starts_with($mime, 'image/')) {
failMediaProxy(415, '媒体内容不是图片');
}
header('ETag: "' . $etag . '"');
header('Cache-Control: public, max-age=86400, immutable');
header('Content-Type: ' . $mime);
header('Content-Length: ' . (string)filesize($cacheFile));
header('Content-Disposition: inline');
header('X-Content-Type-Options: nosniff');
if (trim((string)($_SERVER['HTTP_IF_NONE_MATCH'] ?? ''), ' W/') === '"' . $etag . '"') {
http_response_code(304);
exit;
}
readfile($cacheFile);
exit;
}
[$url, $host] = validatedMediaProxyUrl(trim((string)($_GET['url'] ?? '')));
$cacheRoot = mediaProxyCacheRoot();
$cacheKey = hash('sha256', $url);
$cacheFile = $cacheRoot . '/' . $cacheKey . '.image';
$lockFile = $cacheRoot . '/' . $cacheKey . '.lock';
if (!is_file($cacheFile)) {
$lock = @fopen($lockFile, 'c');
if ($lock === false || !flock($lock, LOCK_EX)) {
if (is_resource($lock)) {
fclose($lock);
}
failMediaProxy(503, '媒体缓存暂时忙碌');
}
if (!is_file($cacheFile)) {
fetchMediaProxyImage($url, $host, $cacheFile);
}
flock($lock, LOCK_UN);
fclose($lock);
}
serveMediaProxyImage($cacheFile, $cacheKey);
+71
View File
@@ -0,0 +1,71 @@
<?php
declare(strict_types=1);
const WEB_MEDIA_STREAM_ROOT = '/opt/im-server/media';
function failMediaStream(int $status, string $message): never
{
http_response_code($status);
header('Content-Type: text/plain; charset=utf-8');
header('Cache-Control: no-store');
echo $message;
exit;
}
$url = trim((string)($_GET['url'] ?? ''));
if ($url === '') {
failMediaStream(400, '缺少视频地址');
}
$path = rawurldecode((string)(parse_url($url, PHP_URL_PATH) ?: ''));
if (!preg_match('#^/fs/[0-9]+/[A-Za-z0-9_./ -]+$#', $path) || str_contains($path, '..')) {
failMediaStream(400, '视频地址不合法');
}
$root = realpath(WEB_MEDIA_STREAM_ROOT);
$fullPath = realpath(rtrim(WEB_MEDIA_STREAM_ROOT, '/') . $path);
if ($root === false || $fullPath === false || !str_starts_with($fullPath, $root . DIRECTORY_SEPARATOR) || !is_file($fullPath)) {
failMediaStream(404, '视频文件不存在');
}
$size = (int)filesize($fullPath);
$mime = (string)(mime_content_type($fullPath) ?: 'video/mp4');
if (!str_starts_with($mime, 'video/')) {
$extension = strtolower((string)pathinfo($fullPath, PATHINFO_EXTENSION));
$mime = $extension === 'webm' ? 'video/webm' : ($extension === 'mov' ? 'video/quicktime' : 'video/mp4');
}
$start = 0;
$end = max(0, $size - 1);
$range = trim((string)($_SERVER['HTTP_RANGE'] ?? ''));
if ($range !== '' && preg_match('/^bytes=(\d*)-(\d*)$/', $range, $matches)) {
if ($matches[1] !== '') $start = (int)$matches[1];
if ($matches[2] !== '') $end = min($end, (int)$matches[2]);
if ($start < 0 || $start > $end || $start >= $size) {
header('Content-Range: bytes */' . $size);
failMediaStream(416, '请求范围无效');
}
http_response_code(206);
header('Content-Range: bytes ' . $start . '-' . $end . '/' . $size);
}
$length = $end - $start + 1;
header('Content-Type: ' . $mime);
header('Content-Length: ' . $length);
header('Accept-Ranges: bytes');
header('Content-Disposition: inline');
header('Cache-Control: public, max-age=86400');
header('X-Content-Type-Options: nosniff');
$stream = fopen($fullPath, 'rb');
if ($stream === false) failMediaStream(500, '视频文件无法读取');
fseek($stream, $start);
$remaining = $length;
while ($remaining > 0 && !feof($stream)) {
$chunk = fread($stream, min(1024 * 1024, $remaining));
if ($chunk === false || $chunk === '') break;
echo $chunk;
$remaining -= strlen($chunk);
flush();
}
fclose($stream);
+351
View File
@@ -0,0 +1,351 @@
<?php
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');
require __DIR__ . '/im_web_bootstrap.php';
class UserActionException extends RuntimeException
{
}
function resolveActionUserId(string $value): string
{
if ($value === '') {
return '';
}
$db = imDb();
$statement = $db->prepare(
'select `_uid` from `t_user` where `_uid` = ? or `_mobile` = ? or `_name` = ? limit 1'
);
$statement->execute([$value, $value, $value]);
$uid = $statement->fetchColumn();
return is_string($uid) && $uid !== '' ? $uid : $value;
}
function messageTimestampMs(string $messageUid): int
{
return (((int)$messageUid) >> 21) + 1514736000000;
}
function nowTimestampMs(): int
{
return (int)floor(microtime(true) * 1000);
}
function recallLimitMinutes(): float
{
$statement = imAppDb()->prepare(
'select `conf_value` from `system_conf`'
. ' where `conf_name` = ? and `is_valid` = 1 limit 1'
);
$statement->execute(['RetractMessage']);
$value = trim((string)($statement->fetchColumn() ?: '0'));
if ($value === '' || !is_numeric($value)) {
return 0.0;
}
return max(0.0, (float)$value);
}
function assertRecallWithinLimit(string $messageUid): void
{
$limitMinutes = recallLimitMinutes();
if ($limitMinutes <= 0) {
return;
}
$messageAgeMs = nowTimestampMs() - messageTimestampMs($messageUid);
$limitMs = (int)round($limitMinutes * 60 * 1000);
if ($messageAgeMs > $limitMs) {
throw new UserActionException('已超过可撤回时间');
}
}
function fetchActionMessageRow(string $messageUid): array
{
$table = imMessageTable($messageUid);
$statement = imDb()->prepare(
'select `_mid`, `_from`, `_content_type`, `_searchable_key` from `' . $table . '` where `_mid` = ? limit 1'
);
$statement->execute([$messageUid]);
$row = $statement->fetch();
return is_array($row) ? $row : [];
}
function ensureMessageEditsTable(): void
{
imDb()->exec(
'create table if not exists `t_web_message_edits` ('
. '`message_uid` varchar(32) not null,'
. '`editor_uid` varchar(64) not null,'
. '`edited_text` text null,'
. '`edited_at_ms` bigint not null,'
. '`created_at` datetime not null default current_timestamp,'
. '`updated_at` datetime null default current_timestamp on update current_timestamp,'
. 'primary key (`message_uid`),'
. 'key `idx_editor_uid` (`editor_uid`),'
. 'key `idx_edited_at_ms` (`edited_at_ms`)'
. ') engine=InnoDB default charset=utf8mb4'
);
}
function ensurePinnedMessagesTable(): void
{
$db = imAppDb();
$db->exec(
'create table if not exists `t_web_pinned_messages` ('
. '`user_id` varchar(64) not null,'
. '`conversation_type` varchar(16) not null,'
. '`target_id` varchar(128) not null,'
. '`message_uid` varchar(32) not null,'
. '`message_json` text null,'
. '`updated_at_ms` bigint not null,'
. 'primary key (`user_id`, `conversation_type`, `target_id`)'
. ') engine=InnoDB default charset=utf8mb4'
);
try {
$db->exec('alter table `t_web_pinned_messages` add column `message_json` text null after `message_uid`');
} catch (Throwable) {
// The column already exists.
}
}
function savePinnedMessage(string $userId, string $conversationType, string $targetId, string $messageUid, array $message): void
{
ensurePinnedMessagesTable();
$statement = imAppDb()->prepare(
'insert into `t_web_pinned_messages` (`user_id`, `conversation_type`, `target_id`, `message_uid`, `message_json`, `updated_at_ms`)'
. ' values (?, ?, ?, ?, ?, ?) on duplicate key update `message_uid` = values(`message_uid`),'
. ' `message_json` = values(`message_json`), `updated_at_ms` = values(`updated_at_ms`)'
);
$statement->execute([
$userId,
$conversationType,
$targetId,
$messageUid,
json_encode($message, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
nowTimestampMs(),
]);
}
function removePinnedMessage(string $userId, string $conversationType, string $targetId): void
{
ensurePinnedMessagesTable();
$statement = imAppDb()->prepare(
'delete from `t_web_pinned_messages` where `user_id` = ? and `conversation_type` = ? and `target_id` = ?'
);
$statement->execute([$userId, $conversationType, $targetId]);
}
function editTextMessage(string $operatorId, string $messageUid, string $text): array
{
$row = fetchActionMessageRow($messageUid);
if (!$row) {
return editWebGroupMessage($operatorId, $messageUid, $text);
}
if ((string)$row['_from'] !== $operatorId) {
throw new UserActionException('只能编辑自己发送的消息');
}
if ((int)$row['_content_type'] !== 1) {
throw new UserActionException('只能编辑文字消息');
}
$editedAt = nowTimestampMs();
$table = imMessageTable($messageUid);
$update = imDb()->prepare('update `' . $table . '` set `_searchable_key` = ? where `_mid` = ?');
$update->execute([$text, $messageUid]);
ensureMessageEditsTable();
$upsert = imDb()->prepare(
'insert into `t_web_message_edits` (`message_uid`, `editor_uid`, `edited_text`, `edited_at_ms`)'
. ' values (?, ?, ?, ?)'
. ' on duplicate key update'
. ' `editor_uid` = values(`editor_uid`),'
. ' `edited_text` = values(`edited_text`),'
. ' `edited_at_ms` = values(`edited_at_ms`),'
. ' `updated_at` = current_timestamp'
);
$upsert->execute([$messageUid, $operatorId, $text, $editedAt]);
return [
'messageUid' => $messageUid,
'text' => $text,
'editedAt' => $editedAt,
];
}
function fetchWebGroupActionMessage(string $messageUid): array
{
ensureWebImAppTables();
$statement = imAppDb()->prepare(
'select m.*, g.`category` from `t_web_group_messages` m'
. ' join `t_web_groups` g on g.`group_id` = m.`group_id` and g.`deleted` = 0'
. ' where m.`message_uid` = ? limit 1'
);
$statement->execute([$messageUid]);
$row = $statement->fetch();
return is_array($row) ? $row : [];
}
function editWebGroupMessage(string $operatorId, string $messageUid, string $text): array
{
$row = fetchWebGroupActionMessage($messageUid);
if (!$row) {
throw new UserActionException('消息不存在');
}
if ((string)$row['sender_uid'] !== $operatorId) {
throw new UserActionException('只能编辑自己发送的消息');
}
if ((int)($row['recalled'] ?? 0) !== 0) {
throw new UserActionException('已撤回的消息请重新编辑发送');
}
$editedAt = nowTimestampMs();
$update = imAppDb()->prepare(
'update `t_web_group_messages` set `text` = ?, `edited_at_ms` = ? where `message_uid` = ?'
);
$update->execute([$text, $editedAt, $messageUid]);
$groupUpdate = imAppDb()->prepare('update `t_web_groups` set `updated_at_ms` = ? where `group_id` = ?');
$groupUpdate->execute([$editedAt, (string)$row['group_id']]);
return [
'messageUid' => $messageUid,
'text' => $text,
'editedAt' => $editedAt,
];
}
function webGroupMemberRoleForAction(string $groupId, string $userId): string
{
$statement = imAppDb()->prepare(
'select `role` from `t_web_group_members`'
. ' where `group_id` = ? and `user_id` = ? and `status` = 0 limit 1'
);
$statement->execute([$groupId, $userId]);
$role = $statement->fetchColumn();
return is_string($role) ? $role : '';
}
function recallWebGroupMessage(string $operatorId, string $messageUid): bool
{
$row = fetchWebGroupActionMessage($messageUid);
if (!$row) {
return false;
}
$isSender = (string)$row['sender_uid'] === $operatorId;
if (!$isSender) {
$role = webGroupMemberRoleForAction((string)$row['group_id'], $operatorId);
if (!in_array($role, ['owner', 'admin'], true)) {
throw new UserActionException('只有群主或管理员可以撤回他人消息');
}
}
assertRecallWithinLimit($messageUid);
$now = nowTimestampMs();
$update = imAppDb()->prepare(
'update `t_web_group_messages` set `recalled` = 1 where `message_uid` = ?'
);
$update->execute([$messageUid]);
$groupUpdate = imAppDb()->prepare('update `t_web_groups` set `updated_at_ms` = ? where `group_id` = ?');
$groupUpdate->execute([$now, (string)$row['group_id']]);
return true;
}
$payload = readJsonPayload();
$action = trim((string)($payload['action'] ?? ''));
$userId = trim((string)($payload['userId'] ?? ''));
$messageUidText = trim((string)($payload['messageUid'] ?? ''));
$messageUid = ctype_digit($messageUidText) ? (int)$messageUidText : 0;
if ($action === '' || $messageUid <= 0) {
respond(400, '缺少操作类型或消息ID');
}
try {
if ($action === 'pin' || $action === 'unpin') {
if ($userId === '') respond(400, '缺少操作者ID');
$targetId = trim((string)($payload['target'] ?? ''));
$conversationType = trim((string)($payload['conversationType'] ?? 'single'));
if ($targetId === '') respond(400, '缺少会话ID');
$userId = resolveActionUserId($userId);
if ($action === 'pin') {
$message = is_array($payload['message'] ?? null) ? $payload['message'] : [];
savePinnedMessage($userId, $conversationType, $targetId, $messageUidText, $message);
} else {
removePinnedMessage($userId, $conversationType, $targetId);
}
respond(0, 'success', ['messageUid' => $messageUidText, 'action' => $action]);
}
if ($action === 'recall') {
if ($userId === '') {
respond(400, '缺少操作者ID');
}
$userId = resolveActionUserId($userId);
$row = fetchActionMessageRow($messageUidText);
if (!$row && recallWebGroupMessage($userId, $messageUidText)) {
respond(0, 'success', [
'messageUid' => (string)$messageUid,
'action' => $action,
]);
}
if (!$row) {
throw new UserActionException('消息不存在');
}
assertRecallWithinLimit($messageUidText);
requireImSuccess(imAdminPost('/admin/message/recall', [
'operator' => $userId,
'messageUid' => $messageUid,
'userRecall' => true,
'isUserRecall' => true,
]), '撤回失败');
respond(0, 'success', [
'messageUid' => (string)$messageUid,
'action' => $action,
]);
}
if ($action === 'edit') {
if ($userId === '') {
respond(400, '缺少操作者ID');
}
$text = trim((string)($payload['text'] ?? ''));
if ($text === '') {
respond(400, '编辑内容不能为空');
}
if (mb_strlen($text, 'UTF-8') > 5000) {
respond(400, '编辑内容过长');
}
$userId = resolveActionUserId($userId);
respond(0, 'success', [
'message' => editTextMessage($userId, $messageUidText, $text),
'action' => $action,
]);
}
if ($action === 'delete') {
requireImSuccess(imAdminPost('/admin/message/delete', [
'messageUid' => $messageUid,
]), '删除失败');
respond(0, 'success', [
'messageUid' => (string)$messageUid,
'action' => $action,
]);
}
respond(400, '不支持的消息操作');
} catch (Throwable $error) {
respond($error instanceof UserActionException ? 400 : 500, $error->getMessage() ?: '消息操作失败');
}
+387
View File
@@ -0,0 +1,387 @@
<?php
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');
require __DIR__ . '/im_web_bootstrap.php';
function detailPlaceholders(array $values): string
{
return implode(',', array_fill(0, count($values), '?'));
}
function detailTimestampMs(?string $datetime, string $messageId = '0'): int
{
$id = (int)$messageId;
if ($id > 0) {
return ($id >> 21) + 1514736000000;
}
if ($datetime !== null && $datetime !== '') {
$date = DateTimeImmutable::createFromFormat(
'Y-m-d H:i:s',
$datetime,
new DateTimeZone(IM_DB_TIMEZONE)
);
if ($date instanceof DateTimeImmutable) {
return $date->getTimestamp() * 1000;
}
}
return 0;
}
function detailResolveUserId(PDO $db, string $value): string
{
if ($value === '') {
return '';
}
$statement = $db->prepare(
'select `_uid` from `t_user` where `_uid` = ? or `_mobile` = ? or `_name` = ? limit 1'
);
$statement->execute([$value, $value, $value]);
$uid = $statement->fetchColumn();
return is_string($uid) && $uid !== '' ? $uid : $value;
}
function detailConversationType(mixed $value): string
{
$type = strtolower(trim((string)$value));
return in_array($type, ['1', 'group', 'channel'], true) ? 'group' : 'single';
}
function detailDeliveryMap(PDO $db, array $userIds): array
{
$userIds = array_values(array_unique(array_filter(array_map('strval', $userIds))));
if (!$userIds) {
return [];
}
$statement = $db->prepare(
'select `_uid`, max(`_dt`) as `_dt` from `t_delivery_report`'
. ' where `_uid` in (' . detailPlaceholders($userIds) . ') group by `_uid`'
);
$statement->execute($userIds);
$items = [];
foreach ($statement->fetchAll() as $row) {
$items[(string)$row['_uid']] = (int)$row['_dt'];
}
return $items;
}
function detailReadAt(PDO $db, string $readerId, array $targets): int
{
$targets = array_values(array_unique(array_filter(array_map('strval', $targets))));
if ($readerId === '' || !$targets) {
return 0;
}
$statement = $db->prepare(
'select max(`_dt`) from `t_read_report`'
. ' where `_uid` = ? and `_type` = 0 and `_line` = 0'
. ' and `_target` in (' . detailPlaceholders($targets) . ')'
);
$statement->execute(array_merge([$readerId], $targets));
$value = $statement->fetchColumn();
return is_numeric($value) ? (int)$value : 0;
}
function detailSingleMessageVisible(PDO $db, string $userId, string $targetId, string $messageUid): bool
{
$table = imUserMessagesTable($userId);
$conversationKeys = [$userId . '|' . $targetId, $targetId . '|' . $userId];
$statement = $db->prepare(
'select 1 from `' . $table . '`'
. ' where `_uid` = ? and `_mid` = ? and `_type` = 0 and `_line` = 0'
. ' and `_target` in (' . detailPlaceholders($conversationKeys) . ') limit 1'
);
$statement->execute(array_merge([$userId, $messageUid], $conversationKeys));
return (bool)$statement->fetchColumn();
}
function detailUserMap(PDO $imDb, PDO $appDb, array $userIds, string $ownerId, string $groupId = ''): array
{
$userIds = array_values(array_unique(array_filter(array_map('strval', $userIds))));
if (!$userIds) {
return [];
}
$statement = $imDb->prepare(
'select `_uid`, `_name`, `_display_name`, `_mobile`, `_portrait` from `t_user`'
. ' where `_uid` in (' . detailPlaceholders($userIds) . ')'
);
$statement->execute($userIds);
$users = [];
foreach ($statement->fetchAll() as $row) {
$uid = (string)$row['_uid'];
$rawName = trim((string)($row['_display_name'] ?? ''))
?: trim((string)($row['_name'] ?? ''))
?: trim((string)($row['_mobile'] ?? ''))
?: $uid;
$users[$uid] = [
'uid' => $uid,
'rawName' => $rawName,
'mobile' => (string)($row['_mobile'] ?? ''),
'portrait' => (string)($row['_portrait'] ?? ''),
'contactAlias' => '',
'remarkAlias' => '',
'groupAlias' => '',
'role' => '',
'displayName' => $rawName,
];
}
if ($ownerId !== '') {
$aliasStatement = $imDb->prepare(
'select `_friend_uid`, `_alias` from `t_friend` where `_uid` = ?'
. ' and `_friend_uid` in (' . detailPlaceholders($userIds) . ')'
);
$aliasStatement->execute(array_merge([$ownerId], $userIds));
foreach ($aliasStatement->fetchAll() as $row) {
$uid = (string)$row['_friend_uid'];
if (isset($users[$uid])) {
$users[$uid]['contactAlias'] = trim((string)($row['_alias'] ?? ''));
}
}
try {
$remarkMap = fetchWebUserRemarkMap($appDb, $ownerId, $userIds);
} catch (Throwable) {
$remarkMap = [];
}
foreach ($remarkMap as $uid => $alias) {
if (isset($users[$uid])) {
$users[$uid]['remarkAlias'] = trim((string)$alias);
}
}
}
if ($groupId !== '') {
$memberStatement = $appDb->prepare(
'select `user_id`, `alias`, `role` from `t_web_group_members`'
. ' where `group_id` = ? and `user_id` in (' . detailPlaceholders($userIds) . ')'
);
$memberStatement->execute(array_merge([$groupId], $userIds));
foreach ($memberStatement->fetchAll() as $row) {
$uid = (string)$row['user_id'];
if (isset($users[$uid])) {
$users[$uid]['groupAlias'] = trim((string)($row['alias'] ?? ''));
$users[$uid]['role'] = (string)($row['role'] ?? '');
}
}
}
foreach ($users as $uid => $user) {
$alias = (string)$user['contactAlias'] !== ''
? (string)$user['contactAlias']
: ((string)$user['remarkAlias'] !== '' ? (string)$user['remarkAlias'] : (string)$user['groupAlias']);
$users[$uid]['displayName'] = $alias !== '' ? $alias : (string)$user['rawName'];
}
foreach ($userIds as $uid) {
if (!isset($users[$uid])) {
$users[$uid] = [
'uid' => $uid,
'rawName' => $uid,
'mobile' => '',
'portrait' => '',
'contactAlias' => '',
'remarkAlias' => '',
'groupAlias' => '',
'role' => '',
'displayName' => $uid,
];
}
}
return $users;
}
function detailMember(array $user, int $time = 0): array
{
return [
'uid' => (string)$user['uid'],
'name' => (string)$user['displayName'],
'rawName' => (string)$user['rawName'],
'mobile' => (string)($user['mobile'] ?? ''),
'portrait' => (string)($user['portrait'] ?? ''),
'role' => (string)($user['role'] ?? ''),
'time' => $time,
];
}
function singleDetail(PDO $imDb, string $userId, string $targetId, string $messageUid): array
{
if (!preg_match('/^\d+$/', $messageUid)) {
respond(400, '缺少可查询的消息ID');
}
$table = imMessageTable($messageUid);
$statement = $imDb->prepare(
'select `_mid`, `_from`, `_target`, `_dt`, `_content_type`, `_searchable_key`, `_to`'
. ' from `' . $table . '` where `_mid` = ? limit 1'
);
$statement->execute([$messageUid]);
$message = $statement->fetch();
if (!is_array($message)) {
respond(404, '没有找到该消息');
}
$senderId = (string)$message['_from'];
if (!detailSingleMessageVisible($imDb, $userId, $targetId, $messageUid)) {
respond(403, '没有权限查看该消息');
}
$receiverId = $senderId === $userId ? $targetId : $userId;
if ($senderId !== $userId && $senderId !== $targetId) {
respond(403, '没有权限查看该消息');
}
$sentAt = detailTimestampMs((string)($message['_dt'] ?? ''), $messageUid);
$targets = [$senderId, $senderId . '|' . $receiverId, $receiverId . '|' . $senderId];
$deliveredRaw = detailDeliveryMap($imDb, [$receiverId])[$receiverId] ?? 0;
$readRaw = detailReadAt($imDb, $receiverId, $targets);
$users = detailUserMap($imDb, imAppDb(), [$senderId, $receiverId], $userId);
return [
'messageUid' => $messageUid,
'conversationType' => 'single',
'sentAt' => $sentAt,
'sender' => detailMember($users[$senderId]),
'receiver' => detailMember($users[$receiverId]),
'deliveredAt' => $deliveredRaw >= $sentAt ? $deliveredRaw : 0,
'readAt' => $readRaw >= $sentAt ? $readRaw : 0,
];
}
function groupDetail(PDO $imDb, PDO $appDb, string $userId, string $groupId, string $messageUid): array
{
ensureWebImAppTables();
if (!preg_match('/^\d+$/', $messageUid)) {
respond(400, '缺少可查询的消息ID');
}
$myMember = $appDb->prepare(
'select `role` from `t_web_group_members` where `group_id` = ? and `user_id` = ? and `status` = 0 limit 1'
);
$myMember->execute([$groupId, $userId]);
if (!$myMember->fetchColumn()) {
respond(403, '你不在该群组中');
}
$messageStatement = $appDb->prepare(
'select `message_uid`, `group_id`, `sender_uid`, `created_at_ms`, `edited_at_ms`, `recalled`'
. ' from `t_web_group_messages` where `group_id` = ? and `message_uid` = ? limit 1'
);
$messageStatement->execute([$groupId, $messageUid]);
$message = $messageStatement->fetch();
if (!is_array($message)) {
respond(404, '没有找到该群消息');
}
$sentAt = (int)$message['created_at_ms'];
$editedAt = (int)($message['edited_at_ms'] ?? 0);
$activityAt = max($sentAt, $editedAt);
$senderId = (string)$message['sender_uid'];
$memberStatement = $appDb->prepare(
'select `user_id`, `role`, `alias`, `joined_at_ms` from `t_web_group_members`'
. ' where `group_id` = ? and `status` = 0 and `joined_at_ms` <= ?'
. ' order by (`role` = "owner") desc, (`role` = "admin") desc, `joined_at_ms` asc'
);
$memberStatement->execute([$groupId, $sentAt]);
$members = array_values(array_filter($memberStatement->fetchAll(), static function (array $member) use ($senderId): bool {
return (string)$member['user_id'] !== $senderId;
}));
$memberIds = array_values(array_unique(array_map(static fn(array $member): string => (string)$member['user_id'], $members)));
$users = detailUserMap($imDb, $appDb, array_merge([$senderId], $memberIds), $userId, $groupId);
$deliveryMap = detailDeliveryMap($imDb, $memberIds);
$readMap = [];
if ($memberIds) {
$readStatement = $appDb->prepare(
'select `user_id`, `read_at_ms` from `t_web_group_reads`'
. ' where `group_id` = ? and `user_id` in (' . detailPlaceholders($memberIds) . ')'
);
$readStatement->execute(array_merge([$groupId], $memberIds));
foreach ($readStatement->fetchAll() as $row) {
$readMap[(string)$row['user_id']] = (int)$row['read_at_ms'];
}
}
$read = [];
$unread = [];
$undelivered = [];
foreach ($memberIds as $uid) {
$readAt = (int)($readMap[$uid] ?? 0);
$deliveredAt = (int)($deliveryMap[$uid] ?? 0);
$member = detailMember($users[$uid], $readAt >= $activityAt ? $readAt : ($deliveredAt >= $sentAt ? $deliveredAt : 0));
if ($readAt >= $activityAt) {
$read[] = $member;
} elseif ($deliveredAt >= $sentAt) {
$unread[] = $member;
} else {
$undelivered[] = $member;
}
}
return [
'messageUid' => $messageUid,
'conversationType' => 'group',
'groupId' => $groupId,
'sentAt' => $sentAt,
'editedAt' => $editedAt,
'recalled' => (bool)$message['recalled'],
'sender' => detailMember($users[$senderId] ?? ['uid' => $senderId, 'displayName' => $senderId, 'rawName' => $senderId]),
'group' => [
'read' => $read,
'unread' => $unread,
'undelivered' => $undelivered,
'counts' => [
'read' => count($read),
'unread' => count($unread),
'undelivered' => count($undelivered),
'total' => count($memberIds),
],
],
];
}
$payload = readJsonPayload();
$userId = trim((string)($payload['userId'] ?? ''));
$target = trim((string)($payload['target'] ?? ''));
$messageUid = trim((string)($payload['messageUid'] ?? $payload['messageId'] ?? ''));
$conversationType = detailConversationType($payload['conversationType'] ?? $payload['type'] ?? 'single');
if ($userId === '') {
respond(400, '缺少用户ID');
}
if ($target === '') {
respond(400, '缺少会话对象');
}
if ($messageUid === '') {
respond(400, '缺少消息ID');
}
try {
$imDb = imDb();
$appDb = imAppDb();
$userId = detailResolveUserId($imDb, $userId);
if ($conversationType === 'group') {
respond(0, 'success', ['detail' => groupDetail($imDb, $appDb, $userId, $target, $messageUid)]);
}
$targetId = detailResolveUserId($imDb, $target);
respond(0, 'success', ['detail' => singleDetail($imDb, $userId, $targetId, $messageUid)]);
} catch (Throwable $error) {
respond(500, $error->getMessage() ?: '消息详情加载失败');
}
File diff suppressed because it is too large Load Diff
+39
View File
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');
require __DIR__ . '/im_web_bootstrap.php';
$defaultName = 'Web IM';
$defaultLogo = '/img/logo.png';
try {
$statement = imAppDb()->prepare(
'select `conf_name`, `conf_value`, `updated_at` from `system_conf` where `conf_name` in (?, ?)'
);
$statement->execute(['PlatformName', 'sys_logo']);
$config = [];
$updatedAtValues = [];
foreach ($statement->fetchAll() as $row) {
$config[(string)$row['conf_name']] = trim((string)($row['conf_value'] ?? ''));
$updatedAtValues[] = (string)($row['updated_at'] ?? '');
}
$platformName = $config['PlatformName'] ?? '';
$logo = $config['sys_logo'] ?? '';
$version = implode('|', array_values(array_filter($updatedAtValues ?? [])));
respond(0, 'success', [
'platformName' => $platformName !== '' ? $platformName : $defaultName,
'logo' => $logo !== '' ? $logo : $defaultLogo,
'version' => $version,
]);
} catch (Throwable $error) {
respond(500, $error->getMessage() ?: '平台配置加载失败', [
'platformName' => $defaultName,
'logo' => $defaultLogo,
]);
}
+321
View File
@@ -0,0 +1,321 @@
<?php
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');
require __DIR__ . '/im_web_bootstrap.php';
const PROFILE_DISPLAY_NAME_FLAG = 0x01;
const PROFILE_PORTRAIT_FLAG = 0x02;
const PROFILE_PORTRAIT_MEDIA_TYPE = 5;
const IM_LOCAL_MEDIA_ROOT = '/opt/im-server/media';
const IM_LOCAL_MEDIA_PUBLIC_PORT = 18000;
function profileRequestValue(string $key, string $default = ''): string
{
return trim((string)($_POST[$key] ?? $_GET[$key] ?? $default));
}
function normalizeProfileUser(array $user): array
{
$uid = (string)($user['userId'] ?? $user['uid'] ?? $user['_uid'] ?? '');
return [
'uid' => $uid,
'userId' => $uid,
'name' => (string)($user['name'] ?? $user['_name'] ?? ''),
'displayName' => (string)($user['displayName'] ?? $user['_display_name'] ?? $user['name'] ?? $user['_name'] ?? $uid),
'mobile' => (string)($user['mobile'] ?? $user['_mobile'] ?? ''),
'portrait' => (string)($user['portrait'] ?? $user['_portrait'] ?? ''),
'address' => (string)($user['address'] ?? $user['_address'] ?? ''),
];
}
function tryProfileUserInfo(array $payload): ?array
{
try {
$result = requireImSuccess(imAdminPost('/admin/user/get_info', $payload), '用户资料加载失败');
return $result ?: null;
} catch (Throwable) {
return null;
}
}
function loadProfileUserFromDb(string $identity): ?array
{
$statement = imDb()->prepare(
'select `_uid`, `_name`, `_display_name`, `_mobile`, `_portrait`, `_address`'
. ' from `t_user` where `_uid` = ? or `_mobile` = ? or `_name` = ?'
. ' order by case when `_uid` = ? then 0 when `_mobile` = ? then 1 when `_name` = ? then 2 else 3 end'
. ' limit 1'
);
$statement->execute([$identity, $identity, $identity, $identity, $identity, $identity]);
$row = $statement->fetch();
return $row ? normalizeProfileUser($row) : null;
}
function mergeProfileUser(array $primary, ?array $fallback): array
{
if (!$fallback) {
return $primary;
}
$fallback = normalizeProfileUser($fallback);
foreach (['name', 'displayName', 'mobile', 'portrait', 'address'] as $key) {
if ((string)($primary[$key] ?? '') === '' && (string)($fallback[$key] ?? '') !== '') {
$primary[$key] = (string)$fallback[$key];
}
}
return $primary;
}
function persistProfileUserToDb(string $userId, string $displayName, string $portrait): void
{
if ($portrait !== '') {
$statement = imDb()->prepare(
'update `t_user` set `_display_name` = ?, `_portrait` = ?, `_dt` = ? where `_uid` = ? limit 1'
);
$statement->execute([$displayName, $portrait, webImNowMs(), $userId]);
return;
}
$statement = imDb()->prepare(
'update `t_user` set `_display_name` = ?, `_dt` = ? where `_uid` = ? limit 1'
);
$statement->execute([$displayName, webImNowMs(), $userId]);
}
function loadProfileUser(string $identity, bool $preferMobile = true): array
{
$identity = trim($identity);
if ($identity === '') {
respond(400, '缺少用户ID');
}
$dbUser = loadProfileUserFromDb($identity);
if ($dbUser) {
$fallback = null;
if ((string)($dbUser['portrait'] ?? '') === '') {
$fallback = tryProfileUserInfo(['userId' => $dbUser['userId']]);
if (!$fallback && (string)($dbUser['mobile'] ?? '') !== '') {
$fallback = tryProfileUserInfo(['mobile' => $dbUser['mobile']]);
}
if (!$fallback && (string)($dbUser['name'] ?? '') !== '') {
$fallback = tryProfileUserInfo(['name' => $dbUser['name']]);
}
}
return mergeProfileUser($dbUser, $fallback);
}
$user = null;
if ($preferMobile && preg_match('/^\+?\d{5,32}$/', $identity)) {
$user = tryProfileUserInfo(['mobile' => $identity]);
}
if (!$user) {
$user = tryProfileUserInfo(['userId' => $identity]);
}
if (!$user) {
$user = tryProfileUserInfo(['name' => $identity]);
}
if (!$user) {
respond(404, '用户资料不存在');
}
return normalizeProfileUser($user);
}
function readProfileJavaSerializedString(string $data, int $offset): ?array
{
if ($offset + 3 > strlen($data) || ord($data[$offset]) !== 0x74) {
return null;
}
$length = (ord($data[$offset + 1]) << 8) | ord($data[$offset + 2]);
$start = $offset + 3;
if ($start + $length > strlen($data)) {
return null;
}
return [substr($data, $start, $length), $start + $length];
}
function profileSessionUserId(string $sessionData): string
{
$marker = "\x74\x00\x06userId";
$offset = strpos($sessionData, $marker);
if ($offset === false) {
return '';
}
$decoded = readProfileJavaSerializedString($sessionData, $offset + strlen($marker));
$userId = is_array($decoded) ? (string)$decoded[0] : '';
if (!preg_match('/^[A-Za-z0-9_:@.+-]{1,128}$/', $userId)) {
return '';
}
return $userId;
}
function requireProfileUpdateAuth(string $targetUserId): void
{
$authToken = trim((string)($_SERVER['HTTP_AUTHTOKEN'] ?? $_SERVER['HTTP_AUTH_TOKEN'] ?? ''));
if ($authToken === '') {
respond(401, '请重新登录后再修改资料');
}
$statement = imAppDb()->prepare('select `session_data` from `shiro_session` where `session_id` = ? limit 1');
$statement->execute([$authToken]);
$row = $statement->fetch();
if (!$row) {
respond(401, '登录状态已失效,请重新登录');
}
$sessionUserId = profileSessionUserId((string)$row['session_data']);
if ($sessionUserId === '' || $sessionUserId !== $targetUserId) {
respond(403, '只能修改自己的资料');
}
}
function profileUploadedFileExtension(string $fileName, string $mime): string
{
$extension = strtolower((string)pathinfo($fileName, PATHINFO_EXTENSION));
$extension = preg_replace('/[^a-z0-9]/', '', $extension) ?: '';
if ($extension === 'jpeg') {
$extension = 'jpg';
}
$allowedExtensions = ['jpg', 'png', 'gif', 'webp', 'bmp', 'ico'];
if (in_array($extension, $allowedExtensions, true)) {
return $extension;
}
return match ($mime) {
'image/jpeg' => 'jpg',
'image/png' => 'png',
'image/gif' => 'gif',
'image/webp' => 'webp',
'image/bmp', 'image/x-ms-bmp' => 'bmp',
'image/x-icon', 'image/vnd.microsoft.icon' => 'ico',
default => 'jpg',
};
}
function profilePublicMediaBaseUrl(): string
{
$isHttps = (string)($_SERVER['HTTPS'] ?? '') !== '' && strtolower((string)$_SERVER['HTTPS']) !== 'off';
$scheme = $isHttps ? 'https' : 'http';
$host = (string)($_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? '127.0.0.1');
$host = trim(preg_replace('/:\d+$/', '', $host) ?: '127.0.0.1');
return $scheme . '://' . $host . ':' . IM_LOCAL_MEDIA_PUBLIC_PORT;
}
function uploadProfilePortrait(array $file): string
{
if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
throw new RuntimeException('头像上传失败');
}
if (($file['size'] ?? 0) <= 0 || ($file['size'] ?? 0) > 5 * 1024 * 1024) {
throw new RuntimeException('头像不能超过5MB');
}
$tmpName = (string)($file['tmp_name'] ?? '');
$mime = mime_content_type($tmpName) ?: '';
if (!str_starts_with($mime, 'image/')) {
throw new RuntimeException('头像必须是图片文件');
}
if (!is_dir(IM_LOCAL_MEDIA_ROOT) || !is_writable(IM_LOCAL_MEDIA_ROOT)) {
throw new RuntimeException('头像存储目录不可写');
}
$datePath = 'fs/' . PROFILE_PORTRAIT_MEDIA_TYPE . '/' . date('Y/m/d/H/i/s');
$targetDir = rtrim(IM_LOCAL_MEDIA_ROOT, '/') . '/' . $datePath;
if (!is_dir($targetDir) && !mkdir($targetDir, 0775, true)) {
throw new RuntimeException('头像存储目录创建失败');
}
$extension = profileUploadedFileExtension((string)($file['name'] ?? 'avatar.jpg'), $mime);
$targetName = bin2hex(random_bytes(12)) . '.' . $extension;
$targetPath = $targetDir . '/' . $targetName;
if (!move_uploaded_file($tmpName, $targetPath)) {
throw new RuntimeException('头像文件保存失败');
}
@chmod($targetPath, 0644);
return profilePublicMediaBaseUrl() . '/' . $datePath . '/' . $targetName;
}
try {
$contentType = (string)($_SERVER['CONTENT_TYPE'] ?? '');
$isMultipart = stripos($contentType, 'multipart/form-data') !== false;
$payload = $isMultipart ? [] : readJsonPayload();
$action = $isMultipart
? profileRequestValue('action', 'update')
: trim((string)($payload['action'] ?? 'get'));
$userId = $isMultipart
? profileRequestValue('userId')
: trim((string)($payload['userId'] ?? $_GET['userId'] ?? ''));
$currentProfile = loadProfileUser($userId);
if ($action === 'get') {
respond(0, 'success', ['profile' => $currentProfile]);
}
if ($action !== 'update') {
respond(400, '不支持的资料操作');
}
requireProfileUpdateAuth((string)$currentProfile['userId']);
$displayName = $isMultipart
? profileRequestValue('displayName')
: trim((string)($payload['displayName'] ?? ''));
if ($displayName === '') {
respond(400, '昵称不能为空');
}
if (mb_strlen($displayName, 'UTF-8') > 64) {
respond(400, '昵称不能超过64个字');
}
$portrait = '';
if (!empty($_FILES['portraitFile']) && ($_FILES['portraitFile']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE) {
$portrait = uploadProfilePortrait($_FILES['portraitFile']);
}
$flag = PROFILE_DISPLAY_NAME_FLAG;
$userInfo = [
'userId' => $currentProfile['userId'],
'displayName' => $displayName,
];
if ($portrait !== '') {
$flag |= PROFILE_PORTRAIT_FLAG;
$userInfo['portrait'] = $portrait;
}
requireImSuccess(
imAdminPost('/admin/user/update', [
'flag' => $flag,
'userInfo' => $userInfo,
]),
'用户资料保存失败'
);
persistProfileUserToDb($currentProfile['userId'], $displayName, $portrait);
$updatedProfile = loadProfileUser($currentProfile['userId'], false);
if ($portrait === '' && (string)$updatedProfile['portrait'] === '' && (string)($currentProfile['portrait'] ?? '') !== '') {
$updatedProfile['portrait'] = (string)$currentProfile['portrait'];
}
if ($portrait !== '' && (string)$updatedProfile['portrait'] === '') {
$updatedProfile['portrait'] = $portrait;
}
if ((string)$updatedProfile['displayName'] === '') {
$updatedProfile['displayName'] = $displayName;
}
respond(0, 'success', ['profile' => $updatedProfile]);
} catch (Throwable $error) {
respond(500, $error->getMessage() ?: '用户资料服务暂不可用');
}
+18
View File
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');
echo json_encode([
'code' => 0,
'message' => 'success',
'data' => [
'methods' => [
'phone' => true,
'email' => false,
'username' => false,
],
'mobile_real_verify' => false,
],
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
+498
View File
@@ -0,0 +1,498 @@
<?php
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');
require __DIR__ . '/im_web_bootstrap.php';
const WEB_MEDIA_ROOT = '/opt/im-server/media';
const WEB_MEDIA_PUBLIC_PORT = 18000;
const WEB_MEDIA_TYPE_IMAGE = 1;
const WEB_MEDIA_TYPE_VIDEO = 3;
const WEB_MEDIA_TYPE_FILE = 4;
const WEB_IMAGE_MAX_BYTES = 10 * 1024 * 1024;
const WEB_FILE_MAX_BYTES = 50 * 1024 * 1024;
function isDailyMuteActive(string $dailyStart, string $dailyEnd, int $nowMs): bool
{
if (!preg_match('/^\d{2}:\d{2}$/', $dailyStart) || !preg_match('/^\d{2}:\d{2}$/', $dailyEnd)) {
return false;
}
$now = (new DateTimeImmutable('@' . (int)floor($nowMs / 1000)))
->setTimezone(new DateTimeZone(IM_DB_TIMEZONE));
$currentMinutes = ((int)$now->format('H')) * 60 + (int)$now->format('i');
[$startHour, $startMinute] = array_map('intval', explode(':', $dailyStart));
[$endHour, $endMinute] = array_map('intval', explode(':', $dailyEnd));
$startMinutes = $startHour * 60 + $startMinute;
$endMinutes = $endHour * 60 + $endMinute;
if ($startMinutes === $endMinutes) {
return true;
}
if ($startMinutes < $endMinutes) {
return $currentMinutes >= $startMinutes && $currentMinutes < $endMinutes;
}
return $currentMinutes >= $startMinutes || $currentMinutes < $endMinutes;
}
function isGroupMutedForSender(PDO $appDb, string $groupId, string $role, int $nowMs): bool
{
if ($role === 'owner') {
return false;
}
$statement = $appDb->prepare('select * from `t_web_group_mute_rules` where `group_id` = ? and `enabled` = 1 limit 1');
$statement->execute([$groupId]);
$rule = $statement->fetch();
if (!is_array($rule)) {
return false;
}
$mode = (string)$rule['mode'];
if ($mode === 'off') {
return false;
}
if ($mode === 'all_except_admins' && $role === 'admin') {
return false;
}
if (!in_array($mode, ['all_include_admins', 'all_except_admins'], true)) {
return false;
}
$scheduleType = (string)$rule['schedule_type'];
if ($scheduleType === 'manual') {
return true;
}
if ($scheduleType === 'daily') {
return isDailyMuteActive((string)$rule['daily_start'], (string)$rule['daily_end'], $nowMs);
}
$startsAtMs = (int)$rule['starts_at_ms'];
$endsAtMs = (int)$rule['ends_at_ms'];
return $startsAtMs > 0 && $endsAtMs > $startsAtMs && $nowMs >= $startsAtMs && $nowMs < $endsAtMs;
}
function messageRequestValue(array $payload, string $key, string $default = ''): string
{
return trim((string)($_POST[$key] ?? $payload[$key] ?? $default));
}
function safeUploadName(string $fileName): string
{
$name = basename(str_replace('\\', '/', $fileName));
$name = preg_replace('/[^\p{L}\p{N}._ -]+/u', '_', $name) ?: 'file';
$name = trim($name, " .\t\n\r\0\x0B");
return $name !== '' ? mb_substr($name, 0, 180, 'UTF-8') : 'file';
}
function uploadExtension(string $fileName, string $mime, string $attachmentType): string
{
$extension = strtolower((string)pathinfo($fileName, PATHINFO_EXTENSION));
$extension = preg_replace('/[^a-z0-9]/', '', $extension) ?: '';
if ($extension === 'jpeg') {
$extension = 'jpg';
}
if ($attachmentType === 'image') {
if (in_array($extension, ['jpg', 'png', 'gif', 'webp', 'bmp', 'svg', 'avif', 'heic', 'heif'], true)) {
return $extension;
}
return match ($mime) {
'image/jpeg' => 'jpg',
'image/png' => 'png',
'image/gif' => 'gif',
'image/webp' => 'webp',
'image/bmp', 'image/x-ms-bmp' => 'bmp',
'image/svg+xml' => 'svg',
'image/avif' => 'avif',
'image/heic' => 'heic',
'image/heif' => 'heif',
default => 'jpg',
};
}
if ($extension !== '') {
return $extension;
}
return 'bin';
}
function detectedUploadMime(string $tmpName): string
{
$mime = mime_content_type($tmpName) ?: '';
if ($mime !== '' && $mime !== 'application/octet-stream') {
return $mime;
}
$imageInfo = @getimagesize($tmpName);
if (is_array($imageInfo) && !empty($imageInfo['mime'])) {
return (string)$imageInfo['mime'];
}
return $mime !== '' ? $mime : 'application/octet-stream';
}
function normalizedImageUploadMime(string $tmpName, string $mime): string
{
if (str_starts_with($mime, 'image/')) {
return $mime;
}
$imageInfo = @getimagesize($tmpName);
$imageMime = is_array($imageInfo) ? (string)($imageInfo['mime'] ?? '') : '';
if ($imageMime !== '' && str_starts_with($imageMime, 'image/')) {
return $imageMime;
}
throw new RuntimeException('请选择图片文件');
}
function mediaPublicBaseUrl(): string
{
$isHttps = (string)($_SERVER['HTTPS'] ?? '') !== '' && strtolower((string)$_SERVER['HTTPS']) !== 'off';
$scheme = $isHttps ? 'https' : 'http';
$host = trim(preg_replace('/:\d+$/', '', (string)($_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? '127.0.0.1')) ?: '127.0.0.1');
return $scheme . '://' . $host . ':' . WEB_MEDIA_PUBLIC_PORT;
}
function saveMessageAttachmentFile(array $file, string $attachmentType): array
{
if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
throw new RuntimeException('文件上传失败');
}
$size = (int)($file['size'] ?? 0);
$maxSize = $attachmentType === 'image' ? WEB_IMAGE_MAX_BYTES : WEB_FILE_MAX_BYTES;
if ($size <= 0 || $size > $maxSize) {
throw new RuntimeException($attachmentType === 'image' ? '图片不能超过10MB' : '文件不能超过50MB');
}
if (!is_dir(WEB_MEDIA_ROOT) || !is_writable(WEB_MEDIA_ROOT)) {
throw new RuntimeException('媒体存储目录不可写');
}
$tmpName = (string)($file['tmp_name'] ?? '');
if ($tmpName === '' || !is_uploaded_file($tmpName)) {
throw new RuntimeException('文件上传失败');
}
$mime = detectedUploadMime($tmpName);
if ($attachmentType === 'image') {
$mime = normalizedImageUploadMime($tmpName, $mime);
}
$mediaType = $attachmentType === 'image' ? WEB_MEDIA_TYPE_IMAGE : WEB_MEDIA_TYPE_FILE;
$datePath = 'fs/' . $mediaType . '/' . date('Y/m/d/H/i/s');
$targetDir = rtrim(WEB_MEDIA_ROOT, '/') . '/' . $datePath;
if (!is_dir($targetDir) && !mkdir($targetDir, 0775, true)) {
throw new RuntimeException('媒体存储目录创建失败');
}
$originalName = safeUploadName((string)($file['name'] ?? ($attachmentType === 'image' ? 'image.jpg' : 'file')));
$extension = uploadExtension($originalName, $mime, $attachmentType);
$targetName = bin2hex(random_bytes(12)) . '.' . $extension;
$targetPath = $targetDir . '/' . $targetName;
if (!move_uploaded_file($tmpName, $targetPath)) {
throw new RuntimeException('文件保存失败');
}
@chmod($targetPath, 0644);
return [
'type' => $attachmentType,
'url' => mediaPublicBaseUrl() . '/' . $datePath . '/' . $targetName,
'name' => $originalName,
'mime' => $mime,
'size' => $size,
'mediaType' => $mediaType,
];
}
function storeMessageAttachment(
PDO $appDb,
string $messageUid,
string $conversationType,
string $target,
string $sender,
array $attachment,
int $timestamp
): void {
if ($messageUid === '' || empty($attachment['url'])) {
return;
}
$statement = $appDb->prepare(
'insert into `t_web_message_attachments`'
. ' (`message_uid`, `conversation_type`, `target_id`, `sender_uid`, `attachment_type`, `url`, `name`, `mime`, `size_bytes`, `created_at_ms`)'
. ' values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
. ' on duplicate key update'
. ' `attachment_type` = values(`attachment_type`),'
. ' `url` = values(`url`),'
. ' `name` = values(`name`),'
. ' `mime` = values(`mime`),'
. ' `size_bytes` = values(`size_bytes`)'
);
$statement->execute([
$messageUid,
$conversationType,
$target,
$sender,
(string)$attachment['type'],
(string)$attachment['url'],
(string)$attachment['name'],
(string)$attachment['mime'],
(int)$attachment['size'],
$timestamp,
]);
}
function attachmentFromRequest(string $messageType): ?array
{
if (!in_array($messageType, ['image', 'video', 'file'], true)) {
return null;
}
$forwardUrl = trim((string)($_POST['attachmentUrl'] ?? ''));
if ($forwardUrl !== '') {
$parts = parse_url($forwardUrl);
$scheme = strtolower((string)($parts['scheme'] ?? ''));
if (!in_array($scheme, ['http', 'https'], true) || empty($parts['host']) || strlen($forwardUrl) > 2048) {
respond(400, '媒体地址不合法');
}
$mime = trim((string)($_POST['attachmentMime'] ?? 'application/octet-stream'));
$name = safeUploadName((string)($_POST['attachmentName'] ?? ($messageType === 'image' ? '图片' : ($messageType === 'video' ? '视频.mp4' : '文件'))));
return [
'type' => $messageType,
'url' => $forwardUrl,
'name' => $name,
'mime' => $mime,
'size' => max(0, (int)($_POST['attachmentSize'] ?? 0)),
'mediaType' => $messageType === 'image' ? WEB_MEDIA_TYPE_IMAGE : ($messageType === 'video' ? WEB_MEDIA_TYPE_VIDEO : WEB_MEDIA_TYPE_FILE),
];
}
$attachmentFile = $_FILES['attachment'] ?? $_FILES['file'] ?? null;
if (!is_array($attachmentFile)) {
respond(400, '缺少上传文件');
}
return saveMessageAttachmentFile($attachmentFile, $messageType);
}
$contentTypeHeader = (string)($_SERVER['CONTENT_TYPE'] ?? '');
$isMultipart = stripos($contentTypeHeader, 'multipart/form-data') !== false;
$payload = $isMultipart ? [] : readJsonPayload();
$sender = messageRequestValue($payload, 'sender');
$target = messageRequestValue($payload, 'target');
$text = messageRequestValue($payload, 'text');
$messageType = messageRequestValue($payload, 'messageType', 'text');
$conversationType = $_POST['conversationType'] ?? $_POST['type'] ?? $payload['conversationType'] ?? $payload['type'] ?? 0;
$isGroupConversation = in_array((string)$conversationType, ['1', 'group', 'channel'], true);
$mentionedUserIds = $payload['mentionedUserIds'] ?? [];
$mentionedUserIds = is_array($mentionedUserIds)
? array_values(array_unique(array_filter(array_map(static fn($value): string => trim((string)$value), $mentionedUserIds))))
: [];
$attachment = null;
if ($sender === '' || $target === '' || ($text === '' && !in_array($messageType, ['image', 'video', 'file'], true))) {
respond(400, '缺少发送者、接收者或消息内容');
}
try {
if ($isGroupConversation) {
ensureWebImAppTables();
$appDb = imAppDb();
$memberStatement = $appDb->prepare(
'select g.`group_id`, g.`category`, g.`owner_uid`, m.`role`'
. ' from `t_web_groups` g'
. ' join `t_web_group_members` m on m.`group_id` = g.`group_id` and m.`status` = 0'
. ' where g.`deleted` = 0 and g.`group_id` = ? and m.`user_id` = ?'
. ' limit 1'
);
$memberStatement->execute([$target, $sender]);
$group = $memberStatement->fetch();
if (!$group) {
// 手机端创建的原生群不一定存在于 Web 自建群表中,需回退检查 IM 群成员表。
$imDb = imDb();
$nativeGroupStatement = $imDb->prepare(
'select 1 from `t_group` where `_gid` = ? and `_deleted` = 0 limit 1'
);
$nativeGroupStatement->execute([$target]);
$nativeMemberStatement = $imDb->prepare(
'select `_type` from `t_group_member` where `_gid` = ? and `_mid` = ? limit 1'
);
$nativeMemberStatement->execute([$target, $sender]);
$nativeMemberType = $nativeMemberStatement->fetchColumn();
if (!$nativeGroupStatement->fetchColumn() || $nativeMemberType === false) {
respond(403, '你不在该群组中');
}
$attachment = attachmentFromRequest($messageType);
$pushContent = $text !== ''
? $text
: ($attachment
? ((string)$attachment['type'] === 'image' ? '[图片]' : ((string)$attachment['type'] === 'video' ? '[视频]' : '[文件] ' . (string)$attachment['name']))
: $text);
$payloadBody = [
'type' => $attachment ? ((string)$attachment['type'] === 'image' ? 3 : ((string)$attachment['type'] === 'video' ? 6 : 5)) : 1,
'searchableContent' => $pushContent,
'pushContent' => $pushContent,
'content' => $text,
'persistFlag' => 3,
];
if ($mentionedUserIds) {
$payloadBody['mentionedType'] = 1;
$payloadBody['mentionedTarget'] = $mentionedUserIds;
}
if ($attachment) {
$payloadBody['mediaType'] = (int)$attachment['mediaType'];
$payloadBody['remoteMediaUrl'] = (string)$attachment['url'];
$payloadBody['extra'] = json_encode([
'name' => (string)$attachment['name'],
'mime' => (string)$attachment['mime'],
'size' => (int)$attachment['size'],
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
$nativeResult = requireImSuccess(imAdminPost('/admin/message/send', [
'sender' => $sender,
'conv' => ['type' => 1, 'target' => $target, 'line' => 0],
'payload' => $payloadBody,
'userMessage' => true,
]), '原生群消息发送失败');
$messageUid = isset($nativeResult['messageUid']) ? (string)$nativeResult['messageUid'] : '';
$timestamp = (int)($nativeResult['timestamp'] ?? webImNowMs());
if ($attachment && $messageUid !== '') {
storeMessageAttachment($appDb, $messageUid, 'group', $target, $sender, $attachment, $timestamp);
}
$role = (int)$nativeMemberType === 2 ? 'owner' : ((int)$nativeMemberType === 1 ? 'admin' : 'member');
respond(0, 'success', [
'messageUid' => $messageUid,
'timestamp' => $timestamp,
'senderRole' => $role,
'attachment' => $attachment,
'nativeError' => '',
]);
}
$category = (string)($group['category'] ?? 'group');
$role = (string)($group['role'] ?? 'member');
if ($category === 'channel' && !in_array($role, ['owner', 'admin'], true)) {
respond(403, '公告群仅管理员可发言');
}
$now = webImNowMs();
if ($category !== 'channel' && isGroupMutedForSender($appDb, $target, $role, $now)) {
respond(403, '当前群组处于禁言时段');
}
$attachment = attachmentFromRequest($messageType);
$messageUid = webImMessageUid();
$insert = $appDb->prepare(
'insert into `t_web_group_messages`'
. ' (`message_uid`, `group_id`, `sender_uid`, `text`, `created_at_ms`, `edited_at_ms`, `recalled`)'
. ' values (?, ?, ?, ?, ?, 0, 0)'
);
$insert->execute([$messageUid, $target, $sender, $text, $now]);
if ($attachment) {
storeMessageAttachment($appDb, $messageUid, 'group', $target, $sender, $attachment, $now);
}
$updateGroup = $appDb->prepare('update `t_web_groups` set `updated_at_ms` = ? where `group_id` = ?');
$updateGroup->execute([$now, $target]);
$nativeError = '';
try {
$pushContent = $text !== ''
? $text
: ($attachment
? ((string)$attachment['type'] === 'image' ? '[图片]' : ((string)$attachment['type'] === 'video' ? '[视频]' : '[文件] ' . (string)$attachment['name']))
: $text);
$payloadBody = [
'type' => $attachment ? ((string)$attachment['type'] === 'image' ? 3 : ((string)$attachment['type'] === 'video' ? 6 : 5)) : 1,
'searchableContent' => $pushContent,
'pushContent' => $pushContent,
'content' => $text,
'persistFlag' => 3,
];
if ($mentionedUserIds) {
$payloadBody['mentionedType'] = 1;
$payloadBody['mentionedTarget'] = $mentionedUserIds;
}
if ($attachment) {
$payloadBody['mediaType'] = (int)$attachment['mediaType'];
$payloadBody['remoteMediaUrl'] = (string)$attachment['url'];
$payloadBody['extra'] = json_encode([
'name' => (string)$attachment['name'],
'mime' => (string)$attachment['mime'],
'size' => (int)$attachment['size'],
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
requireImSuccess(imAdminPost('/admin/message/send', [
'sender' => $sender,
'conv' => [
'type' => 1,
'target' => $target,
'line' => 0,
],
'payload' => $payloadBody,
'userMessage' => true,
]), '原生群消息发送失败');
} catch (Throwable $error) {
$nativeError = $error->getMessage() ?: '原生群消息发送失败';
}
respond(0, 'success', [
'messageUid' => $messageUid,
'timestamp' => $now,
'senderRole' => $role,
'attachment' => $attachment,
'nativeError' => $nativeError,
]);
}
$attachment = attachmentFromRequest($messageType);
$pushContent = $text !== ''
? $text
: ($attachment
? ((string)$attachment['type'] === 'image' ? '[图片]' : ((string)$attachment['type'] === 'video' ? '[视频]' : '[文件] ' . (string)$attachment['name']))
: $text);
$payloadBody = [
'type' => $attachment ? ((string)$attachment['type'] === 'image' ? 3 : ((string)$attachment['type'] === 'video' ? 6 : 5)) : 1,
'searchableContent' => $pushContent,
'pushContent' => $pushContent,
'content' => $text,
'persistFlag' => 3,
];
if ($attachment) {
$payloadBody['mediaType'] = (int)$attachment['mediaType'];
$payloadBody['remoteMediaUrl'] = (string)$attachment['url'];
$payloadBody['extra'] = json_encode([
'name' => (string)$attachment['name'],
'mime' => (string)$attachment['mime'],
'size' => (int)$attachment['size'],
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
$result = requireImSuccess(imAdminPost('/admin/message/send', [
'sender' => $sender,
'conv' => [
'type' => 0,
'target' => $target,
'line' => 0,
],
'payload' => $payloadBody,
'userMessage' => true,
]), '发送失败');
$messageUid = isset($result['messageUid']) ? (string)$result['messageUid'] : '';
$timestamp = (int)($result['timestamp'] ?? webImNowMs());
if ($attachment && $messageUid !== '') {
ensureWebImAppTables();
storeMessageAttachment(imAppDb(), $messageUid, 'single', $target, $sender, $attachment, $timestamp);
}
respond(0, 'success', [
'messageUid' => $messageUid !== '' ? $messageUid : null,
'timestamp' => $timestamp,
'attachment' => $attachment,
]);
} catch (Throwable $error) {
respond(500, $error->getMessage() ?: '发送失败');
}
+61
View File
@@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');
require __DIR__ . '/im_web_bootstrap.php';
$payload = readJsonPayload();
$userId = trim((string)($payload['userId'] ?? ''));
$targetId = trim((string)($payload['targetId'] ?? $payload['friendUid'] ?? ''));
$alias = trim((string)($payload['alias'] ?? ''));
if ($userId === '') {
respond(400, '缺少用户ID');
}
if ($targetId === '') {
respond(400, '缺少联系人ID');
}
if ($targetId === $userId) {
respond(400, '不能给自己设置备注名');
}
if (mb_strlen($alias, 'UTF-8') > 32) {
respond(400, '备注名不能超过32个字');
}
try {
ensureWebImAppTables();
$imDb = imDb();
$exists = $imDb->prepare('select 1 from `t_user` where `_uid` = ? limit 1');
$exists->execute([$targetId]);
if (!$exists->fetchColumn()) {
respond(404, '没有找到该用户');
}
$friend = $imDb->prepare('select 1 from `t_friend` where `_uid` = ? and `_friend_uid` = ? limit 1');
$friend->execute([$userId, $targetId]);
$isContact = (bool)$friend->fetchColumn();
if ($isContact) {
requireImSuccess(
imAdminPost('/admin/friend/set_alias', [
'operator' => $userId,
'targetId' => $targetId,
'alias' => $alias,
]),
'备注名修改失败'
);
}
saveWebUserRemark(imAppDb(), $userId, $targetId, $alias);
respond(0, 'success', [
'contact' => [
'uid' => $targetId,
'alias' => $alias,
'isContact' => $isContact,
],
]);
} catch (Throwable $error) {
respond(500, $error->getMessage() ?: '备注名服务暂不可用');
}
+13
View File
@@ -0,0 +1,13 @@
window.JC_WEB_IM_CONFIG = {
adminServer: 'http://18.141.44.165:8100',
appServer: '/app-server',
qrAppServer: 'http://18.141.44.165:8888',
platformConfigApi: '/api/platform_config.php',
registerConfigApi: 'http://18.141.44.165:8100/api/register-config',
imServerHost: '18.141.44.165',
imRoutePort: 80,
useWss: false,
wsPath: '/ws',
sdkMode: 'legacy-http',
syncIntervalMs: 2500
};
+18
View File
@@ -0,0 +1,18 @@
window.JC_WEB_IM_CONFIG = {
runtimeEnvironment: 'local',
adminServer: 'http://18.141.44.165:8100',
appServer: '/app-server',
qrAppServer: 'http://18.141.44.165:8888',
platformConfigApi: '/local-api/platform_config.php',
registerConfigApi: '/local-api/register_config.php',
registerPhoneExistsApi: 'http://18.141.44.165:8100/api/register-phone-exists',
imServerHost: '18.141.44.165',
imRoutePort: 80,
useWss: false,
wsPath: '/ws',
sdkMode: 'legacy-http',
syncIntervalMs: 2500,
sseEnabled: false,
sseTicketApi: '/local-api/sse_ticket.php',
sseUrl: '/ws-events'
};
@@ -0,0 +1,23 @@
(() => {
const protocol = window.location.protocol || 'http:';
const host = window.location.hostname || '18.141.44.165';
window.JC_WEB_IM_CONFIG = {
runtimeEnvironment: 'production',
adminServer: `${protocol}//${host}:8100`,
appServer: `${protocol}//${host}:8888`,
qrAppServer: `${protocol}//${host}:8888`,
platformConfigApi: '/api/platform_config.php',
registerConfigApi: `${protocol}//${host}:8100/api/register-config`,
registerPhoneExistsApi: `${protocol}//${host}:8100/api/register-phone-exists`,
imServerHost: host,
imRoutePort: 80,
useWss: false,
wsPath: '/ws',
sdkMode: 'legacy-http',
syncIntervalMs: 15000,
sseEnabled: true,
sseTicketApi: '/api/sse_ticket.php',
sseUrl: '/ws-events'
};
})();
Binary file not shown.

After

Width:  |  Height:  |  Size: 958 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

+14
View File
@@ -0,0 +1,14 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Web IM</title>
<link rel="icon" href="favicon.ico">
<script src="config/runtime-config.local.js"></script>
<script defer src="js/chunk-vendors.js"></script><script defer src="js/app.js"></script></head>
<body>
<noscript>请启用 JavaScript 后使用 Web IM。</noscript>
<div id="app"></div>
</body>
</html>
+1056
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
BIN
View File
Binary file not shown.
+10 -6
View File
@@ -34,11 +34,6 @@ try {
} catch (Throwable) {
$remarkMap = [];
}
try {
$friendAliasMap = fetchImFriendAliasMap(imDb(), $userId, $friendIds);
} catch (Throwable) {
$friendAliasMap = [];
}
$contactsByUid = [];
foreach (array_values(array_filter($usersResult['userInfos'] ?? [], 'is_array')) as $user) {
@@ -46,7 +41,16 @@ try {
if ($uid === '' || isset($contactsByUid[$uid])) {
continue;
}
$alias = $friendAliasMap[$uid] ?? '';
$alias = '';
try {
$aliasResult = requireImSuccess(
imAdminPost('/admin/friend/get_alias', ['operator' => $userId, 'targetId' => $uid]),
'联系人备注加载失败'
);
$alias = trim((string)($aliasResult['alias'] ?? ''));
} catch (Throwable $error) {
$alias = '';
}
if ($alias === '') {
$alias = $remarkMap[$uid] ?? '';
}
+69 -194
View File
@@ -70,8 +70,6 @@ function webGroupConversation(array $group, string $role = 'member'): array
'line' => 0,
'category' => $category,
'role' => $role,
'nativeStatus' => (string)($group['native_status'] ?? ''),
'nativeError' => (string)($group['native_error'] ?? ''),
],
];
}
@@ -178,48 +176,6 @@ function createNativeGroup(string $operator, string $groupId, string $name, stri
]), '原生群组创建失败');
}
function fetchNativeGroupInfo(string $groupKey): array
{
$payloads = [
['group_id' => $groupKey],
['groupId' => $groupKey],
['target_id' => $groupKey],
];
$lastError = null;
foreach ($payloads as $payload) {
try {
return requireImSuccess(imAdminPost('/admin/group/get_info', $payload), '群组不存在');
} catch (Throwable $error) {
$lastError = $error;
}
}
throw new RuntimeException($lastError ? ($lastError->getMessage() ?: '群组不存在') : '群组不存在');
}
function nativeGroupInfoValue(array $native, string $key, string $fallback = ''): string
{
$sources = [$native];
if (is_array($native['group_info'] ?? null)) {
$sources[] = $native['group_info'];
}
if (is_array($native['group'] ?? null)) {
$sources[] = $native['group'];
if (is_array($native['group']['group_info'] ?? null)) {
$sources[] = $native['group']['group_info'];
}
}
foreach ($sources as $source) {
if (isset($source[$key]) && (string)$source[$key] !== '') {
return (string)$source[$key];
}
}
return $fallback;
}
function addNativeGroupMember(string $operator, string $groupId, string $userId): void
{
requireImSuccess(imAdminPost('/admin/group/member/add', [
@@ -469,134 +425,37 @@ function currentMuteSetting(PDO $appDb, string $groupId): array
];
}
function nativeGroupRoleFromType(mixed $type): string
{
$value = (int)$type;
if ($value === 2) {
return 'owner';
}
if ($value === 1) {
return 'admin';
}
return 'member';
}
function fetchNativeGroupWithMember(PDO $imDb, string $groupId, string $userId): array
{
$statement = $imDb->prepare(
'select g.*, m.`_type` as `member_type`, m.`_alias` as `member_alias`'
. ' from `t_group` g'
. ' join `t_group_member` m on m.`_gid` = g.`_gid`'
. ' where g.`_gid` = ? and g.`_deleted` = 0 and m.`_mid` = ? limit 1'
);
$statement->execute([$groupId, $userId]);
$group = $statement->fetch();
return is_array($group) ? $group : [];
}
function ensureNativeGroupMember(PDO $imDb, string $groupId, string $userId): array
{
$group = fetchNativeGroupWithMember($imDb, $groupId, $userId);
if ($group) {
return $group;
}
$exists = $imDb->prepare('select 1 from `t_group` where `_gid` = ? and `_deleted` = 0 limit 1');
$exists->execute([$groupId]);
if ($exists->fetchColumn()) {
respond(403, '你不在该群组中');
}
respond(404, '没有找到该群组');
}
function nativeGroupDetailAction(PDO $imDb, string $userId, string $groupId): array
{
$group = ensureNativeGroupMember($imDb, $groupId, $userId);
$ownerId = (string)($group['_owner'] ?? '');
$users = fetchWebUserMap($imDb, [$ownerId, $userId], $userId);
$owner = $users[$ownerId] ?? ['uid' => $ownerId, 'displayName' => $ownerId, 'contactAlias' => ''];
$me = $users[$userId] ?? ['uid' => $userId, 'displayName' => $userId];
$myAlias = (string)($group['member_alias'] ?? '');
return [
'group' => [
'groupId' => (string)$group['_gid'],
'name' => (string)($group['_name'] ?? ''),
'category' => 'group',
'announcement' => '',
'welcomeText' => '',
'ownerUid' => $ownerId,
'ownerName' => (string)($owner['contactAlias'] ?? '') !== '' ? (string)$owner['contactAlias'] : (string)$owner['displayName'],
'myRole' => nativeGroupRoleFromType($group['member_type'] ?? 0),
'myAlias' => $myAlias,
'myDisplayName' => $myAlias !== '' ? $myAlias : (string)$me['displayName'],
'muteSetting' => [
'mode' => 'off',
'scheduleType' => 'once',
'startsAtMs' => 0,
'endsAtMs' => 0,
'dailyStart' => '',
'dailyEnd' => '',
'enabled' => false,
],
'native' => true,
],
];
}
function nativeGroupMembersAction(PDO $imDb, string $userId, string $groupId): array
{
ensureNativeGroupMember($imDb, $groupId, $userId);
$statement = $imDb->prepare(
'select `_mid`, `_alias`, `_type`, `_create_dt` from `t_group_member`'
. ' where `_gid` = ? order by (`_type` = 2) desc, (`_type` = 1) desc, `_create_dt` asc limit 500'
);
$statement->execute([$groupId]);
$members = $statement->fetchAll();
$users = fetchWebUserMap($imDb, array_column($members, '_mid'), $userId);
return [
'members' => array_map(static function (array $member) use ($users): array {
$uid = (string)$member['_mid'];
$user = $users[$uid] ?? [
'uid' => $uid,
'displayName' => $uid,
'mobile' => '',
'portrait' => '',
'contactAlias' => '',
'friendAlias' => '',
'remarkAlias' => '',
'isContact' => false,
];
$alias = trim((string)($member['_alias'] ?? ''));
$contactAlias = trim((string)($user['contactAlias'] ?? ''));
return [
'uid' => $uid,
'role' => nativeGroupRoleFromType($member['_type'] ?? 0),
'alias' => $alias,
'contactAlias' => $contactAlias,
'friendAlias' => trim((string)($user['friendAlias'] ?? '')),
'remarkAlias' => trim((string)($user['remarkAlias'] ?? '')),
'isContact' => (bool)($user['isContact'] ?? false),
'displayName' => $contactAlias !== '' ? $contactAlias : ($alias !== '' ? $alias : (string)$user['displayName']),
'rawDisplayName' => (string)$user['displayName'],
'groupDisplayName' => $alias,
'mobile' => (string)($user['mobile'] ?? ''),
'portrait' => (string)($user['portrait'] ?? ''),
];
}, $members),
];
}
function groupDetailAction(PDO $imDb, PDO $appDb, string $userId, string $groupId): array
{
$group = fetchWebGroup($appDb, $groupId);
if (!$group) {
return nativeGroupDetailAction($imDb, $userId, $groupId);
$groupStatement = $imDb->prepare('select * from `t_group` where `_gid` = ? and `_deleted` = 0 limit 1');
$groupStatement->execute([$groupId]);
$nativeGroup = $groupStatement->fetch();
$memberStatement = $imDb->prepare('select `_type`, `_alias` from `t_group_member` where `_gid` = ? and `_mid` = ? limit 1');
$memberStatement->execute([$groupId, $userId]);
$nativeMember = $memberStatement->fetch();
if (!$nativeGroup || !$nativeMember) {
respond(403, '你不在该群组中');
}
$ownerStatement = $imDb->prepare('select `_mid` from `t_group_member` where `_gid` = ? and `_type` = 2 limit 1');
$ownerStatement->execute([$groupId]);
$ownerId = (string)($ownerStatement->fetchColumn() ?: '');
$users = fetchWebUserMap($imDb, array_filter([$ownerId, $userId]), $userId);
return ['group' => [
'groupId' => $groupId,
'publicId' => (string)($nativeGroup['id'] ?? ''),
'name' => (string)($nativeGroup['_name'] ?? $groupId),
'category' => 'group',
'announcement' => (string)($nativeGroup['_bulletin'] ?? ''),
'welcomeText' => '',
'ownerUid' => $ownerId,
'ownerName' => (string)($users[$ownerId]['displayName'] ?? $ownerId),
'myRole' => ((int)($nativeMember['_type'] ?? 0) === 2 ? 'owner' : ((int)($nativeMember['_type'] ?? 0) === 1 ? 'admin' : 'member')),
'myAlias' => (string)($nativeMember['_alias'] ?? ''),
'myDisplayName' => (string)($nativeMember['_alias'] ?? '') ?: (string)($users[$userId]['displayName'] ?? $userId),
'muteSetting' => ['enabled' => false, 'mode' => 'off'],
]];
}
$member = fetchWebGroupMember($appDb, $groupId, $userId);
if (!$member) {
@@ -612,6 +471,7 @@ function groupDetailAction(PDO $imDb, PDO $appDb, string $userId, string $groupI
return [
'group' => [
'groupId' => (string)$group['group_id'],
'publicId' => (string)($group['id'] ?? ''),
'name' => (string)$group['name'],
'category' => (string)$group['category'],
'announcement' => (string)($group['announcement'] ?? ''),
@@ -629,7 +489,38 @@ function groupDetailAction(PDO $imDb, PDO $appDb, string $userId, string $groupI
function groupMembersAction(PDO $imDb, PDO $appDb, string $userId, string $groupId): array
{
if (!fetchWebGroupMember($appDb, $groupId, $userId)) {
return nativeGroupMembersAction($imDb, $userId, $groupId);
$membership = $imDb->prepare('select 1 from `t_group_member` where `_gid` = ? and `_mid` = ? limit 1');
$membership->execute([$groupId, $userId]);
if (!$membership->fetchColumn()) {
respond(403, '你不在该群组中');
}
$nativeStatement = $imDb->prepare(
'select `_mid` as `user_id`, `_type`, `_alias`, `_create_dt` from `t_group_member`'
. ' where `_gid` = ? order by (`_type` = 2) desc, `_create_dt` asc'
);
$nativeStatement->execute([$groupId]);
$nativeMembers = $nativeStatement->fetchAll();
$nativeUsers = fetchWebUserMap($imDb, array_column($nativeMembers, 'user_id'), $userId);
return ['members' => array_map(static function (array $member) use ($nativeUsers): array {
$uid = (string)$member['user_id'];
$user = $nativeUsers[$uid] ?? ['displayName' => $uid, 'mobile' => '', 'portrait' => '', 'isContact' => false];
$alias = trim((string)($member['_alias'] ?? ''));
$type = (int)($member['_type'] ?? 0);
return [
'uid' => $uid,
'role' => $type === 2 ? 'owner' : ($type === 1 ? 'admin' : 'member'),
'alias' => $alias,
'contactAlias' => trim((string)($user['contactAlias'] ?? '')),
'friendAlias' => trim((string)($user['friendAlias'] ?? '')),
'remarkAlias' => trim((string)($user['remarkAlias'] ?? '')),
'isContact' => (bool)($user['isContact'] ?? false),
'displayName' => trim((string)($user['contactAlias'] ?? '')) ?: ($alias ?: (string)$user['displayName']),
'rawDisplayName' => (string)$user['displayName'],
'groupDisplayName' => $alias,
'mobile' => (string)($user['mobile'] ?? ''),
'portrait' => (string)($user['portrait'] ?? ''),
];
}, $nativeMembers)];
}
$statement = $appDb->prepare(
@@ -679,10 +570,7 @@ function updateGroupAliasAction(PDO $appDb, string $userId, string $groupId, str
respond(400, '本群昵称过长');
}
if (!fetchWebGroupMember($appDb, $groupId, $userId)) {
ensureNativeGroupMember(imDb(), $groupId, $userId);
$update = imDb()->prepare('update `t_group_member` set `_alias` = ? where `_gid` = ? and `_mid` = ?');
$update->execute([$alias, $groupId, $userId]);
return ['alias' => $alias];
respond(403, '你不在该群组中');
}
$now = webImNowMs();
@@ -951,16 +839,8 @@ function joinWebGroupAction(PDO $appDb, string $userId, string $groupKey): array
$group = fetchWebGroup($appDb, $groupKey);
if (!$group) {
try {
$native = fetchNativeGroupInfo($groupKey);
$native = requireImSuccess(imAdminPost('/admin/group/get_info', ['groupId' => $groupKey]), '群组不存在');
$now = webImNowMs();
$nativeGroupId = nativeGroupInfoValue(
$native,
'target_id',
nativeGroupInfoValue($native, 'targetId', nativeGroupInfoValue($native, 'group_id', nativeGroupInfoValue($native, 'groupId', $groupKey)))
);
$nativeName = nativeGroupInfoValue($native, 'name', $nativeGroupId);
$nativePortrait = nativeGroupInfoValue($native, 'portrait', '');
$nativeOwner = nativeGroupInfoValue($native, 'owner', nativeGroupInfoValue($native, 'owner_uid', nativeGroupInfoValue($native, 'ownerUid', '')));
$statement = $appDb->prepare(
'insert into `t_web_groups`'
. ' (`group_id`, `category`, `name`, `portrait`, `owner_uid`, `join_mode`, `announcement`,'
@@ -969,38 +849,33 @@ function joinWebGroupAction(PDO $appDb, string $userId, string $groupKey): array
. ' on duplicate key update `updated_at_ms` = values(`updated_at_ms`)'
);
$statement->execute([
$nativeGroupId,
$nativeName,
$nativePortrait,
$nativeOwner,
$nativeGroupId,
$groupKey,
(string)($native['name'] ?? $groupKey),
(string)($native['portrait'] ?? ''),
(string)($native['owner'] ?? ''),
$groupKey,
$userId,
$now,
$now,
]);
$group = fetchWebGroup($appDb, $nativeGroupId);
$group = fetchWebGroup($appDb, $groupKey);
} catch (Throwable) {
respond(404, '没有找到该群组');
}
}
$groupId = (string)$group['group_id'];
$nativeStatus = (string)($group['native_status'] ?? '');
$nativeError = (string)($group['native_error'] ?? '');
upsertWebGroupMember($appDb, $groupId, $userId, 'member');
try {
addNativeGroupMember((string)($group['owner_uid'] ?: $userId), $groupId, $userId);
} catch (Throwable $error) {
$nativeStatus = $nativeStatus === 'ok' ? 'partial' : ($nativeStatus ?: 'fallback');
$nativeError = mb_substr($error->getMessage() ?: '加入原生群组失败', 0, 255, 'UTF-8');
// Web membership is authoritative for this web build; native group sync is best-effort.
}
$role = fetchWebGroupRole($appDb, $groupId, $userId);
return [
'group' => fetchWebGroup($appDb, $groupId),
'conversation' => webGroupConversation($group, $role),
'nativeStatus' => $nativeStatus,
'nativeError' => $nativeError,
];
}
+9 -104
View File
@@ -1,85 +1,15 @@
<?php
declare(strict_types=1);
function webImEnv(string $key, string $fallback = ''): string
{
$runtimeValue = getenv($key);
if ($runtimeValue !== false && $runtimeValue !== '') {
return $runtimeValue;
}
static $env = null;
if ($env === null) {
$env = [];
$paths = array_filter([
getenv('JC_WEB_IM_ENV_FILE') ?: '',
dirname(__DIR__, 2) . '/.env',
'/var/www/im-admin/.env',
'/var/www/im/.env',
]);
foreach ($paths as $path) {
if (!is_readable($path)) {
continue;
}
foreach (file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [] as $line) {
$line = trim($line);
if ($line === '' || strpos($line, '#') === 0 || strpos($line, '=') === false) {
continue;
}
[$name, $value] = array_map('trim', explode('=', $line, 2));
if ($name === '') {
continue;
}
$value = trim($value);
if (
strlen($value) >= 2
&& (($value[0] === '"' && substr($value, -1) === '"') || ($value[0] === "'" && substr($value, -1) === "'"))
) {
$value = substr($value, 1, -1);
}
$env[$name] = $value;
}
break;
}
}
return $env[$key] ?? $fallback;
}
function webImFirstEnv(array $keys, string $fallback = ''): string
{
foreach ($keys as $key) {
$value = webImEnv($key);
if ($value !== '') {
return $value;
}
}
return $fallback;
}
function webImMysqlDsn(string $host, string $port, string $database): string
{
return sprintf('mysql:host=%s;port=%s;dbname=%s;charset=utf8mb4', $host, $port, $database);
}
define('IM_ADMIN_URL', webImEnv('JC_WEB_IM_ADMIN_URL', 'http://127.0.0.1:18080'));
define('IM_ADMIN_SECRET', webImFirstEnv(['JC_WEB_IM_ADMIN_SECRET', 'SecretKey'], '123456'));
define('IM_DB_DSN', webImMysqlDsn(
webImEnv('JC_WEB_IM_DB_HOST', webImEnv('DB_HOST', '127.0.0.1')),
webImEnv('JC_WEB_IM_DB_PORT', webImEnv('DB_PORT', '3306')),
webImEnv('JC_WEB_IM_DB_DATABASE', webImEnv('DB_DATABASE', 'wfchat'))
));
define('IM_DB_USER', webImEnv('JC_WEB_IM_DB_USER', webImEnv('DB_USERNAME', 'winchen')));
define('IM_DB_PASSWORD', webImEnv('JC_WEB_IM_DB_PASSWORD', webImEnv('DB_PASSWORD', 'winchen@0904')));
define('IM_APP_DB_DSN', webImMysqlDsn(
webImFirstEnv(['JC_WEB_IM_APP_DB_HOST', 'DB_HOST_2', 'DB_HOST2_2'], webImEnv('DB_HOST', '127.0.0.1')),
webImFirstEnv(['JC_WEB_IM_APP_DB_PORT', 'DB_PORT_2', 'DB_PORT2_2'], webImEnv('DB_PORT', '3306')),
webImFirstEnv(['JC_WEB_IM_APP_DB_DATABASE', 'DB_DATABASE_2', 'DB_DATABASE2_2'], webImEnv('DB_DATABASE', 'appdata'))
));
define('IM_APP_DB_USER', webImFirstEnv(['JC_WEB_IM_APP_DB_USER', 'DB_USERNAME_2', 'DB_USERNAME2_2'], webImEnv('DB_USERNAME', 'winchen')));
define('IM_APP_DB_PASSWORD', webImFirstEnv(['JC_WEB_IM_APP_DB_PASSWORD', 'DB_PASSWORD_2', 'DB_PASSWORD2_2'], webImEnv('DB_PASSWORD', 'winchen@0904')));
define('IM_DB_TIMEZONE', webImEnv('JC_WEB_IM_DB_TIMEZONE', 'Asia/Bangkok'));
define('IM_ADMIN_URL', getenv('JC_WEB_IM_ADMIN_URL') ?: 'http://127.0.0.1:18080');
define('IM_ADMIN_SECRET', getenv('JC_WEB_IM_ADMIN_SECRET') ?: '123456');
const IM_DB_DSN = 'mysql:host=im-mysql-005.cbgumoq8g1ks.ap-southeast-1.rds.amazonaws.com;port=3306;dbname=zhongliao_wfchat;charset=utf8mb4';
const IM_DB_USER = 'zhongliaoMysql';
const IM_DB_PASSWORD = 'ZhongLiao@admin';
const IM_APP_DB_DSN = 'mysql:host=im-mysql-005.cbgumoq8g1ks.ap-southeast-1.rds.amazonaws.com;port=3306;dbname=zhongliao_app;charset=utf8mb4';
const IM_APP_DB_USER = 'zhongliaoMysql';
const IM_APP_DB_PASSWORD = 'ZhongLiao@admin';
const IM_DB_TIMEZONE = 'Asia/Shanghai';
function respond(int $code, string $message, array $result = []): void
{
@@ -355,31 +285,6 @@ function fetchWebUserRemarkMap(PDO $db, string $ownerId, array $targetIds): arra
return $remarks;
}
function fetchImFriendAliasMap(PDO $db, string $ownerId, array $friendIds): array
{
$friendIds = array_values(array_unique(array_filter(array_map(static function ($friendId): string {
return trim((string)$friendId);
}, $friendIds))));
if ($ownerId === '' || !$friendIds) {
return [];
}
$aliases = [];
foreach (array_chunk($friendIds, 500) as $chunk) {
$statement = $db->prepare(
'select `_friend_uid`, `_alias` from `t_friend`'
. ' where `_uid` = ? and `_friend_uid` in (' . webImPlaceholders($chunk) . ') and `_state` = 0'
);
$statement->execute(array_merge([$ownerId], $chunk));
foreach ($statement->fetchAll() as $row) {
$aliases[(string)$row['_friend_uid']] = trim((string)($row['_alias'] ?? ''));
}
}
return $aliases;
}
function saveWebUserRemark(PDO $db, string $ownerId, string $targetId, string $alias): void
{
if ($ownerId === '' || $targetId === '') {
+19 -3
View File
@@ -6,6 +6,18 @@ require __DIR__ . '/im_web_bootstrap.php';
const WEB_MEDIA_PROXY_MAX_BYTES = 15 * 1024 * 1024;
const WEB_MEDIA_PROXY_MAX_SECONDS = 25;
function mediaProxyEnv(string $name, string $default = ''): string
{
if (function_exists('webImEnv')) {
return (string)webImEnv($name, $default);
}
$value = getenv($name);
if ($value === false || trim((string)$value) === '') {
return $default;
}
return trim((string)$value);
}
function failMediaProxy(int $status, string $message): never
{
http_response_code($status);
@@ -18,12 +30,13 @@ function failMediaProxy(int $status, string $message): never
function mediaProxyAllowedHosts(): array
{
$configured = webImEnv('JC_WEB_IM_MEDIA_PROXY_HOSTS');
$configured = mediaProxyEnv('JC_WEB_IM_MEDIA_PROXY_HOSTS');
$hosts = array_map(
static fn(string $host): string => strtolower(rtrim(trim($host), '.')),
preg_split('/[,\s]+/', $configured) ?: []
);
$hosts[] = 'zhiyanim.dfpnm.cn';
return array_values(array_unique(array_filter($hosts)));
}
@@ -53,17 +66,20 @@ function validatedMediaProxyUrl(string $url): array
function mediaProxyCacheRoot(): string
{
$root = rtrim(webImEnv('JC_WEB_IM_MEDIA_CACHE_ROOT', '/var/cache/jc-web-im-media'), '/');
$root = rtrim(mediaProxyEnv('JC_WEB_IM_MEDIA_CACHE_ROOT', '/var/cache/jc-web-im-media'), '/');
if ($root === '' || !is_dir($root) || !is_writable($root)) {
$root = rtrim(sys_get_temp_dir(), '/') . '/jc-web-im-media';
if (!is_dir($root) && !@mkdir($root, 0755, true) && !is_dir($root)) {
failMediaProxy(503, '媒体缓存目录不可用');
}
}
return $root;
}
function mediaProxyPreferredIps(): array
{
$configured = preg_split('/[,\s]+/', webImEnv('JC_WEB_IM_MEDIA_PROXY_IPS')) ?: [];
$configured = preg_split('/[,\s]+/', mediaProxyEnv('JC_WEB_IM_MEDIA_PROXY_IPS')) ?: [];
$ips = [];
foreach ($configured as $ip) {
$ip = trim($ip);
+71
View File
@@ -0,0 +1,71 @@
<?php
declare(strict_types=1);
const WEB_MEDIA_STREAM_ROOT = '/opt/im-server/media';
function failMediaStream(int $status, string $message): never
{
http_response_code($status);
header('Content-Type: text/plain; charset=utf-8');
header('Cache-Control: no-store');
echo $message;
exit;
}
$url = trim((string)($_GET['url'] ?? ''));
if ($url === '') {
failMediaStream(400, '缺少视频地址');
}
$path = rawurldecode((string)(parse_url($url, PHP_URL_PATH) ?: ''));
if (!preg_match('#^/fs/[0-9]+/[A-Za-z0-9_./ -]+$#', $path) || str_contains($path, '..')) {
failMediaStream(400, '视频地址不合法');
}
$root = realpath(WEB_MEDIA_STREAM_ROOT);
$fullPath = realpath(rtrim(WEB_MEDIA_STREAM_ROOT, '/') . $path);
if ($root === false || $fullPath === false || !str_starts_with($fullPath, $root . DIRECTORY_SEPARATOR) || !is_file($fullPath)) {
failMediaStream(404, '视频文件不存在');
}
$size = (int)filesize($fullPath);
$mime = (string)(mime_content_type($fullPath) ?: 'video/mp4');
if (!str_starts_with($mime, 'video/')) {
$extension = strtolower((string)pathinfo($fullPath, PATHINFO_EXTENSION));
$mime = $extension === 'webm' ? 'video/webm' : ($extension === 'mov' ? 'video/quicktime' : 'video/mp4');
}
$start = 0;
$end = max(0, $size - 1);
$range = trim((string)($_SERVER['HTTP_RANGE'] ?? ''));
if ($range !== '' && preg_match('/^bytes=(\d*)-(\d*)$/', $range, $matches)) {
if ($matches[1] !== '') $start = (int)$matches[1];
if ($matches[2] !== '') $end = min($end, (int)$matches[2]);
if ($start < 0 || $start > $end || $start >= $size) {
header('Content-Range: bytes */' . $size);
failMediaStream(416, '请求范围无效');
}
http_response_code(206);
header('Content-Range: bytes ' . $start . '-' . $end . '/' . $size);
}
$length = $end - $start + 1;
header('Content-Type: ' . $mime);
header('Content-Length: ' . $length);
header('Accept-Ranges: bytes');
header('Content-Disposition: inline');
header('Cache-Control: public, max-age=86400');
header('X-Content-Type-Options: nosniff');
$stream = fopen($fullPath, 'rb');
if ($stream === false) failMediaStream(500, '视频文件无法读取');
fseek($stream, $start);
$remaining = $length;
while ($remaining > 0 && !feof($stream)) {
$chunk = fread($stream, min(1024 * 1024, $remaining));
if ($chunk === false || $chunk === '') break;
echo $chunk;
$remaining -= strlen($chunk);
flush();
}
fclose($stream);
+63
View File
@@ -95,6 +95,54 @@ function ensureMessageEditsTable(): void
);
}
function ensurePinnedMessagesTable(): void
{
$db = imAppDb();
$db->exec(
'create table if not exists `t_web_pinned_messages` ('
. '`user_id` varchar(64) not null,'
. '`conversation_type` varchar(16) not null,'
. '`target_id` varchar(128) not null,'
. '`message_uid` varchar(32) not null,'
. '`message_json` text null,'
. '`updated_at_ms` bigint not null,'
. 'primary key (`user_id`, `conversation_type`, `target_id`)'
. ') engine=InnoDB default charset=utf8mb4'
);
try {
$db->exec('alter table `t_web_pinned_messages` add column `message_json` text null after `message_uid`');
} catch (Throwable) {
// The column already exists.
}
}
function savePinnedMessage(string $userId, string $conversationType, string $targetId, string $messageUid, array $message): void
{
ensurePinnedMessagesTable();
$statement = imAppDb()->prepare(
'insert into `t_web_pinned_messages` (`user_id`, `conversation_type`, `target_id`, `message_uid`, `message_json`, `updated_at_ms`)'
. ' values (?, ?, ?, ?, ?, ?) on duplicate key update `message_uid` = values(`message_uid`),'
. ' `message_json` = values(`message_json`), `updated_at_ms` = values(`updated_at_ms`)'
);
$statement->execute([
$userId,
$conversationType,
$targetId,
$messageUid,
json_encode($message, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
nowTimestampMs(),
]);
}
function removePinnedMessage(string $userId, string $conversationType, string $targetId): void
{
ensurePinnedMessagesTable();
$statement = imAppDb()->prepare(
'delete from `t_web_pinned_messages` where `user_id` = ? and `conversation_type` = ? and `target_id` = ?'
);
$statement->execute([$userId, $conversationType, $targetId]);
}
function editTextMessage(string $operatorId, string $messageUid, string $text): array
{
$row = fetchActionMessageRow($messageUid);
@@ -223,6 +271,21 @@ if ($action === '' || $messageUid <= 0) {
}
try {
if ($action === 'pin' || $action === 'unpin') {
if ($userId === '') respond(400, '缺少操作者ID');
$targetId = trim((string)($payload['target'] ?? ''));
$conversationType = trim((string)($payload['conversationType'] ?? 'single'));
if ($targetId === '') respond(400, '缺少会话ID');
$userId = resolveActionUserId($userId);
if ($action === 'pin') {
$message = is_array($payload['message'] ?? null) ? $payload['message'] : [];
savePinnedMessage($userId, $conversationType, $targetId, $messageUidText, $message);
} else {
removePinnedMessage($userId, $conversationType, $targetId);
}
respond(0, 'success', ['messageUid' => $messageUidText, 'action' => $action]);
}
if ($action === 'recall') {
if ($userId === '') {
respond(400, '缺少操作者ID');
+134 -18
View File
@@ -213,6 +213,9 @@ function attachmentFallbackText(?array $attachment): string
if ((string)$attachment['type'] === 'image') {
return '[图片]';
}
if ((string)$attachment['type'] === 'video') {
return '[视频]';
}
return '[文件] ' . ((string)($attachment['name'] ?? '') ?: '文件');
}
@@ -594,6 +597,7 @@ function formatWebGroupMessage(
'senderPortrait' => (string)($senderUser['_portrait'] ?? ''),
'senderProfile' => [
'uid' => $from,
'userId' => (string)($senderUser['_name'] ?? ''),
'displayName' => $senderName,
'rawName' => $senderRawName,
'contactAlias' => $senderContactAlias,
@@ -641,6 +645,9 @@ function nativeMediaUrlScore(string $url): int
if (preg_match('/\.(?:jpe?g|png|gif|webp|bmp|avif)$/i', $path)) {
$score += 30;
}
if (preg_match('/\.(?:mp4|mov|m4v|webm|avi|mkv|3gp)$/i', $path)) {
$score += 30;
}
if (strpos($path, 'image') !== false || strpos($path, 'media') !== false || strpos($path, 'upload') !== false) {
$score += 5;
}
@@ -691,11 +698,21 @@ function nativeAttachmentName(string $url, string $type): string
return $name;
}
return $type === 'image' ? '图片' : '文件';
return $type === 'image' ? '图片' : ($type === 'video' ? '视频' : '文件');
}
function nativeAttachmentMime(string $url, string $type): string
{
if ($type === 'video') {
$path = strtolower((string)(parse_url($url, PHP_URL_PATH) ?: ''));
if (preg_match('/\.webm$/', $path)) {
return 'video/webm';
}
if (preg_match('/\.(?:mov|m4v)$/', $path)) {
return 'video/quicktime';
}
return 'video/mp4';
}
if ($type !== 'image') {
return '';
}
@@ -730,7 +747,7 @@ function nativeAttachmentFromRow(array $row, ?array $attachment): ?array
}
$contentType = (int)($row['_content_type'] ?? 0);
if ($contentType !== 3 && $contentType !== 5) {
if (!in_array($contentType, [3, 5, 6], true)) {
return null;
}
@@ -739,7 +756,7 @@ function nativeAttachmentFromRow(array $row, ?array $attachment): ?array
return null;
}
$type = $contentType === 3 ? 'image' : 'file';
$type = $contentType === 3 ? 'image' : ($contentType === 6 ? 'video' : 'file');
return [
'type' => $type,
@@ -767,7 +784,7 @@ function nativeDisplayText(string $searchableText, int $contentType, bool $hasAt
{
$text = trim($searchableText);
if (isNativePlaceholderText($text, $contentType)) {
return '';
$text = '';
}
if ($text === '' && !$isRecalled) {
return nativeMessageFallbackText($contentType, $hasAttachment);
@@ -776,6 +793,29 @@ function nativeDisplayText(string $searchableText, int $contentType, bool $hasAt
return $text;
}
function nativeRedPacketFromText(string $text): ?array
{
$decoded = json_decode(trim($text), true);
if (!is_array($decoded)) {
return null;
}
$packet = $decoded['redPackets'] ?? $decoded['redPacket'] ?? null;
if (!is_array($packet)) {
return null;
}
return [
'id' => (string)($packet['id'] ?? ''),
'senderId' => (string)($packet['userId'] ?? $packet['senderId'] ?? ''),
'target' => (string)($packet['target'] ?? $decoded['target'] ?? ''),
'blessing' => trim((string)($packet['blessing'] ?? '')) ?: '恭喜发财,大吉大利',
'status' => (int)($packet['status'] ?? 0),
'expireTime' => (string)($packet['expireTime'] ?? ''),
'createDate' => (string)($packet['createDate'] ?? ''),
];
}
function nativeMessageFallbackText(int $contentType, bool $hasAttachment): string
{
if ($hasAttachment) {
@@ -784,6 +824,21 @@ function nativeMessageFallbackText(int $contentType, bool $hasAttachment): strin
if ($contentType === 5) {
return '[文件]';
}
if ($contentType === 6) {
return '[视频加载失败]';
}
if ($contentType === 90) {
return '[红包]';
}
if ($contentType === 92) {
return '以上是打招呼的内容';
}
if ($contentType === 93) {
return '你们已经是好友了,可以开始聊天了。';
}
if ($contentType === 105) {
return '[领取了红包]';
}
return '';
}
@@ -886,11 +941,19 @@ function formatNativeGroupMessage(
$messageId = (string)$row['_mid'];
$timestamp = timestampMs((string)($row['_dt'] ?? ''), $messageId);
$contentType = (int)($row['_content_type'] ?? 0);
$redPacket = nativeRedPacketFromText((string)($row['_searchable_key'] ?? ''));
if ($redPacket !== null) {
$contentType = 90;
}
$isRecalled = $contentType === 80;
$direction = $from === $currentUserId ? 'out' : 'in';
$attachment = nativeAttachmentFromRow($row, $attachment);
$messageType = $attachment ? (string)$attachment['type'] : (($contentType === 1 || $isRecalled) ? 'text' : 'unknown');
$text = nativeDisplayText((string)($row['_searchable_key'] ?? ''), $contentType, $attachment !== null, $isRecalled);
$messageType = $attachment
? (string)$attachment['type']
: (in_array($contentType, [1, 80, 90, 92, 93, 105], true) ? 'text' : 'unknown');
$text = $redPacket !== null
? '[红包]'
: nativeDisplayText((string)($row['_searchable_key'] ?? ''), $contentType, $attachment !== null, $isRecalled);
return [
'id' => $messageId,
@@ -902,6 +965,7 @@ function formatNativeGroupMessage(
'senderPortrait' => (string)($senderUser['_portrait'] ?? ''),
'senderProfile' => [
'uid' => $from,
'userId' => (string)($senderUser['_name'] ?? ''),
'displayName' => $senderName,
'rawName' => $senderRawName,
'contactAlias' => $senderContactAlias,
@@ -921,6 +985,7 @@ function formatNativeGroupMessage(
'contentType' => $contentType,
'text' => attachmentDisplayText($text, $attachment),
'attachment' => $attachment,
'redPacket' => $redPacket,
'status' => $isRecalled && $direction === 'out' ? 'recalled' : 'sent',
'deliveryStatus' => $direction === 'out' && !$isRecalled ? 'sent' : '',
'recalled' => $isRecalled,
@@ -1001,7 +1066,7 @@ function loadNativeGroupMessages(PDO $db, string $userId, string $groupId, int $
}
$table = imUserMessagesTable($userId);
$scanLimit = min(max($limit * 4, $limit), 400);
$scanLimit = min(max($limit * 4, $limit), 5000);
$statement = $db->prepare(
'select `_mid`, `_dt` from `' . $table . '`'
. ' where `_uid` = ? and `_type` = 1 and `_line` = 0 and `_target` = ?'
@@ -1325,13 +1390,21 @@ function formatMessage(
$messageId = (string)$row['_mid'];
$from = (string)$row['_from'];
$contentType = (int)($row['_content_type'] ?? 0);
$redPacket = nativeRedPacketFromText((string)($row['_searchable_key'] ?? ''));
if ($redPacket !== null) {
$contentType = 90;
}
$isRecalled = $contentType === 80;
$text = (string)($row['_searchable_key'] ?? '');
$timestamp = timestampMs((string)($row['_dt'] ?? ''), $messageId);
$direction = $from === $currentUserId ? 'out' : 'in';
$attachment = nativeAttachmentFromRow($row, $attachment);
$messageType = $attachment ? (string)$attachment['type'] : (($contentType === 1 || $isRecalled) ? 'text' : 'unknown');
$messageText = nativeDisplayText($text, $contentType, $attachment !== null, $isRecalled);
$messageType = $attachment
? (string)$attachment['type']
: (in_array($contentType, [1, 80, 90, 92, 93, 105], true) ? 'text' : 'unknown');
$messageText = $redPacket !== null
? '[红包]'
: nativeDisplayText($text, $contentType, $attachment !== null, $isRecalled);
$messageText = attachmentDisplayText($messageText, $attachment);
$editedAt = (int)($editState['editedAt'] ?? 0);
$activityTimestamp = messageActivityTimestamp($timestamp, $editState);
@@ -1348,9 +1421,12 @@ function formatMessage(
'target' => $peerId,
'direction' => $direction,
'type' => $messageType,
'contentType' => $attachment ? ((string)$attachment['type'] === 'image' ? 3 : 5) : $contentType,
'contentType' => $attachment
? ((string)$attachment['type'] === 'image' ? 3 : ((string)$attachment['type'] === 'video' ? 6 : 5))
: $contentType,
'text' => $messageText,
'attachment' => $attachment,
'redPacket' => $redPacket,
'status' => $isRecalled && $direction === 'out' ? 'recalled' : ($direction === 'out' ? $deliveryStatus : 'sent'),
'deliveryStatus' => $deliveryStatus,
'recalled' => $isRecalled,
@@ -1500,7 +1576,16 @@ function loadRecentConversations(PDO $db, string $userId, int $limit): array
'portrait' => (string)($users[$peerId]['_portrait'] ?? ''),
'avatarText' => mb_strtoupper(mb_substr($title, 0, 1, 'UTF-8'), 'UTF-8'),
'updatedAt' => $message ? $message['activityTimestamp'] : timestampMs((string)($userRow['_dt'] ?? ''), $messageId),
'raw' => ['type' => 'single', 'target' => $peerId, 'line' => 0],
'raw' => [
'type' => 'single',
'target' => $peerId,
'line' => 0,
'userId' => (string)($users[$peerId]['_name'] ?? $peerId),
'userUid' => $peerId,
'displayName' => (string)($users[$peerId]['_display_name'] ?? ''),
'mobile' => (string)($users[$peerId]['_mobile'] ?? ''),
'address' => (string)($users[$peerId]['_address'] ?? ''),
],
];
}
@@ -1526,20 +1611,51 @@ function messageSyncResult(
string $userId,
array $messages,
bool $includeConversations,
int $limit
int $limit,
string $targetId = '',
string $conversationType = 'single'
): array {
$result = ['messages' => $messages];
if ($includeConversations) {
$result['conversations'] = loadRecentConversations($db, $userId, $limit);
}
if ($targetId !== '') {
try {
imAppDb()->exec(
'create table if not exists `t_web_pinned_messages` ('
. '`user_id` varchar(64) not null, `conversation_type` varchar(16) not null,'
. '`target_id` varchar(128) not null, `message_uid` varchar(32) not null,'
. '`message_json` text null,'
. '`updated_at_ms` bigint not null, primary key (`user_id`, `conversation_type`, `target_id`)'
. ') engine=InnoDB default charset=utf8mb4'
);
try {
imAppDb()->exec('alter table `t_web_pinned_messages` add column `message_json` text null after `message_uid`');
} catch (Throwable) {
// The column already exists.
}
$statement = imAppDb()->prepare(
'select `message_uid`, `message_json` from `t_web_pinned_messages` where `user_id` = ? and `conversation_type` = ? and `target_id` = ? limit 1'
);
$statement->execute([$userId, $conversationType, $targetId]);
$pinnedRow = $statement->fetch();
$result['pinnedMessageUid'] = (string)($pinnedRow['message_uid'] ?? '');
$pinnedMessage = json_decode((string)($pinnedRow['message_json'] ?? ''), true);
$result['pinnedMessage'] = is_array($pinnedMessage) ? $pinnedMessage : null;
} catch (Throwable) {
$result['pinnedMessageUid'] = '';
$result['pinnedMessage'] = null;
}
}
return $result;
}
$payload = readJsonPayload();
$userId = trim((string)($payload['userId'] ?? ''));
$target = trim((string)($payload['target'] ?? ''));
$limit = clampLimit($payload['limit'] ?? 50, 50, 100);
$limit = clampLimit($payload['limit'] ?? 1000, 50, 1000);
$markRead = payloadBool($payload['markRead'] ?? false);
$includeConversations = payloadBool($payload['includeConversations'] ?? false);
$conversationType = normalizeConversationType($payload['conversationType'] ?? $payload['type'] ?? 0);
@@ -1561,7 +1677,7 @@ try {
$userId,
loadWebGroupMessages(imAppDb(), $userId, $target, $limit, $markRead),
$includeConversations,
$limit
$limit, $target, 'group'
));
}
if (isNativeGroupTarget($db, $target)) {
@@ -1570,7 +1686,7 @@ try {
$userId,
loadNativeGroupMessages($db, $userId, $target, $limit, $markRead),
$includeConversations,
$limit
$limit, $target, 'group'
));
}
respond(0, 'success', messageSyncResult(
@@ -1578,7 +1694,7 @@ try {
$userId,
[],
$includeConversations,
$limit
$limit, $target, 'group'
));
}
if (isWebGroupTarget(imAppDb(), $target)) {
@@ -1587,7 +1703,7 @@ try {
$userId,
loadWebGroupMessages(imAppDb(), $userId, $target, $limit, $markRead),
$includeConversations,
$limit
$limit, $target, 'group'
));
}
$targetId = resolveUserId($db, $target);
@@ -1596,7 +1712,7 @@ try {
$userId,
loadConversationMessages($db, $userId, $targetId, $limit, $markRead),
$includeConversations,
$limit
$limit, $targetId, 'single'
));
}
+1 -1
View File
@@ -7,7 +7,7 @@ header('Cache-Control: no-store');
require __DIR__ . '/im_web_bootstrap.php';
$defaultName = 'Web IM';
$defaultLogo = '/img/logo.ico';
$defaultLogo = '/img/logo.png';
try {
$statement = imAppDb()->prepare(
+141 -225
View File
@@ -6,21 +6,13 @@ header('Cache-Control: no-store');
require __DIR__ . '/im_web_bootstrap.php';
define(
'WEB_MEDIA_ROOT',
webImEnv(
'JC_WEB_IM_MEDIA_ROOT',
is_dir('/var/www/im/public/media')
? '/var/www/im/public/media'
: (is_dir('/var/www/IM/public/media') ? '/var/www/IM/public/media' : '/opt/im-server/media')
)
);
define('WEB_MEDIA_PUBLIC_PORT', (int)webImEnv('JC_WEB_IM_MEDIA_PORT', '80'));
const WEB_MEDIA_ROOT = '/opt/im-server/media';
const WEB_MEDIA_PUBLIC_PORT = 18000;
const WEB_MEDIA_TYPE_IMAGE = 1;
const WEB_MEDIA_TYPE_VIDEO = 3;
const WEB_MEDIA_TYPE_FILE = 4;
const WEB_IMAGE_MAX_BYTES = 10 * 1024 * 1024;
const WEB_FILE_MAX_BYTES = 50 * 1024 * 1024;
const WEB_MINIO_PROJECT_CODE = '001';
function isDailyMuteActive(string $dailyStart, string $dailyEnd, int $nowMs): bool
{
@@ -81,33 +73,6 @@ function isGroupMutedForSender(PDO $appDb, string $groupId, string $role, int $n
return $startsAtMs > 0 && $endsAtMs > $startsAtMs && $nowMs >= $startsAtMs && $nowMs < $endsAtMs;
}
function nativeGroupRoleFromType(mixed $type): string
{
$value = (int)$type;
if ($value === 2) {
return 'owner';
}
if ($value === 1) {
return 'admin';
}
return 'member';
}
function fetchNativeGroupForSender(PDO $db, string $sender, string $groupId): array
{
$statement = $db->prepare(
'select g.`_gid`, g.`_name`, g.`_mute`, g.`_deleted`, m.`_type` as `member_type`'
. ' from `t_group` g'
. ' join `t_group_member` m on m.`_gid` = g.`_gid`'
. ' where g.`_gid` = ? and g.`_deleted` = 0 and m.`_mid` = ? limit 1'
);
$statement->execute([$groupId, $sender]);
$group = $statement->fetch();
return is_array($group) ? $group : [];
}
function messageRequestValue(array $payload, string $key, string $default = ''): string
{
return trim((string)($_POST[$key] ?? $payload[$key] ?? $default));
@@ -190,114 +155,11 @@ function mediaPublicBaseUrl(): string
$isHttps = (string)($_SERVER['HTTPS'] ?? '') !== '' && strtolower((string)$_SERVER['HTTPS']) !== 'off';
$scheme = $isHttps ? 'https' : 'http';
$host = trim(preg_replace('/:\d+$/', '', (string)($_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? '127.0.0.1')) ?: '127.0.0.1');
$port = (int)WEB_MEDIA_PUBLIC_PORT;
if ($port <= 0 || ($scheme === 'http' && $port === 80) || ($scheme === 'https' && $port === 443)) {
return $scheme . '://' . $host;
}
return $scheme . '://' . $host . ':' . $port;
return $scheme . '://' . $host . ':' . WEB_MEDIA_PUBLIC_PORT;
}
function messageStorageConfig(): array
{
$config = ['enabled' => false, 'url' => ''];
foreach (['t_app_system_conf', 'system_conf'] as $table) {
try {
$statement = imAppDb()->query(
'select `conf_name`, `conf_value` from `' . $table . '`'
. " where lower(`conf_name`) in ('is_minioplus', 'minio_url') and `is_valid` = 1"
);
$rows = $statement->fetchAll();
if (!$rows) {
continue;
}
foreach ($rows as $row) {
$name = strtolower((string)($row['conf_name'] ?? ''));
if ($name === 'is_minioplus') {
$config['enabled'] = (string)($row['conf_value'] ?? '0') === '1';
} elseif ($name === 'minio_url') {
$config['url'] = rtrim(trim((string)($row['conf_value'] ?? '')), '/');
}
}
break;
} catch (Throwable $error) {
continue;
}
}
return $config;
}
function saveMessageAttachmentToMinio(
array $file,
string $attachmentType,
string $sender,
string $baseUrl
): array {
$size = (int)($file['size'] ?? 0);
$tmpName = (string)($file['tmp_name'] ?? '');
if ($tmpName === '' || !is_uploaded_file($tmpName)) {
throw new RuntimeException('文件上传失败');
}
$mime = detectedUploadMime($tmpName);
if ($attachmentType === 'image') {
$mime = normalizedImageUploadMime($tmpName, $mime);
}
$originalName = safeUploadName((string)($file['name'] ?? ($attachmentType === 'image' ? 'image.jpg' : 'file')));
$content = file_get_contents($tmpName);
if ($content === false) {
throw new RuntimeException('读取上传文件失败');
}
$requestBody = json_encode([
'projectCode' => WEB_MINIO_PROJECT_CODE,
'fileScene' => 'temp',
'fileName' => $originalName,
'contentType' => $mime,
'base64Content' => base64_encode($content),
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if (!is_string($requestBody)) {
throw new RuntimeException('生成图片上传请求失败');
}
$handle = curl_init($baseUrl . '/project-storage/upload');
curl_setopt_array($handle, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 8,
CURLOPT_TIMEOUT => 60,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: minio-' . WEB_MINIO_PROJECT_CODE . '-' . $sender,
],
CURLOPT_POSTFIELDS => $requestBody,
]);
$responseBody = curl_exec($handle);
$status = (int)curl_getinfo($handle, CURLINFO_RESPONSE_CODE);
$curlError = curl_error($handle);
curl_close($handle);
$response = is_string($responseBody) ? json_decode($responseBody, true) : null;
$data = is_array($response) && is_array($response['data'] ?? null) ? $response['data'] : [];
$url = trim((string)($data['previewUrl'] ?? $data['downloadUrl'] ?? ''));
if ($status < 200 || $status >= 300 || (int)($response['code'] ?? -1) !== 0 || $url === '') {
$message = trim((string)($response['message'] ?? ''));
throw new RuntimeException(
$message !== ''
? 'MinIO上传失败:' . $message
: 'MinIO上传失败' . ($curlError !== '' ? ':' . $curlError : '')
);
}
return [
'type' => $attachmentType,
'url' => $url,
'name' => $originalName,
'mime' => $mime,
'size' => $size,
'mediaType' => $attachmentType === 'image' ? WEB_MEDIA_TYPE_IMAGE : WEB_MEDIA_TYPE_FILE,
];
}
function saveMessageAttachmentFile(array $file, string $attachmentType, string $sender): array
function saveMessageAttachmentFile(array $file, string $attachmentType): array
{
if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
throw new RuntimeException('文件上传失败');
@@ -307,6 +169,10 @@ function saveMessageAttachmentFile(array $file, string $attachmentType, string $
if ($size <= 0 || $size > $maxSize) {
throw new RuntimeException($attachmentType === 'image' ? '图片不能超过10MB' : '文件不能超过50MB');
}
if (!is_dir(WEB_MEDIA_ROOT) || !is_writable(WEB_MEDIA_ROOT)) {
throw new RuntimeException('媒体存储目录不可写');
}
$tmpName = (string)($file['tmp_name'] ?? '');
if ($tmpName === '' || !is_uploaded_file($tmpName)) {
throw new RuntimeException('文件上传失败');
@@ -316,17 +182,6 @@ function saveMessageAttachmentFile(array $file, string $attachmentType, string $
$mime = normalizedImageUploadMime($tmpName, $mime);
}
$storage = messageStorageConfig();
if ($storage['enabled']) {
if ($storage['url'] === '') {
throw new RuntimeException('MinIO已开启但未配置服务地址');
}
return saveMessageAttachmentToMinio($file, $attachmentType, $sender, $storage['url']);
}
if (!is_dir(WEB_MEDIA_ROOT) || !is_writable(WEB_MEDIA_ROOT)) {
throw new RuntimeException('媒体存储目录不可写');
}
$mediaType = $attachmentType === 'image' ? WEB_MEDIA_TYPE_IMAGE : WEB_MEDIA_TYPE_FILE;
$datePath = 'fs/' . $mediaType . '/' . date('Y/m/d/H/i/s');
$targetDir = rtrim(WEB_MEDIA_ROOT, '/') . '/' . $datePath;
@@ -391,72 +246,37 @@ function storeMessageAttachment(
]);
}
function attachmentFromRequest(string $messageType, string $sender): ?array
function attachmentFromRequest(string $messageType): ?array
{
if (!in_array($messageType, ['image', 'file'], true)) {
if (!in_array($messageType, ['image', 'video', 'file'], true)) {
return null;
}
$forwardUrl = trim((string)($_POST['attachmentUrl'] ?? ''));
if ($forwardUrl !== '') {
$parts = parse_url($forwardUrl);
$scheme = strtolower((string)($parts['scheme'] ?? ''));
if (!in_array($scheme, ['http', 'https'], true) || empty($parts['host']) || strlen($forwardUrl) > 2048) {
respond(400, '媒体地址不合法');
}
$mime = trim((string)($_POST['attachmentMime'] ?? 'application/octet-stream'));
$name = safeUploadName((string)($_POST['attachmentName'] ?? ($messageType === 'image' ? '图片' : ($messageType === 'video' ? '视频.mp4' : '文件'))));
return [
'type' => $messageType,
'url' => $forwardUrl,
'name' => $name,
'mime' => $mime,
'size' => max(0, (int)($_POST['attachmentSize'] ?? 0)),
'mediaType' => $messageType === 'image' ? WEB_MEDIA_TYPE_IMAGE : ($messageType === 'video' ? WEB_MEDIA_TYPE_VIDEO : WEB_MEDIA_TYPE_FILE),
];
}
$attachmentFile = $_FILES['attachment'] ?? $_FILES['file'] ?? null;
if (!is_array($attachmentFile)) {
respond(400, '缺少上传文件');
}
return saveMessageAttachmentFile($attachmentFile, $messageType, $sender);
}
function messagePayloadBody(string $text, ?array $attachment): array
{
$pushContent = $text !== ''
? $text
: ($attachment
? ((string)$attachment['type'] === 'image' ? '[图片]' : '[文件] ' . (string)$attachment['name'])
: $text);
$payloadBody = [
'type' => $attachment ? ((string)$attachment['type'] === 'image' ? 3 : 5) : 1,
'searchableContent' => $pushContent,
'pushContent' => $pushContent,
'content' => $text,
'persistFlag' => 3,
];
if ($attachment) {
$payloadBody['mediaType'] = (int)$attachment['mediaType'];
$payloadBody['remoteMediaUrl'] = (string)$attachment['url'];
$payloadBody['extra'] = json_encode([
'name' => (string)$attachment['name'],
'mime' => (string)$attachment['mime'],
'size' => (int)$attachment['size'],
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
return $payloadBody;
}
function sendNativeGroupMessage(string $sender, string $target, string $text, ?array $attachment): array
{
$result = requireImSuccess(imAdminPost('/admin/message/send', [
'sender' => $sender,
'conv' => [
'type' => 1,
'target' => $target,
'line' => 0,
],
'payload' => messagePayloadBody($text, $attachment),
'userMessage' => true,
]), '原生群消息发送失败');
$messageUid = isset($result['messageUid']) ? (string)$result['messageUid'] : '';
$timestamp = (int)($result['timestamp'] ?? webImNowMs());
if ($attachment && $messageUid !== '') {
ensureWebImAppTables();
storeMessageAttachment(imAppDb(), $messageUid, 'group', $target, $sender, $attachment, $timestamp);
}
return [
'messageUid' => $messageUid !== '' ? $messageUid : null,
'timestamp' => $timestamp,
'attachment' => $attachment,
];
return saveMessageAttachmentFile($attachmentFile, $messageType);
}
$contentTypeHeader = (string)($_SERVER['CONTENT_TYPE'] ?? '');
@@ -468,9 +288,13 @@ $text = messageRequestValue($payload, 'text');
$messageType = messageRequestValue($payload, 'messageType', 'text');
$conversationType = $_POST['conversationType'] ?? $_POST['type'] ?? $payload['conversationType'] ?? $payload['type'] ?? 0;
$isGroupConversation = in_array((string)$conversationType, ['1', 'group', 'channel'], true);
$mentionedUserIds = $payload['mentionedUserIds'] ?? [];
$mentionedUserIds = is_array($mentionedUserIds)
? array_values(array_unique(array_filter(array_map(static fn($value): string => trim((string)$value), $mentionedUserIds))))
: [];
$attachment = null;
if ($sender === '' || $target === '' || ($text === '' && !in_array($messageType, ['image', 'file'], true))) {
if ($sender === '' || $target === '' || ($text === '' && !in_array($messageType, ['image', 'video', 'file'], true))) {
respond(400, '缺少发送者、接收者或消息内容');
}
@@ -488,16 +312,64 @@ try {
$memberStatement->execute([$target, $sender]);
$group = $memberStatement->fetch();
if (!$group) {
$nativeGroup = fetchNativeGroupForSender(imDb(), $sender, $target);
if (!$nativeGroup) {
// 手机端创建的原生群不一定存在于 Web 自建群表中,需回退检查 IM 群成员表。
$imDb = imDb();
$nativeGroupStatement = $imDb->prepare(
'select 1 from `t_group` where `_gid` = ? and `_deleted` = 0 limit 1'
);
$nativeGroupStatement->execute([$target]);
$nativeMemberStatement = $imDb->prepare(
'select `_type` from `t_group_member` where `_gid` = ? and `_mid` = ? limit 1'
);
$nativeMemberStatement->execute([$target, $sender]);
$nativeMemberType = $nativeMemberStatement->fetchColumn();
if (!$nativeGroupStatement->fetchColumn() || $nativeMemberType === false) {
respond(403, '你不在该群组中');
}
$attachment = attachmentFromRequest($messageType, $sender);
$nativeResult = sendNativeGroupMessage($sender, $target, $text, $attachment);
$attachment = attachmentFromRequest($messageType);
$pushContent = $text !== ''
? $text
: ($attachment
? ((string)$attachment['type'] === 'image' ? '[图片]' : ((string)$attachment['type'] === 'video' ? '[视频]' : '[文件] ' . (string)$attachment['name']))
: $text);
$payloadBody = [
'type' => $attachment ? ((string)$attachment['type'] === 'image' ? 3 : ((string)$attachment['type'] === 'video' ? 6 : 5)) : 1,
'searchableContent' => $pushContent,
'pushContent' => $pushContent,
'content' => $text,
'persistFlag' => 3,
];
if ($mentionedUserIds) {
$payloadBody['mentionedType'] = 1;
$payloadBody['mentionedTarget'] = $mentionedUserIds;
}
if ($attachment) {
$payloadBody['mediaType'] = (int)$attachment['mediaType'];
$payloadBody['remoteMediaUrl'] = (string)$attachment['url'];
$payloadBody['extra'] = json_encode([
'name' => (string)$attachment['name'],
'mime' => (string)$attachment['mime'],
'size' => (int)$attachment['size'],
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
$nativeResult = requireImSuccess(imAdminPost('/admin/message/send', [
'sender' => $sender,
'conv' => ['type' => 1, 'target' => $target, 'line' => 0],
'payload' => $payloadBody,
]), '原生群消息发送失败');
$messageUid = isset($nativeResult['messageUid']) ? (string)$nativeResult['messageUid'] : '';
$timestamp = (int)($nativeResult['timestamp'] ?? webImNowMs());
if ($attachment && $messageUid !== '') {
storeMessageAttachment($appDb, $messageUid, 'group', $target, $sender, $attachment, $timestamp);
}
$role = (int)$nativeMemberType === 2 ? 'owner' : ((int)$nativeMemberType === 1 ? 'admin' : 'member');
respond(0, 'success', [
...$nativeResult,
'senderRole' => nativeGroupRoleFromType($nativeGroup['member_type'] ?? 0),
'native' => true,
'messageUid' => $messageUid,
'timestamp' => $timestamp,
'senderRole' => $role,
'attachment' => $attachment,
'nativeError' => '',
]);
}
$category = (string)($group['category'] ?? 'group');
@@ -510,7 +382,7 @@ try {
if ($category !== 'channel' && isGroupMutedForSender($appDb, $target, $role, $now)) {
respond(403, '当前群组处于禁言时段');
}
$attachment = attachmentFromRequest($messageType, $sender);
$attachment = attachmentFromRequest($messageType);
$messageUid = webImMessageUid();
$insert = $appDb->prepare(
'insert into `t_web_group_messages`'
@@ -526,6 +398,31 @@ try {
$nativeError = '';
try {
$pushContent = $text !== ''
? $text
: ($attachment
? ((string)$attachment['type'] === 'image' ? '[图片]' : ((string)$attachment['type'] === 'video' ? '[视频]' : '[文件] ' . (string)$attachment['name']))
: $text);
$payloadBody = [
'type' => $attachment ? ((string)$attachment['type'] === 'image' ? 3 : ((string)$attachment['type'] === 'video' ? 6 : 5)) : 1,
'searchableContent' => $pushContent,
'pushContent' => $pushContent,
'content' => $text,
'persistFlag' => 3,
];
if ($mentionedUserIds) {
$payloadBody['mentionedType'] = 1;
$payloadBody['mentionedTarget'] = $mentionedUserIds;
}
if ($attachment) {
$payloadBody['mediaType'] = (int)$attachment['mediaType'];
$payloadBody['remoteMediaUrl'] = (string)$attachment['url'];
$payloadBody['extra'] = json_encode([
'name' => (string)$attachment['name'],
'mime' => (string)$attachment['mime'],
'size' => (int)$attachment['size'],
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
requireImSuccess(imAdminPost('/admin/message/send', [
'sender' => $sender,
'conv' => [
@@ -533,8 +430,7 @@ try {
'target' => $target,
'line' => 0,
],
'payload' => messagePayloadBody($text, $attachment),
'userMessage' => true,
'payload' => $payloadBody,
]), '原生群消息发送失败');
} catch (Throwable $error) {
$nativeError = $error->getMessage() ?: '原生群消息发送失败';
@@ -549,7 +445,28 @@ try {
]);
}
$attachment = attachmentFromRequest($messageType, $sender);
$attachment = attachmentFromRequest($messageType);
$pushContent = $text !== ''
? $text
: ($attachment
? ((string)$attachment['type'] === 'image' ? '[图片]' : ((string)$attachment['type'] === 'video' ? '[视频]' : '[文件] ' . (string)$attachment['name']))
: $text);
$payloadBody = [
'type' => $attachment ? ((string)$attachment['type'] === 'image' ? 3 : ((string)$attachment['type'] === 'video' ? 6 : 5)) : 1,
'searchableContent' => $pushContent,
'pushContent' => $pushContent,
'content' => $text,
'persistFlag' => 3,
];
if ($attachment) {
$payloadBody['mediaType'] = (int)$attachment['mediaType'];
$payloadBody['remoteMediaUrl'] = (string)$attachment['url'];
$payloadBody['extra'] = json_encode([
'name' => (string)$attachment['name'],
'mime' => (string)$attachment['mime'],
'size' => (int)$attachment['size'],
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
$result = requireImSuccess(imAdminPost('/admin/message/send', [
'sender' => $sender,
@@ -558,8 +475,7 @@ try {
'target' => $target,
'line' => 0,
],
'payload' => messagePayloadBody($text, $attachment),
'userMessage' => true,
'payload' => $payloadBody,
]), '发送失败');
$messageUid = isset($result['messageUid']) ? (string)$result['messageUid'] : '';
+9 -17
View File
@@ -1,21 +1,13 @@
(() => {
const protocol = window.location.protocol || 'http:';
const host = window.location.hostname || '127.0.0.1';
window.JC_WEB_IM_CONFIG = {
adminServer: `${protocol}//${host}:8100`,
appServer: `${protocol}//${host}:8888`,
window.JC_WEB_IM_CONFIG = {
adminServer: 'http://18.141.44.165:8100',
appServer: '/app-server',
qrAppServer: 'http://18.141.44.165:8888',
platformConfigApi: '/api/platform_config.php',
registerConfigApi: `${protocol}//${host}:8100/api/register-config`,
registerPhoneExistsApi: `${protocol}//${host}:8100/api/register-phone-exists`,
imServerHost: host,
registerConfigApi: 'http://18.141.44.165:8100/api/register-config',
imServerHost: '18.141.44.165',
imRoutePort: 80,
useWss: false,
wsPath: '/ws',
sdkMode: 'http',
syncIntervalMs: 15000,
sseEnabled: true,
sseTicketApi: '/api/sse_ticket.php',
sseUrl: '/ws-events'
};
})();
sdkMode: 'legacy-http',
syncIntervalMs: 2500
};
+18
View File
@@ -0,0 +1,18 @@
window.JC_WEB_IM_CONFIG = {
runtimeEnvironment: 'local',
adminServer: 'http://18.141.44.165:8100',
appServer: '/app-server',
qrAppServer: 'http://18.141.44.165:8888',
platformConfigApi: '/local-api/platform_config.php',
registerConfigApi: '/local-api/register_config.php',
registerPhoneExistsApi: 'http://18.141.44.165:8100/api/register-phone-exists',
imServerHost: '18.141.44.165',
imRoutePort: 80,
useWss: false,
wsPath: '/ws',
sdkMode: 'legacy-http',
syncIntervalMs: 2500,
sseEnabled: false,
sseTicketApi: '/local-api/sse_ticket.php',
sseUrl: '/ws-events'
};
+23
View File
@@ -0,0 +1,23 @@
(() => {
const protocol = window.location.protocol || 'http:';
const host = window.location.hostname || '18.141.44.165';
window.JC_WEB_IM_CONFIG = {
runtimeEnvironment: 'production',
adminServer: `${protocol}//${host}:8100`,
appServer: `${protocol}//${host}:8888`,
qrAppServer: `${protocol}//${host}:8888`,
platformConfigApi: '/api/platform_config.php',
registerConfigApi: `${protocol}//${host}:8100/api/register-config`,
registerPhoneExistsApi: `${protocol}//${host}:8100/api/register-phone-exists`,
imServerHost: host,
imRoutePort: 80,
useWss: false,
wsPath: '/ws',
sdkMode: 'legacy-http',
syncIntervalMs: 15000,
sseEnabled: true,
sseTicketApi: '/api/sse_ticket.php',
sseUrl: '/ws-events'
};
})();
+466 -161
View File
@@ -492,6 +492,183 @@ button {
background: var(--panel);
}
.documented-shell {
min-height: 100dvh;
display: grid;
grid-template-columns: 260px minmax(0, 1fr);
background:
radial-gradient(circle at top left, rgba(23, 125, 114, 0.08), transparent 28%),
linear-gradient(180deg, #f4f8f7 0%, #eef3f7 100%);
}
.documented-rail {
min-height: 0;
display: grid;
align-content: start;
gap: 14px;
padding: 24px 20px;
border-right: 1px solid var(--line);
background: rgba(255, 255, 255, 0.82);
backdrop-filter: blur(12px);
}
.documented-avatar {
width: 64px;
height: 64px;
display: grid;
place-items: center;
overflow: hidden;
border-radius: 16px;
background: #dff4ef;
color: var(--primary-strong);
font-size: 28px;
font-weight: 800;
}
.documented-avatar img {
width: 100%;
height: 100%;
-o-object-fit: cover;
object-fit: cover;
}
.documented-rail-copy {
display: grid;
gap: 4px;
}
.documented-rail-copy strong {
font-size: 16px;
}
.documented-rail-copy small {
color: var(--muted);
overflow-wrap: anywhere;
}
.documented-rail-button {
min-height: 40px;
padding: 0 14px;
border: 0;
border-radius: 10px;
background: var(--primary);
color: #fff;
font-weight: 700;
text-align: left;
}
.documented-rail-button.ghost {
border: 1px solid var(--line);
background: #fff;
color: var(--text);
}
.documented-main {
min-width: 0;
min-height: 0;
overflow: auto;
padding: 28px;
display: grid;
align-content: start;
gap: 18px;
}
.documented-header {
display: flex;
align-items: end;
justify-content: space-between;
gap: 18px;
}
.documented-header h1 {
margin: 0;
font-size: 28px;
}
.documented-header p {
margin: 6px 0 0;
color: var(--muted);
}
.documented-status {
min-width: 180px;
display: grid;
gap: 4px;
padding: 14px 16px;
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(255, 255, 255, 0.88);
}
.documented-status span {
color: var(--muted);
font-size: 12px;
}
.documented-status strong {
font-size: 15px;
}
.documented-card {
display: grid;
gap: 12px;
padding: 20px;
border: 1px solid var(--line);
border-radius: 16px;
background: rgba(255, 255, 255, 0.88);
box-shadow: 0 16px 36px rgba(24, 33, 47, 0.06);
}
.documented-card h2 {
margin: 0;
font-size: 18px;
}
.documented-text {
margin: 0;
color: var(--muted);
line-height: 1.6;
}
.documented-list {
margin: 0;
padding-left: 18px;
display: grid;
gap: 8px;
line-height: 1.55;
}
.documented-list.muted {
color: var(--muted);
}
.documented-meta {
margin: 0;
display: grid;
gap: 10px;
}
.documented-meta div {
display: grid;
grid-template-columns: 110px minmax(0, 1fr);
gap: 12px;
padding-top: 10px;
border-top: 1px solid var(--line);
}
.documented-meta dt {
color: var(--muted);
}
.documented-meta dd {
margin: 0;
overflow-wrap: anywhere;
}
.documented-password-panel {
width: min(100%, 360px);
}
.navigation-rail {
min-height: 0;
display: flex;
@@ -1096,6 +1273,44 @@ button {
background: #eaf3f1;
}
.conversation-item.pinned {
background: rgba(15, 118, 110, 0.055);
}
.conversation-pin {
display: inline-block;
margin-right: 5px;
color: #0f766e;
font-size: 12px;
transform: rotate(-25deg);
}
.conversation-context-menu {
position: fixed;
z-index: 1200;
min-width: 124px;
padding: 6px;
border: 1px solid #d7e0e8;
border-radius: 10px;
background: #fff;
box-shadow: 0 12px 30px rgba(15, 23, 42, 0.18);
}
.conversation-context-menu button {
width: 100%;
padding: 9px 12px;
border: 0;
border-radius: 7px;
background: transparent;
color: #1f2937;
text-align: left;
cursor: pointer;
}
.conversation-context-menu button:hover {
background: #eef7f6;
}
.favorite-item {
width: 100%;
display: grid;
@@ -1257,14 +1472,6 @@ button {
padding: 24px;
}
.empty-list-actions {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 8px;
margin-top: 8px;
}
.empty-chat {
min-height: 0;
padding: 24px;
@@ -1327,6 +1534,10 @@ button {
background: #eef2f5;
}
.chat-panel.has-pinned-message {
grid-template-rows: 72px auto minmax(0, 1fr) auto auto;
}
.contact-panel {
min-width: 0;
min-height: 0;
@@ -1925,17 +2136,6 @@ button {
font-size: 12px;
}
.group-member-row .group-member-role {
width: -moz-fit-content;
width: fit-content;
padding: 2px 7px;
border: 1px solid #b8d8d1;
border-radius: 5px;
background: #edf8f5;
color: var(--primary);
font-weight: 700;
}
.group-management-dialog {
width: min(520px, calc(100% - 32px));
}
@@ -1996,9 +2196,7 @@ button {
min-height: 0;
overflow: auto;
overscroll-behavior: contain;
padding: 24px 24px 72px;
scroll-padding-bottom: 72px;
scrollbar-gutter: stable;
padding: 24px;
}
.message-row {
@@ -2178,31 +2376,225 @@ button {
object-fit: contain;
}
.pinned-message-banner {
width: calc(100% - 28px);
height: 42px;
min-height: 42px;
margin: 8px 14px;
align-self: center;
display: grid;
grid-template-columns: auto auto minmax(0, 1fr) auto;
align-items: center;
gap: 8px;
padding: 8px 12px;
border: 1px solid #d5e2df;
border-radius: 9px;
background: #f7fbfa;
color: #52606d;
text-align: left;
cursor: pointer;
}
.pinned-message-banner strong {
color: #0f766e;
white-space: nowrap;
}
.pinned-message-preview {
min-width: 0;
display: flex;
align-items: center;
gap: 7px;
overflow: hidden;
}
.pinned-message-preview > span {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.pinned-message-preview img {
width: 28px;
height: 28px;
flex: 0 0 28px;
border-radius: 4px;
-o-object-fit: cover;
object-fit: cover;
}
.pinned-message-close {
padding: 0 4px;
color: #748091;
font-size: 20px;
}
.message-row.system {
justify-content: center;
padding-top: 5px;
padding-bottom: 5px;
}
.system-message-pill {
max-width: min(78%, 620px);
padding: 5px 12px;
border-radius: 5px;
background: #c8c8c8;
color: #fff;
font-size: 12px;
line-height: 1.45;
text-align: center;
}
.message-video {
display: block;
width: min(360px, 68vw);
max-height: 360px;
border-radius: 7px;
background: #111;
}
.mention-picker {
position: absolute;
left: 18px;
bottom: 112px;
z-index: 20;
width: min(320px, calc(100% - 36px));
max-height: 260px;
overflow-y: auto;
padding: 6px;
border: 1px solid #d7e0e8;
border-radius: 10px;
background: #fff;
box-shadow: 0 12px 32px rgb(15 23 42 / 18%);
}
.mention-picker button {
display: flex;
width: 100%;
align-items: center;
gap: 10px;
padding: 8px 10px;
border: 0;
border-radius: 7px;
background: transparent;
text-align: left;
}
.mention-picker button:hover {
background: #eef7f5;
}
.mention-picker img,
.mention-picker button > span {
width: 32px;
height: 32px;
border-radius: 7px;
-o-object-fit: cover;
object-fit: cover;
}
.mention-picker button > span {
display: grid;
place-items: center;
background: #dceaf3;
color: #23445c;
}
.red-packet-card {
width: min(320px, 68vw);
margin: -10px -12px -8px;
overflow: hidden;
border-radius: 7px;
background: #ff9f32;
color: #fff;
}
.red-packet-card-main {
display: flex;
align-items: center;
gap: 13px;
padding: 20px 18px 17px;
}
.red-packet-card-main > span:last-child {
display: grid;
gap: 7px;
}
.red-packet-card-main strong {
font-size: 17px;
font-weight: 700;
}
.red-packet-card-main small {
color: rgba(255, 255, 255, 0.9);
font-size: 13px;
}
.red-packet-icon,
.red-packet-mini-icon {
display: grid;
place-items: center;
flex: 0 0 auto;
border-radius: 3px;
background: #d92f27;
color: #ffd968;
font-weight: 800;
}
.red-packet-icon {
width: 34px;
height: 44px;
font-size: 17px;
}
.red-packet-card-footer {
padding: 9px 15px;
background: #fff;
color: #8a8f94;
font-size: 12px;
}
.red-packet-receipt {
display: flex;
align-items: center;
gap: 7px;
color: #69747d;
}
.red-packet-mini-icon {
width: 22px;
height: 28px;
font-size: 11px;
}
.image-viewer-backdrop {
position: fixed;
inset: 0;
z-index: 80;
display: grid;
place-items: center;
padding: 24px;
background: rgba(12, 18, 26, 0.58);
padding: 20px;
background: rgba(7, 12, 20, 0.82);
backdrop-filter: blur(6px);
}
.image-viewer-dialog {
width: min(880px, calc(100vw - 48px));
height: min(640px, calc(100vh - 48px));
min-width: 360px;
min-height: 280px;
max-width: calc(100vw - 48px);
max-height: calc(100vh - 48px);
width: min(920px, calc(100vw - 64px));
height: min(660px, calc(100vh - 64px));
min-width: 320px;
min-height: 260px;
max-width: calc(100vw - 64px);
max-height: calc(100vh - 64px);
display: grid;
grid-template-rows: 52px minmax(0, 1fr);
overflow: hidden;
resize: both;
border: 1px solid rgba(255, 255, 255, 0.18);
border-radius: 8px;
background: #101820;
box-shadow: 0 24px 70px rgba(0, 0, 0, 0.36);
border-radius: 14px;
background: #0b1119;
box-shadow: 0 28px 90px rgba(0, 0, 0, 0.56);
}
.image-viewer-toolbar {
@@ -2216,17 +2608,6 @@ button {
background: rgba(24, 33, 47, 0.94);
}
.image-viewer-title {
min-width: 0;
flex: 1;
overflow: hidden;
color: #f8fafc;
font-size: 13px;
font-weight: 700;
text-overflow: ellipsis;
white-space: nowrap;
}
.image-viewer-toolbar button {
width: 36px;
height: 36px;
@@ -2246,6 +2627,7 @@ button {
}
.image-viewer-stage {
position: relative;
min-width: 0;
min-height: 0;
display: grid;
@@ -2253,34 +2635,58 @@ button {
overflow: hidden;
background: #0c121a;
cursor: default;
touch-action: none;
}
.image-viewer-stage.zoomed {
cursor: grab;
.image-viewer-nav {
position: absolute;
top: 50%;
z-index: 2;
width: 52px;
height: 52px;
display: grid;
place-items: center;
border: 1px solid rgba(255, 255, 255, 0.18);
border-radius: 50%;
background: rgba(18, 27, 39, 0.76);
color: #fff;
font-size: 42px;
font-weight: 300;
line-height: 1;
transform: translateY(-50%);
cursor: pointer;
backdrop-filter: blur(5px);
}
.image-viewer-stage.dragging {
cursor: grabbing;
.image-viewer-nav:hover {
background: rgba(41, 57, 75, 0.94);
}
.image-viewer-prev {
left: 18px;
}
.image-viewer-next {
right: 18px;
}
.image-viewer-img {
max-width: calc(100% - 32px);
max-height: calc(100% - 32px);
position: absolute;
top: 20px;
left: 90px;
width: calc(100% - 180px);
height: calc(100% - 40px);
max-width: none;
max-height: none;
-o-object-fit: contain;
object-fit: contain;
transform-origin: center center;
transition: transform 0.08s ease-out;
transition: transform 0.12s ease-out;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
pointer-events: none;
}
.image-viewer-stage.dragging .image-viewer-img {
transition: none;
}
.sender-profile-backdrop {
position: fixed;
inset: 0;
@@ -2814,11 +3220,9 @@ button {
}
.composer-tools button {
width: 34px;
height: 34px;
display: grid;
place-items: center;
border: 1px solid transparent;
width: 32px;
height: 32px;
border: 0;
border-radius: 6px;
background: transparent;
color: var(--muted);
@@ -2829,105 +3233,6 @@ button {
background: #edf2f5;
}
.composer-tools button:disabled {
cursor: default;
opacity: 0.45;
}
.composer-attachment-preview {
display: flex;
gap: 8px;
padding: 10px 16px 0;
overflow-x: auto;
}
.composer-attachment-item {
position: relative;
width: 88px;
min-width: 88px;
height: 88px;
display: grid;
place-items: center;
overflow: hidden;
border: 1px solid var(--line);
border-radius: 8px;
background: #edf2f5;
}
.composer-attachment-item img {
width: 100%;
height: 100%;
display: block;
-o-object-fit: cover;
object-fit: cover;
}
.composer-attachment-file-icon {
color: var(--primary);
font-size: 30px;
}
.composer-attachment-name {
position: absolute;
right: 0;
bottom: 0;
left: 0;
overflow: hidden;
padding: 4px 6px;
background: rgba(18, 28, 40, 0.72);
color: #fff;
font-size: 10px;
text-overflow: ellipsis;
white-space: nowrap;
}
.composer-attachment-item > button {
position: absolute;
top: 4px;
right: 4px;
width: 24px;
height: 24px;
display: grid;
place-items: center;
border: 0;
border-radius: 50%;
background: rgba(18, 28, 40, 0.74);
color: #fff;
font-size: 17px;
line-height: 1;
}
.composer-tool-button {
border-color: rgba(23, 125, 114, 0.28);
background: rgba(23, 125, 114, 0.1);
color: var(--primary);
}
.composer-tool-button.file-tool {
border-color: rgba(216, 78, 63, 0.28);
background: rgba(216, 78, 63, 0.1);
color: var(--accent);
}
.composer-tool-button:hover {
border-color: currentColor;
background: rgba(23, 125, 114, 0.16);
}
.composer-tool-button.file-tool:hover {
background: rgba(216, 78, 63, 0.16);
}
.composer-tool-icon {
width: 22px;
height: 22px;
fill: none;
stroke: currentColor;
stroke-width: 1.9;
stroke-linecap: round;
stroke-linejoin: round;
}
.emoji-picker {
position: absolute;
left: 16px;
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 958 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

+1 -1
View File
@@ -1 +1 @@
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Web IM</title><link rel="icon" href="img/5IuOieu9PF8MJtp43kD2kCkdLVjVwDp7.ico"><script src="config/runtime-config.js"></script><script defer="defer" src="js/chunk-vendors.86756863.js"></script><script defer="defer" src="js/app.631b8b2d.js"></script><link href="css/app.2c52dabb.css" rel="stylesheet"></head><body><noscript>请启用 JavaScript 后使用 Web IM。</noscript><div id="app"></div></body></html>
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Web IM</title><link rel="icon" href="favicon.ico"><script src="config/runtime-config.production.js"></script><script defer="defer" src="js/chunk-vendors.d3ec3fbc.js"></script><script defer="defer" src="js/app.21e75967.js"></script><link href="css/app.0488f79e.css" rel="stylesheet"></head><body><noscript>请启用 JavaScript 后使用 Web IM。</noscript><div id="app"></div></body></html>
File diff suppressed because it is too large Load Diff
+1
View File
File diff suppressed because one or more lines are too long
-1
View File
File diff suppressed because one or more lines are too long
@@ -9191,7 +9191,7 @@ function finishComponentSetup(instance, isSSR, skipOptions) {
try {
applyOptions(instance);
} finally {
;(0,_vue_reactivity__WEBPACK_IMPORTED_MODULE_20__/* .resetTracking */ .bl)();
(0,_vue_reactivity__WEBPACK_IMPORTED_MODULE_20__/* .resetTracking */ .bl)();
reset();
}
}
@@ -9200,7 +9200,7 @@ function finishComponentSetup(instance, isSSR, skipOptions) {
}
const attrsProxyHandlers = false ? 0 : {
get(target, key) {
;(0,_vue_reactivity__WEBPACK_IMPORTED_MODULE_20__/* .track */ .u4)(target, "get", "");
(0,_vue_reactivity__WEBPACK_IMPORTED_MODULE_20__/* .track */ .u4)(target, "get", "");
return target[key];
}
};
@@ -10813,7 +10813,7 @@ function createInvoker(initialValue, instance) {
} else if (e._vts <= invoker.attached) {
return;
}
;(0,_vue_runtime_core__WEBPACK_IMPORTED_MODULE_18__/* .callWithAsyncErrorHandling */ .qL)(patchStopImmediatePropagation(e, invoker.value), instance, 5, [e]);
(0,_vue_runtime_core__WEBPACK_IMPORTED_MODULE_18__/* .callWithAsyncErrorHandling */ .qL)(patchStopImmediatePropagation(e, invoker.value), instance, 5, [e]);
};
invoker.value = initialValue;
invoker.attached = getNow();
@@ -14701,7 +14701,7 @@ module.exports = function (it) {
/***/ }),
/***/ 5844:
/***/ 3463:
/***/ (function(module) {
"use strict";
@@ -18200,7 +18200,7 @@ module.exports = function (key) {
var globalThis = __webpack_require__(4576);
var uncurryThis = __webpack_require__(9504);
var anObjectOrUndefined = __webpack_require__(3972);
var aString = __webpack_require__(5844);
var aString = __webpack_require__(3463);
var hasOwn = __webpack_require__(9297);
var base64Map = __webpack_require__(2804);
var getAlphabetOption = __webpack_require__(944);
@@ -19436,7 +19436,7 @@ if (Uint8Array) $({ target: 'Uint8Array', proto: true, forced: INCORRECT_BEHAVIO
var $ = __webpack_require__(6518);
var globalThis = __webpack_require__(4576);
var aString = __webpack_require__(5844);
var aString = __webpack_require__(3463);
var anUint8Array = __webpack_require__(4154);
var notDetached = __webpack_require__(5169);
var $fromHex = __webpack_require__(2303);
@@ -23270,7 +23270,7 @@ const isThenable = thing => thing && (isObject(thing) || isFunction(thing)) && i
/* harmony import */ var core_js_modules_es_set_is_superset_of_v2_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(2475);
/* harmony import */ var core_js_modules_es_set_symmetric_difference_v2_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(5024);
/* harmony import */ var core_js_modules_es_set_union_v2_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(1698);
/* harmony import */ var vue_demi__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(3463);
/* harmony import */ var vue_demi__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(7958);
/* harmony import */ var vue_demi__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(6768);
/* harmony import */ var vue_demi__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(144);
@@ -25041,7 +25041,7 @@ const PiniaVuePlugin = function (_Vue) {
/***/ }),
/***/ 3463:
/***/ 7958:
/***/ (function(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
"use strict";
@@ -25077,4 +25077,4 @@ function del(target, key) {
/***/ })
}]);
//# sourceMappingURL=chunk-vendors.86756863.js.map
//# sourceMappingURL=chunk-vendors.d3ec3fbc.js.map
File diff suppressed because one or more lines are too long
+11407
View File
File diff suppressed because it is too large Load Diff
+7 -2
View File
@@ -3,15 +3,20 @@
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve --host 0.0.0.0 --port 8023",
"build": "vue-cli-service build",
"serve": "vue-cli-service serve --mode development --host 0.0.0.0 --port 8026",
"serve:local": "vue-cli-service serve --mode development --host 0.0.0.0 --port 8026",
"build": "vue-cli-service build --mode production",
"build:local": "vue-cli-service build --mode development --dest dist-local",
"build:production": "vue-cli-service build --mode production",
"lint": "vue-cli-service lint"
},
"dependencies": {
"@vueuse/core": "^10.8.0",
"axios": "1.6.7",
"buffer": "^6.0.3",
"jr-qrcode": "^1.1.4",
"pinia": "^2.1.7",
"process": "^0.11.10",
"vue": "3.5.13",
"vue-router": "^4.3.0"
},
BIN
View File
Binary file not shown.
+10 -6
View File
@@ -34,11 +34,6 @@ try {
} catch (Throwable) {
$remarkMap = [];
}
try {
$friendAliasMap = fetchImFriendAliasMap(imDb(), $userId, $friendIds);
} catch (Throwable) {
$friendAliasMap = [];
}
$contactsByUid = [];
foreach (array_values(array_filter($usersResult['userInfos'] ?? [], 'is_array')) as $user) {
@@ -46,7 +41,16 @@ try {
if ($uid === '' || isset($contactsByUid[$uid])) {
continue;
}
$alias = $friendAliasMap[$uid] ?? '';
$alias = '';
try {
$aliasResult = requireImSuccess(
imAdminPost('/admin/friend/get_alias', ['operator' => $userId, 'targetId' => $uid]),
'联系人备注加载失败'
);
$alias = trim((string)($aliasResult['alias'] ?? ''));
} catch (Throwable $error) {
$alias = '';
}
if ($alias === '') {
$alias = $remarkMap[$uid] ?? '';
}
+69 -194
View File
@@ -70,8 +70,6 @@ function webGroupConversation(array $group, string $role = 'member'): array
'line' => 0,
'category' => $category,
'role' => $role,
'nativeStatus' => (string)($group['native_status'] ?? ''),
'nativeError' => (string)($group['native_error'] ?? ''),
],
];
}
@@ -178,48 +176,6 @@ function createNativeGroup(string $operator, string $groupId, string $name, stri
]), '原生群组创建失败');
}
function fetchNativeGroupInfo(string $groupKey): array
{
$payloads = [
['group_id' => $groupKey],
['groupId' => $groupKey],
['target_id' => $groupKey],
];
$lastError = null;
foreach ($payloads as $payload) {
try {
return requireImSuccess(imAdminPost('/admin/group/get_info', $payload), '群组不存在');
} catch (Throwable $error) {
$lastError = $error;
}
}
throw new RuntimeException($lastError ? ($lastError->getMessage() ?: '群组不存在') : '群组不存在');
}
function nativeGroupInfoValue(array $native, string $key, string $fallback = ''): string
{
$sources = [$native];
if (is_array($native['group_info'] ?? null)) {
$sources[] = $native['group_info'];
}
if (is_array($native['group'] ?? null)) {
$sources[] = $native['group'];
if (is_array($native['group']['group_info'] ?? null)) {
$sources[] = $native['group']['group_info'];
}
}
foreach ($sources as $source) {
if (isset($source[$key]) && (string)$source[$key] !== '') {
return (string)$source[$key];
}
}
return $fallback;
}
function addNativeGroupMember(string $operator, string $groupId, string $userId): void
{
requireImSuccess(imAdminPost('/admin/group/member/add', [
@@ -469,134 +425,37 @@ function currentMuteSetting(PDO $appDb, string $groupId): array
];
}
function nativeGroupRoleFromType(mixed $type): string
{
$value = (int)$type;
if ($value === 2) {
return 'owner';
}
if ($value === 1) {
return 'admin';
}
return 'member';
}
function fetchNativeGroupWithMember(PDO $imDb, string $groupId, string $userId): array
{
$statement = $imDb->prepare(
'select g.*, m.`_type` as `member_type`, m.`_alias` as `member_alias`'
. ' from `t_group` g'
. ' join `t_group_member` m on m.`_gid` = g.`_gid`'
. ' where g.`_gid` = ? and g.`_deleted` = 0 and m.`_mid` = ? limit 1'
);
$statement->execute([$groupId, $userId]);
$group = $statement->fetch();
return is_array($group) ? $group : [];
}
function ensureNativeGroupMember(PDO $imDb, string $groupId, string $userId): array
{
$group = fetchNativeGroupWithMember($imDb, $groupId, $userId);
if ($group) {
return $group;
}
$exists = $imDb->prepare('select 1 from `t_group` where `_gid` = ? and `_deleted` = 0 limit 1');
$exists->execute([$groupId]);
if ($exists->fetchColumn()) {
respond(403, '你不在该群组中');
}
respond(404, '没有找到该群组');
}
function nativeGroupDetailAction(PDO $imDb, string $userId, string $groupId): array
{
$group = ensureNativeGroupMember($imDb, $groupId, $userId);
$ownerId = (string)($group['_owner'] ?? '');
$users = fetchWebUserMap($imDb, [$ownerId, $userId], $userId);
$owner = $users[$ownerId] ?? ['uid' => $ownerId, 'displayName' => $ownerId, 'contactAlias' => ''];
$me = $users[$userId] ?? ['uid' => $userId, 'displayName' => $userId];
$myAlias = (string)($group['member_alias'] ?? '');
return [
'group' => [
'groupId' => (string)$group['_gid'],
'name' => (string)($group['_name'] ?? ''),
'category' => 'group',
'announcement' => '',
'welcomeText' => '',
'ownerUid' => $ownerId,
'ownerName' => (string)($owner['contactAlias'] ?? '') !== '' ? (string)$owner['contactAlias'] : (string)$owner['displayName'],
'myRole' => nativeGroupRoleFromType($group['member_type'] ?? 0),
'myAlias' => $myAlias,
'myDisplayName' => $myAlias !== '' ? $myAlias : (string)$me['displayName'],
'muteSetting' => [
'mode' => 'off',
'scheduleType' => 'once',
'startsAtMs' => 0,
'endsAtMs' => 0,
'dailyStart' => '',
'dailyEnd' => '',
'enabled' => false,
],
'native' => true,
],
];
}
function nativeGroupMembersAction(PDO $imDb, string $userId, string $groupId): array
{
ensureNativeGroupMember($imDb, $groupId, $userId);
$statement = $imDb->prepare(
'select `_mid`, `_alias`, `_type`, `_create_dt` from `t_group_member`'
. ' where `_gid` = ? order by (`_type` = 2) desc, (`_type` = 1) desc, `_create_dt` asc limit 500'
);
$statement->execute([$groupId]);
$members = $statement->fetchAll();
$users = fetchWebUserMap($imDb, array_column($members, '_mid'), $userId);
return [
'members' => array_map(static function (array $member) use ($users): array {
$uid = (string)$member['_mid'];
$user = $users[$uid] ?? [
'uid' => $uid,
'displayName' => $uid,
'mobile' => '',
'portrait' => '',
'contactAlias' => '',
'friendAlias' => '',
'remarkAlias' => '',
'isContact' => false,
];
$alias = trim((string)($member['_alias'] ?? ''));
$contactAlias = trim((string)($user['contactAlias'] ?? ''));
return [
'uid' => $uid,
'role' => nativeGroupRoleFromType($member['_type'] ?? 0),
'alias' => $alias,
'contactAlias' => $contactAlias,
'friendAlias' => trim((string)($user['friendAlias'] ?? '')),
'remarkAlias' => trim((string)($user['remarkAlias'] ?? '')),
'isContact' => (bool)($user['isContact'] ?? false),
'displayName' => $contactAlias !== '' ? $contactAlias : ($alias !== '' ? $alias : (string)$user['displayName']),
'rawDisplayName' => (string)$user['displayName'],
'groupDisplayName' => $alias,
'mobile' => (string)($user['mobile'] ?? ''),
'portrait' => (string)($user['portrait'] ?? ''),
];
}, $members),
];
}
function groupDetailAction(PDO $imDb, PDO $appDb, string $userId, string $groupId): array
{
$group = fetchWebGroup($appDb, $groupId);
if (!$group) {
return nativeGroupDetailAction($imDb, $userId, $groupId);
$groupStatement = $imDb->prepare('select * from `t_group` where `_gid` = ? and `_deleted` = 0 limit 1');
$groupStatement->execute([$groupId]);
$nativeGroup = $groupStatement->fetch();
$memberStatement = $imDb->prepare('select `_type`, `_alias` from `t_group_member` where `_gid` = ? and `_mid` = ? limit 1');
$memberStatement->execute([$groupId, $userId]);
$nativeMember = $memberStatement->fetch();
if (!$nativeGroup || !$nativeMember) {
respond(403, '你不在该群组中');
}
$ownerStatement = $imDb->prepare('select `_mid` from `t_group_member` where `_gid` = ? and `_type` = 2 limit 1');
$ownerStatement->execute([$groupId]);
$ownerId = (string)($ownerStatement->fetchColumn() ?: '');
$users = fetchWebUserMap($imDb, array_filter([$ownerId, $userId]), $userId);
return ['group' => [
'groupId' => $groupId,
'publicId' => (string)($nativeGroup['id'] ?? ''),
'name' => (string)($nativeGroup['_name'] ?? $groupId),
'category' => 'group',
'announcement' => (string)($nativeGroup['_bulletin'] ?? ''),
'welcomeText' => '',
'ownerUid' => $ownerId,
'ownerName' => (string)($users[$ownerId]['displayName'] ?? $ownerId),
'myRole' => ((int)($nativeMember['_type'] ?? 0) === 2 ? 'owner' : ((int)($nativeMember['_type'] ?? 0) === 1 ? 'admin' : 'member')),
'myAlias' => (string)($nativeMember['_alias'] ?? ''),
'myDisplayName' => (string)($nativeMember['_alias'] ?? '') ?: (string)($users[$userId]['displayName'] ?? $userId),
'muteSetting' => ['enabled' => false, 'mode' => 'off'],
]];
}
$member = fetchWebGroupMember($appDb, $groupId, $userId);
if (!$member) {
@@ -612,6 +471,7 @@ function groupDetailAction(PDO $imDb, PDO $appDb, string $userId, string $groupI
return [
'group' => [
'groupId' => (string)$group['group_id'],
'publicId' => (string)($group['id'] ?? ''),
'name' => (string)$group['name'],
'category' => (string)$group['category'],
'announcement' => (string)($group['announcement'] ?? ''),
@@ -629,7 +489,38 @@ function groupDetailAction(PDO $imDb, PDO $appDb, string $userId, string $groupI
function groupMembersAction(PDO $imDb, PDO $appDb, string $userId, string $groupId): array
{
if (!fetchWebGroupMember($appDb, $groupId, $userId)) {
return nativeGroupMembersAction($imDb, $userId, $groupId);
$membership = $imDb->prepare('select 1 from `t_group_member` where `_gid` = ? and `_mid` = ? limit 1');
$membership->execute([$groupId, $userId]);
if (!$membership->fetchColumn()) {
respond(403, '你不在该群组中');
}
$nativeStatement = $imDb->prepare(
'select `_mid` as `user_id`, `_type`, `_alias`, `_create_dt` from `t_group_member`'
. ' where `_gid` = ? order by (`_type` = 2) desc, `_create_dt` asc'
);
$nativeStatement->execute([$groupId]);
$nativeMembers = $nativeStatement->fetchAll();
$nativeUsers = fetchWebUserMap($imDb, array_column($nativeMembers, 'user_id'), $userId);
return ['members' => array_map(static function (array $member) use ($nativeUsers): array {
$uid = (string)$member['user_id'];
$user = $nativeUsers[$uid] ?? ['displayName' => $uid, 'mobile' => '', 'portrait' => '', 'isContact' => false];
$alias = trim((string)($member['_alias'] ?? ''));
$type = (int)($member['_type'] ?? 0);
return [
'uid' => $uid,
'role' => $type === 2 ? 'owner' : ($type === 1 ? 'admin' : 'member'),
'alias' => $alias,
'contactAlias' => trim((string)($user['contactAlias'] ?? '')),
'friendAlias' => trim((string)($user['friendAlias'] ?? '')),
'remarkAlias' => trim((string)($user['remarkAlias'] ?? '')),
'isContact' => (bool)($user['isContact'] ?? false),
'displayName' => trim((string)($user['contactAlias'] ?? '')) ?: ($alias ?: (string)$user['displayName']),
'rawDisplayName' => (string)$user['displayName'],
'groupDisplayName' => $alias,
'mobile' => (string)($user['mobile'] ?? ''),
'portrait' => (string)($user['portrait'] ?? ''),
];
}, $nativeMembers)];
}
$statement = $appDb->prepare(
@@ -679,10 +570,7 @@ function updateGroupAliasAction(PDO $appDb, string $userId, string $groupId, str
respond(400, '本群昵称过长');
}
if (!fetchWebGroupMember($appDb, $groupId, $userId)) {
ensureNativeGroupMember(imDb(), $groupId, $userId);
$update = imDb()->prepare('update `t_group_member` set `_alias` = ? where `_gid` = ? and `_mid` = ?');
$update->execute([$alias, $groupId, $userId]);
return ['alias' => $alias];
respond(403, '你不在该群组中');
}
$now = webImNowMs();
@@ -951,16 +839,8 @@ function joinWebGroupAction(PDO $appDb, string $userId, string $groupKey): array
$group = fetchWebGroup($appDb, $groupKey);
if (!$group) {
try {
$native = fetchNativeGroupInfo($groupKey);
$native = requireImSuccess(imAdminPost('/admin/group/get_info', ['groupId' => $groupKey]), '群组不存在');
$now = webImNowMs();
$nativeGroupId = nativeGroupInfoValue(
$native,
'target_id',
nativeGroupInfoValue($native, 'targetId', nativeGroupInfoValue($native, 'group_id', nativeGroupInfoValue($native, 'groupId', $groupKey)))
);
$nativeName = nativeGroupInfoValue($native, 'name', $nativeGroupId);
$nativePortrait = nativeGroupInfoValue($native, 'portrait', '');
$nativeOwner = nativeGroupInfoValue($native, 'owner', nativeGroupInfoValue($native, 'owner_uid', nativeGroupInfoValue($native, 'ownerUid', '')));
$statement = $appDb->prepare(
'insert into `t_web_groups`'
. ' (`group_id`, `category`, `name`, `portrait`, `owner_uid`, `join_mode`, `announcement`,'
@@ -969,38 +849,33 @@ function joinWebGroupAction(PDO $appDb, string $userId, string $groupKey): array
. ' on duplicate key update `updated_at_ms` = values(`updated_at_ms`)'
);
$statement->execute([
$nativeGroupId,
$nativeName,
$nativePortrait,
$nativeOwner,
$nativeGroupId,
$groupKey,
(string)($native['name'] ?? $groupKey),
(string)($native['portrait'] ?? ''),
(string)($native['owner'] ?? ''),
$groupKey,
$userId,
$now,
$now,
]);
$group = fetchWebGroup($appDb, $nativeGroupId);
$group = fetchWebGroup($appDb, $groupKey);
} catch (Throwable) {
respond(404, '没有找到该群组');
}
}
$groupId = (string)$group['group_id'];
$nativeStatus = (string)($group['native_status'] ?? '');
$nativeError = (string)($group['native_error'] ?? '');
upsertWebGroupMember($appDb, $groupId, $userId, 'member');
try {
addNativeGroupMember((string)($group['owner_uid'] ?: $userId), $groupId, $userId);
} catch (Throwable $error) {
$nativeStatus = $nativeStatus === 'ok' ? 'partial' : ($nativeStatus ?: 'fallback');
$nativeError = mb_substr($error->getMessage() ?: '加入原生群组失败', 0, 255, 'UTF-8');
// Web membership is authoritative for this web build; native group sync is best-effort.
}
$role = fetchWebGroupRole($appDb, $groupId, $userId);
return [
'group' => fetchWebGroup($appDb, $groupId),
'conversation' => webGroupConversation($group, $role),
'nativeStatus' => $nativeStatus,
'nativeError' => $nativeError,
];
}
+9 -104
View File
@@ -1,85 +1,15 @@
<?php
declare(strict_types=1);
function webImEnv(string $key, string $fallback = ''): string
{
$runtimeValue = getenv($key);
if ($runtimeValue !== false && $runtimeValue !== '') {
return $runtimeValue;
}
static $env = null;
if ($env === null) {
$env = [];
$paths = array_filter([
getenv('JC_WEB_IM_ENV_FILE') ?: '',
dirname(__DIR__, 2) . '/.env',
'/var/www/im-admin/.env',
'/var/www/im/.env',
]);
foreach ($paths as $path) {
if (!is_readable($path)) {
continue;
}
foreach (file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [] as $line) {
$line = trim($line);
if ($line === '' || strpos($line, '#') === 0 || strpos($line, '=') === false) {
continue;
}
[$name, $value] = array_map('trim', explode('=', $line, 2));
if ($name === '') {
continue;
}
$value = trim($value);
if (
strlen($value) >= 2
&& (($value[0] === '"' && substr($value, -1) === '"') || ($value[0] === "'" && substr($value, -1) === "'"))
) {
$value = substr($value, 1, -1);
}
$env[$name] = $value;
}
break;
}
}
return $env[$key] ?? $fallback;
}
function webImFirstEnv(array $keys, string $fallback = ''): string
{
foreach ($keys as $key) {
$value = webImEnv($key);
if ($value !== '') {
return $value;
}
}
return $fallback;
}
function webImMysqlDsn(string $host, string $port, string $database): string
{
return sprintf('mysql:host=%s;port=%s;dbname=%s;charset=utf8mb4', $host, $port, $database);
}
define('IM_ADMIN_URL', webImEnv('JC_WEB_IM_ADMIN_URL', 'http://127.0.0.1:18080'));
define('IM_ADMIN_SECRET', webImFirstEnv(['JC_WEB_IM_ADMIN_SECRET', 'SecretKey'], '123456'));
define('IM_DB_DSN', webImMysqlDsn(
webImEnv('JC_WEB_IM_DB_HOST', webImEnv('DB_HOST', '127.0.0.1')),
webImEnv('JC_WEB_IM_DB_PORT', webImEnv('DB_PORT', '3306')),
webImEnv('JC_WEB_IM_DB_DATABASE', webImEnv('DB_DATABASE', 'wfchat'))
));
define('IM_DB_USER', webImEnv('JC_WEB_IM_DB_USER', webImEnv('DB_USERNAME', 'winchen')));
define('IM_DB_PASSWORD', webImEnv('JC_WEB_IM_DB_PASSWORD', webImEnv('DB_PASSWORD', 'winchen@0904')));
define('IM_APP_DB_DSN', webImMysqlDsn(
webImFirstEnv(['JC_WEB_IM_APP_DB_HOST', 'DB_HOST_2', 'DB_HOST2_2'], webImEnv('DB_HOST', '127.0.0.1')),
webImFirstEnv(['JC_WEB_IM_APP_DB_PORT', 'DB_PORT_2', 'DB_PORT2_2'], webImEnv('DB_PORT', '3306')),
webImFirstEnv(['JC_WEB_IM_APP_DB_DATABASE', 'DB_DATABASE_2', 'DB_DATABASE2_2'], webImEnv('DB_DATABASE', 'appdata'))
));
define('IM_APP_DB_USER', webImFirstEnv(['JC_WEB_IM_APP_DB_USER', 'DB_USERNAME_2', 'DB_USERNAME2_2'], webImEnv('DB_USERNAME', 'winchen')));
define('IM_APP_DB_PASSWORD', webImFirstEnv(['JC_WEB_IM_APP_DB_PASSWORD', 'DB_PASSWORD_2', 'DB_PASSWORD2_2'], webImEnv('DB_PASSWORD', 'winchen@0904')));
define('IM_DB_TIMEZONE', webImEnv('JC_WEB_IM_DB_TIMEZONE', 'Asia/Bangkok'));
define('IM_ADMIN_URL', getenv('JC_WEB_IM_ADMIN_URL') ?: 'http://127.0.0.1:18080');
define('IM_ADMIN_SECRET', getenv('JC_WEB_IM_ADMIN_SECRET') ?: '123456');
const IM_DB_DSN = 'mysql:host=im-mysql-005.cbgumoq8g1ks.ap-southeast-1.rds.amazonaws.com;port=3306;dbname=zhongliao_wfchat;charset=utf8mb4';
const IM_DB_USER = 'zhongliaoMysql';
const IM_DB_PASSWORD = 'ZhongLiao@admin';
const IM_APP_DB_DSN = 'mysql:host=im-mysql-005.cbgumoq8g1ks.ap-southeast-1.rds.amazonaws.com;port=3306;dbname=zhongliao_app;charset=utf8mb4';
const IM_APP_DB_USER = 'zhongliaoMysql';
const IM_APP_DB_PASSWORD = 'ZhongLiao@admin';
const IM_DB_TIMEZONE = 'Asia/Shanghai';
function respond(int $code, string $message, array $result = []): void
{
@@ -355,31 +285,6 @@ function fetchWebUserRemarkMap(PDO $db, string $ownerId, array $targetIds): arra
return $remarks;
}
function fetchImFriendAliasMap(PDO $db, string $ownerId, array $friendIds): array
{
$friendIds = array_values(array_unique(array_filter(array_map(static function ($friendId): string {
return trim((string)$friendId);
}, $friendIds))));
if ($ownerId === '' || !$friendIds) {
return [];
}
$aliases = [];
foreach (array_chunk($friendIds, 500) as $chunk) {
$statement = $db->prepare(
'select `_friend_uid`, `_alias` from `t_friend`'
. ' where `_uid` = ? and `_friend_uid` in (' . webImPlaceholders($chunk) . ') and `_state` = 0'
);
$statement->execute(array_merge([$ownerId], $chunk));
foreach ($statement->fetchAll() as $row) {
$aliases[(string)$row['_friend_uid']] = trim((string)($row['_alias'] ?? ''));
}
}
return $aliases;
}
function saveWebUserRemark(PDO $db, string $ownerId, string $targetId, string $alias): void
{
if ($ownerId === '' || $targetId === '') {
+19 -3
View File
@@ -6,6 +6,18 @@ require __DIR__ . '/im_web_bootstrap.php';
const WEB_MEDIA_PROXY_MAX_BYTES = 15 * 1024 * 1024;
const WEB_MEDIA_PROXY_MAX_SECONDS = 25;
function mediaProxyEnv(string $name, string $default = ''): string
{
if (function_exists('webImEnv')) {
return (string)webImEnv($name, $default);
}
$value = getenv($name);
if ($value === false || trim((string)$value) === '') {
return $default;
}
return trim((string)$value);
}
function failMediaProxy(int $status, string $message): never
{
http_response_code($status);
@@ -18,12 +30,13 @@ function failMediaProxy(int $status, string $message): never
function mediaProxyAllowedHosts(): array
{
$configured = webImEnv('JC_WEB_IM_MEDIA_PROXY_HOSTS');
$configured = mediaProxyEnv('JC_WEB_IM_MEDIA_PROXY_HOSTS');
$hosts = array_map(
static fn(string $host): string => strtolower(rtrim(trim($host), '.')),
preg_split('/[,\s]+/', $configured) ?: []
);
$hosts[] = 'zhiyanim.dfpnm.cn';
return array_values(array_unique(array_filter($hosts)));
}
@@ -53,17 +66,20 @@ function validatedMediaProxyUrl(string $url): array
function mediaProxyCacheRoot(): string
{
$root = rtrim(webImEnv('JC_WEB_IM_MEDIA_CACHE_ROOT', '/var/cache/jc-web-im-media'), '/');
$root = rtrim(mediaProxyEnv('JC_WEB_IM_MEDIA_CACHE_ROOT', '/var/cache/jc-web-im-media'), '/');
if ($root === '' || !is_dir($root) || !is_writable($root)) {
$root = rtrim(sys_get_temp_dir(), '/') . '/jc-web-im-media';
if (!is_dir($root) && !@mkdir($root, 0755, true) && !is_dir($root)) {
failMediaProxy(503, '媒体缓存目录不可用');
}
}
return $root;
}
function mediaProxyPreferredIps(): array
{
$configured = preg_split('/[,\s]+/', webImEnv('JC_WEB_IM_MEDIA_PROXY_IPS')) ?: [];
$configured = preg_split('/[,\s]+/', mediaProxyEnv('JC_WEB_IM_MEDIA_PROXY_IPS')) ?: [];
$ips = [];
foreach ($configured as $ip) {
$ip = trim($ip);
+71
View File
@@ -0,0 +1,71 @@
<?php
declare(strict_types=1);
const WEB_MEDIA_STREAM_ROOT = '/opt/im-server/media';
function failMediaStream(int $status, string $message): never
{
http_response_code($status);
header('Content-Type: text/plain; charset=utf-8');
header('Cache-Control: no-store');
echo $message;
exit;
}
$url = trim((string)($_GET['url'] ?? ''));
if ($url === '') {
failMediaStream(400, '缺少视频地址');
}
$path = rawurldecode((string)(parse_url($url, PHP_URL_PATH) ?: ''));
if (!preg_match('#^/fs/[0-9]+/[A-Za-z0-9_./ -]+$#', $path) || str_contains($path, '..')) {
failMediaStream(400, '视频地址不合法');
}
$root = realpath(WEB_MEDIA_STREAM_ROOT);
$fullPath = realpath(rtrim(WEB_MEDIA_STREAM_ROOT, '/') . $path);
if ($root === false || $fullPath === false || !str_starts_with($fullPath, $root . DIRECTORY_SEPARATOR) || !is_file($fullPath)) {
failMediaStream(404, '视频文件不存在');
}
$size = (int)filesize($fullPath);
$mime = (string)(mime_content_type($fullPath) ?: 'video/mp4');
if (!str_starts_with($mime, 'video/')) {
$extension = strtolower((string)pathinfo($fullPath, PATHINFO_EXTENSION));
$mime = $extension === 'webm' ? 'video/webm' : ($extension === 'mov' ? 'video/quicktime' : 'video/mp4');
}
$start = 0;
$end = max(0, $size - 1);
$range = trim((string)($_SERVER['HTTP_RANGE'] ?? ''));
if ($range !== '' && preg_match('/^bytes=(\d*)-(\d*)$/', $range, $matches)) {
if ($matches[1] !== '') $start = (int)$matches[1];
if ($matches[2] !== '') $end = min($end, (int)$matches[2]);
if ($start < 0 || $start > $end || $start >= $size) {
header('Content-Range: bytes */' . $size);
failMediaStream(416, '请求范围无效');
}
http_response_code(206);
header('Content-Range: bytes ' . $start . '-' . $end . '/' . $size);
}
$length = $end - $start + 1;
header('Content-Type: ' . $mime);
header('Content-Length: ' . $length);
header('Accept-Ranges: bytes');
header('Content-Disposition: inline');
header('Cache-Control: public, max-age=86400');
header('X-Content-Type-Options: nosniff');
$stream = fopen($fullPath, 'rb');
if ($stream === false) failMediaStream(500, '视频文件无法读取');
fseek($stream, $start);
$remaining = $length;
while ($remaining > 0 && !feof($stream)) {
$chunk = fread($stream, min(1024 * 1024, $remaining));
if ($chunk === false || $chunk === '') break;
echo $chunk;
$remaining -= strlen($chunk);
flush();
}
fclose($stream);
+63
View File
@@ -95,6 +95,54 @@ function ensureMessageEditsTable(): void
);
}
function ensurePinnedMessagesTable(): void
{
$db = imAppDb();
$db->exec(
'create table if not exists `t_web_pinned_messages` ('
. '`user_id` varchar(64) not null,'
. '`conversation_type` varchar(16) not null,'
. '`target_id` varchar(128) not null,'
. '`message_uid` varchar(32) not null,'
. '`message_json` text null,'
. '`updated_at_ms` bigint not null,'
. 'primary key (`user_id`, `conversation_type`, `target_id`)'
. ') engine=InnoDB default charset=utf8mb4'
);
try {
$db->exec('alter table `t_web_pinned_messages` add column `message_json` text null after `message_uid`');
} catch (Throwable) {
// The column already exists.
}
}
function savePinnedMessage(string $userId, string $conversationType, string $targetId, string $messageUid, array $message): void
{
ensurePinnedMessagesTable();
$statement = imAppDb()->prepare(
'insert into `t_web_pinned_messages` (`user_id`, `conversation_type`, `target_id`, `message_uid`, `message_json`, `updated_at_ms`)'
. ' values (?, ?, ?, ?, ?, ?) on duplicate key update `message_uid` = values(`message_uid`),'
. ' `message_json` = values(`message_json`), `updated_at_ms` = values(`updated_at_ms`)'
);
$statement->execute([
$userId,
$conversationType,
$targetId,
$messageUid,
json_encode($message, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
nowTimestampMs(),
]);
}
function removePinnedMessage(string $userId, string $conversationType, string $targetId): void
{
ensurePinnedMessagesTable();
$statement = imAppDb()->prepare(
'delete from `t_web_pinned_messages` where `user_id` = ? and `conversation_type` = ? and `target_id` = ?'
);
$statement->execute([$userId, $conversationType, $targetId]);
}
function editTextMessage(string $operatorId, string $messageUid, string $text): array
{
$row = fetchActionMessageRow($messageUid);
@@ -223,6 +271,21 @@ if ($action === '' || $messageUid <= 0) {
}
try {
if ($action === 'pin' || $action === 'unpin') {
if ($userId === '') respond(400, '缺少操作者ID');
$targetId = trim((string)($payload['target'] ?? ''));
$conversationType = trim((string)($payload['conversationType'] ?? 'single'));
if ($targetId === '') respond(400, '缺少会话ID');
$userId = resolveActionUserId($userId);
if ($action === 'pin') {
$message = is_array($payload['message'] ?? null) ? $payload['message'] : [];
savePinnedMessage($userId, $conversationType, $targetId, $messageUidText, $message);
} else {
removePinnedMessage($userId, $conversationType, $targetId);
}
respond(0, 'success', ['messageUid' => $messageUidText, 'action' => $action]);
}
if ($action === 'recall') {
if ($userId === '') {
respond(400, '缺少操作者ID');
+134 -18
View File
@@ -213,6 +213,9 @@ function attachmentFallbackText(?array $attachment): string
if ((string)$attachment['type'] === 'image') {
return '[图片]';
}
if ((string)$attachment['type'] === 'video') {
return '[视频]';
}
return '[文件] ' . ((string)($attachment['name'] ?? '') ?: '文件');
}
@@ -594,6 +597,7 @@ function formatWebGroupMessage(
'senderPortrait' => (string)($senderUser['_portrait'] ?? ''),
'senderProfile' => [
'uid' => $from,
'userId' => (string)($senderUser['_name'] ?? ''),
'displayName' => $senderName,
'rawName' => $senderRawName,
'contactAlias' => $senderContactAlias,
@@ -641,6 +645,9 @@ function nativeMediaUrlScore(string $url): int
if (preg_match('/\.(?:jpe?g|png|gif|webp|bmp|avif)$/i', $path)) {
$score += 30;
}
if (preg_match('/\.(?:mp4|mov|m4v|webm|avi|mkv|3gp)$/i', $path)) {
$score += 30;
}
if (strpos($path, 'image') !== false || strpos($path, 'media') !== false || strpos($path, 'upload') !== false) {
$score += 5;
}
@@ -691,11 +698,21 @@ function nativeAttachmentName(string $url, string $type): string
return $name;
}
return $type === 'image' ? '图片' : '文件';
return $type === 'image' ? '图片' : ($type === 'video' ? '视频' : '文件');
}
function nativeAttachmentMime(string $url, string $type): string
{
if ($type === 'video') {
$path = strtolower((string)(parse_url($url, PHP_URL_PATH) ?: ''));
if (preg_match('/\.webm$/', $path)) {
return 'video/webm';
}
if (preg_match('/\.(?:mov|m4v)$/', $path)) {
return 'video/quicktime';
}
return 'video/mp4';
}
if ($type !== 'image') {
return '';
}
@@ -730,7 +747,7 @@ function nativeAttachmentFromRow(array $row, ?array $attachment): ?array
}
$contentType = (int)($row['_content_type'] ?? 0);
if ($contentType !== 3 && $contentType !== 5) {
if (!in_array($contentType, [3, 5, 6], true)) {
return null;
}
@@ -739,7 +756,7 @@ function nativeAttachmentFromRow(array $row, ?array $attachment): ?array
return null;
}
$type = $contentType === 3 ? 'image' : 'file';
$type = $contentType === 3 ? 'image' : ($contentType === 6 ? 'video' : 'file');
return [
'type' => $type,
@@ -767,7 +784,7 @@ function nativeDisplayText(string $searchableText, int $contentType, bool $hasAt
{
$text = trim($searchableText);
if (isNativePlaceholderText($text, $contentType)) {
return '';
$text = '';
}
if ($text === '' && !$isRecalled) {
return nativeMessageFallbackText($contentType, $hasAttachment);
@@ -776,6 +793,29 @@ function nativeDisplayText(string $searchableText, int $contentType, bool $hasAt
return $text;
}
function nativeRedPacketFromText(string $text): ?array
{
$decoded = json_decode(trim($text), true);
if (!is_array($decoded)) {
return null;
}
$packet = $decoded['redPackets'] ?? $decoded['redPacket'] ?? null;
if (!is_array($packet)) {
return null;
}
return [
'id' => (string)($packet['id'] ?? ''),
'senderId' => (string)($packet['userId'] ?? $packet['senderId'] ?? ''),
'target' => (string)($packet['target'] ?? $decoded['target'] ?? ''),
'blessing' => trim((string)($packet['blessing'] ?? '')) ?: '恭喜发财,大吉大利',
'status' => (int)($packet['status'] ?? 0),
'expireTime' => (string)($packet['expireTime'] ?? ''),
'createDate' => (string)($packet['createDate'] ?? ''),
];
}
function nativeMessageFallbackText(int $contentType, bool $hasAttachment): string
{
if ($hasAttachment) {
@@ -784,6 +824,21 @@ function nativeMessageFallbackText(int $contentType, bool $hasAttachment): strin
if ($contentType === 5) {
return '[文件]';
}
if ($contentType === 6) {
return '[视频加载失败]';
}
if ($contentType === 90) {
return '[红包]';
}
if ($contentType === 92) {
return '以上是打招呼的内容';
}
if ($contentType === 93) {
return '你们已经是好友了,可以开始聊天了。';
}
if ($contentType === 105) {
return '[领取了红包]';
}
return '';
}
@@ -886,11 +941,19 @@ function formatNativeGroupMessage(
$messageId = (string)$row['_mid'];
$timestamp = timestampMs((string)($row['_dt'] ?? ''), $messageId);
$contentType = (int)($row['_content_type'] ?? 0);
$redPacket = nativeRedPacketFromText((string)($row['_searchable_key'] ?? ''));
if ($redPacket !== null) {
$contentType = 90;
}
$isRecalled = $contentType === 80;
$direction = $from === $currentUserId ? 'out' : 'in';
$attachment = nativeAttachmentFromRow($row, $attachment);
$messageType = $attachment ? (string)$attachment['type'] : (($contentType === 1 || $isRecalled) ? 'text' : 'unknown');
$text = nativeDisplayText((string)($row['_searchable_key'] ?? ''), $contentType, $attachment !== null, $isRecalled);
$messageType = $attachment
? (string)$attachment['type']
: (in_array($contentType, [1, 80, 90, 92, 93, 105], true) ? 'text' : 'unknown');
$text = $redPacket !== null
? '[红包]'
: nativeDisplayText((string)($row['_searchable_key'] ?? ''), $contentType, $attachment !== null, $isRecalled);
return [
'id' => $messageId,
@@ -902,6 +965,7 @@ function formatNativeGroupMessage(
'senderPortrait' => (string)($senderUser['_portrait'] ?? ''),
'senderProfile' => [
'uid' => $from,
'userId' => (string)($senderUser['_name'] ?? ''),
'displayName' => $senderName,
'rawName' => $senderRawName,
'contactAlias' => $senderContactAlias,
@@ -921,6 +985,7 @@ function formatNativeGroupMessage(
'contentType' => $contentType,
'text' => attachmentDisplayText($text, $attachment),
'attachment' => $attachment,
'redPacket' => $redPacket,
'status' => $isRecalled && $direction === 'out' ? 'recalled' : 'sent',
'deliveryStatus' => $direction === 'out' && !$isRecalled ? 'sent' : '',
'recalled' => $isRecalled,
@@ -1001,7 +1066,7 @@ function loadNativeGroupMessages(PDO $db, string $userId, string $groupId, int $
}
$table = imUserMessagesTable($userId);
$scanLimit = min(max($limit * 4, $limit), 400);
$scanLimit = min(max($limit * 4, $limit), 5000);
$statement = $db->prepare(
'select `_mid`, `_dt` from `' . $table . '`'
. ' where `_uid` = ? and `_type` = 1 and `_line` = 0 and `_target` = ?'
@@ -1325,13 +1390,21 @@ function formatMessage(
$messageId = (string)$row['_mid'];
$from = (string)$row['_from'];
$contentType = (int)($row['_content_type'] ?? 0);
$redPacket = nativeRedPacketFromText((string)($row['_searchable_key'] ?? ''));
if ($redPacket !== null) {
$contentType = 90;
}
$isRecalled = $contentType === 80;
$text = (string)($row['_searchable_key'] ?? '');
$timestamp = timestampMs((string)($row['_dt'] ?? ''), $messageId);
$direction = $from === $currentUserId ? 'out' : 'in';
$attachment = nativeAttachmentFromRow($row, $attachment);
$messageType = $attachment ? (string)$attachment['type'] : (($contentType === 1 || $isRecalled) ? 'text' : 'unknown');
$messageText = nativeDisplayText($text, $contentType, $attachment !== null, $isRecalled);
$messageType = $attachment
? (string)$attachment['type']
: (in_array($contentType, [1, 80, 90, 92, 93, 105], true) ? 'text' : 'unknown');
$messageText = $redPacket !== null
? '[红包]'
: nativeDisplayText($text, $contentType, $attachment !== null, $isRecalled);
$messageText = attachmentDisplayText($messageText, $attachment);
$editedAt = (int)($editState['editedAt'] ?? 0);
$activityTimestamp = messageActivityTimestamp($timestamp, $editState);
@@ -1348,9 +1421,12 @@ function formatMessage(
'target' => $peerId,
'direction' => $direction,
'type' => $messageType,
'contentType' => $attachment ? ((string)$attachment['type'] === 'image' ? 3 : 5) : $contentType,
'contentType' => $attachment
? ((string)$attachment['type'] === 'image' ? 3 : ((string)$attachment['type'] === 'video' ? 6 : 5))
: $contentType,
'text' => $messageText,
'attachment' => $attachment,
'redPacket' => $redPacket,
'status' => $isRecalled && $direction === 'out' ? 'recalled' : ($direction === 'out' ? $deliveryStatus : 'sent'),
'deliveryStatus' => $deliveryStatus,
'recalled' => $isRecalled,
@@ -1500,7 +1576,16 @@ function loadRecentConversations(PDO $db, string $userId, int $limit): array
'portrait' => (string)($users[$peerId]['_portrait'] ?? ''),
'avatarText' => mb_strtoupper(mb_substr($title, 0, 1, 'UTF-8'), 'UTF-8'),
'updatedAt' => $message ? $message['activityTimestamp'] : timestampMs((string)($userRow['_dt'] ?? ''), $messageId),
'raw' => ['type' => 'single', 'target' => $peerId, 'line' => 0],
'raw' => [
'type' => 'single',
'target' => $peerId,
'line' => 0,
'userId' => (string)($users[$peerId]['_name'] ?? $peerId),
'userUid' => $peerId,
'displayName' => (string)($users[$peerId]['_display_name'] ?? ''),
'mobile' => (string)($users[$peerId]['_mobile'] ?? ''),
'address' => (string)($users[$peerId]['_address'] ?? ''),
],
];
}
@@ -1526,20 +1611,51 @@ function messageSyncResult(
string $userId,
array $messages,
bool $includeConversations,
int $limit
int $limit,
string $targetId = '',
string $conversationType = 'single'
): array {
$result = ['messages' => $messages];
if ($includeConversations) {
$result['conversations'] = loadRecentConversations($db, $userId, $limit);
}
if ($targetId !== '') {
try {
imAppDb()->exec(
'create table if not exists `t_web_pinned_messages` ('
. '`user_id` varchar(64) not null, `conversation_type` varchar(16) not null,'
. '`target_id` varchar(128) not null, `message_uid` varchar(32) not null,'
. '`message_json` text null,'
. '`updated_at_ms` bigint not null, primary key (`user_id`, `conversation_type`, `target_id`)'
. ') engine=InnoDB default charset=utf8mb4'
);
try {
imAppDb()->exec('alter table `t_web_pinned_messages` add column `message_json` text null after `message_uid`');
} catch (Throwable) {
// The column already exists.
}
$statement = imAppDb()->prepare(
'select `message_uid`, `message_json` from `t_web_pinned_messages` where `user_id` = ? and `conversation_type` = ? and `target_id` = ? limit 1'
);
$statement->execute([$userId, $conversationType, $targetId]);
$pinnedRow = $statement->fetch();
$result['pinnedMessageUid'] = (string)($pinnedRow['message_uid'] ?? '');
$pinnedMessage = json_decode((string)($pinnedRow['message_json'] ?? ''), true);
$result['pinnedMessage'] = is_array($pinnedMessage) ? $pinnedMessage : null;
} catch (Throwable) {
$result['pinnedMessageUid'] = '';
$result['pinnedMessage'] = null;
}
}
return $result;
}
$payload = readJsonPayload();
$userId = trim((string)($payload['userId'] ?? ''));
$target = trim((string)($payload['target'] ?? ''));
$limit = clampLimit($payload['limit'] ?? 50, 50, 100);
$limit = clampLimit($payload['limit'] ?? 1000, 50, 1000);
$markRead = payloadBool($payload['markRead'] ?? false);
$includeConversations = payloadBool($payload['includeConversations'] ?? false);
$conversationType = normalizeConversationType($payload['conversationType'] ?? $payload['type'] ?? 0);
@@ -1561,7 +1677,7 @@ try {
$userId,
loadWebGroupMessages(imAppDb(), $userId, $target, $limit, $markRead),
$includeConversations,
$limit
$limit, $target, 'group'
));
}
if (isNativeGroupTarget($db, $target)) {
@@ -1570,7 +1686,7 @@ try {
$userId,
loadNativeGroupMessages($db, $userId, $target, $limit, $markRead),
$includeConversations,
$limit
$limit, $target, 'group'
));
}
respond(0, 'success', messageSyncResult(
@@ -1578,7 +1694,7 @@ try {
$userId,
[],
$includeConversations,
$limit
$limit, $target, 'group'
));
}
if (isWebGroupTarget(imAppDb(), $target)) {
@@ -1587,7 +1703,7 @@ try {
$userId,
loadWebGroupMessages(imAppDb(), $userId, $target, $limit, $markRead),
$includeConversations,
$limit
$limit, $target, 'group'
));
}
$targetId = resolveUserId($db, $target);
@@ -1596,7 +1712,7 @@ try {
$userId,
loadConversationMessages($db, $userId, $targetId, $limit, $markRead),
$includeConversations,
$limit
$limit, $targetId, 'single'
));
}
+1 -1
View File
@@ -7,7 +7,7 @@ header('Cache-Control: no-store');
require __DIR__ . '/im_web_bootstrap.php';
$defaultName = 'Web IM';
$defaultLogo = '/img/logo.ico';
$defaultLogo = '/img/logo.png';
try {
$statement = imAppDb()->prepare(
+141 -225
View File
@@ -6,21 +6,13 @@ header('Cache-Control: no-store');
require __DIR__ . '/im_web_bootstrap.php';
define(
'WEB_MEDIA_ROOT',
webImEnv(
'JC_WEB_IM_MEDIA_ROOT',
is_dir('/var/www/im/public/media')
? '/var/www/im/public/media'
: (is_dir('/var/www/IM/public/media') ? '/var/www/IM/public/media' : '/opt/im-server/media')
)
);
define('WEB_MEDIA_PUBLIC_PORT', (int)webImEnv('JC_WEB_IM_MEDIA_PORT', '80'));
const WEB_MEDIA_ROOT = '/opt/im-server/media';
const WEB_MEDIA_PUBLIC_PORT = 18000;
const WEB_MEDIA_TYPE_IMAGE = 1;
const WEB_MEDIA_TYPE_VIDEO = 3;
const WEB_MEDIA_TYPE_FILE = 4;
const WEB_IMAGE_MAX_BYTES = 10 * 1024 * 1024;
const WEB_FILE_MAX_BYTES = 50 * 1024 * 1024;
const WEB_MINIO_PROJECT_CODE = '001';
function isDailyMuteActive(string $dailyStart, string $dailyEnd, int $nowMs): bool
{
@@ -81,33 +73,6 @@ function isGroupMutedForSender(PDO $appDb, string $groupId, string $role, int $n
return $startsAtMs > 0 && $endsAtMs > $startsAtMs && $nowMs >= $startsAtMs && $nowMs < $endsAtMs;
}
function nativeGroupRoleFromType(mixed $type): string
{
$value = (int)$type;
if ($value === 2) {
return 'owner';
}
if ($value === 1) {
return 'admin';
}
return 'member';
}
function fetchNativeGroupForSender(PDO $db, string $sender, string $groupId): array
{
$statement = $db->prepare(
'select g.`_gid`, g.`_name`, g.`_mute`, g.`_deleted`, m.`_type` as `member_type`'
. ' from `t_group` g'
. ' join `t_group_member` m on m.`_gid` = g.`_gid`'
. ' where g.`_gid` = ? and g.`_deleted` = 0 and m.`_mid` = ? limit 1'
);
$statement->execute([$groupId, $sender]);
$group = $statement->fetch();
return is_array($group) ? $group : [];
}
function messageRequestValue(array $payload, string $key, string $default = ''): string
{
return trim((string)($_POST[$key] ?? $payload[$key] ?? $default));
@@ -190,114 +155,11 @@ function mediaPublicBaseUrl(): string
$isHttps = (string)($_SERVER['HTTPS'] ?? '') !== '' && strtolower((string)$_SERVER['HTTPS']) !== 'off';
$scheme = $isHttps ? 'https' : 'http';
$host = trim(preg_replace('/:\d+$/', '', (string)($_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? '127.0.0.1')) ?: '127.0.0.1');
$port = (int)WEB_MEDIA_PUBLIC_PORT;
if ($port <= 0 || ($scheme === 'http' && $port === 80) || ($scheme === 'https' && $port === 443)) {
return $scheme . '://' . $host;
}
return $scheme . '://' . $host . ':' . $port;
return $scheme . '://' . $host . ':' . WEB_MEDIA_PUBLIC_PORT;
}
function messageStorageConfig(): array
{
$config = ['enabled' => false, 'url' => ''];
foreach (['t_app_system_conf', 'system_conf'] as $table) {
try {
$statement = imAppDb()->query(
'select `conf_name`, `conf_value` from `' . $table . '`'
. " where lower(`conf_name`) in ('is_minioplus', 'minio_url') and `is_valid` = 1"
);
$rows = $statement->fetchAll();
if (!$rows) {
continue;
}
foreach ($rows as $row) {
$name = strtolower((string)($row['conf_name'] ?? ''));
if ($name === 'is_minioplus') {
$config['enabled'] = (string)($row['conf_value'] ?? '0') === '1';
} elseif ($name === 'minio_url') {
$config['url'] = rtrim(trim((string)($row['conf_value'] ?? '')), '/');
}
}
break;
} catch (Throwable $error) {
continue;
}
}
return $config;
}
function saveMessageAttachmentToMinio(
array $file,
string $attachmentType,
string $sender,
string $baseUrl
): array {
$size = (int)($file['size'] ?? 0);
$tmpName = (string)($file['tmp_name'] ?? '');
if ($tmpName === '' || !is_uploaded_file($tmpName)) {
throw new RuntimeException('文件上传失败');
}
$mime = detectedUploadMime($tmpName);
if ($attachmentType === 'image') {
$mime = normalizedImageUploadMime($tmpName, $mime);
}
$originalName = safeUploadName((string)($file['name'] ?? ($attachmentType === 'image' ? 'image.jpg' : 'file')));
$content = file_get_contents($tmpName);
if ($content === false) {
throw new RuntimeException('读取上传文件失败');
}
$requestBody = json_encode([
'projectCode' => WEB_MINIO_PROJECT_CODE,
'fileScene' => 'temp',
'fileName' => $originalName,
'contentType' => $mime,
'base64Content' => base64_encode($content),
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if (!is_string($requestBody)) {
throw new RuntimeException('生成图片上传请求失败');
}
$handle = curl_init($baseUrl . '/project-storage/upload');
curl_setopt_array($handle, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 8,
CURLOPT_TIMEOUT => 60,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: minio-' . WEB_MINIO_PROJECT_CODE . '-' . $sender,
],
CURLOPT_POSTFIELDS => $requestBody,
]);
$responseBody = curl_exec($handle);
$status = (int)curl_getinfo($handle, CURLINFO_RESPONSE_CODE);
$curlError = curl_error($handle);
curl_close($handle);
$response = is_string($responseBody) ? json_decode($responseBody, true) : null;
$data = is_array($response) && is_array($response['data'] ?? null) ? $response['data'] : [];
$url = trim((string)($data['previewUrl'] ?? $data['downloadUrl'] ?? ''));
if ($status < 200 || $status >= 300 || (int)($response['code'] ?? -1) !== 0 || $url === '') {
$message = trim((string)($response['message'] ?? ''));
throw new RuntimeException(
$message !== ''
? 'MinIO上传失败:' . $message
: 'MinIO上传失败' . ($curlError !== '' ? ':' . $curlError : '')
);
}
return [
'type' => $attachmentType,
'url' => $url,
'name' => $originalName,
'mime' => $mime,
'size' => $size,
'mediaType' => $attachmentType === 'image' ? WEB_MEDIA_TYPE_IMAGE : WEB_MEDIA_TYPE_FILE,
];
}
function saveMessageAttachmentFile(array $file, string $attachmentType, string $sender): array
function saveMessageAttachmentFile(array $file, string $attachmentType): array
{
if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
throw new RuntimeException('文件上传失败');
@@ -307,6 +169,10 @@ function saveMessageAttachmentFile(array $file, string $attachmentType, string $
if ($size <= 0 || $size > $maxSize) {
throw new RuntimeException($attachmentType === 'image' ? '图片不能超过10MB' : '文件不能超过50MB');
}
if (!is_dir(WEB_MEDIA_ROOT) || !is_writable(WEB_MEDIA_ROOT)) {
throw new RuntimeException('媒体存储目录不可写');
}
$tmpName = (string)($file['tmp_name'] ?? '');
if ($tmpName === '' || !is_uploaded_file($tmpName)) {
throw new RuntimeException('文件上传失败');
@@ -316,17 +182,6 @@ function saveMessageAttachmentFile(array $file, string $attachmentType, string $
$mime = normalizedImageUploadMime($tmpName, $mime);
}
$storage = messageStorageConfig();
if ($storage['enabled']) {
if ($storage['url'] === '') {
throw new RuntimeException('MinIO已开启但未配置服务地址');
}
return saveMessageAttachmentToMinio($file, $attachmentType, $sender, $storage['url']);
}
if (!is_dir(WEB_MEDIA_ROOT) || !is_writable(WEB_MEDIA_ROOT)) {
throw new RuntimeException('媒体存储目录不可写');
}
$mediaType = $attachmentType === 'image' ? WEB_MEDIA_TYPE_IMAGE : WEB_MEDIA_TYPE_FILE;
$datePath = 'fs/' . $mediaType . '/' . date('Y/m/d/H/i/s');
$targetDir = rtrim(WEB_MEDIA_ROOT, '/') . '/' . $datePath;
@@ -391,72 +246,37 @@ function storeMessageAttachment(
]);
}
function attachmentFromRequest(string $messageType, string $sender): ?array
function attachmentFromRequest(string $messageType): ?array
{
if (!in_array($messageType, ['image', 'file'], true)) {
if (!in_array($messageType, ['image', 'video', 'file'], true)) {
return null;
}
$forwardUrl = trim((string)($_POST['attachmentUrl'] ?? ''));
if ($forwardUrl !== '') {
$parts = parse_url($forwardUrl);
$scheme = strtolower((string)($parts['scheme'] ?? ''));
if (!in_array($scheme, ['http', 'https'], true) || empty($parts['host']) || strlen($forwardUrl) > 2048) {
respond(400, '媒体地址不合法');
}
$mime = trim((string)($_POST['attachmentMime'] ?? 'application/octet-stream'));
$name = safeUploadName((string)($_POST['attachmentName'] ?? ($messageType === 'image' ? '图片' : ($messageType === 'video' ? '视频.mp4' : '文件'))));
return [
'type' => $messageType,
'url' => $forwardUrl,
'name' => $name,
'mime' => $mime,
'size' => max(0, (int)($_POST['attachmentSize'] ?? 0)),
'mediaType' => $messageType === 'image' ? WEB_MEDIA_TYPE_IMAGE : ($messageType === 'video' ? WEB_MEDIA_TYPE_VIDEO : WEB_MEDIA_TYPE_FILE),
];
}
$attachmentFile = $_FILES['attachment'] ?? $_FILES['file'] ?? null;
if (!is_array($attachmentFile)) {
respond(400, '缺少上传文件');
}
return saveMessageAttachmentFile($attachmentFile, $messageType, $sender);
}
function messagePayloadBody(string $text, ?array $attachment): array
{
$pushContent = $text !== ''
? $text
: ($attachment
? ((string)$attachment['type'] === 'image' ? '[图片]' : '[文件] ' . (string)$attachment['name'])
: $text);
$payloadBody = [
'type' => $attachment ? ((string)$attachment['type'] === 'image' ? 3 : 5) : 1,
'searchableContent' => $pushContent,
'pushContent' => $pushContent,
'content' => $text,
'persistFlag' => 3,
];
if ($attachment) {
$payloadBody['mediaType'] = (int)$attachment['mediaType'];
$payloadBody['remoteMediaUrl'] = (string)$attachment['url'];
$payloadBody['extra'] = json_encode([
'name' => (string)$attachment['name'],
'mime' => (string)$attachment['mime'],
'size' => (int)$attachment['size'],
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
return $payloadBody;
}
function sendNativeGroupMessage(string $sender, string $target, string $text, ?array $attachment): array
{
$result = requireImSuccess(imAdminPost('/admin/message/send', [
'sender' => $sender,
'conv' => [
'type' => 1,
'target' => $target,
'line' => 0,
],
'payload' => messagePayloadBody($text, $attachment),
'userMessage' => true,
]), '原生群消息发送失败');
$messageUid = isset($result['messageUid']) ? (string)$result['messageUid'] : '';
$timestamp = (int)($result['timestamp'] ?? webImNowMs());
if ($attachment && $messageUid !== '') {
ensureWebImAppTables();
storeMessageAttachment(imAppDb(), $messageUid, 'group', $target, $sender, $attachment, $timestamp);
}
return [
'messageUid' => $messageUid !== '' ? $messageUid : null,
'timestamp' => $timestamp,
'attachment' => $attachment,
];
return saveMessageAttachmentFile($attachmentFile, $messageType);
}
$contentTypeHeader = (string)($_SERVER['CONTENT_TYPE'] ?? '');
@@ -468,9 +288,13 @@ $text = messageRequestValue($payload, 'text');
$messageType = messageRequestValue($payload, 'messageType', 'text');
$conversationType = $_POST['conversationType'] ?? $_POST['type'] ?? $payload['conversationType'] ?? $payload['type'] ?? 0;
$isGroupConversation = in_array((string)$conversationType, ['1', 'group', 'channel'], true);
$mentionedUserIds = $payload['mentionedUserIds'] ?? [];
$mentionedUserIds = is_array($mentionedUserIds)
? array_values(array_unique(array_filter(array_map(static fn($value): string => trim((string)$value), $mentionedUserIds))))
: [];
$attachment = null;
if ($sender === '' || $target === '' || ($text === '' && !in_array($messageType, ['image', 'file'], true))) {
if ($sender === '' || $target === '' || ($text === '' && !in_array($messageType, ['image', 'video', 'file'], true))) {
respond(400, '缺少发送者、接收者或消息内容');
}
@@ -488,16 +312,64 @@ try {
$memberStatement->execute([$target, $sender]);
$group = $memberStatement->fetch();
if (!$group) {
$nativeGroup = fetchNativeGroupForSender(imDb(), $sender, $target);
if (!$nativeGroup) {
// 手机端创建的原生群不一定存在于 Web 自建群表中,需回退检查 IM 群成员表。
$imDb = imDb();
$nativeGroupStatement = $imDb->prepare(
'select 1 from `t_group` where `_gid` = ? and `_deleted` = 0 limit 1'
);
$nativeGroupStatement->execute([$target]);
$nativeMemberStatement = $imDb->prepare(
'select `_type` from `t_group_member` where `_gid` = ? and `_mid` = ? limit 1'
);
$nativeMemberStatement->execute([$target, $sender]);
$nativeMemberType = $nativeMemberStatement->fetchColumn();
if (!$nativeGroupStatement->fetchColumn() || $nativeMemberType === false) {
respond(403, '你不在该群组中');
}
$attachment = attachmentFromRequest($messageType, $sender);
$nativeResult = sendNativeGroupMessage($sender, $target, $text, $attachment);
$attachment = attachmentFromRequest($messageType);
$pushContent = $text !== ''
? $text
: ($attachment
? ((string)$attachment['type'] === 'image' ? '[图片]' : ((string)$attachment['type'] === 'video' ? '[视频]' : '[文件] ' . (string)$attachment['name']))
: $text);
$payloadBody = [
'type' => $attachment ? ((string)$attachment['type'] === 'image' ? 3 : ((string)$attachment['type'] === 'video' ? 6 : 5)) : 1,
'searchableContent' => $pushContent,
'pushContent' => $pushContent,
'content' => $text,
'persistFlag' => 3,
];
if ($mentionedUserIds) {
$payloadBody['mentionedType'] = 1;
$payloadBody['mentionedTarget'] = $mentionedUserIds;
}
if ($attachment) {
$payloadBody['mediaType'] = (int)$attachment['mediaType'];
$payloadBody['remoteMediaUrl'] = (string)$attachment['url'];
$payloadBody['extra'] = json_encode([
'name' => (string)$attachment['name'],
'mime' => (string)$attachment['mime'],
'size' => (int)$attachment['size'],
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
$nativeResult = requireImSuccess(imAdminPost('/admin/message/send', [
'sender' => $sender,
'conv' => ['type' => 1, 'target' => $target, 'line' => 0],
'payload' => $payloadBody,
]), '原生群消息发送失败');
$messageUid = isset($nativeResult['messageUid']) ? (string)$nativeResult['messageUid'] : '';
$timestamp = (int)($nativeResult['timestamp'] ?? webImNowMs());
if ($attachment && $messageUid !== '') {
storeMessageAttachment($appDb, $messageUid, 'group', $target, $sender, $attachment, $timestamp);
}
$role = (int)$nativeMemberType === 2 ? 'owner' : ((int)$nativeMemberType === 1 ? 'admin' : 'member');
respond(0, 'success', [
...$nativeResult,
'senderRole' => nativeGroupRoleFromType($nativeGroup['member_type'] ?? 0),
'native' => true,
'messageUid' => $messageUid,
'timestamp' => $timestamp,
'senderRole' => $role,
'attachment' => $attachment,
'nativeError' => '',
]);
}
$category = (string)($group['category'] ?? 'group');
@@ -510,7 +382,7 @@ try {
if ($category !== 'channel' && isGroupMutedForSender($appDb, $target, $role, $now)) {
respond(403, '当前群组处于禁言时段');
}
$attachment = attachmentFromRequest($messageType, $sender);
$attachment = attachmentFromRequest($messageType);
$messageUid = webImMessageUid();
$insert = $appDb->prepare(
'insert into `t_web_group_messages`'
@@ -526,6 +398,31 @@ try {
$nativeError = '';
try {
$pushContent = $text !== ''
? $text
: ($attachment
? ((string)$attachment['type'] === 'image' ? '[图片]' : ((string)$attachment['type'] === 'video' ? '[视频]' : '[文件] ' . (string)$attachment['name']))
: $text);
$payloadBody = [
'type' => $attachment ? ((string)$attachment['type'] === 'image' ? 3 : ((string)$attachment['type'] === 'video' ? 6 : 5)) : 1,
'searchableContent' => $pushContent,
'pushContent' => $pushContent,
'content' => $text,
'persistFlag' => 3,
];
if ($mentionedUserIds) {
$payloadBody['mentionedType'] = 1;
$payloadBody['mentionedTarget'] = $mentionedUserIds;
}
if ($attachment) {
$payloadBody['mediaType'] = (int)$attachment['mediaType'];
$payloadBody['remoteMediaUrl'] = (string)$attachment['url'];
$payloadBody['extra'] = json_encode([
'name' => (string)$attachment['name'],
'mime' => (string)$attachment['mime'],
'size' => (int)$attachment['size'],
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
requireImSuccess(imAdminPost('/admin/message/send', [
'sender' => $sender,
'conv' => [
@@ -533,8 +430,7 @@ try {
'target' => $target,
'line' => 0,
],
'payload' => messagePayloadBody($text, $attachment),
'userMessage' => true,
'payload' => $payloadBody,
]), '原生群消息发送失败');
} catch (Throwable $error) {
$nativeError = $error->getMessage() ?: '原生群消息发送失败';
@@ -549,7 +445,28 @@ try {
]);
}
$attachment = attachmentFromRequest($messageType, $sender);
$attachment = attachmentFromRequest($messageType);
$pushContent = $text !== ''
? $text
: ($attachment
? ((string)$attachment['type'] === 'image' ? '[图片]' : ((string)$attachment['type'] === 'video' ? '[视频]' : '[文件] ' . (string)$attachment['name']))
: $text);
$payloadBody = [
'type' => $attachment ? ((string)$attachment['type'] === 'image' ? 3 : ((string)$attachment['type'] === 'video' ? 6 : 5)) : 1,
'searchableContent' => $pushContent,
'pushContent' => $pushContent,
'content' => $text,
'persistFlag' => 3,
];
if ($attachment) {
$payloadBody['mediaType'] = (int)$attachment['mediaType'];
$payloadBody['remoteMediaUrl'] = (string)$attachment['url'];
$payloadBody['extra'] = json_encode([
'name' => (string)$attachment['name'],
'mime' => (string)$attachment['mime'],
'size' => (int)$attachment['size'],
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
$result = requireImSuccess(imAdminPost('/admin/message/send', [
'sender' => $sender,
@@ -558,8 +475,7 @@ try {
'target' => $target,
'line' => 0,
],
'payload' => messagePayloadBody($text, $attachment),
'userMessage' => true,
'payload' => $payloadBody,
]), '发送失败');
$messageUid = isset($result['messageUid']) ? (string)$result['messageUid'] : '';
+9 -17
View File
@@ -1,21 +1,13 @@
(() => {
const protocol = window.location.protocol || 'http:';
const host = window.location.hostname || '127.0.0.1';
window.JC_WEB_IM_CONFIG = {
adminServer: `${protocol}//${host}:8100`,
appServer: `${protocol}//${host}:8888`,
window.JC_WEB_IM_CONFIG = {
adminServer: 'http://18.141.44.165:8100',
appServer: '/app-server',
qrAppServer: 'http://18.141.44.165:8888',
platformConfigApi: '/api/platform_config.php',
registerConfigApi: `${protocol}//${host}:8100/api/register-config`,
registerPhoneExistsApi: `${protocol}//${host}:8100/api/register-phone-exists`,
imServerHost: host,
registerConfigApi: 'http://18.141.44.165:8100/api/register-config',
imServerHost: '18.141.44.165',
imRoutePort: 80,
useWss: false,
wsPath: '/ws',
sdkMode: 'http',
syncIntervalMs: 15000,
sseEnabled: true,
sseTicketApi: '/api/sse_ticket.php',
sseUrl: '/ws-events'
};
})();
sdkMode: 'legacy-http',
syncIntervalMs: 2500
};
+18
View File
@@ -0,0 +1,18 @@
window.JC_WEB_IM_CONFIG = {
runtimeEnvironment: 'local',
adminServer: 'http://18.141.44.165:8100',
appServer: '/app-server',
qrAppServer: 'http://18.141.44.165:8888',
platformConfigApi: '/local-api/platform_config.php',
registerConfigApi: '/local-api/register_config.php',
registerPhoneExistsApi: 'http://18.141.44.165:8100/api/register-phone-exists',
imServerHost: '18.141.44.165',
imRoutePort: 80,
useWss: false,
wsPath: '/ws',
sdkMode: 'legacy-http',
syncIntervalMs: 2500,
sseEnabled: false,
sseTicketApi: '/local-api/sse_ticket.php',
sseUrl: '/ws-events'
};
@@ -0,0 +1,23 @@
(() => {
const protocol = window.location.protocol || 'http:';
const host = window.location.hostname || '18.141.44.165';
window.JC_WEB_IM_CONFIG = {
runtimeEnvironment: 'production',
adminServer: `${protocol}//${host}:8100`,
appServer: `${protocol}//${host}:8888`,
qrAppServer: `${protocol}//${host}:8888`,
platformConfigApi: '/api/platform_config.php',
registerConfigApi: `${protocol}//${host}:8100/api/register-config`,
registerPhoneExistsApi: `${protocol}//${host}:8100/api/register-phone-exists`,
imServerHost: host,
imRoutePort: 80,
useWss: false,
wsPath: '/ws',
sdkMode: 'legacy-http',
syncIntervalMs: 15000,
sseEnabled: true,
sseTicketApi: '/api/sse_ticket.php',
sseUrl: '/ws-events'
};
})();
Binary file not shown.

After

Width:  |  Height:  |  Size: 958 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

+2 -2
View File
@@ -4,8 +4,8 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Web IM</title>
<link rel="icon" href="<%= BASE_URL %>img/5IuOieu9PF8MJtp43kD2kCkdLVjVwDp7.ico">
<script src="<%= BASE_URL %>config/runtime-config.js"></script>
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<script src="<%= BASE_URL %>config/<%= htmlWebpackPlugin.options.runtimeConfigFile %>"></script>
</head>
<body>
<noscript>请启用 JavaScript 后使用 Web IM。</noscript>
+1 -11
View File
@@ -4,24 +4,14 @@
</template>
<script setup>
import { onMounted, watch } from 'vue';
import { onMounted } from 'vue';
import LoginView from './components/LoginView.vue';
import ChatShell from './components/ChatShell.vue';
import { useSessionStore } from './stores/session';
import { useConversationStore } from './stores/conversations';
const session = useSessionStore();
const conversations = useConversationStore();
onMounted(() => {
session.restore();
});
watch(() => session.userId, userId => {
if (userId && session.isAuthenticated) {
conversations.bootstrapDemoData();
return;
}
conversations.clearUserState();
});
</script>
+20
View File
@@ -22,11 +22,31 @@ import FavoritePanel from './favorites/FavoritePanel.vue';
import { useConversationStore } from '@/stores/conversations';
import { useNavigationStore } from '@/stores/navigation';
import { useContactStore } from '@/stores/contacts';
import { useAutoDismiss } from '@/composables/useAutoDismiss';
const conversations = useConversationStore();
const navigation = useNavigationStore();
const contacts = useContactStore();
useAutoDismiss(
() => conversations.actionError || conversations.actionNotice,
value => {
if ((conversations.actionError || conversations.actionNotice) === value) {
conversations.actionError = '';
conversations.actionNotice = '';
}
}
);
useAutoDismiss(
() => contacts.actionError || contacts.actionInfo,
value => {
if ((contacts.actionError || contacts.actionInfo) === value) {
contacts.actionError = '';
contacts.actionInfo = '';
}
}
);
onMounted(() => {
conversations.refreshRemoteConversations();
contacts.refreshContacts();
+194
View File
@@ -0,0 +1,194 @@
<template>
<main class="documented-shell">
<aside class="documented-rail">
<div class="documented-avatar">
<img v-if="session.portrait" :src="session.portrait" alt="" @error="useImageProxyFallback($event, session.portrait)">
<span v-else>{{ initials }}</span>
</div>
<div class="documented-rail-copy">
<strong>{{ session.displayName || session.userId }}</strong>
<small>{{ session.userId }}</small>
</div>
<button class="documented-rail-button" type="button" @click="openPasswordDialog">修改密码</button>
<button class="documented-rail-button ghost" type="button" @click="logout">退出登录</button>
</aside>
<section class="documented-main">
<header class="documented-header">
<div>
<h1>文档对接模式</h1>
<p>当前界面只保留这两份文档已经明确提供的能力。</p>
</div>
<div class="documented-status">
<span>连接状态</span>
<strong>{{ session.connectionStatusText || '已登录' }}</strong>
</div>
</header>
<section class="documented-card">
<h2>已按文档接入</h2>
<ul class="documented-list">
<li>`/auth/login_pwd` 密码登录</li>
<li>`/auth/register` 注册并返回 `imToken`、`accessToken`、`refreshToken`</li>
<li>`/auth/sendEmailCode` 邮箱验证码</li>
<li>`/auth/refreshToken` 过期自动刷新</li>
<li>`/auth/changePassword` 修改密码</li>
<li>`/auth/logout` 退出登录</li>
<li>扫码登录兼容接口:`/pc_session` 与 `/session_login/{token}`</li>
<li>AES-128-CBC 请求加密、响应解密、`X-Timestamp`、排除路径规则</li>
</ul>
</section>
<section class="documented-card">
<h2>当前按 1 比 1 已停用</h2>
<p class="documented-text">下面这些旧页面功能已经不再走本地 PHP 或旧接口,因为你给的文档里没有对应定义。</p>
<ul class="documented-list muted">
<li>会话列表与消息列表</li>
<li>发送文字、图片、文件消息</li>
<li>联系人列表、添加联系人、备注</li>
<li>群详情、群成员、群管理</li>
<li>个人资料编辑与头像上传</li>
</ul>
</section>
<section class="documented-card">
<h2>当前登录态</h2>
<dl class="documented-meta">
<div>
<dt>用户 ID</dt>
<dd>{{ session.userId || '-' }}</dd>
</div>
<div>
<dt>显示名</dt>
<dd>{{ session.displayName || '-' }}</dd>
</div>
<div>
<dt>IM Token</dt>
<dd>{{ session.token ? '已保存' : '未保存' }}</dd>
</div>
<div>
<dt>App Server</dt>
<dd>{{ appConfig.appServer }}</dd>
</div>
<div>
<dt>扫码服务</dt>
<dd>{{ appConfig.qrAppServer }}</dd>
</div>
</dl>
</section>
</section>
<div v-if="passwordDialogOpen" class="modal-backdrop" @click.self="closePasswordDialog">
<form class="modal-panel documented-password-panel" @submit.prevent="savePassword">
<header>
<strong>修改密码</strong>
<button type="button" class="icon-button" title="关闭" @click="closePasswordDialog">×</button>
</header>
<label>
<span>当前密码</span>
<input v-model="passwordDraft.oldPassword" type="password" autocomplete="current-password">
</label>
<label>
<span>新密码</span>
<input v-model="passwordDraft.newPassword" type="password" autocomplete="new-password">
</label>
<label>
<span>确认新密码</span>
<input v-model="passwordDraft.confirmPassword" type="password" autocomplete="new-password">
</label>
<p v-if="passwordError" class="form-error">{{ passwordError }}</p>
<p v-if="passwordNotice" class="form-info">{{ passwordNotice }}</p>
<div class="modal-actions">
<button type="button" class="ghost-inline-action" :disabled="passwordSaving" @click="closePasswordDialog">取消</button>
<button class="primary-inline-action" :disabled="passwordSaving">
{{ passwordSaving ? '保存中...' : '保存' }}
</button>
</div>
</form>
</div>
</main>
</template>
<script setup>
import { computed, reactive, ref } from 'vue';
import { useSessionStore } from '@/stores/session';
import { appConfig } from '@/config';
import { useAutoDismiss } from '@/composables/useAutoDismiss';
import { useImageProxyFallback } from '@/services/mediaProxy';
const session = useSessionStore();
const passwordDialogOpen = ref(false);
const passwordSaving = ref(false);
const passwordError = ref('');
const passwordNotice = ref('');
useAutoDismiss(() => passwordError.value || passwordNotice.value, value => {
if ((passwordError.value || passwordNotice.value) === value) {
passwordError.value = '';
passwordNotice.value = '';
}
});
const passwordDraft = reactive({
oldPassword: '',
newPassword: '',
confirmPassword: ''
});
const initials = computed(() => String(session.displayName || session.userId || 'U').slice(0, 1).toUpperCase());
function resetPasswordDraft() {
passwordDraft.oldPassword = '';
passwordDraft.newPassword = '';
passwordDraft.confirmPassword = '';
}
function openPasswordDialog() {
passwordError.value = '';
passwordNotice.value = '';
resetPasswordDraft();
passwordDialogOpen.value = true;
}
function closePasswordDialog() {
if (passwordSaving.value) {
return;
}
passwordDialogOpen.value = false;
passwordError.value = '';
passwordNotice.value = '';
resetPasswordDraft();
}
async function savePassword() {
passwordError.value = '';
passwordNotice.value = '';
if (!passwordDraft.oldPassword || !passwordDraft.newPassword || !passwordDraft.confirmPassword) {
passwordError.value = '请填写完整密码';
return;
}
if (passwordDraft.newPassword !== passwordDraft.confirmPassword) {
passwordError.value = '两次输入的新密码不一致';
return;
}
if (passwordDraft.oldPassword === passwordDraft.newPassword) {
passwordError.value = '新密码不能与当前密码相同';
return;
}
passwordSaving.value = true;
try {
await session.changePassword({
oldPassword: passwordDraft.oldPassword,
newPassword: passwordDraft.newPassword
});
passwordNotice.value = '密码已修改,当前登录态会按文档要求失效。';
} catch (error) {
passwordError.value = error.message || '密码修改失败';
} finally {
passwordSaving.value = false;
}
}
async function logout() {
await session.logout();
}
</script>
File diff suppressed because it is too large Load Diff
+114 -38
View File
@@ -1,5 +1,5 @@
<template>
<section class="chat-panel">
<section class="chat-panel" :class="{ 'has-pinned-message': Boolean(conversations.activePinnedMessage) }">
<header class="chat-header">
<div>
<button
@@ -8,7 +8,7 @@
class="chat-title-button"
@click="openGroupOverview"
>
<img v-if="activeConversation?.portrait" class="chat-title-avatar image-avatar" :src="activeConversation.portrait" alt="">
<img v-if="activeConversation?.portrait" class="chat-title-avatar image-avatar" :src="activeConversation.portrait" alt="" @error="useImageProxyFallback($event, activeConversation.portrait)">
<span v-else class="chat-title-avatar">{{ activeConversation?.avatarText || '?' }}</span>
<span class="chat-title-copy">
<h2>{{ activeConversation?.title || '未选择会话' }}</h2>
@@ -20,7 +20,7 @@
class="chat-title-button"
@click="openSingleProfile"
>
<img v-if="singleProfile.portrait" class="chat-title-avatar image-avatar" :src="singleProfile.portrait" alt="">
<img v-if="singleProfile.portrait" class="chat-title-avatar image-avatar" :src="singleProfile.portrait" alt="" @error="useImageProxyFallback($event, singleProfile.portrait)">
<span v-else class="chat-title-avatar">{{ singleProfile.avatarText }}</span>
<span class="chat-title-copy">
<h2>{{ activeConversation?.title || '未选择会话' }}</h2>
@@ -44,12 +44,32 @@
<strong>选择一个会话</strong>
<span>真实会话同步完成后,可以在左侧打开聊天</span>
</div>
<button
v-if="activeConversation && conversations.activePinnedMessage"
type="button"
class="pinned-message-banner"
title="点击定位该消息"
@click="conversations.focusMessage(conversations.activePinnedMessage)"
>
<span>📌</span>
<strong>置顶消息</strong>
<span class="pinned-message-preview">
<img
v-if="pinnedMessageIsImage"
:src="conversations.activePinnedMessage.attachment.url"
alt="置顶图片"
>
<span>{{ pinnedMessageText }}</span>
</span>
<span class="pinned-message-close" title="取消置顶" @click.stop="conversations.clearPinnedMessage">×</span>
</button>
<MessageList
v-else
v-if="activeConversation"
:messages="conversations.activeMessages"
:selection-mode="conversations.selectionMode"
:selected-message-ids="conversations.selectedMessageIds"
:favorite-message-ids="conversations.favoriteMessageIds"
:pinned-message-id="conversations.activePinnedMessage?.key || ''"
:attention-message-id="conversations.attentionMessageId"
:can-recall-others="canManageGroup && isGroupConversation"
@message-action="conversations.handleMessageAction"
@@ -66,6 +86,7 @@
<MessageComposer
:disabled="!activeConversation || !session.isAuthenticated || !conversations.canSendActiveConversation"
:quote-message="conversations.quotedMessage"
:mention-users="isGroupConversation ? mentionCandidates : []"
@cancel-quote="conversations.cancelQuote"
@send="conversations.sendText"
@send-attachment="conversations.sendAttachment"
@@ -162,7 +183,7 @@
</header>
<div v-if="messageDetailGroup?.read?.length" class="message-detail-member-list">
<div v-for="member in messageDetailGroup.read" :key="`read-${member.uid}`" class="message-detail-member-row">
<img v-if="member.portrait" class="conversation-avatar image-avatar" :src="member.portrait" alt="">
<img v-if="member.portrait" class="conversation-avatar image-avatar" :src="member.portrait" alt="" @error="useImageProxyFallback($event, member.portrait)">
<span v-else class="conversation-avatar">{{ detailMemberAvatar(member) }}</span>
<span class="message-detail-member-main">
<strong>{{ detailMemberName(member) }}</strong>
@@ -182,7 +203,7 @@
</header>
<div v-if="messageDetailGroup?.unread?.length" class="message-detail-member-list">
<div v-for="member in messageDetailGroup.unread" :key="`unread-${member.uid}`" class="message-detail-member-row">
<img v-if="member.portrait" class="conversation-avatar image-avatar" :src="member.portrait" alt="">
<img v-if="member.portrait" class="conversation-avatar image-avatar" :src="member.portrait" alt="" @error="useImageProxyFallback($event, member.portrait)">
<span v-else class="conversation-avatar">{{ detailMemberAvatar(member) }}</span>
<span class="message-detail-member-main">
<strong>{{ detailMemberName(member) }}</strong>
@@ -202,7 +223,7 @@
</header>
<div v-if="messageDetailGroup?.undelivered?.length" class="message-detail-member-list">
<div v-for="member in messageDetailGroup.undelivered" :key="`undelivered-${member.uid}`" class="message-detail-member-row">
<img v-if="member.portrait" class="conversation-avatar image-avatar" :src="member.portrait" alt="">
<img v-if="member.portrait" class="conversation-avatar image-avatar" :src="member.portrait" alt="" @error="useImageProxyFallback($event, member.portrait)">
<span v-else class="conversation-avatar">{{ detailMemberAvatar(member) }}</span>
<span class="message-detail-member-main">
<strong>{{ detailMemberName(member) }}</strong>
@@ -226,14 +247,14 @@
<button type="button" class="icon-button" title="关闭" @click="closeSingleProfile">×</button>
</header>
<div class="single-profile-summary">
<img v-if="singleProfile.portrait" class="profile-avatar image-avatar" :src="singleProfile.portrait" alt="">
<img v-if="singleProfile.portrait" class="profile-avatar image-avatar" :src="singleProfile.portrait" alt="" @error="useImageProxyFallback($event, singleProfile.portrait)">
<div v-else class="profile-avatar">{{ singleProfile.avatarText }}</div>
<strong>{{ singleProfile.displayName }}</strong>
</div>
<dl class="group-profile">
<div>
<dt>用户ID</dt>
<dd>{{ singleProfile.uid || '-' }}</dd>
<dd>{{ singleProfile.userId || '-' }}</dd>
</div>
<div>
<dt>昵称</dt>
@@ -274,9 +295,9 @@
<dt>群名</dt>
<dd>{{ groupDetail?.name || activeConversation?.title || '-' }}</dd>
</div>
<div>
<div v-if="groupDisplayId">
<dt>群ID</dt>
<dd>{{ groupDetail?.groupId || activeConversation?.target || '-' }}</dd>
<dd>{{ groupDisplayId }}</dd>
</div>
<div>
<dt>群说明</dt>
@@ -303,15 +324,12 @@
</header>
<div v-if="groupBusy" class="group-loading">正在加载</div>
<div v-else class="group-member-list">
<div v-for="member in sortedGroupMembers" :key="member.uid" class="group-member-row">
<img v-if="member.portrait" class="conversation-avatar image-avatar" :src="member.portrait" alt="">
<div v-for="member in groupMembers" :key="member.uid" class="group-member-row">
<img v-if="member.portrait" class="conversation-avatar image-avatar" :src="member.portrait" alt="" @error="useImageProxyFallback($event, member.portrait)">
<span v-else class="conversation-avatar">{{ memberAvatar(member) }}</span>
<span>
<strong>{{ member.displayName }}</strong>
<small v-if="detailRoleLabel(member.role)" class="group-member-role">
{{ detailRoleLabel(member.role) }}
</small>
<small v-else>{{ member.rawDisplayName }}</small>
<small>{{ member.role === 'owner' ? '群主' : member.rawDisplayName }}</small>
</span>
</div>
<div v-if="!groupMembers.length" class="contact-picker-empty">暂无群员</div>
@@ -348,7 +366,7 @@
:class="{ selected: transferTargetId === member.uid }"
@click="transferTargetId = member.uid"
>
<img v-if="member.portrait" class="conversation-avatar image-avatar" :src="member.portrait" alt="">
<img v-if="member.portrait" class="conversation-avatar image-avatar" :src="member.portrait" alt="" @error="useImageProxyFallback($event, member.portrait)">
<span v-else class="conversation-avatar">{{ memberAvatar(member) }}</span>
<span>
<strong>{{ member.displayName }}</strong>
@@ -385,7 +403,7 @@
class="group-member-row selectable with-check"
>
<input type="checkbox" :checked="selectedAdminIds.includes(member.uid)" @change="toggleAdmin(member.uid)">
<img v-if="member.portrait" class="conversation-avatar image-avatar" :src="member.portrait" alt="">
<img v-if="member.portrait" class="conversation-avatar image-avatar" :src="member.portrait" alt="" @error="useImageProxyFallback($event, member.portrait)">
<span v-else class="conversation-avatar">{{ memberAvatar(member) }}</span>
<span>
<strong>{{ member.displayName }}</strong>
@@ -425,7 +443,7 @@
class="group-member-row selectable with-check"
>
<input type="checkbox" :checked="selectedKickIds.includes(member.uid)" @change="toggleKick(member.uid)">
<img v-if="member.portrait" class="conversation-avatar image-avatar" :src="member.portrait" alt="">
<img v-if="member.portrait" class="conversation-avatar image-avatar" :src="member.portrait" alt="" @error="useImageProxyFallback($event, member.portrait)">
<span v-else class="conversation-avatar">{{ memberAvatar(member) }}</span>
<span>
<strong>{{ member.displayName }}</strong>
@@ -498,11 +516,28 @@ import { imClient } from '@/services/imClient';
import { useConversationStore } from '@/stores/conversations';
import { useContactStore } from '@/stores/contacts';
import { useSessionStore } from '@/stores/session';
import { useAutoDismiss } from '@/composables/useAutoDismiss';
import { useImageProxyFallback } from '@/services/mediaProxy';
const conversations = useConversationStore();
const contacts = useContactStore();
const session = useSessionStore();
const activeConversation = computed(() => conversations.activeConversation);
const pinnedMessageIsImage = computed(() => {
const message = conversations.activePinnedMessage;
return message?.attachment?.url && (message.type === 'image' || message.attachment.type === 'image');
});
const pinnedMessageText = computed(() => {
const message = conversations.activePinnedMessage;
if (!message) return '';
const text = String(message.text || '').trim();
if (text && text !== '[消息]') return text;
const attachment = message.attachment || {};
if (message.type === 'image' || attachment.type === 'image') return attachment.name || '图片';
if (message.type === 'video' || attachment.type === 'video') return attachment.name || '视频';
if (attachment.url) return attachment.name || '文件';
return '[消息]';
});
const groupMenuOpen = ref(false);
const singleProfileOpen = ref(false);
const singleAliasDraft = ref('');
@@ -533,6 +568,18 @@ const muteDraft = ref({
});
const muteSaveNotice = ref('');
const muteSaveError = ref('');
useAutoDismiss(() => singleProfileError.value || singleProfileNotice.value, value => {
if ((singleProfileError.value || singleProfileNotice.value) === value) {
singleProfileError.value = '';
singleProfileNotice.value = '';
}
});
useAutoDismiss(() => muteSaveError.value || muteSaveNotice.value, value => {
if ((muteSaveError.value || muteSaveNotice.value) === value) {
muteSaveError.value = '';
muteSaveNotice.value = '';
}
});
const singlePeerId = computed(() => {
if (!activeConversation.value || isGroupConversation.value) {
return '';
@@ -561,6 +608,7 @@ const singleProfile = computed(() => {
return {
uid: singlePeerId.value,
userId: rawUser.name || conversation.raw?.userId || singlePeerId.value,
displayName,
rawName,
mobile: rawUser.mobile || conversation.raw?.mobile || '',
@@ -570,6 +618,9 @@ const singleProfile = computed(() => {
alias: contact?.alias || ''
};
});
const groupDisplayId = computed(() => {
return String(groupDetail.value?.publicId || '');
});
const isGroupConversation = computed(() => {
return ['group', 'channel'].includes(activeConversation.value?.type)
|| activeConversation.value?.raw?.type === 'group';
@@ -579,19 +630,26 @@ const currentGroupRole = computed(() => {
});
const isGroupOwner = computed(() => currentGroupRole.value === 'owner');
const canManageGroup = computed(() => ['owner', 'admin'].includes(currentGroupRole.value));
const sortedGroupMembers = computed(() => {
const roleOrder = { owner: 0, admin: 1, member: 2 };
return groupMembers.value
.map((member, index) => ({ member, index }))
.sort((left, right) => {
const leftOrder = roleOrder[left.member.role] ?? 3;
const rightOrder = roleOrder[right.member.role] ?? 3;
return leftOrder - rightOrder || left.index - right.index;
})
.map(item => item.member);
});
const adminCandidateMembers = computed(() => groupMembers.value.filter(member => member.role !== 'owner'));
const transferableMembers = computed(() => groupMembers.value.filter(member => member.role !== 'owner'));
const mentionCandidates = computed(() => {
const members = new Map();
groupMembers.value.forEach(member => {
const uid = String(member?.uid || '').trim();
if (uid && uid !== String(session.userId || '')) members.set(uid, member);
});
conversations.activeMessages.forEach(message => {
const uid = String(message?.from || '').trim();
if (!uid || uid === 'me' || uid === session.userId || members.has(uid)) return;
members.set(uid, {
uid,
displayName: message?.senderName || uid,
portrait: message?.senderPortrait || message?.portrait || '',
role: message?.senderRole || 'member'
});
});
return Array.from(members.values());
});
const messageDetail = computed(() => conversations.messageDetail || null);
const messageDetailGroup = computed(() => messageDetail.value?.group || null);
const isMessageDetailGroup = computed(() => {
@@ -752,15 +810,21 @@ async function loadGroupDetail() {
if (!session.userId || !activeConversation.value?.target) {
return null;
}
const requestedConversationId = activeConversation.value.id;
const requestedTarget = activeConversation.value.target;
groupBusy.value = true;
try {
groupDetail.value = await imClient.getGroupDetail(session.userId, activeConversation.value.target);
const detail = await imClient.getGroupDetail(session.userId, requestedTarget);
if (activeConversation.value?.id !== requestedConversationId) return null;
groupDetail.value = detail;
return groupDetail.value;
} catch (error) {
if (activeConversation.value?.id === requestedConversationId) {
conversations.setActionError(error.message || '群资料加载失败');
}
return null;
} finally {
groupBusy.value = false;
if (activeConversation.value?.id === requestedConversationId) groupBusy.value = false;
}
}
@@ -779,19 +843,26 @@ async function openGroupMembers() {
await loadGroupMembers();
}
async function loadGroupMembers() {
async function loadGroupMembers({ silent = false } = {}) {
const requestedConversationId = activeConversation.value?.id;
const requestedTarget = activeConversation.value?.target;
if (!session.userId || !requestedConversationId || !requestedTarget) return [];
groupBusy.value = true;
try {
groupMembers.value = await imClient.getGroupMembers(session.userId, activeConversation.value.target);
const members = await imClient.getGroupMembers(session.userId, requestedTarget);
if (activeConversation.value?.id !== requestedConversationId) return [];
groupMembers.value = members;
selectedAdminIds.value = groupMembers.value
.filter(member => member.role === 'admin')
.map(member => member.uid);
return groupMembers.value;
} catch (error) {
if (!silent && activeConversation.value?.id === requestedConversationId) {
conversations.setActionError(error.message || '群员加载失败');
}
return [];
} finally {
groupBusy.value = false;
if (activeConversation.value?.id === requestedConversationId) groupBusy.value = false;
}
}
@@ -1065,7 +1136,9 @@ onBeforeUnmount(() => {
watch(
() => activeConversation.value?.id,
() => {
async () => {
conversations.actionError = '';
conversations.actionNotice = '';
closeGroupMenu();
closeSingleProfile();
closeGroupPanel();
@@ -1076,6 +1149,9 @@ watch(
selectedKickIds.value = [];
transferTargetId.value = '';
manageSection.value = '';
if (isGroupConversation.value) {
await loadGroupMembers({ silent: true });
}
);
}
, { immediate: true });
</script>
+91 -87
View File
@@ -17,36 +17,10 @@
<button type="button" title="取消引用" @click="$emit('cancel-quote')">×</button>
</div>
<div class="composer-tools">
<button type="button" title="表情" aria-label="表情" :disabled="disabled" @click="toggleEmojiPicker">☺</button>
<button
type="button"
class="composer-tool-button image-tool"
title="图片"
aria-label="图片"
:disabled="disabled"
@click="chooseImage"
>
<svg class="composer-tool-icon" viewBox="0 0 24 24" aria-hidden="true">
<rect x="3" y="5" width="18" height="14" rx="2.5"></rect>
<circle cx="8.2" cy="9.2" r="1.6"></circle>
<path d="M6.5 17l4.2-4.7 3.1 3.4 1.8-2 2.9 3.3"></path>
</svg>
</button>
<button
type="button"
class="composer-tool-button file-tool"
title="文件"
aria-label="文件"
:disabled="disabled"
@click="chooseFile"
>
<svg class="composer-tool-icon" viewBox="0 0 24 24" aria-hidden="true">
<path d="M7 3.8h7.2L19 8.6V20a1.8 1.8 0 0 1-1.8 1.8H7A1.8 1.8 0 0 1 5.2 20V5.6A1.8 1.8 0 0 1 7 3.8z"></path>
<path d="M14 4v5h5"></path>
<path d="M8.5 13h7"></path>
<path d="M8.5 16.5h5.2"></path>
</svg>
</button>
<button type="button" title="表情" :disabled="disabled" @click="toggleEmojiPicker">☺</button>
<button type="button" title="艾特群成员" :disabled="disabled || !mentionUsers.length" @click="openMentionPicker">@</button>
<button type="button" title="图片" :disabled="disabled" @click="chooseImage">▧</button>
<button type="button" title="文件" :disabled="disabled" @click="chooseFile">▤</button>
<input ref="imageInput" type="file" accept="image/*" multiple @change="selectAttachment($event, 'image')">
<input ref="fileInput" type="file" multiple @change="selectAttachment($event, 'file')">
<div v-if="emojiOpen" class="emoji-picker" @click.stop>
@@ -60,39 +34,36 @@
</button>
</div>
</div>
<div v-if="pendingAttachments.length" class="composer-attachment-preview">
<article
v-for="(attachment, index) in pendingAttachments"
:key="attachment.id"
class="composer-attachment-item"
>
<img
v-if="attachment.type === 'image'"
:src="attachment.previewUrl"
:alt="attachment.file.name || '待发送图片'"
>
<span v-else class="composer-attachment-file-icon">▤</span>
<span class="composer-attachment-name">{{ attachment.file.name }}</span>
<button type="button" title="移除" aria-label="移除待发送文件" @click="removePendingAttachment(index)">×</button>
</article>
</div>
<textarea
ref="textareaEl"
v-model="text"
:disabled="disabled"
placeholder="输入消息"
rows="3"
@input="handleMentionInput"
@keydown.enter.exact.prevent="submit"
></textarea>
<div v-if="mentionOpen && filteredMentionUsers.length" class="mention-picker">
<button
v-for="member in filteredMentionUsers"
:key="member.uid"
type="button"
@click="selectMention(member)"
>
<img v-if="member.portrait" :src="member.portrait" alt="">
<span v-else>{{ mentionName(member).slice(0, 1) }}</span>
<strong>{{ mentionName(member) }}</strong>
</button>
</div>
<div class="composer-footer">
<span>Enter 发送,Shift + Enter 换行</span>
<button class="send-button" :disabled="disabled || (!text.trim() && !pendingAttachments.length)">发送</button>
<button class="send-button" :disabled="disabled || !text.trim()">发送</button>
</div>
</form>
</template>
<script setup>
import { onBeforeUnmount, ref } from 'vue';
import { computed, nextTick, ref } from 'vue';
const props = defineProps({
disabled: {
@@ -102,6 +73,10 @@ const props = defineProps({
quoteMessage: {
type: Object,
default: null
},
mentionUsers: {
type: Array,
default: () => []
}
});
@@ -112,36 +87,83 @@ const dropActive = ref(false);
const textareaEl = ref(null);
const imageInput = ref(null);
const fileInput = ref(null);
const pendingAttachments = ref([]);
const mentionOpen = ref(false);
const mentionQuery = ref('');
const mentionStart = ref(-1);
const mentionedUserIds = ref([]);
let dragDepth = 0;
const emojiList = [
'😀', '😄', '😂', '😊', '😍', '😘', '😎', '😢',
'😡', '👍', '🙏', '👏', '💪', '🎉', '❤️', '🔥',
'🌹', '☕', '✅', '⭐', '💰', '🎁', '🤝', '👌'
];
const filteredMentionUsers = computed(() => {
const query = mentionQuery.value.toLowerCase();
return props.mentionUsers
.filter(member => member?.uid)
.filter(member => !query || mentionName(member).toLowerCase().includes(query))
.slice(0, 12);
});
function submit() {
const value = text.value.trim();
const attachments = [...pendingAttachments.value];
if (!value && !attachments.length) {
if (!value) {
return;
}
if (attachments.length) {
attachments.forEach((attachment, index) => {
emit('send-attachment', {
type: attachment.type,
file: attachment.file,
text: index === 0 ? value : ''
});
});
clearPendingAttachments();
} else {
emit('send', value);
}
emit('send', { text: value, mentionedUserIds: [...mentionedUserIds.value] });
text.value = '';
mentionedUserIds.value = [];
mentionOpen.value = false;
emojiOpen.value = false;
}
function mentionName(member) {
return String(member?.displayName || member?.name || member?.rawName || member?.uid || '群成员');
}
function handleMentionInput(event) {
const cursor = event?.target?.selectionStart ?? text.value.length;
const beforeCursor = text.value.slice(0, cursor);
const match = beforeCursor.match(/@([^\s@]*)$/);
mentionOpen.value = Boolean(match && props.mentionUsers.length);
mentionQuery.value = match?.[1] || '';
mentionStart.value = match ? cursor - match[1].length - 1 : -1;
}
function openMentionPicker() {
if (!props.mentionUsers.length) return;
const element = textareaEl.value;
const start = element?.selectionStart ?? text.value.length;
const end = element?.selectionEnd ?? start;
text.value = `${text.value.slice(0, start)}@${text.value.slice(end)}`;
mentionStart.value = start;
mentionQuery.value = '';
mentionOpen.value = true;
nextTick(() => {
element?.focus();
element?.setSelectionRange(start + 1, start + 1);
});
}
function selectMention(member) {
const element = textareaEl.value;
const cursor = element?.selectionStart ?? text.value.length;
const start = mentionStart.value >= 0 ? mentionStart.value : cursor;
const name = mentionName(member);
text.value = `${text.value.slice(0, start)}@${name} ${text.value.slice(cursor)}`;
if (!mentionedUserIds.value.includes(String(member.uid))) {
mentionedUserIds.value.push(String(member.uid));
}
mentionOpen.value = false;
mentionQuery.value = '';
mentionStart.value = -1;
nextTick(() => {
const nextCursor = start + name.length + 2;
element?.focus();
element?.setSelectionRange(nextCursor, nextCursor);
});
}
function toggleEmojiPicker() {
emojiOpen.value = !emojiOpen.value;
}
@@ -186,34 +208,18 @@ function emitFiles(files, fallbackType = 'file') {
return;
}
validFiles.forEach(file => {
const type = attachmentTypeForFile(file, fallbackType);
pendingAttachments.value.push({
id: `${Date.now()}-${Math.random().toString(16).slice(2)}`,
type,
const caption = text.value.trim();
validFiles.forEach((file, index) => {
emit('send-attachment', {
type: attachmentTypeForFile(file, fallbackType),
file,
previewUrl: type === 'image' ? URL.createObjectURL(file) : ''
text: index === 0 ? caption : ''
});
});
text.value = '';
emojiOpen.value = false;
}
function releasePendingAttachment(attachment) {
if (attachment?.previewUrl) {
URL.revokeObjectURL(attachment.previewUrl);
}
}
function removePendingAttachment(index) {
const [attachment] = pendingAttachments.value.splice(index, 1);
releasePendingAttachment(attachment);
}
function clearPendingAttachments() {
pendingAttachments.value.forEach(releasePendingAttachment);
pendingAttachments.value = [];
}
function selectAttachment(event, type) {
const input = event.target;
const files = input.files ? Array.from(input.files) : [];
@@ -292,6 +298,4 @@ function handlePaste(event) {
event.preventDefault();
emitFiles(imageFiles, 'image');
}
onBeforeUnmount(clearPendingAttachments);
</script>
+204 -96
View File
@@ -4,11 +4,12 @@
v-for="message in messages"
:key="message.id"
class="message-row"
:class="[message.direction, { selected: isSelected(message), attention: isAttention(message), recalled: message.recalled || message.status === 'recalled' }]"
:class="[message.direction, { system: isSystemMessage(message), selected: isSelected(message), attention: isAttention(message), recalled: message.recalled || message.status === 'recalled' }]"
:data-message-key="messageIdentity(message)"
@click="handleMessageClick(message)"
>
<label v-if="selectionMode" class="message-select">
<div v-if="isSystemMessage(message)" class="system-message-pill">{{ systemMessageText(message) }}</div>
<label v-if="selectionMode && !isSystemMessage(message)" class="message-select">
<input
type="checkbox"
:checked="isSelected(message)"
@@ -17,16 +18,16 @@
>
</label>
<button
v-if="showGroupSender(message)"
v-if="!isSystemMessage(message) && showGroupSender(message)"
type="button"
class="message-sender-avatar"
:title="groupSenderName(message)"
@click.stop="openSenderProfile(message)"
>
<img v-if="message.senderPortrait" :src="message.senderPortrait" alt="">
<img v-if="message.senderPortrait" :src="message.senderPortrait" alt="" @error="useImageProxyFallback($event, message.senderPortrait)">
<span v-else>{{ groupSenderAvatarText(message) }}</span>
</button>
<div class="message-stack">
<div v-if="!isSystemMessage(message)" class="message-stack">
<button
v-if="showGroupSender(message)"
type="button"
@@ -41,20 +42,39 @@
:class="roleBubbleClass(message)"
@contextmenu.prevent="openMenu($event, message)"
>
<div v-if="isRedPacketMessage(message)" class="red-packet-card">
<div class="red-packet-card-main">
<span class="red-packet-icon">福</span>
<span>
<strong>{{ redPacketBlessing(message) }}</strong>
<small>请在 App 上领取</small>
</span>
</div>
<div class="red-packet-card-footer">中聊红包</div>
</div>
<div v-else-if="isRedPacketReceipt(message)" class="red-packet-receipt">
<span class="red-packet-mini-icon">福</span>
<span>{{ redPacketReceiptText(message) }}</span>
</div>
<button
v-if="isImageMessage(message)"
v-else-if="isImageMessage(message)"
type="button"
class="message-image"
@click.stop="handleImageClick(message)"
>
<img
:src="imageDisplayUrl(message.attachment.url)"
:alt="message.attachment.name || '图片'"
loading="lazy"
decoding="async"
@error="retryImageLoad"
>
<img :src="message.attachment.url" :alt="message.attachment.name || '图片'">
</button>
<video
v-else-if="isVideoMessage(message)"
class="message-video"
:src="videoDisplayUrl(message.attachment.url)"
controls
playsinline
preload="metadata"
@error="useVideoOriginalFallback($event, message.attachment.url)"
>
当前浏览器无法播放该视频
</video>
<a
v-else-if="isFileMessage(message)"
class="message-file"
@@ -65,11 +85,11 @@
>
<span class="message-file-icon">▤</span>
<span class="message-file-main">
<strong>{{ message.attachment.name || '文件' }}</strong>
<strong>{{ displayFileName(message) }}</strong>
<small>{{ formatFileSize(message.attachment.size) }}</small>
</span>
</a>
<p v-if="displayMessageText(message)">{{ displayMessageText(message) }}</p>
<p v-if="message.text && !isFileMessage(message) && !isRedPacketMessage(message) && !isRedPacketReceipt(message)">{{ message.text }}</p>
<time>
<span v-if="isRecallNotice(message)" class="recall-mark">{{ message.recallStatus || '已撤回' }}</span>
<span>{{ formatTime(message.displayTimestamp || message.timestamp) }}</span>
@@ -116,10 +136,6 @@
@click.stop
>
<div class="image-viewer-toolbar">
<span class="image-viewer-title">{{ imageViewer.name || '图片' }}</span>
<button type="button" title="缩小" aria-label="缩小" @click="zoomImage(-0.25)">−</button>
<button type="button" title="放大" aria-label="放大" @click="zoomImage(0.25)">+</button>
<button type="button" title="还原" aria-label="还原" @click="resetImageViewer">1:1</button>
<button type="button" title="旋转" aria-label="旋转" @click="rotateImage">⟳</button>
<button type="button" title="保存" aria-label="保存" @click="saveViewerImage">⇩</button>
<button type="button" title="关闭" aria-label="关闭" @click="closeImageViewer">×</button>
@@ -127,19 +143,32 @@
<div
ref="viewerStage"
class="image-viewer-stage"
:class="{ dragging: imageViewer.dragging, zoomed: imageViewer.scale > 1 }"
@wheel.prevent="handleImageWheel"
@pointerdown.prevent="startImageDrag"
>
<button
v-if="viewerImages.length > 1"
type="button"
class="image-viewer-nav image-viewer-prev"
title="上一张"
aria-label="上一张"
@pointerdown.stop
@click.stop="showPreviousImage"
>‹</button>
<img
class="image-viewer-img"
:src="imageDisplayUrl(imageViewer.url)"
:src="imageViewer.url"
:alt="imageViewer.name || '图片'"
:style="imageViewerStyle"
decoding="async"
@error="retryImageLoad"
draggable="false"
>
<button
v-if="viewerImages.length > 1"
type="button"
class="image-viewer-nav image-viewer-next"
title="下一张"
aria-label="下一张"
@pointerdown.stop
@click.stop="showNextImage"
>›</button>
</div>
</div>
</div>
@@ -156,15 +185,15 @@
<button type="button" class="icon-button" title="关闭" @click="closeSenderProfile">×</button>
</header>
<div class="sender-profile-main">
<img v-if="senderProfile.portrait" class="profile-avatar image-avatar" :src="senderProfile.portrait" alt="">
<img v-if="senderProfile.portrait" class="profile-avatar image-avatar" :src="senderProfile.portrait" alt="" @error="useImageProxyFallback($event, senderProfile.portrait)">
<div v-else class="profile-avatar">{{ senderProfile.avatarText }}</div>
<strong>{{ senderProfile.displayName || senderProfile.uid }}</strong>
<span v-if="senderProfile.roleLabel">{{ senderProfile.roleLabel }}</span>
</div>
<dl class="sender-profile-fields">
<div>
<div v-if="senderProfile.isContact">
<dt>用户ID</dt>
<dd>{{ senderProfile.uid || '-' }}</dd>
<dd>{{ senderProfile.userId || '-' }}</dd>
</div>
<div>
<dt>昵称</dt>
@@ -219,7 +248,8 @@
<script setup>
import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue';
import { useContactStore } from '@/stores/contacts';
import { imageDisplayUrl } from '@/services/mediaProxy';
import { useImageProxyFallback, useVideoOriginalFallback, videoDisplayUrl } from '@/services/mediaProxy';
import { useAutoDismiss } from '@/composables/useAutoDismiss';
const props = defineProps({
messages: {
@@ -238,6 +268,10 @@ const props = defineProps({
type: Array,
default: () => []
},
pinnedMessageId: {
type: String,
default: ''
},
attentionMessageId: {
type: String,
default: ''
@@ -260,16 +294,12 @@ const contextMenu = reactive({
});
const IMAGE_MIN_SCALE = 0.5;
const IMAGE_MAX_SCALE = 6;
const messageTimeFormatter = new Intl.DateTimeFormat('zh-CN', {
hour: '2-digit',
minute: '2-digit',
hour12: false,
timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone
});
const imageViewer = reactive({
visible: false,
url: '',
name: '',
sourceUrl: '',
index: 0,
scale: 1,
rotation: 0,
offsetX: 0,
@@ -283,6 +313,7 @@ const imageViewer = reactive({
const senderProfile = reactive({
visible: false,
uid: '',
userId: '',
displayName: '',
rawName: '',
mobile: '',
@@ -300,11 +331,22 @@ const senderProfile = reactive({
notice: '',
error: ''
});
useAutoDismiss(
() => senderProfile.error || senderProfile.notice,
value => {
if ((senderProfile.error || senderProfile.notice) === value) {
senderProfile.error = '';
senderProfile.notice = '';
}
}
);
const imageViewerStyle = computed(() => ({
transform: `translate3d(${imageViewer.offsetX}px, ${imageViewer.offsetY}px, 0) scale(${imageViewer.scale}) rotate(${imageViewer.rotation}deg)`
}));
const viewerImages = computed(() => props.messages.filter(message => isImageMessage(message)));
const menuItems = computed(() => {
if (!contextMenu.message) {
return [];
@@ -319,11 +361,13 @@ const menuItems = computed(() => {
];
}
const favoriteLabel = isFavorite(contextMenu.message) ? '取消收藏' : '收藏';
const pinnedLabel = props.pinnedMessageId === messageIdentity(contextMenu.message) ? '取消置顶' : '置顶';
const items = [
{ action: 'copy', label: '复制' },
{ action: 'delete', label: '删除' },
{ action: 'forward', label: '转发' },
{ action: 'favorite', label: favoriteLabel },
{ action: 'pin', label: pinnedLabel },
{ action: 'quote', label: '引用' },
{ action: 'select', label: '多选' },
{ action: 'detail', label: '详情' }
@@ -339,20 +383,10 @@ const menuItems = computed(() => {
function scrollToBottom() {
nextTick(() => {
requestAnimationFrame(() => {
if (listEl.value) {
listEl.value.scrollTop = listEl.value.scrollHeight;
}
});
});
}
function isNearBottom() {
const element = listEl.value;
if (!element) {
return true;
}
return element.scrollHeight - element.scrollTop - element.clientHeight < 120;
}
function scrollToMessage(messageId) {
@@ -369,12 +403,8 @@ function scrollToMessage(messageId) {
}
watch(
() => props.messages.map(messageIdentity).join('|'),
(nextKeys, previousKeys) => {
if (!previousKeys || (nextKeys !== previousKeys && isNearBottom())) {
scrollToBottom();
}
},
() => props.messages.map(message => `${message.id}:${message.status}:${message.deliveryStatus || ''}:${message.messageUid || ''}:${message.recalled ? '1' : ''}`).join('|'),
scrollToBottom,
{ immediate: true }
);
@@ -401,22 +431,6 @@ function messageIdentity(message) {
return String(message.messageUid || message.id || '');
}
function displayMessageText(message) {
const text = String(message?.text || '').replace(/^引用:.*(?:\r?\n|$)/, '').trim();
const contentType = Number(message?.contentType || 0);
if (!text) {
return '';
}
if (contentType !== 1 && text === '[暂不支持的消息类型]') {
return '';
}
if ((contentType === 3 || message?.type === 'image') && (text === '[图片]' || text === '图片')) {
return '';
}
return text;
}
function canOpenMessageMenu(message) {
return message && message.status !== 'failed' && message.status !== 'sending';
}
@@ -449,6 +463,82 @@ function isFileMessage(message) {
return message?.type === 'file' && message?.attachment?.url;
}
function displayFileName(message) {
const text = String(message?.text || '').trim();
const attachmentName = String(message?.attachment?.name || '').trim();
return text || attachmentName || '文件';
}
function isVideoMessage(message) {
return (message?.type === 'video' || Number(message?.contentType || 0) === 6) && message?.attachment?.url;
}
function isRedPacketMessage(message) {
return Number(message?.contentType || 0) === 90 || Boolean(redPacketPayload(message));
}
function isRedPacketReceipt(message) {
return Number(message?.contentType || 0) === 105;
}
function isSystemMessage(message) {
return [92, 93].includes(Number(message?.contentType || 0));
}
function systemMessageText(message) {
const contentType = Number(message?.contentType || 0);
if (contentType === 92) {
return '以上是打招呼的内容';
}
if (contentType === 93) {
return '你们已经是好友了,可以开始聊天了。';
}
return String(message?.text || '');
}
function redPacketReceiptText(message) {
const text = String(message?.text || '').trim();
if (text && text !== '[领取了红包]') {
return text;
}
const receiverName = message?.direction === 'out' ? '你' : (message?.senderName || '对方');
const packetSenderName = message?.redPacketSenderName || nearestRedPacketSenderName(message);
return packetSenderName
? `${receiverName}领取了${packetSenderName}的红包`
: `${receiverName}领取了红包`;
}
function nearestRedPacketSenderName(receiptMessage) {
const receiptIndex = props.messages.findIndex(item => messageIdentity(item) === messageIdentity(receiptMessage));
for (let index = receiptIndex - 1; index >= 0; index -= 1) {
const candidate = props.messages[index];
if (isRedPacketMessage(candidate)) {
return candidate?.direction === 'out' ? '你' : (candidate?.senderName || '对方');
}
}
return '';
}
function redPacketPayload(message) {
if (message?.redPacket && typeof message.redPacket === 'object') {
return message.redPacket;
}
const text = String(message?.text || '').trim();
if (!text.startsWith('{')) {
return null;
}
try {
const payload = JSON.parse(text);
return payload?.redPackets || payload?.redPacket || null;
} catch (error) {
return null;
}
}
function redPacketBlessing(message) {
return String(redPacketPayload(message)?.blessing || '恭喜发财,大吉大利');
}
function isGroupMessage(message) {
return ['group', 'channel'].includes(message?.conversationType || '');
}
@@ -491,6 +581,10 @@ function openSenderProfile(message) {
const displayName = contactAlias || groupAlias || rawName || uid;
senderProfile.visible = true;
senderProfile.uid = uid;
senderProfile.userId = profile.userId
|| profile.name
|| cachedContact?.rawUser?.name
|| '';
senderProfile.displayName = displayName;
senderProfile.rawName = rawName || '';
senderProfile.mobile = profile.mobile || cachedContact?.rawUser?.mobile || '';
@@ -597,30 +691,6 @@ function formatFileSize(size) {
return bytes > 0 ? `${bytes} B` : '';
}
function retryImageLoad(event) {
const image = event.currentTarget;
if (!(image instanceof HTMLImageElement)) {
return;
}
const attempts = Number(image.dataset.loadRetries || 0);
if (attempts >= 2) {
return;
}
const originalUrl = image.dataset.originalUrl || image.getAttribute('src') || '';
if (!originalUrl) {
return;
}
image.dataset.originalUrl = originalUrl;
image.dataset.loadRetries = String(attempts + 1);
window.setTimeout(() => {
if (!image.isConnected) {
return;
}
const separator = originalUrl.includes('?') ? '&' : '?';
image.src = `${originalUrl}${separator}_image_retry=${attempts + 1}`;
}, 500 * (attempts + 1));
}
function handleMessageClick(message) {
if (props.selectionMode) {
emit('toggle-select', message);
@@ -642,14 +712,37 @@ function openImageViewer(message) {
}
closeMenu();
imageViewer.visible = true;
imageViewer.url = attachment.url;
imageViewer.name = attachment.name || 'image';
const index = viewerImages.value.findIndex(item => messageIdentity(item) === messageIdentity(message));
showViewerImage(index >= 0 ? index : 0);
}
function showViewerImage(index) {
const images = viewerImages.value;
if (!images.length) {
closeImageViewer();
return;
}
const normalizedIndex = (index + images.length) % images.length;
const attachment = images[normalizedIndex]?.attachment || {};
imageViewer.index = normalizedIndex;
imageViewer.sourceUrl = attachment.url || '';
imageViewer.url = attachment.url || '';
imageViewer.name = attachment.name || `图片 ${normalizedIndex + 1}`;
resetImageViewer();
}
function showPreviousImage() {
showViewerImage(imageViewer.index - 1);
}
function showNextImage() {
showViewerImage(imageViewer.index + 1);
}
function closeImageViewer() {
imageViewer.visible = false;
imageViewer.dragging = false;
imageViewer.sourceUrl = '';
}
function resetImageViewer() {
@@ -723,11 +816,11 @@ function stopImageDrag() {
}
function saveViewerImage() {
if (!imageViewer.url) {
if (!imageViewer.sourceUrl) {
return;
}
const downloadUrl = new URL('/api/media_download.php', window.location.origin);
downloadUrl.searchParams.set('url', imageViewer.url);
downloadUrl.searchParams.set('url', imageViewer.sourceUrl);
downloadUrl.searchParams.set('name', imageViewer.name || 'image');
const link = document.createElement('a');
@@ -755,6 +848,16 @@ function closeMenu() {
}
function closeMenuOnEscape(event) {
if (imageViewer.visible && event.key === 'ArrowLeft') {
event.preventDefault();
showPreviousImage();
return;
}
if (imageViewer.visible && event.key === 'ArrowRight') {
event.preventDefault();
showNextImage();
return;
}
if (event.key === 'Escape') {
if (senderProfile.visible) {
closeSenderProfile();
@@ -774,7 +877,12 @@ function chooseMenuAction(action) {
}
function formatTime(timestamp) {
return messageTimeFormatter.format(timestamp);
return new Intl.DateTimeFormat('zh-CN', {
hour: '2-digit',
minute: '2-digit',
hour12: false,
timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone
}).format(timestamp);
}
function deliveryState(message) {
+6 -1
View File
@@ -9,7 +9,7 @@
</header>
<div class="contact-profile">
<img v-if="contact.portrait" class="profile-avatar image-avatar" :src="contact.portrait" alt="">
<img v-if="contact.portrait" class="profile-avatar image-avatar" :src="contact.portrait" alt="" @error="useImageProxyFallback($event, contact.portrait)">
<div v-else class="profile-avatar">{{ contact.avatarText }}</div>
<div class="profile-main">
<div class="remark-row">
@@ -63,6 +63,8 @@
<script setup>
import { computed, ref, watch } from 'vue';
import { useContactStore } from '@/stores/contacts';
import { useAutoDismiss } from '@/composables/useAutoDismiss';
import { useImageProxyFallback } from '@/services/mediaProxy';
const contacts = useContactStore();
const contact = computed(() => contacts.activeContact);
@@ -74,6 +76,9 @@ const editingAlias = ref(false);
const aliasDraft = ref('');
const aliasSaving = ref(false);
const aliasError = ref('');
useAutoDismiss(aliasError, value => {
if (aliasError.value === value) aliasError.value = '';
});
watch(contact, () => {
editingAlias.value = false;
+7 -3
View File
@@ -15,11 +15,11 @@
<a
v-if="isImageFavorite(favorite)"
class="favorite-detail-image"
:href="imageDisplayUrl(favorite.attachment.url)"
:href="favorite.attachment.url"
target="_blank"
rel="noreferrer"
>
<img :src="imageDisplayUrl(favorite.attachment.url)" :alt="favorite.attachment.name || '图片'">
<img :src="favorite.attachment.url" :alt="favorite.attachment.name || '图片'">
</a>
<a
v-else-if="isFileFavorite(favorite)"
@@ -59,7 +59,7 @@
import { computed, ref } from 'vue';
import { useConversationStore } from '@/stores/conversations';
import { useNavigationStore } from '@/stores/navigation';
import { imageDisplayUrl } from '@/services/mediaProxy';
import { useAutoDismiss } from '@/composables/useAutoDismiss';
const conversations = useConversationStore();
const navigation = useNavigationStore();
@@ -67,6 +67,10 @@ const favorite = computed(() => conversations.activeFavorite);
const notice = ref('');
const error = ref('');
useAutoDismiss(() => error.value || notice.value, value => {
if ((error.value || notice.value) === value) clearFeedback();
});
function clearFeedback() {
notice.value = '';
error.value = '';
+2 -1
View File
@@ -23,7 +23,7 @@
:class="{ active: item.id === contacts.activeId }"
@click="contacts.setActiveContact(item.id)"
>
<img v-if="item.portrait" class="conversation-avatar image-avatar" :src="item.portrait" alt="">
<img v-if="item.portrait" class="conversation-avatar image-avatar" :src="item.portrait" alt="" @error="useImageProxyFallback($event, item.portrait)">
<span v-else class="conversation-avatar">{{ item.avatarText }}</span>
<span class="conversation-copy">
<strong>{{ item.title }}</strong>
@@ -63,6 +63,7 @@
<script setup>
import { computed, ref } from 'vue';
import { useContactStore } from '@/stores/contacts';
import { useImageProxyFallback } from '@/services/mediaProxy';
const contacts = useContactStore();
const keyword = ref('');
+52 -7
View File
@@ -26,13 +26,14 @@
v-for="item in filteredConversationItems"
:key="item.resultKey"
class="conversation-item"
:class="{ active: isListItemActive(item) }"
:class="{ active: isListItemActive(item), pinned: isPinned(item) }"
@click="selectListItem(item)"
@contextmenu.prevent="openConversationMenu($event, item)"
>
<img v-if="item.portrait" class="conversation-avatar image-avatar" :src="item.portrait" alt="">
<img v-if="item.portrait" class="conversation-avatar image-avatar" :src="item.portrait" alt="" @error="useImageProxyFallback($event, item.portrait)">
<span v-else class="conversation-avatar">{{ item.avatarText }}</span>
<span class="conversation-copy">
<strong>{{ item.title }}</strong>
<strong><span v-if="isPinned(item)" class="conversation-pin" aria-label="已置顶">⌖</span>{{ item.title }}</strong>
<small>{{ item.subtitle }}</small>
</span>
<span
@@ -44,6 +45,18 @@
</span>
</button>
<div
v-if="conversationMenu.item"
class="conversation-context-menu"
:style="{ left: `${conversationMenu.x}px`, top: `${conversationMenu.y}px` }"
@click.stop
>
<button type="button" @click="togglePinned">
{{ isPinned(conversationMenu.item) ? '取消置顶' : '置顶会话' }}
</button>
<button type="button" @click="deleteConversation">删除会话</button>
</div>
<div v-if="!filteredConversationItems.length && searchKeyword" class="empty-list">
<strong>没有匹配结果</strong>
<span>换个关键词再试试</span>
@@ -52,10 +65,6 @@
<div v-else-if="!conversations.conversations.length && !conversations.usingDemoData" class="empty-list">
<strong>暂无会话</strong>
<span>收到或发起消息后会出现在这里</span>
<div class="empty-list-actions">
<button type="button" class="primary-inline-action" @click="openAction('createGroup')">新建群组</button>
<button type="button" class="ghost-inline-action" @click="openAction('joinGroup')">加入群组</button>
</div>
</div>
</div>
@@ -155,6 +164,7 @@
import { computed, defineComponent, h, onBeforeUnmount, onMounted, ref } from 'vue';
import { useConversationStore } from '@/stores/conversations';
import { useContactStore } from '@/stores/contacts';
import { useImageProxyFallback } from '@/services/mediaProxy';
const conversations = useConversationStore();
const contacts = useContactStore();
@@ -172,6 +182,7 @@ const channelName = ref('');
const channelAnnouncement = ref('');
const contactKeyword = ref('');
const selectedContactIds = ref([]);
const conversationMenu = ref({ item: null, x: 0, y: 0 });
const actionTitles = {
addContact: '添加联系人',
@@ -257,6 +268,38 @@ onMounted(() => {
contacts.refreshContacts().catch(() => {});
});
function isPinned(item) {
return item?.resultKind === 'conversation' && Number(item.pinnedAt || item.top || 0) > 0;
}
function openConversationMenu(event, item) {
if (item.resultKind !== 'conversation') return;
conversationMenu.value = {
item,
x: Math.min(event.clientX, window.innerWidth - 140),
y: Math.min(event.clientY, window.innerHeight - 60)
};
}
function closeConversationMenu() {
conversationMenu.value = { item: null, x: 0, y: 0 };
}
function togglePinned() {
const item = conversationMenu.value.item;
if (item) conversations.togglePinnedConversation(item.id);
closeConversationMenu();
}
function deleteConversation() {
const item = conversationMenu.value.item;
if (item && window.confirm(`确定删除与“${item.title}”的会话吗?`)) {
conversations.removeConversation(item.id);
conversations.setActionNotice('会话已删除');
}
closeConversationMenu();
}
const ContactPicker = defineComponent({
name: 'ContactPicker',
props: {
@@ -518,8 +561,10 @@ async function submitAction() {
}
document.addEventListener('click', closeActionMenu);
document.addEventListener('click', closeConversationMenu);
onBeforeUnmount(() => {
document.removeEventListener('click', closeActionMenu);
document.removeEventListener('click', closeConversationMenu);
});
function formatUnread(value) {
+18 -1
View File
@@ -1,7 +1,7 @@
<template>
<aside class="navigation-rail">
<button type="button" class="rail-avatar rail-avatar-button" title="编辑个人资料" @click="openProfileEditor">
<img v-if="session.portrait" :src="session.portrait" alt="">
<img v-if="session.portrait" :src="session.portrait" alt="" @error="useImageProxyFallback($event, session.portrait)">
<span v-else>{{ initials }}</span>
</button>
<button class="rail-button" :class="{ active: navigation.section === 'messages' }" title="消息" @click="navigation.showMessages">💬</button>
@@ -203,6 +203,8 @@ import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref } from 'v
import { useSessionStore } from '@/stores/session';
import { useNavigationStore } from '@/stores/navigation';
import { useContactStore } from '@/stores/contacts';
import { useAutoDismiss } from '@/composables/useAutoDismiss';
import { useImageProxyFallback } from '@/services/mediaProxy';
const session = useSessionStore();
const navigation = useNavigationStore();
@@ -270,6 +272,21 @@ const avatarCropper = reactive({
dragOffsetX: 0,
dragOffsetY: 0
});
useAutoDismiss(() => settingsError.value || settingsNotice.value, value => {
if ((settingsError.value || settingsNotice.value) === value) {
settingsError.value = '';
settingsNotice.value = '';
}
});
useAutoDismiss(() => profileError.value || profileNotice.value, value => {
if ((profileError.value || profileNotice.value) === value) {
profileError.value = '';
profileNotice.value = '';
}
});
useAutoDismiss(() => avatarCropper.error, value => {
if (avatarCropper.error === value) avatarCropper.error = '';
});
const avatarPreviewStyle = computed(() => ({
transform: `translate3d(${avatarPreviewViewer.offsetX}px, ${avatarPreviewViewer.offsetY}px, 0) scale(${avatarPreviewViewer.scale})`
}));
+18
View File
@@ -0,0 +1,18 @@
import { onBeforeUnmount, watch } from 'vue';
export function useAutoDismiss(source, clear, delay = 3000) {
let timer = null;
watch(source, value => {
window.clearTimeout(timer);
timer = null;
if (!value) return;
const currentValue = value;
timer = window.setTimeout(() => {
clear(currentValue);
timer = null;
}, delay);
}, { flush: 'post' });
onBeforeUnmount(() => window.clearTimeout(timer));
}
+6 -4
View File
@@ -1,12 +1,14 @@
const currentHost = window.location.hostname || '127.0.0.1';
const runtimeConfig = window.JC_WEB_IM_CONFIG || {};
const appServerOrigin = `${window.location.protocol}//${currentHost}:18888`;
const appServerOrigin = `${window.location.protocol}//${currentHost}:8888`;
const qrAppServerOrigin = `${window.location.protocol}//${currentHost}:18888`;
const adminServerOrigin = `${window.location.protocol}//${currentHost}:8024`;
export const appConfig = {
appName: 'Web IM',
adminServer: runtimeConfig.adminServer || process.env.VUE_APP_ADMIN_SERVER || adminServerOrigin,
appServer: runtimeConfig.appServer || process.env.VUE_APP_APP_SERVER || appServerOrigin,
qrAppServer: runtimeConfig.qrAppServer || process.env.VUE_APP_QR_APP_SERVER || qrAppServerOrigin,
platformConfigApi: runtimeConfig.platformConfigApi || process.env.VUE_APP_PLATFORM_CONFIG_API || (process.env.NODE_ENV === 'development' ? '/local-api/platform_config.php' : '/api/platform_config.php'),
registerConfigApi: runtimeConfig.registerConfigApi || process.env.VUE_APP_REGISTER_CONFIG_API || `${adminServerOrigin}/api/register-config`,
registerPhoneExistsApi: runtimeConfig.registerPhoneExistsApi || process.env.VUE_APP_REGISTER_PHONE_EXISTS_API || `${adminServerOrigin}/api/register-phone-exists`,
@@ -19,15 +21,15 @@ export const appConfig = {
messageDetailApi: runtimeConfig.messageDetailApi || process.env.VUE_APP_MESSAGE_DETAIL_API || (process.env.NODE_ENV === 'development' ? '/local-api/message_detail.php' : '/api/message_detail.php'),
messagesApi: runtimeConfig.messagesApi || process.env.VUE_APP_MESSAGES_API || (process.env.NODE_ENV === 'development' ? '/local-api/messages.php' : '/api/messages.php'),
profileApi: runtimeConfig.profileApi || process.env.VUE_APP_PROFILE_API || (process.env.NODE_ENV === 'development' ? '/local-api/profile.php' : '/api/profile.php'),
changePasswordApi: runtimeConfig.changePasswordApi || process.env.VUE_APP_CHANGE_PASSWORD_API || `${appServerOrigin}/change_pwd`,
resetPasswordApi: runtimeConfig.resetPasswordApi || process.env.VUE_APP_RESET_PASSWORD_API || `${appServerOrigin}/reset_pwd`,
changePasswordApi: runtimeConfig.changePasswordApi || process.env.VUE_APP_CHANGE_PASSWORD_API || `${appServerOrigin}/auth/changePassword`,
logoutApi: runtimeConfig.logoutApi || process.env.VUE_APP_LOGOUT_API || `${appServerOrigin}/auth/logout`,
imServerHost: runtimeConfig.imServerHost || process.env.VUE_APP_IM_SERVER_HOST || currentHost,
imRoutePort: Number(runtimeConfig.imRoutePort || process.env.VUE_APP_IM_ROUTE_PORT || 18000),
useWss: runtimeConfig.useWss ?? process.env.VUE_APP_USE_WSS === 'true',
wsPath: runtimeConfig.wsPath || process.env.VUE_APP_WS_PATH || '/ws',
wsUrl: runtimeConfig.wsUrl || process.env.VUE_APP_WS_URL || '',
sdkMode: runtimeConfig.sdkMode || process.env.VUE_APP_IM_MODE || 'http',
syncIntervalMs: Number(runtimeConfig.syncIntervalMs || process.env.VUE_APP_SYNC_INTERVAL_MS || 15000),
syncIntervalMs: Number(runtimeConfig.syncIntervalMs || process.env.VUE_APP_SYNC_INTERVAL_MS || 300),
sseEnabled: runtimeConfig.sseEnabled ?? process.env.VUE_APP_SSE_ENABLED === 'true',
sseTicketApi: runtimeConfig.sseTicketApi || process.env.VUE_APP_SSE_TICKET_API || '/api/sse_ticket.php',
sseUrl: runtimeConfig.sseUrl || process.env.VUE_APP_SSE_URL || '/ws-events',
+266
View File
@@ -0,0 +1,266 @@
import axios from 'axios';
import { appConfig } from '@/config';
const AES_KEY = 'xczx2026!@#secKe';
const ENCRYPTION_EXCLUDE_PATHS = ['/avatar/', '/f/', '/amr2mp3', '/appVersion/check'];
const AUTH_STORAGE_KEY = 'qmt-web-im-app-auth-v1';
const AUTH_ERROR_CODE = 13;
const REFRESH_ERROR_CODE = 20045;
let importedCryptoKeyPromise = null;
let refreshPromise = null;
function storageScope() {
return appConfig.appServer || '';
}
function readAuthStore() {
try {
return JSON.parse(localStorage.getItem(AUTH_STORAGE_KEY) || '{}');
} catch (error) {
return {};
}
}
function writeAuthStore(store) {
localStorage.setItem(AUTH_STORAGE_KEY, JSON.stringify(store));
}
function normalizeAuthBundle(bundle = {}) {
const accessToken = String(bundle.accessToken || '').trim();
const refreshToken = String(bundle.refreshToken || '').trim();
if (!accessToken || !refreshToken) {
return null;
}
return {
accessToken,
refreshToken,
tokenType: String(bundle.tokenType || 'Bearer').trim() || 'Bearer',
accessTokenExpireIn: Number(bundle.accessTokenExpireIn || 0) || 0,
accessTokenExpireAt: Number(bundle.accessTokenExpireAt || 0) || 0,
refreshTokenExpireIn: Number(bundle.refreshTokenExpireIn || 0) || 0,
refreshTokenExpireAt: Number(bundle.refreshTokenExpireAt || 0) || 0
};
}
export function getStoredAppAuth() {
const store = readAuthStore();
return normalizeAuthBundle(store[storageScope()]);
}
export function persistAppAuth(bundle) {
const normalized = normalizeAuthBundle(bundle);
const store = readAuthStore();
if (!normalized) {
delete store[storageScope()];
writeAuthStore(store);
return null;
}
store[storageScope()] = normalized;
writeAuthStore(store);
return normalized;
}
export function clearStoredAppAuth() {
persistAppAuth(null);
}
function hasFormData(value) {
return typeof FormData !== 'undefined' && value instanceof FormData;
}
function absoluteUrl(url) {
return new URL(url, window.location.origin);
}
function shouldEncrypt(url) {
const pathname = absoluteUrl(url).pathname;
return !ENCRYPTION_EXCLUDE_PATHS.some(path => pathname === path || pathname.startsWith(path));
}
function shouldAttachAuth(config) {
return !config.skipAuth;
}
function textEncoder() {
return new TextEncoder();
}
function textDecoder() {
return new TextDecoder();
}
function bytesToBase64(bytes) {
let binary = '';
bytes.forEach(byte => {
binary += String.fromCharCode(byte);
});
return btoa(binary);
}
function base64ToBytes(base64) {
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let index = 0; index < binary.length; index += 1) {
bytes[index] = binary.charCodeAt(index);
}
return bytes;
}
async function getCryptoKey() {
if (!importedCryptoKeyPromise) {
importedCryptoKeyPromise = window.crypto.subtle.importKey(
'raw',
textEncoder().encode(AES_KEY),
{ name: 'AES-CBC' },
false,
['encrypt', 'decrypt']
);
}
return importedCryptoKeyPromise;
}
async function encryptPayload(plainText) {
const iv = window.crypto.getRandomValues(new Uint8Array(16));
const key = await getCryptoKey();
const encrypted = await window.crypto.subtle.encrypt(
{ name: 'AES-CBC', iv },
key,
textEncoder().encode(plainText)
);
return `${bytesToBase64(iv)}:${bytesToBase64(new Uint8Array(encrypted))}`;
}
async function decryptPayload(cipherText) {
const [ivBase64, encryptedBase64] = String(cipherText || '').split(':', 2);
if (!ivBase64 || !encryptedBase64) {
throw new Error('Encrypted payload format is invalid');
}
const key = await getCryptoKey();
const decrypted = await window.crypto.subtle.decrypt(
{ name: 'AES-CBC', iv: base64ToBytes(ivBase64) },
key,
base64ToBytes(encryptedBase64)
);
return textDecoder().decode(decrypted);
}
function normalizeBusinessResponse(payload) {
if (payload && typeof payload === 'object' && !Array.isArray(payload)) {
return payload;
}
return {
code: 0,
message: 'success',
data: payload
};
}
async function decodeResponsePayload(response) {
const encrypted = String(response.headers?.['x-encrypted'] || '').toLowerCase() === 'true';
if (encrypted && typeof response.data === 'string') {
const plainText = await decryptPayload(response.data);
response.data = normalizeBusinessResponse(JSON.parse(plainText));
return response;
}
response.data = normalizeBusinessResponse(response.data);
return response;
}
const client = axios.create({
withCredentials: false
});
client.interceptors.request.use(async config => {
const nextConfig = { ...config };
const url = absoluteUrl(nextConfig.url || '').toString();
if (shouldAttachAuth(nextConfig)) {
const auth = getStoredAppAuth();
if (auth?.accessToken) {
nextConfig.headers = {
...(nextConfig.headers || {}),
Authorization: `${auth.tokenType || 'Bearer'} ${auth.accessToken}`
};
}
}
if (!hasFormData(nextConfig.data) && nextConfig.method?.toLowerCase() !== 'get' && shouldEncrypt(url)) {
const plainBody = JSON.stringify(nextConfig.data ?? {});
nextConfig.data = await encryptPayload(plainBody);
nextConfig.headers = {
...(nextConfig.headers || {}),
'Content-Type': 'text/plain;charset=UTF-8',
'X-Timestamp': `${Math.floor(Date.now() / 1000)}`
};
}
return nextConfig;
});
client.interceptors.response.use(async response => decodeResponsePayload(response));
async function refreshAccessToken() {
if (refreshPromise) {
return refreshPromise;
}
const auth = getStoredAppAuth();
if (!auth?.refreshToken) {
clearStoredAppAuth();
throw new Error('登录状态已失效,请重新登录');
}
refreshPromise = client.post(`${appConfig.appServer}/auth/refreshToken`, {
refreshToken: auth.refreshToken
}, {
skipAuth: true
}).then(response => {
const payload = response.data || {};
if (Number(payload.code) !== 0 || !payload.data) {
if (Number(payload.code) === REFRESH_ERROR_CODE) {
clearStoredAppAuth();
}
throw new Error(payload.message || '刷新登录状态失败');
}
persistAppAuth(payload.data);
return payload.data;
}).finally(() => {
refreshPromise = null;
});
return refreshPromise;
}
async function request(config) {
const response = await client.request(config);
const payload = response.data || {};
if (Number(payload.code) === AUTH_ERROR_CODE && shouldAttachAuth(config) && !config._retriedAfterRefresh) {
await refreshAccessToken();
return request({
...config,
_retriedAfterRefresh: true
});
}
return response;
}
export async function appServerRequest(config) {
return request(config);
}
export async function appServerGet(url, config = {}) {
return request({
...config,
method: 'get',
url
});
}
export async function appServerPost(url, data = {}, config = {}) {
return request({
...config,
method: 'post',
url,
data
});
}
+273
View File
@@ -0,0 +1,273 @@
import { appConfig } from '@/config';
import { HttpImClient } from './httpImClient';
import axios from 'axios';
import {
appServerGet,
appServerPost,
clearStoredAppAuth,
getStoredAppAuth,
persistAppAuth
} from './appServerClient';
function inferAccountType(account) {
return String(account || '').includes('@') ? 2 : 1;
}
function unwrapData(response) {
return response.data?.data ?? response.data?.result ?? null;
}
function unwrapMessage(response, fallback) {
return response.data?.message || response.data?.msg || fallback;
}
export class DocumentedHttpImClient extends HttpImClient {
unsupported(feature) {
throw new Error(`当前对接文档未提供“${feature}”接口,已禁用旧本地代理链路`);
}
async loginWithPassword(account, password, type = inferAccountType(account)) {
const response = await appServerPost(`${appConfig.appServer}/auth/login_pwd`, {
type,
number: account,
password,
platform: appConfig.platform,
clientId: this.getClientId()
}, {
skipAuth: true
});
if (response.data?.code !== 0) {
throw new Error(unwrapMessage(response, '登录失败'));
}
persistAppAuth(unwrapData(response));
return unwrapData(response);
}
async requestAuthCode(email) {
const response = await appServerPost(`${appConfig.appServer}/auth/sendEmailCode`, {
email
}, {
skipAuth: true
});
if (response.data?.code !== 0) {
throw new Error(unwrapMessage(response, '验证码发送失败'));
}
return unwrapData(response);
}
async loginWithCode(account, code) {
void account;
void code;
throw new Error('接口文档未提供验证码登录接口,请使用密码登录');
}
async register({ type, number, code = '', password, invitationCode = '' }) {
const response = await appServerPost(`${appConfig.appServer}/auth/register`, {
type,
number,
code,
password,
clientId: this.getClientId(),
platform: appConfig.platform,
invitationCode
}, {
skipAuth: true
});
if (response.data?.code !== 0) {
throw new Error(unwrapMessage(response, '注册失败'));
}
persistAppAuth(unwrapData(response));
return unwrapData(response);
}
async createPcSession(userId = '') {
const response = await axios.post(`${appConfig.qrAppServer}/pc_session`, {
flag: 1,
device_name: 'Web IM',
userId,
clientId: this.getClientId(),
platform: appConfig.platform
}, { withCredentials: false });
if (response.data?.code !== 0) {
throw new Error(unwrapMessage(response, '二维码登录会话创建失败'));
}
return unwrapData(response) || {};
}
async loginWithPcSession(token) {
const url = `${appConfig.qrAppServer}/session_login/${encodeURIComponent(token)}`;
let response;
try {
response = await axios.post(url, null, { withCredentials: false });
} catch (postError) {
response = await axios.get(url, { withCredentials: false });
}
this.persistAppToken(url, response);
const payload = response.data || {};
const result = payload.result ?? payload.data ?? null;
if (Number(payload.code) === 0 && result) {
persistAppAuth(result);
}
if ([0, 8, 9, 10, 13, 18, 20042].includes(Number(payload.code))) {
return {
...payload,
data: result
};
}
throw new Error(payload.message || '扫码登录失败');
}
async changePassword({ oldPassword, newPassword }) {
const response = await appServerPost(appConfig.changePasswordApi, {
oldPassword,
newPassword
});
if (response.data?.code !== 0) {
throw new Error(unwrapMessage(response, '密码修改失败'));
}
return true;
}
async resetPasswordWithCode({ mobile, resetCode, newPassword }) {
void mobile;
void resetCode;
void newPassword;
throw new Error('接口文档未提供重置密码接口,请联系服务端确认流程');
}
async logout() {
const auth = getStoredAppAuth();
if (!auth?.refreshToken) {
clearStoredAppAuth();
return true;
}
try {
const response = await appServerPost(appConfig.logoutApi, {
refreshToken: auth.refreshToken
});
if (response.data?.code !== 0) {
throw new Error(unwrapMessage(response, '退出登录失败'));
}
} finally {
clearStoredAppAuth();
}
return true;
}
async fetchRemoteConversations() {
return [];
}
async fetchRemoteMessages() {
return [];
}
async getServerContactList() {
return [];
}
async getProfile() {
return null;
}
async sendTextMessage() {
this.unsupported('发送消息');
}
async sendAttachmentMessage() {
this.unsupported('发送附件消息');
}
async addContact() {
this.unsupported('添加联系人');
}
async updateContactAlias() {
this.unsupported('联系人备注');
}
async createGroup() {
this.unsupported('创建群组');
}
async joinGroup() {
this.unsupported('加入群组');
}
async broadcastMessage() {
this.unsupported('群发消息');
}
async getGroupDetail() {
this.unsupported('群详情');
}
async getGroupMembers() {
this.unsupported('群成员');
}
async updateGroupAlias() {
this.unsupported('群备注');
}
async leaveGroup() {
this.unsupported('退出群组');
}
async dismissGroup() {
this.unsupported('解散群组');
}
async transferGroup() {
this.unsupported('转让群组');
}
async setGroupAdmins() {
this.unsupported('设置群管理员');
}
async updateGroupProfile() {
this.unsupported('更新群资料');
}
async kickGroupMembers() {
this.unsupported('移除群成员');
}
async updateGroupMuteSetting() {
this.unsupported('群禁言设置');
}
async updateProfile() {
this.unsupported('更新个人资料');
}
async recallMessage() {
this.unsupported('撤回消息');
}
async editMessage() {
this.unsupported('编辑消息');
}
async getMessageDetail() {
this.unsupported('消息详情');
}
}
+150 -29
View File
@@ -1,5 +1,12 @@
import axios from 'axios';
import { appConfig } from '@/config';
import {
appServerGet,
appServerPost,
clearStoredAppAuth,
getStoredAppAuth,
persistAppAuth
} from '@/services/appServerClient';
const LOCAL_MESSAGE_STORAGE_KEY = 'qmt-web-im-local-messages-v2';
const LOCAL_HIDDEN_MESSAGE_STORAGE_KEY = 'qmt-web-im-hidden-messages-v1';
@@ -149,7 +156,13 @@ function mergeSyncedMessages(localMessages, remoteMessages, conversationId, user
if (message.status === 'sent') {
return !hasRemoteMatch(message) && now - Number(message.timestamp || 0) < 30000;
}
return message.status === 'sending' || message.status === 'failed';
if (message.status === 'failed') {
// Failed optimistic messages are only transient feedback. Keeping them in
// localStorage forever makes an old server error reappear every time the
// conversation is opened, even after later messages send successfully.
return now - Number(message.timestamp || 0) < 3000;
}
return message.status === 'sending';
});
return [...visibleRemoteMessages, ...pendingLocalMessages].sort((a, b) => {
@@ -208,13 +221,11 @@ export class HttpImClient {
async loginWithPassword(mobile, password) {
const url = `${appConfig.appServer}/login_pwd`;
const deviceId = getUniqueEquipment(mobile, this.getClientId());
const response = await axios.post(url, {
mobile,
password,
platform: appConfig.platform,
clientId: deviceId,
uniqueEquipment: deviceId
clientId: this.getClientId()
}, { withCredentials: false });
this.persistAppToken(url, response);
@@ -242,13 +253,11 @@ export class HttpImClient {
async loginWithCode(mobile, code) {
const url = `${appConfig.appServer}/login`;
const deviceId = getUniqueEquipment(mobile, this.getClientId());
const response = await axios.post(url, {
mobile,
code,
platform: appConfig.platform,
clientId: deviceId,
uniqueEquipment: deviceId
clientId: this.getClientId()
}, { withCredentials: false });
this.persistAppToken(url, response);
@@ -392,6 +401,9 @@ export class HttpImClient {
displayTimestamp: message.displayTimestamp || message.timestamp,
conversationId: conversation.id
}));
messages.hasPinnedMessageState = Object.prototype.hasOwnProperty.call(response.data?.result || {}, 'pinnedMessageUid');
messages.pinnedMessageUid = String(response.data?.result?.pinnedMessageUid || '');
messages.pinnedMessage = response.data?.result?.pinnedMessage || null;
if (options.includeConversations && Array.isArray(response.data?.result?.conversations)) {
const remoteConversations = response.data.result.conversations.map(remoteConversation => ({
...remoteConversation,
@@ -404,10 +416,115 @@ export class HttpImClient {
const userId = this.currentUser?.userId || '';
const messagesByConversation = readLocalMessages(userId);
messagesByConversation[conversation.id] = mergeSyncedMessages(messagesByConversation[conversation.id] || [], messages, conversation.id, userId);
messagesByConversation[conversation.id].pinnedMessageUid = messages.pinnedMessageUid;
messagesByConversation[conversation.id].pinnedMessage = messages.pinnedMessage;
messagesByConversation[conversation.id].hasPinnedMessageState = messages.hasPinnedMessageState;
writeLocalMessages(messagesByConversation, userId);
return messagesByConversation[conversation.id];
}
async setPinnedMessage(conversation, messageUid = '', message = null) {
const isGroup = ['group', 'channel'].includes(conversation?.type)
|| ['group', 'channel', 1, '1'].includes(conversation?.raw?.type);
if (isGroup) {
if (messageUid && message) {
return this.addGroupPinnedMessage(conversation, message);
}
const serverPinId = String(message?.serverPinId || message?.pinId || '').trim();
if (!serverPinId) {
throw new Error('缺少置顶记录ID,请刷新会话后重试');
}
return this.removeGroupPinnedMessage(serverPinId);
}
const action = messageUid ? 'pin' : 'unpin';
const response = await axios.post(appConfig.messageActionApi, {
action,
userId: this.currentUser?.userId || '',
messageUid: messageUid || '1',
target: conversation.target || conversation.raw?.target || '',
conversationType: ['group', 'channel'].includes(conversation.type) ? 'group' : 'single',
message: message ? {
id: String(message.messageUid || message.id || messageUid),
messageUid: String(message.messageUid || message.id || messageUid),
text: String(message.text || ''),
type: message.type || 'text',
attachment: message.attachment || null,
senderName: message.senderName || message.from || '',
timestamp: Number(message.displayTimestamp || message.timestamp || Date.now())
} : null
}, { withCredentials: false });
if (response.data?.code !== 0) throw new Error(response.data?.message || '置顶失败');
}
async fetchGroupPinnedMessages(conversation) {
const groupId = String(conversation?.target || conversation?.raw?.target || '').trim();
if (!groupId) return [];
const url = `${appConfig.appServer}/groupTopMessage/gets`;
const response = await axios.get(url, {
params: { groupId },
headers: this.getAppAuthHeaders(url),
withCredentials: false
});
const payload = response.data || {};
if (payload.code !== undefined && Number(payload.code) !== 0) {
throw new Error(payload.message || '置顶消息加载失败');
}
const result = payload.result ?? payload.data ?? payload;
return Array.isArray(result) ? result : [];
}
async addGroupPinnedMessage(conversation, message) {
const groupId = String(conversation?.target || conversation?.raw?.target || '').trim();
const messageId = String(message?.messageId || message?.messageUid || message?.id || '').trim();
if (!groupId || !messageId) throw new Error('缺少群ID或消息ID');
const searchableContent = String(message?.text || '').trim()
|| (message?.type === 'image' ? '[图片]' : message?.type === 'video' ? '[视频]' : '[消息]');
const rawConversationType = Number(conversation?.raw?.type);
const conversationType = Number.isFinite(rawConversationType) && rawConversationType > 0
? rawConversationType
: 1;
const url = `${appConfig.appServer}/groupTopMessage/add`;
const response = await axios.post(url, {
groupId,
userId: message?.from || this.currentUser?.userId || '',
messageId,
messageType: conversationType,
messageText: JSON.stringify({
...message,
messageId,
from: message?.from || this.currentUser?.userId || '',
conversation: {
type: conversationType,
target: groupId,
line: Number(conversation?.raw?.line || 0)
},
content: { searchableContent }
})
}, {
headers: this.getAppAuthHeaders(url),
withCredentials: false
});
const payload = response.data || {};
if (payload.code !== undefined && Number(payload.code) !== 0) {
const detail = payload.message || payload.msg || payload.result?.message || '置顶失败';
throw new Error(payload.code !== undefined ? `${detail}(错误码 ${payload.code})` : detail);
}
return payload.result ?? payload.data ?? payload;
}
async removeGroupPinnedMessage(pinId) {
const url = `${appConfig.appServer}/groupTopMessage/remove/?id=${encodeURIComponent(pinId)}`;
const response = await axios.post(url, {}, {
headers: this.getAppAuthHeaders(url),
withCredentials: false
});
const payload = response.data || {};
if (payload.code !== undefined && Number(payload.code) !== 0) {
throw new Error(payload.message || '取消置顶失败');
}
return payload.result ?? payload.data ?? payload;
}
hideMessages(conversation, messages) {
const items = Array.isArray(messages) ? messages : [messages];
if (!conversation?.id || !items.length) {
@@ -513,7 +630,7 @@ export class HttpImClient {
return response.data?.result?.detail || null;
}
async sendTextMessage(conversation, text, initialMessage = null) {
async sendTextMessage(conversation, text, initialMessage = null, options = {}) {
const senderRole = conversation?.role || conversation?.raw?.role || '';
const message = initialMessage || {
id: randomId(),
@@ -537,7 +654,8 @@ export class HttpImClient {
sender: this.currentUser?.userId || '',
target: conversation.target || conversation.raw?.target || conversation.id.replace(/^single-/, ''),
conversationType: conversation.type || conversation.raw?.type || 0,
text
text,
mentionedUserIds: Array.isArray(options.mentionedUserIds) ? options.mentionedUserIds : []
}, { withCredentials: false });
if (response.data?.code !== 0) {
@@ -640,6 +758,27 @@ export class HttpImClient {
}
}
async forwardAttachmentMessage(conversation, sourceMessage) {
const attachment = sourceMessage?.attachment || {};
const type = attachment.type || sourceMessage?.type || 'file';
const formData = new FormData();
formData.append('sender', this.currentUser?.userId || '');
formData.append('target', conversation.target || conversation.raw?.target || conversation.id.replace(/^single-/, ''));
formData.append('conversationType', conversation.type || conversation.raw?.type || 0);
formData.append('messageType', type);
formData.append('text', sourceMessage?.text || '');
formData.append('attachmentUrl', attachment.url || '');
formData.append('attachmentName', attachment.name || (type === 'image' ? '转发图片' : (type === 'video' ? '转发视频.mp4' : '转发文件')));
formData.append('attachmentMime', attachment.mime || (type === 'video' ? 'video/mp4' : 'application/octet-stream'));
formData.append('attachmentSize', String(attachment.size || 0));
const response = await axios.post(appConfig.sendMessageApi, formData, { withCredentials: false });
if (response.data?.code !== 0) {
throw new Error(response.data?.message || '转发失败');
}
return response.data?.result || {};
}
getContactList() {
return [];
}
@@ -729,16 +868,7 @@ export class HttpImClient {
throw new Error(response.data?.message || (channel ? '创建公告群失败' : '创建群组失败'));
}
const result = response.data?.result || {};
const conversation = this.normalizeConversation(result.conversation || {});
conversation.nativeStatus = result.nativeStatus || '';
conversation.nativeError = result.nativeError || '';
conversation.raw = {
...(conversation.raw || {}),
nativeStatus: conversation.nativeStatus,
nativeError: conversation.nativeError
};
return conversation;
return this.normalizeConversation(response.data?.result?.conversation || {});
}
async joinGroup(userId, groupKey) {
@@ -752,16 +882,7 @@ export class HttpImClient {
throw new Error(response.data?.message || '加入群组失败');
}
const result = response.data?.result || {};
const conversation = this.normalizeConversation(result.conversation || {});
conversation.nativeStatus = result.nativeStatus || '';
conversation.nativeError = result.nativeError || '';
conversation.raw = {
...(conversation.raw || {}),
nativeStatus: conversation.nativeStatus,
nativeError: conversation.nativeError
};
return conversation;
return this.normalizeConversation(response.data?.result?.conversation || {});
}
async broadcastMessage(userId, targetIds, text) {
+10 -2
View File
@@ -1,6 +1,7 @@
import { appConfig } from '@/config';
import { HttpImClient } from './httpImClient';
import { LongConnectionImClient } from './longConnectionImClient';
import { DocumentedHttpImClient } from './documentedHttpImClient';
class UnsupportedWildfireImClient {
constructor() {
@@ -12,6 +13,13 @@ export const imClient = appConfig.sdkMode === 'wildfire'
? new UnsupportedWildfireImClient()
: appConfig.sdkMode === 'custom-ws' || appConfig.sdkMode === 'long'
? new LongConnectionImClient()
: new HttpImClient();
: appConfig.sdkMode === 'legacy-http'
? new HttpImClient()
: new DocumentedHttpImClient();
export { HttpImClient, LongConnectionImClient, UnsupportedWildfireImClient as WildfireImClient };
export {
DocumentedHttpImClient,
HttpImClient,
LongConnectionImClient,
UnsupportedWildfireImClient as WildfireImClient
};
+27 -1
View File
@@ -4,7 +4,7 @@ function configuredProxyHosts() {
? configured
: String(configured || '').split(/[\s,]+/);
return new Set(
values
['zhiyanim.dfpnm.cn', ...values]
.map(value => String(value || '').trim().toLowerCase().replace(/\.$/, ''))
.filter(Boolean)
);
@@ -28,3 +28,29 @@ export function imageDisplayUrl(value) {
return source;
}
}
export function videoDisplayUrl(value) {
const source = String(value || '').trim();
if (!source || source.startsWith('blob:') || source.startsWith('data:')) return source;
const streamUrl = new URL('/api/media_stream.php', window.location.origin);
streamUrl.searchParams.set('url', source);
return streamUrl.toString();
}
export function useVideoOriginalFallback(event, value) {
const video = event?.currentTarget;
const source = String(value || '').trim();
if (!video || !source || video.dataset.originalFallback === '1') return;
video.dataset.originalFallback = '1';
video.src = source;
video.load();
}
export function useImageProxyFallback(event, value) {
const image = event?.currentTarget;
if (!image) return;
const fallback = imageDisplayUrl(value);
if (!fallback || fallback === value || image.dataset.proxyFallback === '1') return;
image.dataset.proxyFallback = '1';
image.src = fallback;
}
+326 -260
View File
@@ -6,26 +6,8 @@ import { realtimeNotifications } from '@/services/realtimeNotifications';
const LOCAL_CONVERSATION_STORAGE_KEY = 'qmt-web-im-local-conversations-v2';
const LOCAL_FAVORITE_MESSAGES_KEY = 'qmt-web-im-favorite-messages-v1';
const recentRealtimeNotifications = new Map();
function isDuplicateRealtimeNotification(payload) {
const messageId = String(payload?.messageId || '');
if (!messageId) {
return false;
}
const key = `${payload?.kind || 'message'}:${messageId}`;
const now = Date.now();
const previousAt = Number(recentRealtimeNotifications.get(key) || 0);
recentRealtimeNotifications.set(key, now);
if (recentRealtimeNotifications.size > 200) {
recentRealtimeNotifications.forEach((seenAt, seenKey) => {
if (now - seenAt > 30000) {
recentRealtimeNotifications.delete(seenKey);
}
});
}
return now - previousAt < 5000;
}
const LOCAL_PINNED_MESSAGES_KEY = 'qmt-web-im-pinned-messages-v1';
const LOCAL_HIDDEN_CONVERSATIONS_KEY = 'qmt-web-im-hidden-conversations-v1';
function scopedStorageKey(baseKey) {
const session = useSessionStore();
@@ -57,6 +39,77 @@ function writeLocalConversations(conversations) {
localStorage.setItem(scopedStorageKey(LOCAL_CONVERSATION_STORAGE_KEY), JSON.stringify(conversations));
}
function readHiddenConversationIds() {
try {
return JSON.parse(localStorage.getItem(scopedStorageKey(LOCAL_HIDDEN_CONVERSATIONS_KEY)) || '[]');
} catch (error) {
return [];
}
}
function writeHiddenConversationIds(ids) {
localStorage.setItem(scopedStorageKey(LOCAL_HIDDEN_CONVERSATIONS_KEY), JSON.stringify(ids));
}
function readPinnedMessages() {
try {
return JSON.parse(localStorage.getItem(scopedStorageKey(LOCAL_PINNED_MESSAGES_KEY)) || '{}');
} catch (error) {
return {};
}
}
function writePinnedMessages(messages) {
localStorage.setItem(scopedStorageKey(LOCAL_PINNED_MESSAGES_KEY), JSON.stringify(messages));
}
function parseNativePinnedMessage(item, messages = []) {
if (!item) return null;
const messageId = String(item.messageId || item.messageUid || '').trim();
const matched = messages.find(message => [message.messageId, message.messageUid, message.id]
.filter(Boolean)
.some(value => String(value) === messageId));
let encoded = {};
try {
encoded = typeof item.messageText === 'string' ? JSON.parse(item.messageText) : (item.messageText || {});
} catch (error) {
encoded = {};
}
const text = String(
encoded?.content?.searchableContent
|| encoded?.messageContent?.searchableContent
|| encoded?.text
|| matched?.text
|| '[消息]'
);
return {
...(matched || {}),
key: messageId || `group-pin-${item.id}`,
id: messageId || `group-pin-${item.id}`,
messageUid: messageId || matched?.messageUid || '',
serverPinId: String(item.id || ''),
text,
type: matched?.type || encoded?.type || 'text',
attachment: matched?.attachment || encoded?.attachment || null,
senderName: matched?.senderName || encoded?.senderName || encoded?.from || '',
timestamp: Number(matched?.displayTimestamp || matched?.timestamp || item.updateTime || item.createTime || Date.now())
};
}
function sortConversations(conversations) {
return [...conversations].sort((left, right) => {
const leftPinned = Number(left.pinnedAt || left.top || 0);
const rightPinned = Number(right.pinnedAt || right.top || 0);
if (Boolean(leftPinned) !== Boolean(rightPinned)) {
return rightPinned ? 1 : -1;
}
if (leftPinned && rightPinned && leftPinned !== rightPinned) {
return rightPinned - leftPinned;
}
return Number(right.updatedAt || 0) - Number(left.updatedAt || 0);
});
}
function randomId() {
if (window.crypto && window.crypto.randomUUID) {
return window.crypto.randomUUID().replaceAll('-', '');
@@ -76,17 +129,6 @@ function messageActivityTimestamp(message) {
return Number(message?.activityTimestamp || message?.editedAt || message?.displayTimestamp || message?.timestamp || 0);
}
function hasSameRenderState(left, right) {
if (left === right) {
return true;
}
try {
return JSON.stringify(left) === JSON.stringify(right);
} catch (error) {
return false;
}
}
function isRecalledMessage(message) {
return Boolean(message?.recalled) || message?.status === 'recalled';
}
@@ -102,84 +144,14 @@ function attachmentLabel(message) {
return `[文件] ${attachment.name || '文件'}`;
}
function cleanPlaceholderText(text, message = {}) {
const value = String(text || '').replace(/\s+/g, ' ').trim();
const contentType = Number(message?.contentType || 0);
if (!value) {
return '';
}
if (contentType !== 1 && value === '[暂不支持的消息类型]') {
return '';
}
if ((contentType === 3 || message?.type === 'image') && (value === '[图片]' || value === '图片')) {
return '';
}
return value;
}
function messagePreviewText(message) {
if (isRecalledMessage(message)) {
return `[${message?.recallStatus || '已撤回'}]`;
}
const text = cleanPlaceholderText(message?.text, message);
const text = String(message?.text || '').replace(/\s+/g, ' ').trim();
return text || attachmentLabel(message);
}
function sanitizeConversation(conversation) {
if (!conversation) {
return conversation;
}
return {
...conversation,
subtitle: cleanPlaceholderText(conversation.subtitle, conversation)
};
}
function isHttpUrl(value) {
try {
const url = new URL(String(value || '').trim());
return url.protocol === 'http:' || url.protocol === 'https:';
} catch (error) {
return false;
}
}
function fileNameFromUrl(url, fallback = '图片') {
try {
const path = new URL(url).pathname;
const name = decodeURIComponent(path.split('/').filter(Boolean).pop() || '');
return name || fallback;
} catch (error) {
return fallback;
}
}
function normalizeMessageForDisplay(message) {
if (!message || message.attachment) {
return message;
}
const contentType = Number(message.contentType || 0);
const text = String(message.text || '').trim();
if ((contentType === 3 || message.type === 'image') && isHttpUrl(text)) {
return {
...message,
type: 'image',
text: '',
attachment: {
type: 'image',
url: text,
name: fileNameFromUrl(text, '图片'),
mime: 'image/*',
size: 0
}
};
}
return message;
}
function quotePrefix(message) {
const text = messagePreviewText(message);
return text.length > 48 ? `${text.slice(0, 48)}...` : text;
@@ -240,17 +212,33 @@ function canMarkReadNow(options = {}) {
return true;
}
function isPageVisible() {
return typeof document === 'undefined' || document.visibilityState === 'visible';
function forwardedText(message) {
return String(message?.text || '')
.replace(/^转发\s*[::]\s*/u, '')
.trim();
}
function activeMessageSyncIntervalMs() {
const configured = Number(appConfig.syncIntervalMs || 0);
return Math.max(15000, Number.isFinite(configured) && configured > 0 ? configured : 15000);
}
function conversationListSyncIntervalMs() {
return Math.max(30000, activeMessageSyncIntervalMs() * 2);
function normalizeMessageForDisplay(message) {
if (!message || message.attachment || String(message.text || '').trim()) {
return message;
}
const contentType = Number(message.contentType || 0);
const labels = {
3: '[图片加载失败]',
6: '[视频加载失败]',
90: '[红包]',
92: '以上是打招呼的内容',
93: '你们已经是好友了,可以开始聊天了。',
105: '[领取了红包]'
};
if (!labels[contentType]) {
return message;
}
return {
...message,
type: 'text',
text: labels[contentType]
};
}
function mergeVisibleMessages(currentMessages, syncedMessages) {
@@ -345,12 +333,8 @@ export const useConversationStore = defineStore('conversations', {
readPresenceEventsBound: false,
syncInFlight: false,
pendingReadReceiptConversationId: '',
pendingConversationSync: false,
conversationSyncInFlight: false,
messageSyncTimer: null,
messageSyncQueuedAt: 0,
pendingMessageSyncOptions: {},
lastReadSyncByConversation: {},
syncAfterSendTimer: null,
optimisticMessagesByConversation: {},
quotedMessage: null,
forwardingMessages: [],
@@ -366,9 +350,13 @@ export const useConversationStore = defineStore('conversations', {
selectionMode: false,
selectedMessageIds: [],
favoriteMessages: [],
pinnedMessagesByConversation: {},
groupPinnedSyncAt: {},
hiddenConversationIds: [],
activeFavoriteKey: '',
actionNotice: '',
actionError: '',
actionNoticeTimer: null,
realtimeSyncTimer: null
}),
getters: {
@@ -399,6 +387,13 @@ export const useConversationStore = defineStore('conversations', {
|| state.favoriteMessages[0]
|| null;
},
activePinnedMessage(state) {
const pinned = state.pinnedMessagesByConversation[state.activeId] || null;
if (!pinned) return null;
const message = (state.visibleMessagesByConversation[state.activeId] || [])
.find(item => messageStableKey(item) === pinned.key);
return message ? { ...pinned, ...message, key: pinned.key } : pinned;
},
selectedMessages(state) {
const selectedIds = new Set(state.selectedMessageIds);
return (state.visibleMessagesByConversation[state.activeId] || [])
@@ -419,10 +414,13 @@ export const useConversationStore = defineStore('conversations', {
realtimeNotifications.start(session.userId, payload => this.handleRealtimeNotification(payload));
},
loadScopedLocalState() {
this.conversations = readLocalConversations().map(sanitizeConversation);
this.conversations = [];
this.favoriteMessages = readFavoriteMessages();
this.pinnedMessagesByConversation = readPinnedMessages();
this.groupPinnedSyncAt = {};
this.hiddenConversationIds = readHiddenConversationIds();
this.activeFavoriteKey = this.favoriteMessages[0]?.key || '';
this.activeId = this.conversations[0]?.id || '';
this.activeId = '';
this.messagesByConversation = {};
this.visibleMessagesByConversation = {};
this.optimisticMessagesByConversation = {};
@@ -437,29 +435,24 @@ export const useConversationStore = defineStore('conversations', {
this.messageDetail = null;
this.selectionMode = false;
this.selectedMessageIds = [];
if (this.activeId) {
this.loadActiveMessages({ allowReadReceipt: true });
}
},
clearUserState() {
window.clearInterval(this.syncTimer);
window.clearInterval(this.conversationSyncTimer);
window.clearTimeout(this.messageSyncTimer);
window.clearTimeout(this.syncAfterSendTimer);
window.clearTimeout(this.attentionMessageTimer);
window.clearTimeout(this.actionNoticeTimer);
window.clearTimeout(this.realtimeSyncTimer);
realtimeNotifications.stop();
this.syncTimer = null;
this.conversationSyncTimer = null;
this.messageSyncTimer = null;
this.messageSyncQueuedAt = 0;
this.pendingMessageSyncOptions = {};
this.syncAfterSendTimer = null;
this.attentionMessageTimer = null;
this.actionNoticeTimer = null;
this.realtimeSyncTimer = null;
this.syncInFlight = false;
this.conversationSyncInFlight = false;
this.pendingReadReceiptConversationId = '';
this.pendingConversationSync = false;
this.lastReadSyncByConversation = {};
this.activeId = '';
this.conversations = [];
this.messagesByConversation = {};
@@ -478,6 +471,7 @@ export const useConversationStore = defineStore('conversations', {
this.selectionMode = false;
this.selectedMessageIds = [];
this.favoriteMessages = [];
this.hiddenConversationIds = [];
this.activeFavoriteKey = '';
this.actionNotice = '';
this.actionError = '';
@@ -493,7 +487,7 @@ export const useConversationStore = defineStore('conversations', {
imClient.on('messageReceived', message => {
this.appendMessage(message.conversationId, message);
if (message.conversationId === this.activeId) {
this.scheduleActiveMessagesSync({ allowReadReceipt: true }, 700);
this.scheduleActiveMessagesSync({ allowReadReceipt: true }, 500);
}
});
imClient.on('messageStatusChanged', message => {
@@ -512,13 +506,16 @@ export const useConversationStore = defineStore('conversations', {
}
this.loadActiveMessages({ allowReadReceipt: true, userAction: true });
},
sendText(text) {
sendText(payload) {
const conversation = this.activeConversation;
const text = typeof payload === 'string' ? payload : String(payload?.text || '');
const mentionedUserIds = Array.isArray(payload?.mentionedUserIds) ? payload.mentionedUserIds : [];
if (!conversation || !text.trim()) {
return;
}
let value = text.trim();
if (this.quotedMessage) {
value = `引用:${quotePrefix(this.quotedMessage)}\n${value}`;
this.quotedMessage = null;
}
const message = {
@@ -535,11 +532,12 @@ export const useConversationStore = defineStore('conversations', {
};
this.appendVisibleMessage(conversation.id, message);
this.appendMessage(conversation.id, message);
imClient.sendTextMessage(conversation, value, message);
imClient.sendTextMessage(conversation, value, message, { mentionedUserIds });
conversation.subtitle = value;
conversation.updatedAt = Date.now();
writeLocalConversations(this.conversations);
this.scheduleActiveMessagesSync({}, 700);
window.clearTimeout(this.syncAfterSendTimer);
this.syncAfterSendTimer = window.setTimeout(() => this.syncActiveMessages(), 250);
},
sendAttachment({ type, file, text = '' }) {
const conversation = this.activeConversation;
@@ -548,6 +546,7 @@ export const useConversationStore = defineStore('conversations', {
}
let value = text.trim();
if (this.quotedMessage) {
value = `引用:${quotePrefix(this.quotedMessage)}\n${value}`.trim();
this.quotedMessage = null;
}
const now = Date.now();
@@ -577,7 +576,8 @@ export const useConversationStore = defineStore('conversations', {
conversation.subtitle = messagePreviewText(message);
conversation.updatedAt = now;
writeLocalConversations(this.conversations);
this.scheduleActiveMessagesSync({}, 700);
window.clearTimeout(this.syncAfterSendTimer);
this.syncAfterSendTimer = window.setTimeout(() => this.syncActiveMessages(), 350);
},
async sendTextToConversation(conversation, text) {
if (!conversation || !text.trim()) {
@@ -602,7 +602,6 @@ export const useConversationStore = defineStore('conversations', {
return sentMessage;
},
upsertConversation(conversation) {
conversation = sanitizeConversation(conversation);
const index = this.conversations.findIndex(item => item.id === conversation.id);
if (index >= 0) {
this.conversations.splice(index, 1, {
@@ -616,6 +615,10 @@ export const useConversationStore = defineStore('conversations', {
writeLocalConversations(this.conversations);
},
removeConversation(conversationId) {
if (!this.hiddenConversationIds.includes(conversationId)) {
this.hiddenConversationIds = [...this.hiddenConversationIds, conversationId];
writeHiddenConversationIds(this.hiddenConversationIds);
}
this.conversations = this.conversations.filter(conversation => conversation.id !== conversationId);
const {
[conversationId]: removedMessages,
@@ -644,12 +647,13 @@ export const useConversationStore = defineStore('conversations', {
}
},
applyRemoteConversations(remoteConversations) {
const remote = Array.isArray(remoteConversations) ? remoteConversations : [];
const hidden = new Set(this.hiddenConversationIds);
const remote = (Array.isArray(remoteConversations) ? remoteConversations : [])
.filter(conversation => !hidden.has(conversation.id));
if (!remote.length && this.conversations.length) {
return;
}
const previousActiveId = this.activeId;
const merged = new Map();
this.conversations.forEach(conversation => {
merged.set(conversation.id, conversation);
@@ -658,19 +662,13 @@ export const useConversationStore = defineStore('conversations', {
const unread = conversation.id === this.activeId && canMarkReadNow() ? 0 : Number(conversation.unread || 0);
merged.set(conversation.id, {
...(merged.get(conversation.id) || {}),
...sanitizeConversation(conversation),
...conversation,
unread
});
});
const nextConversations = Array.from(merged.values())
.map(sanitizeConversation)
.sort((a, b) => Number(b.updatedAt || 0) - Number(a.updatedAt || 0))
this.conversations = sortConversations(Array.from(merged.values()))
.slice(0, 100);
const conversationsChanged = !hasSameRenderState(this.conversations, nextConversations);
if (conversationsChanged) {
this.conversations = nextConversations;
}
if (!this.conversations.length) {
this.activeId = '';
@@ -684,15 +682,22 @@ export const useConversationStore = defineStore('conversations', {
if (!this.conversations.find(item => item.id === this.activeId)) {
this.activeId = this.conversations[0].id;
}
if (conversationsChanged) {
writeLocalConversations(this.conversations);
}
if (previousActiveId !== this.activeId || !this.messagesByConversation[this.activeId]) {
this.loadActiveMessages();
}
},
togglePinnedConversation(conversationId) {
const conversation = this.conversations.find(item => item.id === conversationId);
if (!conversation) return;
conversation.pinnedAt = Number(conversation.pinnedAt || conversation.top || 0) > 0 ? 0 : Date.now();
conversation.top = conversation.pinnedAt;
this.conversations = sortConversations(this.conversations);
writeLocalConversations(this.conversations);
},
appendMessage(conversationId, message) {
message = normalizeMessageForDisplay(message);
if (message?.direction === 'in' && this.hiddenConversationIds.includes(conversationId)) {
this.hiddenConversationIds = this.hiddenConversationIds.filter(id => id !== conversationId);
writeHiddenConversationIds(this.hiddenConversationIds);
}
if (!this.messagesByConversation[conversationId]) {
this.messagesByConversation = {
...this.messagesByConversation,
@@ -752,7 +757,7 @@ export const useConversationStore = defineStore('conversations', {
return;
}
conversation.subtitle = messagePreviewText(message) || cleanPlaceholderText(conversation.subtitle, conversation);
conversation.subtitle = message.text || conversation.subtitle || '';
conversation.updatedAt = messageActivityTimestamp(message) || Date.now();
if (message.direction === 'in') {
conversation.unread = conversationId === this.activeId ? 0 : Number(conversation.unread || 0) + 1;
@@ -761,7 +766,6 @@ export const useConversationStore = defineStore('conversations', {
.sort((a, b) => Number(b.updatedAt || 0) - Number(a.updatedAt || 0));
},
appendVisibleMessage(conversationId, message) {
message = normalizeMessageForDisplay(message);
const messages = this.visibleMessagesByConversation[conversationId] || [];
this.visibleMessagesByConversation = {
...this.visibleMessagesByConversation,
@@ -770,7 +774,6 @@ export const useConversationStore = defineStore('conversations', {
};
},
replaceMessage(conversationId, message) {
message = normalizeMessageForDisplay(message);
if (!this.messagesByConversation[conversationId]) {
this.messagesByConversation = {
...this.messagesByConversation,
@@ -797,17 +800,13 @@ export const useConversationStore = defineStore('conversations', {
this.syncVisibleMessages(conversationId);
},
syncVisibleMessages(conversationId) {
const currentMessages = this.visibleMessagesByConversation[conversationId] || [];
const nextMessages = mergeVisibleMessages(
this.optimisticMessagesByConversation[conversationId] || [],
this.messagesByConversation[conversationId] || []
);
if (!hasSameRenderState(currentMessages, nextMessages)) {
this.visibleMessagesByConversation = {
...this.visibleMessagesByConversation,
[conversationId]: nextMessages
[conversationId]: mergeVisibleMessages(
this.optimisticMessagesByConversation[conversationId] || [],
this.messagesByConversation[conversationId] || []
)
};
}
},
keepOptimisticMessage(conversationId, message) {
if (!this.optimisticMessagesByConversation[conversationId]) {
@@ -859,13 +858,10 @@ export const useConversationStore = defineStore('conversations', {
this.loading = true;
const messages = imClient.getMessages(conversation, 30);
this.pruneOptimisticMessages(conversation.id, messages);
const nextMessages = mergeVisibleMessages(this.messagesByConversation[conversation.id] || [], messages);
if (!hasSameRenderState(this.messagesByConversation[conversation.id] || [], nextMessages)) {
this.messagesByConversation = {
...this.messagesByConversation,
[conversation.id]: nextMessages
[conversation.id]: mergeVisibleMessages(this.messagesByConversation[conversation.id] || [], messages)
};
}
this.syncVisibleMessages(conversation.id);
this.loading = false;
this.syncActiveMessages(syncOptions);
@@ -875,51 +871,77 @@ export const useConversationStore = defineStore('conversations', {
if (!conversation) {
return;
}
if (options.skipWhenHidden !== false && !isPageVisible()) {
return;
}
const wantsReadReceipt = Boolean(options.allowReadReceipt);
const explicitReadReceipt = wantsReadReceipt && canMarkReadNow({ userAction: Boolean(options.userAction) });
const now = Date.now();
const previousReadSyncAt = Number(this.lastReadSyncByConversation[conversation.id] || 0);
const pollingReadReceipt = canMarkReadNow() && now - previousReadSyncAt >= 10000;
const pollingReadReceipt = canMarkReadNow();
const markRead = explicitReadReceipt || pollingReadReceipt;
if (this.syncInFlight) {
if (wantsReadReceipt) {
this.pendingReadReceiptConversationId = conversation.id;
}
if (options.includeConversations) {
this.pendingConversationSync = true;
}
return;
}
this.syncInFlight = true;
const syncedConversationId = conversation.id;
const previousMessages = this.messagesByConversation[syncedConversationId] || [];
try {
const messages = await imClient.fetchRemoteMessages(conversation, 50, {
const messages = await imClient.fetchRemoteMessages(conversation, 1000, {
markRead,
includeConversations: Boolean(options.includeConversations)
});
if (markRead) {
this.lastReadSyncByConversation = {
...this.lastReadSyncByConversation,
const isGroupConversation = ['group', 'channel'].includes(conversation.type)
|| ['group', 'channel', 1, '1'].includes(conversation.raw?.type);
const shouldSyncGroupPin = isGroupConversation
&& Date.now() - Number(this.groupPinnedSyncAt[syncedConversationId] || 0) >= 3000;
if (shouldSyncGroupPin) {
try {
const nativePins = await imClient.fetchGroupPinnedMessages(conversation);
this.groupPinnedSyncAt = {
...this.groupPinnedSyncAt,
[syncedConversationId]: Date.now()
};
const nextPinned = { ...this.pinnedMessagesByConversation };
if (nativePins.length) {
nextPinned[syncedConversationId] = parseNativePinnedMessage(nativePins[0], messages);
} else {
delete nextPinned[syncedConversationId];
}
this.pinnedMessagesByConversation = nextPinned;
writePinnedMessages(nextPinned);
} catch (error) {
console.warn('群置顶消息同步失败', error);
}
}
const remotePinnedKey = String(messages.pinnedMessageUid || '');
if (!isGroupConversation && remotePinnedKey) {
const pinnedMessage = messages.find(item => messageStableKey(item) === remotePinnedKey)
|| messages.pinnedMessage
|| (this.pinnedMessagesByConversation[syncedConversationId]?.key === remotePinnedKey
? this.pinnedMessagesByConversation[syncedConversationId]
: null);
this.pinnedMessagesByConversation = {
...this.pinnedMessagesByConversation,
[syncedConversationId]: pinnedMessage
? {
key: remotePinnedKey,
id: remotePinnedKey,
text: messagePreviewText(pinnedMessage),
type: pinnedMessage.type || 'text',
attachment: pinnedMessage.attachment ? { ...pinnedMessage.attachment } : null,
senderName: pinnedMessage.senderName || pinnedMessage.from || '',
timestamp: Number(pinnedMessage.displayTimestamp || pinnedMessage.timestamp || Date.now())
}
: { key: remotePinnedKey, id: remotePinnedKey, text: '[置顶消息]' }
};
writePinnedMessages(this.pinnedMessagesByConversation);
}
const editedIncomingMessages = incomingEditedMessages(previousMessages, messages);
this.pruneOptimisticMessages(syncedConversationId, messages);
const nextMessages = mergeVisibleMessages(
this.messagesByConversation[syncedConversationId] || [],
messages
);
if (!hasSameRenderState(this.messagesByConversation[syncedConversationId] || [], nextMessages)) {
this.messagesByConversation = {
...this.messagesByConversation,
[syncedConversationId]: nextMessages
[syncedConversationId]: mergeVisibleMessages(this.messagesByConversation[syncedConversationId] || [], messages)
};
}
this.syncVisibleMessages(syncedConversationId);
if (editedIncomingMessages.length && syncedConversationId === this.activeId) {
this.focusMessage(editedIncomingMessages.sort((a, b) => messageActivityTimestamp(b) - messageActivityTimestamp(a))[0]);
@@ -932,94 +954,57 @@ export const useConversationStore = defineStore('conversations', {
return latestMessage;
}, null);
if (latest) {
const nextSubtitle = messagePreviewText(latest);
const nextUpdatedAt = messageActivityTimestamp(latest);
if (conversation.subtitle !== nextSubtitle || Number(conversation.updatedAt || 0) !== nextUpdatedAt) {
conversation.subtitle = nextSubtitle;
conversation.updatedAt = nextUpdatedAt;
conversation.subtitle = messagePreviewText(latest);
conversation.updatedAt = messageActivityTimestamp(latest);
writeLocalConversations(this.conversations);
}
}
} catch (error) {
// Keep the local view usable if a polling request misses.
} finally {
this.syncInFlight = false;
if (
(this.pendingReadReceiptConversationId === this.activeId || this.pendingConversationSync)
&& canMarkReadNow()
) {
const includeConversations = this.pendingConversationSync;
if (this.pendingReadReceiptConversationId === this.activeId && canMarkReadNow()) {
this.pendingReadReceiptConversationId = '';
this.pendingConversationSync = false;
this.scheduleActiveMessagesSync({
allowReadReceipt: true,
includeConversations
}, 700);
window.setTimeout(() => this.syncActiveMessages({ allowReadReceipt: true }), 0);
}
}
},
scheduleActiveMessagesSync(options = {}, delay = 700) {
if (!this.activeId || !isPageVisible()) {
scheduleActiveMessagesSync(options = {}, delay = 500) {
if (!this.activeId || (typeof document !== 'undefined' && document.visibilityState !== 'visible')) {
return;
}
const now = Date.now();
if (!this.messageSyncQueuedAt) {
this.messageSyncQueuedAt = now;
}
this.pendingMessageSyncOptions = {
...this.pendingMessageSyncOptions,
allowReadReceipt: Boolean(
this.pendingMessageSyncOptions.allowReadReceipt || options.allowReadReceipt
),
userAction: Boolean(this.pendingMessageSyncOptions.userAction || options.userAction),
includeConversations: Boolean(
this.pendingMessageSyncOptions.includeConversations || options.includeConversations
)
};
const maxWait = 1200;
const runAt = Math.min(now + Math.max(0, Number(delay) || 0), this.messageSyncQueuedAt + maxWait);
window.clearTimeout(this.messageSyncTimer);
this.messageSyncTimer = window.setTimeout(() => {
const pendingOptions = this.pendingMessageSyncOptions;
this.messageSyncTimer = null;
this.messageSyncQueuedAt = 0;
this.pendingMessageSyncOptions = {};
this.syncActiveMessages(pendingOptions);
}, Math.max(0, runAt - now));
window.clearTimeout(this.syncAfterSendTimer);
this.syncAfterSendTimer = window.setTimeout(() => {
this.syncAfterSendTimer = null;
this.syncActiveMessages(options);
}, Math.max(0, Number(delay) || 0));
},
startMessageSync() {
this.bindReadPresenceEvents();
if (!this.syncTimer) {
this.syncTimer = window.setInterval(() => {
if (isPageVisible() && !realtimeNotifications.isConnected()) {
if (document.visibilityState === 'visible' && !realtimeNotifications.isConnected()) {
this.syncActiveMessages();
}
}, activeMessageSyncIntervalMs());
}, Math.max(250, appConfig.syncIntervalMs));
}
if (!this.conversationSyncTimer) {
this.conversationSyncTimer = window.setInterval(() => {
if (isPageVisible() && !realtimeNotifications.isConnected()) {
if (document.visibilityState === 'visible' && !realtimeNotifications.isConnected()) {
this.refreshRemoteConversations();
}
}, conversationListSyncIntervalMs());
}, Math.max(5000, appConfig.syncIntervalMs * 2));
this.refreshRemoteConversations();
}
},
handleRealtimeNotification(payload) {
if (isDuplicateRealtimeNotification(payload)) {
return;
}
handleRealtimeNotification() {
window.clearTimeout(this.realtimeSyncTimer);
this.realtimeSyncTimer = window.setTimeout(() => {
if (this.activeId) {
this.refreshRemoteConversations();
this.scheduleActiveMessagesSync({
allowReadReceipt: canMarkReadNow(),
includeConversations: true
}, 700);
} else {
this.refreshRemoteConversations();
}
}, 500);
}, 300);
}, 300);
},
bindReadPresenceEvents() {
if (this.readPresenceEventsBound || typeof window === 'undefined' || typeof document === 'undefined') {
@@ -1029,7 +1014,7 @@ export const useConversationStore = defineStore('conversations', {
const syncWhenReadable = () => {
if (canMarkReadNow()) {
this.refreshRemoteConversations();
this.scheduleActiveMessagesSync({ allowReadReceipt: true }, 300);
this.scheduleActiveMessagesSync({ allowReadReceipt: true }, 200);
}
};
window.addEventListener('focus', syncWhenReadable);
@@ -1057,15 +1042,17 @@ export const useConversationStore = defineStore('conversations', {
window.clearTimeout(this.actionNoticeTimer);
this.actionNoticeTimer = window.setTimeout(() => {
this.actionNotice = '';
}, 1800);
this.actionNoticeTimer = null;
}, 3000);
},
setActionError(message) {
this.actionError = message;
this.actionNotice = '';
window.clearTimeout(this.actionErrorTimer);
this.actionErrorTimer = window.setTimeout(() => {
window.clearTimeout(this.actionNoticeTimer);
this.actionNoticeTimer = window.setTimeout(() => {
this.actionError = '';
}, 2400);
this.actionNoticeTimer = null;
}, 3000);
},
focusMessage(message) {
const key = messageStableKey(message);
@@ -1094,6 +1081,8 @@ export const useConversationStore = defineStore('conversations', {
this.startForward([message]);
} else if (action === 'favorite') {
this.toggleFavorite(message);
} else if (action === 'pin') {
this.togglePinnedMessage(message);
} else if (action === 'detail') {
await this.openMessageDetail(message);
} else if (action === 'quote') {
@@ -1204,6 +1193,68 @@ export const useConversationStore = defineStore('conversations', {
this.favoriteMessages = this.favoriteMessages.slice(0, 200);
writeFavoriteMessages(this.favoriteMessages);
},
async togglePinnedMessage(message) {
const conversationId = message?.conversationId || this.activeId;
const key = messageStableKey(message);
if (!conversationId || !key) return;
const current = this.pinnedMessagesByConversation[conversationId];
const next = { ...this.pinnedMessagesByConversation };
if (current && current.key === key) {
delete next[conversationId];
this.pinnedMessagesByConversation = next;
writePinnedMessages(next);
this.setActionNotice('已取消置顶');
try {
await imClient.setPinnedMessage(this.activeConversation, '', current);
} catch (error) {
this.setActionError(`已在本地取消,服务器同步失败:${error.message || '取消置顶失败'}`);
}
} else {
next[conversationId] = {
key,
id: key,
text: messagePreviewText(message),
type: message.type || 'text',
attachment: message.attachment ? { ...message.attachment } : null,
senderName: message.senderName || message.from || '',
timestamp: Number(message.displayTimestamp || message.timestamp || Date.now())
};
this.pinnedMessagesByConversation = next;
writePinnedMessages(next);
this.setActionNotice('消息已置顶');
try {
await imClient.setPinnedMessage(this.activeConversation, key, message);
const nativePins = await imClient.fetchGroupPinnedMessages(this.activeConversation).catch(() => []);
if (nativePins.length) {
const refreshed = parseNativePinnedMessage(nativePins[0], this.activeMessages);
this.pinnedMessagesByConversation = {
...this.pinnedMessagesByConversation,
[conversationId]: refreshed
};
writePinnedMessages(this.pinnedMessagesByConversation);
}
} catch (error) {
const rollback = { ...this.pinnedMessagesByConversation };
delete rollback[conversationId];
this.pinnedMessagesByConversation = rollback;
writePinnedMessages(rollback);
this.setActionError(`置顶失败:${error.message || '服务器同步失败'}`);
}
}
},
async clearPinnedMessage() {
const current = this.pinnedMessagesByConversation[this.activeId] || null;
const next = { ...this.pinnedMessagesByConversation };
delete next[this.activeId];
this.pinnedMessagesByConversation = next;
writePinnedMessages(next);
this.setActionNotice('已取消置顶');
try {
await imClient.setPinnedMessage(this.activeConversation, '', current);
} catch (error) {
this.setActionError(`已在本地取消,服务器同步失败:${error.message || '取消置顶失败'}`);
}
},
setActiveFavorite(key) {
this.activeFavoriteKey = String(key || '');
},
@@ -1260,7 +1311,7 @@ export const useConversationStore = defineStore('conversations', {
this.deleteMessages(this.selectedMessages);
},
startForward(messages) {
this.forwardingMessages = messages.filter(message => message?.text);
this.forwardingMessages = messages.filter(message => message?.text || message?.attachment?.url);
if (!this.forwardingMessages.length) {
this.setActionError('没有可转发的消息');
}
@@ -1313,7 +1364,7 @@ export const useConversationStore = defineStore('conversations', {
const editedMessage = await imClient.editMessage(conversation, message, text);
this.replaceLocalMessage(conversation.id, message, editedMessage);
if (messageActivityTimestamp(editedMessage) >= Number(conversation.updatedAt || 0)) {
conversation.subtitle = messagePreviewText(editedMessage);
conversation.subtitle = editedMessage.text;
conversation.updatedAt = messageActivityTimestamp(editedMessage);
writeLocalConversations(this.conversations);
}
@@ -1328,16 +1379,37 @@ export const useConversationStore = defineStore('conversations', {
if (!target || !this.forwardingMessages.length) {
return;
}
const text = this.forwardingMessages
.map(message => `转发:${message.text || ''}`)
.join('\n\n');
const messages = [...this.forwardingMessages];
let successCount = 0;
const errors = [];
for (const message of messages) {
try {
await this.sendTextToConversation(target, text);
if (message.attachment?.url) {
await imClient.forwardAttachmentMessage(target, message);
} else if (message.text) {
const text = forwardedText(message);
if (!text) {
throw new Error('消息内容为空');
}
const sentMessage = await this.sendTextToConversation(target, text);
if (sentMessage?.status === 'failed') {
throw new Error(sentMessage.error || '转发失败');
}
}
successCount += 1;
} catch (error) {
errors.push(error.message || '转发失败');
}
}
if (successCount > 0) {
this.forwardingMessages = [];
this.clearSelection();
this.setActionNotice('已转发');
} catch (error) {
this.setActionError(error.message || '转发失败');
this.refreshRemoteConversations();
}
if (errors.length) {
this.setActionError(`成功 ${successCount} 条,失败 ${errors.length} 条:${errors[0]}`);
} else {
this.setActionNotice(`已转发 ${successCount} 条`);
}
},
async recallMessage(message) {
@@ -1374,12 +1446,7 @@ export const useConversationStore = defineStore('conversations', {
const conversation = await imClient.createGroup(session.userId, options);
this.upsertConversation(conversation);
this.setActiveConversation(conversation.id);
const nativeStatus = conversation.nativeStatus || conversation.raw?.nativeStatus || '';
if (nativeStatus && nativeStatus !== 'ok') {
this.setActionNotice(options.channel ? '公告群已创建,仅网页可见' : '群组已创建,仅网页可见');
} else {
this.setActionNotice(options.channel ? '公告群已创建' : '群组已创建');
}
this.refreshRemoteConversations();
return true;
} catch (error) {
@@ -1397,8 +1464,7 @@ export const useConversationStore = defineStore('conversations', {
const conversation = await imClient.joinGroup(session.userId, groupKey);
this.upsertConversation(conversation);
this.setActiveConversation(conversation.id);
const nativeStatus = conversation.nativeStatus || conversation.raw?.nativeStatus || '';
this.setActionNotice(nativeStatus && nativeStatus !== 'ok' ? '已加入群组,仅网页可见' : '已加入群组');
this.setActionNotice('已加入群组');
this.refreshRemoteConversations();
return true;
} catch (error) {
+39 -16
View File
@@ -12,6 +12,10 @@ function nextProfilePortrait(profilePortrait, currentPortrait) {
return normalizeStoredPortrait(profilePortrait) || normalizeStoredPortrait(currentPortrait);
}
function inferAccountType(account) {
return String(account || '').includes('@') ? 2 : 1;
}
export const useSessionStore = defineStore('session', {
state: () => ({
isAuthenticated: false,
@@ -32,12 +36,14 @@ export const useSessionStore = defineStore('session', {
if (!raw) {
return;
}
try {
const session = JSON.parse(raw);
if (session.appServer !== appConfig.appServer) {
localStorage.removeItem(STORAGE_KEY);
return;
}
if (session.userId && session.token) {
if (!session.clientId) {
localStorage.removeItem(STORAGE_KEY);
@@ -49,9 +55,6 @@ export const useSessionStore = defineStore('session', {
this.portrait = normalizeStoredPortrait(session.portrait);
this.isAuthenticated = true;
imClient.restoreClientId(session.clientId);
if (session.localOnly) {
this.connectionStatusText = '本地调试登录';
}
this.connect();
this.refreshProfile();
}
@@ -59,11 +62,12 @@ export const useSessionStore = defineStore('session', {
localStorage.removeItem(STORAGE_KEY);
}
},
async loginWithPassword(mobile, password) {
async loginWithPassword(account, password, type = inferAccountType(account)) {
this.error = '';
this.connecting = true;
try {
const result = await imClient.loginWithPassword(mobile, password);
const result = await imClient.loginWithPassword(account, password, type);
this.applyLoginResult(result);
await this.connect();
} catch (error) {
@@ -72,11 +76,12 @@ export const useSessionStore = defineStore('session', {
this.connecting = false;
}
},
async loginWithCode(mobile, code) {
async loginWithCode(account, code) {
this.error = '';
this.connecting = true;
try {
const result = await imClient.loginWithCode(mobile, code);
const result = await imClient.loginWithCode(account, code);
this.applyLoginResult(result);
await this.connect();
} catch (error) {
@@ -85,6 +90,7 @@ export const useSessionStore = defineStore('session', {
this.connecting = false;
}
},
async completePcSessionLogin(result) {
this.error = '';
this.connecting = true;
@@ -97,11 +103,15 @@ export const useSessionStore = defineStore('session', {
this.connecting = false;
}
},
async registerWithPhone(mobile, code) {
async register(payload) {
this.error = '';
this.connecting = true;
try {
return await imClient.registerWithPhone(mobile, code);
const result = await imClient.register(payload);
this.applyLoginResult(result);
await this.connect();
return result;
} catch (error) {
this.error = error.message || '注册失败';
return null;
@@ -109,28 +119,27 @@ export const useSessionStore = defineStore('session', {
this.connecting = false;
}
},
applyLoginResult(result) {
this.userId = result.userId || result.uid || result.id || '';
this.token = result.token || result.imToken || '';
this.displayName = result.displayName || result.userName || result.name || this.userId;
this.portrait = normalizeStoredPortrait(result.portrait);
this.isAuthenticated = Boolean(this.userId && this.token);
if (result.localOnly) {
this.connectionStatusText = '本地调试登录';
}
this.persistSession(Boolean(result.localOnly));
this.persistSession();
},
persistSession(localOnly = false) {
persistSession() {
localStorage.setItem(STORAGE_KEY, JSON.stringify({
userId: this.userId,
token: this.token,
displayName: this.displayName,
portrait: this.portrait,
clientId: imClient.getClientId(),
localOnly,
appServer: appConfig.appServer
}));
},
applyProfile(profile) {
if (!profile) {
return;
@@ -140,6 +149,7 @@ export const useSessionStore = defineStore('session', {
this.portrait = nextProfilePortrait(profile.portrait, this.portrait);
this.persistSession();
},
async refreshProfile() {
if (!this.userId) {
return null;
@@ -152,6 +162,7 @@ export const useSessionStore = defineStore('session', {
return null;
}
},
async saveProfile({ displayName, portraitFile }) {
if (!this.userId) {
throw new Error('请先登录');
@@ -163,17 +174,21 @@ export const useSessionStore = defineStore('session', {
this.applyProfile(profile);
return profile;
},
async changePassword({ oldPassword, newPassword }) {
if (!this.userId) {
throw new Error('请先登录');
}
await imClient.changePassword({ oldPassword, newPassword });
await this.logout();
return true;
},
async resetPasswordWithCode({ mobile, resetCode, newPassword }) {
await imClient.resetPasswordWithCode({ mobile, resetCode, newPassword });
return true;
},
async connect() {
if (!this.userId || !this.token) {
return;
@@ -183,6 +198,7 @@ export const useSessionStore = defineStore('session', {
this.bindImEvents();
await imClient.connect(this.userId, this.token);
},
bindImEvents() {
if (this.eventsBound) {
return;
@@ -193,10 +209,17 @@ export const useSessionStore = defineStore('session', {
this.connectionStatusText = status.statusText || (status.connected ? '已连接' : '未连接');
});
},
logout() {
async logout() {
try {
await imClient.logout?.();
} catch (error) {
this.error = error.message || '退出登录失败';
} finally {
imClient.disconnect();
localStorage.removeItem(STORAGE_KEY);
this.$reset();
}
}
}
});
+463 -159
View File
@@ -479,6 +479,182 @@ button {
background: var(--panel);
}
.documented-shell {
min-height: 100dvh;
display: grid;
grid-template-columns: 260px minmax(0, 1fr);
background:
radial-gradient(circle at top left, rgba(23, 125, 114, 0.08), transparent 28%),
linear-gradient(180deg, #f4f8f7 0%, #eef3f7 100%);
}
.documented-rail {
min-height: 0;
display: grid;
align-content: start;
gap: 14px;
padding: 24px 20px;
border-right: 1px solid var(--line);
background: rgba(255, 255, 255, 0.82);
backdrop-filter: blur(12px);
}
.documented-avatar {
width: 64px;
height: 64px;
display: grid;
place-items: center;
overflow: hidden;
border-radius: 16px;
background: #dff4ef;
color: var(--primary-strong);
font-size: 28px;
font-weight: 800;
}
.documented-avatar img {
width: 100%;
height: 100%;
object-fit: cover;
}
.documented-rail-copy {
display: grid;
gap: 4px;
}
.documented-rail-copy strong {
font-size: 16px;
}
.documented-rail-copy small {
color: var(--muted);
overflow-wrap: anywhere;
}
.documented-rail-button {
min-height: 40px;
padding: 0 14px;
border: 0;
border-radius: 10px;
background: var(--primary);
color: #fff;
font-weight: 700;
text-align: left;
}
.documented-rail-button.ghost {
border: 1px solid var(--line);
background: #fff;
color: var(--text);
}
.documented-main {
min-width: 0;
min-height: 0;
overflow: auto;
padding: 28px;
display: grid;
align-content: start;
gap: 18px;
}
.documented-header {
display: flex;
align-items: end;
justify-content: space-between;
gap: 18px;
}
.documented-header h1 {
margin: 0;
font-size: 28px;
}
.documented-header p {
margin: 6px 0 0;
color: var(--muted);
}
.documented-status {
min-width: 180px;
display: grid;
gap: 4px;
padding: 14px 16px;
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(255, 255, 255, 0.88);
}
.documented-status span {
color: var(--muted);
font-size: 12px;
}
.documented-status strong {
font-size: 15px;
}
.documented-card {
display: grid;
gap: 12px;
padding: 20px;
border: 1px solid var(--line);
border-radius: 16px;
background: rgba(255, 255, 255, 0.88);
box-shadow: 0 16px 36px rgba(24, 33, 47, 0.06);
}
.documented-card h2 {
margin: 0;
font-size: 18px;
}
.documented-text {
margin: 0;
color: var(--muted);
line-height: 1.6;
}
.documented-list {
margin: 0;
padding-left: 18px;
display: grid;
gap: 8px;
line-height: 1.55;
}
.documented-list.muted {
color: var(--muted);
}
.documented-meta {
margin: 0;
display: grid;
gap: 10px;
}
.documented-meta div {
display: grid;
grid-template-columns: 110px minmax(0, 1fr);
gap: 12px;
padding-top: 10px;
border-top: 1px solid var(--line);
}
.documented-meta dt {
color: var(--muted);
}
.documented-meta dd {
margin: 0;
overflow-wrap: anywhere;
}
.documented-password-panel {
width: min(100%, 360px);
}
.navigation-rail {
min-height: 0;
display: flex;
@@ -1078,6 +1254,44 @@ button {
background: #eaf3f1;
}
.conversation-item.pinned {
background: rgba(15, 118, 110, 0.055);
}
.conversation-pin {
display: inline-block;
margin-right: 5px;
color: #0f766e;
font-size: 12px;
transform: rotate(-25deg);
}
.conversation-context-menu {
position: fixed;
z-index: 1200;
min-width: 124px;
padding: 6px;
border: 1px solid #d7e0e8;
border-radius: 10px;
background: #fff;
box-shadow: 0 12px 30px rgba(15, 23, 42, 0.18);
}
.conversation-context-menu button {
width: 100%;
padding: 9px 12px;
border: 0;
border-radius: 7px;
background: transparent;
color: #1f2937;
text-align: left;
cursor: pointer;
}
.conversation-context-menu button:hover {
background: #eef7f6;
}
.favorite-item {
width: 100%;
display: grid;
@@ -1238,14 +1452,6 @@ button {
padding: 24px;
}
.empty-list-actions {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 8px;
margin-top: 8px;
}
.empty-chat {
min-height: 0;
padding: 24px;
@@ -1308,6 +1514,10 @@ button {
background: #eef2f5;
}
.chat-panel.has-pinned-message {
grid-template-rows: 72px auto minmax(0, 1fr) auto auto;
}
.contact-panel {
min-width: 0;
min-height: 0;
@@ -1906,16 +2116,6 @@ button {
font-size: 12px;
}
.group-member-row .group-member-role {
width: fit-content;
padding: 2px 7px;
border: 1px solid #b8d8d1;
border-radius: 5px;
background: #edf8f5;
color: var(--primary);
font-weight: 700;
}
.group-management-dialog {
width: min(520px, calc(100% - 32px));
}
@@ -1976,9 +2176,7 @@ button {
min-height: 0;
overflow: auto;
overscroll-behavior: contain;
padding: 24px 24px 72px;
scroll-padding-bottom: 72px;
scrollbar-gutter: stable;
padding: 24px;
}
.message-row {
@@ -2156,31 +2354,223 @@ button {
object-fit: contain;
}
.pinned-message-banner {
width: calc(100% - 28px);
height: 42px;
min-height: 42px;
margin: 8px 14px;
align-self: center;
display: grid;
grid-template-columns: auto auto minmax(0, 1fr) auto;
align-items: center;
gap: 8px;
padding: 8px 12px;
border: 1px solid #d5e2df;
border-radius: 9px;
background: #f7fbfa;
color: #52606d;
text-align: left;
cursor: pointer;
}
.pinned-message-banner strong {
color: #0f766e;
white-space: nowrap;
}
.pinned-message-preview {
min-width: 0;
display: flex;
align-items: center;
gap: 7px;
overflow: hidden;
}
.pinned-message-preview > span {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.pinned-message-preview img {
width: 28px;
height: 28px;
flex: 0 0 28px;
border-radius: 4px;
object-fit: cover;
}
.pinned-message-close {
padding: 0 4px;
color: #748091;
font-size: 20px;
}
.message-row.system {
justify-content: center;
padding-top: 5px;
padding-bottom: 5px;
}
.system-message-pill {
max-width: min(78%, 620px);
padding: 5px 12px;
border-radius: 5px;
background: #c8c8c8;
color: #fff;
font-size: 12px;
line-height: 1.45;
text-align: center;
}
.message-video {
display: block;
width: min(360px, 68vw);
max-height: 360px;
border-radius: 7px;
background: #111;
}
.mention-picker {
position: absolute;
left: 18px;
bottom: 112px;
z-index: 20;
width: min(320px, calc(100% - 36px));
max-height: 260px;
overflow-y: auto;
padding: 6px;
border: 1px solid #d7e0e8;
border-radius: 10px;
background: #fff;
box-shadow: 0 12px 32px rgb(15 23 42 / 18%);
}
.mention-picker button {
display: flex;
width: 100%;
align-items: center;
gap: 10px;
padding: 8px 10px;
border: 0;
border-radius: 7px;
background: transparent;
text-align: left;
}
.mention-picker button:hover {
background: #eef7f5;
}
.mention-picker img,
.mention-picker button > span {
width: 32px;
height: 32px;
border-radius: 7px;
object-fit: cover;
}
.mention-picker button > span {
display: grid;
place-items: center;
background: #dceaf3;
color: #23445c;
}
.red-packet-card {
width: min(320px, 68vw);
margin: -10px -12px -8px;
overflow: hidden;
border-radius: 7px;
background: #ff9f32;
color: #fff;
}
.red-packet-card-main {
display: flex;
align-items: center;
gap: 13px;
padding: 20px 18px 17px;
}
.red-packet-card-main > span:last-child {
display: grid;
gap: 7px;
}
.red-packet-card-main strong {
font-size: 17px;
font-weight: 700;
}
.red-packet-card-main small {
color: rgba(255, 255, 255, 0.9);
font-size: 13px;
}
.red-packet-icon,
.red-packet-mini-icon {
display: grid;
place-items: center;
flex: 0 0 auto;
border-radius: 3px;
background: #d92f27;
color: #ffd968;
font-weight: 800;
}
.red-packet-icon {
width: 34px;
height: 44px;
font-size: 17px;
}
.red-packet-card-footer {
padding: 9px 15px;
background: #fff;
color: #8a8f94;
font-size: 12px;
}
.red-packet-receipt {
display: flex;
align-items: center;
gap: 7px;
color: #69747d;
}
.red-packet-mini-icon {
width: 22px;
height: 28px;
font-size: 11px;
}
.image-viewer-backdrop {
position: fixed;
inset: 0;
z-index: 80;
display: grid;
place-items: center;
padding: 24px;
background: rgba(12, 18, 26, 0.58);
padding: 20px;
background: rgba(7, 12, 20, 0.82);
backdrop-filter: blur(6px);
}
.image-viewer-dialog {
width: min(880px, calc(100vw - 48px));
height: min(640px, calc(100vh - 48px));
min-width: 360px;
min-height: 280px;
max-width: calc(100vw - 48px);
max-height: calc(100vh - 48px);
width: min(920px, calc(100vw - 64px));
height: min(660px, calc(100vh - 64px));
min-width: 320px;
min-height: 260px;
max-width: calc(100vw - 64px);
max-height: calc(100vh - 64px);
display: grid;
grid-template-rows: 52px minmax(0, 1fr);
overflow: hidden;
resize: both;
border: 1px solid rgba(255, 255, 255, 0.18);
border-radius: 8px;
background: #101820;
box-shadow: 0 24px 70px rgba(0, 0, 0, 0.36);
border-radius: 14px;
background: #0b1119;
box-shadow: 0 28px 90px rgba(0, 0, 0, 0.56);
}
.image-viewer-toolbar {
@@ -2194,17 +2584,6 @@ button {
background: rgba(24, 33, 47, 0.94);
}
.image-viewer-title {
min-width: 0;
flex: 1;
overflow: hidden;
color: #f8fafc;
font-size: 13px;
font-weight: 700;
text-overflow: ellipsis;
white-space: nowrap;
}
.image-viewer-toolbar button {
width: 36px;
height: 36px;
@@ -2224,6 +2603,7 @@ button {
}
.image-viewer-stage {
position: relative;
min-width: 0;
min-height: 0;
display: grid;
@@ -2231,31 +2611,55 @@ button {
overflow: hidden;
background: #0c121a;
cursor: default;
touch-action: none;
}
.image-viewer-stage.zoomed {
cursor: grab;
.image-viewer-nav {
position: absolute;
top: 50%;
z-index: 2;
width: 52px;
height: 52px;
display: grid;
place-items: center;
border: 1px solid rgba(255, 255, 255, 0.18);
border-radius: 50%;
background: rgba(18, 27, 39, 0.76);
color: #fff;
font-size: 42px;
font-weight: 300;
line-height: 1;
transform: translateY(-50%);
cursor: pointer;
backdrop-filter: blur(5px);
}
.image-viewer-stage.dragging {
cursor: grabbing;
.image-viewer-nav:hover {
background: rgba(41, 57, 75, 0.94);
}
.image-viewer-prev {
left: 18px;
}
.image-viewer-next {
right: 18px;
}
.image-viewer-img {
max-width: calc(100% - 32px);
max-height: calc(100% - 32px);
position: absolute;
top: 20px;
left: 90px;
width: calc(100% - 180px);
height: calc(100% - 40px);
max-width: none;
max-height: none;
object-fit: contain;
transform-origin: center center;
transition: transform 0.08s ease-out;
transition: transform 0.12s ease-out;
user-select: none;
pointer-events: none;
}
.image-viewer-stage.dragging .image-viewer-img {
transition: none;
}
.sender-profile-backdrop {
position: fixed;
inset: 0;
@@ -2789,11 +3193,9 @@ button {
}
.composer-tools button {
width: 34px;
height: 34px;
display: grid;
place-items: center;
border: 1px solid transparent;
width: 32px;
height: 32px;
border: 0;
border-radius: 6px;
background: transparent;
color: var(--muted);
@@ -2804,104 +3206,6 @@ button {
background: #edf2f5;
}
.composer-tools button:disabled {
cursor: default;
opacity: 0.45;
}
.composer-attachment-preview {
display: flex;
gap: 8px;
padding: 10px 16px 0;
overflow-x: auto;
}
.composer-attachment-item {
position: relative;
width: 88px;
min-width: 88px;
height: 88px;
display: grid;
place-items: center;
overflow: hidden;
border: 1px solid var(--line);
border-radius: 8px;
background: #edf2f5;
}
.composer-attachment-item img {
width: 100%;
height: 100%;
display: block;
object-fit: cover;
}
.composer-attachment-file-icon {
color: var(--primary);
font-size: 30px;
}
.composer-attachment-name {
position: absolute;
right: 0;
bottom: 0;
left: 0;
overflow: hidden;
padding: 4px 6px;
background: rgba(18, 28, 40, 0.72);
color: #fff;
font-size: 10px;
text-overflow: ellipsis;
white-space: nowrap;
}
.composer-attachment-item > button {
position: absolute;
top: 4px;
right: 4px;
width: 24px;
height: 24px;
display: grid;
place-items: center;
border: 0;
border-radius: 50%;
background: rgba(18, 28, 40, 0.74);
color: #fff;
font-size: 17px;
line-height: 1;
}
.composer-tool-button {
border-color: rgba(23, 125, 114, 0.28);
background: rgba(23, 125, 114, 0.1);
color: var(--primary);
}
.composer-tool-button.file-tool {
border-color: rgba(216, 78, 63, 0.28);
background: rgba(216, 78, 63, 0.1);
color: var(--accent);
}
.composer-tool-button:hover {
border-color: currentColor;
background: rgba(23, 125, 114, 0.16);
}
.composer-tool-button.file-tool:hover {
background: rgba(216, 78, 63, 0.16);
}
.composer-tool-icon {
width: 22px;
height: 22px;
fill: none;
stroke: currentColor;
stroke-width: 1.9;
stroke-linecap: round;
stroke-linejoin: round;
}
.emoji-picker {
position: absolute;
left: 16px;
+22 -1
View File
@@ -1,6 +1,12 @@
const path = require('path');
const webpack = require('webpack');
const runtimeEnvironment = process.env.VUE_APP_RUNTIME_ENV === 'production'
? 'production'
: 'local';
const appServerTarget = process.env.VUE_APP_APP_SERVER_TARGET || 'http://18.141.44.165:8888';
const webApiTarget = process.env.VUE_APP_WEB_API_TARGET || 'http://18.141.44.165:9000';
module.exports = {
outputDir: 'dist',
publicPath: './',
@@ -35,16 +41,31 @@ module.exports = {
overlay: false
},
proxy: {
'/app-server': {
target: appServerTarget,
changeOrigin: true,
pathRewrite: {
'^/app-server': ''
}
},
'/local-api': {
target: 'http://127.0.0.1:8024',
target: webApiTarget,
changeOrigin: true,
pathRewrite: {
'^/local-api': '/api'
}
},
'/api': {
target: webApiTarget,
changeOrigin: true
}
}
},
chainWebpack(config) {
config.plugin('html').tap((args) => {
args[0].runtimeConfigFile = `runtime-config.${runtimeEnvironment}.js`;
return args;
});
config.optimization.concatenateModules(false);
config.optimization.minimize(false);
}