Helpers.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. <?php
  2. namespace App\Utils;
  3. use App\Models\CouponLog;
  4. use App\Models\Marketing;
  5. use App\Models\NotificationLog;
  6. use App\Models\SsConfig;
  7. use App\Models\User;
  8. use App\Models\UserCreditLog;
  9. use App\Models\UserDataModifyLog;
  10. use App\Models\UserLoginLog;
  11. use App\Models\UserSubscribe;
  12. use Log;
  13. use RuntimeException;
  14. use Str;
  15. class Helpers
  16. {
  17. private static array $denyPorts = [1068, 1109, 1434, 3127, 3128, 3129, 3130, 3332, 4444, 5554, 6669, 8080, 8081, 8082, 8181, 8282, 9996, 17185, 24554, 35601, 60177, 60179]; // 不生成的端口
  18. public static function makeSubscribeCode(): string
  19. { // 生成用户的订阅码
  20. do {
  21. $code = Str::random();
  22. } while (UserSubscribe::whereCode($code)->exists());
  23. return $code;
  24. }
  25. /**
  26. * 添加用户.
  27. *
  28. * @param string $username 用户名
  29. * @param string $password 用户密码
  30. * @param int $transfer_enable 可用流量
  31. * @param int $date 可使用天数
  32. * @param int|null $inviter_id 邀请人
  33. * @param string|null $nickname 昵称
  34. * @param int $status 状态:-1-禁用、0-未激活、1-正常
  35. */
  36. public static function addUser(string $username, string $password, int $transfer_enable = 0, int $date = 0, ?int $inviter_id = null, ?string $nickname = null, int $status = 0): User
  37. {
  38. return User::create([
  39. 'nickname' => $nickname ?? $username,
  40. 'username' => $username,
  41. 'password' => $password,
  42. 'port' => self::getPort(), // 生成一个可用端口
  43. 'passwd' => Str::random(),
  44. 'vmess_id' => Str::uuid(),
  45. 'method' => self::getDefaultMethod(),
  46. 'protocol' => self::getDefaultProtocol(),
  47. 'obfs' => self::getDefaultObfs(),
  48. 'transfer_enable' => $transfer_enable,
  49. 'expired_at' => now()->addDays($date)->toDateString(),
  50. 'user_group_id' => null,
  51. 'reg_ip' => IP::getClientIp(),
  52. 'inviter_id' => $inviter_id,
  53. 'status' => $status,
  54. ]);
  55. }
  56. public static function getPort(): int
  57. { // 获取一个有效端口
  58. $minPort = (int) sysConfig('min_port');
  59. $maxPort = (int) sysConfig('max_port');
  60. $isRandPort = sysConfig('is_rand_port');
  61. $occupiedPorts = array_merge(User::where('port', '!=', 0)->pluck('port')->toArray(), self::$denyPorts);
  62. $totalPorts = $maxPort - $minPort + 1;
  63. $availablePortsCount = $totalPorts - count($occupiedPorts);
  64. if ($availablePortsCount === 0) {
  65. throw new RuntimeException('No available port found.');
  66. }
  67. if ($isRandPort) {
  68. $attempts = 0;
  69. do {
  70. $port = random_int($minPort, $maxPort);
  71. $attempts++;
  72. // 防止无限循环
  73. if ($attempts > 100) {
  74. throw new RuntimeException('Unable to find available port after 100 attempts.');
  75. }
  76. } while (in_array($port, $occupiedPorts, true));
  77. } else {
  78. $port = $minPort;
  79. while (in_array($port, $occupiedPorts, true)) {
  80. $port++;
  81. if ($port > $maxPort) {
  82. throw new RuntimeException('No available port found.');
  83. }
  84. }
  85. }
  86. return $port;
  87. }
  88. public static function getDefaultMethod(): string
  89. { // 获取默认加密方式
  90. static $method = null;
  91. if ($method === null) {
  92. $config = SsConfig::default()->type(1)->first();
  93. $method = $config->name ?? 'aes-256-cfb';
  94. }
  95. return $method;
  96. }
  97. public static function getDefaultProtocol(): string
  98. { // 获取默认协议
  99. static $protocol = null;
  100. if ($protocol === null) {
  101. $config = SsConfig::default()->type(2)->first();
  102. $protocol = $config->name ?? 'origin';
  103. }
  104. return $protocol;
  105. }
  106. public static function getDefaultObfs(): string
  107. { // 获取默认混淆
  108. static $obfs = null;
  109. if ($obfs === null) {
  110. $config = SsConfig::default()->type(3)->first();
  111. $obfs = $config->name ?? 'plain';
  112. }
  113. return $obfs;
  114. }
  115. /**
  116. * 添加通知推送日志.
  117. *
  118. * @param string $title 标题
  119. * @param string $content 内容
  120. * @param int $type 发送类型
  121. * @param int $status 投递状态
  122. * @param string|null $error 投递失败时记录的异常信息
  123. * @param string|null $msgId 对公查询ID
  124. * @param string $address 收信方
  125. */
  126. public static function addNotificationLog(string $title, string $content, int $type, int $status = 1, ?string $error = null, ?string $msgId = null, string $address = 'admin'): int
  127. {
  128. return NotificationLog::create(['type' => $type, 'msg_id' => $msgId, 'address' => $address, 'title' => $title, 'content' => $content, 'status' => $status, 'error' => $error])->id;
  129. }
  130. /**
  131. * 添加优惠券操作日志.
  132. *
  133. * @param string $description 备注
  134. * @param int $couponId 优惠券ID
  135. * @param int|null $goodsId 商品ID
  136. * @param int|null $orderId 订单ID
  137. */
  138. public static function addCouponLog(string $description, int $couponId, ?int $goodsId = null, ?int $orderId = null): bool
  139. {
  140. return CouponLog::create(['coupon_id' => $couponId, 'goods_id' => $goodsId, 'order_id' => $orderId, 'description' => $description])->wasRecentlyCreated;
  141. }
  142. /**
  143. * 记录余额操作日志.
  144. *
  145. * @param int $userId 用户ID
  146. * @param int|null $orderId 订单ID
  147. * @param float|int $before 记录前余额
  148. * @param float|int $after 记录后余额
  149. * @param float|int $amount 发生金额
  150. * @param string|null $description 描述
  151. */
  152. public static function addUserCreditLog(int $userId, ?int $orderId, float|int $before, float|int $after, float|int $amount, ?string $description = null): bool
  153. {
  154. return UserCreditLog::create(['user_id' => $userId, 'order_id' => $orderId, 'before' => $before, 'after' => $after, 'amount' => $amount, 'description' => $description, 'created_at' => now()])->wasRecentlyCreated;
  155. }
  156. /**
  157. * 记录流量变动日志.
  158. *
  159. * @param int $userId 用户ID
  160. * @param int $before 记录前的值
  161. * @param int $after 记录后的值
  162. * @param string|null $description 描述
  163. * @param int|null $orderId 订单ID
  164. */
  165. public static function addUserTrafficModifyLog(int $userId, int $before, int $after, ?string $description = null, ?int $orderId = null): bool
  166. {
  167. return UserDataModifyLog::create(['user_id' => $userId, 'order_id' => $orderId, 'before' => $before, 'after' => $after, 'description' => $description])->wasRecentlyCreated;
  168. }
  169. /**
  170. * 推销信息推送
  171. *
  172. * @param string $receiver 收件人
  173. * @param int $type 渠道类型
  174. * @param string $title 标题
  175. * @param string $content 内容
  176. * @param int $status 状态
  177. * @param string|null $error 报错
  178. */
  179. public static function addMarketing(string $receiver, int $type, string $title, string $content, int $status = 1, ?string $error = null): bool
  180. {
  181. return Marketing::create(['type' => $type, 'receiver' => $receiver, 'title' => $title, 'content' => $content, 'error' => $error, 'status' => $status])->wasRecentlyCreated;
  182. }
  183. /**
  184. * 用户登录后操作.
  185. *
  186. * @param User $user 用户ID
  187. * @param string $ip IP地址
  188. */
  189. public static function userLoginAction(User $user, string $ip): void
  190. {
  191. $ipLocation = IP::getIPInfo($ip);
  192. $logData = [
  193. 'user_id' => $user->id,
  194. 'ip' => $ip,
  195. 'country' => $ipLocation['country'] ?? '',
  196. 'province' => $ipLocation['region'] ?? '',
  197. 'city' => $ipLocation['city'] ?? '',
  198. 'county' => '', // 未使用的字段
  199. 'isp' => $ipLocation['isp'] ?? '',
  200. 'area' => $ipLocation['area'] ?? '',
  201. ];
  202. // 记录错误日志仅在 IP 信息无效时
  203. if (! $ipLocation) {
  204. Log::warning(trans('errors.get_ip').':'.$ip);
  205. }
  206. // 批量插入日志记录并更新用户登录时间
  207. UserLoginLog::create($logData);
  208. $user->update(['last_login' => time()]);
  209. }
  210. public static function getPriceTag(int|float $amount): string
  211. { // Get price with money symbol in the user's preferred currency.
  212. $currentCurrency = session('currency');
  213. $standard = sysConfig('standard_currency');
  214. $currencyLib = array_column(config('common.currency'), 'symbol', 'code');
  215. if (! empty($currentCurrency) && isset($currencyLib[$currentCurrency]) && $currentCurrency !== $standard) {
  216. $convert = CurrencyExchange::convert($currentCurrency, $amount);
  217. if ($convert !== false) {
  218. return $currencyLib[$currentCurrency].$convert;
  219. }
  220. }
  221. return $currencyLib[$standard].$amount;
  222. }
  223. }