AutoJob.php 7.2 KB

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