AutoJob.php 7.1 KB

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