AutoJob.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Components\Helpers;
  4. use App\Components\PushNotification;
  5. use App\Models\Config;
  6. use App\Models\Coupon;
  7. use App\Models\Invite;
  8. use App\Models\Node;
  9. use App\Models\NodeHeartBeat;
  10. use App\Models\Order;
  11. use App\Models\User;
  12. use App\Models\UserBanedLog;
  13. use App\Models\UserHourlyDataFlow;
  14. use App\Models\VerifyCode;
  15. use Cache;
  16. use Illuminate\Console\Command;
  17. use Log;
  18. class AutoJob extends Command
  19. {
  20. protected $signature = 'autoJob';
  21. protected $description = '自动化任务';
  22. /*
  23. * 警告:除非熟悉业务流程,否则不推荐更改以下执行顺序,随意变更以下顺序可能导致系统异常
  24. */
  25. public function handle(): void
  26. {
  27. $jobStartTime = microtime(true);
  28. // 关闭超时未支付本地订单
  29. $this->closeOrders();
  30. //过期验证码、优惠券、邀请码无效化
  31. $this->expireCode();
  32. // 封禁访问异常的订阅链接
  33. $this->blockSubscribe();
  34. // 封禁账号
  35. $this->blockUsers();
  36. // 解封被封禁的账号
  37. $this->unblockUsers();
  38. // 端口回收与分配
  39. if (sysConfig('auto_release_port')) {
  40. $this->dispatchPort();
  41. }
  42. // 检测节点是否离线
  43. $this->checkNodeStatus();
  44. // 检查维护模式
  45. if (sysConfig('maintenance_mode')) {
  46. Config::whereIn('name', ['maintenance_mode', 'maintenance_time'])->update(['value' => null]);
  47. }
  48. $jobEndTime = microtime(true);
  49. $jobUsedTime = round(($jobEndTime - $jobStartTime), 4);
  50. Log::info('---【'.$this->description.'】完成---,耗时'.$jobUsedTime.'秒');
  51. }
  52. // 关闭超时未支付本地订单
  53. private function closeOrders(): void
  54. {
  55. // 关闭超时未支付的本地支付订单
  56. foreach (Order::recentUnPay()->get() as $order) {
  57. // 关闭订单
  58. $order->update(['status' => -1]);
  59. }
  60. }
  61. // 注册验证码自动置无效 & 优惠券无效化
  62. private function expireCode(): void
  63. {
  64. // 注册验证码自动置无效
  65. VerifyCode::recentUnused()->update(['status' => 2]);
  66. // 优惠券到期 / 用尽的 自动置无效
  67. Coupon::whereStatus(0)
  68. ->where('end_time', '<=', time())
  69. ->orWhereIn('type', [1, 2])
  70. ->whereUsableTimes(0)
  71. ->update(['status' => 2]);
  72. // 邀请码到期自动置无效
  73. Invite::whereStatus(0)->where('dateline', '<=', date('Y-m-d H:i:s'))->update(['status' => 2]);
  74. }
  75. // 封禁访问异常的订阅链接
  76. private function blockSubscribe(): void
  77. {
  78. if (sysConfig('is_subscribe_ban')) {
  79. $subscribe_ban_times = sysConfig('subscribe_ban_times');
  80. foreach (User::activeUser()->with('subscribe')->get() as $user) {
  81. if (! $user->subscribe || $user->subscribe->status === 0) { // 无订阅链接 或 已封
  82. continue;
  83. }
  84. // 24小时内不同IP的请求次数
  85. $request_times = $user->subscribeLogs()
  86. ->where('request_time', '>=', date('Y-m-d H:i:s', strtotime('-1 days')))
  87. ->distinct()
  88. ->count('request_ip');
  89. if ($request_times >= $subscribe_ban_times) {
  90. $user->subscribe->update([
  91. 'status' => 0,
  92. 'ban_time' => strtotime('+'.sysConfig('traffic_ban_time').' minutes'),
  93. 'ban_desc' => '存在异常,自动封禁',
  94. ]);
  95. // 记录封禁日志
  96. $this->addUserBanLog($user->id, 0, '【完全封禁订阅】-订阅24小时内请求异常');
  97. }
  98. }
  99. }
  100. }
  101. /**
  102. * 添加用户封禁日志.
  103. *
  104. * @param int $userId 用户ID
  105. * @param int $time 封禁时长,单位分钟
  106. * @param string $description 封禁理由
  107. */
  108. private function addUserBanLog(int $userId, int $time, string $description): void
  109. {
  110. $log = new UserBanedLog();
  111. $log->user_id = $userId;
  112. $log->time = $time;
  113. $log->description = $description;
  114. $log->save();
  115. }
  116. // 封禁账号
  117. private function blockUsers(): void
  118. {
  119. // 禁用流量超限用户
  120. foreach (User::activeUser()->whereRaw('u + d >= transfer_enable')->get() as $user) {
  121. $user->update(['enable' => 0]);
  122. // 写入日志
  123. $this->addUserBanLog($user->id, 0, '【封禁代理】-流量已用完');
  124. }
  125. // 封禁1小时内流量异常账号
  126. if (sysConfig('is_traffic_ban')) {
  127. $trafficBanValue = sysConfig('traffic_ban_value');
  128. $trafficBanTime = sysConfig('traffic_ban_time');
  129. foreach (User::activeUser()->whereBanTime(null)->get() as $user) {
  130. // 对管理员豁免
  131. if ($user->is_admin) {
  132. continue;
  133. }
  134. // 多往前取5分钟,防止数据统计任务执行时间过长导致没有数据
  135. $totalTraffic = UserHourlyDataFlow::userRecentUsed($user->id)->sum('total');
  136. if ($totalTraffic >= $trafficBanValue * GB) {
  137. $user->update([
  138. 'enable' => 0,
  139. 'ban_time' => strtotime('+'.$trafficBanTime.' minutes'),
  140. ]);
  141. // 写入日志
  142. $this->addUserBanLog($user->id, $trafficBanTime, '【临时封禁代理】-1小时内流量异常');
  143. }
  144. }
  145. }
  146. }
  147. // 解封被临时封禁的账号
  148. private function unblockUsers(): void
  149. {
  150. // 解封被临时封禁的账号
  151. $userList = User::whereEnable(0)->where('status', '>=', 0)->whereNotNull('ban_time')->get();
  152. foreach ($userList as $user) {
  153. if ($user->ban_time < time()) {
  154. $user->update(['enable' => 1, 'ban_time' => null]);
  155. // 写入操作日志
  156. $this->addUserBanLog($user->id, 0, '【自动解封】-临时封禁到期');
  157. }
  158. }
  159. // 可用流量大于已用流量也解封(比如:邀请返利自动加了流量)
  160. $userList = User::whereEnable(0)
  161. ->where('status', '>=', 0)
  162. ->whereBanTime(null)
  163. ->where('expired_at', '>=', date('Y-m-d'))
  164. ->whereRaw('u + d < transfer_enable')
  165. ->get();
  166. foreach ($userList as $user) {
  167. $user->update(['enable' => 1]);
  168. // 写入操作日志
  169. $this->addUserBanLog($user->id, 0, '【自动解封】-有流量解封');
  170. }
  171. }
  172. // 端口回收与分配
  173. private function dispatchPort(): void
  174. {
  175. // 自动分配端口
  176. foreach (User::activeUser()->wherePort(0)->get() as $user) {
  177. $user->update(['port' => Helpers::getPort()]);
  178. }
  179. // 被封禁 / 过期一个月 的账号自动释放端口
  180. User::where('port', '<>', 0)
  181. ->whereStatus(-1)
  182. ->orWhere('expired_at', '<=', date('Y-m-d', strtotime('-1 months')))
  183. ->update(['port' => 0]);
  184. }
  185. // 检测节点是否离线
  186. private function checkNodeStatus(): void
  187. {
  188. if (sysConfig('is_node_offline')) {
  189. $offlineCheckTimes = sysConfig('offline_check_times');
  190. $onlineNode = NodeHeartBeat::recently()->distinct()->pluck('node_id')->toArray();
  191. foreach (Node::whereIsRelay(0)->whereStatus(1)->get() as $node) {
  192. // 10分钟内无节点负载信息则认为是后端炸了
  193. $nodeTTL = ! in_array($node->id, $onlineNode, true);
  194. if ($nodeTTL && $offlineCheckTimes) {
  195. // 已通知次数
  196. $cacheKey = 'offline_check_times'.$node->id;
  197. if (Cache::has($cacheKey)) {
  198. $times = Cache::get($cacheKey);
  199. } else {
  200. // 键将保留24小时
  201. Cache::put($cacheKey, 1, Day);
  202. $times = 1;
  203. }
  204. if ($times < $offlineCheckTimes) {
  205. Cache::increment($cacheKey);
  206. PushNotification::send('节点异常警告', "节点**{$node->name}【{$node->ip}】**异常:**心跳异常,可能离线了**");
  207. }
  208. }
  209. }
  210. }
  211. }
  212. }