AutoJob.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Components\Helpers;
  4. use App\Components\PushNotification;
  5. use App\Http\Models\Config;
  6. use App\Http\Models\Coupon;
  7. use App\Http\Models\Invite;
  8. use App\Http\Models\Order;
  9. use App\Http\Models\Payment;
  10. use App\Http\Models\SsNode;
  11. use App\Http\Models\SsNodeInfo;
  12. use App\Http\Models\User;
  13. use App\Http\Models\UserBanLog;
  14. use App\Http\Models\UserSubscribe;
  15. use App\Http\Models\UserSubscribeLog;
  16. use App\Http\Models\UserTrafficHourly;
  17. use App\Http\Models\VerifyCode;
  18. use Cache;
  19. use DB;
  20. use Exception;
  21. use Illuminate\Console\Command;
  22. use Log;
  23. class AutoJob extends Command
  24. {
  25. protected static $systemConfig;
  26. protected $signature = 'autoJob';
  27. protected $description = '自动化任务';
  28. public function __construct()
  29. {
  30. parent::__construct();
  31. self::$systemConfig = Helpers::systemConfig();
  32. }
  33. /*
  34. * 警告:除非熟悉业务流程,否则不推荐更改以下执行顺序,随意变更以下顺序可能导致系统异常
  35. */
  36. public function handle()
  37. {
  38. $jobStartTime = microtime(TRUE);
  39. // 关闭超时未支付在线订单
  40. $this->closePayments();
  41. // 关闭超时未支付订单
  42. $this->closeOrders();
  43. //过期验证码、优惠券、邀请码无效化
  44. $this->expireCode();
  45. // 封禁访问异常的订阅链接
  46. $this->blockSubscribe();
  47. // 封禁账号
  48. $this->blockUsers();
  49. // 解封被封禁的账号
  50. $this->unblockUsers();
  51. // 端口回收与分配
  52. $this->dispatchPort();
  53. // 检测节点是否离线
  54. $this->checkNodeStatus();
  55. // 检查 维护模式
  56. if(self::$systemConfig['maintenance_mode']){
  57. if(strtotime(self::$systemConfig['maintenance_time']) < time()){
  58. Config::query()->whereName('maintenance_mode')->update(['value' => 0]);
  59. Config::query()->whereName('maintenance_time')->update(['value' => '']);
  60. }
  61. }
  62. $jobEndTime = microtime(TRUE);
  63. $jobUsedTime = round(($jobEndTime-$jobStartTime), 4);
  64. Log::info('---【'.$this->description.'】完成---,耗时'.$jobUsedTime.'秒');
  65. }
  66. // 关闭超时未在线支付订单
  67. private function closePayments()
  68. {
  69. // 关闭超时未支付的在线支付订单(在线支付收款二维码超过30分钟自动关闭,关闭后无法再支付,所以我们限制15分钟内必须付款)
  70. $paymentList = Payment::query()->whereStatus(0)->where('created_at', '<=', date("Y-m-d H:i:s", strtotime("-15 minutes")))->get();
  71. if($paymentList->isNotEmpty()){
  72. DB::beginTransaction();
  73. try{
  74. foreach($paymentList as $payment){
  75. // 关闭支付单
  76. Payment::query()->whereId($payment->id)->update(['status' => -1]);
  77. // 关闭订单
  78. Order::query()->whereOid($payment->oid)->update(['status' => -1]);
  79. // 退回优惠券
  80. if($payment->order->coupon_id){
  81. Coupon::query()->whereId($payment->order->coupon_id)->update(['status' => 0]);
  82. Helpers::addCouponLog($payment->order->coupon_id, $payment->order->goods_id, $payment->oid, '在线订单超时未支付,自动退回');
  83. }
  84. }
  85. DB::commit();
  86. }catch(Exception $e){
  87. Log::info('【异常】自动关闭超时未支付在线订单:'.$e);
  88. DB::rollBack();
  89. }
  90. }
  91. }
  92. // 关闭超时未支付订单
  93. private function closeOrders()
  94. {
  95. // 关闭超时未支付的在线支付订单(在线支付收款二维码超过30分钟自动关闭,关闭后无法再支付,所以我们限制15分钟内必须付款)
  96. $orderList = Order::query()->whereStatus(0)->where('created_at', '<=', date("Y-m-d H:i:s", strtotime("-30 minutes")))->get();
  97. if($orderList->isNotEmpty()){
  98. DB::beginTransaction();
  99. try{
  100. foreach($orderList as $order){
  101. // 关闭订单
  102. Order::query()->whereKey($order->oid)->update(['status' => -1]);
  103. // 退回优惠券
  104. if($order->coupon_id){
  105. Coupon::query()->whereId($order->coupon_id)->update(['status' => 0]);
  106. Helpers::addCouponLog($order->coupon_id, $order->goods_id, $order->oid, '订单超时未支付,自动退回');
  107. }
  108. }
  109. DB::commit();
  110. }catch(Exception $e){
  111. Log::info('【异常】自动关闭超时未支付订单:'.$e);
  112. DB::rollBack();
  113. }
  114. }
  115. }
  116. // 注册验证码自动置无效
  117. private function expireCode()
  118. {
  119. // 注册验证码自动置无效
  120. VerifyCode::query()->whereStatus(0)->where('created_at', '<=', date('Y-m-d H:i:s', strtotime("-10 minutes")))->update(['status' => 2]);
  121. // 优惠券到期自动置无效
  122. Coupon::query()->whereStatus(0)->where('available_end', '<=', time())->update(['status' => 2]);
  123. // 邀请码到期自动置无效
  124. Invite::query()->whereStatus(0)->where('dateline', '<=', date('Y-m-d H:i:s'))->update(['status' => 2]);
  125. }
  126. // 封禁访问异常的订阅链接
  127. private function blockSubscribe()
  128. {
  129. if(self::$systemConfig['is_subscribe_ban']){
  130. $userList = User::query()->where('status', '>=', 0)->whereEnable(1)->get();
  131. foreach($userList as $user){
  132. $subscribe = UserSubscribe::query()->whereUserId($user->id)->first();
  133. if($subscribe){
  134. // 24小时内不同IP的请求次数
  135. $request_times = UserSubscribeLog::query()->whereSid($subscribe->id)->where('request_time', '>=', date("Y-m-d H:i:s", strtotime("-24 hours")))->distinct('request_ip')->count('request_ip');
  136. if($request_times >= self::$systemConfig['subscribe_ban_times']){
  137. UserSubscribe::query()->whereId($subscribe->id)->update(['status' => 0, 'ban_time' => time(), 'ban_desc' => '存在异常,自动封禁']);
  138. // 记录封禁日志
  139. $this->addUserBanLog($subscribe->user_id, 0, '【完全封禁订阅】-订阅24小时内请求异常');
  140. }
  141. }
  142. }
  143. }
  144. }
  145. /**
  146. * 添加用户封禁日志
  147. *
  148. * @param int $userId 用户ID
  149. * @param int $minutes 封禁时长,单位分钟
  150. * @param string $desc 封禁理由
  151. */
  152. private function addUserBanLog($userId, $minutes, $desc)
  153. {
  154. $log = new UserBanLog();
  155. $log->user_id = $userId;
  156. $log->minutes = $minutes;
  157. $log->desc = $desc;
  158. $log->save();
  159. }
  160. // 封禁账号
  161. private function blockUsers()
  162. {
  163. // 封禁1小时内流量异常账号
  164. if(self::$systemConfig['is_traffic_ban']){
  165. $userList = User::query()->whereEnable(1)->where('status', '>=', 0)->whereBanTime(0)->get();
  166. foreach($userList as $user){
  167. // 对管理员豁免
  168. if($user->is_admin){
  169. continue;
  170. }
  171. // 多往前取5分钟,防止数据统计任务执行时间过长导致没有数据
  172. $totalTraffic = UserTrafficHourly::query()->whereUserId($user->id)->whereNodeId(0)->where('created_at', '>=', date('Y-m-d H:i:s', time()-3900))->sum('total');
  173. if($totalTraffic >= (self::$systemConfig['traffic_ban_value']*1073741824)){
  174. User::query()->whereId($user->id)->update(['enable' => 0, 'ban_time' => strtotime(date('Y-m-d H:i:s', strtotime("+".self::$systemConfig['traffic_ban_time']." minutes")))]);
  175. // 写入日志
  176. $this->addUserBanLog($user->id, self::$systemConfig['traffic_ban_time'], '【临时封禁代理】-1小时内流量异常');
  177. }
  178. }
  179. }
  180. // 禁用流量超限用户
  181. $userList = User::query()->whereEnable(1)->where('status', '>=', 0)->whereBanTime(0)->whereRaw("u + d >= transfer_enable")->get();
  182. foreach($userList as $user){
  183. User::query()->whereId($user->id)->update(['enable' => 0]);
  184. // 写入日志
  185. $this->addUserBanLog($user->id, 0, '【封禁代理】-流量已用完');
  186. }
  187. }
  188. // 解封被临时封禁的账号
  189. private function unblockUsers()
  190. {
  191. // 解封被临时封禁的账号
  192. $userList = User::query()->whereEnable(0)->where('status', '>=', 0)->where('ban_time', '>', 0)->get();
  193. foreach($userList as $user){
  194. if($user->ban_time < time()){
  195. User::query()->whereId($user->id)->update(['enable' => 1, 'ban_time' => 0]);
  196. // 写入操作日志
  197. $this->addUserBanLog($user->id, 0, '【自动解封】-临时封禁到期');
  198. }
  199. }
  200. // 可用流量大于已用流量也解封(比如:邀请返利自动加了流量)
  201. $userList = User::query()->whereEnable(0)->where('status', '>=', 0)->whereBanTime(0)->where('expire_time', '>=', date('Y-m-d'))->whereRaw("u + d < transfer_enable")->get();
  202. foreach($userList as $user){
  203. User::query()->whereId($user->id)->update(['enable' => 1]);
  204. // 写入操作日志
  205. $this->addUserBanLog($user->id, 0, '【自动解封】-有流量解封');
  206. }
  207. }
  208. // 端口回收与分配
  209. private function dispatchPort()
  210. {
  211. if(self::$systemConfig['auto_release_port']){
  212. ## 自动分配端口
  213. $userList = User::query()->whereEnable(1)->where('status', '>=', 0)->wherePort(0)->get();
  214. foreach($userList as $user){
  215. $port = self::$systemConfig['is_rand_port']? Helpers::getRandPort() : Helpers::getOnlyPort();
  216. User::query()->whereId($user->id)->update(['port' => $port]);
  217. }
  218. ## 被封禁的账号自动释放端口
  219. User::query()->whereEnable(0)->whereStatus(-1)->where('port', '!=', 0)->update(['port' => 0]);
  220. ## 过期一个月的账户自动释放端口
  221. User::query()->whereEnable(0)->where('port', '!=', 0)->where('expire_time', '<=', date("Y-m-d", strtotime("-30 days")))->update(['port' => 0]);
  222. }
  223. }
  224. // 检测节点是否离线
  225. private function checkNodeStatus()
  226. {
  227. if(self::$systemConfig['is_node_offline']){
  228. $nodeList = SsNode::query()->whereIsTransit(0)->whereStatus(1)->get();
  229. foreach($nodeList as $node){
  230. // 10分钟内无节点负载信息则认为是后端炸了
  231. $nodeTTL = SsNodeInfo::query()->whereNodeId($node->id)->where('log_time', '>=', strtotime("-10 minutes"))->orderBy('id', 'desc')->doesntExist();
  232. if($nodeTTL){
  233. if(self::$systemConfig['offline_check_times']){
  234. // 已通知次数
  235. $cacheKey = 'offline_check_times'.$node->id;
  236. if(Cache::has($cacheKey)){
  237. $times = Cache::get($cacheKey);
  238. }else{
  239. // 键将保留24小时
  240. Cache::put($cacheKey, 1, 86400);
  241. $times = 1;
  242. }
  243. if($times < self::$systemConfig['offline_check_times']){
  244. Cache::increment($cacheKey);
  245. PushNotification::send('节点异常警告', "节点**{$node->name}【{$node->ip}】**异常:**心跳异常,可能离线了**");
  246. }
  247. }
  248. }
  249. }
  250. }
  251. }
  252. }