SubscribeLog.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Models;
  4. use App\Services\Notification;
  5. use App\Utils\Tools;
  6. use Exception;
  7. use GuzzleHttp\Exception\GuzzleException;
  8. use Illuminate\Database\Query\Builder;
  9. use Psr\Http\Client\ClientExceptionInterface;
  10. use Telegram\Bot\Exceptions\TelegramSDKException;
  11. use function time;
  12. /**
  13. * @property int $id 记录ID
  14. * @property int $user_id 用户ID
  15. * @property string $type 获取的订阅类型
  16. * @property string $request_ip 请求IP
  17. * @property string $request_user_agent 请求UA
  18. * @property int $request_time 请求时间
  19. *
  20. * @mixin Builder
  21. */
  22. final class SubscribeLog extends Model
  23. {
  24. protected $connection = 'default';
  25. protected $table = 'subscribe_log';
  26. /**
  27. * 用户
  28. */
  29. public function user(): ?User
  30. {
  31. return (new User())->find($this->user_id);
  32. }
  33. /**
  34. * Ip 地理位置
  35. */
  36. public function getLocationAttribute(): string
  37. {
  38. try {
  39. return Tools::getIpLocation($this->request_ip);
  40. } catch (Exception) {
  41. return '未知';
  42. }
  43. }
  44. /**
  45. * 记录订阅日志
  46. */
  47. public function add(User $user, string $type, string $ua): void
  48. {
  49. $this->user_id = $user->id;
  50. $this->type = $type;
  51. $this->request_ip = $_SERVER['REMOTE_ADDR'];
  52. $this->request_user_agent = $ua;
  53. $this->request_time = time();
  54. if (Config::obtain('notify_new_subscribe') &&
  55. (new SubscribeLog())->where('user_id', $this->user_id)
  56. ->where('request_ip', 'like', '%' . $this->request_ip . '%')
  57. ->count() === 0
  58. ) {
  59. try {
  60. Notification::notifyUser(
  61. $user,
  62. $_ENV['appName'] . '-新订阅通知',
  63. '你的账号于 ' . date('Y-m-d H:i:s') . ' 通过 ' . $this->request_ip . ' 地址订阅了新的节点',
  64. );
  65. } catch (GuzzleException|ClientExceptionInterface|TelegramSDKException $e) {
  66. echo $e->getMessage();
  67. }
  68. }
  69. $this->save();
  70. }
  71. }