270 lines
9.4 KiB
PHP
270 lines
9.4 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 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']);
|
|
}
|
|
|
|
/**
|
|
* 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,
|
|
]);
|
|
}
|
|
|
|
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();
|
|
$data = collect($paginator->items())->map(function ($row) use ($portal) {
|
|
/** @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),
|
|
'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'))
|
|
);
|
|
}
|
|
|
|
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);
|
|
}
|
|
}
|
|
}
|