OnlineLogController.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Controllers\Admin;
  4. use App\Controllers\BaseController;
  5. use App\Models\OnlineLog;
  6. use App\Utils\Tools;
  7. use Exception;
  8. use MaxMind\Db\Reader\InvalidDatabaseException;
  9. use Psr\Http\Message\ResponseInterface;
  10. use Slim\Http\Response;
  11. use Slim\Http\ServerRequest;
  12. use function time;
  13. final class OnlineLogController extends BaseController
  14. {
  15. private static array $details =
  16. [
  17. 'field' => [
  18. 'id' => '事件ID',
  19. 'user_id' => '用户ID',
  20. 'user_name' => '用户名',
  21. 'node_id' => '节点ID',
  22. 'node_name' => '节点名',
  23. 'ip' => 'IP',
  24. 'location' => 'IP归属地',
  25. 'first_time' => '首次连接',
  26. 'last_time' => '最后连接',
  27. ],
  28. ];
  29. /**
  30. * 后台在线 IP 页面
  31. *
  32. * @throws Exception
  33. */
  34. public function index(ServerRequest $request, Response $response, array $args): Response|ResponseInterface
  35. {
  36. return $response->write(
  37. $this->view()
  38. ->assign('details', self::$details)
  39. ->fetch('admin/log/online.tpl')
  40. );
  41. }
  42. /**
  43. * 后台在线 IP 页面 AJAX
  44. *
  45. * @throws InvalidDatabaseException
  46. */
  47. public function ajax(ServerRequest $request, Response $response, array $args): Response|ResponseInterface
  48. {
  49. $length = $request->getParam('length');
  50. $page = $request->getParam('start') / $length + 1;
  51. $draw = $request->getParam('draw');
  52. $onlines = OnlineLog::where('last_time', '>', time() - 90)->orderByDesc('last_time')->paginate($length, '*', '', $page);
  53. $total = OnlineLog::where('last_time', '>', time() - 90)->count();
  54. foreach ($onlines as $online) {
  55. $online->user_name = $online->userName();
  56. $online->node_name = $online->nodeName();
  57. $online->ip = $online->ip();
  58. $online->location = Tools::getIpLocation($online->ip);
  59. $online->first_time = Tools::toDateTime($online->first_time);
  60. $online->last_time = Tools::toDateTime($online->last_time);
  61. }
  62. return $response->withJson([
  63. 'draw' => $draw,
  64. 'recordsTotal' => $total,
  65. 'recordsFiltered' => $total,
  66. 'onlines' => $onlines,
  67. ]);
  68. }
  69. }