| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
- <?php
- namespace App\Http\Controllers\admin;
- use App\Constants\HttpStatus;
- use App\Http\Controllers\Controller;
- use App\Services\AdminRealtime\AdminRealtimeFeed;
- use App\Services\AdminRealtime\AdminRealtimeTicket;
- use App\Services\JwtService;
- use Exception;
- use Illuminate\Http\JsonResponse;
- /** 后台订单、用户列表实时推送,接入说明见 docs/admin-websocket.md */
- class Realtime extends Controller
- {
- /** 后台登录态换取推送网关连接票据 */
- public function ticket(JwtService $jwtService): JsonResponse
- {
- try {
- if (!config('admin_realtime.enabled')) {
- throw new Exception('实时推送未启用');
- }
- $token = str_replace('Bearer ', '', (string) request()->header('Authorization'));
- $session = $jwtService->validateToken($token);
- $result = AdminRealtimeTicket::issue((int) request()->user->id, isset($session->exp) ? (int) $session->exp : null);
- } catch (Exception $e) {
- return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
- }
- return $this->success($result);
- }
- /** 推送网关内部拉取事件,仅凭 X-Realtime-Secret 访问 */
- public function events(): JsonResponse
- {
- $secret = (string) config('admin_realtime.internal_secret');
- if ($secret === '' || !hash_equals($secret, (string) request()->header('X-Realtime-Secret'))) {
- return response()->json(['code' => HttpStatus::CUSTOM_ERROR, 'timestamp' => time(), 'msg' => 'forbidden', 'data' => []], 403);
- }
- if (!config('admin_realtime.enabled')) {
- return $this->error(HttpStatus::CUSTOM_ERROR, '实时推送未启用');
- }
- try {
- $gaps = array_filter(explode(',', (string) request()->input('gaps', '')), 'ctype_digit');
- $result = AdminRealtimeFeed::pull((int) request()->input('after', -1), $gaps);
- } catch (\Throwable $e) {
- return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
- }
- return $this->success($result);
- }
- }
|