Compare commits

..

No commits in common. "master" and "1.6.0" have entirely different histories.

172 changed files with 2068 additions and 3958 deletions

View File

@ -14,7 +14,7 @@ DB_USERNAME=root
DB_PASSWORD=123456
BROADCAST_DRIVER=log
CACHE_DRIVER=file
CACHE_DRIVER=redis
QUEUE_CONNECTION=redis
SESSION_DRIVER=redis
SESSION_LIFETIME=120

View File

@ -1,39 +0,0 @@
---
name: Bug report | 问题反馈
about: Tell us what problems you have encountered
title: "[BUG]"
labels: ''
assignees: ''
---
🙇🙇🙇注意XrayR等非V2Board问题请前往项目方提问
🙇🙇🙇Note: XrayR and other non-V2Board issues please go to the project side to ask questions
The V2Board version number you are using
当前使用的V2Board版本号
--------
Briefly describe the problem you are experiencing
简单描述你遇到的问题
--------
Screenshot of the reported error(Please do desensitization)
报告错误的截图(请做脱敏处理)
--------
Screenshot of the reported error(Please do desensitization)
报告错误的截图(请做脱敏处理)
--------
The latest log files in the storage/logs directory report from #1 (Please do desensitization)
storage/logs 目录下最新的日志文件从 #1 开始报告(请做脱敏处理)
--------

View File

@ -1,11 +0,0 @@
---
name: Feature request | 功能请求
about: Tell us what you need
title: "[Feature request]"
labels: ''
assignees: ''
---
Please describe in detail the problems or needs you have encountered.
请详细描述你遇到的问题或需求。

View File

@ -50,7 +50,7 @@ class CheckCommission extends Command
if ((int)config('v2board.commission_auto_check_enable', 1)) {
Order::where('commission_status', 0)
->where('invite_user_id', '!=', NULL)
->where('status', 3)
->whereNotIn('status', [0, 2])
->where('updated_at', '<=', strtotime('-3 day', time()))
->update([
'commission_status' => 1
@ -80,14 +80,15 @@ class CheckCommission extends Command
public function payHandle($inviteUserId, Order $order)
{
$level = 3;
if ((int)config('v2board.commission_distribution_enable', 0)) {
$level = 3;
$commissionShareLevels = [
0 => (int)config('v2board.commission_distribution_l1'),
1 => (int)config('v2board.commission_distribution_l2'),
2 => (int)config('v2board.commission_distribution_l3')
];
} else {
$level = 3;
$commissionShareLevels = [
0 => 100
];

View File

@ -41,7 +41,6 @@ class CheckTicket extends Command
ini_set('memory_limit', -1);
$tickets = Ticket::where('status', 0)
->where('updated_at', '<=', time() - 24 * 3600)
->where('reply_status', 0)
->get();
foreach ($tickets as $ticket) {
if ($ticket->user_id === $ticket->last_reply_user_id) continue;

View File

@ -1,52 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Models\Log;
use App\Models\Plan;
use App\Models\StatServer;
use App\Models\StatUser;
use App\Utils\Helper;
use Illuminate\Console\Command;
use App\Models\User;
use Illuminate\Support\Facades\DB;
class ResetLog extends Command
{
protected $builder;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'reset:log';
/**
* The console command description.
*
* @var string
*/
protected $description = '清空日志';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
StatUser::where('record_at', '<', strtotime('-2 month', time()))->delete();
StatServer::where('record_at', '<', strtotime('-2 month', time()))->delete();
Log::where('created_at', '<', strtotime('-1 month', time()))->delete();
}
}

View File

@ -1,58 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Models\Plan;
use App\Utils\Helper;
use Illuminate\Console\Command;
use App\Models\User;
use Illuminate\Support\Facades\DB;
class ResetUser extends Command
{
protected $builder;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'reset:user';
/**
* The console command description.
*
* @var string
*/
protected $description = '重置所有用户信息';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
if (!$this->confirm("确定要重置所有用户安全信息吗?")) {
return;
}
ini_set('memory_limit', -1);
$users = User::all();
foreach ($users as $user)
{
$user->token = Helper::guid();
$user->uuid = Helper::guid(true);
$user->save();
$this->info("已重置用户{$user->email}的安全信息");
}
}
}

View File

@ -45,7 +45,6 @@ class SendRemindMail extends Command
$mailService = new MailService();
foreach ($users as $user) {
if ($user->remind_expire) $mailService->remindExpire($user);
if ($user->remind_traffic) $mailService->remindTraffic($user);
}
}
}

View File

@ -2,7 +2,15 @@
namespace App\Console\Commands;
use App\Models\Order;
use App\Models\User;
use App\Utils\CacheKey;
use App\Utils\Helper;
use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Foundation\Console\ConfigCacheCommand;
use Illuminate\Support\Facades\Cache;
use Matriphe\Larinfo;
class Test extends Command
{

View File

@ -48,9 +48,7 @@ class V2boardInstall extends Command
$this->info(" \ V / / __/| |_) | (_) | (_| | | | (_| | ");
$this->info(" \_/ |_____|____/ \___/ \__,_|_| \__,_| ");
if (\File::exists(base_path() . '/.env')) {
$securePath = config('v2board.secure_path', config('v2board.frontend_admin_path', hash('crc32b', config('app.key'))));
$this->info("访问 http(s)://你的站点/{$securePath} 进入管理面板,你可以在用户中心修改你的密码。");
abort(500, '如需重新安装请删除目录下.env文件');
abort(500, 'V2board 已安装,如需重新安装请删除目录下.env文件');
}
if (!copy(base_path() . '/.env.example', base_path() . '/.env')) {
@ -91,17 +89,16 @@ class V2boardInstall extends Command
while (!$email) {
$email = $this->ask('请输入管理员邮箱?');
}
$password = Helper::guid(false);
$password = '';
while (!$password) {
$password = $this->ask('请输入管理员密码?');
}
if (!$this->registerAdmin($email, $password)) {
abort(500, '管理员账号注册失败,请重试');
}
$this->info('一切就绪');
$this->info("管理员邮箱:{$email}");
$this->info("管理员密码:{$password}");
$defaultSecurePath = hash('crc32b', config('app.key'));
$this->info("访问 http(s)://你的站点/{$defaultSecurePath} 进入管理面板,你可以在用户中心修改你的密码。");
$this->info('访问 http(s)://你的站点/admin 进入管理面板');
} catch (\Exception $e) {
$this->error($e->getMessage());
}

View File

@ -2,15 +2,10 @@
namespace App\Console\Commands;
use App\Models\StatServer;
use App\Models\StatUser;
use App\Models\User;
use App\Services\StatisticalService;
use Illuminate\Console\Command;
use App\Models\Order;
use App\Models\Stat;
use App\Models\StatOrder;
use App\Models\CommissionLog;
use Illuminate\Support\Facades\DB;
class V2boardStatistics extends Command
{
@ -45,87 +40,39 @@ class V2boardStatistics extends Command
*/
public function handle()
{
$startAt = microtime(true);
ini_set('memory_limit', -1);
$this->statUser();
$this->statServer();
$this->stat();
$this->info('耗时' . (microtime(true) - $startAt));
$this->statOrder();
}
private function statServer()
{
$createdAt = time();
$recordAt = strtotime('-1 day', strtotime(date('Y-m-d')));
$statService = new StatisticalService();
$statService->setStartAt($recordAt);
$statService->setServerStats();
$stats = $statService->getStatServer();
DB::beginTransaction();
foreach ($stats as $stat) {
if (!StatServer::insert([
'server_id' => $stat['server_id'],
'server_type' => $stat['server_type'],
'u' => $stat['u'],
'd' => $stat['d'],
'created_at' => $createdAt,
'updated_at' => $createdAt,
'record_type' => 'd',
'record_at' => $recordAt
])) {
DB::rollback();
throw new \Exception('stat server fail');
}
}
DB::commit();
$statService->clearStatServer();
}
private function statUser()
{
$createdAt = time();
$recordAt = strtotime('-1 day', strtotime(date('Y-m-d')));
$statService = new StatisticalService();
$statService->setStartAt($recordAt);
$statService->setUserStats();
$stats = $statService->getStatUser();
DB::beginTransaction();
foreach ($stats as $stat) {
if (!StatUser::insert([
'user_id' => $stat['user_id'],
'u' => $stat['u'],
'd' => $stat['d'],
'server_rate' => $stat['server_rate'],
'created_at' => $createdAt,
'updated_at' => $createdAt,
'record_type' => 'd',
'record_at' => $recordAt
])) {
DB::rollback();
throw new \Exception('stat user fail');
}
}
DB::commit();
$statService->clearStatUser();
}
private function stat()
private function statOrder()
{
$endAt = strtotime(date('Y-m-d'));
$startAt = strtotime('-1 day', $endAt);
$statisticalService = new StatisticalService();
$statisticalService->setStartAt($startAt);
$statisticalService->setEndAt($endAt);
$data = $statisticalService->generateStatData();
$data['record_at'] = $startAt;
$data['record_type'] = 'd';
$statistic = Stat::where('record_at', $startAt)
$orderBuilder = Order::where('paid_at', '>=', $startAt)
->where('paid_at', '<', $endAt)
->whereNotIn('status', [0, 2]);
$orderCount = $orderBuilder->count();
$orderAmount = $orderBuilder->sum('total_amount');
$commissionBuilder = CommissionLog::where('created_at', '>=', $startAt)
->where('created_at', '<', $endAt)
->where('get_amount', '>', 0);
$commissionCount = $commissionBuilder->count();
$commissionAmount = $commissionBuilder->sum('get_amount');
$data = [
'order_count' => $orderCount,
'order_amount' => $orderAmount,
'commission_count' => $commissionCount,
'commission_amount' => $commissionAmount,
'record_type' => 'd',
'record_at' => $startAt
];
$statistic = StatOrder::where('record_at', $startAt)
->where('record_type', 'd')
->first();
if ($statistic) {
$statistic->update($data);
return;
}
Stat::create($data);
StatOrder::create($data);
}
}

View File

@ -57,7 +57,6 @@ class V2boardUpdate extends Command
} catch (\Exception $e) {
}
}
\Artisan::call('horizon:terminate');
$this->info('更新完毕,队列服务已重启,你无需进行任何操作。');
$this->info('更新完毕,请重新启动队列服务。');
}
}

View File

@ -35,7 +35,6 @@ class Kernel extends ConsoleKernel
$schedule->command('check:ticket')->everyMinute();
// reset
$schedule->command('reset:traffic')->daily();
$schedule->command('reset:log')->daily();
// send
$schedule->command('send:remindMail')->dailyAt('11:30');
// horizon metrics

View File

@ -54,7 +54,9 @@ class Handler extends ExceptionHandler
public function render($request, Throwable $exception)
{
if ($exception instanceof ViewException) {
abort(500, "主题渲染失败。如更新主题,参数可能发生变化请重新配置主题后再试。");
return response([
'message' => "主题初始化发生错误,请在后台对主题检查或配置后重试。"
]);
}
return parent::render($request, $exception);
}

View File

