Files
zyt/server/app/common/service/assistantservice/WecomArchiveHttp.php
T
2026-11-26 15:46:20 +08:00

130 lines
6.8 KiB
PHP

<?php
declare(strict_types=1);
namespace app\common\service\assistantservice;
use RuntimeException;
/** 线上企微归档。本地库不存在时,工作台和预警都走这组令牌接口。 */
final class WecomArchiveHttp
{
public static function configured(): bool
{
return WecomArchiveScope::tenant() !== '' && self::base() !== '' && self::token() !== '';
}
/** @return list<array{external_id:string,name:string,conversations:int}> */
public static function accounts(): array
{
$json = self::get('/api/v2/archive/staff-feed/accounts');
$accounts = [];
foreach (is_array($json['accounts'] ?? null) ? $json['accounts'] : [] as $row) {
if (!is_array($row)) { continue; }
$accounts[] = ['external_id' => (string) ($row['external_id'] ?? ''), 'name' => trim((string) ($row['name'] ?? '')),
'conversations' => (int) ($row['conversations'] ?? 0)];
}
return $accounts;
}
/** @return list<array{id:string,name:string,conversation_type:string,last_message_at:string,message_count:int,preview:string}> */
public static function conversations(string $externalId): array
{
if ($externalId === '') { return []; }
$json = self::get('/api/v2/archive/staff-feed/conversations', ['account' => $externalId]);
$items = [];
foreach (is_array($json['conversations'] ?? null) ? $json['conversations'] : [] as $row) {
if (!is_array($row)) { continue; }
$items[] = ['id' => (string) ($row['id'] ?? ''), 'name' => trim((string) ($row['name'] ?? '')),
'conversation_type' => (string) ($row['conversation_type'] ?? ''), 'last_message_at' => (string) ($row['last_message_at'] ?? ''),
'message_count' => (int) ($row['message_count'] ?? 0), 'preview' => trim((string) ($row['preview'] ?? ''))];
}
return $items;
}
/** @return array{account:string,messages:list<array{id:string,sent_at:string,direction:string,message_type:string,sender_name:string,content:string}>} */
public static function messages(string $conversationId): array
{
if ($conversationId === '') { return ['account' => '', 'messages' => []]; }
$json = self::get('/api/v2/archive/staff-feed/messages', ['conversation_id' => $conversationId]);
$messages = [];
foreach (is_array($json['messages'] ?? null) ? $json['messages'] : [] as $row) {
if (!is_array($row)) { continue; }
$messages[] = ['id' => (string) ($row['id'] ?? ''), 'sent_at' => (string) ($row['sent_at'] ?? ''),
'direction' => (string) ($row['direction'] ?? ''), 'message_type' => (string) ($row['message_type'] ?? ''),
'sender_name' => trim((string) ($row['sender_name'] ?? '')), 'content' => trim((string) ($row['content'] ?? ''))];
}
return ['account' => (string) ($json['account'] ?? ''), 'messages' => $messages];
}
/** @return array{configured:bool,items:array<int,array<string,mixed>>,next_cursor:string,has_more:bool} */
public static function page(string $cursor, int $limit): array
{
$empty = ['configured' => false, 'items' => [], 'next_cursor' => $cursor, 'has_more' => false];
if (!self::configured()) { return $empty; }
$limit = max(1, min(200, $limit));
$json = self::get('/api/v2/archive/staff-feed/outbound', ['cursor' => $cursor, 'limit' => (string) $limit]);
$rows = is_array($json['items'] ?? null) ? $json['items'] : [];
return ['configured' => true, 'items' => WecomArchiveSqlite::identify($rows),
'next_cursor' => (string) ($json['next_cursor'] ?? $cursor), 'has_more' => (bool) ($json['has_more'] ?? false)];
}
/** @param array<string,string> $query @return array<string,mixed> */
private static function get(string $path, array $query = []): array
{
$base = self::base();
$token = self::token();
$tenant = WecomArchiveScope::tenant();
if ($tenant === '' || $base === '' || $token === '') { throw new RuntimeException('WECOM_ARCHIVE'); }
$url = $base . $path;
if ($query) { $url .= '?' . http_build_query($query); }
$handle = curl_init($url);
if ($handle === false) { throw new RuntimeException('WECOM_ARCHIVE'); }
$attestedTenants = [];
$inHeaders = false;
$readHeader = static function ($handle, string $line) use (&$attestedTenants, &$inHeaders): int {
// CONNECT 和 1xx 可先于最终响应,租户声明只认最后一组响应头。
if (preg_match('/\AHTTP\/\S+\s+\d{3}\b/i', $line)) {
$attestedTenants = [];
$inHeaders = true;
} elseif (rtrim($line, "\r\n") === '') {
$inHeaders = false;
} elseif (stripos($line, 'X-Archive-Tenant:') === 0) {
$attestedTenants[] = $inHeaders ? trim(substr($line, strlen('X-Archive-Tenant:')), " \t\r\n") : '';
}
return strlen($line);
};
$options = [CURLOPT_HEADERFUNCTION => $readHeader, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 15, CURLOPT_FOLLOWLOCATION => false,
CURLOPT_HTTPHEADER => ['Accept: application/json', 'X-Archive-Feed-Token: ' . $token, 'X-Archive-Tenant: ' . $tenant]];
if (parse_url($base, PHP_URL_SCHEME) === 'http') { $options[CURLOPT_PROXY] = ''; }
try {
if (!curl_setopt_array($handle, $options)) { throw new RuntimeException('WECOM_ARCHIVE'); }
$body = curl_exec($handle);
$code = (int) curl_getinfo($handle, CURLINFO_RESPONSE_CODE);
} finally { curl_close($handle); }
if ($code !== 200 || $attestedTenants !== [$tenant]) { throw new RuntimeException('WECOM_ARCHIVE'); }
$json = is_string($body) ? json_decode($body, true) : null;
if (!is_array($json)) { throw new RuntimeException('WECOM_ARCHIVE'); }
return $json;
}
private static function base(): string
{
$url = rtrim((string) config('assistant_service.wecom_archive_base_url', ''), '/');
if ($url === '' || str_contains($url, '\\') || preg_match('/[\x00-\x20\x7f]/', $url)) { return ''; }
$parts = parse_url($url);
if (!$parts || empty($parts['host']) || isset($parts['user']) || isset($parts['pass'])
|| isset($parts['query']) || isset($parts['fragment'])) { return ''; }
$scheme = $parts['scheme'] ?? '';
if ($scheme === 'https') { return $url; }
$local = in_array(strtolower($parts['host']), ['localhost', '127.0.0.1', '[::1]'], true);
return $scheme === 'http' && $local ? $url : '';
}
private static function token(): string
{
$token = (string) config('assistant_service.wecom_archive_token', '');
return preg_match('/\A[\x21-\x7e]{32,512}\z/D', $token) === 1 ? $token : '';
}
}