AutoJob.php 9.6 KB

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