@ -39,7 +39,7 @@ class ConfigController extends Controller
public function testSendMail(Request $request)
{
$obj = new SendEmailJob([
'email' => $request->user['email'],
'email' => $request->session()->get('email'),
'subject' => 'This is v2board test email',
'template_name' => 'notify',
'template_value' => [
@ -87,16 +87,27 @@ class ConfigController extends Controller
'site' => [
'logo' => config('v2board.logo'),
'force_https' => (int)config('v2board.force_https', 0),
'safe_mode_enable' => (int)config('v2board.safe_mode_enable', 0),
'stop_register' => (int)config('v2board.stop_register', 0),
'email_verify' => (int)config('v2board.email_verify', 0),
'app_name' => config('v2board.app_name', 'V2Board'),
'app_description' => config('v2board.app_description', 'V2Board is best!'),
'app_url' => config('v2board.app_url'),
'subscribe_url' => config('v2board.subscribe_url'),
'try_out_plan_id' => (int)config('v2board.try_out_plan_id', 0),
'try_out_hour' => (int)config('v2board.try_out_hour', 1),
'email_whitelist_enable' => (int)config('v2board.email_whitelist_enable', 0),
'email_whitelist_suffix' => config('v2board.email_whitelist_suffix', Dict::EMAIL_WHITELIST_SUFFIX_DEFAULT),
'email_gmail_limit_enable' => config('v2board.email_gmail_limit_enable', 0),
'recaptcha_enable' => (int)config('v2board.recaptcha_enable', 0),
'recaptcha_key' => config('v2board.recaptcha_key'),
'recaptcha_site_key' => config('v2board.recaptcha_site_key'),
'tos_url' => config('v2board.tos_url'),
'currency' => config('v2board.currency', 'CNY'),
'currency_symbol' => config('v2board.currency_symbol', '¥'),
'register_limit_by_ip_enable' => (int)config('v2board.register_limit_by_ip_enable', 0),
'register_limit_count' => config('v2board.register_limit_count', 3),
'register_limit_expire' => config('v2board.register_limit_expire', 60)
],
'subscribe' => [
'plan_change_enable' => (int)config('v2board.plan_change_enable', 1),
@ -113,11 +124,14 @@ class ConfigController extends Controller
'frontend_theme_header' => config('v2board.frontend_theme_header', 'dark'),
'frontend_theme_color' => config('v2board.frontend_theme_color', 'default'),
'frontend_background_url' => config('v2board.frontend_background_url'),
'frontend_admin_path' => config('v2board.frontend_admin_path', 'admin')
],
'server' => [
'server_token' => config('v2board.server_token'),
'server_pull_interval' => config('v2board.server_pull_interval', 60),
'server_push_interval' => config('v2board.server_push_interval', 60),
'server_license' => config('v2board.server_license'),
'server_log_enable' => config('v2board.server_log_enable', 0),
'server_v2ray_domain' => config('v2board.server_v2ray_domain'),
'server_v2ray_protocol' => config('v2board.server_v2ray_protocol'),
],
'email' => [
'email_template' => config('v2board.email_template', 'default'),
@ -140,23 +154,6 @@ class ConfigController extends Controller
'macos_download_url' => config('v2board.macos_download_url'),
'android_version' => config('v2board.android_version'),
'android_download_url' => config('v2board.android_download_url')
],
'safe' => [
'email_verify' => (int)config('v2board.email_verify', 0),
'safe_mode_enable' => (int)config('v2board.safe_mode_enable', 0),
'secure_path' => config('v2board.secure_path', config('v2board.frontend_admin_path', hash('crc32b', config('app.key')))),
'email_whitelist_enable' => (int)config('v2board.email_whitelist_enable', 0),
'email_whitelist_suffix' => config('v2board.email_whitelist_suffix', Dict::EMAIL_WHITELIST_SUFFIX_DEFAULT),
'email_gmail_limit_enable' => config('v2board.email_gmail_limit_enable', 0),
'recaptcha_enable' => (int)config('v2board.recaptcha_enable', 0),
'recaptcha_key' => config('v2board.recaptcha_key'),
'recaptcha_site_key' => config('v2board.recaptcha_site_key'),
'register_limit_by_ip_enable' => (int)config('v2board.register_limit_by_ip_enable', 0),
'register_limit_count' => config('v2board.register_limit_count', 3),
'register_limit_expire' => config('v2board.register_limit_expire', 60),
'password_limit_enable' => (int)config('v2board.password_limit_enable', 1),
'password_limit_count' => config('v2board.password_limit_count', 5),
'password_limit_expire' => config('v2board.password_limit_expire', 60)
]
];
if ($key && isset($data[$key])) {

View File

@ -82,7 +82,6 @@ class CouponController extends Controller
$coupons = [];
$coupon = $request->validated();
$coupon['created_at'] = $coupon['updated_at'] = time();
$coupon['show'] = 1;
unset($coupon['generate_count']);
for ($i = 0;$i < $request->input('generate_count');$i++) {
$coupon['code'] = Helper::randomChar(8);

View File

@ -8,7 +8,6 @@ use App\Utils\Helper;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Payment;
use Illuminate\Support\Facades\DB;
class PaymentController extends Controller
{
@ -25,7 +24,7 @@ class PaymentController extends Controller
public function fetch()
{
$payments = Payment::orderBy('sort', 'ASC')->get();
$payments = Payment::all();
foreach ($payments as $k => $v) {
$notifyUrl = url("/api/v1/guest/payment/notify/{$v->payment}/{$v->uuid}");
if ($v->notify_domain) {
@ -108,26 +107,4 @@ class PaymentController extends Controller
'data' => $payment->delete()
]);
}
public function sort(Request $request)
{
$request->validate([
'ids' => 'required|array'
], [
'ids.required' => '参数有误',
'ids.array' => '参数有误'
]);
DB::beginTransaction();
foreach ($request->input('ids') as $k => $v) {
if (!Payment::find($v)->update(['sort' => $k + 1])) {
DB::rollBack();
abort(500, '保存失败');
}
}
DB::commit();
return response([
'data' => true
]);
}
}

View File

@ -5,7 +5,6 @@ namespace App\Http\Controllers\Admin;
use App\Http\Requests\Admin\PlanSave;
use App\Http\Requests\Admin\PlanSort;
use App\Http\Requests\Admin\PlanUpdate;
use App\Services\PlanService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Plan;
@ -17,7 +16,17 @@ class PlanController extends Controller
{
public function fetch(Request $request)
{
$counts = PlanService::countActiveUsers();
$counts = User::select(
DB::raw("plan_id"),
DB::raw("count(*) as count")
)
->where('plan_id', '!=', NULL)
->where(function ($query) {
$query->where('expired_at', '>=', time())
->orWhere('expired_at', NULL);
})
->groupBy("plan_id")
->get();
$plans = Plan::orderBy('sort', 'ASC')->get();
foreach ($plans as $k => $v) {
$plans[$k]->count = 0;
@ -41,13 +50,10 @@ class PlanController extends Controller
DB::beginTransaction();
// update user group id and transfer
try {
if ($request->input('force_update')) {
User::where('plan_id', $plan->id)->update([
'group_id' => $params['group_id'],
'transfer_enable' => $params['transfer_enable'] * 1073741824,
'speed_limit' => $params['speed_limit']
]);
}
User::where('plan_id', $plan->id)->update([
'group_id' => $params['group_id'],
'transfer_enable' => $params['transfer_enable'] * 1073741824
]);
$plan->update($params);
} catch (\Exception $e) {
DB::rollBack();

View File

@ -5,7 +5,7 @@ namespace App\Http\Controllers\Admin\Server;
use App\Models\Plan;
use App\Models\ServerShadowsocks;
use App\Models\ServerTrojan;
use App\Models\ServerVmess;
use App\Models\ServerV2ray;
use App\Models\ServerGroup;
use App\Models\User;
use App\Services\ServerService;
@ -65,7 +65,7 @@ class GroupController extends Controller
}
}
$servers = ServerVmess::all();
$servers = ServerV2ray::all();
foreach ($servers as $server) {
if (in_array($request->input('id'), $server->group_id)) {
abort(500, '该组已被节点所使用,无法删除');

View File

@ -1,113 +0,0 @@
<?php
namespace App\Http\Controllers\Admin\Server;
use App\Http\Requests\Admin\ServerVmessSave;
use App\Http\Requests\Admin\ServerVmessUpdate;
use App\Models\ServerHysteria;
use App\Services\ServerService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\ServerVmess;
class HysteriaController extends Controller
{
public function save(Request $request)
{
$params = $request->validate([
'show' => '',
'name' => 'required',
'group_id' => 'required|array',
'route_id' => 'nullable|array',
'parent_id' => 'nullable|integer',
'host' => 'required',
'port' => 'required',
'server_port' => 'required',
'tags' => 'nullable|array',
'rate' => 'required|numeric',
'up_mbps' => 'required|numeric|min:1',
'down_mbps' => 'required|numeric|min:1',
'server_name' => 'nullable',
'insecure' => 'required|in:0,1'
]);
if ($request->input('id')) {
$server = ServerHysteria::find($request->input('id'));
if (!$server) {
abort(500, '服务器不存在');
}
try {
$server->update($params);
} catch (\Exception $e) {
abort(500, '保存失败');
}
return response([
'data' => true
]);
}
if (!ServerHysteria::create($params)) {
abort(500, '创建失败');
}
return response([
'data' => true
]);
}
public function drop(Request $request)
{
if ($request->input('id')) {
$server = ServerHysteria::find($request->input('id'));
if (!$server) {
abort(500, '节点ID不存在');
}
}
return response([
'data' => $server->delete()
]);
}
public function update(Request $request)
{
$request->validate([
'show' => 'in:0,1'
], [
'show.in' => '显示状态格式不正确'
]);
$params = $request->only([
'show',
]);
$server = ServerHysteria::find($request->input('id'));
if (!$server) {
abort(500, '该服务器不存在');
}
try {
$server->update($params);
} catch (\Exception $e) {
abort(500, '保存失败');
}
return response([
'data' => true
]);
}
public function copy(Request $request)
{
$server = ServerHysteria::find($request->input('id'));
$server->show = 0;
if (!$server) {
abort(500, '服务器不存在');
}
if (!ServerHysteria::create($server->toArray())) {
abort(500, '复制失败');
}
return response([
'data' => true
]);
}
}

View File

@ -2,6 +2,9 @@
namespace App\Http\Controllers\Admin\Server;
use App\Models\ServerV2ray;
use App\Models\ServerShadowsocks;
use App\Models\ServerTrojan;
use App\Services\ServerService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
@ -20,20 +23,27 @@ class ManageController extends Controller
public function sort(Request $request)
{
ini_set('post_max_size', '1m');
$params = $request->only(
'shadowsocks',
'vmess',
'trojan',
'hysteria'
) ?? [];
DB::beginTransaction();
foreach ($params as $k => $v) {
$model = 'App\\Models\\Server' . ucfirst($k);
foreach($v as $id => $sort) {
if (!$model::find($id)->update(['sort' => $sort])) {
DB::rollBack();
abort(500, '保存失败');
}
foreach ($request->input('sorts') as $k => $v) {
switch ($v['key']) {
case 'shadowsocks':
if (!ServerShadowsocks::find($v['value'])->update(['sort' => $k + 1])) {
DB::rollBack();
abort(500, '保存失败');
}
break;
case 'v2ray':
if (!ServerV2ray::find($v['value'])->update(['sort' => $k + 1])) {
DB::rollBack();
abort(500, '保存失败');
}
break;
case 'trojan':
if (!ServerTrojan::find($v['value'])->update(['sort' => $k + 1])) {
DB::rollBack();
abort(500, '保存失败');
}
break;
}
}
DB::commit();

View File

@ -1,72 +0,0 @@
<?php
namespace App\Http\Controllers\Admin\Server;
use App\Http\Requests\Admin\ServerShadowsocksSave;
use App\Http\Requests\Admin\ServerShadowsocksUpdate;
use App\Models\ServerRoute;
use App\Models\ServerShadowsocks;
use App\Services\ServerService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class RouteController extends Controller
{
public function fetch(Request $request)
{
$routes = ServerRoute::get();
// TODO: remove on 1.8.0
foreach ($routes as $k => $route) {
$array = json_decode($route->match, true);
if (is_array($array)) $routes[$k]['match'] = $array;
}
// TODO: remove on 1.8.0
return [
'data' => $routes
];
}
public function save(Request $request)
{
$params = $request->validate([
'remarks' => 'required',
'match' => 'required|array',
'action' => 'required|in:block,dns',
'action_value' => 'nullable'
], [
'remarks.required' => '备注不能为空',
'match.required' => '匹配值不能为空',
'action.required' => '动作类型不能为空',
'action.in' => '动作类型参数有误'
]);
$params['match'] = array_filter($params['match']);
// TODO: remove on 1.8.0
$params['match'] = json_encode($params['match']);
// TODO: remove on 1.8.0
if ($request->input('id')) {
try {
$route = ServerRoute::find($request->input('id'));
$route->update($params);
return [
'data' => true
];
} catch (\Exception $e) {
abort(500, '保存失败');
}
}
if (!ServerRoute::create($params)) abort(500, '创建失败');
return [
'data' => true
];
}
public function drop(Request $request)
{
$route = ServerRoute::find($request->input('id'));
if (!$route) abort(500, '路由不存在');
if (!$route->delete()) abort(500, '删除失败');
return [
'data' => true
];
}
}

View File

@ -2,21 +2,21 @@
namespace App\Http\Controllers\Admin\Server;
use App\Http\Requests\Admin\ServerVmessSave;
use App\Http\Requests\Admin\ServerVmessUpdate;
use App\Http\Requests\Admin\ServerV2raySave;
use App\Http\Requests\Admin\ServerV2rayUpdate;
use App\Services\ServerService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\ServerVmess;
use App\Models\ServerV2ray;
class VmessController extends Controller
class V2rayController extends Controller
{
public function save(ServerVmessSave $request)
public function save(ServerV2raySave $request)
{
$params = $request->validated();
if ($request->input('id')) {
$server = ServerVmess::find($request->input('id'));
$server = ServerV2ray::find($request->input('id'));
if (!$server) {
abort(500, '服务器不存在');
}
@ -30,7 +30,7 @@ class VmessController extends Controller
]);
}
if (!ServerVmess::create($params)) {
if (!ServerV2ray::create($params)) {
abort(500, '创建失败');
}
@ -42,7 +42,7 @@ class VmessController extends Controller
public function drop(Request $request)
{
if ($request->input('id')) {
$server = ServerVmess::find($request->input('id'));
$server = ServerV2ray::find($request->input('id'));
if (!$server) {
abort(500, '节点ID不存在');
}
@ -52,13 +52,13 @@ class VmessController extends Controller
]);
}
public function update(ServerVmessUpdate $request)
public function update(ServerV2rayUpdate $request)
{
$params = $request->only([
'show',
]);
$server = ServerVmess::find($request->input('id'));
$server = ServerV2ray::find($request->input('id'));
if (!$server) {
abort(500, '该服务器不存在');
@ -76,12 +76,12 @@ class VmessController extends Controller
public function copy(Request $request)
{
$server = ServerVmess::find($request->input('id'));
$server = ServerV2ray::find($request->input('id'));
$server->show = 0;
if (!$server) {
abort(500, '服务器不存在');
}
if (!ServerVmess::create($server->toArray())) {
if (!ServerV2ray::create($server->toArray())) {
abort(500, '复制失败');
}
@ -89,4 +89,13 @@ class VmessController extends Controller
'data' => true
]);
}
public function viewConfig(Request $request)
{
$serverService = new ServerService();
$config = $serverService->getV2RayConfig($request->input('node_id'), 23333);
return response([
'data' => $config
]);
}
}

View File

@ -2,99 +2,27 @@
namespace App\Http\Controllers\Admin;
use App\Models\CommissionLog;
use App\Models\ServerShadowsocks;
use App\Models\ServerTrojan;
use App\Models\StatUser;
use App\Services\ServerService;
use App\Services\StatisticalService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\ServerGroup;
use App\Models\ServerVmess;
use App\Models\ServerV2ray;
use App\Models\Plan;
use App\Models\User;
use App\Models\Ticket;
use App\Models\Order;
use App\Models\Stat;
use App\Models\StatOrder;
use App\Models\StatServer;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
class StatController extends Controller
{
public function getStat(Request $request)
{
$params = $request->validate([
'start_at' => '',
'end_at' => ''
]);
if (isset($params['start_at']) && isset($params['end_at'])) {
$stats = Stat::where('record_at', '>=', $params['start_at'])
->where('record_at', '<', $params['end_at'])
->get()
->makeHidden(['record_at', 'created_at', 'updated_at', 'id', 'record_type'])
->toArray();
} else {
$statisticalService = new StatisticalService();
return [
'data' => $statisticalService->generateStatData()
];
}
$stats = array_reduce($stats, function($carry, $item) {
foreach($item as $key => $value) {
if(isset($carry[$key]) && $carry[$key]) {
$carry[$key] += $value;
} else {
$carry[$key] = $value;
}
}
return $carry;
}, []);
return [
'data' => $stats
];
}
public function getStatRecord(Request $request)
{
$request->validate([
'type' => 'required|in:paid_total,commission_total,register_count',
'start_at' => '',
'end_at' => ''
]);
$statisticalService = new StatisticalService();
$statisticalService->setStartAt($request->input('start_at'));
$statisticalService->setEndAt($request->input('end_at'));
return [
'data' => $statisticalService->getStatRecord($request->input('type'))
];
}
public function getRanking(Request $request)
{
$request->validate([
'type' => 'required|in:server_traffic_rank,user_consumption_rank,invite_rank',
'start_at' => '',
'end_at' => '',
'limit' => 'nullable|integer'
]);
$statisticalService = new StatisticalService();
$statisticalService->setStartAt($request->input('start_at'));
$statisticalService->setEndAt($request->input('end_at'));
return [
'data' => $statisticalService->getRanking($request->input('type'), $request->input('limit') ?? 20)
];
}
public function getOverride(Request $request)
{
return [
return response([
'data' => [
'month_income' => Order::where('created_at', '>=', strtotime(date('Y-m-1')))
->where('created_at', '<', time())
@ -117,20 +45,14 @@ class StatController extends Controller
'last_month_income' => Order::where('created_at', '>=', strtotime('-1 month', strtotime(date('Y-m-1'))))
->where('created_at', '<', strtotime(date('Y-m-1')))
->whereNotIn('status', [0, 2])
->sum('total_amount'),
'commission_month_payout' => CommissionLog::where('created_at', '>=', strtotime(date('Y-m-1')))
->where('created_at', '<', time())
->sum('get_amount'),
'commission_last_month_payout' => CommissionLog::where('created_at', '>=', strtotime('-1 month', strtotime(date('Y-m-1'))))
->where('created_at', '<', strtotime(date('Y-m-1')))
->sum('get_amount'),
->sum('total_amount')
]
];
]);
}
public function getOrder(Request $request)
{
$statistics = Stat::where('record_type', 'd')
$statistics = StatOrder::where('record_type', 'd')
->limit(31)
->orderBy('record_at', 'DESC')
->get()
@ -138,50 +60,49 @@ class StatController extends Controller
$result = [];
foreach ($statistics as $statistic) {
$date = date('m-d', $statistic['record_at']);
$result[] = [
array_push($result, [
'type' => '收款金额',
'date' => $date,
'value' => $statistic['paid_total'] / 100
];
$result[] = [
'value' => $statistic['order_amount'] / 100
]);
array_push($result, [
'type' => '收款笔数',
'date' => $date,
'value' => $statistic['paid_count']
];
$result[] = [
'value' => $statistic['order_count']
]);
array_push($result, [
'type' => '佣金金额(已发放)',
'date' => $date,
'value' => $statistic['commission_total'] / 100
];
$result[] = [
'value' => $statistic['commission_amount'] / 100
]);
array_push($result, [
'type' => '佣金笔数(已发放)',
'date' => $date,
'value' => $statistic['commission_count']
];
]);
}
$result = array_reverse($result);
return [
return response([
'data' => $result
];
]);
}
public function getServerLastRank()
{
$servers = [
'shadowsocks' => ServerShadowsocks::where('parent_id', null)->get()->toArray(),
'v2ray' => ServerVmess::where('parent_id', null)->get()->toArray(),
'trojan' => ServerTrojan::where('parent_id', null)->get()->toArray(),
'vmess' => ServerVmess::where('parent_id', null)->get()->toArray()
'vmess' => ServerV2ray::where('parent_id', null)->get()->toArray(),
'trojan' => ServerTrojan::where('parent_id', null)->get()->toArray()
];
$startAt = strtotime('-1 day', strtotime(date('Y-m-d')));
$endAt = strtotime(date('Y-m-d'));
$statistics = StatServer::select([
'server_id',
'server_type',
'u',
'd',
DB::raw('(u+d) as total')
])
'server_id',
'server_type',
'u',
'd',
DB::raw('(u+d) as total')
])
->where('record_at', '>=', $startAt)
->where('record_at', '<', $endAt)
->where('record_type', 'd')
@ -198,28 +119,9 @@ class StatController extends Controller
$statistics[$k]['total'] = $statistics[$k]['total'] / 1073741824;
}
array_multisort(array_column($statistics, 'total'), SORT_DESC, $statistics);
return [
return response([
'data' => $statistics
];
}
public function getStatUser(Request $request)
{
$request->validate([
'user_id' => 'required|integer'
]);
$current = $request->input('current') ? $request->input('current') : 1;
$pageSize = $request->input('pageSize') >= 10 ? $request->input('pageSize') : 10;
$builder = StatUser::orderBy('record_at', 'DESC')->where('user_id', $request->input('user_id'));
$total = $builder->count();
$records = $builder->forPage($current, $pageSize)
->get();
return [
'data' => $records,
'total' => $total
];
}
}

View File

@ -2,39 +2,37 @@
namespace App\Http\Controllers\Admin;
use App\Models\ServerShadowsocks;
use App\Models\ServerTrojan;
use App\Services\ServerService;
use App\Utils\CacheKey;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\ServerGroup;
use App\Models\ServerV2ray;
use App\Models\Plan;
use App\Models\User;
use App\Models\Ticket;
use App\Models\Order;
use App\Models\StatOrder;
use App\Models\StatServer;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Laravel\Horizon\Contracts\JobRepository;
use Laravel\Horizon\Contracts\MasterSupervisorRepository;
use Laravel\Horizon\Contracts\MetricsRepository;
use Laravel\Horizon\Contracts\SupervisorRepository;
use Laravel\Horizon\Contracts\WorkloadRepository;
use Laravel\Horizon\WaitTimeCalculator;
class SystemController extends Controller
{
public function getSystemStatus()
public function getStatus()
{
return response([
'data' => [
'schedule' => $this->getScheduleStatus(),
'horizon' => $this->getHorizonStatus(),
'schedule_last_runtime' => Cache::get(CacheKey::get('SCHEDULE_LAST_CHECK_AT', null))
'horizon' => $this->getHorizonStatus()
]
]);
}
public function getQueueWorkload(WorkloadRepository $workload)
{
return response([
'data' => collect($workload->get())->sortBy('name')->values()->toArray()
]);
}
protected function getScheduleStatus():bool
{
return (time() - 120) < Cache::get(CacheKey::get('SCHEDULE_LAST_CHECK_AT', null));
@ -50,56 +48,5 @@ class SystemController extends Controller
return $master->status === 'paused';
}) ? false : true;
}
public function getQueueStats()
{
return response([
'data' => [
'failedJobs' => app(JobRepository::class)->countRecentlyFailed(),
'jobsPerMinute' => app(MetricsRepository::class)->jobsProcessedPerMinute(),
'pausedMasters' => $this->totalPausedMasters(),
'periods' => [
'failedJobs' => config('horizon.trim.recent_failed', config('horizon.trim.failed')),
'recentJobs' => config('horizon.trim.recent'),
],
'processes' => $this->totalProcessCount(),
'queueWithMaxRuntime' => app(MetricsRepository::class)->queueWithMaximumRuntime(),
'queueWithMaxThroughput' => app(MetricsRepository::class)->queueWithMaximumThroughput(),
'recentJobs' => app(JobRepository::class)->countRecent(),
'status' => $this->getHorizonStatus(),
'wait' => collect(app(WaitTimeCalculator::class)->calculate())->take(1),
]
]);
}
/**
* Get the total process count across all supervisors.
*
* @return int
*/
protected function totalProcessCount()
{
$supervisors = app(SupervisorRepository::class)->all();
return collect($supervisors)->reduce(function ($carry, $supervisor) {
return $carry + collect($supervisor->processes)->sum();
}, 0);
}
/**
* Get the number of master supervisors that are currently paused.
*
* @return int
*/
protected function totalPausedMasters()
{
if (! $masters = app(MasterSupervisorRepository::class)->all()) {
return 0;
}
return collect($masters)->filter(function ($master) {
return $master->status === 'paused';
})->count();
}
}

View File

@ -25,9 +25,9 @@ class ThemeController extends Controller
{
$themeConfigs = [];
foreach ($this->themes as $theme) {
$themeConfigFile = $this->path . "{$theme}/config.json";
$themeConfigFile = $this->path . "{$theme}/config.php";
if (!File::exists($themeConfigFile)) continue;
$themeConfig = json_decode(File::get($themeConfigFile), true);
$themeConfig = include($themeConfigFile);
if (!isset($themeConfig['configs']) || !is_array($themeConfig)) continue;
$themeConfigs[$theme] = $themeConfig;
if (config("theme.{$theme}")) continue;
@ -60,10 +60,9 @@ class ThemeController extends Controller
]);
$payload['config'] = json_decode(base64_decode($payload['config']), true);
if (!$payload['config'] || !is_array($payload['config'])) abort(500, '参数有误');
$themeConfigFile = public_path("theme/{$payload['name']}/config.json");
$themeConfigFile = public_path("theme/{$payload['name']}/config.php");
if (!File::exists($themeConfigFile)) abort(500, '主题不存在');
$themeConfig = json_decode(File::get($themeConfigFile), true);
if (!isset($themeConfig['configs']) || !is_array($themeConfig)) abort(500, '主题配置文件有误');
$themeConfig = include($themeConfigFile);
$validateFields = array_column($themeConfig['configs'], 'field_name');
$config = [];
foreach ($validateFields as $validateField) {

View File

@ -68,7 +68,7 @@ class TicketController extends Controller
$ticketService->replyByAdmin(
$request->input('id'),
$request->input('message'),
$request->user['id']
$request->session()->get('id')
);
return response([
'data' => true

View File

@ -7,7 +7,6 @@ use App\Http\Requests\Admin\UserGenerate;
use App\Http\Requests\Admin\UserSendMail;
use App\Http\Requests\Admin\UserUpdate;
use App\Jobs\SendEmailJob;
use App\Services\AuthService;
use App\Services\UserService;
use App\Utils\Helper;
use Illuminate\Http\Request;
@ -129,11 +128,6 @@ class UserController extends Controller
$params['invite_user_id'] = null;
}
if (isset($params['banned']) && (int)$params['banned'] === 1) {
$authService = new AuthService($user);
$authService->removeAllSession();
}
try {
$user->update($params);
} catch (\Exception $e) {

View File

@ -5,7 +5,9 @@ namespace App\Http\Controllers\Client;
use App\Http\Controllers\Controller;
use App\Services\ServerService;
use App\Services\UserService;
use App\Utils\Clash;
use Illuminate\Http\Request;
use App\Models\ServerV2ray;
use Illuminate\Support\Facades\File;
use Symfony\Component\Yaml\Yaml;
@ -31,18 +33,11 @@ class AppController extends Controller
$proxies = [];
foreach ($servers as $item) {
if ($item['type'] === 'shadowsocks'
&& in_array($item['cipher'], [
'aes-128-gcm',
'aes-192-gcm',
'aes-256-gcm',
'chacha20-ietf-poly1305'
])
) {
if ($item['type'] === 'shadowsocks') {
array_push($proxy, Protocols\Clash::buildShadowsocks($user['uuid'], $item));
array_push($proxies, $item['name']);
}
if ($item['type'] === 'vmess') {
if ($item['type'] === 'v2ray') {
array_push($proxy, Protocols\Clash::buildVmess($user['uuid'], $item));
array_push($proxies, $item['name']);
}

View File

@ -2,10 +2,9 @@
namespace App\Http\Controllers\Client;
use App\Http\Controllers\Client\Protocols\General;
use App\Http\Controllers\Client\Protocols\V2rayN;
use App\Http\Controllers\Controller;
use App\Services\ServerService;
use App\Utils\Helper;
use Illuminate\Http\Request;
use App\Services\UserService;
@ -14,7 +13,9 @@ class ClientController extends Controller
public function subscribe(Request $request)
{
$flag = $request->input('flag')
?? ($_SERVER['HTTP_USER_AGENT'] ?? '');
?? (isset($_SERVER['HTTP_USER_AGENT'])
? $_SERVER['HTTP_USER_AGENT']
: '');
$flag = strtolower($flag);
$user = $request->user;
// account not expired and is not banned.
@ -24,7 +25,7 @@ class ClientController extends Controller
$servers = $serverService->getAvailableServers($user);
$this->setSubscribeInfoToServers($servers, $user);
if ($flag) {
foreach (array_reverse(glob(app_path('Http//Controllers//Client//Protocols') . '/*.php')) as $file) {
foreach (glob(app_path('Http//Controllers//Client//Protocols') . '/*.php') as $file) {
$file = 'App\\Http\\Controllers\\Client\\Protocols\\' . basename($file, '.php');
$class = new $file($user, $servers);
if (strpos($flag, $class->flag) !== false) {
@ -32,18 +33,19 @@ class ClientController extends Controller
}
}
}
$class = new General($user, $servers);
// todo 1.5.3 remove
$class = new V2rayN($user, $servers);
die($class->handle());
die('该客户端暂不支持进行订阅');
}
}
private function setSubscribeInfoToServers(&$servers, $user)
{
if (!isset($servers[0])) return;
if (!(int)config('v2board.show_info_to_server_enable', 0)) return;
$useTraffic = $user['u'] + $user['d'];
$totalTraffic = $user['transfer_enable'];
$remainingTraffic = Helper::trafficConvert($totalTraffic - $useTraffic);
$useTraffic = round($user['u'] / (1024*1024*1024), 2) + round($user['d'] / (1024*1024*1024), 2);
$totalTraffic = round($user['transfer_enable'] / (1024*1024*1024), 2);
$remainingTraffic = $totalTraffic - $useTraffic;
$expiredDate = $user['expired_at'] ? date('Y-m-d', $user['expired_at']) : '长期有效';
$userService = new UserService();
$resetDay = $userService->getResetDay($user);
@ -56,7 +58,7 @@ class ClientController extends Controller
]));
}
array_unshift($servers, array_merge($servers[0], [
'name' => "剩余流量:{$remainingTraffic}",
'name' => "剩余流量:{$remainingTraffic} GB",
]));
}
}

View File

@ -2,8 +2,6 @@
namespace App\Http\Controllers\Client\Protocols;
use App\Utils\Dict;
use phpDocumentor\Reflection\Types\Self_;
use Symfony\Component\Yaml\Yaml;
class Clash
@ -26,7 +24,6 @@ class Clash
header("subscription-userinfo: upload={$user['u']}; download={$user['d']}; total={$user['transfer_enable']}; expire={$user['expired_at']}");
header('profile-update-interval: 24');
header("content-disposition:attachment;filename*=UTF-8''".rawurlencode($appName));
header("profile-web-page-url:" . config('v2board.app_url'));
$defaultConfig = base_path() . '/resources/rules/default.clash.yaml';
$customConfig = base_path() . '/resources/rules/custom.clash.yaml';
if (\File::exists($customConfig)) {
@ -38,18 +35,11 @@ class Clash
$proxies = [];
foreach ($servers as $item) {
if ($item['type'] === 'shadowsocks'
&& in_array($item['cipher'], [
'aes-128-gcm',
'aes-192-gcm',
'aes-256-gcm',
'chacha20-ietf-poly1305'
])
) {
if ($item['type'] === 'shadowsocks') {
array_push($proxy, self::buildShadowsocks($user['uuid'], $item));
array_push($proxies, $item['name']);
}
if ($item['type'] === 'vmess') {
if ($item['type'] === 'v2ray') {
array_push($proxy, self::buildVmess($user['uuid'], $item));
array_push($proxies, $item['name']);
}
@ -77,18 +67,12 @@ class Clash
if ($isFilter) continue;
$config['proxy-groups'][$k]['proxies'] = array_merge($config['proxy-groups'][$k]['proxies'], $proxies);
}
$config['proxy-groups'] = array_filter($config['proxy-groups'], function($group) {
return $group['proxies'];
});
$config['proxy-groups'] = array_values($config['proxy-groups']);
// Force the current subscription domain to be a direct rule
$subsDomain = $_SERVER['HTTP_HOST'];
if ($subsDomain) {
array_unshift($config['rules'], "DOMAIN,{$subsDomain},DIRECT");
}
$subsDomain = $_SERVER['SERVER_NAME'];
$subsDomainRule = "DOMAIN,{$subsDomain},DIRECT";
array_unshift($config['rules'], $subsDomainRule);
$yaml = Yaml::dump($config, 2, 4, Yaml::DUMP_EMPTY_ARRAY_AS_SEQUENCE);
$yaml = Yaml::dump($config);
$yaml = str_replace('$app_name', config('v2board.app_name', 'V2Board'), $yaml);
return $yaml;
}
@ -128,11 +112,6 @@ class Clash
$array['servername'] = $tlsSettings['serverName'];
}
}
if ($server['network'] === 'tcp') {
$tcpSettings = $server['networkSettings'];
if (isset($tcpSettings['header']['type'])) $array['network'] = $tcpSettings['header']['type'];
if (isset($tcpSettings['header']['request']['path'][0])) $array['http-opts']['path'] = $tcpSettings['header']['request']['path'][0];
}
if ($server['network'] === 'ws') {
$array['network'] = 'ws';
if ($server['networkSettings']) {
@ -142,6 +121,7 @@ class Clash
$array['ws-opts']['path'] = $wsSettings['path'];
if (isset($wsSettings['headers']['Host']) && !empty($wsSettings['headers']['Host']))
$array['ws-opts']['headers'] = ['Host' => $wsSettings['headers']['Host']];
// TODO: 2022.06.01 remove it
if (isset($wsSettings['path']) && !empty($wsSettings['path']))
$array['ws-path'] = $wsSettings['path'];
if (isset($wsSettings['headers']['Host']) && !empty($wsSettings['headers']['Host']))

View File

@ -1,186 +0,0 @@
<?php
namespace App\Http\Controllers\Client\Protocols;
use App\Utils\Helper;
use Symfony\Component\Yaml\Yaml;
class ClashMeta
{
public $flag = 'meta';
private $servers;
private $user;
public function __construct($user, $servers)
{
$this->user = $user;
$this->servers = $servers;
}
public function handle()
{
$servers = $this->servers;
$user = $this->user;
$appName = config('v2board.app_name', 'V2Board');
header("subscription-userinfo: upload={$user['u']}; download={$user['d']}; total={$user['transfer_enable']}; expire={$user['expired_at']}");
header('profile-update-interval: 24');
header("content-disposition:attachment;filename*=UTF-8''".rawurlencode($appName));
$defaultConfig = base_path() . '/resources/rules/default.clash.yaml';
$customConfig = base_path() . '/resources/rules/custom.clash.yaml';
if (\File::exists($customConfig)) {
$config = Yaml::parseFile($customConfig);
} else {
$config = Yaml::parseFile($defaultConfig);
}
$proxy = [];
$proxies = [];
foreach ($servers as $item) {
if ($item['type'] === 'shadowsocks') {
array_push($proxy, self::buildShadowsocks($user['uuid'], $item));
array_push($proxies, $item['name']);
}
if ($item['type'] === 'vmess') {
array_push($proxy, self::buildVmess($user['uuid'], $item));
array_push($proxies, $item['name']);
}
if ($item['type'] === 'trojan') {
array_push($proxy, self::buildTrojan($user['uuid'], $item));
array_push($proxies, $item['name']);
}
}
$config['proxies'] = array_merge($config['proxies'] ? $config['proxies'] : [], $proxy);
foreach ($config['proxy-groups'] as $k => $v) {
if (!is_array($config['proxy-groups'][$k]['proxies'])) $config['proxy-groups'][$k]['proxies'] = [];
$isFilter = false;
foreach ($config['proxy-groups'][$k]['proxies'] as $src) {
foreach ($proxies as $dst) {
if (!$this->isRegex($src)) continue;
$isFilter = true;
$config['proxy-groups'][$k]['proxies'] = array_values(array_diff($config['proxy-groups'][$k]['proxies'], [$src]));
if ($this->isMatch($src, $dst)) {
array_push($config['proxy-groups'][$k]['proxies'], $dst);
}
}
if ($isFilter) continue;
}
if ($isFilter) continue;
$config['proxy-groups'][$k]['proxies'] = array_merge($config['proxy-groups'][$k]['proxies'], $proxies);
}
$config['proxy-groups'] = array_filter($config['proxy-groups'], function($group) {
return $group['proxies'];
});
$config['proxy-groups'] = array_values($config['proxy-groups']);
// Force the current subscription domain to be a direct rule
$subsDomain = $_SERVER['HTTP_HOST'];
if ($subsDomain) {
array_unshift($config['rules'], "DOMAIN,{$subsDomain},DIRECT");
}
$yaml = Yaml::dump($config, 2, 4, Yaml::DUMP_EMPTY_ARRAY_AS_SEQUENCE);
$yaml = str_replace('$app_name', config('v2board.app_name', 'V2Board'), $yaml);
return $yaml;
}
public static function buildShadowsocks($password, $server)
{
if ($server['cipher'] === '2022-blake3-aes-128-gcm') {
$serverKey = Helper::getServerKey($server['created_at'], 16);
$userKey = Helper::uuidToBase64($password, 16);
$password = "{$serverKey}:{$userKey}";
}
if ($server['cipher'] === '2022-blake3-aes-256-gcm') {
$serverKey = Helper::getServerKey($server['created_at'], 32);
$userKey = Helper::uuidToBase64($password, 32);
$password = "{$serverKey}:{$userKey}";
}
$array = [];
$array['name'] = $server['name'];
$array['type'] = 'ss';
$array['server'] = $server['host'];
$array['port'] = $server['port'];
$array['cipher'] = $server['cipher'];
$array['password'] = $password;
$array['udp'] = true;
return $array;
}
public static function buildVmess($uuid, $server)
{
$array = [];
$array['name'] = $server['name'];
$array['type'] = 'vmess';
$array['server'] = $server['host'];
$array['port'] = $server['port'];
$array['uuid'] = $uuid;
$array['alterId'] = 0;
$array['cipher'] = 'auto';
$array['udp'] = true;
if ($server['tls']) {
$array['tls'] = true;
if ($server['tlsSettings']) {
$tlsSettings = $server['tlsSettings'];
if (isset($tlsSettings['allowInsecure']) && !empty($tlsSettings['allowInsecure']))
$array['skip-cert-verify'] = ($tlsSettings['allowInsecure'] ? true : false);
if (isset($tlsSettings['serverName']) && !empty($tlsSettings['serverName']))
$array['servername'] = $tlsSettings['serverName'];
}
}
if ($server['network'] === 'tcp') {
$tcpSettings = $server['networkSettings'];
if (isset($tcpSettings['header']['type'])) $array['network'] = $tcpSettings['header']['type'];
if (isset($tcpSettings['header']['request']['path'][0])) $array['http-opts']['path'] = $tcpSettings['header']['request']['path'][0];
}
if ($server['network'] === 'ws') {
$array['network'] = 'ws';
if ($server['networkSettings']) {
$wsSettings = $server['networkSettings'];
$array['ws-opts'] = [];
if (isset($wsSettings['path']) && !empty($wsSettings['path']))
$array['ws-opts']['path'] = $wsSettings['path'];
if (isset($wsSettings['headers']['Host']) && !empty($wsSettings['headers']['Host']))
$array['ws-opts']['headers'] = ['Host' => $wsSettings['headers']['Host']];
if (isset($wsSettings['path']) && !empty($wsSettings['path']))
$array['ws-path'] = $wsSettings['path'];
if (isset($wsSettings['headers']['Host']) && !empty($wsSettings['headers']['Host']))
$array['ws-headers'] = ['Host' => $wsSettings['headers']['Host']];
}
}
if ($server['network'] === 'grpc') {
$array['network'] = 'grpc';
if ($server['networkSettings']) {
$grpcSettings = $server['networkSettings'];
$array['grpc-opts'] = [];
if (isset($grpcSettings['serviceName'])) $array['grpc-opts']['grpc-service-name'] = $grpcSettings['serviceName'];
}
}
return $array;
}
public static function buildTrojan($password, $server)
{
$array = [];
$array['name'] = $server['name'];
$array['type'] = 'trojan';
$array['server'] = $server['host'];
$array['port'] = $server['port'];
$array['password'] = $password;
$array['udp'] = true;
if (!empty($server['server_name'])) $array['sni'] = $server['server_name'];
if (!empty($server['allow_insecure'])) $array['skip-cert-verify'] = ($server['allow_insecure'] ? true : false);
return $array;
}
private function isMatch($exp, $str)
{
return @preg_match($exp, $str);
}
private function isRegex($exp)
{
return @preg_match($exp, null) !== false;
}
}

View File

@ -1,113 +0,0 @@
<?php
namespace App\Http\Controllers\Client\Protocols;
use App\Utils\Helper;
class General
{
public $flag = 'general';
private $servers;
private $user;
public function __construct($user, $servers)
{
$this->user = $user;
$this->servers = $servers;
}
public function handle()
{
$servers = $this->servers;
$user = $this->user;
$uri = '';
foreach ($servers as $item) {
if ($item['type'] === 'vmess') {
$uri .= self::buildVmess($user['uuid'], $item);
}
if ($item['type'] === 'shadowsocks') {
$uri .= self::buildShadowsocks($user['uuid'], $item);
}
if ($item['type'] === 'trojan') {
$uri .= self::buildTrojan($user['uuid'], $item);
}
}
return base64_encode($uri);
}
public static function buildShadowsocks($password, $server)
{
if ($server['cipher'] === '2022-blake3-aes-128-gcm') {
$serverKey = Helper::getServerKey($server['created_at'], 16);
$userKey = Helper::uuidToBase64($password, 16);
$password = "{$serverKey}:{$userKey}";
}
if ($server['cipher'] === '2022-blake3-aes-256-gcm') {
$serverKey = Helper::getServerKey($server['created_at'], 32);
$userKey = Helper::uuidToBase64($password, 32);
$password = "{$serverKey}:{$userKey}";
}
$name = rawurlencode($server['name']);
$str = str_replace(
['+', '/', '='],
['-', '_', ''],
base64_encode("{$server['cipher']}:{$password}")
);
return "ss://{$str}@{$server['host']}:{$server['port']}#{$name}\r\n";
}
public static function buildVmess($uuid, $server)
{
$config = [
"v" => "2",
"ps" => $server['name'],
"add" => $server['host'],
"port" => (string)$server['port'],
"id" => $uuid,
"aid" => '0',
"net" => $server['network'],
"type" => "none",
"host" => "",
"path" => "",
"tls" => $server['tls'] ? "tls" : "",
];
if ($server['tls']) {
if ($server['tlsSettings']) {
$tlsSettings = $server['tlsSettings'];
if (isset($tlsSettings['serverName']) && !empty($tlsSettings['serverName']))
$config['sni'] = $tlsSettings['serverName'];
}
}
if ((string)$server['network'] === 'tcp') {
$tcpSettings = $server['networkSettings'];
if (isset($tcpSettings['header']['type'])) $config['type'] = $tcpSettings['header']['type'];
if (isset($tcpSettings['header']['request']['path'][0])) $config['path'] = $tcpSettings['header']['request']['path'][0];
}
if ((string)$server['network'] === 'ws') {
$wsSettings = $server['networkSettings'];
if (isset($wsSettings['path'])) $config['path'] = $wsSettings['path'];
if (isset($wsSettings['headers']['Host'])) $config['host'] = $wsSettings['headers']['Host'];
}
if ((string)$server['network'] === 'grpc') {
$grpcSettings = $server['networkSettings'];
if (isset($grpcSettings['serviceName'])) $config['path'] = $grpcSettings['serviceName'];
}
return "vmess://" . base64_encode(json_encode($config)) . "\r\n";
}
public static function buildTrojan($password, $server)
{
$name = rawurlencode($server['name']);
$query = http_build_query([
'allowInsecure' => $server['allow_insecure'],
'peer' => $server['server_name'],
'sni' => $server['server_name']
]);
$uri = "trojan://{$password}@{$server['host']}:{$server['port']}?{$query}#{$name}";
$uri .= "\r\n";
return $uri;
}
}

View File

@ -1,137 +0,0 @@
<?php
namespace App\Http\Controllers\Client\Protocols;
use App\Utils\Helper;
class Loon
{
public $flag = 'loon';
private $servers;
private $user;
public function __construct($user, $servers)
{
$this->user = $user;
$this->servers = $servers;
}
public function handle()
{
$servers = $this->servers;
$user = $this->user;
$uri = '';
header("Subscription-Userinfo: upload={$user['u']}; download={$user['d']}; total={$user['transfer_enable']}; expire={$user['expired_at']}");
foreach ($servers as $item) {
if ($item['type'] === 'shadowsocks'
&& in_array($item['cipher'], [
'aes-128-gcm',
'aes-192-gcm',
'aes-256-gcm',
'chacha20-ietf-poly1305'
])
) {
$uri .= self::buildShadowsocks($user['uuid'], $item);
}
if ($item['type'] === 'vmess') {
$uri .= self::buildVmess($user['uuid'], $item);
}
if ($item['type'] === 'trojan') {
$uri .= self::buildTrojan($user['uuid'], $item);
}
}
return $uri;
}
public static function buildShadowsocks($password, $server)
{
$config = [
"{$server['name']}=Shadowsocks",
"{$server['host']}",
"{$server['port']}",
"{$server['cipher']}",
"{$password}",
'fast-open=false',
'udp=true'
];
$config = array_filter($config);
$uri = implode(',', $config);
$uri .= "\r\n";
return $uri;
}
public static function buildVmess($uuid, $server)
{
$config = [
"{$server['name']}=vmess",
"{$server['host']}",
"{$server['port']}",
'auto',
"{$uuid}",
'fast-open=false',
'udp=true',
"alterId=0"
];
if ($server['network'] === 'tcp') {
array_push($config, 'transport=tcp');
if ($server['networkSettings']) {
$tcpSettings = $server['networkSettings'];
if (isset($tcpSettings['header']['type']) && !empty($tcpSettings['header']['type']))
$config = str_replace('transport=tcp', "transport={$tcpSettings['header']['type']}", $config);
if (isset($tcpSettings['header']['request']['path'][0]) && !empty($tcpSettings['header']['request']['path'][0]))
array_push($config, "path={$tcpSettings['header']['request']['path'][0]}");
if (isset($tcpSettings['header']['Host']) && !empty($tcpSettings['header']['Host']))
array_push($config, "host={$tcpSettings['header']['Host']}");
}
}
if ($server['tls']) {
if ($server['network'] === 'tcp')
array_push($config, 'over-tls=true');
if ($server['tlsSettings']) {
$tlsSettings = $server['tlsSettings'];
if (isset($tlsSettings['allowInsecure']) && !empty($tlsSettings['allowInsecure']))
array_push($config, 'skip-cert-verify=' . ($tlsSettings['allowInsecure'] ? 'true' : 'false'));
if (isset($tlsSettings['serverName']) && !empty($tlsSettings['serverName']))
array_push($config, "tls-name={$tlsSettings['serverName']}");
}
}
if ($server['network'] === 'ws') {
array_push($config, 'transport=ws');
if ($server['networkSettings']) {
$wsSettings = $server['networkSettings'];
if (isset($wsSettings['path']) && !empty($wsSettings['path']))
array_push($config, "path={$wsSettings['path']}");
if (isset($wsSettings['headers']['Host']) && !empty($wsSettings['headers']['Host']))
array_push($config, "host={$wsSettings['headers']['Host']}");
}
}
$uri = implode(',', $config);
$uri .= "\r\n";
return $uri;
}
public static function buildTrojan($password, $server)
{
$config = [
"{$server['name']}=trojan",
"{$server['host']}",
"{$server['port']}",
"{$password}",
$server['server_name'] ? "tls-name={$server['server_name']}" : "",
'fast-open=false',
'udp=true'
];
if (!empty($server['allow_insecure'])) {
array_push($config, $server['allow_insecure'] ? 'skip-cert-verify=true' : 'skip-cert-verify=false');
}
$config = array_filter($config);
$uri = implode(',', $config);
$uri .= "\r\n";
return $uri;
}
}

View File

@ -22,7 +22,7 @@ class Passwall
$uri = '';
foreach ($servers as $item) {
if ($item['type'] === 'vmess') {
if ($item['type'] === 'v2ray') {
$uri .= self::buildVmess($user['uuid'], $item);
}
if ($item['type'] === 'shadowsocks') {
@ -68,11 +68,6 @@ class Passwall
$config['sni'] = $tlsSettings['serverName'];
}
}
if ((string)$server['network'] === 'tcp') {
$tcpSettings = $server['networkSettings'];
if (isset($tcpSettings['header']['type'])) $config['type'] = $tcpSettings['header']['type'];
if (isset($tcpSettings['header']['request']['path'][0])) $config['path'] = $tcpSettings['header']['request']['path'][0];
}
if ((string)$server['network'] === 'ws') {
$wsSettings = $server['networkSettings'];
if (isset($wsSettings['path'])) $config['path'] = $wsSettings['path'];

View File

@ -25,7 +25,7 @@ class QuantumultX
if ($item['type'] === 'shadowsocks') {
$uri .= self::buildShadowsocks($user['uuid'], $item);
}
if ($item['type'] === 'vmess') {
if ($item['type'] === 'v2ray') {
$uri .= self::buildVmess($user['uuid'], $item);
}
if ($item['type'] === 'trojan') {

View File

@ -22,7 +22,7 @@ class SSRPlus
$uri = '';
foreach ($servers as $item) {
if ($item['type'] === 'vmess') {
if ($item['type'] === 'v2ray') {
$uri .= self::buildVmess($user['uuid'], $item);
}
if ($item['type'] === 'shadowsocks') {

View File

@ -21,7 +21,7 @@ class SagerNet
$uri = '';
foreach ($servers as $item) {
if ($item['type'] === 'vmess') {
if ($item['type'] === 'v2ray') {
$uri .= self::buildVmess($user['uuid'], $item);
}
if ($item['type'] === 'shadowsocks') {
@ -72,11 +72,6 @@ class SagerNet
$config['sni'] = urlencode($tlsSettings['serverName']);
}
}
if ((string)$server['network'] === 'tcp') {
$tcpSettings = $server['networkSettings'];
if (isset($tcpSettings['header']['type'])) $config['type'] = $tcpSettings['header']['type'];
if (isset($tcpSettings['header']['request']['path'][0])) $config['path'] = $tcpSettings['header']['request']['path'][0];
}
if ((string)$server['network'] === 'ws') {
$wsSettings = $server['networkSettings'];
if (isset($wsSettings['path'])) $config['path'] = $wsSettings['path'];

View File

@ -2,8 +2,6 @@
namespace App\Http\Controllers\Client\Protocols;
use App\Utils\Helper;
class Shadowrocket
{
public $flag = 'shadowrocket';
@ -32,7 +30,7 @@ class Shadowrocket
if ($item['type'] === 'shadowsocks') {
$uri .= self::buildShadowsocks($user['uuid'], $item);
}
if ($item['type'] === 'vmess') {
if ($item['type'] === 'v2ray') {
$uri .= self::buildVmess($user['uuid'], $item);
}
if ($item['type'] === 'trojan') {
@ -45,16 +43,6 @@ class Shadowrocket
public static function buildShadowsocks($password, $server)
{
if ($server['cipher'] === '2022-blake3-aes-128-gcm') {
$serverKey = Helper::getServerKey($server['created_at'], 16);
$userKey = Helper::uuidToBase64($password, 16);
$password = "{$serverKey}:{$userKey}";
}
if ($server['cipher'] === '2022-blake3-aes-256-gcm') {
$serverKey = Helper::getServerKey($server['created_at'], 32);
$userKey = Helper::uuidToBase64($password, 32);
$password = "{$serverKey}:{$userKey}";
}
$name = rawurlencode($server['name']);
$str = str_replace(
['+', '/', '='],
@ -82,15 +70,6 @@ class Shadowrocket
$config['peer'] = $tlsSettings['serverName'];
}
}
if ($server['network'] === 'tcp') {
if ($server['networkSettings']) {
$tcpSettings = $server['networkSettings'];
if (isset($tcpSettings['header']['type']) && !empty($tcpSettings['header']['type']))
$config['obfs'] = $tcpSettings['header']['type'];
if (isset($tcpSettings['header']['request']['path'][0]) && !empty($tcpSettings['header']['request']['path'][0]))
$config['path'] = $tcpSettings['header']['request']['path'][0];
}
}
if ($server['network'] === 'ws') {
$config['obfs'] = "websocket";
if ($server['networkSettings']) {

View File

@ -29,9 +29,7 @@ class Shadowsocks
$bytesRemaining = $user['transfer_enable'] - $bytesUsed;
foreach ($servers as $item) {
if ($item['type'] === 'shadowsocks'
&& in_array($item['cipher'], ['aes-128-gcm', 'aes-256-gcm', 'aes-192-gcm', 'chacha20-ietf-poly1305'])
) {
if ($item['type'] === 'shadowsocks') {
array_push($configs, self::SIP008($item, $user));
}
}

View File

@ -36,18 +36,11 @@ class Stash
$proxies = [];
foreach ($servers as $item) {
if ($item['type'] === 'shadowsocks'
&& in_array($item['cipher'], [
'aes-128-gcm',
'aes-192-gcm',
'aes-256-gcm',
'chacha20-ietf-poly1305'
])
) {
if ($item['type'] === 'shadowsocks') {
array_push($proxy, self::buildShadowsocks($user['uuid'], $item));
array_push($proxies, $item['name']);
}
if ($item['type'] === 'vmess') {
if ($item['type'] === 'v2ray') {
array_push($proxy, self::buildVmess($user['uuid'], $item));
array_push($proxies, $item['name']);
}
@ -75,17 +68,12 @@ class Stash
if ($isFilter) continue;
$config['proxy-groups'][$k]['proxies'] = array_merge($config['proxy-groups'][$k]['proxies'], $proxies);
}
$config['proxy-groups'] = array_filter($config['proxy-groups'], function($group) {
return $group['proxies'];
});
$config['proxy-groups'] = array_values($config['proxy-groups']);
// Force the current subscription domain to be a direct rule
$subsDomain = $_SERVER['HTTP_HOST'];
if ($subsDomain) {
array_unshift($config['rules'], "DOMAIN,{$subsDomain},DIRECT");
}
$subsDomain = $_SERVER['SERVER_NAME'];
$subsDomainRule = "DOMAIN,{$subsDomain},DIRECT";
array_unshift($config['rules'], $subsDomainRule);
$yaml = Yaml::dump($config, 2, 4, Yaml::DUMP_EMPTY_ARRAY_AS_SEQUENCE);
$yaml = Yaml::dump($config);
$yaml = str_replace('$app_name', config('v2board.app_name', 'V2Board'), $yaml);
return $yaml;
}
@ -125,11 +113,6 @@ class Stash
$array['servername'] = $tlsSettings['serverName'];
}
}
if ($server['network'] === 'tcp') {
$tcpSettings = $server['networkSettings'];
if (isset($tcpSettings['header']['type'])) $array['network'] = $tcpSettings['header']['type'];
if (isset($tcpSettings['header']['request']['path'][0])) $array['http-opts']['path'] = $tcpSettings['header']['request']['path'][0];
}
if ($server['network'] === 'ws') {
$array['network'] = 'ws';
if ($server['networkSettings']) {
@ -139,6 +122,7 @@ class Stash
$array['ws-opts']['path'] = $wsSettings['path'];
if (isset($wsSettings['headers']['Host']) && !empty($wsSettings['headers']['Host']))
$array['ws-opts']['headers'] = ['Host' => $wsSettings['headers']['Host']];
// TODO: 2022.06.01 remove it
if (isset($wsSettings['path']) && !empty($wsSettings['path']))
$array['ws-path'] = $wsSettings['path'];
if (isset($wsSettings['headers']['Host']) && !empty($wsSettings['headers']['Host']))
@ -171,11 +155,6 @@ class Stash
return $array;
}
private function isRegex($exp)
{
return @preg_match($exp, null) !== false;
}
private function isMatch($exp, $str)
{
try {

View File

@ -21,27 +21,17 @@ class Surfboard
$servers = $this->servers;
$user = $this->user;
$appName = config('v2board.app_name', 'V2Board');
header("content-disposition:attachment;filename*=UTF-8''".rawurlencode($appName).".conf");
$proxies = '';
$proxyGroup = '';
foreach ($servers as $item) {
if ($item['type'] === 'shadowsocks'
&& in_array($item['cipher'], [
'aes-128-gcm',
'aes-192-gcm',
'aes-256-gcm',
'chacha20-ietf-poly1305'
])
) {
if ($item['type'] === 'shadowsocks') {
// [Proxy]
$proxies .= self::buildShadowsocks($user['uuid'], $item);
// [Proxy Group]
$proxyGroup .= $item['name'] . ', ';
}
if ($item['type'] === 'vmess') {
if ($item['type'] === 'v2ray') {
// [Proxy]
$proxies .= self::buildVmess($user['uuid'], $item);
// [Proxy Group]
@ -65,21 +55,12 @@ class Surfboard
// Subscription link
$subsURL = Helper::getSubscribeUrl("/api/v1/client/subscribe?token={$user['token']}");
$subsDomain = $_SERVER['HTTP_HOST'];
$subsDomain = $_SERVER['SERVER_NAME'];
$config = str_replace('$subs_link', $subsURL, $config);
$config = str_replace('$subs_domain', $subsDomain, $config);
$config = str_replace('$proxies', $proxies, $config);
$config = str_replace('$proxy_group', rtrim($proxyGroup, ', '), $config);
$upload = round($user['u'] / (1024*1024*1024), 2);
$download = round($user['d'] / (1024*1024*1024), 2);
$useTraffic = $upload + $download;
$totalTraffic = round($user['transfer_enable'] / (1024*1024*1024), 2);
$expireDate = $user['expired_at'] === NULL ? '长期有效' : date('Y-m-d H:i:s', $user['expired_at']);
$subscribeInfo = "title={$appName}订阅信息, content=上传流量:{$upload}GB\\n下载流量{$download}GB\\n剩余流量{$useTraffic}GB\\n套餐流量{$totalTraffic}GB\\n到期时间{$expireDate}";
$config = str_replace('$subscribe_info', $subscribeInfo, $config);
return $config;
}

View File

@ -21,27 +21,17 @@ class Surge
$servers = $this->servers;
$user = $this->user;
$appName = config('v2board.app_name', 'V2Board');
header("content-disposition:attachment;filename*=UTF-8''".rawurlencode($appName).".conf");
$proxies = '';
$proxyGroup = '';
foreach ($servers as $item) {
if ($item['type'] === 'shadowsocks'
&& in_array($item['cipher'], [
'aes-128-gcm',
'aes-192-gcm',
'aes-256-gcm',
'chacha20-ietf-poly1305'
])
) {
if ($item['type'] === 'shadowsocks') {
// [Proxy]
$proxies .= self::buildShadowsocks($user['uuid'], $item);
// [Proxy Group]
$proxyGroup .= $item['name'] . ', ';
}
if ($item['type'] === 'vmess') {
if ($item['type'] === 'v2ray') {
// [Proxy]
$proxies .= self::buildVmess($user['uuid'], $item);
// [Proxy Group]
@ -65,22 +55,13 @@ class Surge
// Subscription link
$subsURL = Helper::getSubscribeUrl("/api/v1/client/subscribe?token={$user['token']}");
$subsDomain = $_SERVER['HTTP_HOST'];
$subsDomain = $_SERVER['SERVER_NAME'];
$subsURL = 'https://' . $subsDomain . '/api/v1/client/subscribe?token=' . $user['token'];
$config = str_replace('$subs_link', $subsURL, $config);
$config = str_replace('$subs_domain', $subsDomain, $config);
$config = str_replace('$proxies', $proxies, $config);
$config = str_replace('$proxy_group', rtrim($proxyGroup, ', '), $config);
$upload = round($user['u'] / (1024*1024*1024), 2);
$download = round($user['d'] / (1024*1024*1024), 2);
$useTraffic = $upload + $download;
$totalTraffic = round($user['transfer_enable'] / (1024*1024*1024), 2);
$expireDate = $user['expired_at'] === NULL ? '长期有效' : date('Y-m-d H:i:s', $user['expired_at']);
$subscribeInfo = "title={$appName}订阅信息, content=上传流量:{$upload}GB\\n下载流量{$download}GB\\n剩余流量{$useTraffic}GB\\n套餐流量{$totalTraffic}GB\\n到期时间{$expireDate}";
$config = str_replace('$subscribe_info', $subscribeInfo, $config);
return $config;
}

View File

@ -3,8 +3,6 @@
namespace App\Http\Controllers\Client\Protocols;
use App\Utils\Helper;
class V2rayN
{
public $flag = 'v2rayn';
@ -24,7 +22,7 @@ class V2rayN
$uri = '';
foreach ($servers as $item) {
if ($item['type'] === 'vmess') {
if ($item['type'] === 'v2ray') {
$uri .= self::buildVmess($user['uuid'], $item);
}
if ($item['type'] === 'shadowsocks') {
@ -39,16 +37,6 @@ class V2rayN
public static function buildShadowsocks($password, $server)
{
if ($server['cipher'] === '2022-blake3-aes-128-gcm') {
$serverKey = Helper::getServerKey($server['created_at'], 16);
$userKey = Helper::uuidToBase64($password, 16);
$password = "{$serverKey}:{$userKey}";
}
if ($server['cipher'] === '2022-blake3-aes-256-gcm') {
$serverKey = Helper::getServerKey($server['created_at'], 32);
$userKey = Helper::uuidToBase64($password, 32);
$password = "{$serverKey}:{$userKey}";
}
$name = rawurlencode($server['name']);
$str = str_replace(
['+', '/', '='],
@ -80,11 +68,6 @@ class V2rayN
$config['sni'] = $tlsSettings['serverName'];
}
}
if ((string)$server['network'] === 'tcp') {
$tcpSettings = $server['networkSettings'];
if (isset($tcpSettings['header']['type'])) $config['type'] = $tcpSettings['header']['type'];
if (isset($tcpSettings['header']['request']['path'][0])) $config['path'] = $tcpSettings['header']['request']['path'][0];
}
if ((string)$server['network'] === 'ws') {
$wsSettings = $server['networkSettings'];
if (isset($wsSettings['path'])) $config['path'] = $wsSettings['path'];

View File

@ -22,7 +22,7 @@ class V2rayNG
$uri = '';
foreach ($servers as $item) {
if ($item['type'] === 'vmess') {
if ($item['type'] === 'v2ray') {
$uri .= self::buildVmess($user['uuid'], $item);
}
if ($item['type'] === 'shadowsocks') {
@ -68,11 +68,6 @@ class V2rayNG
$config['sni'] = $tlsSettings['serverName'];
}
}
if ((string)$server['network'] === 'tcp') {
$tcpSettings = $server['networkSettings'];
if (isset($tcpSettings['header']['type'])) $config['type'] = $tcpSettings['header']['type'];
if (isset($tcpSettings['header']['request']['path'][0])) $config['path'] = $tcpSettings['header']['request']['path'][0];
}
if ((string)$server['network'] === 'ws') {
$wsSettings = $server['networkSettings'];
if (isset($wsSettings['path'])) $config['path'] = $wsSettings['path'];

View File

@ -10,28 +10,25 @@ class TelegramController extends Controller
{
protected $msg;
protected $commands = [];
protected $telegramService;
public function __construct(Request $request)
{
if ($request->input('access_token') !== md5(config('v2board.telegram_bot_token'))) {
abort(401);
}
$this->telegramService = new TelegramService();
}
public function webhook(Request $request)
{
$this->formatMessage($request->input());
$this->formatChatJoinRequest($request->input());
$this->msg = $this->getMessage($request->input());
if (!$this->msg) return;
$this->handle();
}
public function handle()
{
if (!$this->msg) return;
$msg = $this->msg;
$commandName = explode('@', $msg->command);
// To reduce request, only commands contains @ will get the bot name
@ -62,62 +59,34 @@ class TelegramController extends Controller
}
}
} catch (\Exception $e) {
$this->telegramService->sendMessage($msg->chat_id, $e->getMessage());
$telegramService = new TelegramService();
$telegramService->sendMessage($msg->chat_id, $e->getMessage());
}
}
public function getBotName()
{
$response = $this->telegramService->getMe();
$telegramService = new TelegramService();
$response = $telegramService->getMe();
return $response->result->username;
}
private function formatMessage(array $data)
private function getMessage(array $data)
{
if (!isset($data['message'])) return;
if (!isset($data['message']['text'])) return;
if (!isset($data['message'])) return false;
$obj = new \StdClass();
if (!isset($data['message']['text'])) return false;
$text = explode(' ', $data['message']['text']);
$obj->command = $text[0];
$obj->args = array_slice($text, 1);
$obj->chat_id = $data['message']['chat']['id'];
$obj->message_id = $data['message']['message_id'];
$obj->message_type = 'message';
$obj->message_type = !isset($data['message']['reply_to_message']['text']) ? 'message' : 'reply_message';
$obj->text = $data['message']['text'];
$obj->is_private = $data['message']['chat']['type'] === 'private';
if (isset($data['message']['reply_to_message']['text'])) {
$obj->message_type = 'reply_message';
if ($obj->message_type === 'reply_message') {
$obj->reply_text = $data['message']['reply_to_message']['text'];
}
$this->msg = $obj;
}
private function formatChatJoinRequest(array $data)
{
if (!isset($data['chat_join_request'])) return;
if (!isset($data['chat_join_request']['from']['id'])) return;
if (!isset($data['chat_join_request']['chat']['id'])) return;
$user = \App\Models\User::where('telegram_id', $data['chat_join_request']['from']['id'])
->first();
if (!$user) {
$this->telegramService->declineChatJoinRequest(
$data['chat_join_request']['chat']['id'],
$data['chat_join_request']['from']['id']
);
return;
}
$userService = new \App\Services\UserService();
if (!$userService->isAvailable($user)) {
$this->telegramService->declineChatJoinRequest(
$data['chat_join_request']['chat']['id'],
$data['chat_join_request']['from']['id']
);
return;
}
$userService = new \App\Services\UserService();
$this->telegramService->approveChatJoinRequest(
$data['chat_join_request']['chat']['id'],
$data['chat_join_request']['from']['id']
);
return $obj;
}
}

View File

@ -6,8 +6,6 @@ use App\Http\Controllers\Controller;
use App\Http\Requests\Passport\AuthRegister;
use App\Http\Requests\Passport\AuthForget;
use App\Http\Requests\Passport\AuthLogin;
use App\Jobs\SendEmailJob;
use App\Services\AuthService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use App\Models\Plan;
@ -20,67 +18,12 @@ use ReCaptcha\ReCaptcha;
class AuthController extends Controller
{
public function loginWithMailLink(Request $request)
{
if (!(int)config('v2board.login_with_mail_link_enable')) {
abort(404);
}
$params = $request->validate([
'email' => 'required|email:strict',
'redirect' => 'nullable'
]);
if (Cache::get(CacheKey::get('LAST_SEND_LOGIN_WITH_MAIL_LINK_TIMESTAMP', $params['email']))) {
abort(500, __('Sending frequently, please try again later'));
}
$user = User::where('email', $params['email'])->first();
if (!$user) {
return response([
'data' => true
]);
}
$code = Helper::guid();
$key = CacheKey::get('TEMP_TOKEN', $code);
Cache::put($key, $user->id, 300);
Cache::put(CacheKey::get('LAST_SEND_LOGIN_WITH_MAIL_LINK_TIMESTAMP', $params['email']), time(), 60);
$redirect = '/#/login?verify=' . $code . '&redirect=' . ($request->input('redirect') ? $request->input('redirect') : 'dashboard');
if (config('v2board.app_url')) {
$link = config('v2board.app_url') . $redirect;
} else {
$link = url($redirect);
}
SendEmailJob::dispatch([
'email' => $user->email,
'subject' => __('Login to :name', [
'name' => config('v2board.app_name', 'V2Board')
]),
'template_name' => 'login',
'template_value' => [
'name' => config('v2board.app_name', 'V2Board'),
'link' => $link,
'url' => config('v2board.app_url')
]
]);
return response([
'data' => $link
]);
}
public function register(AuthRegister $request)
{
if ((int)config('v2board.register_limit_by_ip_enable', 0)) {
$registerCountByIP = Cache::get(CacheKey::get('REGISTER_IP_RATE_LIMIT', $request->ip())) ?? 0;
if ((int)$registerCountByIP >= (int)config('v2board.register_limit_count', 3)) {
abort(500, __('Register frequently, please try again after :minute minute', [
'minute' => config('v2board.register_limit_expire', 60)
]));
abort(500, __('Register frequently, please try again after 1 hour'));
}
}
if ((int)config('v2board.recaptcha_enable', 0)) {
@ -116,7 +59,7 @@ class AuthController extends Controller
if (empty($request->input('email_code'))) {
abort(500, __('Email verification code cannot be empty'));
}
if ((string)Cache::get(CacheKey::get('EMAIL_VERIFY_CODE', $request->input('email'))) !== (string)$request->input('email_code')) {
if (Cache::get(CacheKey::get('EMAIL_VERIFY_CODE', $request->input('email'))) !== $request->input('email_code')) {
abort(500, __('Incorrect email verification code'));
}
}
@ -156,7 +99,6 @@ class AuthController extends Controller
$user->plan_id = $plan->id;
$user->group_id = $plan->group_id;
$user->expired_at = time() + (config('v2board.try_out_hour', 1) * 3600);
$user->speed_limit = $plan->speed_limit;
}
}
@ -167,6 +109,12 @@ class AuthController extends Controller
Cache::forget(CacheKey::get('EMAIL_VERIFY_CODE', $request->input('email')));
}
$data = [
'token' => $user->token,
'auth_data' => base64_encode("{$user->email}:{$user->password}")
];
$request->session()->put('email', $user->email);
$request->session()->put('id', $user->id);
$user->last_login_at = time();
$user->save();
@ -177,11 +125,8 @@ class AuthController extends Controller
(int)config('v2board.register_limit_expire', 60) * 60
);
}
$authService = new AuthService($user);
return response()->json([
'data' => $authService->generateAuthData($request)
'data' => $data
]);
}
@ -190,15 +135,6 @@ class AuthController extends Controller
$email = $request->input('email');
$password = $request->input('password');
if ((int)config('v2board.password_limit_enable', 1)) {
$passwordErrorCount = (int)Cache::get(CacheKey::get('PASSWORD_ERROR_LIMIT', $email), 0);
if ($passwordErrorCount >= (int)config('v2board.password_limit_count', 5)) {
abort(500, __('There are too many password errors, please try again after :minute minutes.', [
'minute' => config('v2board.password_limit_expire', 60)
]));
}
}
$user = User::where('email', $email)->first();
if (!$user) {
abort(500, __('Incorrect email or password'));
@ -209,13 +145,6 @@ class AuthController extends Controller
$password,
$user->password)
) {
if ((int)config('v2board.password_limit_enable')) {
Cache::put(
CacheKey::get('PASSWORD_ERROR_LIMIT', $email),
(int)$passwordErrorCount + 1,
60 * (int)config('v2board.password_limit_expire', 60)
);
}
abort(500, __('Incorrect email or password'));
}
@ -223,9 +152,22 @@ class AuthController extends Controller
abort(500, __('Your account has been suspended'));
}
$authService = new AuthService($user);
$data = [
'token' => $user->token,
'auth_data' => base64_encode("{$user->email}:{$user->password}")
];
$request->session()->put('email', $user->email);
$request->session()->put('id', $user->id);
if ($user->is_admin) {
$request->session()->put('is_admin', true);
$data['is_admin'] = true;
}
if ($user->is_staff) {
$request->session()->put('is_staff', true);
$data['is_staff'] = true;
}
return response([
'data' => $authService->generateAuthData($request)
'data' => $data
]);
}
@ -254,25 +196,47 @@ class AuthController extends Controller
if ($user->banned) {
abort(500, __('Your account has been suspended'));
}
$request->session()->put('email', $user->email);
$request->session()->put('id', $user->id);
if ($user->is_admin) {
$request->session()->put('is_admin', true);
}
Cache::forget($key);
$authService = new AuthService($user);
return response([
'data' => $authService->generateAuthData($request)
'data' => true
]);
}
}
public function getQuickLoginUrl(Request $request)
public function getTempToken(Request $request)
{
$authorization = $request->input('auth_data') ?? $request->header('authorization');
if (!$authorization) abort(403, '未登录或登陆已过期');
$user = AuthService::decryptAuthData($authorization);
if (!$user) abort(403, '未登录或登陆已过期');
$user = User::where('token', $request->input('token'))->first();
if (!$user) {
abort(500, __('Token error'));
}
$code = Helper::guid();
$key = CacheKey::get('TEMP_TOKEN', $code);
Cache::put($key, $user['id'], 60);
Cache::put($key, $user->id, 60);
return response([
'data' => $code
]);
}
public function getQuickLoginUrl(Request $request)
{
$authData = explode(':', base64_decode($request->input('auth_data')));
if (!isset($authData[0])) abort(403, __('Token error'));
$user = User::where('email', $authData[0])
->where('password', $authData[1])
->first();
if (!$user) {
abort(500, __('Token error'));
}
$code = Helper::guid();
$key = CacheKey::get('TEMP_TOKEN', $code);
Cache::put($key, $user->id, 60);
$redirect = '/#/login?verify=' . $code . '&redirect=' . ($request->input('redirect') ? $request->input('redirect') : 'dashboard');
if (config('v2board.app_url')) {
$url = config('v2board.app_url') . $redirect;
@ -284,9 +248,22 @@ class AuthController extends Controller
]);
}
public function check(Request $request)
{
$data = [
'is_login' => $request->session()->get('id') ? true : false
];
if ($request->session()->get('is_admin')) {
$data['is_admin'] = true;
}
return response([
'data' => $data
]);
}
public function forget(AuthForget $request)
{
if ((string)Cache::get(CacheKey::get('EMAIL_VERIFY_CODE', $request->input('email'))) !== (string)$request->input('email_code')) {
if (Cache::get(CacheKey::get('EMAIL_VERIFY_CODE', $request->input('email'))) !== $request->input('email_code')) {
abort(500, __('Incorrect email verification code'));
}
$user = User::where('email', $request->input('email'))->first();
@ -304,4 +281,5 @@ class AuthController extends Controller
'data' => true
]);
}
}

View File

@ -17,6 +17,24 @@ use ReCaptcha\ReCaptcha;
class CommController extends Controller
{
// TODO: remove on 1.5.5
public function config()
{
return response([
'data' => [
'isEmailVerify' => (int)config('v2board.email_verify', 0) ? 1 : 0,
'isInviteForce' => (int)config('v2board.invite_force', 0) ? 1 : 0,
'emailWhitelistSuffix' => (int)config('v2board.email_whitelist_enable', 0)
? $this->getEmailSuffix()
: 0,
'isRecaptcha' => (int)config('v2board.recaptcha_enable', 0) ? 1 : 0,
'recaptchaSiteKey' => config('v2board.recaptcha_site_key'),
'appDescription' => config('v2board.app_description'),
'appUrl' => config('v2board.app_url')
]
]);
}
private function isEmailVerify()
{
return response([

View File

@ -3,13 +3,12 @@
namespace App\Http\Controllers\Server;
use App\Services\ServerService;
use App\Services\StatisticalService;
use App\Services\UserService;
use App\Utils\CacheKey;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\ServerVmess;
use App\Models\ServerV2ray;
use App\Models\ServerLog;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
@ -38,11 +37,11 @@ class DeepbworkController extends Controller
{
ini_set('memory_limit', -1);
$nodeId = $request->input('node_id');
$server = ServerVmess::find($nodeId);
$server = ServerV2ray::find($nodeId);
if (!$server) {
abort(500, 'fail');
}
Cache::put(CacheKey::get('SERVER_VMESS_LAST_CHECK_AT', $server->id), time(), 3600);
Cache::put(CacheKey::get('SERVER_V2RAY_LAST_CHECK_AT', $server->id), time(), 3600);
$serverService = new ServerService();
$users = $serverService->getAvailableUsers($server->group_id);
$result = [];
@ -70,7 +69,7 @@ class DeepbworkController extends Controller
public function submit(Request $request)
{
// Log::info('serverSubmitData:' . $request->input('node_id') . ':' . file_get_contents('php://input'));
$server = ServerVmess::find($request->input('node_id'));
$server = ServerV2ray::find($request->input('node_id'));
if (!$server) {
return response([
'ret' => 0,
@ -79,15 +78,14 @@ class DeepbworkController extends Controller
}
$data = file_get_contents('php://input');
$data = json_decode($data, true);
Cache::put(CacheKey::get('SERVER_VMESS_ONLINE_USER', $server->id), count($data), 3600);
Cache::put(CacheKey::get('SERVER_VMESS_LAST_PUSH_AT', $server->id), time(), 3600);
Cache::put(CacheKey::get('SERVER_V2RAY_ONLINE_USER', $server->id), count($data), 3600);
Cache::put(CacheKey::get('SERVER_V2RAY_LAST_PUSH_AT', $server->id), time(), 3600);
$userService = new UserService();
$formatData = [];
foreach ($data as $item) {
$formatData[$item['user_id']] = [$item['u'], $item['d']];
$u = $item['u'] * $server->rate;
$d = $item['d'] * $server->rate;
$userService->trafficFetch($u, $d, $item['user_id'], $server, 'vmess');
}
$userService->trafficFetch($server->toArray(), 'vmess', $formatData);
return response([
'ret' => 1,
@ -114,7 +112,7 @@ class DeepbworkController extends Controller
private function getV2RayConfig(int $nodeId, int $localPort)
{
$server = ServerVmess::find($nodeId);
$server = ServerV2ray::find($nodeId);
if (!$server) {
abort(500, '节点不存在');
}
@ -131,7 +129,7 @@ class DeepbworkController extends Controller
return $json;
}
private function setDns(ServerVmess $server, object $json)
private function setDns(ServerV2ray $server, object $json)
{
if ($server->dnsSettings) {
$dns = $server->dnsSettings;
@ -144,7 +142,7 @@ class DeepbworkController extends Controller
}
}
private function setNetwork(ServerVmess $server, object $json)
private function setNetwork(ServerV2ray $server, object $json)
{
if ($server->networkSettings) {
switch ($server->network) {
@ -173,7 +171,7 @@ class DeepbworkController extends Controller
}
}
private function setRule(ServerVmess $server, object $json)
private function setRule(ServerV2ray $server, object $json)
{
$domainRules = array_filter(explode(PHP_EOL, config('v2board.server_v2ray_domain')));
$protocolRules = array_filter(explode(PHP_EOL, config('v2board.server_v2ray_protocol')));
@ -213,7 +211,7 @@ class DeepbworkController extends Controller
}
}
private function setTls(ServerVMess $server, object $json)
private function setTls(ServerV2ray $server, object $json)
{
if ((int)$server->tls) {
$tlsSettings = $server->tlsSettings;

View File

@ -4,7 +4,6 @@ namespace App\Http\Controllers\Server;
use App\Models\ServerShadowsocks;
use App\Services\ServerService;
use App\Services\StatisticalService;
use App\Services\UserService;
use App\Utils\CacheKey;
use Illuminate\Http\Request;
@ -74,12 +73,11 @@ class ShadowsocksTidalabController extends Controller
Cache::put(CacheKey::get('SERVER_SHADOWSOCKS_ONLINE_USER', $server->id), count($data), 3600);
Cache::put(CacheKey::get('SERVER_SHADOWSOCKS_LAST_PUSH_AT', $server->id), time(), 3600);
$userService = new UserService();
$formatData = [];
foreach ($data as $item) {
$formatData[$item['user_id']] = [$item['u'], $item['d']];
$u = $item['u'] * $server->rate;
$d = $item['d'] * $server->rate;
$userService->trafficFetch($u, $d, $item['user_id'], $server, 'shadowsocks');
}
$userService->trafficFetch($server->toArray(), 'shadowsocks', $formatData);
return response([
'ret' => 1,

View File

@ -3,7 +3,6 @@
namespace App\Http\Controllers\Server;
use App\Services\ServerService;
use App\Services\StatisticalService;
use App\Services\UserService;
use App\Utils\CacheKey;
use Illuminate\Http\Request;
@ -79,11 +78,11 @@ class TrojanTidalabController extends Controller
Cache::put(CacheKey::get('SERVER_TROJAN_ONLINE_USER', $server->id), count($data), 3600);
Cache::put(CacheKey::get('SERVER_TROJAN_LAST_PUSH_AT', $server->id), time(), 3600);
$userService = new UserService();
$formatData = [];
foreach ($data as $item) {
$formatData[$item['user_id']] = [$item['u'], $item['d']];
$u = $item['u'] * $server->rate;
$d = $item['d'] * $server->rate;
$userService->trafficFetch($u, $d, $item['user_id'], $server, 'trojan');
}
$userService->trafficFetch($server->toArray(), 'trojan', $formatData);
return response([
'ret' => 1,

View File

@ -3,23 +3,21 @@
namespace App\Http\Controllers\Server;
use App\Services\ServerService;
use App\Services\StatisticalService;
use App\Services\UserService;
use App\Utils\CacheKey;
use App\Utils\Helper;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\ServerShadowsocks;
use App\Models\ServerVmess;
use App\Models\ServerV2ray;
use App\Models\ServerTrojan;
use Illuminate\Support\Facades\Cache;
class UniProxyController extends Controller
class VProxyController extends Controller
{
private $nodeType;
private $nodeInfo;
private $nodeId;
private $serverService;
private $token;
public function __construct(Request $request)
{
@ -30,12 +28,25 @@ class UniProxyController extends Controller
if ($token !== config('v2board.server_token')) {
abort(500, 'token is error');
}
$this->token = $token;
$this->nodeType = $request->input('node_type');
if ($this->nodeType === 'v2ray') $this->nodeType = 'vmess';
$this->nodeId = $request->input('node_id');
$this->serverService = new ServerService();
$this->nodeInfo = $this->serverService->getServer($this->nodeId, $this->nodeType);
if (!$this->nodeInfo) abort(500, 'server is not exist');
switch ($this->nodeType) {
case 'v2ray':
$this->nodeInfo = ServerV2ray::find($this->nodeId);
break;
case 'shadowsocks':
$this->nodeInfo = ServerShadowsocks::find($this->nodeId);
break;
case 'trojan':
$this->nodeInfo = ServerTrojan::find($this->nodeId);
break;
default:
break;
}
if (!$this->nodeInfo) {
abort(500, 'server not found');
}
}
// 后端获取用户
@ -43,11 +54,21 @@ class UniProxyController extends Controller
{
ini_set('memory_limit', -1);
Cache::put(CacheKey::get('SERVER_' . strtoupper($this->nodeType) . '_LAST_CHECK_AT', $this->nodeInfo->id), time(), 3600);
$users = $this->serverService->getAvailableUsers($this->nodeInfo->group_id);
$serverService = new ServerService();
$users = $serverService->getAvailableUsers($this->nodeInfo->group_id);
$users = $users->toArray();
$response['users'] = $users;
switch ($this->nodeType) {
case 'shadowsocks':
$response['server'] = [
'cipher' => $this->nodeInfo->cipher,
'server_port' => $this->nodeInfo->server_port
];
break;
}
$eTag = sha1(json_encode($response));
if (strpos($request->header('If-None-Match'), $eTag) !== false ) {
abort(304);
@ -57,14 +78,18 @@ class UniProxyController extends Controller
}
// 后端提交数据
public function push(Request $request)
public function submit(Request $request)
{
$data = file_get_contents('php://input');
$data = json_decode($data, true);
Cache::put(CacheKey::get('SERVER_' . strtoupper($this->nodeType) . '_ONLINE_USER', $this->nodeInfo->id), count($data), 3600);
Cache::put(CacheKey::get('SERVER_' . strtoupper($this->nodeType) . '_LAST_PUSH_AT', $this->nodeInfo->id), time(), 3600);
$userService = new UserService();
$userService->trafficFetch($this->nodeInfo->toArray(), $this->nodeType, $data);
foreach ($data as $item) {
$u = $item['u'] * $this->nodeInfo->rate;
$d = $item['d'] * $this->nodeInfo->rate;
$userService->trafficFetch($u, $d, $item['user_id'], $this->nodeInfo, $this->nodeType);
}
return response([
'data' => true
@ -76,58 +101,28 @@ class UniProxyController extends Controller
{
switch ($this->nodeType) {
case 'shadowsocks':
$response = [
die(json_encode([
'server_port' => $this->nodeInfo->server_port,
'cipher' => $this->nodeInfo->cipher,
'obfs' => $this->nodeInfo->obfs,
'obfs_settings' => $this->nodeInfo->obfs_settings
];
if ($this->nodeInfo->cipher === '2022-blake3-aes-128-gcm') {
$response['server_key'] = Helper::getServerKey($this->nodeInfo->created_at, 16);
}
if ($this->nodeInfo->cipher === '2022-blake3-aes-256-gcm') {
$response['server_key'] = Helper::getServerKey($this->nodeInfo->created_at, 32);
}
], JSON_UNESCAPED_UNICODE));
break;
case 'vmess':
$response = [
case 'v2ray':
die(json_encode([
'server_port' => $this->nodeInfo->server_port,
'network' => $this->nodeInfo->network,
'cipher' => $this->nodeInfo->cipher,
'networkSettings' => $this->nodeInfo->networkSettings,
'tls' => $this->nodeInfo->tls
];
], JSON_UNESCAPED_UNICODE));
break;
case 'trojan':
$response = [
die(json_encode([
'host' => $this->nodeInfo->host,
'server_port' => $this->nodeInfo->server_port,
'server_name' => $this->nodeInfo->server_name,
];
break;
case 'hysteria':
$response = [
'host' => $this->nodeInfo->host,
'server_port' => $this->nodeInfo->server_port,
'server_name' => $this->nodeInfo->server_name,
'up_mbps' => $this->nodeInfo->up_mbps,
'down_mbps' => $this->nodeInfo->down_mbps,
'obfs' => Helper::getServerKey($this->nodeInfo->created_at, 16)
];
'server_port' => $this->nodeInfo->server_port
], JSON_UNESCAPED_UNICODE));
break;
}
$response['base_config'] = [
'push_interval' => (int)config('v2board.server_push_interval', 60),
'pull_interval' => (int)config('v2board.server_pull_interval', 60)
];
if ($this->nodeInfo['route_id']) {
$response['routes'] = $this->serverService->getRoutes($this->nodeInfo['route_id']);
}
$eTag = sha1(json_encode($response));
if (strpos($request->header('If-None-Match'), $eTag) !== false ) {
abort(304);
}
return response($response)->header('ETag', "\"{$eTag}\"");
}
}

View File

@ -57,7 +57,7 @@ class TicketController extends Controller
$ticketService->replyByAdmin(
$request->input('id'),
$request->input('message'),
$request->user['id']
$request->session()->get('id')
);
return response([
'data' => true

View File

@ -19,11 +19,7 @@ class CommController extends Controller
'withdraw_methods' => config('v2board.commission_withdraw_method', Dict::WITHDRAW_METHOD_WHITELIST_DEFAULT),
'withdraw_close' => (int)config('v2board.withdraw_close_enable', 0),
'currency' => config('v2board.currency', 'CNY'),
'currency_symbol' => config('v2board.currency_symbol', '¥'),
'commission_distribution_enable' => (int)config('v2board.commission_distribution_enable', 0),
'commission_distribution_l1' => config('v2board.commission_distribution_l1'),
'commission_distribution_l2' => config('v2board.commission_distribution_l2'),
'commission_distribution_l3' => config('v2board.commission_distribution_l3')
'currency_symbol' => config('v2board.currency_symbol', '¥')
]
]);
}

View File

@ -16,7 +16,7 @@ class CouponController extends Controller
}
$couponService = new CouponService($request->input('code'));
$couponService->setPlanId($request->input('plan_id'));
$couponService->setUserId($request->user['id']);
$couponService->setUserId($request->session()->get('id'));
$couponService->check();
return response([
'data' => $couponService->getCoupon()

View File

@ -14,11 +14,11 @@ class InviteController extends Controller
{
public function save(Request $request)
{
if (InviteCode::where('user_id', $request->user['id'])->where('status', 0)->count() >= config('v2board.invite_gen_limit', 5)) {
if (InviteCode::where('user_id', $request->session()->get('id'))->where('status', 0)->count() >= config('v2board.invite_gen_limit', 5)) {
abort(500, __('The maximum number of creations has been reached'));
}
$inviteCode = new InviteCode();
$inviteCode->user_id = $request->user['id'];
$inviteCode->user_id = $request->session()->get('id');
$inviteCode->code = Helper::randomChar(8);
return response([
'data' => $inviteCode->save()
@ -27,52 +27,43 @@ class InviteController extends Controller
public function details(Request $request)
{
$current = $request->input('current') ? $request->input('current') : 1;
$pageSize = $request->input('page_size') >= 10 ? $request->input('page_size') : 10;
$builder = CommissionLog::where('invite_user_id', $request->user['id'])
->where('get_amount', '>', 0)
->select([
'id',
'trade_no',
'order_amount',
'get_amount',
'created_at'
])
->orderBy('created_at', 'DESC');
$total = $builder->count();
$details = $builder->forPage($current, $pageSize)
->get();
return response([
'data' => $details,
'total' => $total
'data' => CommissionLog::where('invite_user_id', $request->session()->get('id'))
->where('get_amount', '>', 0)
->select([
'id',
'trade_no',
'order_amount',
'get_amount',
'created_at'
])
->get()
]);
}
public function fetch(Request $request)
{
$codes = InviteCode::where('user_id', $request->user['id'])
$codes = InviteCode::where('user_id', $request->session()->get('id'))
->where('status', 0)
->get();
$commission_rate = config('v2board.invite_commission', 10);
$user = User::find($request->user['id']);
$user = User::find($request->session()->get('id'));
if ($user->commission_rate) {
$commission_rate = $user->commission_rate;
}
$uncheck_commission_balance = (int)Order::where('status', 3)
->where('commission_status', 0)
->where('invite_user_id', $request->user['id'])
->sum('commission_balance');
if (config('v2board.commission_distribution_enable', 0)) {
$uncheck_commission_balance = $uncheck_commission_balance * (config('v2board.commission_distribution_l1') / 100);
}
$stat = [
//已注册用户数
(int)User::where('invite_user_id', $request->user['id'])->count(),
(int)User::where('invite_user_id', $request->session()->get('id'))->count(),
//有效的佣金
(int)CommissionLog::where('invite_user_id', $request->user['id'])
->sum('get_amount'),
(int)Order::where('status', 3)
->where('commission_status', 2)
->where('invite_user_id', $request->session()->get('id'))
->sum('commission_balance'),
//确认中的佣金
$uncheck_commission_balance,
(int)Order::where('status', 3)
->where('commission_status', 0)
->where('invite_user_id', $request->session()->get('id'))
->sum('commission_balance'),
//佣金比例
(int)$commission_rate,
//可用佣金

View File

@ -19,9 +19,14 @@ class KnowledgeController extends Controller
->first()
->toArray();
if (!$knowledge) abort(500, __('Article does not exist'));
$user = User::find($request->user['id']);
$user = User::find($request->session()->get('id'));
$userService = new UserService();
if (!$userService->isAvailable($user)) {
if ($userService->isAvailable($user)) {
$appleId = config('v2board.apple_id');
$appleIdPassword = config('v2board.apple_id_password');
} else {
$appleId = __('No active subscription. Unable to use our provided Apple ID');
$appleIdPassword = __('No active subscription. Unable to use our provided Apple ID');
$this->formatAccessData($knowledge['body']);
}
$subscribeUrl = Helper::getSubscribeUrl("/api/v1/client/subscribe?token={$user['token']}");
@ -41,19 +46,11 @@ class KnowledgeController extends Controller
'data' => $knowledge
]);
}
$builder = Knowledge::select(['id', 'category', 'title', 'updated_at'])
$knowledges = Knowledge::select(['id', 'category', 'title', 'updated_at'])
->where('language', $request->input('language'))
->where('show', 1)
->orderBy('sort', 'ASC');
$keyword = $request->input('keyword');
if ($keyword) {
$builder = $builder->where(function ($query) use ($keyword) {
$query->where('title', 'LIKE', "%{$keyword}%")
->orWhere('body', 'LIKE', "%{$keyword}%");
});
}
$knowledges = $builder->get()
->orderBy('sort', 'ASC')
->get()
->groupBy('category');
return response([
'data' => $knowledges

View File

@ -9,7 +9,6 @@ use App\Models\Payment;
use App\Services\CouponService;
use App\Services\OrderService;
use App\Services\PaymentService;
use App\Services\PlanService;
use App\Services\UserService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
@ -29,7 +28,7 @@ class OrderController extends Controller
{
public function fetch(Request $request)
{
$model = Order::where('user_id', $request->user['id'])
$model = Order::where('user_id', $request->session()->get('id'))
->orderBy('created_at', 'DESC');
if ($request->input('status') !== null) {
$model->where('status', $request->input('status'));
@ -50,7 +49,7 @@ class OrderController extends Controller
public function detail(Request $request)
{
$order = Order::where('user_id', $request->user['id'])
$order = Order::where('user_id', $request->session()->get('id'))
->where('trade_no', $request->input('trade_no'))
->first();
if (!$order) {
@ -72,30 +71,28 @@ class OrderController extends Controller
public function save(OrderSave $request)
{
$userService = new UserService();
if ($userService->isNotCompleteOrderByUserId($request->user['id'])) {
if ($userService->isNotCompleteOrderByUserId($request->session()->get('id'))) {
abort(500, __('You have an unpaid or pending order, please try again later or cancel it'));
}
$planService = new PlanService($request->input('plan_id'));
$plan = $planService->plan;
$user = User::find($request->user['id']);
$plan = Plan::find($request->input('plan_id'));
$user = User::find($request->session()->get('id'));
if (!$plan) {
abort(500, __('Subscription plan does not exist'));
}
if ($user->plan_id !== $plan->id && !$planService->haveCapacity() && $request->input('period') !== 'reset_price') {
abort(500, __('Current product is sold out'));
}
if ($plan[$request->input('period')] === NULL) {
abort(500, __('This payment period cannot be purchased, please choose another period'));
}
if ($request->input('period') === 'reset_price') {
if (!$userService->isAvailable($user) || $plan->id !== $user->plan_id) {
if (!$user->plan_id) {
abort(500, __('Subscription has expired or no active subscription, unable to purchase Data Reset Package'));
} else {
if ($user->plan_id !== $plan->id) {
abort(500, __('This subscription reset package does not apply to your subscription'));
}
}
}
@ -117,7 +114,7 @@ class OrderController extends Controller
DB::beginTransaction();
$order = new Order();
$orderService = new OrderService($order);
$order->user_id = $request->user['id'];
$order->user_id = $request->session()->get('id');
$order->plan_id = $plan->id;
$order->period = $request->input('period');
$order->trade_no = Helper::generateOrderNo();
@ -173,7 +170,7 @@ class OrderController extends Controller
$tradeNo = $request->input('trade_no');
$method = $request->input('method');
$order = Order::where('trade_no', $tradeNo)
->where('user_id', $request->user['id'])
->where('user_id', $request->session()->get('id'))
->where('status', 0)
->first();
if (!$order) {
@ -191,7 +188,6 @@ class OrderController extends Controller
$payment = Payment::find($method);
if (!$payment || $payment->enable !== 1) abort(500, __('Payment method is not available'));
$paymentService = new PaymentService($payment->payment, $payment->id);
$order->handling_amount = NULL;
if ($payment->handling_fee_fixed || $payment->handling_fee_percent) {
$order->handling_amount = round(($order->total_amount * ($payment->handling_fee_percent / 100)) + $payment->handling_fee_fixed);
}
@ -213,7 +209,7 @@ class OrderController extends Controller
{
$tradeNo = $request->input('trade_no');
$order = Order::where('trade_no', $tradeNo)
->where('user_id', $request->user['id'])
->where('user_id', $request->session()->get('id'))
->first();
if (!$order) {
abort(500, __('Order does not exist'));
@ -233,9 +229,7 @@ class OrderController extends Controller
'handling_fee_fixed',
'handling_fee_percent'
])
->where('enable', 1)
->orderBy('sort', 'ASC')
->get();
->where('enable', 1)->get();
return response([
'data' => $methods
@ -248,7 +242,7 @@ class OrderController extends Controller
abort(500, __('Invalid parameter'));
}
$order = Order::where('trade_no', $request->input('trade_no'))
->where('user_id', $request->user['id'])
->where('user_id', $request->session()->get('id'))
->first();
if (!$order) {
abort(500, __('Order does not exist'));

View File

@ -4,16 +4,14 @@ namespace App\Http\Controllers\User;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Services\PlanService;
use Illuminate\Http\Request;
use App\Models\Plan;
use Illuminate\Support\Facades\DB;
class PlanController extends Controller
{
public function fetch(Request $request)
{
$user = User::find($request->user['id']);
$user = User::find($request->session()->get('id'));
if ($request->input('id')) {
$plan = Plan::where('id', $request->input('id'))->first();
if (!$plan) {
@ -26,18 +24,11 @@ class PlanController extends Controller
'data' => $plan
]);
}
$counts = PlanService::countActiveUsers();
$plans = Plan::where('show', 1)
$plan = Plan::where('show', 1)
->orderBy('sort', 'ASC')
->get();
foreach ($plans as $k => $v) {
if ($plans[$k]->capacity_limit === NULL) continue;
if (!isset($counts[$plans[$k]->id])) continue;
$plans[$k]->capacity_limit = $plans[$k]->capacity_limit - $counts[$plans[$k]->id]->count;
}
return response([
'data' => $plans
'data' => $plan
]);
}
}

View File

@ -8,7 +8,7 @@ use App\Services\UserService;
use App\Utils\CacheKey;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use App\Models\ServerVmess;
use App\Models\ServerV2ray;
use App\Models\ServerLog;
use App\Models\User;
@ -19,20 +19,15 @@ class ServerController extends Controller
{
public function fetch(Request $request)
{
$user = User::find($request->user['id']);
$user = User::find($request->session()->get('id'));
$servers = [];
$userService = new UserService();
if ($userService->isAvailable($user)) {
$serverService = new ServerService();
$servers = $serverService->getAvailableServers($user);
}
$eTag = sha1(json_encode(array_column($servers, 'cache_key')));
if (strpos($request->header('If-None-Match'), $eTag) !== false ) {
abort(304);
}
return response([
'data' => $servers
])->header('ETag', "\"{$eTag}\"");
]);
}
}

View File

@ -18,7 +18,7 @@ class StatController extends Controller
'user_id',
'server_rate'
])
->where('user_id', $request->user['id'])
->where('user_id', $request->session()->get('id'))
->where('record_at', '>=', strtotime(date('Y-m-1')))
->orderBy('record_at', 'DESC');
return response([

View File

@ -22,6 +22,6 @@ class TelegramController extends Controller
public function unbind(Request $request)
{
$user = User::where('user_id', $request->user['id'])->first();
$user = User::where('user_id', $request->session()->get('id'))->first();
}
}

View File

@ -21,7 +21,7 @@ class TicketController extends Controller
{
if ($request->input('id')) {
$ticket = Ticket::where('id', $request->input('id'))
->where('user_id', $request->user['id'])
->where('user_id', $request->session()->get('id'))
->first();
if (!$ticket) {
abort(500, __('Ticket does not exist'));
@ -38,7 +38,7 @@ class TicketController extends Controller
'data' => $ticket
]);
}
$ticket = Ticket::where('user_id', $request->user['id'])
$ticket = Ticket::where('user_id', $request->session()->get('id'))
->orderBy('created_at', 'DESC')
->get();
return response([
@ -49,21 +49,21 @@ class TicketController extends Controller
public function save(TicketSave $request)
{
DB::beginTransaction();
if ((int)Ticket::where('status', 0)->where('user_id', $request->user['id'])->lockForUpdate()->count()) {
if ((int)Ticket::where('status', 0)->where('user_id', $request->session()->get('id'))->lockForUpdate()->count()) {
abort(500, __('There are other unresolved tickets'));
}
$ticket = Ticket::create(array_merge($request->only([
'subject',
'level'
]), [
'user_id' => $request->user['id']
'user_id' => $request->session()->get('id')
]));
if (!$ticket) {
DB::rollback();
abort(500, __('Failed to open ticket'));
}
$ticketMessage = TicketMessage::create([
'user_id' => $request->user['id'],
'user_id' => $request->session()->get('id'),
'ticket_id' => $ticket->id,
'message' => $request->input('message')
]);
@ -87,7 +87,7 @@ class TicketController extends Controller
abort(500, __('Message cannot be empty'));
}
$ticket = Ticket::where('id', $request->input('id'))
->where('user_id', $request->user['id'])
->where('user_id', $request->session()->get('id'))
->first();
if (!$ticket) {
abort(500, __('Ticket does not exist'));
@ -95,14 +95,14 @@ class TicketController extends Controller
if ($ticket->status) {
abort(500, __('The ticket is closed and cannot be replied'));
}
if ($request->user['id'] == $this->getLastMessage($ticket->id)->user_id) {
if ($request->session()->get('id') == $this->getLastMessage($ticket->id)->user_id) {
abort(500, __('Please wait for the technical enginneer to reply'));
}
$ticketService = new TicketService();
if (!$ticketService->reply(
$ticket,
$request->input('message'),
$request->user['id']
$request->session()->get('id')
)) {
abort(500, __('Ticket reply failed'));
}
@ -119,7 +119,7 @@ class TicketController extends Controller
abort(500, __('Invalid parameter'));
}
$ticket = Ticket::where('id', $request->input('id'))
->where('user_id', $request->user['id'])
->where('user_id', $request->session()->get('id'))
->first();
if (!$ticket) {
abort(500, __('Ticket does not exist'));
@ -154,7 +154,7 @@ class TicketController extends Controller
)) {
abort(500, __('Unsupported withdrawal method'));
}
$user = User::find($request->user['id']);
$user = User::find($request->session()->get('id'));
$limit = config('v2board.commission_withdraw_limit', 100);
if ($limit > ($user->commission_balance / 100)) {
abort(500, __('The current required minimum withdrawal commission is :limit', ['limit' => $limit]));
@ -164,7 +164,7 @@ class TicketController extends Controller
$ticket = Ticket::create([
'subject' => $subject,
'level' => 2,
'user_id' => $request->user['id']
'user_id' => $request->session()->get('id')
]);
if (!$ticket) {
DB::rollback();
@ -175,7 +175,7 @@ class TicketController extends Controller
__('Withdrawal account') . "" . $request->input('withdraw_account')
);
$ticketMessage = TicketMessage::create([
'user_id' => $request->user['id'],
'user_id' => $request->session()->get('id'),
'ticket_id' => $ticket->id,
'message' => $message
]);

View File

@ -6,7 +6,6 @@ use App\Http\Controllers\Controller;
use App\Http\Requests\User\UserTransfer;
use App\Http\Requests\User\UserUpdate;
use App\Http\Requests\User\UserChangePassword;
use App\Services\AuthService;
use App\Services\UserService;
use App\Utils\CacheKey;
use Illuminate\Http\Request;
@ -19,46 +18,17 @@ use Illuminate\Support\Facades\Cache;
class UserController extends Controller
{
public function getActiveSession(Request $request)
public function logout(Request $request)
{
$user = User::find($request->user['id']);
if (!$user) {
abort(500, __('The user does not exist'));
}
$authService = new AuthService($user);
$request->session()->flush();
return response([
'data' => $authService->getSessions()
]);
}
public function removeActiveSession(Request $request)
{
$user = User::find($request->user['id']);
if (!$user) {
abort(500, __('The user does not exist'));
}
$authService = new AuthService($user);
return response([
'data' => $authService->removeSession($request->input('session_id'))
]);
}
public function checkLogin(Request $request)
{
$data = [
'is_login' => $request->user['id'] ? true : false
];
if ($request->user['is_admin']) {
$data['is_admin'] = true;
}
return response([
'data' => $data
'data' => true
]);
}
public function changePassword(UserChangePassword $request)
{
$user = User::find($request->user['id']);
$user = User::find($request->session()->get('id'));
if (!$user) {
abort(500, __('The user does not exist'));
}
@ -76,6 +46,7 @@ class UserController extends Controller
if (!$user->save()) {
abort(500, __('Save failed'));
}
$request->session()->flush();
return response([
'data' => true
]);
@ -83,7 +54,7 @@ class UserController extends Controller
public function info(Request $request)
{
$user = User::where('id', $request->user['id'])
$user = User::where('id', $request->session()->get('id'))
->select([
'email',
'transfer_enable',
@ -115,12 +86,12 @@ class UserController extends Controller
{
$stat = [
Order::where('status', 0)
->where('user_id', $request->user['id'])
->where('user_id', $request->session()->get('id'))
->count(),
Ticket::where('status', 0)
->where('user_id', $request->user['id'])
->where('user_id', $request->session()->get('id'))
->count(),
User::where('invite_user_id', $request->user['id'])
User::where('invite_user_id', $request->session()->get('id'))
->count()
];
return response([
@ -130,7 +101,7 @@ class UserController extends Controller
public function getSubscribe(Request $request)
{
$user = User::where('id', $request->user['id'])
$user = User::where('id', $request->session()->get('id'))
->select([
'plan_id',
'token',
@ -138,8 +109,7 @@ class UserController extends Controller
'u',
'd',
'transfer_enable',
'email',
'uuid'
'email'
])
->first();
if (!$user) {
@ -161,7 +131,7 @@ class UserController extends Controller
public function resetSecurity(Request $request)
{
$user = User::find($request->user['id']);
$user = User::find($request->session()->get('id'));
if (!$user) {
abort(500, __('The user does not exist'));
}
@ -182,7 +152,7 @@ class UserController extends Controller
'remind_traffic'
]);
$user = User::find($request->user['id']);
$user = User::find($request->session()->get('id'));
if (!$user) {
abort(500, __('The user does not exist'));
}
@ -199,7 +169,7 @@ class UserController extends Controller
public function transfer(UserTransfer $request)
{
$user = User::find($request->user['id']);
$user = User::find($request->session()->get('id'));
if (!$user) {
abort(500, __('The user does not exist'));
}
@ -218,7 +188,7 @@ class UserController extends Controller
public function getQuickLoginUrl(Request $request)
{
$user = User::find($request->user['id']);
$user = User::find($request->session()->get('id'));
if (!$user) {
abort(500, __('The user does not exist'));
}

View File

@ -2,7 +2,6 @@
namespace App\Http;
use Fruitcake\Cors\HandleCors;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
@ -15,7 +14,6 @@ class Kernel extends HttpKernel
* @var array
*/
protected $middleware = [
\App\Http\Middleware\CORS::class,
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
@ -30,20 +28,22 @@ class Kernel extends HttpKernel
*/
protected $middlewareGroups = [
'web' => [
// \App\Http\Middleware\EncryptCookies::class,
// \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
// \Illuminate\Session\Middleware\StartSession::class,
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
// \Illuminate\View\Middleware\ShareErrorsFromSession::class,
// \App\Http\Middleware\VerifyCsrfToken::class,
// \Illuminate\Routing\Middleware\SubstituteBindings::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\CORS::class,
],
'api' => [
// \App\Http\Middleware\EncryptCookies::class,
// \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
// \Illuminate\Session\Middleware\StartSession::class,
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\App\Http\Middleware\ForceJson::class,
\App\Http\Middleware\CORS::class,
\App\Http\Middleware\Language::class,
'bindings',
],
@ -70,7 +70,6 @@ class Kernel extends HttpKernel
'admin' => \App\Http\Middleware\Admin::class,
'client' => \App\Http\Middleware\Client::class,
'staff' => \App\Http\Middleware\Staff::class,
'log' => \App\Http\Middleware\RequestLog::class
];
/**

View File

@ -2,9 +2,7 @@
namespace App\Http\Middleware;
use App\Services\AuthService;
use Closure;
use Illuminate\Support\Facades\Cache;
class Admin
{
@ -17,14 +15,9 @@ class Admin
*/
public function handle($request, Closure $next)
{
$authorization = $request->input('auth_data') ?? $request->header('authorization');
if (!$authorization) abort(403, '未登录或登陆已过期');
$user = AuthService::decryptAuthData($authorization);
if (!$user || !$user['is_admin']) abort(403, '未登录或登陆已过期');
$request->merge([
'user' => $user
]);
if (!$request->session()->get('is_admin')) {
abort(403, '权限不足');
}
return $next($request);
}
}

View File

@ -17,8 +17,8 @@ class CORS
}
$response = $next($request);
$response->header('Access-Control-Allow-Origin', trim($origin, '/'));
$response->header('Access-Control-Allow-Methods', 'GET,POST,OPTIONS,HEAD');
$response->header('Access-Control-Allow-Headers', 'Origin,Content-Type,Accept,Authorization,X-Request-With');
$response->header('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
$response->header('Access-Control-Allow-Headers', 'Content-Type,X-Requested-With');
$response->header('Access-Control-Allow-Credentials', 'true');
$response->header('Access-Control-Max-Age', 10080);

View File

@ -26,9 +26,7 @@ class Client
if (!$user) {
abort(403, 'token is error');
}
$request->merge([
'user' => $user
]);
$request->user = $user;
return $next($request);
}
}

View File

@ -1,24 +0,0 @@
<?php
namespace App\Http\Middleware;
use Closure;
class RequestLog
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($request->method() === 'POST') {
$path = $request->path();
info("POST {$path}");
};
return $next($request);
}
}

View File

@ -2,7 +2,6 @@
namespace App\Http\Middleware;
use App\Services\AuthService;
use Closure;
class Staff
@ -16,14 +15,9 @@ class Staff
*/
public function handle($request, Closure $next)
{
$authorization = $request->input('auth_data') ?? $request->header('authorization');
if (!$authorization) abort(403, '未登录或登陆已过期');
$user = AuthService::decryptAuthData($authorization);
if (!$user || !$user['is_staff']) abort(403, '未登录或登陆已过期');
$request->merge([
'user' => $user
]);
if (!$request->session()->get('is_staff')) {
abort(403, '权限不足');
}
return $next($request);
}
}

View File

@ -2,9 +2,7 @@
namespace App\Http\Middleware;
use App\Services\AuthService;
use Closure;
use Illuminate\Support\Facades\Cache;
class User
{
@ -18,13 +16,19 @@ class User
public function handle($request, Closure $next)
{
$authorization = $request->input('auth_data') ?? $request->header('authorization');
if (!$authorization) abort(403, '未登录或登陆已过期');
$user = AuthService::decryptAuthData($authorization);
if (!$user) abort(403, '未登录或登陆已过期');
$request->merge([
'user' => $user
]);
if ($authorization) {
$authData = explode(':', base64_decode($authorization));
if (!isset($authData[1]) || !isset($authData[0])) abort(403, '鉴权失败,请重新登入');
$user = \App\Models\User::where('password', $authData[1])
->where('email', $authData[0])
->first();
if (!$user) abort(403, '鉴权失败,请重新登入');
$request->session()->put('email', $user->email);
$request->session()->put('id', $user->id);
}
if (!$request->session()->get('id')) {
abort(403, '未登录或登陆已过期');
}
return $next($request);
}
}

View File

@ -24,7 +24,9 @@ class ConfigSave extends FormRequest
// site
'logo' => 'nullable|url',
'force_https' => 'in:0,1',
'safe_mode_enable' => 'in:0,1',
'stop_register' => 'in:0,1',
'email_verify' => 'in:0,1',
'app_name' => '',
'app_description' => '',
'app_url' => 'nullable|url',
@ -32,9 +34,18 @@ class ConfigSave extends FormRequest
'try_out_enable' => 'in:0,1',
'try_out_plan_id' => 'integer',
'try_out_hour' => 'numeric',
'email_whitelist_enable' => 'in:0,1',
'email_whitelist_suffix' => 'nullable|array',
'email_gmail_limit_enable' => 'in:0,1',
'recaptcha_enable' => 'in:0,1',
'recaptcha_key' => '',
'recaptcha_site_key' => '',
'tos_url' => 'nullable|url',
'currency' => '',
'currency_symbol' => '',
'register_limit_by_ip_enable' => 'in:0,1',
'register_limit_count' => 'integer',
'register_limit_expire' => 'integer',
// subscribe
'plan_change_enable' => 'in:0,1',
'reset_traffic_method' => 'in:0,1,2,3,4',
@ -45,14 +56,17 @@ class ConfigSave extends FormRequest
'show_info_to_server_enable' => 'in:0,1',
// server
'server_token' => 'nullable|min:16',
'server_pull_interval' => 'integer',
'server_push_interval' => 'integer',
'server_license' => 'nullable',
'server_log_enable' => 'in:0,1',
'server_v2ray_domain' => '',
'server_v2ray_protocol' => '',
// frontend
'frontend_theme' => '',
'frontend_theme_sidebar' => 'nullable|in:dark,light',
'frontend_theme_header' => 'nullable|in:dark,light',
'frontend_theme_color' => 'nullable|in:default,darkblue,black,green',
'frontend_theme_sidebar' => 'in:dark,light',
'frontend_theme_header' => 'in:dark,light',
'frontend_theme_color' => 'in:default,darkblue,black,green',
'frontend_background_url' => 'nullable|url',
'frontend_admin_path' => '',
// email
'email_template' => '',
'email_host' => '',
@ -73,23 +87,7 @@ class ConfigSave extends FormRequest
'macos_version' => '',
'macos_download_url' => '',
'android_version' => '',
'android_download_url' => '',
// safe
'email_whitelist_enable' => 'in:0,1',
'email_whitelist_suffix' => 'nullable|array',
'email_gmail_limit_enable' => 'in:0,1',
'recaptcha_enable' => 'in:0,1',
'recaptcha_key' => '',
'recaptcha_site_key' => '',
'email_verify' => 'in:0,1',
'safe_mode_enable' => 'in:0,1',
'register_limit_by_ip_enable' => 'in:0,1',
'register_limit_count' => 'integer',
'register_limit_expire' => 'integer',
'secure_path' => 'min:8|regex:/^[\w-]*$/',
'password_limit_enable' => 'in:0,1',
'password_limit_count' => 'integer',
'password_limit_expire' => 'integer',
'android_download_url' => ''
];
/**
* Get the validation rules that apply to the request.
@ -110,9 +108,7 @@ class ConfigSave extends FormRequest
'server_token.min' => '通讯密钥长度必须大于16位',
'tos_url.url' => '服务条款URL格式不正确必须携带http(s)://',
'telegram_discuss_link.url' => 'Telegram群组地址必须为URL格式必须携带http(s)://',
'logo.url' => 'LOGO URL格式不正确必须携带https(s)://',
'secure_path.min' => '后台路径长度最小为8位',
'secure_path.regex' => '后台路径只能为字母或数字'
'logo.url' => 'LOGO URL格式不正确必须携带https(s)://'
];
}
}

View File

@ -14,7 +14,7 @@ class OrderFetch extends FormRequest
public function rules()
{
return [
'filter.*.key' => 'required|in:email,trade_no,status,commission_status,user_id,invite_user_id,callback_no,commission_balance',
'filter.*.key' => 'required|in:email,trade_no,status,commission_status,user_id,invite_user_id,callback_no',
'filter.*.condition' => 'required|in:>,<,=,>=,<=,模糊,!=',
'filter.*.value' => ''
];

View File

@ -26,9 +26,7 @@ class PlanSave extends FormRequest
'three_year_price' => 'nullable|integer',
'onetime_price' => 'nullable|integer',
'reset_price' => 'nullable|integer',
'reset_traffic_method' => 'nullable|integer|in:0,1,2,3,4',
'capacity_limit' => 'nullable|integer',
'speed_limit' => 'nullable|integer'
'reset_traffic_method' => 'nullable|integer|in:0,1,2,3,4'
];
}
@ -49,9 +47,7 @@ class PlanSave extends FormRequest
'onetime_price.integer' => '一次性金额有误',
'reset_price.integer' => '流量重置包金额有误',
'reset_traffic_method.integer' => '流量重置方式格式有误',
'reset_traffic_method.in' => '流量重置方式格式有误',
'capacity_limit.integer' => '容纳用户量限制格式有误',
'speed_limit.integer' => '限速格式有误'
'reset_traffic_method.in' => '流量重置方式格式有误'
];
}
}

View File

@ -18,11 +18,10 @@ class ServerShadowsocksSave extends FormRequest
'name' => 'required',
'group_id' => 'required|array',
'parent_id' => 'nullable|integer',
'route_id' => 'nullable|array',
'host' => 'required',
'port' => 'required',
'server_port' => 'required',
'cipher' => 'required|in:aes-128-gcm,aes-192-gcm,aes-256-gcm,chacha20-ietf-poly1305,2022-blake3-aes-128-gcm,2022-blake3-aes-256-gcm',
'cipher' => 'required|in:aes-128-gcm,aes-256-gcm,chacha20-ietf-poly1305',
'obfs' => 'nullable|in:http',
'obfs_settings' => 'nullable|array',
'tags' => 'nullable|array',
@ -36,7 +35,6 @@ class ServerShadowsocksSave extends FormRequest
'name.required' => '节点名称不能为空',
'group_id.required' => '权限组不能为空',
'group_id.array' => '权限组格式不正确',
'route_id.array' => '路由组格式不正确',
'parent_id.integer' => '父节点格式不正确',
'host.required' => '节点地址不能为空',
'port.required' => '连接端口不能为空',

View File

@ -17,7 +17,6 @@ class ServerTrojanSave extends FormRequest
'show' => '',
'name' => 'required',
'group_id' => 'required|array',
'route_id' => 'nullable|array',
'parent_id' => 'nullable|integer',
'host' => 'required',
'port' => 'required',
@ -35,7 +34,6 @@ class ServerTrojanSave extends FormRequest
'name.required' => '节点名称不能为空',
'group_id.required' => '权限组不能为空',
'group_id.array' => '权限组格式不正确',
'route_id.array' => '路由组格式不正确',
'parent_id.integer' => '父节点格式不正确',
'host.required' => '节点地址不能为空',
'port.required' => '连接端口不能为空',

View File

@ -4,7 +4,7 @@ namespace App\Http\Requests\Admin;
use Illuminate\Foundation\Http\FormRequest;
class ServerVmessSave extends FormRequest
class ServerV2raySave extends FormRequest
{
/**
* Get the validation rules that apply to the request.
@ -17,7 +17,6 @@ class ServerVmessSave extends FormRequest
'show' => '',
'name' => 'required',
'group_id' => 'required|array',
'route_id' => 'nullable|array',
'parent_id' => 'nullable|integer',
'host' => 'required',
'port' => 'required',
@ -39,7 +38,6 @@ class ServerVmessSave extends FormRequest
'name.required' => '节点名称不能为空',
'group_id.required' => '权限组不能为空',
'group_id.array' => '权限组格式不正确',
'route_id.array' => '路由组格式不正确',
'parent_id.integer' => '父ID格式不正确',
'host.required' => '节点地址不能为空',
'port.required' => '连接端口不能为空',

View File

@ -4,7 +4,7 @@ namespace App\Http\Requests\Admin;
use Illuminate\Foundation\Http\FormRequest;
class ServerVmessUpdate extends FormRequest
class ServerV2rayUpdate extends FormRequest
{
/**
* Get the validation rules that apply to the request.

View File

@ -14,7 +14,7 @@ class UserFetch extends FormRequest
public function rules()
{
return [
'filter.*.key' => 'required|in:id,email,transfer_enable,d,expired_at,uuid,token,invite_by_email,invite_user_id,plan_id,banned,remarks,is_admin',
'filter.*.key' => 'required|in:id,email,transfer_enable,d,expired_at,uuid,token,invite_by_email,invite_user_id,plan_id,banned,remarks',
'filter.*.condition' => 'required|in:>,<,=,>=,<=,模糊,!=',
'filter.*.value' => 'required'
];

View File

@ -14,7 +14,7 @@ class UserUpdate extends FormRequest
public function rules()
{
return [
'email' => 'required|email:strict',
'email' => 'required|email',
'password' => 'nullable|min:8',
'transfer_enable' => 'numeric',
'expired_at' => 'nullable|integer',
@ -29,8 +29,7 @@ class UserUpdate extends FormRequest
'balance' => 'integer',
'commission_type' => 'integer',
'commission_balance' => 'integer',
'remarks' => 'nullable',
'speed_limit' => 'nullable|integer'
'remarks' => 'nullable'
];
}
@ -60,8 +59,7 @@ class UserUpdate extends FormRequest
'd.integer' => '下行流量格式不正确',
'balance.integer' => '余额格式不正确',
'commission_balance.integer' => '佣金格式不正确',
'password.min' => '密码长度最小8位',
'speed_limit.integer' => '限速格式不正确'
'password.min' => '密码长度最小8位'
];
}
}

View File

@ -14,7 +14,7 @@ class AuthForget extends FormRequest
public function rules()
{
return [
'email' => 'required|email:strict',
'email' => 'required|email',
'password' => 'required|min:8',
'email_code' => 'required'
];

View File

@ -14,7 +14,7 @@ class AuthLogin extends FormRequest
public function rules()
{
return [
'email' => 'required|email:strict',
'email' => 'required|email',
'password' => 'required|min:8'
];
}

View File

@ -14,7 +14,7 @@ class AuthRegister extends FormRequest
public function rules()
{
return [
'email' => 'required|email:strict',
'email' => 'required|email',
'password' => 'required|min:8'
];
}

View File

@ -14,7 +14,7 @@ class CommSendEmailVerify extends FormRequest
public function rules()
{
return [
'email' => 'required|email:strict'
'email' => 'required|email'
];
}

View File

@ -14,7 +14,7 @@ class UserUpdate extends FormRequest
public function rules()
{
return [
'email' => 'required|email:strict',
'email' => 'required|email',
'password' => 'nullable',
'transfer_enable' => 'numeric',
'expired_at' => 'nullable|integer',

View File

@ -8,8 +8,8 @@ class AdminRoute
public function map(Registrar $router)
{
$router->group([
'prefix' => config('v2board.secure_path', config('v2board.frontend_admin_path', hash('crc32b', config('app.key')))),
'middleware' => ['admin', 'log']
'prefix' => 'admin',
'middleware' => 'admin'
], function ($router) {
// Config
$router->get ('/config/fetch', 'Admin\\ConfigController@fetch');
@ -28,9 +28,6 @@ class AdminRoute
$router->get ('/server/group/fetch', 'Admin\\Server\\GroupController@fetch');
$router->post('/server/group/save', 'Admin\\Server\\GroupController@save');
$router->post('/server/group/drop', 'Admin\\Server\\GroupController@drop');
$router->get ('/server/route/fetch', 'Admin\\Server\\RouteController@fetch');
$router->post('/server/route/save', 'Admin\\Server\\RouteController@save');
$router->post('/server/route/drop', 'Admin\\Server\\RouteController@drop');
$router->get ('/server/manage/getNodes', 'Admin\\Server\\ManageController@getNodes');
$router->post('/server/manage/sort', 'Admin\\Server\\ManageController@sort');
$router->group([
@ -45,14 +42,15 @@ class AdminRoute
$router->post('viewConfig', 'Admin\\Server\\TrojanController@viewConfig');
});
$router->group([
'prefix' => 'server/vmess'
'prefix' => 'server/v2ray'
], function ($router) {
$router->get ('fetch', 'Admin\\Server\\VmessController@fetch');
$router->post('save', 'Admin\\Server\\VmessController@save');
$router->post('drop', 'Admin\\Server\\VmessController@drop');
$router->post('update', 'Admin\\Server\\VmessController@update');
$router->post('copy', 'Admin\\Server\\VmessController@copy');
$router->post('sort', 'Admin\\Server\\VmessController@sort');
$router->get ('fetch', 'Admin\\Server\\V2rayController@fetch');
$router->post('save', 'Admin\\Server\\V2rayController@save');
$router->post('drop', 'Admin\\Server\\V2rayController@drop');
$router->post('update', 'Admin\\Server\\V2rayController@update');
$router->post('copy', 'Admin\\Server\\V2rayController@copy');
$router->post('sort', 'Admin\\Server\\V2rayController@sort');
$router->post('viewConfig', 'Admin\\Server\\V2rayController@viewConfig');
});
$router->group([
'prefix' => 'server/shadowsocks'
@ -64,16 +62,6 @@ class AdminRoute
$router->post('copy', 'Admin\\Server\\ShadowsocksController@copy');
$router->post('sort', 'Admin\\Server\\ShadowsocksController@sort');
});
$router->group([
'prefix' => 'server/hysteria'
], function ($router) {
$router->get ('fetch', 'Admin\\Server\\HysteriaController@fetch');
$router->post('save', 'Admin\\Server\\HysteriaController@save');
$router->post('drop', 'Admin\\Server\\HysteriaController@drop');
$router->post('update', 'Admin\\Server\\HysteriaController@update');
$router->post('copy', 'Admin\\Server\\HysteriaController@copy');
$router->post('sort', 'Admin\\Server\\HysteriaController@sort');
});
// Order
$router->get ('/order/fetch', 'Admin\\OrderController@fetch');
$router->post('/order/update', 'Admin\\OrderController@update');
@ -91,14 +79,10 @@ class AdminRoute
$router->post('/user/ban', 'Admin\\UserController@ban');
$router->post('/user/resetSecret', 'Admin\\UserController@resetSecret');
$router->post('/user/setInviteUser', 'Admin\\UserController@setInviteUser');
// Stat
$router->get ('/stat/getStat', 'Admin\\StatController@getStat');
// StatOrder
$router->get ('/stat/getOverride', 'Admin\\StatController@getOverride');
$router->get ('/stat/getServerLastRank', 'Admin\\StatController@getServerLastRank');
$router->get ('/stat/getOrder', 'Admin\\StatController@getOrder');
$router->get ('/stat/getStatUser', 'Admin\\StatController@getStatUser');
$router->get ('/stat/getRanking', 'Admin\\StatController@getRanking');
$router->get ('/stat/getStatRecord', 'Admin\\StatController@getStatRecord');
// Notice
$router->get ('/notice/fetch', 'Admin\\NoticeController@fetch');
$router->post('/notice/save', 'Admin\\NoticeController@save');
@ -128,13 +112,8 @@ class AdminRoute
$router->post('/payment/save', 'Admin\\PaymentController@save');
$router->post('/payment/drop', 'Admin\\PaymentController@drop');
$router->post('/payment/show', 'Admin\\PaymentController@show');
$router->post('/payment/sort', 'Admin\\PaymentController@sort');
// System
$router->get ('/system/getSystemStatus', 'Admin\\SystemController@getSystemStatus');
$router->get ('/system/getQueueStats', 'Admin\\SystemController@getQueueStats');
$router->get ('/system/getQueueWorkload', 'Admin\\SystemController@getQueueWorkload');
$router->get ('/system/getQueueMasters', '\\Laravel\\Horizon\\Http\\Controllers\\MasterSupervisorController@index');
$router->get ('/system/getSystemLog', 'Admin\\SystemController@getSystemLog');
$router->get ('/system/getStatus', 'Admin\\SystemController@getStatus');
// Theme
$router->get ('/theme/getThemes', 'Admin\\ThemeController@getThemes');
$router->post('/theme/saveThemeConfig', 'Admin\\ThemeController@saveThemeConfig');

View File

@ -14,6 +14,7 @@ class ClientRoute
// Client
$router->get('/subscribe', 'Client\\ClientController@subscribe');
// App
$router->get('/app/config', 'Client\\AppController@config');
$router->get('/app/getConfig', 'Client\\AppController@getConfig');
$router->get('/app/getVersion', 'Client\\AppController@getVersion');
});

View File

@ -14,10 +14,12 @@ class PassportRoute
$router->post('/auth/register', 'Passport\\AuthController@register');
$router->post('/auth/login', 'Passport\\AuthController@login');
$router->get ('/auth/token2Login', 'Passport\\AuthController@token2Login');
$router->get ('/auth/check', 'Passport\\AuthController@check');
$router->post('/auth/forget', 'Passport\\AuthController@forget');
$router->post('/auth/getTempToken', 'Passport\\AuthController@getTempToken');
$router->post('/auth/getQuickLoginUrl', 'Passport\\AuthController@getQuickLoginUrl');
$router->post('/auth/loginWithMailLink', 'Passport\\AuthController@loginWithMailLink');
// Comm
$router->get ('/comm/config', 'Passport\\CommController@config');
$router->post('/comm/sendEmailVerify', 'Passport\\CommController@sendEmailVerify');
$router->post('/comm/pv', 'Passport\\CommController@pv');
});

View File

@ -13,20 +13,21 @@ class UserRoute
], function ($router) {
// User
$router->get ('/resetSecurity', 'User\\UserController@resetSecurity');
$router->get ('/logout', 'User\\UserController@logout');
$router->get ('/info', 'User\\UserController@info');
$router->post('/changePassword', 'User\\UserController@changePassword');
$router->post('/update', 'User\\UserController@update');
$router->get ('/getSubscribe', 'User\\UserController@getSubscribe');
$router->get ('/getStat', 'User\\UserController@getStat');
$router->get ('/checkLogin', 'User\\UserController@checkLogin');
$router->post('/transfer', 'User\\UserController@transfer');
$router->post('/getQuickLoginUrl', 'User\\UserController@getQuickLoginUrl');
$router->get ('/getActiveSession', 'User\\UserController@getActiveSession');
$router->post('/removeActiveSession', 'User\\UserController@removeActiveSession');
// Order
$router->post('/order/save', 'User\\OrderController@save');
$router->post('/order/checkout', 'User\\OrderController@checkout');
$router->get ('/order/check', 'User\\OrderController@check');
// TODO: 1.5.6 remove
$router->get ('/order/details', 'User\\OrderController@detail');
// TODO: 1.5.6 remove
$router->get ('/order/detail', 'User\\OrderController@detail');
$router->get ('/order/fetch', 'User\\OrderController@fetch');
$router->get ('/order/getPaymentMethod', 'User\\OrderController@getPaymentMethod');

View File

@ -15,8 +15,6 @@ class OrderHandleJob implements ShouldQueue
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $order;
public $tries = 3;
public $timeout = 5;
/**
* Create a new job instance.
*

View File

@ -16,8 +16,6 @@ class SendEmailJob implements ShouldQueue
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $params;
public $tries = 3;
public $timeout = 10;
/**
* Create a new job instance.
*

View File

@ -16,7 +16,7 @@ class SendTelegramJob implements ShouldQueue
protected $text;
public $tries = 3;
public $timeout = 10;
public $timeout = 5;
/**
* Create a new job instance.

View File

@ -0,0 +1,78 @@
<?php
namespace App\Jobs;
use App\Models\StatServer;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class StatServerJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $u;
protected $d;
protected $server;
protected $protocol;
protected $recordType;
public $tries = 3;
public $timeout = 60;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($u, $d, $server, $protocol, $recordType = 'd')
{
$this->onQueue('stat');
$this->u = $u;
$this->d = $d;
$this->server = $server;
$this->protocol = $protocol;
$this->recordType = $recordType;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$recordAt = strtotime(date('Y-m-d'));
if ($this->recordType === 'm') {
//
}
$data = StatServer::where('record_at', $recordAt)
->where('server_id', $this->server->id)
->where('server_type', $this->protocol)
->lockForUpdate()
->first();
if ($data) {
try {
$data->update([
'u' => $data['u'] + $this->u,
'd' => $data['d'] + $this->d
]);
} catch (\Exception $e) {
abort(500, '节点统计数据更新失败');
}
} else {
if (!StatServer::create([
'server_id' => $this->server->id,
'server_type' => $this->protocol,
'u' => $this->u,
'd' => $this->d,
'record_type' => $this->recordType,
'record_at' => $recordAt
])) {
abort(500, '节点统计数据创建失败');
}
}
}
}

80
app/Jobs/StatUserJob.php Normal file
View File

@ -0,0 +1,80 @@
<?php
namespace App\Jobs;
use App\Models\StatServer;
use App\Models\StatUser;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class StatUserJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $u;
protected $d;
protected $userId;
protected $server;
protected $protocol;
protected $recordType;
public $tries = 3;
public $timeout = 60;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($u, $d, $userId, $server, $protocol, $recordType = 'd')
{
$this->onQueue('stat');
$this->u = $u;
$this->d = $d;
$this->userId = $userId;
$this->server = $server;
$this->protocol = $protocol;
$this->recordType = $recordType;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$recordAt = strtotime(date('Y-m-d'));
if ($this->recordType === 'm') {
//
}
$data = StatUser::where('record_at', $recordAt)
->where('server_rate', $this->server->rate)
->where('user_id', $this->userId)
->first();
if ($data) {
try {
$data->update([
'u' => $data['u'] + $this->u,
'd' => $data['d'] + $this->d
]);
} catch (\Exception $e) {
abort(500, '用户统计数据更新失败');
}
} else {
if (!StatUser::create([
'user_id' => $this->userId,
'server_rate' => $this->server->rate,
'u' => $this->u,
'd' => $this->d,
'record_type' => $this->recordType,
'record_at' => $recordAt
])) {
abort(500, '用户统计数据创建失败');
}
}
}
}

View File

@ -20,14 +20,14 @@ class TrafficFetchJob implements ShouldQueue
protected $protocol;
public $tries = 3;
public $timeout = 10;
public $timeout = 3;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($u, $d, $userId, array $server, $protocol)
public function __construct($u, $d, $userId, $server, $protocol)
{
$this->onQueue('traffic_fetch');
$this->u = $u;
@ -48,10 +48,10 @@ class TrafficFetchJob implements ShouldQueue
if (!$user) return;
$user->t = time();
$user->u = $user->u + ($this->u * $this->server['rate']);
$user->d = $user->d + ($this->d * $this->server['rate']);
if (!$user->save()) {
info("流量更新失败\n未记录用户ID:{$this->userId}\n未记录上行:{$user->u}\n未记录下行:{$user->d}");
}
$user->u = $user->u + $this->u;
$user->d = $user->d + $this->d;
if (!$user->save()) throw new \Exception('流量更新失败');
$mailService = new MailService();
$mailService->remindTraffic($user);
}
}

View File

@ -1,11 +0,0 @@
<?php
namespace App\Logging;
class MysqlLogger
{
public function __invoke(array $config){
return tap(new \Monolog\Logger('mysql'), function ($logger) {
$logger->pushHandler(new MysqlLoggerHandler());
});
}
}

View File

@ -1,44 +0,0 @@
<?php
namespace App\Logging;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Monolog\Handler\AbstractProcessingHandler;
use Monolog\Logger;
use App\Models\Log as LogModel;
class MysqlLoggerHandler extends AbstractProcessingHandler
{
public function __construct($level = Logger::DEBUG, bool $bubble = true)
{
parent::__construct($level, $bubble);
}
protected function write(array $record): void
{
try{
if(isset($record['context']['exception']) && is_object($record['context']['exception'])){
$record['context']['exception'] = (array)$record['context']['exception'];
}
$record['request_data'] = request()->all() ??[];
$log = [
'title' => $record['message'],
'level' => $record['level_name'],
'host' => $record['request_host'] ?? request()->getSchemeAndHttpHost(),
'uri' => $record['request_uri'] ?? request()->getRequestUri(),
'method' => $record['request_method'] ?? request()->getMethod(),
'ip' => request()->getClientIp(),
'data' => json_encode($record['request_data']) ,
'context' => isset($record['context']) ? json_encode($record['context']) : '',
'created_at' => strtotime($record['datetime']),
'updated_at' => strtotime($record['datetime']),
];
LogModel::insert(
$log
);
}catch (\Exception $e){
Log::channel('daily')->error($e->getMessage().$e->getFile().$e->getTraceAsString());
}
}
}

View File

@ -1,19 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class ServerHysteria extends Model
{
protected $table = 'v2_server_hysteria';
protected $dateFormat = 'U';
protected $guarded = ['id'];
protected $casts = [
'created_at' => 'timestamp',
'updated_at' => 'timestamp',
'group_id' => 'array',
'route_id' => 'array',
'tags' => 'array'
];
}

View File

@ -1,16 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class ServerRoute extends Model
{
protected $table = 'v2_server_route';
protected $dateFormat = 'U';
protected $guarded = ['id'];
protected $casts = [
'created_at' => 'timestamp',
'updated_at' => 'timestamp',
];
}

View File

@ -13,7 +13,6 @@ class ServerShadowsocks extends Model
'created_at' => 'timestamp',
'updated_at' => 'timestamp',
'group_id' => 'array',
'route_id' => 'array',
'tags' => 'array',
'obfs_settings' => 'array'
];

Some files were not shown because too many files have changed in this diff Show More