feat: improve realtime messaging and media handling

This commit is contained in:
winchen
2026-07-28 19:43:14 +08:00
parent 051f60aaf0
commit 6f18980a64
31 changed files with 25265 additions and 21814 deletions
+6 -10
View File
@@ -34,6 +34,11 @@ 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) {
@@ -41,16 +46,7 @@ try {
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 = '';
}
$alias = $friendAliasMap[$uid] ?? '';
if ($alias === '') {
$alias = $remarkMap[$uid] ?? '';
}
+194 -11
View File
@@ -70,6 +70,8 @@ function webGroupConversation(array $group, string $role = 'member'): array
'line' => 0,
'category' => $category,
'role' => $role,
'nativeStatus' => (string)($group['native_status'] ?? ''),
'nativeError' => (string)($group['native_error'] ?? ''),
],
];
}
@@ -176,6 +178,48 @@ 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', [
@@ -425,11 +469,134 @@ 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) {
respond(404, '没有找到该群组');
return nativeGroupDetailAction($imDb, $userId, $groupId);
}
$member = fetchWebGroupMember($appDb, $groupId, $userId);
if (!$member) {
@@ -462,7 +629,7 @@ 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)) {
respond(403, '你不在该群组中');
return nativeGroupMembersAction($imDb, $userId, $groupId);
}
$statement = $appDb->prepare(
@@ -512,7 +679,10 @@ function updateGroupAliasAction(PDO $appDb, string $userId, string $groupId, str
respond(400, '本群昵称过长');
}
if (!fetchWebGroupMember($appDb, $groupId, $userId)) {
respond(403, '你不在该群组中');
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];
}
$now = webImNowMs();
@@ -781,8 +951,16 @@ function joinWebGroupAction(PDO $appDb, string $userId, string $groupKey): array
$group = fetchWebGroup($appDb, $groupKey);
if (!$group) {
try {
$native = requireImSuccess(imAdminPost('/admin/group/get_info', ['groupId' => $groupKey]), '群组不存在');
$native = fetchNativeGroupInfo($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`,'
@@ -791,33 +969,38 @@ function joinWebGroupAction(PDO $appDb, string $userId, string $groupKey): array
. ' on duplicate key update `updated_at_ms` = values(`updated_at_ms`)'
);
$statement->execute([
$groupKey,
(string)($native['name'] ?? $groupKey),
(string)($native['portrait'] ?? ''),
(string)($native['owner'] ?? ''),
$groupKey,
$nativeGroupId,
$nativeName,
$nativePortrait,
$nativeOwner,
$nativeGroupId,
$userId,
$now,
$now,
]);
$group = fetchWebGroup($appDb, $groupKey);
$group = fetchWebGroup($appDb, $nativeGroupId);
} 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) {
// Web membership is authoritative for this web build; native group sync is best-effort.
$nativeStatus = $nativeStatus === 'ok' ? 'partial' : ($nativeStatus ?: 'fallback');
$nativeError = mb_substr($error->getMessage() ?: '加入原生群组失败', 0, 255, 'UTF-8');
}
$role = fetchWebGroupRole($appDb, $groupId, $userId);
return [
'group' => fetchWebGroup($appDb, $groupId),
'conversation' => webGroupConversation($group, $role),
'nativeStatus' => $nativeStatus,
'nativeError' => $nativeError,
];
}
+25
View File
@@ -355,6 +355,31 @@ 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 === '') {
+677 -9
View File
@@ -132,7 +132,7 @@ function fetchMessageRows(PDO $db, array $messageIds): array
$messages = [];
foreach ($idsByTable as $table => $ids) {
$sql = 'select `_mid`, `_from`, `_type`, `_target`, `_line`, `_searchable_key`, `_dt`, `_content_type`, `_to`'
$sql = 'select `_mid`, `_from`, `_type`, `_target`, `_line`, `_data`, `_searchable_key`, `_dt`, `_content_type`, `_to`'
. ' from `' . $table . '` where `_mid` in (' . placeholders($ids) . ')';
$statement = $db->prepare($sql);
$statement->execute($ids);
@@ -232,12 +232,21 @@ function messagePreviewText(?array $message): string
return '';
}
$attachment = is_array($message['attachment'] ?? null) ? $message['attachment'] : null;
$contentType = (int)($message['contentType'] ?? 0);
$messageType = (string)($message['type'] ?? '');
$placeholderIsImage = $contentType === 3 || $messageType === 'image';
$text = trim((string)($message['text'] ?? ''));
if ($contentType !== 1 && $text === '[暂不支持的消息类型]') {
$text = '';
}
if ($placeholderIsImage && ($text === '[图片]' || $text === '图片')) {
$text = '';
}
if ($attachment) {
$text = trim((string)($message['text'] ?? ''));
return $text !== '' ? $text : attachmentFallbackText($attachment);
}
return (string)($message['text'] ?? '');
return $text;
}
function fetchUserInfoMap(PDO $db, array $userIds, string $ownerId = ''): array
@@ -405,6 +414,42 @@ function isWebGroupTarget(PDO $appDb, string $targetId): bool
return (bool)$statement->fetchColumn();
}
function nativeGroupRoleFromType(mixed $type): string
{
$value = (int)$type;
if ($value === 2) {
return 'owner';
}
if ($value === 1) {
return 'admin';
}
return 'member';
}
function isNativeGroupTarget(PDO $db, string $targetId): bool
{
if ($targetId === '') {
return false;
}
$statement = $db->prepare('select 1 from `t_group` where `_gid` = ? and `_deleted` = 0 limit 1');
$statement->execute([$targetId]);
return (bool)$statement->fetchColumn();
}
function nativeGroupRole(PDO $db, string $userId, string $groupId): string
{
$statement = $db->prepare(
'select `_type` from `t_group_member` where `_gid` = ? and `_mid` = ? limit 1'
);
$statement->execute([$groupId, $userId]);
$type = $statement->fetchColumn();
return $type === false ? '' : nativeGroupRoleFromType($type);
}
function markWebGroupRead(PDO $appDb, string $userId, string $groupId, int $timestamp): void
{
if ($userId === '' || $groupId === '' || $timestamp <= 0) {
@@ -422,6 +467,34 @@ function markWebGroupRead(PDO $appDb, string $userId, string $groupId, int $time
$statement->execute([$groupId, $userId, $timestamp, $now]);
}
function markNativeGroupRead(PDO $db, string $userId, string $groupId, int $timestamp): void
{
if ($userId === '' || $groupId === '' || $timestamp <= 0) {
return;
}
$statement = $db->prepare(
'select `id`, `_dt` from `t_read_report`'
. ' where `_uid` = ? and `_type` = 1 and `_line` = 0 and `_target` = ?'
. ' order by `_dt` desc limit 1'
);
$statement->execute([$userId, $groupId]);
$row = $statement->fetch();
if ($row) {
if ($timestamp > (int)$row['_dt']) {
$update = $db->prepare('update `t_read_report` set `_dt` = ? where `id` = ?');
$update->execute([$timestamp, (int)$row['id']]);
}
return;
}
$insert = $db->prepare(
'insert into `t_read_report` (`_uid`, `_type`, `_line`, `_target`, `_dt`) values (?, 1, 0, ?, ?)'
);
$insert->execute([$userId, $groupId, $timestamp]);
}
function webGroupRole(PDO $appDb, string $userId, string $groupId): string
{
$statement = $appDb->prepare(
@@ -434,6 +507,50 @@ function webGroupRole(PDO $appDb, string $userId, string $groupId): string
return is_string($role) && $role !== '' ? $role : '';
}
function loadNativeGroupReadStateMap(PDO $db, string $userId, array $groupIds): array
{
$groupIds = array_values(array_unique(array_filter(array_map('strval', $groupIds))));
if ($userId === '' || !$groupIds) {
return [];
}
$statement = $db->prepare(
'select `_target`, max(`_dt`) as `_read_at` from `t_read_report`'
. ' where `_uid` = ? and `_type` = 1 and `_line` = 0'
. ' and `_target` in (' . placeholders($groupIds) . ')'
. ' group by `_target`'
);
$statement->execute(array_merge([$userId], $groupIds));
$readAtByGroup = [];
foreach ($statement->fetchAll() as $row) {
$readAtByGroup[(string)$row['_target']] = (int)$row['_read_at'];
}
return $readAtByGroup;
}
function fetchNativeGroupMemberMap(PDO $db, string $groupId, array $userIds): array
{
$userIds = array_values(array_unique(array_filter(array_map('strval', $userIds))));
if ($groupId === '' || !$userIds) {
return [];
}
$statement = $db->prepare(
'select `_mid`, `_alias`, `_type`, `_dt`, `_create_dt` from `t_group_member`'
. ' where `_gid` = ? and `_mid` in (' . placeholders($userIds) . ')'
);
$statement->execute(array_merge([$groupId], $userIds));
$members = [];
foreach ($statement->fetchAll() as $row) {
$members[(string)$row['_mid']] = $row;
}
return $members;
}
function formatWebGroupMessage(
array $row,
string $currentUserId,
@@ -508,6 +625,314 @@ function formatWebGroupMessage(
];
}
function cleanupNativeMediaUrl(string $url): string
{
return rtrim($url, " \t\r\n\0\x0B\"'<>.,;)]}");
}
function nativeMediaUrlScore(string $url): int
{
$path = strtolower((string)(parse_url($url, PHP_URL_PATH) ?: $url));
$score = 0;
if (preg_match('/\.(?:jpe?g|png|gif|webp|bmp|avif)$/i', $path)) {
$score += 30;
}
if (strpos($path, 'image') !== false || strpos($path, 'media') !== false || strpos($path, 'upload') !== false) {
$score += 5;
}
if (strpos($path, 'thumb') !== false || strpos($path, 'thumbnail') !== false) {
$score -= 10;
}
return $score;
}
function extractNativeMediaUrlFromData($data): string
{
if (is_resource($data)) {
$data = stream_get_contents($data);
}
if (!is_string($data) || $data === '') {
return '';
}
if (!preg_match_all("~https?://[^\\s\"'<>\\x00]+~i", $data, $matches)) {
return '';
}
$urls = [];
foreach ($matches[0] as $url) {
$url = cleanupNativeMediaUrl((string)$url);
if ($url !== '' && filter_var($url, FILTER_VALIDATE_URL)) {
$urls[$url] = $url;
}
}
if (!$urls) {
return '';
}
$urls = array_values($urls);
usort($urls, static function (string $left, string $right): int {
$scoreDelta = nativeMediaUrlScore($right) <=> nativeMediaUrlScore($left);
return $scoreDelta !== 0 ? $scoreDelta : strlen($right) <=> strlen($left);
});
return $urls[0] ?? '';
}
function nativeAttachmentName(string $url, string $type): string
{
$path = (string)(parse_url($url, PHP_URL_PATH) ?: '');
$name = trim(rawurldecode((string)basename($path)));
if ($name !== '' && $name !== '.' && $name !== '/') {
return $name;
}
return $type === 'image' ? '图片' : '文件';
}
function nativeAttachmentMime(string $url, string $type): string
{
if ($type !== 'image') {
return '';
}
$path = strtolower((string)(parse_url($url, PHP_URL_PATH) ?: ''));
if (preg_match('/\.jpe?g$/', $path)) {
return 'image/jpeg';
}
if (preg_match('/\.png$/', $path)) {
return 'image/png';
}
if (preg_match('/\.gif$/', $path)) {
return 'image/gif';
}
if (preg_match('/\.webp$/', $path)) {
return 'image/webp';
}
if (preg_match('/\.bmp$/', $path)) {
return 'image/bmp';
}
if (preg_match('/\.avif$/', $path)) {
return 'image/avif';
}
return 'image/*';
}
function nativeAttachmentFromRow(array $row, ?array $attachment): ?array
{
if ($attachment !== null) {
return $attachment;
}
$contentType = (int)($row['_content_type'] ?? 0);
if ($contentType !== 3 && $contentType !== 5) {
return null;
}
$url = extractNativeMediaUrlFromData($row['_data'] ?? '');
if ($url === '') {
return null;
}
$type = $contentType === 3 ? 'image' : 'file';
return [
'type' => $type,
'url' => $url,
'name' => nativeAttachmentName($url, $type),
'mime' => nativeAttachmentMime($url, $type),
'size' => 0,
];
}
function isNativePlaceholderText(string $text, int $contentType): bool
{
$text = trim($text);
if ($text === '') {
return false;
}
if ($contentType !== 1 && $text === '[暂不支持的消息类型]') {
return true;
}
return $contentType === 3 && ($text === '[图片]' || $text === '图片');
}
function nativeDisplayText(string $searchableText, int $contentType, bool $hasAttachment, bool $isRecalled = false): string
{
$text = trim($searchableText);
if (isNativePlaceholderText($text, $contentType)) {
return '';
}
if ($text === '' && !$isRecalled) {
return nativeMessageFallbackText($contentType, $hasAttachment);
}
return $text;
}
function nativeMessageFallbackText(int $contentType, bool $hasAttachment): string
{
if ($hasAttachment) {
return '';
}
if ($contentType === 5) {
return '[文件]';
}
return '';
}
function nativeMessageTableForDate(DateTimeImmutable $date): string
{
$localDate = $date->setTimezone(new DateTimeZone(IM_DB_TIMEZONE));
$year = (int)$localDate->format('Y');
$month = (int)$localDate->format('n') - 1;
return 't_messages_' . (($year % 3) * 12 + $month);
}
function recentNativeMessageTables(int $monthsBack = 3): array
{
$monthsBack = max(1, min($monthsBack, 12));
$cursor = (new DateTimeImmutable('now', new DateTimeZone(IM_DB_TIMEZONE)))
->modify('first day of this month');
$tables = [];
for ($index = 0; $index < $monthsBack; $index++) {
$tables[] = nativeMessageTableForDate($cursor);
$cursor = $cursor->modify('-1 month');
}
return array_values(array_unique($tables));
}
function loadNativeGroupRowsFromGlobal(PDO $db, array $groupIds, int $limit): array
{
$groupIds = array_values(array_unique(array_filter(array_map('strval', $groupIds))));
if (!$groupIds) {
return [];
}
$limit = min(max($limit, 50), 1000);
$rows = [];
foreach (recentNativeMessageTables(3) as $table) {
try {
$statement = $db->prepare(
'select `_mid`, `_from`, `_type`, `_target`, `_line`, `_data`, `_searchable_key`, `_dt`, `_content_type`, `_to`'
. ' from `' . $table . '`'
. ' where `_type` = 1 and `_line` = 0'
. ' and `_target` in (' . placeholders($groupIds) . ')'
. ' order by `_mid` desc limit ' . $limit
);
$statement->execute($groupIds);
} catch (Throwable) {
continue;
}
foreach ($statement->fetchAll() as $row) {
$rows[] = $row;
}
}
usort($rows, static fn($left, $right) => strcmp((string)$right['_mid'], (string)$left['_mid']));
$uniqueRows = [];
$seenMessageIds = [];
foreach ($rows as $row) {
$messageId = (string)$row['_mid'];
if ($messageId === '' || isset($seenMessageIds[$messageId])) {
continue;
}
$seenMessageIds[$messageId] = true;
$uniqueRows[] = $row;
if (count($uniqueRows) >= $limit) {
break;
}
}
return $uniqueRows;
}
function formatNativeGroupMessage(
array $row,
string $currentUserId,
array $group,
?array $attachment = null,
array $users = [],
array $members = []
): array {
$groupId = (string)$row['_target'];
$from = (string)$row['_from'];
$senderUser = $users[$from] ?? [];
$senderMember = $members[$from] ?? [];
$senderAlias = trim((string)($senderMember['_alias'] ?? ''));
$senderContactAlias = trim((string)($senderUser['_alias'] ?? ''));
$senderFriendAlias = trim((string)($senderUser['_friend_alias'] ?? ''));
$senderRemarkAlias = trim((string)($senderUser['_remark_alias'] ?? ''));
$senderRawName = trim((string)($senderUser['_display_name'] ?? ''))
?: trim((string)($senderUser['_name'] ?? ''))
?: trim((string)($senderUser['_mobile'] ?? ''))
?: $from;
$senderName = $senderContactAlias
?: $senderAlias
?: $senderRawName;
$senderRole = nativeGroupRoleFromType($senderMember['_type'] ?? 0);
$messageId = (string)$row['_mid'];
$timestamp = timestampMs((string)($row['_dt'] ?? ''), $messageId);
$contentType = (int)($row['_content_type'] ?? 0);
$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);
return [
'id' => $messageId,
'messageUid' => $messageId,
'conversationId' => 'group-' . $groupId,
'from' => $from,
'senderRole' => $senderRole,
'senderName' => $senderName,
'senderPortrait' => (string)($senderUser['_portrait'] ?? ''),
'senderProfile' => [
'uid' => $from,
'displayName' => $senderName,
'rawName' => $senderRawName,
'contactAlias' => $senderContactAlias,
'friendAlias' => $senderFriendAlias,
'remarkAlias' => $senderRemarkAlias,
'groupAlias' => $senderAlias,
'isContact' => (bool)($senderUser['_is_friend'] ?? false),
'mobile' => (string)($senderUser['_mobile'] ?? ''),
'address' => (string)($senderUser['_address'] ?? ''),
'portrait' => (string)($senderUser['_portrait'] ?? ''),
'role' => $senderRole,
],
'to' => $groupId,
'target' => $groupId,
'direction' => $direction,
'type' => $messageType,
'contentType' => $contentType,
'text' => attachmentDisplayText($text, $attachment),
'attachment' => $attachment,
'status' => $isRecalled && $direction === 'out' ? 'recalled' : 'sent',
'deliveryStatus' => $direction === 'out' && !$isRecalled ? 'sent' : '',
'recalled' => $isRecalled,
'recallStatus' => $isRecalled ? '已撤回' : '',
'editedAt' => 0,
'timestamp' => $timestamp,
'activityTimestamp' => $timestamp,
'displayTimestamp' => $timestamp,
'conversationType' => 'group',
'raw' => [
'native' => true,
'groupName' => (string)($group['_name'] ?? ''),
],
];
}
function loadWebGroupMessages(PDO $appDb, string $userId, string $groupId, int $limit, bool $markRead): array
{
ensureWebImAppTables();
@@ -557,6 +982,81 @@ function loadWebGroupMessages(PDO $appDb, string $userId, string $groupId, int $
return $messages;
}
function loadNativeGroupMessages(PDO $db, string $userId, string $groupId, int $limit, bool $markRead): array
{
$role = nativeGroupRole($db, $userId, $groupId);
if ($role === '') {
return [];
}
$groupStatement = $db->prepare('select * from `t_group` where `_gid` = ? and `_deleted` = 0 limit 1');
$groupStatement->execute([$groupId]);
$group = $groupStatement->fetch();
if (!is_array($group)) {
return [];
}
$table = imUserMessagesTable($userId);
$scanLimit = min(max($limit * 4, $limit), 400);
$statement = $db->prepare(
'select `_mid`, `_dt` from `' . $table . '`'
. ' where `_uid` = ? and `_type` = 1 and `_line` = 0 and `_target` = ?'
. ' order by `_mid` desc limit ' . $scanLimit
);
$statement->execute([$userId, $groupId]);
$userRows = $statement->fetchAll();
$messageRows = fetchMessageRows($db, array_column($userRows, '_mid'));
$globalRows = loadNativeGroupRowsFromGlobal($db, [$groupId], $scanLimit);
foreach ($globalRows as $row) {
$messageId = (string)$row['_mid'];
if ($messageId !== '') {
$messageRows[$messageId] = $row;
$userRows[] = [
'_mid' => $messageId,
'_dt' => (string)($row['_dt'] ?? ''),
];
}
}
usort($userRows, static fn($left, $right) => strcmp((string)$right['_mid'], (string)$left['_mid']));
$attachmentMap = fetchAttachmentMap(imAppDb(), array_column($userRows, '_mid'));
$messages = [];
$seenMessageIds = [];
foreach ($userRows as $userRow) {
$messageId = (string)$userRow['_mid'];
if (isset($seenMessageIds[$messageId]) || !isset($messageRows[$messageId])) {
continue;
}
$seenMessageIds[$messageId] = true;
if (!shouldDisplayMessageForUser($messageRows[$messageId], $userId)) {
continue;
}
$messages[] = $messageRows[$messageId];
if (count($messages) >= $limit) {
break;
}
}
$messages = array_reverse($messages);
$senderIds = array_values(array_unique(array_map(static fn(array $row): string => (string)$row['_from'], $messages)));
$users = fetchUserInfoMap($db, $senderIds, $userId);
$memberMap = fetchNativeGroupMemberMap($db, $groupId, $senderIds);
$readTimestamp = 0;
$formatted = [];
foreach ($messages as $row) {
$messageId = (string)$row['_mid'];
$message = formatNativeGroupMessage($row, $userId, $group, $attachmentMap[$messageId] ?? null, $users, $memberMap);
$readTimestamp = max($readTimestamp, (int)$message['activityTimestamp']);
$formatted[] = $message;
}
if ($markRead) {
markNativeGroupRead($db, $userId, $groupId, $readTimestamp);
}
return $formatted;
}
function loadWebGroupConversations(PDO $appDb, string $userId, int $limit): array
{
ensureWebImAppTables();
@@ -619,7 +1119,7 @@ function loadWebGroupConversations(PDO $appDb, string $userId, int $limit): arra
? (messagePreviewText([
'text' => attachmentDisplayText((string)$lastMessage['text'], $lastAttachment),
'attachment' => $lastAttachment,
]) ?: (string)$lastMessage['text'])
]))
: ($isChannel ? '公告群' : ($memberCount > 0 ? $memberCount . ' 位成员' : '群组'));
$updatedAt = $lastMessage
? max((int)$lastMessage['created_at_ms'], (int)($lastMessage['edited_at_ms'] ?? 0))
@@ -649,6 +1149,152 @@ function loadWebGroupConversations(PDO $appDb, string $userId, int $limit): arra
return $conversations;
}
function loadNativeGroupConversations(PDO $db, string $userId, int $limit): array
{
$statement = $db->prepare(
'select g.*, m.`_type` as `member_type`, m.`_alias` as `member_alias`'
. ' from `t_group_member` m'
. ' join `t_group` g on g.`_gid` = m.`_gid` and g.`_deleted` = 0'
. ' where m.`_mid` = ?'
. ' order by greatest(g.`_dt`, m.`_dt`) desc limit ' . min(max($limit, 50), 100)
);
$statement->execute([$userId]);
$groups = $statement->fetchAll();
if (!$groups) {
return [];
}
$groupIds = array_values(array_unique(array_map(static fn(array $group): string => (string)$group['_gid'], $groups)));
$table = imUserMessagesTable($userId);
$scanLimit = min(max($limit * 20, 200), 1000);
$messageStatement = $db->prepare(
'select `_mid`, `_target`, `_dt` from `' . $table . '`'
. ' where `_uid` = ? and `_type` = 1 and `_line` = 0'
. ' and `_target` in (' . placeholders($groupIds) . ')'
. ' order by `_mid` desc limit ' . $scanLimit
);
$messageStatement->execute(array_merge([$userId], $groupIds));
$scanRows = $messageStatement->fetchAll();
$messageRows = fetchMessageRows($db, array_column($scanRows, '_mid'));
$globalRows = loadNativeGroupRowsFromGlobal($db, $groupIds, $scanLimit);
foreach ($globalRows as $row) {
$messageId = (string)$row['_mid'];
if ($messageId !== '') {
$messageRows[$messageId] = $row;
$scanRows[] = [
'_mid' => $messageId,
'_target' => (string)($row['_target'] ?? ''),
'_dt' => (string)($row['_dt'] ?? ''),
];
}
}
usort($scanRows, static fn($left, $right) => strcmp((string)$right['_mid'], (string)$left['_mid']));
$attachmentMap = fetchAttachmentMap(imAppDb(), array_column($scanRows, '_mid'));
$readAtByGroup = loadNativeGroupReadStateMap($db, $userId, $groupIds);
$latestByGroup = [];
$unreadByGroup = [];
$seenMessageIds = [];
foreach ($scanRows as $row) {
$messageId = (string)$row['_mid'];
if (isset($seenMessageIds[$messageId])) {
continue;
}
$seenMessageIds[$messageId] = true;
$groupId = (string)$row['_target'];
$message = $messageRows[$messageId] ?? null;
if ($groupId === '' || !$message || !shouldDisplayMessageForUser($message, $userId)) {
continue;
}
$activityTimestamp = timestampMs((string)($message['_dt'] ?? ''), $messageId);
if (!isset($latestByGroup[$groupId]) || $activityTimestamp > (int)($latestByGroup[$groupId]['_activity_at'] ?? 0)) {
$row['_activity_at'] = $activityTimestamp;
$latestByGroup[$groupId] = $row;
}
if ((string)$message['_from'] !== $userId && !isRecallMessage($message)) {
if ($activityTimestamp > (int)($readAtByGroup[$groupId] ?? 0)) {
$unreadByGroup[$groupId] = (int)($unreadByGroup[$groupId] ?? 0) + 1;
}
}
}
$groupsById = [];
foreach ($groups as $group) {
$groupsById[(string)$group['_gid']] = $group;
}
$senderIds = [];
foreach ($latestByGroup as $row) {
$message = $messageRows[(string)$row['_mid']] ?? null;
if ($message) {
$senderIds[] = (string)$message['_from'];
}
}
$users = fetchUserInfoMap($db, $senderIds, $userId);
$conversations = [];
foreach ($groupsById as $groupId => $group) {
$latestRow = $latestByGroup[$groupId] ?? null;
$messageId = $latestRow ? (string)$latestRow['_mid'] : '';
$message = $messageId !== '' && isset($messageRows[$messageId])
? formatNativeGroupMessage(
$messageRows[$messageId],
$userId,
$group,
$attachmentMap[$messageId] ?? null,
$users,
fetchNativeGroupMemberMap($db, $groupId, [(string)$messageRows[$messageId]['_from']])
)
: null;
$title = (string)($group['_name'] ?? '') ?: $groupId;
$updatedAt = $message ? (int)$message['activityTimestamp'] : (int)($group['_dt'] ?? 0);
$conversations[] = [
'id' => 'group-' . $groupId,
'type' => 'group',
'target' => $groupId,
'title' => $title,
'subtitle' => $message
? (messagePreviewText($message) ?: nativeMessageFallbackText((int)($message['contentType'] ?? 0), false))
: (((int)($group['_member_count'] ?? 0) > 0) ? (int)$group['_member_count'] . ' 位成员' : '群组'),
'unread' => (int)($unreadByGroup[$groupId] ?? 0),
'portrait' => (string)($group['_portrait'] ?? ''),
'avatarText' => mb_strtoupper(mb_substr($title, 0, 1, 'UTF-8'), 'UTF-8'),
'updatedAt' => $updatedAt,
'role' => nativeGroupRoleFromType($group['member_type'] ?? 0),
'memberCount' => (int)($group['_member_count'] ?? 0),
'raw' => [
'type' => 'group',
'target' => $groupId,
'line' => 0,
'native' => true,
'role' => nativeGroupRoleFromType($group['member_type'] ?? 0),
],
];
}
return $conversations;
}
function mergeConversationsById(array $conversations, array $extraConversations): array
{
$merged = [];
foreach (array_merge($conversations, $extraConversations) as $conversation) {
$id = (string)($conversation['id'] ?? '');
if ($id === '') {
continue;
}
if (!isset($merged[$id])) {
$merged[$id] = $conversation;
continue;
}
if ((int)($conversation['updatedAt'] ?? 0) > (int)($merged[$id]['updatedAt'] ?? 0)) {
$merged[$id] = array_merge($merged[$id], $conversation);
}
}
return array_values($merged);
}
function isRecallMessage(array $row): bool
{
return (int)($row['_content_type'] ?? 0) === 80;
@@ -679,8 +1325,9 @@ function formatMessage(
$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 = $text !== '' ? $text : ($isRecalled || $attachment ? '' : '[暂不支持的消息类型]');
$messageText = nativeDisplayText($text, $contentType, $attachment !== null, $isRecalled);
$messageText = attachmentDisplayText($messageText, $attachment);
$editedAt = (int)($editState['editedAt'] ?? 0);
$activityTimestamp = messageActivityTimestamp($timestamp, $editState);
@@ -854,10 +1501,16 @@ function loadRecentConversations(PDO $db, string $userId, int $limit): array
}
try {
$conversations = array_merge($conversations, loadWebGroupConversations(imAppDb(), $userId, $limit));
} catch (Throwable) {
$conversations = mergeConversationsById($conversations, loadWebGroupConversations(imAppDb(), $userId, $limit));
} catch (Throwable $error) {
error_log('web group conversation sync failed: ' . $error->getMessage());
// Keep single-chat sync available if appdata group metadata is temporarily unavailable.
}
try {
$conversations = mergeConversationsById($conversations, loadNativeGroupConversations($db, $userId, $limit));
} catch (Throwable $error) {
error_log('native group conversation sync failed: ' . $error->getMessage());
}
usort($conversations, static fn($a, $b) => $b['updatedAt'] <=> $a['updatedAt']);
@@ -881,12 +1534,27 @@ try {
markUserDelivered($db, $userId, nowMs());
if ($target !== '') {
$targetId = resolveUserId($db, $target);
if ($conversationType === 'group' || isWebGroupTarget(imAppDb(), $target)) {
if ($conversationType === 'group') {
if (isWebGroupTarget(imAppDb(), $target)) {
respond(0, 'success', [
'messages' => loadWebGroupMessages(imAppDb(), $userId, $target, $limit, $markRead),
]);
}
if (isNativeGroupTarget($db, $target)) {
respond(0, 'success', [
'messages' => loadNativeGroupMessages($db, $userId, $target, $limit, $markRead),
]);
}
respond(0, 'success', [
'messages' => [],
]);
}
if (isWebGroupTarget(imAppDb(), $target)) {
respond(0, 'success', [
'messages' => loadWebGroupMessages(imAppDb(), $userId, $target, $limit, $markRead),
]);
}
$targetId = resolveUserId($db, $target);
respond(0, 'success', [
'messages' => loadConversationMessages($db, $userId, $targetId, $limit, $markRead),
]);
+219 -55
View File
@@ -6,12 +6,21 @@ header('Cache-Control: no-store');
require __DIR__ . '/im_web_bootstrap.php';
const WEB_MEDIA_ROOT = '/opt/im-server/media';
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_TYPE_IMAGE = 1;
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
{
@@ -72,6 +81,33 @@ 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));
@@ -162,7 +198,106 @@ function mediaPublicBaseUrl(): string
return $scheme . '://' . $host . ':' . $port;
}
function saveMessageAttachmentFile(array $file, string $attachmentType): array
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
{
if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
throw new RuntimeException('文件上传失败');
@@ -172,10 +307,6 @@ function saveMessageAttachmentFile(array $file, string $attachmentType): array
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('文件上传失败');
@@ -185,6 +316,17 @@ function saveMessageAttachmentFile(array $file, string $attachmentType): array
$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;
@@ -249,7 +391,7 @@ function storeMessageAttachment(
]);
}
function attachmentFromRequest(string $messageType): ?array
function attachmentFromRequest(string $messageType, string $sender): ?array
{
if (!in_array($messageType, ['image', 'file'], true)) {
return null;
@@ -260,7 +402,61 @@ function attachmentFromRequest(string $messageType): ?array
respond(400, '缺少上传文件');
}
return saveMessageAttachmentFile($attachmentFile, $messageType);
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,
];
}
$contentTypeHeader = (string)($_SERVER['CONTENT_TYPE'] ?? '');
@@ -292,7 +488,17 @@ try {
$memberStatement->execute([$target, $sender]);
$group = $memberStatement->fetch();
if (!$group) {
respond(403, '你不在该群组中');
$nativeGroup = fetchNativeGroupForSender(imDb(), $sender, $target);
if (!$nativeGroup) {
respond(403, '你不在该群组中');
}
$attachment = attachmentFromRequest($messageType, $sender);
$nativeResult = sendNativeGroupMessage($sender, $target, $text, $attachment);
respond(0, 'success', [
...$nativeResult,
'senderRole' => nativeGroupRoleFromType($nativeGroup['member_type'] ?? 0),
'native' => true,
]);
}
$category = (string)($group['category'] ?? 'group');
$role = (string)($group['role'] ?? 'member');
@@ -304,7 +510,7 @@ try {
if ($category !== 'channel' && isGroupMutedForSender($appDb, $target, $role, $now)) {
respond(403, '当前群组处于禁言时段');
}
$attachment = attachmentFromRequest($messageType);
$attachment = attachmentFromRequest($messageType, $sender);
$messageUid = webImMessageUid();
$insert = $appDb->prepare(
'insert into `t_web_group_messages`'
@@ -320,27 +526,6 @@ try {
$nativeError = '';
try {
$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);
}
requireImSuccess(imAdminPost('/admin/message/send', [
'sender' => $sender,
'conv' => [
@@ -348,7 +533,7 @@ try {
'target' => $target,
'line' => 0,
],
'payload' => $payloadBody,
'payload' => messagePayloadBody($text, $attachment),
'userMessage' => true,
]), '原生群消息发送失败');
} catch (Throwable $error) {
@@ -364,28 +549,7 @@ try {
]);
}
$attachment = attachmentFromRequest($messageType);
$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);
}
$attachment = attachmentFromRequest($messageType, $sender);
$result = requireImSuccess(imAdminPost('/admin/message/send', [
'sender' => $sender,
@@ -394,7 +558,7 @@ try {
'target' => $target,
'line' => 0,
],
'payload' => $payloadBody,
'payload' => messagePayloadBody($text, $attachment),
'userMessage' => true,
]), '发送失败');