id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
10,637
|
mainwindow_grpc.cpp
|
MatsuriDayo_nekoray/ui/mainwindow_grpc.cpp
|
#include "./ui_mainwindow.h"
#include "mainwindow.h"
#include "db/Database.hpp"
#include "db/ConfigBuilder.hpp"
#include "db/traffic/TrafficLooper.hpp"
#include "rpc/gRPC.h"
#include "ui/widget/MessageBoxTimer.h"
#include <QTimer>
#include <QThread>
#include <QInputDialog>
#include <QPushButton>
#include <QDesktopServices>
#include <QMessageBox>
#include <QDialogButtonBox>
// ext core
std::list<std::shared_ptr<NekoGui_sys::ExternalProcess>> CreateExtCFromExtR(const std::list<std::shared_ptr<NekoGui_fmt::ExternalBuildResult>> &extRs, bool start) {
// plz run and start in same thread
std::list<std::shared_ptr<NekoGui_sys::ExternalProcess>> l;
for (const auto &extR: extRs) {
std::shared_ptr<NekoGui_sys::ExternalProcess> extC(new NekoGui_sys::ExternalProcess());
extC->tag = extR->tag;
extC->program = extR->program;
extC->arguments = extR->arguments;
extC->env = extR->env;
l.emplace_back(extC);
//
if (start) extC->Start();
}
return l;
}
// grpc
#ifndef NKR_NO_GRPC
using namespace NekoGui_rpc;
#endif
void MainWindow::setup_grpc() {
#ifndef NKR_NO_GRPC
// Setup Connection
defaultClient = new Client(
[=](const QString &errStr) {
MW_show_log("[Error] gRPC: " + errStr);
},
"127.0.0.1:" + Int2String(NekoGui::dataStore->core_port), NekoGui::dataStore->core_token);
// Looper
runOnNewThread([=] { NekoGui_traffic::trafficLooper->Loop(); });
#endif
}
// 测速
inline bool speedtesting = false;
inline QList<QThread *> speedtesting_threads = {};
void MainWindow::speedtest_current_group(int mode, bool test_group) {
if (speedtesting) {
MessageBoxWarning(software_name, QObject::tr("The last speed test did not exit completely, please wait. If it persists, please restart the program."));
return;
}
auto profiles = get_selected_or_group();
if (test_group) profiles = NekoGui::profileManager->CurrentGroup()->ProfilesWithOrder();
if (profiles.isEmpty()) return;
auto group = NekoGui::profileManager->CurrentGroup();
if (group->archive) return;
// menu_stop_testing
if (mode == 114514) {
while (!speedtesting_threads.isEmpty()) {
auto t = speedtesting_threads.takeFirst();
if (t != nullptr) t->exit();
}
speedtesting = false;
return;
}
#ifndef NKR_NO_GRPC
QStringList full_test_flags;
if (mode == libcore::FullTest) {
auto w = new QDialog(this);
auto layout = new QVBoxLayout(w);
w->setWindowTitle(tr("Test Options"));
//
auto l1 = new QCheckBox(tr("Latency"));
auto l2 = new QCheckBox(tr("UDP latency"));
auto l3 = new QCheckBox(tr("Download speed"));
auto l4 = new QCheckBox(tr("In and Out IP"));
//
auto box = new QDialogButtonBox;
box->setOrientation(Qt::Horizontal);
box->setStandardButtons(QDialogButtonBox::Cancel | QDialogButtonBox::Ok);
connect(box, &QDialogButtonBox::accepted, w, &QDialog::accept);
connect(box, &QDialogButtonBox::rejected, w, &QDialog::reject);
//
layout->addWidget(l1);
layout->addWidget(l2);
layout->addWidget(l3);
layout->addWidget(l4);
layout->addWidget(box);
if (w->exec() != QDialog::Accepted) {
w->deleteLater();
return;
}
//
if (l1->isChecked()) full_test_flags << "1";
if (l2->isChecked()) full_test_flags << "2";
if (l3->isChecked()) full_test_flags << "3";
if (l4->isChecked()) full_test_flags << "4";
//
w->deleteLater();
if (full_test_flags.isEmpty()) return;
}
speedtesting = true;
runOnNewThread([this, profiles, mode, full_test_flags]() {
QMutex lock_write;
QMutex lock_return;
int threadN = NekoGui::dataStore->test_concurrent;
int threadN_finished = 0;
auto profiles_test = profiles; // copy
// Threads
lock_return.lock();
for (int i = 0; i < threadN; i++) {
runOnNewThread([&] {
speedtesting_threads << QObject::thread();
forever {
//
lock_write.lock();
if (profiles_test.isEmpty()) {
threadN_finished++;
if (threadN == threadN_finished) {
// quit control thread
lock_return.unlock();
}
lock_write.unlock();
// quit of this thread
speedtesting_threads.removeAll(QObject::thread());
return;
}
auto profile = profiles_test.takeFirst();
lock_write.unlock();
//
libcore::TestReq req;
req.set_mode((libcore::TestMode) mode);
req.set_timeout(10 * 1000);
req.set_url(NekoGui::dataStore->test_latency_url.toStdString());
//
std::list<std::shared_ptr<NekoGui_sys::ExternalProcess>> extCs;
QSemaphore extSem;
if (mode == libcore::TestMode::UrlTest || mode == libcore::FullTest) {
auto c = BuildConfig(profile, true, false);
if (!c->error.isEmpty()) {
profile->full_test_report = c->error;
profile->Save();
auto profileId = profile->id;
runOnUiThread([this, profileId] {
refresh_proxy_list(profileId);
});
continue;
}
//
if (!c->extRs.empty()) {
runOnUiThread(
[&] {
extCs = CreateExtCFromExtR(c->extRs, true);
QThread::msleep(500);
extSem.release();
},
DS_cores);
extSem.acquire();
}
//
auto config = new libcore::LoadConfigReq;
config->set_core_config(QJsonObject2QString(c->coreConfig, false).toStdString());
req.set_allocated_config(config);
req.set_in_address(profile->bean->serverAddress.toStdString());
req.set_full_latency(full_test_flags.contains("1"));
req.set_full_udp_latency(full_test_flags.contains("2"));
req.set_full_speed(full_test_flags.contains("3"));
req.set_full_in_out(full_test_flags.contains("4"));
req.set_full_speed_url(NekoGui::dataStore->test_download_url.toStdString());
req.set_full_speed_timeout(NekoGui::dataStore->test_download_timeout);
} else if (mode == libcore::TcpPing) {
req.set_address(profile->bean->DisplayAddress().toStdString());
}
bool rpcOK;
auto result = defaultClient->Test(&rpcOK, req);
//
if (!extCs.empty()) {
runOnUiThread(
[&] {
for (const auto &extC: extCs) {
extC->Kill();
}
extSem.release();
},
DS_cores);
extSem.acquire();
}
//
if (!rpcOK) return;
if (result.error().empty()) {
profile->latency = result.ms();
if (profile->latency == 0) profile->latency = 1; // nekoray use 0 to represents not tested
} else {
profile->latency = -1;
}
profile->full_test_report = result.full_report().c_str(); // higher priority
profile->Save();
if (!result.error().empty()) {
MW_show_log(tr("[%1] test error: %2").arg(profile->bean->DisplayTypeAndName(), result.error().c_str()));
}
auto profileId = profile->id;
runOnUiThread([this, profileId] {
refresh_proxy_list(profileId);
});
}
});
}
// Control
lock_return.lock();
lock_return.unlock();
speedtesting = false;
});
#endif
}
void MainWindow::speedtest_current() {
#ifndef NKR_NO_GRPC
last_test_time = QTime::currentTime();
ui->label_running->setText(tr("Testing"));
runOnNewThread([=] {
libcore::TestReq req;
req.set_mode(libcore::UrlTest);
req.set_timeout(10 * 1000);
req.set_url(NekoGui::dataStore->test_latency_url.toStdString());
bool rpcOK;
auto result = defaultClient->Test(&rpcOK, req);
if (!rpcOK) return;
auto latency = result.ms();
last_test_time = QTime::currentTime();
runOnUiThread([=] {
if (!result.error().empty()) {
MW_show_log(QString("UrlTest error: %1").arg(result.error().c_str()));
}
if (latency <= 0) {
ui->label_running->setText(tr("Test Result") + ": " + tr("Unavailable"));
} else if (latency > 0) {
ui->label_running->setText(tr("Test Result") + ": " + QString("%1 ms").arg(latency));
}
});
});
#endif
}
void MainWindow::stop_core_daemon() {
#ifndef NKR_NO_GRPC
NekoGui_rpc::defaultClient->Exit();
#endif
}
void MainWindow::neko_start(int _id) {
if (NekoGui::dataStore->prepare_exit) return;
auto ents = get_now_selected_list();
auto ent = (_id < 0 && !ents.isEmpty()) ? ents.first() : NekoGui::profileManager->GetProfile(_id);
if (ent == nullptr) return;
if (select_mode) {
emit profile_selected(ent->id);
select_mode = false;
refresh_status();
return;
}
auto group = NekoGui::profileManager->GetGroup(ent->gid);
if (group == nullptr || group->archive) return;
auto result = BuildConfig(ent, false, false);
if (!result->error.isEmpty()) {
MessageBoxWarning("BuildConfig return error", result->error);
return;
}
auto neko_start_stage2 = [=] {
#ifndef NKR_NO_GRPC
libcore::LoadConfigReq req;
req.set_core_config(QJsonObject2QString(result->coreConfig, false).toStdString());
req.set_enable_nekoray_connections(NekoGui::dataStore->connection_statistics);
if (NekoGui::dataStore->traffic_loop_interval > 0) {
req.add_stats_outbounds("proxy");
req.add_stats_outbounds("bypass");
}
//
bool rpcOK;
QString error = defaultClient->Start(&rpcOK, req);
if (rpcOK && !error.isEmpty()) {
runOnUiThread([=] { MessageBoxWarning("LoadConfig return error", error); });
return false;
} else if (!rpcOK) {
return false;
}
//
NekoGui_traffic::trafficLooper->proxy = result->outboundStat.get();
NekoGui_traffic::trafficLooper->items = result->outboundStats;
NekoGui::dataStore->ignoreConnTag = result->ignoreConnTag;
NekoGui_traffic::trafficLooper->loop_enabled = true;
#endif
runOnUiThread(
[=] {
auto extCs = CreateExtCFromExtR(result->extRs, true);
NekoGui_sys::running_ext.splice(NekoGui_sys::running_ext.end(), extCs);
},
DS_cores);
NekoGui::dataStore->UpdateStartedId(ent->id);
running = ent;
runOnUiThread([=] {
refresh_status();
refresh_proxy_list(ent->id);
});
return true;
};
if (!mu_starting.tryLock()) {
MessageBoxWarning(software_name, "Another profile is starting...");
return;
}
if (!mu_stopping.tryLock()) {
MessageBoxWarning(software_name, "Another profile is stopping...");
mu_starting.unlock();
return;
}
mu_stopping.unlock();
// check core state
if (!NekoGui::dataStore->core_running) {
runOnUiThread(
[=] {
MW_show_log("Try to start the config, but the core has not listened to the grpc port, so restart it...");
core_process->start_profile_when_core_is_up = ent->id;
core_process->Restart();
},
DS_cores);
mu_starting.unlock();
return; // let CoreProcess call neko_start when core is up
}
// timeout message
auto restartMsgbox = new QMessageBox(QMessageBox::Question, software_name, tr("If there is no response for a long time, it is recommended to restart the software."),
QMessageBox::Yes | QMessageBox::No, this);
connect(restartMsgbox, &QMessageBox::accepted, this, [=] { MW_dialog_message("", "RestartProgram"); });
auto restartMsgboxTimer = new MessageBoxTimer(this, restartMsgbox, 5000);
runOnNewThread([=] {
// stop current running
if (NekoGui::dataStore->started_id >= 0) {
runOnUiThread([=] { neko_stop(false, true); });
sem_stopped.acquire();
}
// do start
MW_show_log(">>>>>>>> " + tr("Starting profile %1").arg(ent->bean->DisplayTypeAndName()));
if (!neko_start_stage2()) {
MW_show_log("<<<<<<<< " + tr("Failed to start profile %1").arg(ent->bean->DisplayTypeAndName()));
}
mu_starting.unlock();
// cancel timeout
runOnUiThread([=] {
restartMsgboxTimer->cancel();
restartMsgboxTimer->deleteLater();
restartMsgbox->deleteLater();
#ifdef Q_OS_LINUX
// Check systemd-resolved
if (NekoGui::dataStore->spmode_vpn && NekoGui::dataStore->routing->direct_dns.startsWith("local") && ReadFileText("/etc/resolv.conf").contains("systemd-resolved")) {
MW_show_log("[Warning] The default Direct DNS may not works with systemd-resolved, you may consider change your DNS settings.");
}
#endif
});
});
}
void MainWindow::neko_stop(bool crash, bool sem) {
auto id = NekoGui::dataStore->started_id;
if (id < 0) {
if (sem) sem_stopped.release();
return;
}
auto neko_stop_stage2 = [=] {
runOnUiThread(
[=] {
while (!NekoGui_sys::running_ext.empty()) {
auto extC = NekoGui_sys::running_ext.front();
extC->Kill();
NekoGui_sys::running_ext.pop_front();
}
},
DS_cores);
#ifndef NKR_NO_GRPC
NekoGui_traffic::trafficLooper->loop_enabled = false;
NekoGui_traffic::trafficLooper->loop_mutex.lock();
if (NekoGui::dataStore->traffic_loop_interval != 0) {
NekoGui_traffic::trafficLooper->UpdateAll();
for (const auto &item: NekoGui_traffic::trafficLooper->items) {
NekoGui::profileManager->GetProfile(item->id)->Save();
runOnUiThread([=] { refresh_proxy_list(item->id); });
}
}
NekoGui_traffic::trafficLooper->loop_mutex.unlock();
if (!crash) {
bool rpcOK;
QString error = defaultClient->Stop(&rpcOK);
if (rpcOK && !error.isEmpty()) {
runOnUiThread([=] { MessageBoxWarning("Stop return error", error); });
return false;
} else if (!rpcOK) {
return false;
}
}
#endif
NekoGui::dataStore->UpdateStartedId(-1919);
NekoGui::dataStore->need_keep_vpn_off = false;
running = nullptr;
runOnUiThread([=] {
refresh_status();
refresh_proxy_list(id);
});
return true;
};
if (!mu_stopping.tryLock()) {
if (sem) sem_stopped.release();
return;
}
// timeout message
auto restartMsgbox = new QMessageBox(QMessageBox::Question, software_name, tr("If there is no response for a long time, it is recommended to restart the software."),
QMessageBox::Yes | QMessageBox::No, this);
connect(restartMsgbox, &QMessageBox::accepted, this, [=] { MW_dialog_message("", "RestartProgram"); });
auto restartMsgboxTimer = new MessageBoxTimer(this, restartMsgbox, 5000);
runOnNewThread([=] {
// do stop
MW_show_log(">>>>>>>> " + tr("Stopping profile %1").arg(running->bean->DisplayTypeAndName()));
if (!neko_stop_stage2()) {
MW_show_log("<<<<<<<< " + tr("Failed to stop, please restart the program."));
}
mu_stopping.unlock();
if (sem) sem_stopped.release();
// cancel timeout
runOnUiThread([=] {
restartMsgboxTimer->cancel();
restartMsgboxTimer->deleteLater();
restartMsgbox->deleteLater();
});
});
}
void MainWindow::CheckUpdate() {
// on new thread...
#ifndef NKR_NO_GRPC
bool ok;
libcore::UpdateReq request;
request.set_action(libcore::UpdateAction::Check);
request.set_check_pre_release(NekoGui::dataStore->check_include_pre);
auto response = NekoGui_rpc::defaultClient->Update(&ok, request);
if (!ok) return;
auto err = response.error();
if (!err.empty()) {
runOnUiThread([=] {
MessageBoxWarning(QObject::tr("Update"), err.c_str());
});
return;
}
if (response.release_download_url() == nullptr) {
runOnUiThread([=] {
MessageBoxInfo(QObject::tr("Update"), QObject::tr("No update"));
});
return;
}
runOnUiThread([=] {
auto allow_updater = !NekoGui::dataStore->flag_use_appdata;
auto note_pre_release = response.is_pre_release() ? " (Pre-release)" : "";
QMessageBox box(QMessageBox::Question, QObject::tr("Update") + note_pre_release,
QObject::tr("Update found: %1\nRelease note:\n%2").arg(response.assets_name().c_str(), response.release_note().c_str()));
//
QAbstractButton *btn1 = nullptr;
if (allow_updater) {
btn1 = box.addButton(QObject::tr("Update"), QMessageBox::AcceptRole);
}
QAbstractButton *btn2 = box.addButton(QObject::tr("Open in browser"), QMessageBox::AcceptRole);
box.addButton(QObject::tr("Close"), QMessageBox::RejectRole);
box.exec();
//
if (btn1 == box.clickedButton() && allow_updater) {
// Download Update
runOnNewThread([=] {
bool ok2;
libcore::UpdateReq request2;
request2.set_action(libcore::UpdateAction::Download);
auto response2 = NekoGui_rpc::defaultClient->Update(&ok2, request2);
runOnUiThread([=] {
if (response2.error().empty()) {
auto q = QMessageBox::question(nullptr, QObject::tr("Update"),
QObject::tr("Update is ready, restart to install?"));
if (q == QMessageBox::StandardButton::Yes) {
this->exit_reason = 1;
on_menu_exit_triggered();
}
} else {
MessageBoxWarning(QObject::tr("Update"), response2.error().c_str());
}
});
});
} else if (btn2 == box.clickedButton()) {
QDesktopServices::openUrl(QUrl(response.release_url().c_str()));
}
});
#endif
}
| 20,326
|
C++
|
.cpp
| 492
| 29.276423
| 177
| 0.533714
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,638
|
dialog_hotkey.cpp
|
MatsuriDayo_nekoray/ui/dialog_hotkey.cpp
|
#include "dialog_hotkey.h"
#include "ui_dialog_hotkey.h"
#include "ui/mainwindow_interface.h"
DialogHotkey::DialogHotkey(QWidget *parent) : QDialog(parent), ui(new Ui::DialogHotkey) {
ui->setupUi(this);
ui->show_mainwindow->setKeySequence(NekoGui::dataStore->hotkey_mainwindow);
ui->show_groups->setKeySequence(NekoGui::dataStore->hotkey_group);
ui->show_routes->setKeySequence(NekoGui::dataStore->hotkey_route);
ui->system_proxy->setKeySequence(NekoGui::dataStore->hotkey_system_proxy_menu);
GetMainWindow()->RegisterHotkey(true);
}
DialogHotkey::~DialogHotkey() {
if (result() == QDialog::Accepted) {
NekoGui::dataStore->hotkey_mainwindow = ui->show_mainwindow->keySequence().toString();
NekoGui::dataStore->hotkey_group = ui->show_groups->keySequence().toString();
NekoGui::dataStore->hotkey_route = ui->show_routes->keySequence().toString();
NekoGui::dataStore->hotkey_system_proxy_menu = ui->system_proxy->keySequence().toString();
NekoGui::dataStore->Save();
}
GetMainWindow()->RegisterHotkey(false);
delete ui;
}
| 1,103
|
C++
|
.cpp
| 22
| 45.363636
| 98
| 0.718924
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,639
|
ProxyItem.cpp
|
MatsuriDayo_nekoray/ui/widget/ProxyItem.cpp
|
#include "ProxyItem.h"
#include "ui_ProxyItem.h"
#include <QMessageBox>
ProxyItem::ProxyItem(QWidget *parent, const std::shared_ptr<NekoGui::ProxyEntity> &ent, QListWidgetItem *item)
: QWidget(parent), ui(new Ui::ProxyItem) {
ui->setupUi(this);
this->setLayoutDirection(Qt::LeftToRight);
this->item = item;
this->ent = ent;
if (ent == nullptr) return;
refresh_data();
}
ProxyItem::~ProxyItem() {
delete ui;
}
void ProxyItem::refresh_data() {
ui->type->setText(ent->bean->DisplayType());
ui->name->setText(ent->bean->DisplayName());
ui->address->setText(ent->bean->DisplayAddress());
ui->traffic->setText(ent->traffic_data->DisplayTraffic());
ui->test_result->setText(ent->DisplayLatency());
runOnUiThread(
[=] {
adjustSize();
item->setSizeHint(sizeHint());
dynamic_cast<QWidget *>(parent())->adjustSize();
},
this);
}
void ProxyItem::on_remove_clicked() {
if (!this->remove_confirm ||
QMessageBox::question(this, tr("Confirmation"), tr("Remove %1?").arg(ent->bean->DisplayName())) == QMessageBox::StandardButton::Yes) {
// TODO do remove (or not) -> callback
delete item;
}
}
QPushButton *ProxyItem::get_change_button() {
return ui->change;
}
| 1,304
|
C++
|
.cpp
| 39
| 28.307692
| 142
| 0.644108
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,640
|
GroupItem.cpp
|
MatsuriDayo_nekoray/ui/widget/GroupItem.cpp
|
#include "GroupItem.h"
#include "ui_GroupItem.h"
#include "ui/edit/dialog_edit_group.h"
#include "main/GuiUtils.hpp"
#include "sub/GroupUpdater.hpp"
#include <QMessageBox>
QString ParseSubInfo(const QString &info) {
if (info.trimmed().isEmpty()) return "";
QString result;
long long used = 0;
long long total = 0;
long long expire = 0;
auto re0m = QRegularExpression("total=([0-9]+)").match(info);
if (re0m.lastCapturedIndex() >= 1) {
total = re0m.captured(1).toLongLong();
} else {
return "";
}
auto re1m = QRegularExpression("upload=([0-9]+)").match(info);
if (re1m.lastCapturedIndex() >= 1) {
used += re1m.captured(1).toLongLong();
}
auto re2m = QRegularExpression("download=([0-9]+)").match(info);
if (re2m.lastCapturedIndex() >= 1) {
used += re2m.captured(1).toLongLong();
}
auto re3m = QRegularExpression("expire=([0-9]+)").match(info);
if (re3m.lastCapturedIndex() >= 1) {
expire = re3m.captured(1).toLongLong();
}
result = QObject::tr("Used: %1 Remain: %2 Expire: %3")
.arg(ReadableSize(used), ReadableSize(total - used), DisplayTime(expire, QLocale::ShortFormat));
return result;
}
GroupItem::GroupItem(QWidget *parent, const std::shared_ptr<NekoGui::Group> &ent, QListWidgetItem *item) : QWidget(parent), ui(new Ui::GroupItem) {
ui->setupUi(this);
this->setLayoutDirection(Qt::LeftToRight);
this->parentWindow = parent;
this->ent = ent;
this->item = item;
if (ent == nullptr) return;
connect(this, &GroupItem::edit_clicked, this, &GroupItem::on_edit_clicked);
connect(NekoGui_sub::groupUpdater, &NekoGui_sub::GroupUpdater::asyncUpdateCallback, this, [=](int gid) { if (gid == this->ent->id) refresh_data(); });
refresh_data();
}
GroupItem::~GroupItem() {
delete ui;
}
void GroupItem::refresh_data() {
ui->name->setText(ent->name);
auto type = ent->url.isEmpty() ? tr("Basic") : tr("Subscription");
if (ent->archive) type = tr("Archive") + " " + type;
type += " (" + Int2String(ent->Profiles().length()) + ")";
ui->type->setText(type);
if (ent->url.isEmpty()) {
ui->url->hide();
ui->subinfo->hide();
ui->update_sub->hide();
} else {
ui->url->setText(ent->url);
QStringList info;
if (ent->sub_last_update != 0) {
info << tr("Last update: %1").arg(DisplayTime(ent->sub_last_update, QLocale::ShortFormat));
}
auto subinfo = ParseSubInfo(ent->info);
if (!ent->info.isEmpty()) {
info << subinfo;
}
if (info.isEmpty()) {
ui->subinfo->hide();
} else {
ui->subinfo->show();
ui->subinfo->setText(info.join(" | "));
}
}
runOnUiThread(
[=] {
adjustSize();
item->setSizeHint(sizeHint());
dynamic_cast<QWidget *>(parent())->adjustSize();
},
this);
}
void GroupItem::on_update_sub_clicked() {
NekoGui_sub::groupUpdater->AsyncUpdate(ent->url, ent->id);
}
void GroupItem::on_edit_clicked() {
auto dialog = new DialogEditGroup(ent, parentWindow);
connect(dialog, &QDialog::finished, this, [=] {
if (dialog->result() == QDialog::Accepted) {
ent->Save();
refresh_data();
MW_dialog_message(Dialog_DialogManageGroups, "refresh" + Int2String(ent->id));
}
dialog->deleteLater();
});
dialog->show();
}
void GroupItem::on_remove_clicked() {
if (NekoGui::profileManager->groups.size() <= 1) return;
if (QMessageBox::question(this, tr("Confirmation"), tr("Remove %1?").arg(ent->name)) ==
QMessageBox::StandardButton::Yes) {
NekoGui::profileManager->DeleteGroup(ent->id);
MW_dialog_message(Dialog_DialogManageGroups, "refresh-1");
delete item;
}
}
| 3,909
|
C++
|
.cpp
| 107
| 30.11215
| 154
| 0.602696
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,641
|
dialog_edit_group.cpp
|
MatsuriDayo_nekoray/ui/edit/dialog_edit_group.cpp
|
#include "dialog_edit_group.h"
#include "ui_dialog_edit_group.h"
#include "db/Database.hpp"
#include "ui/mainwindow_interface.h"
#include <QClipboard>
#define ADJUST_SIZE runOnUiThread([=] { adjustSize(); adjustPosition(mainwindow); }, this);
DialogEditGroup::DialogEditGroup(const std::shared_ptr<NekoGui::Group> &ent, QWidget *parent) : QDialog(parent), ui(new Ui::DialogEditGroup) {
ui->setupUi(this);
this->ent = ent;
connect(ui->type, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, [=](int index) {
ui->cat_sub->setHidden(index == 0);
ADJUST_SIZE
});
ui->name->setText(ent->name);
ui->archive->setChecked(ent->archive);
ui->skip_auto_update->setChecked(ent->skip_auto_update);
ui->url->setText(ent->url);
ui->type->setCurrentIndex(ent->url.isEmpty() ? 0 : 1);
ui->type->currentIndexChanged(ui->type->currentIndex());
ui->manually_column_width->setChecked(ent->manually_column_width);
ui->cat_share->setVisible(false);
if (ent->id >= 0) { // already a group
ui->type->setDisabled(true);
if (!ent->Profiles().isEmpty()) {
ui->cat_share->setVisible(true);
}
} else { // new group
ui->front_proxy->hide();
ui->front_proxy_l->hide();
ui->front_proxy_clear->hide();
}
CACHE.front_proxy = ent->front_proxy_id;
refresh_front_proxy();
connect(ui->front_proxy_clear, &QPushButton::clicked, this, [=] {
CACHE.front_proxy = -1;
refresh_front_proxy();
});
connect(ui->copy_links, &QPushButton::clicked, this, [=] {
QStringList links;
for (const auto &[_, profile]: NekoGui::profileManager->profiles) {
if (profile->gid != ent->id) continue;
links += profile->bean->ToShareLink();
}
QApplication::clipboard()->setText(links.join("\n"));
MessageBoxInfo(software_name, tr("Copied"));
});
connect(ui->copy_links_nkr, &QPushButton::clicked, this, [=] {
QStringList links;
for (const auto &[_, profile]: NekoGui::profileManager->profiles) {
if (profile->gid != ent->id) continue;
links += profile->bean->ToNekorayShareLink(profile->type);
}
QApplication::clipboard()->setText(links.join("\n"));
MessageBoxInfo(software_name, tr("Copied"));
});
ADJUST_SIZE
}
DialogEditGroup::~DialogEditGroup() {
delete ui;
}
void DialogEditGroup::accept() {
if (ent->id >= 0) { // already a group
if (!ent->url.isEmpty() && ui->url->text().isEmpty()) {
MessageBoxWarning(tr("Warning"), tr("Please input URL"));
return;
}
}
ent->name = ui->name->text();
ent->url = ui->url->text();
ent->archive = ui->archive->isChecked();
ent->skip_auto_update = ui->skip_auto_update->isChecked();
ent->manually_column_width = ui->manually_column_width->isChecked();
ent->front_proxy_id = CACHE.front_proxy;
QDialog::accept();
}
void DialogEditGroup::refresh_front_proxy() {
auto fEnt = NekoGui::profileManager->GetProfile(CACHE.front_proxy);
ui->front_proxy->setText(fEnt == nullptr ? tr("None") : fEnt->bean->DisplayTypeAndName());
}
void DialogEditGroup::on_front_proxy_clicked() {
auto parent = dynamic_cast<QWidget *>(this->parent());
parent->hide();
this->hide();
GetMainWindow()->start_select_mode(this, [=](int id) {
CACHE.front_proxy = id;
refresh_front_proxy();
parent->show();
show();
});
}
| 3,556
|
C++
|
.cpp
| 90
| 33.288889
| 142
| 0.622538
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,642
|
edit_vmess.cpp
|
MatsuriDayo_nekoray/ui/edit/edit_vmess.cpp
|
#include "edit_vmess.h"
#include "ui_edit_vmess.h"
#include "fmt/VMessBean.hpp"
#include <QUuid>
EditVMess::EditVMess(QWidget *parent) : QWidget(parent), ui(new Ui::EditVMess) {
ui->setupUi(this);
connect(ui->uuidgen, &QPushButton::clicked, this, [=] { ui->uuid->setText(QUuid::createUuid().toString().remove("{").remove("}")); });
}
EditVMess::~EditVMess() {
delete ui;
}
void EditVMess::onStart(std::shared_ptr<NekoGui::ProxyEntity> _ent) {
this->ent = _ent;
auto bean = this->ent->VMessBean();
ui->uuid->setText(bean->uuid);
ui->aid->setText(Int2String(bean->aid));
ui->security->setCurrentText(bean->security);
}
bool EditVMess::onEnd() {
auto bean = this->ent->VMessBean();
bean->uuid = ui->uuid->text();
bean->aid = ui->aid->text().toInt();
bean->security = ui->security->currentText();
return true;
}
| 869
|
C++
|
.cpp
| 25
| 31.32
| 138
| 0.661078
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,643
|
edit_trojan_vless.cpp
|
MatsuriDayo_nekoray/ui/edit/edit_trojan_vless.cpp
|
#include "edit_trojan_vless.h"
#include "ui_edit_trojan_vless.h"
#include "fmt/TrojanVLESSBean.hpp"
#include "fmt/Preset.hpp"
EditTrojanVLESS::EditTrojanVLESS(QWidget *parent) : QWidget(parent), ui(new Ui::EditTrojanVLESS) {
ui->setupUi(this);
}
EditTrojanVLESS::~EditTrojanVLESS() {
delete ui;
}
void EditTrojanVLESS::onStart(std::shared_ptr<NekoGui::ProxyEntity> _ent) {
this->ent = _ent;
auto bean = this->ent->TrojanVLESSBean();
if (bean->proxy_type == NekoGui_fmt::TrojanVLESSBean::proxy_VLESS) {
ui->label->setText("UUID");
}
if (bean->proxy_type != NekoGui_fmt::TrojanVLESSBean::proxy_VLESS) {
ui->flow->hide();
ui->flow_l->hide();
}
ui->password->setText(bean->password);
ui->flow->addItems(Preset::SingBox::Flows);
ui->flow->setCurrentText(bean->flow);
}
bool EditTrojanVLESS::onEnd() {
auto bean = this->ent->TrojanVLESSBean();
bean->password = ui->password->text();
bean->flow = ui->flow->currentText();
return true;
}
| 1,019
|
C++
|
.cpp
| 30
| 30
| 98
| 0.676829
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,644
|
dialog_edit_profile.cpp
|
MatsuriDayo_nekoray/ui/edit/dialog_edit_profile.cpp
|
#include "dialog_edit_profile.h"
#include "ui_dialog_edit_profile.h"
#include "ui/edit/edit_socks_http.h"
#include "ui/edit/edit_shadowsocks.h"
#include "ui/edit/edit_chain.h"
#include "ui/edit/edit_vmess.h"
#include "ui/edit/edit_trojan_vless.h"
#include "ui/edit/edit_naive.h"
#include "ui/edit/edit_quic.h"
#include "ui/edit/edit_custom.h"
#include "fmt/includes.h"
#include "fmt/Preset.hpp"
#include "3rdparty/qv2ray/v2/ui/widgets/editors/w_JsonEditor.hpp"
#include "main/GuiUtils.hpp"
#include <QInputDialog>
#define ADJUST_SIZE runOnUiThread([=] { adjustSize(); adjustPosition(mainwindow); }, this);
#define LOAD_TYPE(a) ui->type->addItem(NekoGui::ProfileManager::NewProxyEntity(a)->bean->DisplayType(), a);
DialogEditProfile::DialogEditProfile(const QString &_type, int profileOrGroupId, QWidget *parent)
: QDialog(parent), ui(new Ui::DialogEditProfile) {
// setup UI
ui->setupUi(this);
ui->dialog_layout->setAlignment(ui->left, Qt::AlignTop);
// network changed
network_title_base = ui->network_box->title();
connect(ui->network, &QComboBox::currentTextChanged, this, [=](const QString &txt) {
ui->network_box->setTitle(network_title_base.arg(txt));
// 传输设置
if (txt == "tcp") {
ui->header_type->setVisible(true);
ui->header_type_l->setVisible(true);
ui->path->setVisible(true);
ui->path_l->setVisible(true);
ui->host->setVisible(true);
ui->host_l->setVisible(true);
} else if (txt == "grpc") {
ui->header_type->setVisible(false);
ui->header_type_l->setVisible(false);
ui->path->setVisible(true);
ui->path_l->setVisible(true);
ui->host->setVisible(false);
ui->host_l->setVisible(false);
} else if (txt == "ws" || txt == "http" || txt == "httpupgrade") {
ui->header_type->setVisible(false);
ui->header_type_l->setVisible(false);
ui->path->setVisible(true);
ui->path_l->setVisible(true);
ui->host->setVisible(true);
ui->host_l->setVisible(true);
} else {
ui->header_type->setVisible(false);
ui->header_type_l->setVisible(false);
ui->path->setVisible(false);
ui->path_l->setVisible(false);
ui->host->setVisible(false);
ui->host_l->setVisible(false);
}
// 传输设置 ED
if (txt == "ws") {
ui->ws_early_data_length->setVisible(true);
ui->ws_early_data_length_l->setVisible(true);
ui->ws_early_data_name->setVisible(true);
ui->ws_early_data_name_l->setVisible(true);
} else {
ui->ws_early_data_length->setVisible(false);
ui->ws_early_data_length_l->setVisible(false);
ui->ws_early_data_name->setVisible(false);
ui->ws_early_data_name_l->setVisible(false);
}
// 传输设置 for NekoBox
if (!ui->utlsFingerprint->count()) ui->utlsFingerprint->addItems(Preset::SingBox::UtlsFingerPrint);
// 传输设置 是否可见
int networkBoxVisible = 0;
for (auto label: ui->network_box->findChildren<QLabel *>()) {
if (!label->isHidden()) networkBoxVisible++;
}
ui->network_box->setVisible(networkBoxVisible);
ADJUST_SIZE
});
ui->network->removeItem(0);
// security changed
connect(ui->security, &QComboBox::currentTextChanged, this, [=](const QString &txt) {
if (txt == "tls") {
ui->security_box->setVisible(true);
ui->tls_camouflage_box->setVisible(true);
ui->reality_spx->hide();
ui->reality_spx_l->hide();
} else {
ui->security_box->setVisible(false);
ui->tls_camouflage_box->setVisible(false);
}
ADJUST_SIZE
});
emit ui->security->currentTextChanged(ui->security->currentText());
// 确定模式和 ent
newEnt = _type != "";
if (newEnt) {
this->groupId = profileOrGroupId;
this->type = _type;
// load type to combo box
LOAD_TYPE("socks")
LOAD_TYPE("http")
LOAD_TYPE("shadowsocks")
LOAD_TYPE("trojan")
LOAD_TYPE("vmess")
LOAD_TYPE("vless")
LOAD_TYPE("naive")
LOAD_TYPE("hysteria2")
LOAD_TYPE("tuic")
ui->type->addItem(tr("Custom (%1 outbound)").arg(software_core_name), "internal");
ui->type->addItem(tr("Custom (%1 config)").arg(software_core_name), "internal-full");
ui->type->addItem(tr("Custom (Extra Core)"), "custom");
LOAD_TYPE("chain")
// type changed
connect(ui->type, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, [=](int index) {
typeSelected(ui->type->itemData(index).toString());
});
ui->apply_to_group->hide();
} else {
this->ent = NekoGui::profileManager->GetProfile(profileOrGroupId);
if (this->ent == nullptr) return;
this->type = ent->type;
ui->type->setVisible(false);
ui->type_l->setVisible(false);
}
typeSelected(this->type);
}
DialogEditProfile::~DialogEditProfile() {
delete ui;
}
void DialogEditProfile::typeSelected(const QString &newType) {
QString customType;
type = newType;
bool validType = true;
if (type == "socks" || type == "http") {
auto _innerWidget = new EditSocksHttp(this);
innerWidget = _innerWidget;
innerEditor = _innerWidget;
} else if (type == "shadowsocks") {
auto _innerWidget = new EditShadowSocks(this);
innerWidget = _innerWidget;
innerEditor = _innerWidget;
} else if (type == "chain") {
auto _innerWidget = new EditChain(this);
innerWidget = _innerWidget;
innerEditor = _innerWidget;
} else if (type == "vmess") {
auto _innerWidget = new EditVMess(this);
innerWidget = _innerWidget;
innerEditor = _innerWidget;
} else if (type == "trojan" || type == "vless") {
auto _innerWidget = new EditTrojanVLESS(this);
innerWidget = _innerWidget;
innerEditor = _innerWidget;
} else if (type == "naive") {
auto _innerWidget = new EditNaive(this);
innerWidget = _innerWidget;
innerEditor = _innerWidget;
} else if (type == "hysteria2" || type == "tuic") {
auto _innerWidget = new EditQUIC(this);
innerWidget = _innerWidget;
innerEditor = _innerWidget;
} else if (type == "custom" || type == "internal" || type == "internal-full") {
auto _innerWidget = new EditCustom(this);
innerWidget = _innerWidget;
innerEditor = _innerWidget;
customType = newEnt ? type : ent->CustomBean()->core;
if (customType != "custom") _innerWidget->preset_core = customType;
type = "custom";
} else {
validType = false;
}
if (!validType) {
MessageBoxWarning(newType, "Wrong type");
return;
}
if (newEnt) {
this->ent = NekoGui::ProfileManager::NewProxyEntity(type);
this->ent->gid = groupId;
}
// hide some widget
auto showAddressPort = type != "chain" && customType != "internal" && customType != "internal-full";
ui->address->setVisible(showAddressPort);
ui->address_l->setVisible(showAddressPort);
ui->port->setVisible(showAddressPort);
ui->port_l->setVisible(showAddressPort);
// 右边 stream
auto stream = GetStreamSettings(ent->bean.get());
if (stream != nullptr) {
ui->right_all_w->setVisible(true);
ui->network->setCurrentText(stream->network);
ui->security->setCurrentText(stream->security);
ui->packet_encoding->setCurrentText(stream->packet_encoding);
ui->path->setText(stream->path);
ui->host->setText(stream->host);
ui->sni->setText(stream->sni);
ui->alpn->setText(stream->alpn);
if (newEnt) {
ui->utlsFingerprint->setCurrentText(NekoGui::dataStore->utlsFingerprint);
} else {
ui->utlsFingerprint->setCurrentText(stream->utlsFingerprint);
}
ui->insecure->setChecked(stream->allow_insecure);
ui->header_type->setCurrentText(stream->header_type);
ui->ws_early_data_name->setText(stream->ws_early_data_name);
ui->ws_early_data_length->setText(Int2String(stream->ws_early_data_length));
ui->reality_pbk->setText(stream->reality_pbk);
ui->reality_sid->setText(stream->reality_sid);
ui->multiplex->setCurrentIndex(stream->multiplex_status);
CACHE.certificate = stream->certificate;
} else {
ui->right_all_w->setVisible(false);
}
// left: custom
CACHE.custom_config = ent->bean->custom_config;
CACHE.custom_outbound = ent->bean->custom_outbound;
bool show_custom_config = true;
bool show_custom_outbound = true;
if (type == "chain") {
show_custom_outbound = false;
} else if (type == "custom") {
if (customType == "internal") {
show_custom_outbound = false;
} else if (customType == "internal-full") {
show_custom_outbound = false;
show_custom_config = false;
}
}
ui->custom_box->setVisible(show_custom_outbound);
ui->custom_global_box->setVisible(show_custom_config);
// 左边 bean
auto old = ui->bean->layout()->itemAt(0)->widget();
ui->bean->layout()->removeWidget(old);
innerWidget->layout()->setContentsMargins(0, 0, 0, 0);
ui->bean->layout()->addWidget(innerWidget);
ui->bean->setTitle(ent->bean->DisplayType());
delete old;
// 左边 bean inner editor
innerEditor->get_edit_dialog = [&]() { return (QWidget *) this; };
innerEditor->get_edit_text_name = [&]() { return ui->name->text(); };
innerEditor->get_edit_text_serverAddress = [&]() { return ui->address->text(); };
innerEditor->get_edit_text_serverPort = [&]() { return ui->port->text(); };
innerEditor->editor_cache_updated = [=] { editor_cache_updated_impl(); };
innerEditor->onStart(ent);
// 左边 common
ui->name->setText(ent->bean->name);
ui->address->setText(ent->bean->serverAddress);
ui->port->setText(Int2String(ent->bean->serverPort));
ui->port->setValidator(QRegExpValidator_Number);
// 星号
ADD_ASTERISK(this)
// 设置 for NekoBox
if (type == "vmess" || type == "vless") {
ui->packet_encoding->setVisible(true);
ui->packet_encoding_l->setVisible(true);
} else {
ui->packet_encoding->setVisible(false);
ui->packet_encoding_l->setVisible(false);
}
if (type == "vmess" || type == "vless" || type == "trojan") {
ui->network_l->setVisible(true);
ui->network->setVisible(true);
ui->network_box->setVisible(true);
} else {
ui->network_l->setVisible(false);
ui->network->setVisible(false);
ui->network_box->setVisible(false);
}
if (type == "vmess" || type == "vless" || type == "trojan" || type == "http") {
ui->security->setVisible(true);
ui->security_l->setVisible(true);
} else {
ui->security->setVisible(false);
ui->security_l->setVisible(false);
}
if (type == "vmess" || type == "vless" || type == "trojan" || type == "shadowsocks") {
ui->multiplex->setVisible(true);
ui->multiplex_l->setVisible(true);
} else {
ui->multiplex->setVisible(false);
ui->multiplex_l->setVisible(false);
}
// 设置 是否可见
int streamBoxVisible = 0;
for (auto label: ui->stream_box->findChildren<QLabel *>()) {
if (!label->isHidden()) streamBoxVisible++;
}
ui->stream_box->setVisible(streamBoxVisible);
// 载入 type 之后,有些类型没有右边的设置
auto rightNoBox = (ui->stream_box->isHidden() && ui->network_box->isHidden() && ui->security_box->isHidden());
if (rightNoBox && !ui->right_all_w->isHidden()) {
ui->right_all_w->setVisible(false);
}
editor_cache_updated_impl();
ADJUST_SIZE
// 第一次显示
if (isHidden()) {
runOnUiThread([=] { show(); }, this);
}
}
bool DialogEditProfile::onEnd() {
// bean
if (!innerEditor->onEnd()) {
return false;
}
// 左边
ent->bean->name = ui->name->text();
ent->bean->serverAddress = ui->address->text().remove(' ');
ent->bean->serverPort = ui->port->text().toInt();
// 右边 stream
auto stream = GetStreamSettings(ent->bean.get());
if (stream != nullptr) {
stream->network = ui->network->currentText();
stream->security = ui->security->currentText();
stream->packet_encoding = ui->packet_encoding->currentText();
stream->path = ui->path->text();
stream->host = ui->host->text();
stream->sni = ui->sni->text();
stream->alpn = ui->alpn->text();
stream->utlsFingerprint = ui->utlsFingerprint->currentText();
stream->allow_insecure = ui->insecure->isChecked();
stream->header_type = ui->header_type->currentText();
stream->ws_early_data_name = ui->ws_early_data_name->text();
stream->ws_early_data_length = ui->ws_early_data_length->text().toInt();
stream->reality_pbk = ui->reality_pbk->text();
stream->reality_sid = ui->reality_sid->text();
stream->multiplex_status = ui->multiplex->currentIndex();
stream->certificate = CACHE.certificate;
}
// cached custom
ent->bean->custom_outbound = CACHE.custom_outbound;
ent->bean->custom_config = CACHE.custom_config;
return true;
}
void DialogEditProfile::accept() {
// save to ent
if (!onEnd()) {
return;
}
// finish
QStringList msg = {"accept"};
if (newEnt) {
auto ok = NekoGui::profileManager->AddProfile(ent);
if (!ok) {
MessageBoxWarning("???", "id exists");
}
} else {
auto changed = ent->Save();
if (changed && NekoGui::dataStore->started_id == ent->id) msg << "restart";
}
MW_dialog_message(Dialog_DialogEditProfile, msg.join(","));
QDialog::accept();
}
// cached editor (dialog)
void DialogEditProfile::editor_cache_updated_impl() {
if (CACHE.certificate.isEmpty()) {
ui->certificate_edit->setText(tr("Not set"));
} else {
ui->certificate_edit->setText(tr("Already set"));
}
if (CACHE.custom_outbound.isEmpty()) {
ui->custom_outbound_edit->setText(tr("Not set"));
} else {
ui->custom_outbound_edit->setText(tr("Already set"));
}
if (CACHE.custom_config.isEmpty()) {
ui->custom_config_edit->setText(tr("Not set"));
} else {
ui->custom_config_edit->setText(tr("Already set"));
}
// CACHE macro
for (auto a: innerEditor->get_editor_cached()) {
if (a.second.isEmpty()) {
a.first->setText(tr("Not set"));
} else {
a.first->setText(tr("Already set"));
}
}
}
void DialogEditProfile::on_custom_outbound_edit_clicked() {
C_EDIT_JSON_ALLOW_EMPTY(custom_outbound)
editor_cache_updated_impl();
}
void DialogEditProfile::on_custom_config_edit_clicked() {
C_EDIT_JSON_ALLOW_EMPTY(custom_config)
editor_cache_updated_impl();
}
void DialogEditProfile::on_certificate_edit_clicked() {
bool ok;
auto txt = QInputDialog::getMultiLineText(this, tr("Certificate"), "", CACHE.certificate, &ok);
if (ok) {
CACHE.certificate = txt;
editor_cache_updated_impl();
}
}
void DialogEditProfile::on_apply_to_group_clicked() {
if (apply_to_group_ui.empty()) {
apply_to_group_ui[ui->multiplex] = new FloatCheckBox(ui->multiplex, this);
apply_to_group_ui[ui->sni] = new FloatCheckBox(ui->sni, this);
apply_to_group_ui[ui->alpn] = new FloatCheckBox(ui->alpn, this);
apply_to_group_ui[ui->host] = new FloatCheckBox(ui->host, this);
apply_to_group_ui[ui->path] = new FloatCheckBox(ui->path, this);
apply_to_group_ui[ui->utlsFingerprint] = new FloatCheckBox(ui->utlsFingerprint, this);
apply_to_group_ui[ui->insecure] = new FloatCheckBox(ui->insecure, this);
apply_to_group_ui[ui->certificate_edit] = new FloatCheckBox(ui->certificate_edit, this);
apply_to_group_ui[ui->custom_config_edit] = new FloatCheckBox(ui->custom_config_edit, this);
apply_to_group_ui[ui->custom_outbound_edit] = new FloatCheckBox(ui->custom_outbound_edit, this);
ui->apply_to_group->setText(tr("Confirm"));
} else {
auto group = NekoGui::profileManager->GetGroup(ent->gid);
if (group == nullptr) {
MessageBoxWarning("failed", "unknown group");
return;
}
// save this
if (onEnd()) {
ent->Save();
} else {
MessageBoxWarning("failed", "failed to save");
return;
}
// copy keys
for (const auto &pair: apply_to_group_ui) {
if (pair.second->isChecked()) {
do_apply_to_group(group, pair.first);
}
delete pair.second;
}
apply_to_group_ui.clear();
ui->apply_to_group->setText(tr("Apply settings to this group"));
}
}
void DialogEditProfile::do_apply_to_group(const std::shared_ptr<NekoGui::Group> &group, QWidget *key) {
auto stream = GetStreamSettings(ent->bean.get());
auto copyStream = [=](void *p) {
for (const auto &profile: group->Profiles()) {
auto newStream = GetStreamSettings(profile->bean.get());
if (newStream == nullptr) continue;
if (stream == newStream) continue;
newStream->_setValue(stream->_name(p), p);
// qDebug() << newStream->ToJsonBytes();
profile->Save();
}
};
auto copyBean = [=](void *p) {
for (const auto &profile: group->Profiles()) {
if (profile == ent) continue;
profile->bean->_setValue(ent->bean->_name(p), p);
// qDebug() << profile->bean->ToJsonBytes();
profile->Save();
}
};
if (key == ui->multiplex) {
copyStream(&stream->multiplex_status);
} else if (key == ui->sni) {
copyStream(&stream->sni);
} else if (key == ui->alpn) {
copyStream(&stream->alpn);
} else if (key == ui->host) {
copyStream(&stream->host);
} else if (key == ui->path) {
copyStream(&stream->path);
} else if (key == ui->utlsFingerprint) {
copyStream(&stream->utlsFingerprint);
} else if (key == ui->insecure) {
copyStream(&stream->allow_insecure);
} else if (key == ui->certificate_edit) {
copyStream(&stream->certificate);
} else if (key == ui->custom_config_edit) {
copyBean(&ent->bean->custom_config);
} else if (key == ui->custom_outbound_edit) {
copyBean(&ent->bean->custom_outbound);
}
}
| 19,056
|
C++
|
.cpp
| 473
| 32.433404
| 120
| 0.60249
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,645
|
edit_quic.cpp
|
MatsuriDayo_nekoray/ui/edit/edit_quic.cpp
|
#include "edit_quic.h"
#include "ui_edit_quic.h"
#include "fmt/QUICBean.hpp"
#include <QInputDialog>
#include <QUuid>
EditQUIC::EditQUIC(QWidget *parent) : QWidget(parent), ui(new Ui::EditQUIC) {
ui->setupUi(this);
connect(ui->uuidgen, &QPushButton::clicked, this, [=] { ui->uuid->setText(QUuid::createUuid().toString().remove("{").remove("}")); });
}
EditQUIC::~EditQUIC() {
delete ui;
}
void EditQUIC::onStart(std::shared_ptr<NekoGui::ProxyEntity> _ent) {
this->ent = _ent;
auto bean = this->ent->QUICBean();
P_LOAD_STRING(hopPort);
P_LOAD_INT(hopInterval);
P_LOAD_INT(uploadMbps);
P_LOAD_INT(downloadMbps);
P_LOAD_BOOL(disableMtuDiscovery)
P_LOAD_STRING(obfsPassword);
P_LOAD_INT(streamReceiveWindow);
P_LOAD_INT(connectionReceiveWindow);
P_LOAD_BOOL(forceExternal);
P_LOAD_STRING(uuid);
P_LOAD_STRING(password);
P_LOAD_COMBO_STRING(congestionControl);
P_LOAD_COMBO_STRING(udpRelayMode);
P_LOAD_BOOL(zeroRttHandshake);
P_LOAD_STRING(heartbeat);
P_LOAD_BOOL(uos);
// TLS
P_LOAD_STRING(sni);
P_LOAD_STRING(alpn);
P_C_LOAD_STRING(caText);
P_LOAD_BOOL(allowInsecure);
P_LOAD_BOOL(disableSni);
if (bean->proxy_type == NekoGui_fmt::QUICBean::proxy_Hysteria2) {
ui->uuid->hide();
ui->uuid_l->hide();
ui->uuidgen->hide();
ui->congestionControl->hide();
ui->congestionControl_l->hide();
ui->udpRelayMode->hide();
ui->udpRelayMode_l->hide();
ui->zeroRttHandshake->hide();
ui->heartbeat->hide();
ui->heartbeat_l->hide();
ui->uos->hide();
ui->alpn->hide();
ui->alpn_l->hide();
ui->TLS->removeItem(ui->alpn_sp);
ui->disableMtuDiscovery->hide();
ui->connectionReceiveWindow->hide();
ui->connectionReceiveWindow_l->hide();
ui->streamReceiveWindow->hide();
ui->streamReceiveWindow_l->hide();
} else if (bean->proxy_type == NekoGui_fmt::QUICBean::proxy_TUIC) {
ui->hopPort->hide();
ui->hopPort_l->hide();
ui->hopInterval->hide();
ui->hopInterval_l->hide();
ui->uploadMbps->hide();
ui->uploadMbps_l->hide();
ui->downloadMbps->hide();
ui->downloadMbps_l->hide();
ui->disableMtuDiscovery->hide();
ui->obfsPassword->hide();
ui->obfsPassword_l->hide();
ui->streamReceiveWindow->hide();
ui->streamReceiveWindow_l->hide();
ui->connectionReceiveWindow->hide();
ui->connectionReceiveWindow_l->hide();
ui->uos->hide();
}
}
bool EditQUIC::onEnd() {
auto bean = this->ent->QUICBean();
P_SAVE_BOOL(forceExternal);
// Hysteria 2
P_SAVE_STRING(hopPort);
P_SAVE_INT(hopInterval);
P_SAVE_INT(uploadMbps);
P_SAVE_INT(downloadMbps);
P_SAVE_BOOL(disableMtuDiscovery)
P_SAVE_STRING(obfsPassword);
P_SAVE_INT(streamReceiveWindow);
P_SAVE_INT(connectionReceiveWindow);
// TUIC
P_SAVE_STRING(uuid);
P_SAVE_STRING(password);
P_SAVE_COMBO_STRING(congestionControl);
P_SAVE_COMBO_STRING(udpRelayMode);
P_SAVE_BOOL(zeroRttHandshake);
P_SAVE_STRING(heartbeat);
P_SAVE_BOOL(uos);
// TLS
P_SAVE_STRING(sni);
P_SAVE_STRING(alpn);
P_SAVE_BOOL(allowInsecure);
P_C_SAVE_STRING(caText);
P_SAVE_BOOL(disableSni);
return true;
}
QList<QPair<QPushButton *, QString>> EditQUIC::get_editor_cached() {
return {
{ui->certificate, CACHE.caText},
};
}
void EditQUIC::on_certificate_clicked() {
bool ok;
auto txt = QInputDialog::getMultiLineText(this, tr("Certificate"), "", CACHE.caText, &ok);
if (ok) {
CACHE.caText = txt;
editor_cache_updated();
}
}
| 3,763
|
C++
|
.cpp
| 117
| 26.290598
| 138
| 0.633131
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,646
|
edit_shadowsocks.cpp
|
MatsuriDayo_nekoray/ui/edit/edit_shadowsocks.cpp
|
#include "edit_shadowsocks.h"
#include "ui_edit_shadowsocks.h"
#include "fmt/ShadowSocksBean.hpp"
#include "fmt/Preset.hpp"
EditShadowSocks::EditShadowSocks(QWidget *parent) : QWidget(parent),
ui(new Ui::EditShadowSocks) {
ui->setupUi(this);
ui->method->addItems(Preset::SingBox::ShadowsocksMethods);
}
EditShadowSocks::~EditShadowSocks() {
delete ui;
}
void EditShadowSocks::onStart(std::shared_ptr<NekoGui::ProxyEntity> _ent) {
this->ent = _ent;
auto bean = this->ent->ShadowSocksBean();
ui->method->setCurrentText(bean->method);
ui->uot->setCurrentIndex(bean->uot);
ui->password->setText(bean->password);
auto ssPlugin = bean->plugin.split(";");
if (!ssPlugin.empty()) {
ui->plugin->setCurrentText(ssPlugin[0]);
ui->plugin_opts->setText(SubStrAfter(bean->plugin, ";"));
}
}
bool EditShadowSocks::onEnd() {
auto bean = this->ent->ShadowSocksBean();
bean->method = ui->method->currentText();
bean->password = ui->password->text();
bean->uot = ui->uot->currentIndex();
bean->plugin = ui->plugin->currentText();
if (!bean->plugin.isEmpty()) {
bean->plugin += ";" + ui->plugin_opts->text();
}
return true;
}
| 1,266
|
C++
|
.cpp
| 35
| 30.6
| 81
| 0.644317
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,647
|
edit_custom.cpp
|
MatsuriDayo_nekoray/ui/edit/edit_custom.cpp
|
#include "edit_custom.h"
#include "ui_edit_custom.h"
#include "3rdparty/qv2ray/v2/ui/widgets/editors/w_JsonEditor.hpp"
#include "fmt/CustomBean.hpp"
#include "fmt/Preset.hpp"
#include "db/ConfigBuilder.hpp"
#include "db/Database.hpp"
#include <QMessageBox>
#include <QClipboard>
EditCustom::EditCustom(QWidget *parent) : QWidget(parent), ui(new Ui::EditCustom) {
ui->setupUi(this);
ui->config_simple->setPlaceholderText(
"example:\n"
" server-address: \"127.0.0.1:%mapping_port%\"\n"
" listen-address: \"127.0.0.1\"\n"
" listen-port: %socks_port%\n"
" host: your-domain.com\n"
" sni: your-domain.com\n");
}
EditCustom::~EditCustom() {
delete ui;
}
#define SAVE_CUSTOM_BEAN \
P_SAVE_COMBO_STRING(core) \
bean->command = ui->command->text().split(" "); \
P_SAVE_STRING_PLAIN(config_simple) \
P_SAVE_COMBO_STRING(config_suffix) \
P_SAVE_INT(mapping_port) \
P_SAVE_INT(socks_port)
void EditCustom::onStart(std::shared_ptr<NekoGui::ProxyEntity> _ent) {
this->ent = _ent;
auto bean = this->ent->CustomBean();
// load known core
auto core_map = QString2QJsonObject(NekoGui::dataStore->extraCore->core_map);
for (const auto &key: core_map.keys()) {
ui->core->addItem(key);
}
if (preset_core == "internal") {
preset_command = preset_config = "";
ui->config_simple->setPlaceholderText(
"{\n"
" \"type\": \"socks\",\n"
" // ...\n"
"}");
} else if (preset_core == "internal-full") {
preset_command = preset_config = "";
ui->config_simple->setPlaceholderText(
"{\n"
" \"inbounds\": [],\n"
" \"outbounds\": []\n"
"}");
}
// load core ui
P_LOAD_COMBO_STRING(core)
ui->command->setText(bean->command.join(" "));
ui->config_simple->setPlainText(bean->config_simple);
P_LOAD_COMBO_STRING(config_suffix)
P_LOAD_INT(mapping_port)
P_LOAD_INT(socks_port)
// custom external
if (!bean->core.isEmpty()) {
ui->core->setDisabled(true);
} else if (!preset_core.isEmpty()) {
bean->core = preset_core;
ui->core->setDisabled(true);
ui->core->setCurrentText(preset_core);
ui->command->setText(preset_command);
ui->config_simple->setPlainText(preset_config);
}
// custom internal
if (preset_core == "internal" || preset_core == "internal-full") {
ui->core->hide();
if (preset_core == "internal") {
ui->core_l->setText(tr("Outbound JSON, please read the documentation."));
} else {
ui->core_l->setText(tr("Please fill the complete config."));
}
ui->w_ext1->hide();
ui->w_ext2->hide();
}
// Preview
connect(ui->preview, &QPushButton::clicked, this, [=] {
// CustomBean::BuildExternal
QStringList th;
auto mapping_port = ui->mapping_port->text().toInt();
auto socks_port = ui->socks_port->text().toInt();
th << "%mapping_port% => " + (mapping_port <= 0 ? "Random" : Int2String(mapping_port));
th << "%socks_port% => " + (socks_port <= 0 ? "Random" : Int2String(socks_port));
th << "%server_addr% => " + get_edit_text_serverAddress();
th << "%server_port% => " + get_edit_text_serverPort();
MessageBoxInfo(tr("Preview replace"), th.join("\n"));
// EditCustom::onEnd
auto tmpEnt = NekoGui::ProfileManager::NewProxyEntity("custom");
auto bean = tmpEnt->CustomBean();
SAVE_CUSTOM_BEAN
// 补充
bean->serverAddress = get_edit_text_serverAddress();
bean->serverPort = get_edit_text_serverPort().toInt();
if (bean->core.isEmpty()) return;
//
auto result = NekoGui::BuildConfig(tmpEnt, false, false);
if (!result->error.isEmpty()) {
MessageBoxInfo(software_name, result->error);
return;
}
for (const auto &extR: result->extRs) {
auto command = QStringList{extR->program};
command += extR->arguments;
auto btn = QMessageBox::information(this, tr("Preview config"),
QString("Command: %1\n\n%2").arg(QStringList2Command(command), extR->config_export),
"OK", "Copy", "", 0, 0);
if (btn == 1) {
QApplication::clipboard()->setText(extR->config_export);
}
}
});
}
bool EditCustom::onEnd() {
if (get_edit_text_name().isEmpty()) {
MessageBoxWarning(software_name, tr("Name cannot be empty."));
return false;
}
if (ui->core->currentText().isEmpty()) {
MessageBoxWarning(software_name, tr("Please pick a core."));
return false;
}
auto bean = this->ent->CustomBean();
SAVE_CUSTOM_BEAN
return true;
}
void EditCustom::on_as_json_clicked() {
auto editor = new JsonEditor(QString2QJsonObject(ui->config_simple->toPlainText()), this);
auto result = editor->OpenEditor();
if (!result.isEmpty()) {
ui->config_simple->setPlainText(QJsonObject2QString(result, false));
}
}
| 5,350
|
C++
|
.cpp
| 137
| 31.277372
| 132
| 0.570576
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,648
|
edit_naive.cpp
|
MatsuriDayo_nekoray/ui/edit/edit_naive.cpp
|
#include "edit_naive.h"
#include "ui_edit_naive.h"
#include "fmt/NaiveBean.hpp"
#include <QInputDialog>
EditNaive::EditNaive(QWidget *parent) : QWidget(parent), ui(new Ui::EditNaive) {
ui->setupUi(this);
}
EditNaive::~EditNaive() {
delete ui;
}
void EditNaive::onStart(std::shared_ptr<NekoGui::ProxyEntity> _ent) {
this->ent = _ent;
auto bean = this->ent->NaiveBean();
P_LOAD_STRING(username);
P_LOAD_STRING(password);
P_LOAD_COMBO_STRING(protocol);
P_C_LOAD_STRING(extra_headers);
P_LOAD_STRING(sni);
P_C_LOAD_STRING(certificate);
P_LOAD_INT(insecure_concurrency);
P_LOAD_BOOL(disable_log);
}
bool EditNaive::onEnd() {
auto bean = this->ent->NaiveBean();
P_SAVE_STRING(username);
P_SAVE_STRING(password);
P_SAVE_COMBO_STRING(protocol);
P_C_SAVE_STRING(extra_headers);
P_SAVE_STRING(sni);
P_C_SAVE_STRING(certificate);
P_SAVE_INT(insecure_concurrency);
P_SAVE_BOOL(disable_log);
return true;
}
QList<QPair<QPushButton *, QString>> EditNaive::get_editor_cached() {
return {
{ui->certificate, CACHE.certificate},
{ui->extra_headers, CACHE.extra_headers},
};
}
void EditNaive::on_certificate_clicked() {
bool ok;
auto txt = QInputDialog::getMultiLineText(this, tr("Certificate"), "", CACHE.certificate, &ok);
if (ok) {
CACHE.certificate = txt;
editor_cache_updated();
}
}
void EditNaive::on_extra_headers_clicked() {
bool ok;
auto txt = QInputDialog::getMultiLineText(this, tr("Extra headers"), "", CACHE.extra_headers, &ok);
if (ok) {
CACHE.extra_headers = txt;
editor_cache_updated();
}
}
| 1,676
|
C++
|
.cpp
| 56
| 25.571429
| 103
| 0.668532
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,649
|
edit_socks_http.cpp
|
MatsuriDayo_nekoray/ui/edit/edit_socks_http.cpp
|
#include "edit_socks_http.h"
#include "ui_edit_socks_http.h"
#include "fmt/SocksHttpBean.hpp"
EditSocksHttp::EditSocksHttp(QWidget *parent) : QWidget(parent),
ui(new Ui::EditSocksHttp) {
ui->setupUi(this);
}
EditSocksHttp::~EditSocksHttp() {
delete ui;
}
void EditSocksHttp::onStart(std::shared_ptr<NekoGui::ProxyEntity> _ent) {
this->ent = _ent;
auto bean = this->ent->SocksHTTPBean();
if (bean->socks_http_type == NekoGui_fmt::SocksHttpBean::type_Socks4) {
ui->version->setCurrentIndex(1);
} else {
ui->version->setCurrentIndex(0);
}
if (bean->socks_http_type == NekoGui_fmt::SocksHttpBean::type_HTTP) {
ui->version->setVisible(false);
ui->version_l->setVisible(false);
}
ui->username->setText(bean->username);
ui->password->setText(bean->password);
}
bool EditSocksHttp::onEnd() {
auto bean = this->ent->SocksHTTPBean();
if (ui->version->isVisible()) {
if (ui->version->currentIndex() == 1) {
bean->socks_http_type = NekoGui_fmt::SocksHttpBean::type_Socks4;
} else {
bean->socks_http_type = NekoGui_fmt::SocksHttpBean::type_Socks5;
}
}
bean->username = ui->username->text();
bean->password = ui->password->text();
return true;
}
| 1,338
|
C++
|
.cpp
| 38
| 28.789474
| 76
| 0.625581
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,650
|
edit_chain.cpp
|
MatsuriDayo_nekoray/ui/edit/edit_chain.cpp
|
#include "edit_chain.h"
#include "ui_edit_chain.h"
#include "ui/mainwindow_interface.h"
#include "ui/widget/ProxyItem.h"
#include "db/Database.hpp"
#include "fmt/ChainBean.hpp"
EditChain::EditChain(QWidget *parent) : QWidget(parent), ui(new Ui::EditChain) {
ui->setupUi(this);
}
EditChain::~EditChain() {
delete ui;
}
void EditChain::onStart(std::shared_ptr<NekoGui::ProxyEntity> _ent) {
this->ent = _ent;
auto bean = this->ent->ChainBean();
for (auto id: bean->list) {
AddProfileToListIfExist(id);
}
}
bool EditChain::onEnd() {
if (get_edit_text_name().isEmpty()) {
MessageBoxWarning(software_name, tr("Name cannot be empty."));
return false;
}
auto bean = this->ent->ChainBean();
QList<int> idList;
for (int i = 0; i < ui->listWidget->count(); i++) {
idList << ui->listWidget->item(i)->data(114514).toInt();
}
bean->list = idList;
return true;
}
void EditChain::on_select_profile_clicked() {
get_edit_dialog()->hide();
GetMainWindow()->start_select_mode(this, [=](int id) {
get_edit_dialog()->show();
AddProfileToListIfExist(id);
});
}
void EditChain::AddProfileToListIfExist(int profileId) {
auto _ent = NekoGui::profileManager->GetProfile(profileId);
if (_ent != nullptr && _ent->type != "chain") {
auto wI = new QListWidgetItem();
wI->setData(114514, profileId);
auto w = new ProxyItem(this, _ent, wI);
ui->listWidget->addItem(wI);
ui->listWidget->setItemWidget(wI, w);
// change button
connect(w->get_change_button(), &QPushButton::clicked, w, [=] {
get_edit_dialog()->hide();
GetMainWindow()->start_select_mode(w, [=](int newId) {
get_edit_dialog()->show();
ReplaceProfile(w, newId);
});
});
}
}
void EditChain::ReplaceProfile(ProxyItem *w, int profileId) {
auto _ent = NekoGui::profileManager->GetProfile(profileId);
if (_ent != nullptr && _ent->type != "chain") {
w->item->setData(114514, profileId);
w->ent = _ent;
w->refresh_data();
}
}
| 2,157
|
C++
|
.cpp
| 65
| 27.430769
| 80
| 0.611833
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,651
|
Bean2CoreObj_box.cpp
|
MatsuriDayo_nekoray/fmt/Bean2CoreObj_box.cpp
|
#include "db/ProxyEntity.hpp"
#include "fmt/includes.h"
namespace NekoGui_fmt {
void V2rayStreamSettings::BuildStreamSettingsSingBox(QJsonObject *outbound) {
// https://sing-box.sagernet.org/configuration/shared/v2ray-transport
if (network != "tcp") {
QJsonObject transport{{"type", network}};
if (network == "ws") {
if (!host.isEmpty()) transport["headers"] = QJsonObject{{"Host", host}};
// ws path & ed
auto pathWithoutEd = SubStrBefore(path, "?ed=");
if (!pathWithoutEd.isEmpty()) transport["path"] = pathWithoutEd;
if (pathWithoutEd != path) {
auto ed = SubStrAfter(path, "?ed=").toInt();
if (ed > 0) {
transport["max_early_data"] = ed;
transport["early_data_header_name"] = "Sec-WebSocket-Protocol";
}
}
if (ws_early_data_length > 0) {
transport["max_early_data"] = ws_early_data_length;
transport["early_data_header_name"] = ws_early_data_name;
}
} else if (network == "http") {
if (!path.isEmpty()) transport["path"] = path;
if (!host.isEmpty()) transport["host"] = QList2QJsonArray(host.split(","));
} else if (network == "grpc") {
if (!path.isEmpty()) transport["service_name"] = path;
} else if (network == "httpupgrade") {
if (!path.isEmpty()) transport["path"] = path;
if (!host.isEmpty()) transport["host"] = host;
}
outbound->insert("transport", transport);
} else if (header_type == "http") {
// TCP + headerType
QJsonObject transport{
{"type", "http"},
{"method", "GET"},
{"path", path},
{"headers", QJsonObject{{"Host", QList2QJsonArray(host.split(","))}}},
};
outbound->insert("transport", transport);
}
// 对应字段 tls
if (security == "tls") {
QJsonObject tls{{"enabled", true}};
if (allow_insecure || NekoGui::dataStore->skip_cert) tls["insecure"] = true;
if (!sni.trimmed().isEmpty()) tls["server_name"] = sni;
if (!certificate.trimmed().isEmpty()) {
tls["certificate"] = certificate.trimmed();
}
if (!alpn.trimmed().isEmpty()) {
tls["alpn"] = QList2QJsonArray(alpn.split(","));
}
QString fp = utlsFingerprint;
if (!reality_pbk.trimmed().isEmpty()) {
tls["reality"] = QJsonObject{
{"enabled", true},
{"public_key", reality_pbk},
{"short_id", reality_sid.split(",")[0]},
};
if (fp.isEmpty()) fp = "random";
}
if (!fp.isEmpty()) {
tls["utls"] = QJsonObject{
{"enabled", true},
{"fingerprint", fp},
};
}
outbound->insert("tls", tls);
}
if (outbound->value("type").toString() == "vmess" || outbound->value("type").toString() == "vless") {
outbound->insert("packet_encoding", packet_encoding);
}
}
CoreObjOutboundBuildResult SocksHttpBean::BuildCoreObjSingBox() {
CoreObjOutboundBuildResult result;
QJsonObject outbound;
outbound["type"] = socks_http_type == type_HTTP ? "http" : "socks";
if (socks_http_type == type_Socks4) outbound["version"] = "4";
outbound["server"] = serverAddress;
outbound["server_port"] = serverPort;
if (!username.isEmpty() && !password.isEmpty()) {
outbound["username"] = username;
outbound["password"] = password;
}
stream->BuildStreamSettingsSingBox(&outbound);
result.outbound = outbound;
return result;
}
CoreObjOutboundBuildResult ShadowSocksBean::BuildCoreObjSingBox() {
CoreObjOutboundBuildResult result;
QJsonObject outbound{{"type", "shadowsocks"}};
outbound["server"] = serverAddress;
outbound["server_port"] = serverPort;
outbound["method"] = method;
outbound["password"] = password;
if (uot != 0) {
QJsonObject udp_over_tcp{
{"enabled", true},
{"version", uot},
};
outbound["udp_over_tcp"] = udp_over_tcp;
} else {
outbound["udp_over_tcp"] = false;
}
if (!plugin.trimmed().isEmpty()) {
outbound["plugin"] = SubStrBefore(plugin, ";");
outbound["plugin_opts"] = SubStrAfter(plugin, ";");
}
stream->BuildStreamSettingsSingBox(&outbound);
result.outbound = outbound;
return result;
}
CoreObjOutboundBuildResult VMessBean::BuildCoreObjSingBox() {
CoreObjOutboundBuildResult result;
QJsonObject outbound{
{"type", "vmess"},
{"server", serverAddress},
{"server_port", serverPort},
{"uuid", uuid.trimmed()},
{"alter_id", aid},
{"security", security},
};
stream->BuildStreamSettingsSingBox(&outbound);
result.outbound = outbound;
return result;
}
CoreObjOutboundBuildResult TrojanVLESSBean::BuildCoreObjSingBox() {
CoreObjOutboundBuildResult result;
QJsonObject outbound{
{"type", proxy_type == proxy_VLESS ? "vless" : "trojan"},
{"server", serverAddress},
{"server_port", serverPort},
};
QJsonObject settings;
if (proxy_type == proxy_VLESS) {
if (flow.right(7) == "-udp443") {
// 检查末尾是否包含"-udp443",如果是,则删去
flow.chop(7);
} else if (flow == "none") {
// 不使用 flow
flow = "";
}
outbound["uuid"] = password.trimmed();
outbound["flow"] = flow;
} else {
outbound["password"] = password;
}
stream->BuildStreamSettingsSingBox(&outbound);
result.outbound = outbound;
return result;
}
CoreObjOutboundBuildResult QUICBean::BuildCoreObjSingBox() {
CoreObjOutboundBuildResult result;
QJsonObject coreTlsObj{
{"enabled", true},
{"disable_sni", disableSni},
{"insecure", allowInsecure},
{"certificate", caText.trimmed()},
{"server_name", sni},
};
if (!alpn.trimmed().isEmpty()) coreTlsObj["alpn"] = QList2QJsonArray(alpn.split(","));
if (proxy_type == proxy_Hysteria2) coreTlsObj["alpn"] = "h3";
QJsonObject outbound{
{"server", serverAddress},
{"server_port", serverPort},
{"tls", coreTlsObj},
};
if (proxy_type == proxy_Hysteria2) {
outbound["type"] = "hysteria2";
outbound["password"] = password;
outbound["up_mbps"] = uploadMbps;
outbound["down_mbps"] = downloadMbps;
if (!hopPort.trimmed().isEmpty()) {
outbound["hop_ports"] = hopPort;
outbound["hop_interval"] = hopInterval;
}
if (!obfsPassword.isEmpty()) {
outbound["obfs"] = QJsonObject{
{"type", "salamander"},
{"password", obfsPassword},
};
}
} else if (proxy_type == proxy_TUIC) {
outbound["type"] = "tuic";
outbound["uuid"] = uuid;
outbound["password"] = password;
outbound["congestion_control"] = congestionControl;
if (uos) {
outbound["udp_over_stream"] = true;
} else {
outbound["udp_relay_mode"] = udpRelayMode;
}
outbound["zero_rtt_handshake"] = zeroRttHandshake;
if (!heartbeat.trimmed().isEmpty()) outbound["heartbeat"] = heartbeat;
}
result.outbound = outbound;
return result;
}
CoreObjOutboundBuildResult CustomBean::BuildCoreObjSingBox() {
CoreObjOutboundBuildResult result;
if (core == "internal") {
result.outbound = QString2QJsonObject(config_simple);
}
return result;
}
} // namespace NekoGui_fmt
| 8,612
|
C++
|
.cpp
| 208
| 28.8125
| 109
| 0.51927
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,652
|
Link2Bean.cpp
|
MatsuriDayo_nekoray/fmt/Link2Bean.cpp
|
#include "db/ProxyEntity.hpp"
#include "fmt/includes.h"
#include <QUrlQuery>
namespace NekoGui_fmt {
#define DECODE_V2RAY_N_1 \
QString linkN = DecodeB64IfValid(SubStrBefore(SubStrAfter(link, "://"), "#"), QByteArray::Base64Option::Base64UrlEncoding); \
if (linkN.isEmpty()) return false; \
auto hasRemarks = link.contains("#"); \
if (hasRemarks) linkN += "#" + SubStrAfter(link, "#"); \
auto url = QUrl("https://" + linkN);
bool SocksHttpBean::TryParseLink(const QString &link) {
auto url = QUrl(link);
if (!url.isValid()) return false;
auto query = GetQuery(url);
if (link.startsWith("socks4")) socks_http_type = type_Socks4;
if (link.startsWith("http")) socks_http_type = type_HTTP;
name = url.fragment(QUrl::FullyDecoded);
serverAddress = url.host();
serverPort = url.port();
username = url.userName();
password = url.password();
if (serverPort == -1) serverPort = socks_http_type == type_HTTP ? 443 : 1080;
// v2rayN fmt
if (password.isEmpty() && !username.isEmpty()) {
QString n = DecodeB64IfValid(username);
if (!n.isEmpty()) {
username = SubStrBefore(n, ":");
password = SubStrAfter(n, ":");
}
}
stream->security = GetQueryValue(query, "security", "");
stream->sni = GetQueryValue(query, "sni");
if (link.startsWith("https")) stream->security = "tls";
return !serverAddress.isEmpty();
}
bool TrojanVLESSBean::TryParseLink(const QString &link) {
auto url = QUrl(link);
if (!url.isValid()) return false;
auto query = GetQuery(url);
name = url.fragment(QUrl::FullyDecoded);
serverAddress = url.host();
serverPort = url.port();
password = url.userName();
if (serverPort == -1) serverPort = 443;
// security
auto type = GetQueryValue(query, "type", "tcp");
if (type == "h2") {
type = "http";
}
stream->network = type;
if (proxy_type == proxy_Trojan) {
stream->security = GetQueryValue(query, "security", "tls").replace("reality", "tls").replace("none", "");
} else {
stream->security = GetQueryValue(query, "security", "").replace("reality", "tls").replace("none", "");
}
auto sni1 = GetQueryValue(query, "sni");
auto sni2 = GetQueryValue(query, "peer");
if (!sni1.isEmpty()) stream->sni = sni1;
if (!sni2.isEmpty()) stream->sni = sni2;
stream->alpn = GetQueryValue(query, "alpn");
if (!query.queryItemValue("allowInsecure").isEmpty()) stream->allow_insecure = true;
stream->reality_pbk = GetQueryValue(query, "pbk", "");
stream->reality_sid = GetQueryValue(query, "sid", "");
stream->reality_spx = GetQueryValue(query, "spx", "");
stream->utlsFingerprint = GetQueryValue(query, "fp", "");
if (stream->utlsFingerprint.isEmpty()) {
stream->utlsFingerprint = NekoGui::dataStore->utlsFingerprint;
}
// type
if (stream->network == "ws") {
stream->path = GetQueryValue(query, "path", "");
stream->host = GetQueryValue(query, "host", "");
} else if (stream->network == "http") {
stream->path = GetQueryValue(query, "path", "");
stream->host = GetQueryValue(query, "host", "").replace("|", ",");
} else if (stream->network == "httpupgrade") {
stream->path = GetQueryValue(query, "path", "");
stream->host = GetQueryValue(query, "host", "");
} else if (stream->network == "grpc") {
stream->path = GetQueryValue(query, "serviceName", "");
} else if (stream->network == "tcp") {
if (GetQueryValue(query, "headerType") == "http") {
stream->header_type = "http";
stream->host = GetQueryValue(query, "host", "");
stream->path = GetQueryValue(query, "path", "");
}
}
// protocol
if (proxy_type == proxy_VLESS) {
flow = GetQueryValue(query, "flow", "");
}
return !(password.isEmpty() || serverAddress.isEmpty());
}
bool ShadowSocksBean::TryParseLink(const QString &link) {
if (SubStrBefore(link, "#").contains("@")) {
// SS
auto url = QUrl(link);
if (!url.isValid()) return false;
name = url.fragment(QUrl::FullyDecoded);
serverAddress = url.host();
serverPort = url.port();
if (url.password().isEmpty()) {
// traditional format
auto method_password = DecodeB64IfValid(url.userName(), QByteArray::Base64Option::Base64UrlEncoding);
if (method_password.isEmpty()) return false;
method = SubStrBefore(method_password, ":");
password = SubStrAfter(method_password, ":");
} else {
// 2022 format
method = url.userName();
password = url.password();
}
auto query = GetQuery(url);
plugin = query.queryItemValue("plugin").replace("simple-obfs;", "obfs-local;");
} else {
// v2rayN
DECODE_V2RAY_N_1
if (hasRemarks) name = url.fragment(QUrl::FullyDecoded);
serverAddress = url.host();
serverPort = url.port();
method = url.userName();
password = url.password();
}
return !(serverAddress.isEmpty() || method.isEmpty() || password.isEmpty());
}
bool VMessBean::TryParseLink(const QString &link) {
// V2RayN Format
auto linkN = DecodeB64IfValid(SubStrAfter(link, "vmess://"));
if (!linkN.isEmpty()) {
auto objN = QString2QJsonObject(linkN);
if (objN.isEmpty()) return false;
// REQUIRED
uuid = objN["id"].toString();
serverAddress = objN["add"].toString();
serverPort = objN["port"].toVariant().toInt();
// OPTIONAL
name = objN["ps"].toString();
aid = objN["aid"].toVariant().toInt();
stream->host = objN["host"].toString();
stream->path = objN["path"].toString();
stream->sni = objN["sni"].toString();
stream->header_type = objN["type"].toString();
auto net = objN["net"].toString();
if (!net.isEmpty()) {
if (net == "h2") {
net = "http";
}
stream->network = net;
}
auto scy = objN["scy"].toString();
if (!scy.isEmpty()) security = scy;
// TLS (XTLS?)
stream->security = objN["tls"].toString();
// TODO quic & kcp
return true;
} else {
// https://github.com/XTLS/Xray-core/discussions/716
auto url = QUrl(link);
if (!url.isValid()) return false;
auto query = GetQuery(url);
name = url.fragment(QUrl::FullyDecoded);
serverAddress = url.host();
serverPort = url.port();
uuid = url.userName();
if (serverPort == -1) serverPort = 443;
aid = 0; // “此分享标准仅针对 VMess AEAD 和 VLESS。”
security = GetQueryValue(query, "encryption", "auto");
// security
auto type = GetQueryValue(query, "type", "tcp");
if (type == "h2") {
type = "http";
}
stream->network = type;
stream->security = GetQueryValue(query, "security", "tls").replace("reality", "tls");
auto sni1 = GetQueryValue(query, "sni");
auto sni2 = GetQueryValue(query, "peer");
if (!sni1.isEmpty()) stream->sni = sni1;
if (!sni2.isEmpty()) stream->sni = sni2;
if (!query.queryItemValue("allowInsecure").isEmpty()) stream->allow_insecure = true;
stream->reality_pbk = GetQueryValue(query, "pbk", "");
stream->reality_sid = GetQueryValue(query, "sid", "");
stream->reality_spx = GetQueryValue(query, "spx", "");
stream->utlsFingerprint = GetQueryValue(query, "fp", "");
if (stream->utlsFingerprint.isEmpty()) {
stream->utlsFingerprint = NekoGui::dataStore->utlsFingerprint;
}
// type
if (stream->network == "ws") {
stream->path = GetQueryValue(query, "path", "");
stream->host = GetQueryValue(query, "host", "");
} else if (stream->network == "http") {
stream->path = GetQueryValue(query, "path", "");
stream->host = GetQueryValue(query, "host", "").replace("|", ",");
} else if (stream->network == "httpupgrade") {
stream->path = GetQueryValue(query, "path", "");
stream->host = GetQueryValue(query, "host", "");
} else if (stream->network == "grpc") {
stream->path = GetQueryValue(query, "serviceName", "");
} else if (stream->network == "tcp") {
if (GetQueryValue(query, "headerType") == "http") {
stream->header_type = "http";
stream->path = GetQueryValue(query, "path", "");
stream->host = GetQueryValue(query, "host", "");
}
}
return !(uuid.isEmpty() || serverAddress.isEmpty());
}
return false;
}
bool NaiveBean::TryParseLink(const QString &link) {
auto url = QUrl(link);
if (!url.isValid()) return false;
protocol = url.scheme().replace("naive+", "");
if (protocol != "https" && protocol != "quic") return false;
name = url.fragment(QUrl::FullyDecoded);
serverAddress = url.host();
serverPort = url.port();
username = url.userName();
password = url.password();
return !(username.isEmpty() || password.isEmpty() || serverAddress.isEmpty());
}
bool QUICBean::TryParseLink(const QString &link) {
auto url = QUrl(link);
auto query = QUrlQuery(url.query());
if (url.host().isEmpty() || url.port() == -1) return false;
if (url.scheme() == "tuic") {
// by daeuniverse
// https://github.com/daeuniverse/dae/discussions/182
name = url.fragment(QUrl::FullyDecoded);
serverAddress = url.host();
if (serverPort == -1) serverPort = 443;
serverPort = url.port();
uuid = url.userName();
password = url.password();
congestionControl = query.queryItemValue("congestion_control");
alpn = query.queryItemValue("alpn");
sni = query.queryItemValue("sni");
udpRelayMode = query.queryItemValue("udp_relay_mode");
allowInsecure = query.queryItemValue("allow_insecure") == "1";
disableSni = query.queryItemValue("disable_sni") == "1";
} else if (QStringList{"hy2", "hysteria2"}.contains(url.scheme())) {
name = url.fragment(QUrl::FullyDecoded);
serverAddress = url.host();
serverPort = url.port();
hopPort = query.queryItemValue("mport");
obfsPassword = query.queryItemValue("obfs-password");
allowInsecure = QStringList{"1", "true"}.contains(query.queryItemValue("insecure"));
if (url.password().isEmpty()) {
password = url.userName();
} else {
password = url.userName() + ":" + url.password();
}
sni = query.queryItemValue("sni");
}
return true;
}
} // namespace NekoGui_fmt
| 12,273
|
C++
|
.cpp
| 257
| 36.050584
| 129
| 0.522463
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,653
|
Bean2Link.cpp
|
MatsuriDayo_nekoray/fmt/Bean2Link.cpp
|
#include "db/ProxyEntity.hpp"
#include "fmt/includes.h"
#include <QUrlQuery>
namespace NekoGui_fmt {
QString SocksHttpBean::ToShareLink() {
QUrl url;
if (socks_http_type == type_HTTP) { // http
if (stream->security == "tls") {
url.setScheme("https");
} else {
url.setScheme("http");
}
} else {
url.setScheme(QString("socks%1").arg(socks_http_type));
}
if (!name.isEmpty()) url.setFragment(name);
if (!username.isEmpty()) url.setUserName(username);
if (!password.isEmpty()) url.setPassword(password);
url.setHost(serverAddress);
url.setPort(serverPort);
return url.toString(QUrl::FullyEncoded);
}
QString TrojanVLESSBean::ToShareLink() {
QUrl url;
QUrlQuery query;
url.setScheme(proxy_type == proxy_VLESS ? "vless" : "trojan");
url.setUserName(password);
url.setHost(serverAddress);
url.setPort(serverPort);
if (!name.isEmpty()) url.setFragment(name);
// security
auto security = stream->security;
if (security == "tls" && !stream->reality_pbk.trimmed().isEmpty()) security = "reality";
query.addQueryItem("security", security);
if (!stream->sni.isEmpty()) query.addQueryItem("sni", stream->sni);
if (!stream->alpn.isEmpty()) query.addQueryItem("alpn", stream->alpn);
if (stream->allow_insecure) query.addQueryItem("allowInsecure", "1");
if (!stream->utlsFingerprint.isEmpty()) query.addQueryItem("fp", stream->utlsFingerprint);
if (security == "reality") {
query.addQueryItem("pbk", stream->reality_pbk);
if (!stream->reality_sid.isEmpty()) query.addQueryItem("sid", stream->reality_sid);
if (!stream->reality_spx.isEmpty()) query.addQueryItem("spx", stream->reality_spx);
}
// type
query.addQueryItem("type", stream->network);
if (stream->network == "ws" || stream->network == "http" || stream->network == "httpupgrade") {
if (!stream->path.isEmpty()) query.addQueryItem("path", stream->path);
if (!stream->host.isEmpty()) query.addQueryItem("host", stream->host);
} else if (stream->network == "grpc") {
if (!stream->path.isEmpty()) query.addQueryItem("serviceName", stream->path);
} else if (stream->network == "tcp") {
if (stream->header_type == "http") {
if (!stream->path.isEmpty()) query.addQueryItem("path", stream->path);
query.addQueryItem("headerType", "http");
query.addQueryItem("host", stream->host);
}
}
// protocol
if (proxy_type == proxy_VLESS) {
if (!flow.isEmpty()) {
query.addQueryItem("flow", flow);
}
query.addQueryItem("encryption", "none");
}
url.setQuery(query);
return url.toString(QUrl::FullyEncoded);
}
const char* fixShadowsocksUserNameEncodeMagic = "fixShadowsocksUserNameEncodeMagic-holder-for-QUrl";
QString ShadowSocksBean::ToShareLink() {
QUrl url;
url.setScheme("ss");
if (method.startsWith("2022-")) {
url.setUserName(fixShadowsocksUserNameEncodeMagic);
} else {
auto method_password = method + ":" + password;
url.setUserName(method_password.toUtf8().toBase64(QByteArray::Base64Option::Base64UrlEncoding));
}
url.setHost(serverAddress);
url.setPort(serverPort);
if (!name.isEmpty()) url.setFragment(name);
QUrlQuery q;
if (!plugin.isEmpty()) q.addQueryItem("plugin", plugin);
if (!q.isEmpty()) url.setQuery(q);
//
auto link = url.toString(QUrl::FullyEncoded);
link = link.replace(fixShadowsocksUserNameEncodeMagic, method + ":" + QUrl::toPercentEncoding(password));
return link;
}
QString VMessBean::ToShareLink() {
if (NekoGui::dataStore->old_share_link_format) {
// v2rayN format
QJsonObject N{
{"v", "2"},
{"ps", name},
{"add", serverAddress},
{"port", Int2String(serverPort)},
{"id", uuid},
{"aid", Int2String(aid)},
{"net", stream->network},
{"host", stream->host},
{"path", stream->path},
{"type", stream->header_type},
{"scy", security},
{"tls", stream->security == "tls" ? "tls" : ""},
{"sni", stream->sni},
};
return "vmess://" + QJsonObject2QString(N, true).toUtf8().toBase64();
} else {
// ducksoft format
QUrl url;
QUrlQuery query;
url.setScheme("vmess");
url.setUserName(uuid);
url.setHost(serverAddress);
url.setPort(serverPort);
if (!name.isEmpty()) url.setFragment(name);
query.addQueryItem("encryption", security);
// security
auto security = stream->security;
if (security == "tls" && !stream->reality_pbk.trimmed().isEmpty()) security = "reality";
query.addQueryItem("security", security);
if (!stream->sni.isEmpty()) query.addQueryItem("sni", stream->sni);
if (stream->allow_insecure) query.addQueryItem("allowInsecure", "1");
if (stream->utlsFingerprint.isEmpty()) {
query.addQueryItem("fp", NekoGui::dataStore->utlsFingerprint);
} else {
query.addQueryItem("fp", stream->utlsFingerprint);
}
if (security == "reality") {
query.addQueryItem("pbk", stream->reality_pbk);
if (!stream->reality_sid.isEmpty()) query.addQueryItem("sid", stream->reality_sid);
if (!stream->reality_spx.isEmpty()) query.addQueryItem("spx", stream->reality_spx);
}
// type
query.addQueryItem("type", stream->network);
if (stream->network == "ws" || stream->network == "http" || stream->network == "httpupgrade") {
if (!stream->path.isEmpty()) query.addQueryItem("path", stream->path);
if (!stream->host.isEmpty()) query.addQueryItem("host", stream->host);
} else if (stream->network == "grpc") {
if (!stream->path.isEmpty()) query.addQueryItem("serviceName", stream->path);
} else if (stream->network == "tcp") {
if (stream->header_type == "http") {
query.addQueryItem("headerType", "http");
query.addQueryItem("host", stream->host);
}
}
url.setQuery(query);
return url.toString(QUrl::FullyEncoded);
}
}
QString NaiveBean::ToShareLink() {
QUrl url;
url.setScheme("naive+" + protocol);
url.setUserName(username);
url.setPassword(password);
url.setHost(serverAddress);
url.setPort(serverPort);
if (!name.isEmpty()) url.setFragment(name);
return url.toString(QUrl::FullyEncoded);
}
QString QUICBean::ToShareLink() {
QUrl url;
if (proxy_type == proxy_TUIC) {
url.setScheme("tuic");
url.setUserName(uuid);
url.setPassword(password);
url.setHost(serverAddress);
url.setPort(serverPort);
QUrlQuery q;
if (!congestionControl.isEmpty()) q.addQueryItem("congestion_control", congestionControl);
if (!alpn.isEmpty()) q.addQueryItem("alpn", alpn);
if (!sni.isEmpty()) q.addQueryItem("sni", sni);
if (!udpRelayMode.isEmpty()) q.addQueryItem("udp_relay_mode", udpRelayMode);
if (allowInsecure) q.addQueryItem("allow_insecure", "1");
if (disableSni) q.addQueryItem("disable_sni", "1");
if (!q.isEmpty()) url.setQuery(q);
if (!name.isEmpty()) url.setFragment(name);
} else if (proxy_type == proxy_Hysteria2) {
url.setScheme("hy2");
url.setHost(serverAddress);
url.setPort(serverPort);
if (password.contains(":")) {
url.setUserName(SubStrBefore(password, ":"));
url.setPassword(SubStrAfter(password, ":"));
} else {
url.setUserName(password);
}
QUrlQuery q;
if (!obfsPassword.isEmpty()) {
q.addQueryItem("obfs", "salamander");
q.addQueryItem("obfs-password", obfsPassword);
}
if (!hopPort.trimmed().isEmpty()) q.addQueryItem("mport", hopPort);
if (allowInsecure) q.addQueryItem("insecure", "1");
if (!sni.isEmpty()) q.addQueryItem("sni", sni);
if (!q.isEmpty()) url.setQuery(q);
if (!name.isEmpty()) url.setFragment(name);
}
return url.toString(QUrl::FullyEncoded);
}
} // namespace NekoGui_fmt
| 9,159
|
C++
|
.cpp
| 201
| 33.885572
| 113
| 0.55803
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,654
|
AbstractBean.cpp
|
MatsuriDayo_nekoray/fmt/AbstractBean.cpp
|
#include "includes.h"
#include <QApplication>
#include <QHostInfo>
#include <QUrl>
namespace NekoGui_fmt {
AbstractBean::AbstractBean(int version) {
this->version = version;
_add(new configItem("_v", &this->version, itemType::integer));
_add(new configItem("name", &name, itemType::string));
_add(new configItem("addr", &serverAddress, itemType::string));
_add(new configItem("port", &serverPort, itemType::integer));
_add(new configItem("c_cfg", &custom_config, itemType::string));
_add(new configItem("c_out", &custom_outbound, itemType::string));
}
QString AbstractBean::ToNekorayShareLink(const QString &type) {
auto b = ToJson();
QUrl url;
url.setScheme("nekoray");
url.setHost(type);
url.setFragment(QJsonObject2QString(b, true)
.toUtf8()
.toBase64(QByteArray::Base64UrlEncoding));
return url.toString();
}
QString AbstractBean::DisplayAddress() {
return ::DisplayAddress(serverAddress, serverPort);
}
QString AbstractBean::DisplayName() {
if (name.isEmpty()) {
return DisplayAddress();
}
return name;
}
QString AbstractBean::DisplayTypeAndName() {
return QString("[%1] %2").arg(DisplayType(), DisplayName());
}
void AbstractBean::ResolveDomainToIP(const std::function<void()> &onFinished) {
bool noResolve = false;
if (dynamic_cast<ChainBean *>(this) != nullptr) noResolve = true;
if (dynamic_cast<CustomBean *>(this) != nullptr) noResolve = true;
if (dynamic_cast<NaiveBean *>(this) != nullptr) noResolve = true;
if (IsIpAddress(serverAddress)) noResolve = true;
if (noResolve) {
onFinished();
return;
}
#if QT_VERSION >= QT_VERSION_CHECK(5, 11, 0) // TODO older QT
QHostInfo::lookupHost(serverAddress, QApplication::instance(), [=](const QHostInfo &host) {
auto addr = host.addresses();
if (!addr.isEmpty()) {
auto domain = serverAddress;
auto stream = GetStreamSettings(this);
// replace serverAddress
serverAddress = addr.first().toString();
// replace ws tls
if (stream != nullptr) {
if (stream->security == "tls" && stream->sni.isEmpty()) {
stream->sni = domain;
}
if (stream->network == "ws" && stream->host.isEmpty()) {
stream->host = domain;
}
}
}
onFinished();
});
#endif
}
} // namespace NekoGui_fmt
| 2,772
|
C++
|
.cpp
| 69
| 29.695652
| 99
| 0.564798
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,655
|
Bean2External.cpp
|
MatsuriDayo_nekoray/fmt/Bean2External.cpp
|
#include "db/ProxyEntity.hpp"
#include "fmt/includes.h"
#include <QFile>
#include <QDir>
#include <QFileInfo>
#include <QUrl>
#define WriteTempFile(fn, data) \
QDir dir; \
if (!dir.exists("temp")) dir.mkdir("temp"); \
QFile f(QString("temp/") + fn); \
bool ok = f.open(QIODevice::WriteOnly | QIODevice::Truncate); \
if (ok) { \
f.write(data); \
} else { \
result.error = f.errorString(); \
} \
f.close(); \
auto TempFile = QFileInfo(f).absoluteFilePath();
namespace NekoGui_fmt {
// -1: Cannot use this config
// 0: Internal
// 1: Mapping External
// 2: Direct External
int NaiveBean::NeedExternal(bool isFirstProfile) {
if (isFirstProfile) {
if (NekoGui::dataStore->spmode_vpn) {
return 1;
}
return 2;
}
return 1;
}
int QUICBean::NeedExternal(bool isFirstProfile) {
auto extCore = [=] {
if (isFirstProfile) {
if (NekoGui::dataStore->spmode_vpn && hopPort.trimmed().isEmpty()) {
return 1;
}
return 2;
} else {
if (!hopPort.trimmed().isEmpty()) {
return -1;
}
}
return 1;
};
if (!forceExternal) {
// sing-box support
return 0;
} else {
// external core support
return extCore();
}
}
int CustomBean::NeedExternal(bool isFirstProfile) {
if (core == "internal" || core == "internal-full") return 0;
return 1;
}
ExternalBuildResult NaiveBean::BuildExternal(int mapping_port, int socks_port, int external_stat) {
ExternalBuildResult result{NekoGui::dataStore->extraCore->Get("naive")};
auto is_direct = external_stat == 2;
auto domain_address = sni.isEmpty() ? serverAddress : sni;
auto connect_address = is_direct ? serverAddress : "127.0.0.1";
auto connect_port = is_direct ? serverPort : mapping_port;
domain_address = WrapIPV6Host(domain_address);
connect_address = WrapIPV6Host(connect_address);
auto proxy_url = QUrl();
proxy_url.setScheme(protocol);
proxy_url.setUserName(username);
proxy_url.setPassword(password);
proxy_url.setPort(connect_port);
proxy_url.setHost(domain_address);
if (!disable_log) result.arguments += "--log";
result.arguments += "--listen=socks://127.0.0.1:" + Int2String(socks_port);
result.arguments += "--proxy=" + proxy_url.toString(QUrl::FullyEncoded);
if (domain_address != connect_address)
result.arguments += "--host-resolver-rules=MAP " + domain_address + " " + connect_address;
if (insecure_concurrency > 0) result.arguments += "--insecure-concurrency=" + Int2String(insecure_concurrency);
if (!extra_headers.trimmed().isEmpty()) result.arguments += "--extra-headers=" + extra_headers;
if (!certificate.trimmed().isEmpty()) {
WriteTempFile("naive_" + GetRandomString(10) + ".crt", certificate.toUtf8());
result.env += "SSL_CERT_FILE=" + TempFile;
}
auto config_export = QStringList{result.program};
config_export += result.arguments;
result.config_export = QStringList2Command(config_export);
return result;
}
ExternalBuildResult QUICBean::BuildExternal(int mapping_port, int socks_port, int external_stat) {
if (proxy_type == proxy_TUIC) {
ExternalBuildResult result{NekoGui::dataStore->extraCore->Get("tuic")};
QJsonObject relay;
relay["uuid"] = uuid;
relay["password"] = password;
relay["udp_relay_mode"] = udpRelayMode;
relay["congestion_control"] = congestionControl;
relay["zero_rtt_handshake"] = zeroRttHandshake;
relay["disable_sni"] = disableSni;
if (!heartbeat.trimmed().isEmpty()) relay["heartbeat"] = heartbeat;
if (!alpn.trimmed().isEmpty()) relay["alpn"] = QList2QJsonArray(alpn.split(","));
if (!caText.trimmed().isEmpty()) {
WriteTempFile("tuic_" + GetRandomString(10) + ".crt", caText.toUtf8());
QJsonArray certificate;
certificate.append(TempFile);
relay["certificates"] = certificate;
}
// The most confused part of TUIC......
if (serverAddress == sni) {
relay["server"] = serverAddress + ":" + Int2String(serverPort);
} else {
relay["server"] = sni + ":" + Int2String(serverPort);
relay["ip"] = serverAddress;
}
QJsonObject local{
{"server", "127.0.0.1:" + Int2String(socks_port)},
};
QJsonObject config{
{"relay", relay},
{"local", local},
};
//
result.config_export = QJsonObject2QString(config, false);
WriteTempFile("tuic_" + GetRandomString(10) + ".json", result.config_export.toUtf8());
result.arguments = QStringList{"-c", TempFile};
return result;
} else if (proxy_type == proxy_Hysteria2) {
ExternalBuildResult result{NekoGui::dataStore->extraCore->Get("hysteria2")};
QJsonObject config;
auto server = serverAddress;
if (!hopPort.trimmed().isEmpty()) {
server = WrapIPV6Host(server) + ":" + hopPort;
} else {
server = WrapIPV6Host(server) + ":" + Int2String(serverPort);
}
QJsonObject transport;
transport["type"] = "udp";
transport["udp"] = QJsonObject{
{"hopInterval", QString::number(hopInterval) + "s"},
};
config["transport"] = transport;
config["server"] = server;
config["socks5"] = QJsonObject{
{"listen", "127.0.0.1:" + Int2String(socks_port)},
{"disableUDP", false},
};
config["auth"] = password;
QJsonObject bandwidth;
if (uploadMbps > 0) bandwidth["up"] = Int2String(uploadMbps) + " mbps";
if (downloadMbps > 0) bandwidth["down"] = Int2String(downloadMbps) + " mbps";
config["bandwidth"] = bandwidth;
QJsonObject quic;
if (streamReceiveWindow > 0) quic["initStreamReceiveWindow"] = streamReceiveWindow;
if (connectionReceiveWindow > 0) quic["initConnReceiveWindow"] = connectionReceiveWindow;
if (disableMtuDiscovery) quic["disablePathMTUDiscovery"] = true;
config["quic"] = quic;
config["fastOpen"] = true;
config["lazy"] = true;
if (!obfsPassword.isEmpty()) {
QJsonObject obfs;
obfs["type"] = "salamander";
obfs["salamander"] = QJsonObject{
{"password", obfsPassword},
};
config["obfs"] = obfs;
}
QJsonObject tls;
auto sniGen = sni;
if (sni.isEmpty() && !IsIpAddress(serverAddress)) sniGen = serverAddress;
tls["sni"] = sniGen;
if (allowInsecure) tls["insecure"] = true;
if (!caText.trimmed().isEmpty()) {
WriteTempFile("hysteria2_" + GetRandomString(10) + ".crt", caText.toUtf8());
QJsonArray certificate;
certificate.append(TempFile);
tls["certificates"] = certificate;
}
config["tls"] = tls;
result.config_export = QJsonObject2QString(config, false);
WriteTempFile("hysteria2_" + GetRandomString(10) + ".json", result.config_export.toUtf8());
result.arguments = QStringList{"-c", TempFile};
return result;
}
ExternalBuildResult e;
e.error = "unknown type";
return e;
}
ExternalBuildResult CustomBean::BuildExternal(int mapping_port, int socks_port, int external_stat) {
ExternalBuildResult result{NekoGui::dataStore->extraCore->Get(core)};
result.arguments = command; // TODO split?
for (int i = 0; i < result.arguments.length(); i++) {
auto arg = result.arguments[i];
arg = arg.replace("%mapping_port%", Int2String(mapping_port));
arg = arg.replace("%socks_port%", Int2String(socks_port));
arg = arg.replace("%server_addr%", serverAddress);
arg = arg.replace("%server_port%", Int2String(serverPort));
result.arguments[i] = arg;
}
if (!config_simple.trimmed().isEmpty()) {
auto config = config_simple;
config = config.replace("%mapping_port%", Int2String(mapping_port));
config = config.replace("%socks_port%", Int2String(socks_port));
config = config.replace("%server_addr%", serverAddress);
config = config.replace("%server_port%", Int2String(serverPort));
// suffix
QString suffix;
if (!config_suffix.isEmpty()) {
suffix = "." + config_suffix;
} else if (!QString2QJsonObject(config).isEmpty()) {
// trojan-go: unsupported config format: xxx.tmp. use .yaml or .json instead.
suffix = ".json";
}
// write config
WriteTempFile("custom_" + GetRandomString(10) + suffix, config.toUtf8());
for (int i = 0; i < result.arguments.count(); i++) {
result.arguments[i] = result.arguments[i].replace("%config%", TempFile);
}
result.config_export = config;
}
return result;
}
} // namespace NekoGui_fmt
| 10,339
|
C++
|
.cpp
| 221
| 35.158371
| 119
| 0.536033
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,656
|
ExternalProcess.cpp
|
MatsuriDayo_nekoray/sys/ExternalProcess.cpp
|
#include "ExternalProcess.hpp"
#include "main/NekoGui.hpp"
#include <QTimer>
#include <QDir>
#include <QApplication>
#include <QElapsedTimer>
namespace NekoGui_sys {
ExternalProcess::ExternalProcess() : QProcess() {
// qDebug() << "[Debug] ExternalProcess()" << this << running_ext;
this->env = QProcessEnvironment::systemEnvironment().toStringList();
}
ExternalProcess::~ExternalProcess() {
// qDebug() << "[Debug] ~ExternalProcess()" << this << running_ext;
}
void ExternalProcess::Start() {
if (started) return;
started = true;
if (managed) {
connect(this, &QProcess::readyReadStandardOutput, this, [&]() {
auto log = readAllStandardOutput();
if (logCounter.fetchAndAddRelaxed(log.count("\n")) > NekoGui::dataStore->max_log_line) return;
MW_show_log_ext_vt100(log);
});
connect(this, &QProcess::readyReadStandardError, this, [&]() {
MW_show_log_ext_vt100(readAllStandardError().trimmed());
});
connect(this, &QProcess::errorOccurred, this, [&](QProcess::ProcessError error) {
if (!killed) {
crashed = true;
MW_show_log_ext(tag, "errorOccurred:" + errorString());
MW_dialog_message("ExternalProcess", "Crashed");
}
});
connect(this, &QProcess::stateChanged, this, [&](QProcess::ProcessState state) {
if (state == QProcess::NotRunning) {
if (killed) { // 用户命令退出
MW_show_log_ext(tag, "External core stopped");
} else if (!crashed) { // 异常退出
crashed = true;
MW_show_log_ext(tag, "[Error] Program exited accidentally: " + errorString());
Kill();
MW_dialog_message("ExternalProcess", "Crashed");
}
}
});
MW_show_log_ext(tag, "External core starting: " + env.join(" ") + " " + program + " " + arguments.join(" "));
}
QProcess::setEnvironment(env);
QProcess::start(program, arguments);
}
void ExternalProcess::Kill() {
if (killed) return;
killed = true;
if (!crashed) {
QProcess::kill();
QProcess::waitForFinished(500);
}
}
//
QElapsedTimer coreRestartTimer;
CoreProcess::CoreProcess(const QString &core_path, const QStringList &args) : ExternalProcess() {
ExternalProcess::managed = false;
ExternalProcess::program = core_path;
ExternalProcess::arguments = args;
connect(this, &QProcess::readyReadStandardOutput, this, [&]() {
auto log = readAllStandardOutput();
if (!NekoGui::dataStore->core_running) {
if (log.contains("grpc server listening")) {
// The core really started
NekoGui::dataStore->core_running = true;
if (start_profile_when_core_is_up >= 0) {
MW_dialog_message("ExternalProcess", "CoreStarted," + Int2String(start_profile_when_core_is_up));
start_profile_when_core_is_up = -1;
}
} else if (log.contains("failed to serve")) {
// The core failed to start
QProcess::kill();
}
}
if (logCounter.fetchAndAddRelaxed(log.count("\n")) > NekoGui::dataStore->max_log_line) return;
MW_show_log(log);
});
connect(this, &QProcess::readyReadStandardError, this, [&]() {
auto log = readAllStandardError().trimmed();
if (show_stderr) {
MW_show_log(log);
return;
}
if (log.contains("token is set")) {
show_stderr = true;
}
});
connect(this, &QProcess::errorOccurred, this, [&](QProcess::ProcessError error) {
if (error == QProcess::ProcessError::FailedToStart) {
failed_to_start = true;
MW_show_log("start core error occurred: " + errorString() + "\n");
}
});
connect(this, &QProcess::stateChanged, this, [&](QProcess::ProcessState state) {
if (state == QProcess::NotRunning) {
NekoGui::dataStore->core_running = false;
}
if (!NekoGui::dataStore->prepare_exit && state == QProcess::NotRunning) {
if (failed_to_start) return; // no retry
if (restarting) return;
MW_dialog_message("ExternalProcess", "CoreCrashed");
// Retry rate limit
if (coreRestartTimer.isValid()) {
if (coreRestartTimer.restart() < 10 * 1000) {
coreRestartTimer = QElapsedTimer();
MW_show_log("[Error] " + QObject::tr("Core exits too frequently, stop automatic restart this profile."));
return;
}
} else {
coreRestartTimer.start();
}
// Restart
start_profile_when_core_is_up = NekoGui::dataStore->started_id;
MW_show_log("[Error] " + QObject::tr("Core exited, restarting."));
setTimeout([=] { Restart(); }, this, 1000);
}
});
}
void CoreProcess::Start() {
show_stderr = false;
// cwd: same as GUI, at ./config
ExternalProcess::Start();
write((NekoGui::dataStore->core_token + "\n").toUtf8());
}
void CoreProcess::Restart() {
restarting = true;
QProcess::kill();
QProcess::waitForFinished(500);
ExternalProcess::started = false;
Start();
restarting = false;
}
} // namespace NekoGui_sys
| 6,037
|
C++
|
.cpp
| 138
| 30.514493
| 129
| 0.522615
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,657
|
AutoRun.cpp
|
MatsuriDayo_nekoray/sys/AutoRun.cpp
|
#include "AutoRun.hpp"
#include <QApplication>
#include <QDir>
#include "3rdparty/fix_old_qt.h"
#include "main/NekoGui.hpp"
// macOS headers (possibly OBJ-c)
#if defined(Q_OS_MACOS)
#include <CoreFoundation/CoreFoundation.h>
#include <CoreServices/CoreServices.h>
#endif
#ifdef Q_OS_WIN
#include <QSettings>
QString Windows_GenAutoRunString() {
auto appPath = QApplication::applicationFilePath();
appPath = "\"" + QDir::toNativeSeparators(appPath) + "\"";
appPath += " -tray";
return appPath;
}
void AutoRun_SetEnabled(bool enable) {
// 以程序名称作为注册表中的键
// 根据键获取对应的值(程序路径)
auto appPath = QApplication::applicationFilePath();
QFileInfo fInfo(appPath);
QString name = fInfo.baseName();
QSettings settings("HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat);
if (enable) {
settings.setValue(name, Windows_GenAutoRunString());
} else {
settings.remove(name);
}
}
bool AutoRun_IsEnabled() {
QSettings settings("HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat);
// 以程序名称作为注册表中的键
// 根据键获取对应的值(程序路径)
auto appPath = QApplication::applicationFilePath();
QFileInfo fInfo(appPath);
QString name = fInfo.baseName();
return settings.value(name).toString() == Windows_GenAutoRunString();
}
#endif
#ifdef Q_OS_MACOS
void AutoRun_SetEnabled(bool enable) {
// From
// https://github.com/nextcloud/desktop/blob/master/src/common/utility_mac.cpp
QString filePath = QDir(QCoreApplication::applicationDirPath() + QLatin1String("/../..")).absolutePath();
CFStringRef folderCFStr = CFStringCreateWithCString(0, filePath.toUtf8().data(), kCFStringEncodingUTF8);
CFURLRef urlRef = CFURLCreateWithFileSystemPath(0, folderCFStr, kCFURLPOSIXPathStyle, true);
LSSharedFileListRef loginItems = LSSharedFileListCreate(0, kLSSharedFileListSessionLoginItems, 0);
if (loginItems && enable) {
// Insert an item to the list.
LSSharedFileListItemRef item =
LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemLast, 0, 0, urlRef, 0, 0);
if (item) CFRelease(item);
CFRelease(loginItems);
} else if (loginItems && !enable) {
// We need to iterate over the items and check which one is "ours".
UInt32 seedValue;
CFArrayRef itemsArray = LSSharedFileListCopySnapshot(loginItems, &seedValue);
CFStringRef appUrlRefString = CFURLGetString(urlRef);
for (int i = 0; i < CFArrayGetCount(itemsArray); i++) {
LSSharedFileListItemRef item = (LSSharedFileListItemRef) CFArrayGetValueAtIndex(itemsArray, i);
CFURLRef itemUrlRef = NULL;
if (LSSharedFileListItemResolve(item, 0, &itemUrlRef, NULL) == noErr && itemUrlRef) {
CFStringRef itemUrlString = CFURLGetString(itemUrlRef);
if (CFStringCompare(itemUrlString, appUrlRefString, 0) == kCFCompareEqualTo) {
LSSharedFileListItemRemove(loginItems, item); // remove it!
}
CFRelease(itemUrlRef);
}
}
CFRelease(itemsArray);
CFRelease(loginItems);
}
CFRelease(folderCFStr);
CFRelease(urlRef);
}
bool AutoRun_IsEnabled() {
// From
// https://github.com/nextcloud/desktop/blob/master/src/common/utility_mac.cpp
// this is quite some duplicate code with setLaunchOnStartup, at some
// point we should fix this FIXME.
bool returnValue = false;
QString filePath = QDir(QCoreApplication::applicationDirPath() + QLatin1String("/../..")).absolutePath();
CFStringRef folderCFStr = CFStringCreateWithCString(0, filePath.toUtf8().data(), kCFStringEncodingUTF8);
CFURLRef urlRef = CFURLCreateWithFileSystemPath(0, folderCFStr, kCFURLPOSIXPathStyle, true);
LSSharedFileListRef loginItems = LSSharedFileListCreate(0, kLSSharedFileListSessionLoginItems, 0);
if (loginItems) {
// We need to iterate over the items and check which one is "ours".
UInt32 seedValue;
CFArrayRef itemsArray = LSSharedFileListCopySnapshot(loginItems, &seedValue);
CFStringRef appUrlRefString = CFURLGetString(urlRef); // no need for release
for (int i = 0; i < CFArrayGetCount(itemsArray); i++) {
LSSharedFileListItemRef item = (LSSharedFileListItemRef) CFArrayGetValueAtIndex(itemsArray, i);
CFURLRef itemUrlRef = NULL;
if (LSSharedFileListItemResolve(item, 0, &itemUrlRef, NULL) == noErr && itemUrlRef) {
CFStringRef itemUrlString = CFURLGetString(itemUrlRef);
if (CFStringCompare(itemUrlString, appUrlRefString, 0) == kCFCompareEqualTo) {
returnValue = true;
}
CFRelease(itemUrlRef);
}
}
CFRelease(itemsArray);
}
CFRelease(loginItems);
CFRelease(folderCFStr);
CFRelease(urlRef);
return returnValue;
}
#endif
#ifdef Q_OS_LINUX
#include <QStandardPaths>
#include <QProcessEnvironment>
#include <QTextStream>
#define NEWLINE "\n"
// launchatlogin.cpp
// ShadowClash
//
// Created by TheWanderingCoel on 2018/6/12.
// Copyright © 2019 Coel Wu. All rights reserved.
//
QString getUserAutostartDir_private() {
QString config = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation);
config += QLatin1String("/autostart/");
return config;
}
void AutoRun_SetEnabled(bool enable) {
// From https://github.com/nextcloud/desktop/blob/master/src/common/utility_unix.cpp
QString appName = QCoreApplication::applicationName();
QString userAutoStartPath = getUserAutostartDir_private();
QString desktopFileLocation = userAutoStartPath + appName + QLatin1String(".desktop");
QStringList appCmdList;
// nekoray: launcher
if (qEnvironmentVariable("NKR_FROM_LAUNCHER") == "1") {
appCmdList << QApplication::applicationDirPath() + "/launcher"
<< "--";
} else {
if (QProcessEnvironment::systemEnvironment().contains("APPIMAGE")) {
appCmdList << QProcessEnvironment::systemEnvironment().value("APPIMAGE");
} else {
appCmdList << QApplication::applicationFilePath();
}
}
appCmdList << "-tray";
if (NekoGui::dataStore->flag_use_appdata) {
appCmdList << "-appdata";
}
if (enable) {
if (!QDir().exists(userAutoStartPath) && !QDir().mkpath(userAutoStartPath)) {
// qCWarning(lcUtility) << "Could not create autostart folder"
// << userAutoStartPath;
return;
}
QFile iniFile(desktopFileLocation);
if (!iniFile.open(QIODevice::WriteOnly)) {
// qCWarning(lcUtility) << "Could not write auto start entry" <<
// desktopFileLocation;
return;
}
QTextStream ts(&iniFile);
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
ts.setCodec("UTF-8");
#endif
ts << QLatin1String("[Desktop Entry]") << NEWLINE
<< QLatin1String("Name=") << appName << NEWLINE
<< QLatin1String("Exec=") << appCmdList.join(" ") << NEWLINE
<< QLatin1String("Terminal=") << "false" << NEWLINE
<< QLatin1String("Categories=") << "Network" << NEWLINE
<< QLatin1String("Type=") << "Application" << NEWLINE
<< QLatin1String("StartupNotify=") << "false" << NEWLINE
<< QLatin1String("X-GNOME-Autostart-enabled=") << "true" << NEWLINE;
ts.flush();
iniFile.close();
} else {
QFile::remove(desktopFileLocation);
}
}
bool AutoRun_IsEnabled() {
QString appName = QCoreApplication::applicationName();
QString desktopFileLocation = getUserAutostartDir_private() + appName + QLatin1String(".desktop");
return QFile::exists(desktopFileLocation);
}
#endif
| 8,027
|
C++
|
.cpp
| 184
| 36.146739
| 120
| 0.6776
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,658
|
LinuxCap.cpp
|
MatsuriDayo_nekoray/sys/linux/LinuxCap.cpp
|
#include "LinuxCap.h"
#include <QDebug>
#include <QProcess>
#include <QStandardPaths>
#define EXIT_CODE(p) (p.exitStatus() == QProcess::NormalExit ? p.exitCode() : -1)
QString Linux_GetCapString(const QString &path) {
QProcess p;
p.setProgram(Linux_FindCapProgsExec("getcap"));
p.setArguments({path});
p.start();
p.waitForFinished(500);
return p.readAllStandardOutput();
}
int Linux_Pkexec_SetCapString(const QString &path, const QString &cap) {
QProcess p;
p.setProgram("pkexec");
p.setArguments({Linux_FindCapProgsExec("setcap"), cap, path});
p.start();
p.waitForFinished(-1);
return EXIT_CODE(p);
}
bool Linux_HavePkexec() {
QProcess p;
p.setProgram("pkexec");
p.setArguments({"--help"});
p.setProcessChannelMode(QProcess::SeparateChannels);
p.start();
p.waitForFinished(500);
return EXIT_CODE(p) == 0;
}
QString Linux_FindCapProgsExec(const QString &name) {
QString exec = QStandardPaths::findExecutable(name);
if (exec.isEmpty())
exec = QStandardPaths::findExecutable(name, {"/usr/sbin", "/sbin"});
if (exec.isEmpty())
qDebug() << "Executable" << name << "could not be resolved";
else
qDebug() << "Found exec" << name << "at" << exec;
return exec.isEmpty() ? name : exec;
}
| 1,307
|
C++
|
.cpp
| 40
| 28.475
| 81
| 0.671168
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,659
|
MiniDump.cpp
|
MatsuriDayo_nekoray/sys/windows/MiniDump.cpp
|
#include "MiniDump.h"
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <tchar.h>
#include <dbghelp.h>
#include <QApplication>
#include <QDir>
#include <QDateTime>
#include <QMessageBox>
typedef BOOL(WINAPI *MINIDUMPWRITEDUMP)(
HANDLE hProcess,
DWORD dwPid,
HANDLE hFile,
MINIDUMP_TYPE DumpType,
CONST PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam,
CONST PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam,
CONST PMINIDUMP_CALLBACK_INFORMATION CallbackParam);
LONG __stdcall CreateCrashHandler(EXCEPTION_POINTERS *pException) {
QDir::setCurrent(QApplication::applicationDirPath());
HMODULE DllHandle = NULL;
DllHandle = LoadLibrary(_T("DBGHELP.DLL"));
if (DllHandle) {
MINIDUMPWRITEDUMP Dump = (MINIDUMPWRITEDUMP) GetProcAddress(DllHandle, "MiniDumpWriteDump");
if (Dump) {
// 创建 Dump 文件
QDateTime CurDTime = QDateTime::currentDateTime();
QString current_date = CurDTime.toString("yyyy_MM_dd_hh_mm_ss");
// dmp文件的命名
QString dumpText = "Dump_" + current_date + ".dmp";
EXCEPTION_RECORD *record = pException->ExceptionRecord;
QString errCode(QString::number(record->ExceptionCode, 16));
QString errAddr(QString::number((uintptr_t) record->ExceptionAddress, 16));
QString errFlag(QString::number(record->ExceptionFlags, 16));
QString errPara(QString::number(record->NumberParameters, 16));
HANDLE DumpHandle = CreateFile((LPCWSTR) dumpText.utf16(),
GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (DumpHandle != INVALID_HANDLE_VALUE) {
MINIDUMP_EXCEPTION_INFORMATION dumpInfo;
dumpInfo.ExceptionPointers = pException;
dumpInfo.ThreadId = GetCurrentThreadId();
dumpInfo.ClientPointers = TRUE;
// 将dump信息写入dmp文件
Dump(GetCurrentProcess(), GetCurrentProcessId(), DumpHandle, MiniDumpNormal, &dumpInfo,
NULL, NULL);
CloseHandle(DumpHandle);
} else {
dumpText = "";
}
// 创建消息提示
QMessageBox::warning(NULL, "Application crashed",
QString("ErrorCode: %1 ErrorAddr:%2 ErrorFlag: %3 ErrorPara: %4\nVersion: %5\nDump file at %6")
.arg(errCode)
.arg(errAddr)
.arg(errFlag)
.arg(errPara)
.arg(NKR_VERSION)
.arg(dumpText),
QMessageBox::Ok);
}
}
return EXCEPTION_EXECUTE_HANDLER;
}
void Windows_SetCrashHandler() {
SetErrorMode(SEM_FAILCRITICALERRORS);
SetUnhandledExceptionFilter(CreateCrashHandler);
}
| 3,059
|
C++
|
.cpp
| 68
| 32.117647
| 128
| 0.595918
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,660
|
guihelper.cpp
|
MatsuriDayo_nekoray/sys/windows/guihelper.cpp
|
#include "guihelper.h"
#include <QWidget>
#include <windows.h>
#include <shlobj.h>
void Windows_QWidget_SetForegroundWindow(QWidget *w) {
HWND hForgroundWnd = GetForegroundWindow();
DWORD dwForeID = ::GetWindowThreadProcessId(hForgroundWnd, NULL);
DWORD dwCurID = ::GetCurrentThreadId();
::AttachThreadInput(dwCurID, dwForeID, TRUE);
::SetForegroundWindow((HWND) w->winId());
::AttachThreadInput(dwCurID, dwForeID, FALSE);
}
int isThisAdmin = -1; // cached
bool Windows_IsInAdmin() {
if (isThisAdmin >= 0) return isThisAdmin;
isThisAdmin = IsUserAnAdmin();
return isThisAdmin;
}
| 621
|
C++
|
.cpp
| 18
| 31.166667
| 69
| 0.737018
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,661
|
gRPC.cpp
|
MatsuriDayo_nekoray/rpc/gRPC.cpp
|
#include "gRPC.h"
#include <utility>
#include <QStringList>
#ifndef NKR_NO_GRPC
#include "main/NekoGui.hpp"
#include <QCoreApplication>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QTimer>
#include <QtEndian>
#include <QThread>
#include <QMutex>
#include <QAbstractNetworkCache>
namespace QtGrpc {
const char *GrpcAcceptEncodingHeader = "grpc-accept-encoding";
const char *AcceptEncodingHeader = "accept-encoding";
const char *TEHeader = "te";
const char *GrpcStatusHeader = "grpc-status";
const char *GrpcStatusMessage = "grpc-message";
const int GrpcMessageSizeHeaderSize = 5;
class NoCache : public QAbstractNetworkCache {
public:
QNetworkCacheMetaData metaData(const QUrl &url) override {
return {};
}
void updateMetaData(const QNetworkCacheMetaData &metaData) override {
}
QIODevice *data(const QUrl &url) override {
return nullptr;
}
bool remove(const QUrl &url) override {
return false;
}
[[nodiscard]] qint64 cacheSize() const override {
return 0;
}
QIODevice *prepare(const QNetworkCacheMetaData &metaData) override {
return nullptr;
}
void insert(QIODevice *device) override {
}
void clear() override {
}
};
class Http2GrpcChannelPrivate {
private:
QThread *thread;
QNetworkAccessManager *nm;
QString url_base;
QString serviceName;
QByteArray nekoray_auth;
// async
QNetworkReply *post(const QString &method, const QString &service, const QByteArray &args) {
QUrl callUrl = url_base + "/" + service + "/" + method;
// qDebug() << "Service call url: " << callUrl;
QNetworkRequest request(callUrl);
// request.setAttribute(QNetworkRequest::CacheSaveControlAttribute, false);
// request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::AlwaysNetwork);
#if QT_VERSION >= QT_VERSION_CHECK(5, 11, 0)
request.setAttribute(QNetworkRequest::Http2DirectAttribute, true);
#endif
request.setHeader(QNetworkRequest::ContentTypeHeader, QLatin1String{"application/grpc"});
request.setRawHeader("Cache-Control", "no-store");
request.setRawHeader(GrpcAcceptEncodingHeader, QByteArray{"identity,deflate,gzip"});
request.setRawHeader(AcceptEncodingHeader, QByteArray{"identity,gzip"});
request.setRawHeader(TEHeader, QByteArray{"trailers"});
request.setRawHeader("nekoray_auth", nekoray_auth);
QByteArray msg(GrpcMessageSizeHeaderSize, '\0');
*reinterpret_cast<int *>(msg.data() + 1) = qToBigEndian((int) args.size());
msg += args;
// qDebug() << "SEND: " << msg.size();
QNetworkReply *networkReply = nm->post(request, msg);
return networkReply;
}
static QByteArray processReply(QNetworkReply *networkReply, QNetworkReply::NetworkError &statusCode) {
// Check if no network error occured
if (networkReply->error() != QNetworkReply::NoError) {
statusCode = networkReply->error();
return {};
}
// Check if server answer with error
auto errCode = networkReply->rawHeader(GrpcStatusHeader).toInt();
if (errCode != 0) {
QStringList errstr;
errstr << "grpc-status error code:" << Int2String(errCode) << ", error msg:"
<< QLatin1String(networkReply->rawHeader(GrpcStatusMessage));
MW_show_log(errstr.join(" "));
statusCode = QNetworkReply::NetworkError::ProtocolUnknownError;
return {};
}
statusCode = QNetworkReply::NetworkError::NoError;
return networkReply->readAll().mid(GrpcMessageSizeHeaderSize);
}
QNetworkReply::NetworkError call(const QString &method, const QString &service, const QByteArray &args, QByteArray &qByteArray, int timeout_ms) {
QNetworkReply *networkReply = post(method, service, args);
QTimer *abortTimer = nullptr;
if (timeout_ms > 0) {
abortTimer = new QTimer;
abortTimer->setSingleShot(true);
abortTimer->setInterval(timeout_ms);
QObject::connect(abortTimer, &QTimer::timeout, networkReply, &QNetworkReply::abort);
abortTimer->start();
}
{
QEventLoop loop;
QObject::connect(networkReply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
loop.exec();
}
if (abortTimer != nullptr) {
abortTimer->stop();
abortTimer->deleteLater();
}
auto grpcStatus = QNetworkReply::NetworkError::ProtocolUnknownError;
qByteArray = processReply(networkReply, grpcStatus);
// qDebug() << __func__ << "RECV: " << qByteArray.toHex() << "grpcStatus" << grpcStatus;
// qDebug() << networkReply->rawHeaderPairs();
networkReply->deleteLater();
return grpcStatus;
}
public:
Http2GrpcChannelPrivate(const QString &url_, const QString &nekoray_auth_, const QString &serviceName_) {
url_base = "http://" + url_;
nekoray_auth = nekoray_auth_.toLatin1();
serviceName = serviceName_;
//
thread = new QThread;
nm = new QNetworkAccessManager();
nm->setCache(new NoCache);
nm->moveToThread(thread);
thread->start();
}
~Http2GrpcChannelPrivate() {
nm->deleteLater();
thread->quit();
thread->wait();
thread->deleteLater();
}
QNetworkReply::NetworkError Call(const QString &methodName,
const google::protobuf::Message &req, google::protobuf::Message *rsp,
int timeout_ms = 0) {
if (!NekoGui::dataStore->core_running) return QNetworkReply::NetworkError(-1919);
std::string reqStr;
req.SerializeToString(&reqStr);
auto requestArray = QByteArray::fromStdString(reqStr);
QByteArray responseArray;
QNetworkReply::NetworkError err;
QMutex lock;
lock.lock();
runOnUiThread(
[&] {
err = call(methodName, serviceName, requestArray, responseArray, timeout_ms);
lock.unlock();
},
nm);
lock.lock();
lock.unlock();
// qDebug() << "rsp err" << err;
// qDebug() << "rsp array" << responseArray;
if (err != QNetworkReply::NetworkError::NoError) {
return err;
}
if (!rsp->ParseFromArray(responseArray.data(), responseArray.size())) {
return QNetworkReply::NetworkError(-114514);
}
return QNetworkReply::NetworkError::NoError;
}
};
} // namespace QtGrpc
namespace NekoGui_rpc {
Client::Client(std::function<void(const QString &)> onError, const QString &target, const QString &token) {
this->make_grpc_channel = [=]() { return std::make_unique<QtGrpc::Http2GrpcChannelPrivate>(target, token, "libcore.LibcoreService"); };
this->default_grpc_channel = make_grpc_channel();
this->onError = std::move(onError);
}
#define NOT_OK \
*rpcOK = false; \
onError(QString("QNetworkReply::NetworkError code: %1\n").arg(status));
void Client::Exit() {
libcore::EmptyReq request;
libcore::EmptyResp reply;
default_grpc_channel->Call("Exit", request, &reply, 500);
}
QString Client::Start(bool *rpcOK, const libcore::LoadConfigReq &request) {
libcore::ErrorResp reply;
auto status = default_grpc_channel->Call("Start", request, &reply);
if (status == QNetworkReply::NoError) {
*rpcOK = true;
return {reply.error().c_str()};
} else {
NOT_OK
return "";
}
}
QString Client::Stop(bool *rpcOK) {
libcore::EmptyReq request;
libcore::ErrorResp reply;
auto status = default_grpc_channel->Call("Stop", request, &reply);
if (status == QNetworkReply::NoError) {
*rpcOK = true;
return {reply.error().c_str()};
} else {
NOT_OK
return "";
}
}
long long Client::QueryStats(const std::string &tag, const std::string &direct) {
libcore::QueryStatsReq request;
request.set_tag(tag);
request.set_direct(direct);
libcore::QueryStatsResp reply;
auto status = default_grpc_channel->Call("QueryStats", request, &reply, 500);
if (status == QNetworkReply::NoError) {
return reply.traffic();
} else {
return 0;
}
}
std::string Client::ListConnections() {
libcore::EmptyReq request;
libcore::ListConnectionsResp reply;
auto status = default_grpc_channel->Call("ListConnections", request, &reply, 500);
if (status == QNetworkReply::NoError) {
return reply.nekoray_connections_json();
} else {
return "";
}
}
//
libcore::TestResp Client::Test(bool *rpcOK, const libcore::TestReq &request) {
libcore::TestResp reply;
auto status = make_grpc_channel()->Call("Test", request, &reply);
if (status == QNetworkReply::NoError) {
*rpcOK = true;
return reply;
} else {
NOT_OK
return reply;
}
}
libcore::UpdateResp Client::Update(bool *rpcOK, const libcore::UpdateReq &request) {
libcore::UpdateResp reply;
auto status = default_grpc_channel->Call("Update", request, &reply);
if (status == QNetworkReply::NoError) {
*rpcOK = true;
return reply;
} else {
NOT_OK
return reply;
}
}
} // namespace NekoGui_rpc
#endif
| 10,405
|
C++
|
.cpp
| 252
| 30.623016
| 153
| 0.586879
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,662
|
main.cpp
|
MatsuriDayo_nekoray/main/main.cpp
|
#include <csignal>
#include <QApplication>
#include <QDir>
#include <QTranslator>
#include <QMessageBox>
#include <QStandardPaths>
#include <QLocalSocket>
#include <QLocalServer>
#include <QThread>
#include "3rdparty/RunGuard.hpp"
#include "main/NekoGui.hpp"
#include "ui/mainwindow_interface.h"
#ifdef Q_OS_WIN
#include "sys/windows/MiniDump.h"
#endif
void signal_handler(int signum) {
if (qApp) {
GetMainWindow()->on_commitDataRequest();
qApp->exit();
}
}
QTranslator* trans = nullptr;
QTranslator* trans_qt = nullptr;
void loadTranslate(const QString& locale) {
if (trans != nullptr) {
trans->deleteLater();
}
if (trans_qt != nullptr) {
trans_qt->deleteLater();
}
//
trans = new QTranslator;
trans_qt = new QTranslator;
QLocale::setDefault(QLocale(locale));
//
if (trans->load(":/translations/" + locale + ".qm")) {
QCoreApplication::installTranslator(trans);
}
if (trans_qt->load(QApplication::applicationDirPath() + "/qtbase_" + locale + ".qm")) {
QCoreApplication::installTranslator(trans_qt);
}
}
#define LOCAL_SERVER_PREFIX "nekoraylocalserver-"
int main(int argc, char* argv[]) {
// Core dump
#ifdef Q_OS_WIN
Windows_SetCrashHandler();
#endif
// pre-init QApplication
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) && QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)
QApplication::setAttribute(Qt::AA_DisableWindowContextHelpButton);
#endif
#if QT_VERSION >= QT_VERSION_CHECK(5, 7, 0)
QApplication::setAttribute(Qt::AA_DontUseNativeDialogs);
#endif
QApplication::setQuitOnLastWindowClosed(false);
auto preQApp = new QApplication(argc, argv);
// Clean
QDir::setCurrent(QApplication::applicationDirPath());
if (QFile::exists("updater.old")) {
QFile::remove("updater.old");
}
#ifndef Q_OS_WIN
if (!QFile::exists("updater")) {
QFile::link("launcher", "updater");
}
#endif
// Flags
NekoGui::dataStore->argv = QApplication::arguments();
if (NekoGui::dataStore->argv.contains("-many")) NekoGui::dataStore->flag_many = true;
if (NekoGui::dataStore->argv.contains("-appdata")) {
NekoGui::dataStore->flag_use_appdata = true;
int appdataIndex = NekoGui::dataStore->argv.indexOf("-appdata");
if (NekoGui::dataStore->argv.size() > appdataIndex + 1 && !NekoGui::dataStore->argv.at(appdataIndex + 1).startsWith("-")) {
NekoGui::dataStore->appdataDir = NekoGui::dataStore->argv.at(appdataIndex + 1);
}
}
if (NekoGui::dataStore->argv.contains("-tray")) NekoGui::dataStore->flag_tray = true;
if (NekoGui::dataStore->argv.contains("-debug")) NekoGui::dataStore->flag_debug = true;
if (NekoGui::dataStore->argv.contains("-flag_restart_tun_on")) NekoGui::dataStore->flag_restart_tun_on = true;
if (NekoGui::dataStore->argv.contains("-flag_reorder")) NekoGui::dataStore->flag_reorder = true;
#ifdef NKR_CPP_USE_APPDATA
NekoGui::dataStore->flag_use_appdata = true; // Example: Package & MacOS
#endif
#ifdef NKR_CPP_DEBUG
NekoGui::dataStore->flag_debug = true;
#endif
// dirs & clean
auto wd = QDir(QApplication::applicationDirPath());
if (NekoGui::dataStore->flag_use_appdata) {
QApplication::setApplicationName("nekoray");
if (!NekoGui::dataStore->appdataDir.isEmpty()) {
wd.setPath(NekoGui::dataStore->appdataDir);
} else {
wd.setPath(QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation));
}
}
if (!wd.exists()) wd.mkpath(wd.absolutePath());
if (!wd.exists("config")) wd.mkdir("config");
QDir::setCurrent(wd.absoluteFilePath("config"));
QDir("temp").removeRecursively();
// init QApplication
delete preQApp;
QApplication a(argc, argv);
// dispatchers
DS_cores = new QThread;
DS_cores->start();
// RunGuard
RunGuard guard("nekoray" + wd.absolutePath());
quint64 guard_data_in = GetRandomUint64();
quint64 guard_data_out = 0;
if (!NekoGui::dataStore->flag_many && !guard.tryToRun(&guard_data_in)) {
// Some Good System
if (guard.isAnotherRunning(&guard_data_out)) {
// Wake up a running instance
QLocalSocket socket;
socket.connectToServer(LOCAL_SERVER_PREFIX + Int2String(guard_data_out));
qDebug() << socket.fullServerName();
if (!socket.waitForConnected(500)) {
qDebug() << "Failed to wake a running instance.";
return 0;
}
qDebug() << "connected to local server, try to raise another program";
return 0;
}
// Some Bad System
QMessageBox::warning(nullptr, "NekoGui", "RunGuard disallow to run, use -many to force start.");
return 0;
}
MF_release_runguard = [&] { guard.release(); };
// icons
#if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
QIcon::setFallbackSearchPaths(QStringList{
":/neko",
":/icon",
});
#endif
// icon for no theme
if (QIcon::themeName().isEmpty()) {
QIcon::setThemeName("breeze");
}
// Dir
QDir dir;
bool dir_success = true;
if (!dir.exists("profiles")) {
dir_success &= dir.mkdir("profiles");
}
if (!dir.exists("groups")) {
dir_success &= dir.mkdir("groups");
}
if (!dir.exists(ROUTES_PREFIX_NAME)) {
dir_success &= dir.mkdir(ROUTES_PREFIX_NAME);
}
if (!dir_success) {
QMessageBox::warning(nullptr, "Error", "No permission to write " + dir.absolutePath());
return 1;
}
// Load dataStore
switch (NekoGui::coreType) {
case NekoGui::CoreType::SING_BOX:
NekoGui::dataStore->fn = "groups/nekobox.json";
break;
default:
MessageBoxWarning("Error", "Unknown coreType.");
return 0;
}
auto isLoaded = NekoGui::dataStore->Load();
if (!isLoaded) {
NekoGui::dataStore->Save();
}
// Datastore & Flags
if (NekoGui::dataStore->start_minimal) NekoGui::dataStore->flag_tray = true;
// load routing
NekoGui::dataStore->routing = std::make_unique<NekoGui::Routing>();
NekoGui::dataStore->routing->fn = ROUTES_PREFIX + NekoGui::dataStore->active_routing;
isLoaded = NekoGui::dataStore->routing->Load();
if (!isLoaded) {
NekoGui::dataStore->routing->Save();
}
// Translate
QString locale;
switch (NekoGui::dataStore->language) {
case 1: // English
break;
case 2:
locale = "zh_CN";
break;
case 3:
locale = "fa_IR"; // farsi(iran)
break;
case 4:
locale = "ru_RU"; // Russian
break;
default:
locale = QLocale().name();
}
QGuiApplication::tr("QT_LAYOUT_DIRECTION");
loadTranslate(locale);
// Signals
signal(SIGTERM, signal_handler);
signal(SIGINT, signal_handler);
// QLocalServer
QLocalServer server;
auto server_name = LOCAL_SERVER_PREFIX + Int2String(guard_data_in);
QLocalServer::removeServer(server_name);
server.listen(server_name);
QObject::connect(&server, &QLocalServer::newConnection, &a, [&] {
auto socket = server.nextPendingConnection();
qDebug() << "nextPendingConnection:" << server_name << socket;
socket->deleteLater();
// raise main window
MW_dialog_message("", "Raise");
});
UI_InitMainWindow();
return QApplication::exec();
}
| 7,551
|
C++
|
.cpp
| 216
| 28.782407
| 131
| 0.633466
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,663
|
NekoGui_Utils.cpp
|
MatsuriDayo_nekoray/main/NekoGui_Utils.cpp
|
#include "NekoGui_Utils.hpp"
#include "3rdparty/base64.h"
#include "3rdparty/QThreadCreateThread.hpp"
#include <random>
#include <QApplication>
#include <QUrlQuery>
#include <QTcpServer>
#include <QTimer>
#include <QMessageBox>
#include <QFile>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonDocument>
#include <QRegularExpression>
#include <QDateTime>
#include <QLocale>
#ifdef Q_OS_WIN
#include "sys/windows/guihelper.h"
#endif
QStringList SplitLines(const QString &_string) {
#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
return _string.split(QRegularExpression("[\r\n]"), Qt::SplitBehaviorFlags::SkipEmptyParts);
#else
return _string.split(QRegularExpression("[\r\n]"), QString::SkipEmptyParts);
#endif
}
QStringList SplitLinesSkipSharp(const QString &_string, int maxLine) {
auto lines = SplitLines(_string);
QStringList newLines;
int i = 0;
for (const auto &line: lines) {
if (line.trimmed().startsWith("#")) continue;
newLines << line;
if (maxLine > 0 && ++i >= maxLine) break;
}
return newLines;
}
QByteArray DecodeB64IfValid(const QString &input, QByteArray::Base64Options options) {
Qt515Base64::Base64Options newOptions = Qt515Base64::Base64Option::AbortOnBase64DecodingErrors;
if (options.testFlag(QByteArray::Base64UrlEncoding)) newOptions |= Qt515Base64::Base64Option::Base64UrlEncoding;
if (options.testFlag(QByteArray::OmitTrailingEquals)) newOptions |= Qt515Base64::Base64Option::OmitTrailingEquals;
auto result = Qt515Base64::QByteArray_fromBase64Encoding(input.toUtf8(), newOptions);
if (result) {
return result.decoded;
}
return {};
}
QString QStringList2Command(const QStringList &list) {
QStringList new_list;
for (auto str: list) {
auto q = "\"" + str.replace("\"", "\\\"") + "\"";
new_list << q;
}
return new_list.join(" ");
}
QString GetQueryValue(const QUrlQuery &q, const QString &key, const QString &def) {
auto a = q.queryItemValue(key);
if (a.isEmpty()) {
return def;
}
return a;
}
QString GetRandomString(int randomStringLength) {
std::random_device rd;
std::mt19937 mt(rd());
const QString possibleCharacters("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
std::uniform_int_distribution<int> dist(0, possibleCharacters.length() - 1);
QString randomString;
for (int i = 0; i < randomStringLength; ++i) {
QChar nextChar = possibleCharacters.at(dist(mt));
randomString.append(nextChar);
}
return randomString;
}
quint64 GetRandomUint64() {
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_int_distribution<quint64> dist;
return dist(mt);
}
// QString >> QJson
QJsonObject QString2QJsonObject(const QString &jsonString) {
QJsonDocument jsonDocument = QJsonDocument::fromJson(jsonString.toUtf8());
QJsonObject jsonObject = jsonDocument.object();
return jsonObject;
}
// QJson >> QString
QString QJsonObject2QString(const QJsonObject &jsonObject, bool compact) {
return QJsonDocument(jsonObject).toJson(compact ? QJsonDocument::Compact : QJsonDocument::Indented);
}
template<typename T>
QJsonArray QList2QJsonArray(const QList<T> &list) {
QVariantList list2;
for (auto &item: list)
list2.append(item);
return QJsonArray::fromVariantList(list2);
}
template QJsonArray QList2QJsonArray<int>(const QList<int> &list);
template QJsonArray QList2QJsonArray<QString>(const QList<QString> &list);
QList<int> QJsonArray2QListInt(const QJsonArray &arr) {
QList<int> list2;
for (auto item: arr)
list2.append(item.toInt());
return list2;
}
QList<QString> QJsonArray2QListString(const QJsonArray &arr) {
QList<QString> list2;
for (auto item: arr)
list2.append(item.toString());
return list2;
}
QByteArray ReadFile(const QString &path) {
QFile file(path);
file.open(QFile::ReadOnly);
return file.readAll();
}
QString ReadFileText(const QString &path) {
QFile file(path);
file.open(QFile::ReadOnly | QFile::Text);
QTextStream stream(&file);
return stream.readAll();
}
int MkPort() {
QTcpServer s;
s.listen();
auto port = s.serverPort();
s.close();
return port;
}
QString ReadableSize(const qint64 &size) {
double sizeAsDouble = size;
static QStringList measures;
if (measures.isEmpty())
measures << "B"
<< "KiB"
<< "MiB"
<< "GiB"
<< "TiB"
<< "PiB"
<< "EiB"
<< "ZiB"
<< "YiB";
QStringListIterator it(measures);
QString measure(it.next());
while (sizeAsDouble >= 1024.0 && it.hasNext()) {
measure = it.next();
sizeAsDouble /= 1024.0;
}
return QString::fromLatin1("%1 %2").arg(sizeAsDouble, 0, 'f', 2).arg(measure);
}
bool IsIpAddress(const QString &str) {
auto address = QHostAddress(str);
if (address.protocol() == QAbstractSocket::IPv4Protocol || address.protocol() == QAbstractSocket::IPv6Protocol)
return true;
return false;
}
bool IsIpAddressV4(const QString &str) {
auto address = QHostAddress(str);
if (address.protocol() == QAbstractSocket::IPv4Protocol)
return true;
return false;
}
bool IsIpAddressV6(const QString &str) {
auto address = QHostAddress(str);
if (address.protocol() == QAbstractSocket::IPv6Protocol)
return true;
return false;
}
QString DisplayTime(long long time, int formatType) {
QDateTime t;
t.setMSecsSinceEpoch(time * 1000);
return QLocale().toString(t, QLocale::FormatType(formatType));
}
QWidget *GetMessageBoxParent() {
auto activeWindow = QApplication::activeWindow();
if (activeWindow == nullptr && mainwindow != nullptr) {
if (mainwindow->isVisible()) return mainwindow;
return nullptr;
}
return activeWindow;
}
int MessageBoxWarning(const QString &title, const QString &text) {
return QMessageBox::warning(GetMessageBoxParent(), title, text);
}
int MessageBoxInfo(const QString &title, const QString &text) {
return QMessageBox::information(GetMessageBoxParent(), title, text);
}
void ActivateWindow(QWidget *w) {
w->setWindowState(w->windowState() & ~Qt::WindowMinimized);
w->setVisible(true);
#ifdef Q_OS_WIN
Windows_QWidget_SetForegroundWindow(w);
#endif
w->raise();
w->activateWindow();
}
void runOnUiThread(const std::function<void()> &callback, QObject *parent) {
// any thread
auto *timer = new QTimer();
auto thread = dynamic_cast<QThread *>(parent);
if (thread == nullptr) {
timer->moveToThread(parent == nullptr ? mainwindow->thread() : parent->thread());
} else {
timer->moveToThread(thread);
}
timer->setSingleShot(true);
QObject::connect(timer, &QTimer::timeout, [=]() {
// main thread
callback();
timer->deleteLater();
});
QMetaObject::invokeMethod(timer, "start", Qt::QueuedConnection, Q_ARG(int, 0));
}
void runOnNewThread(const std::function<void()> &callback) {
createQThread(callback)->start();
}
void setTimeout(const std::function<void()> &callback, QObject *obj, int timeout) {
auto t = new QTimer;
QObject::connect(t, &QTimer::timeout, obj, [=] {
callback();
t->deleteLater();
});
t->setSingleShot(true);
t->setInterval(timeout);
t->start();
}
| 7,473
|
C++
|
.cpp
| 226
| 28.442478
| 118
| 0.686772
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,664
|
NekoGui.cpp
|
MatsuriDayo_nekoray/main/NekoGui.cpp
|
#include "NekoGui.hpp"
#include "fmt/Preset.hpp"
#include <QFile>
#include <QDir>
#include <QApplication>
#include <QFileInfo>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonDocument>
#ifdef Q_OS_WIN
#include "sys/windows/guihelper.h"
#else
#ifdef Q_OS_LINUX
#include <sys/linux/LinuxCap.h>
#endif
#include <unistd.h>
#endif
namespace NekoGui_ConfigItem {
// 添加关联
void JsonStore::_add(configItem *item) {
_map.insert(item->name, std::shared_ptr<configItem>(item));
}
QString JsonStore::_name(void *p) {
for (const auto &_item: _map) {
if (_item->ptr == p) return _item->name;
}
return {};
}
std::shared_ptr<configItem> JsonStore::_get(const QString &name) {
// 直接 [] 会设置一个 nullptr ,所以先判断是否存在
if (_map.contains(name)) {
return _map[name];
}
return nullptr;
}
void JsonStore::_setValue(const QString &name, void *p) {
auto item = _get(name);
if (item == nullptr) return;
switch (item->type) {
case itemType::string:
*(QString *) item->ptr = *(QString *) p;
break;
case itemType::boolean:
*(bool *) item->ptr = *(bool *) p;
break;
case itemType::integer:
*(int *) item->ptr = *(int *) p;
break;
case itemType::integer64:
*(long long *) item->ptr = *(long long *) p;
break;
// others...
case stringList:
case integerList:
case jsonStore:
break;
}
}
QJsonObject JsonStore::ToJson(const QStringList &without) {
QJsonObject object;
for (const auto &_item: _map) {
auto item = _item.get();
if (without.contains(item->name)) continue;
switch (item->type) {
case itemType::string:
// Allow Empty
if (!((QString *) item->ptr)->isEmpty()) {
object.insert(item->name, *(QString *) item->ptr);
}
break;
case itemType::integer:
object.insert(item->name, *(int *) item->ptr);
break;
case itemType::integer64:
object.insert(item->name, *(long long *) item->ptr);
break;
case itemType::boolean:
object.insert(item->name, *(bool *) item->ptr);
break;
case itemType::stringList:
object.insert(item->name, QList2QJsonArray<QString>(*(QList<QString> *) item->ptr));
break;
case itemType::integerList:
object.insert(item->name, QList2QJsonArray<int>(*(QList<int> *) item->ptr));
break;
case itemType::jsonStore:
// _add 时应关联对应 JsonStore 的指针
object.insert(item->name, ((JsonStore *) item->ptr)->ToJson());
break;
}
}
return object;
}
QByteArray JsonStore::ToJsonBytes() {
QJsonDocument document;
document.setObject(ToJson());
return document.toJson(save_control_compact ? QJsonDocument::Compact : QJsonDocument::Indented);
}
void JsonStore::FromJson(QJsonObject object) {
for (const auto &key: object.keys()) {
if (_map.count(key) == 0) {
continue;
}
auto value = object[key];
auto item = _map[key].get();
if (item == nullptr)
continue; // 故意忽略
// 根据类型修改ptr的内容
switch (item->type) {
case itemType::string:
if (value.type() != QJsonValue::String) {
continue;
}
*(QString *) item->ptr = value.toString();
break;
case itemType::integer:
if (value.type() != QJsonValue::Double) {
continue;
}
*(int *) item->ptr = value.toInt();
break;
case itemType::integer64:
if (value.type() != QJsonValue::Double) {
continue;
}
*(long long *) item->ptr = value.toDouble();
break;
case itemType::boolean:
if (value.type() != QJsonValue::Bool) {
continue;
}
*(bool *) item->ptr = value.toBool();
break;
case itemType::stringList:
if (value.type() != QJsonValue::Array) {
continue;
}
*(QList<QString> *) item->ptr = QJsonArray2QListString(value.toArray());
break;
case itemType::integerList:
if (value.type() != QJsonValue::Array) {
continue;
}
*(QList<int> *) item->ptr = QJsonArray2QListInt(value.toArray());
break;
case itemType::jsonStore:
if (value.type() != QJsonValue::Object) {
continue;
}
((JsonStore *) item->ptr)->FromJson(value.toObject());
break;
}
}
if (callback_after_load != nullptr) callback_after_load();
}
void JsonStore::FromJsonBytes(const QByteArray &data) {
QJsonParseError error{};
auto document = QJsonDocument::fromJson(data, &error);
if (error.error != error.NoError) {
qDebug() << "QJsonParseError" << error.errorString();
return;
}
FromJson(document.object());
}
bool JsonStore::Save() {
if (callback_before_save != nullptr) callback_before_save();
if (save_control_no_save) return false;
auto save_content = ToJsonBytes();
auto changed = last_save_content != save_content;
last_save_content = save_content;
QFile file;
file.setFileName(fn);
file.open(QIODevice::ReadWrite | QIODevice::Truncate);
file.write(save_content);
file.close();
return changed;
}
bool JsonStore::Load() {
QFile file;
file.setFileName(fn);
if (!file.exists() && !load_control_must) {
return false;
}
bool ok = file.open(QIODevice::ReadOnly);
if (!ok) {
MessageBoxWarning("error", "can not open config " + fn + "\n" + file.errorString());
} else {
last_save_content = file.readAll();
FromJsonBytes(last_save_content);
}
file.close();
return ok;
}
} // namespace NekoGui_ConfigItem
namespace NekoGui {
DataStore *dataStore = new DataStore();
// datastore
DataStore::DataStore() : JsonStore() {
_add(new configItem("extraCore", dynamic_cast<JsonStore *>(extraCore), itemType::jsonStore));
_add(new configItem("inbound_auth", dynamic_cast<JsonStore *>(inbound_auth), itemType::jsonStore));
_add(new configItem("user_agent2", &user_agent, itemType::string));
_add(new configItem("test_url", &test_latency_url, itemType::string));
_add(new configItem("test_url_dl", &test_download_url, itemType::string));
_add(new configItem("test_dl_timeout", &test_download_timeout, itemType::integer));
_add(new configItem("current_group", ¤t_group, itemType::integer));
_add(new configItem("inbound_address", &inbound_address, itemType::string));
_add(new configItem("inbound_socks_port", &inbound_socks_port, itemType::integer));
_add(new configItem("log_level", &log_level, itemType::string));
_add(new configItem("mux_protocol", &mux_protocol, itemType::string));
_add(new configItem("mux_concurrency", &mux_concurrency, itemType::integer));
_add(new configItem("mux_padding", &mux_padding, itemType::boolean));
_add(new configItem("mux_default_on", &mux_default_on, itemType::boolean));
_add(new configItem("traffic_loop_interval", &traffic_loop_interval, itemType::integer));
_add(new configItem("test_concurrent", &test_concurrent, itemType::integer));
_add(new configItem("theme", &theme, itemType::string));
_add(new configItem("custom_inbound", &custom_inbound, itemType::string));
_add(new configItem("custom_route", &custom_route_global, itemType::string));
_add(new configItem("sub_use_proxy", &sub_use_proxy, itemType::boolean));
_add(new configItem("remember_id", &remember_id, itemType::integer));
_add(new configItem("remember_enable", &remember_enable, itemType::boolean));
_add(new configItem("language", &language, itemType::integer));
_add(new configItem("spmode2", &remember_spmode, itemType::stringList));
_add(new configItem("skip_cert", &skip_cert, itemType::boolean));
_add(new configItem("hk_mw", &hotkey_mainwindow, itemType::string));
_add(new configItem("hk_group", &hotkey_group, itemType::string));
_add(new configItem("hk_route", &hotkey_route, itemType::string));
_add(new configItem("hk_spmenu", &hotkey_system_proxy_menu, itemType::string));
_add(new configItem("fakedns", &fake_dns, itemType::boolean));
_add(new configItem("active_routing", &active_routing, itemType::string));
_add(new configItem("mw_size", &mw_size, itemType::string));
_add(new configItem("conn_stat", &connection_statistics, itemType::boolean));
_add(new configItem("vpn_impl", &vpn_implementation, itemType::integer));
_add(new configItem("vpn_mtu", &vpn_mtu, itemType::integer));
_add(new configItem("vpn_ipv6", &vpn_ipv6, itemType::boolean));
_add(new configItem("vpn_hide_console", &vpn_hide_console, itemType::boolean));
_add(new configItem("vpn_strict_route", &vpn_strict_route, itemType::boolean));
_add(new configItem("vpn_bypass_process", &vpn_rule_process, itemType::string));
_add(new configItem("vpn_bypass_cidr", &vpn_rule_cidr, itemType::string));
_add(new configItem("vpn_rule_white", &vpn_rule_white, itemType::boolean));
_add(new configItem("check_include_pre", &check_include_pre, itemType::boolean));
_add(new configItem("sp_format", &system_proxy_format, itemType::string));
_add(new configItem("sub_clear", &sub_clear, itemType::boolean));
_add(new configItem("sub_insecure", &sub_insecure, itemType::boolean));
_add(new configItem("sub_auto_update", &sub_auto_update, itemType::integer));
_add(new configItem("log_ignore", &log_ignore, itemType::stringList));
_add(new configItem("start_minimal", &start_minimal, itemType::boolean));
_add(new configItem("max_log_line", &max_log_line, itemType::integer));
_add(new configItem("splitter_state", &splitter_state, itemType::string));
_add(new configItem("utlsFingerprint", &utlsFingerprint, itemType::string));
_add(new configItem("core_box_clash_api", &core_box_clash_api, itemType::integer));
_add(new configItem("core_box_clash_api_secret", &core_box_clash_api_secret, itemType::string));
_add(new configItem("core_box_underlying_dns", &core_box_underlying_dns, itemType::string));
_add(new configItem("vpn_internal_tun", &vpn_internal_tun, itemType::boolean));
}
void DataStore::UpdateStartedId(int id) {
started_id = id;
if (remember_enable) {
remember_id = id;
Save();
} else if (remember_id >= 0) {
remember_id = -1919;
Save();
}
}
QString DataStore::GetUserAgent(bool isDefault) const {
if (user_agent.isEmpty()) {
isDefault = true;
}
if (isDefault) {
QString version = SubStrBefore(NKR_VERSION, "-");
if (!version.contains(".")) version = "2.0";
return "NekoBox/PC/" + version + " (Prefer ClashMeta Format)";
}
return user_agent;
}
// preset routing
Routing::Routing(int preset) : JsonStore() {
if (preset == 1) {
direct_ip =
"geoip:cn\n"
"geoip:private";
direct_domain = "geosite:cn";
proxy_ip = "";
proxy_domain = "";
block_ip = "";
block_domain =
"geosite:category-ads-all\n"
"domain:appcenter.ms\n"
"domain:firebase.io\n"
"domain:crashlytics.com\n";
}
if (!Preset::SingBox::DomainStrategy.contains(domain_strategy)) domain_strategy = "";
if (!Preset::SingBox::DomainStrategy.contains(outbound_domain_strategy)) outbound_domain_strategy = "";
_add(new configItem("direct_ip", &this->direct_ip, itemType::string));
_add(new configItem("direct_domain", &this->direct_domain, itemType::string));
_add(new configItem("proxy_ip", &this->proxy_ip, itemType::string));
_add(new configItem("proxy_domain", &this->proxy_domain, itemType::string));
_add(new configItem("block_ip", &this->block_ip, itemType::string));
_add(new configItem("block_domain", &this->block_domain, itemType::string));
_add(new configItem("def_outbound", &this->def_outbound, itemType::string));
_add(new configItem("custom", &this->custom, itemType::string));
//
_add(new configItem("remote_dns", &this->remote_dns, itemType::string));
_add(new configItem("remote_dns_strategy", &this->remote_dns_strategy, itemType::string));
_add(new configItem("direct_dns", &this->direct_dns, itemType::string));
_add(new configItem("direct_dns_strategy", &this->direct_dns_strategy, itemType::string));
_add(new configItem("domain_strategy", &this->domain_strategy, itemType::string));
_add(new configItem("outbound_domain_strategy", &this->outbound_domain_strategy, itemType::string));
_add(new configItem("dns_routing", &this->dns_routing, itemType::boolean));
_add(new configItem("sniffing_mode", &this->sniffing_mode, itemType::integer));
_add(new configItem("use_dns_object", &this->use_dns_object, itemType::boolean));
_add(new configItem("dns_object", &this->dns_object, itemType::string));
_add(new configItem("dns_final_out", &this->dns_final_out, itemType::string));
}
QString Routing::DisplayRouting() const {
return QString("[Proxy] %1\n[Proxy] %2\n[Direct] %3\n[Direct] %4\n[Block] %5\n[Block] %6\n[Default Outbound] %7\n[DNS] %8")
.arg(SplitLinesSkipSharp(proxy_domain).join(","), 10)
.arg(SplitLinesSkipSharp(proxy_ip).join(","), 10)
.arg(SplitLinesSkipSharp(direct_domain).join(","), 10)
.arg(SplitLinesSkipSharp(direct_ip).join(","), 10)
.arg(SplitLinesSkipSharp(block_domain).join(","), 10)
.arg(SplitLinesSkipSharp(block_ip).join(","), 10)
.arg(def_outbound)
.arg(use_dns_object ? "DNS Object" : "Simple DNS");
}
QStringList Routing::List() {
QDir dr(ROUTES_PREFIX);
return dr.entryList(QDir::Files);
}
bool Routing::SetToActive(const QString &name) {
NekoGui::dataStore->routing = std::make_unique<Routing>();
NekoGui::dataStore->routing->load_control_must = true;
NekoGui::dataStore->routing->fn = ROUTES_PREFIX + name;
auto ok = NekoGui::dataStore->routing->Load();
if (ok) {
NekoGui::dataStore->active_routing = name;
NekoGui::dataStore->Save();
}
return ok;
}
// NO default extra core
ExtraCore::ExtraCore() : JsonStore() {
_add(new configItem("core_map", &this->core_map, itemType::string));
}
QString ExtraCore::Get(const QString &id) const {
auto obj = QString2QJsonObject(core_map);
for (const auto &c: obj.keys()) {
if (c == id) return obj[id].toString();
}
return "";
}
void ExtraCore::Set(const QString &id, const QString &path) {
auto obj = QString2QJsonObject(core_map);
obj[id] = path;
core_map = QJsonObject2QString(obj, true);
}
void ExtraCore::Delete(const QString &id) {
auto obj = QString2QJsonObject(core_map);
obj.remove(id);
core_map = QJsonObject2QString(obj, true);
}
InboundAuthorization::InboundAuthorization() : JsonStore() {
_add(new configItem("user", &this->username, itemType::string));
_add(new configItem("pass", &this->password, itemType::string));
}
bool InboundAuthorization::NeedAuth() const {
return !username.trimmed().isEmpty() && !password.trimmed().isEmpty();
}
// System Utils
QString FindCoreAsset(const QString &name) {
QStringList search{};
search << QApplication::applicationDirPath();
search << "/usr/share/sing-geoip";
search << "/usr/share/sing-geosite";
search << "/usr/share/sing-box";
search << "/usr/lib/nekobox";
search << "/usr/share/nekobox";
for (const auto &dir: search) {
if (dir.isEmpty()) continue;
QFileInfo asset(dir + "/" + name);
if (asset.exists()) {
return asset.absoluteFilePath();
}
}
return {};
}
QString FindNekoBoxCoreRealPath() {
auto fn = QApplication::applicationDirPath() + "/nekobox_core";
auto fi = QFileInfo(fn);
if (fi.isSymLink()) return fi.symLinkTarget();
return fn;
}
short isAdminCache = -1;
// IsAdmin 主要判断:有无权限启动 Tun
bool IsAdmin() {
if (isAdminCache >= 0) return isAdminCache;
bool admin = false;
#ifdef Q_OS_WIN
admin = Windows_IsInAdmin();
#else
#ifdef Q_OS_LINUX
admin |= Linux_GetCapString(FindNekoBoxCoreRealPath()).contains("cap_net_admin");
#endif
admin |= geteuid() == 0;
#endif
isAdminCache = admin;
return admin;
};
} // namespace NekoGui
| 18,599
|
C++
|
.cpp
| 409
| 34.359413
| 131
| 0.572245
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,665
|
HTTPRequestHelper.cpp
|
MatsuriDayo_nekoray/main/HTTPRequestHelper.cpp
|
#include "HTTPRequestHelper.hpp"
#include <QByteArray>
#include <QNetworkProxy>
#include <QEventLoop>
#include <QMetaEnum>
#include <QTimer>
#include "main/NekoGui.hpp"
namespace NekoGui_network {
NekoHTTPResponse NetworkRequestHelper::HttpGet(const QUrl &url) {
QNetworkRequest request;
QNetworkAccessManager accessManager;
request.setUrl(url);
// Set proxy
if (NekoGui::dataStore->sub_use_proxy) {
QNetworkProxy p;
// Note: sing-box mixed socks5 protocol error
p.setType(QNetworkProxy::HttpProxy);
p.setHostName("127.0.0.1");
p.setPort(NekoGui::dataStore->inbound_socks_port);
if (NekoGui::dataStore->inbound_auth->NeedAuth()) {
p.setUser(NekoGui::dataStore->inbound_auth->username);
p.setPassword(NekoGui::dataStore->inbound_auth->password);
}
accessManager.setProxy(p);
if (NekoGui::dataStore->started_id < 0) {
return NekoHTTPResponse{QObject::tr("Request with proxy but no profile started.")};
}
}
if (accessManager.proxy().type() == QNetworkProxy::Socks5Proxy) {
auto cap = accessManager.proxy().capabilities();
accessManager.proxy().setCapabilities(cap | QNetworkProxy::HostNameLookupCapability);
}
// Set attribute
#if (QT_VERSION >= QT_VERSION_CHECK(5, 9, 0))
request.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy);
#endif
request.setHeader(QNetworkRequest::KnownHeaders::UserAgentHeader, NekoGui::dataStore->GetUserAgent());
if (NekoGui::dataStore->sub_insecure) {
QSslConfiguration c;
c.setPeerVerifyMode(QSslSocket::PeerVerifyMode::VerifyNone);
request.setSslConfiguration(c);
}
//
auto _reply = accessManager.get(request);
connect(_reply, &QNetworkReply::sslErrors, _reply, [](const QList<QSslError> &errors) {
QStringList error_str;
for (const auto &err: errors) {
error_str << err.errorString();
}
MW_show_log(QString("SSL Errors: %1 %2").arg(error_str.join(","), NekoGui::dataStore->sub_insecure ? "(Ignored)" : ""));
});
// Wait for response
auto abortTimer = new QTimer;
abortTimer->setSingleShot(true);
abortTimer->setInterval(10000);
QObject::connect(abortTimer, &QTimer::timeout, _reply, &QNetworkReply::abort);
abortTimer->start();
{
QEventLoop loop;
QObject::connect(_reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
loop.exec();
}
if (abortTimer != nullptr) {
abortTimer->stop();
abortTimer->deleteLater();
}
//
auto result = NekoHTTPResponse{_reply->error() == QNetworkReply::NetworkError::NoError ? "" : _reply->errorString(),
_reply->readAll(), _reply->rawHeaderPairs()};
_reply->deleteLater();
return result;
}
QString NetworkRequestHelper::GetHeader(const QList<QPair<QByteArray, QByteArray>> &header, const QString &name) {
for (const auto &p: header) {
if (QString(p.first).toLower() == name.toLower()) return p.second;
}
return "";
}
} // namespace NekoGui_network
| 3,457
|
C++
|
.cpp
| 79
| 33.936709
| 132
| 0.614769
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,666
|
Database.hpp
|
MatsuriDayo_nekoray/db/Database.hpp
|
#pragma once
#include "main/NekoGui.hpp"
#include "ProxyEntity.hpp"
#include "Group.hpp"
namespace NekoGui {
class ProfileManager : private JsonStore {
public:
// JsonStore
// order -> id
QList<int> groupsTabOrder;
// Manager
std::map<int, std::shared_ptr<ProxyEntity>> profiles;
std::map<int, std::shared_ptr<Group>> groups;
ProfileManager();
// LoadManager Reset and loads profiles & groups
void LoadManager();
void SaveManager();
[[nodiscard]] static std::shared_ptr<ProxyEntity> NewProxyEntity(const QString &type);
[[nodiscard]] static std::shared_ptr<Group> NewGroup();
bool AddProfile(const std::shared_ptr<ProxyEntity> &ent, int gid = -1);
void DeleteProfile(int id);
void MoveProfile(const std::shared_ptr<ProxyEntity> &ent, int gid);
std::shared_ptr<ProxyEntity> GetProfile(int id);
bool AddGroup(const std::shared_ptr<Group> &ent);
void DeleteGroup(int gid);
std::shared_ptr<Group> GetGroup(int id);
std::shared_ptr<Group> CurrentGroup();
private:
// sort by id
QList<int> profilesIdOrder;
QList<int> groupsIdOrder;
[[nodiscard]] int NewProfileID() const;
[[nodiscard]] int NewGroupID() const;
static std::shared_ptr<ProxyEntity> LoadProxyEntity(const QString &jsonPath);
static std::shared_ptr<Group> LoadGroup(const QString &jsonPath);
};
extern ProfileManager *profileManager;
} // namespace NekoGui
| 1,574
|
C++
|
.h
| 38
| 33.578947
| 94
| 0.656746
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,667
|
ProxyEntity.hpp
|
MatsuriDayo_nekoray/db/ProxyEntity.hpp
|
#pragma once
#include "main/NekoGui.hpp"
#include "db/traffic/TrafficData.hpp"
#include "fmt/AbstractBean.hpp"
namespace NekoGui_fmt {
class SocksHttpBean;
class ShadowSocksBean;
class VMessBean;
class TrojanVLESSBean;
class NaiveBean;
class QUICBean;
class CustomBean;
class ChainBean;
}; // namespace NekoGui_fmt
namespace NekoGui {
class ProxyEntity : public JsonStore {
public:
QString type;
int id = -1;
int gid = 0;
int latency = 0;
std::shared_ptr<NekoGui_fmt::AbstractBean> bean;
std::shared_ptr<NekoGui_traffic::TrafficData> traffic_data = std::make_shared<NekoGui_traffic::TrafficData>("");
QString full_test_report;
ProxyEntity(NekoGui_fmt::AbstractBean *bean, const QString &type_);
[[nodiscard]] QString DisplayLatency() const;
[[nodiscard]] QColor DisplayLatencyColor() const;
[[nodiscard]] NekoGui_fmt::ChainBean *ChainBean() const {
return (NekoGui_fmt::ChainBean *) bean.get();
};
[[nodiscard]] NekoGui_fmt::SocksHttpBean *SocksHTTPBean() const {
return (NekoGui_fmt::SocksHttpBean *) bean.get();
};
[[nodiscard]] NekoGui_fmt::ShadowSocksBean *ShadowSocksBean() const {
return (NekoGui_fmt::ShadowSocksBean *) bean.get();
};
[[nodiscard]] NekoGui_fmt::VMessBean *VMessBean() const {
return (NekoGui_fmt::VMessBean *) bean.get();
};
[[nodiscard]] NekoGui_fmt::TrojanVLESSBean *TrojanVLESSBean() const {
return (NekoGui_fmt::TrojanVLESSBean *) bean.get();
};
[[nodiscard]] NekoGui_fmt::NaiveBean *NaiveBean() const {
return (NekoGui_fmt::NaiveBean *) bean.get();
};
[[nodiscard]] NekoGui_fmt::QUICBean *QUICBean() const {
return (NekoGui_fmt::QUICBean *) bean.get();
};
[[nodiscard]] NekoGui_fmt::CustomBean *CustomBean() const {
return (NekoGui_fmt::CustomBean *) bean.get();
};
};
} // namespace NekoGui
| 2,092
|
C++
|
.h
| 53
| 31.471698
| 120
| 0.628968
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,668
|
ProfileFilter.hpp
|
MatsuriDayo_nekoray/db/ProfileFilter.hpp
|
#pragma once
#include "ProxyEntity.hpp"
namespace NekoGui {
class ProfileFilter {
public:
static void Uniq(
const QList<std::shared_ptr<ProxyEntity>> &in,
QList<std::shared_ptr<ProxyEntity>> &out,
bool by_address = false, // def by bean
bool keep_last = false // def keep first
);
static void Common(
const QList<std::shared_ptr<ProxyEntity>> &src,
const QList<std::shared_ptr<ProxyEntity>> &dst,
QList<std::shared_ptr<ProxyEntity>> &outSrc,
QList<std::shared_ptr<ProxyEntity>> &outDst,
bool by_address = false // def by bean
);
static void OnlyInSrc(
const QList<std::shared_ptr<ProxyEntity>> &src,
const QList<std::shared_ptr<ProxyEntity>> &dst,
QList<std::shared_ptr<ProxyEntity>> &out,
bool by_address = false // def by bean
);
static void OnlyInSrc_ByPointer(
const QList<std::shared_ptr<ProxyEntity>> &src,
const QList<std::shared_ptr<ProxyEntity>> &dst,
QList<std::shared_ptr<ProxyEntity>> &out);
};
} // namespace NekoGui
| 1,197
|
C++
|
.h
| 30
| 30.066667
| 59
| 0.590361
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,669
|
Group.hpp
|
MatsuriDayo_nekoray/db/Group.hpp
|
#pragma once
#include "main/NekoGui.hpp"
#include "ProxyEntity.hpp"
namespace NekoGui {
class Group : public JsonStore {
public:
int id = -1;
bool archive = false;
bool skip_auto_update = false;
QString name = "";
QString url = "";
QString info = "";
qint64 sub_last_update = 0;
int front_proxy_id = -1;
// list ui
bool manually_column_width = false;
QList<int> column_width;
QList<int> order;
Group();
// 按 id 顺序
[[nodiscard]] QList<std::shared_ptr<ProxyEntity>> Profiles() const;
// 按 显示 顺序
[[nodiscard]] QList<std::shared_ptr<ProxyEntity>> ProfilesWithOrder() const;
};
} // namespace NekoGui
| 766
|
C++
|
.h
| 25
| 22.84
| 84
| 0.581363
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,670
|
ConfigBuilder.hpp
|
MatsuriDayo_nekoray/db/ConfigBuilder.hpp
|
#pragma once
#include "ProxyEntity.hpp"
#include "sys/ExternalProcess.hpp"
namespace NekoGui {
class BuildConfigResult {
public:
QString error;
QJsonObject coreConfig;
QList<std::shared_ptr<NekoGui_traffic::TrafficData>> outboundStats; // all, but not including "bypass" "block"
std::shared_ptr<NekoGui_traffic::TrafficData> outboundStat; // main
QStringList ignoreConnTag;
std::list<std::shared_ptr<NekoGui_fmt::ExternalBuildResult>> extRs;
};
class BuildConfigStatus {
public:
std::shared_ptr<BuildConfigResult> result;
std::shared_ptr<ProxyEntity> ent;
bool forTest;
bool forExport;
// priv
QList<int> globalProfiles;
// xxList is V2Ray format string list
QStringList domainListDNSRemote;
QStringList domainListDNSDirect;
QStringList domainListRemote;
QStringList domainListDirect;
QStringList ipListRemote;
QStringList ipListDirect;
QStringList domainListBlock;
QStringList ipListBlock;
// config format
QJsonArray routingRules;
QJsonArray inbounds;
QJsonArray outbounds;
};
std::shared_ptr<BuildConfigResult> BuildConfig(const std::shared_ptr<ProxyEntity> &ent, bool forTest, bool forExport);
void BuildConfigSingBox(const std::shared_ptr<BuildConfigStatus> &status);
QString BuildChain(int chainId, const std::shared_ptr<BuildConfigStatus> &status);
QString BuildChainInternal(int chainId, const QList<std::shared_ptr<ProxyEntity>> &ents,
const std::shared_ptr<BuildConfigStatus> &status);
QString WriteVPNSingBoxConfig();
QString WriteVPNLinuxScript(const QString &configPath);
} // namespace NekoGui
| 1,811
|
C++
|
.h
| 43
| 34.255814
| 122
| 0.699201
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,671
|
TrafficData.hpp
|
MatsuriDayo_nekoray/db/traffic/TrafficData.hpp
|
#pragma once
#include "main/NekoGui.hpp"
namespace NekoGui_traffic {
class TrafficData : public JsonStore {
public:
int id = -1; // ent id
std::string tag;
long long downlink = 0;
long long uplink = 0;
long long downlink_rate = 0;
long long uplink_rate = 0;
long long last_update;
explicit TrafficData(std::string tag) {
this->tag = std::move(tag);
_add(new configItem("dl", &downlink, itemType::integer64));
_add(new configItem("ul", &uplink, itemType::integer64));
};
void Reset() {
downlink = 0;
uplink = 0;
downlink_rate = 0;
uplink_rate = 0;
}
[[nodiscard]] QString DisplaySpeed() const {
return UNICODE_LRO + QString("%1↑ %2↓").arg(ReadableSize(uplink_rate), ReadableSize(downlink_rate));
}
[[nodiscard]] QString DisplayTraffic() const {
if (downlink + uplink == 0) return "";
return UNICODE_LRO + QString("%1↑ %2↓").arg(ReadableSize(uplink), ReadableSize(downlink));
}
};
} // namespace NekoGui_traffic
| 1,178
|
C++
|
.h
| 32
| 27.4375
| 112
| 0.565487
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,672
|
TrafficLooper.hpp
|
MatsuriDayo_nekoray/db/traffic/TrafficLooper.hpp
|
#pragma once
#include <QString>
#include <QList>
#include <QMutex>
#include "TrafficData.hpp"
namespace NekoGui_traffic {
class TrafficLooper {
public:
bool loop_enabled = false;
bool looping = false;
QMutex loop_mutex;
QList<std::shared_ptr<TrafficData>> items;
TrafficData *proxy = nullptr;
void UpdateAll();
void Loop();
private:
TrafficData *bypass = new TrafficData("bypass");
[[nodiscard]] static TrafficData *update_stats(TrafficData *item);
[[nodiscard]] static QJsonArray get_connection_list();
};
extern TrafficLooper *trafficLooper;
} // namespace NekoGui_traffic
| 685
|
C++
|
.h
| 22
| 25.136364
| 74
| 0.67075
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,673
|
WinCommander.hpp
|
MatsuriDayo_nekoray/3rdparty/WinCommander.hpp
|
/****************************************************************************
**
** Copyright (C) 2014 UpdateNode UG (haftungsbeschr√§nkt)
** Contact: code@updatenode.com
**
** This file is part of the UpdateNode Client.
**
** Commercial License Usage
** Licensees holding valid commercial UpdateNode license may use this file
** under the terms of the the Apache License, Version 2.0
** Full license description file: LICENSE.COM
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation. Please review the following information to ensure the
** GNU General Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
** Full license description file: LICENSE.GPL
**
****************************************************************************/
#ifndef WINCOMMANDER_H
#define WINCOMMANDER_H
#include <QString>
#include <QStringList>
class WinCommander {
public:
static const int SW_HIDE = 0;
static const int SW_NORMAL = 1;
static const int SW_SHOWMINIMIZED = 2;
static uint runProcessElevated(const QString &path,
const QStringList ¶meters = QStringList(),
const QString &workingDir = QString(),
int nShow = SW_SHOWMINIMIZED, bool aWait = true);
};
#endif // WINCOMMANDER_H
| 1,473
|
C++
|
.h
| 36
| 36.444444
| 84
| 0.631542
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,674
|
fix_old_qt.h
|
MatsuriDayo_nekoray/3rdparty/fix_old_qt.h
|
#pragma once
#include <QString>
#if QT_VERSION < QT_VERSION_CHECK(5, 10, 0)
inline QString qEnvironmentVariable(const char *varName) {
return qgetenv(varName);
}
#endif
| 177
|
C++
|
.h
| 7
| 23.142857
| 58
| 0.76506
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,675
|
RunGuard.hpp
|
MatsuriDayo_nekoray/3rdparty/RunGuard.hpp
|
#ifndef RUNGUARD_H
#define RUNGUARD_H
#include <QObject>
#include <QSharedMemory>
#include <QSystemSemaphore>
#include <QCryptographicHash>
class RunGuard {
public:
RunGuard(const QString &key);
~RunGuard();
bool isAnotherRunning(quint64 *data_out);
bool tryToRun(quint64 *data_in);
void release();
private:
const QString key;
const QString memLockKey;
const QString sharedmemKey;
QSharedMemory sharedMem;
QSystemSemaphore memLock;
Q_DISABLE_COPY(RunGuard)
};
namespace {
QString generateKeyHash(const QString &key, const QString &salt) {
QByteArray data;
data.append(key.toUtf8());
data.append(salt.toUtf8());
data = QCryptographicHash::hash(data, QCryptographicHash::Sha1).toHex();
return data;
}
} // namespace
RunGuard::RunGuard(const QString &key)
: key(key), memLockKey(generateKeyHash(key, "_memLockKey")), sharedmemKey(generateKeyHash(key, "_sharedmemKey")), sharedMem(sharedmemKey), memLock(memLockKey, 1) {
memLock.acquire();
{
QSharedMemory fix(sharedmemKey); // Fix for *nix: http://habrahabr.ru/post/173281/
fix.attach();
}
memLock.release();
}
RunGuard::~RunGuard() {
release();
}
bool RunGuard::isAnotherRunning(quint64 *data_out) {
if (sharedMem.isAttached())
return false;
memLock.acquire();
const bool isRunning = sharedMem.attach();
if (isRunning) {
if (data_out != nullptr) {
memcpy(data_out, sharedMem.data(), sizeof(quint64));
}
sharedMem.detach();
}
memLock.release();
return isRunning;
}
bool RunGuard::tryToRun(quint64 *data_in) {
memLock.acquire();
const bool result = sharedMem.create(sizeof(quint64));
if (result) memcpy(sharedMem.data(), data_in, sizeof(quint64));
memLock.release();
if (!result) {
release();
return false;
}
return true;
}
void RunGuard::release() {
memLock.acquire();
if (sharedMem.isAttached())
sharedMem.detach();
memLock.release();
}
#endif // RUNGUARD_H
| 2,098
|
C++
|
.h
| 74
| 23.405405
| 167
| 0.674
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
10,677
|
QThreadCreateThread.hpp
|
MatsuriDayo_nekoray/3rdparty/QThreadCreateThread.hpp
|
#pragma once
#include <future>
#include <QThread>
// FOR OLD QT
class QThreadCreateThread : public QThread {
public:
explicit QThreadCreateThread(std::future<void> &&future)
: m_future(std::move(future)) {
// deleteLater
connect(this, &QThread::finished, this, &QThread::deleteLater);
}
private:
void run() override {
m_future.get();
}
std::future<void> m_future;
};
inline QThread *createThreadImpl(std::future<void> &&future) {
return new QThreadCreateThread(std::move(future));
}
template<typename Function, typename... Args>
QThread *createQThread(Function &&f, Args &&... args) {
using DecayedFunction = typename std::decay<Function>::type;
auto threadFunction =
[f = static_cast<DecayedFunction>(std::forward<Function>(f))](auto &&... largs) mutable -> void {
(void) std::invoke(std::move(f), std::forward<decltype(largs)>(largs)...);
};
return createThreadImpl(std::async(std::launch::deferred,
std::move(threadFunction),
std::forward<Args>(args)...));
}
| 1,160
|
C++
|
.h
| 31
| 30.032258
| 109
| 0.618198
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,679
|
base64.h
|
MatsuriDayo_nekoray/3rdparty/base64.h
|
#include <QByteArray>
namespace Qt515Base64 {
enum Base64Option {
Base64Encoding = 0,
Base64UrlEncoding = 1,
KeepTrailingEquals = 0,
OmitTrailingEquals = 2,
IgnoreBase64DecodingErrors = 0,
AbortOnBase64DecodingErrors = 4,
};
Q_DECLARE_FLAGS(Base64Options, Base64Option)
Q_DECLARE_OPERATORS_FOR_FLAGS(Base64Options)
enum class Base64DecodingStatus {
Ok,
IllegalInputLength,
IllegalCharacter,
IllegalPadding,
};
class FromBase64Result {
public:
QByteArray decoded;
Base64DecodingStatus decodingStatus;
void swap(FromBase64Result &other) noexcept {
qSwap(decoded, other.decoded);
qSwap(decodingStatus, other.decodingStatus);
}
explicit operator bool() const noexcept { return decodingStatus == Base64DecodingStatus::Ok; }
#if defined(Q_COMPILER_REF_QUALIFIERS) && !defined(Q_QDOC)
QByteArray &operator*() &noexcept { return decoded; }
const QByteArray &operator*() const &noexcept { return decoded; }
QByteArray &&operator*() &&noexcept { return std::move(decoded); }
#else
QByteArray &operator*() noexcept { return decoded; }
const QByteArray &operator*() const noexcept { return decoded; }
#endif
};
FromBase64Result QByteArray_fromBase64Encoding(const QByteArray &base64, Base64Options options);
} // namespace Qt515Base64
| 1,456
|
C++
|
.h
| 38
| 31.184211
| 102
| 0.684883
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,680
|
VT100Parser.hpp
|
MatsuriDayo_nekoray/3rdparty/VT100Parser.hpp
|
#pragma once
#include <QString>
inline QString cleanVT100String(const QString &in) {
QString out;
bool in_033 = false;
for (auto &&chr: in) {
if (chr == '\033') {
in_033 = true;
continue;
}
if (in_033) {
if (chr == 'm') {
in_033 = false;
}
continue;
}
out += chr;
}
return out;
}
| 418
|
C++
|
.h
| 20
| 13
| 52
| 0.439394
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,682
|
QtExtKeySequenceEdit.h
|
MatsuriDayo_nekoray/3rdparty/QtExtKeySequenceEdit.h
|
#include <QKeySequenceEdit>
class QtExtKeySequenceEdit : public QKeySequenceEdit {
public:
QtExtKeySequenceEdit(QWidget *parent);
~QtExtKeySequenceEdit();
protected:
virtual void keyPressEvent(QKeyEvent *pEvent);
};
| 231
|
C++
|
.h
| 8
| 26
| 54
| 0.804545
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,683
|
wrapper.hpp
|
MatsuriDayo_nekoray/3rdparty/qv2ray/wrapper.hpp
|
#pragma once
// Qv2ray wrapper
#include <QJsonDocument>
#include <QDebug>
#define LOG(...) Qv2ray::base::log_internal(__VA_ARGS__)
#define DEBUG(...) Qv2ray::base::log_internal(__VA_ARGS__)
namespace Qv2ray {
namespace base {
template<typename... T>
inline void log_internal(T... v) {}
} // namespace base
} // namespace Qv2ray
#define JsonToString(a) QJsonObject2QString(a, false)
#define JsonFromString(a) QString2QJsonObject(a)
#define QvMessageBoxWarn(a, b, c) MessageBoxWarning(b, c)
inline QString VerifyJsonString(const QString &source) {
QJsonParseError error{};
QJsonDocument doc = QJsonDocument::fromJson(source.toUtf8(), &error);
Q_UNUSED(doc)
if (error.error == QJsonParseError::NoError) {
return "";
} else {
// LOG("WARNING: Json parse returns: " + error.errorString());
return error.errorString();
}
}
#define RED(obj) \
{ \
auto _temp = obj->palette(); \
_temp.setColor(QPalette::Text, Qt::red); \
obj->setPalette(_temp); \
}
#define BLACK(obj) obj->setPalette(QWidget::palette());
| 1,214
|
C++
|
.h
| 33
| 32.393939
| 73
| 0.606138
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,684
|
QvProxyConfigurator.hpp
|
MatsuriDayo_nekoray/3rdparty/qv2ray/v2/components/proxy/QvProxyConfigurator.hpp
|
#pragma once
#include <QHostAddress>
#include <QObject>
#include <QString>
//
namespace Qv2ray::components::proxy {
void ClearSystemProxy();
void SetSystemProxy(int http_port, int socks_port);
} // namespace Qv2ray::components::proxy
using namespace Qv2ray::components;
using namespace Qv2ray::components::proxy;
| 322
|
C++
|
.h
| 11
| 27.454545
| 55
| 0.783871
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
10,685
|
QvAutoCompleteTextEdit.hpp
|
MatsuriDayo_nekoray/3rdparty/qv2ray/v2/ui/QvAutoCompleteTextEdit.hpp
|
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of The Qt Company Ltd nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#pragma once
#include <QAbstractItemModel>
#include <QPlainTextEdit>
QT_BEGIN_NAMESPACE
class QCompleter;
QT_END_NAMESPACE
namespace Qv2ray {
namespace ui {
namespace widgets {
class AutoCompleteTextEdit : public QPlainTextEdit {
Q_OBJECT
public:
AutoCompleteTextEdit(const QString &prefix, const QStringList &sourceStrings, QWidget *parent = nullptr);
~AutoCompleteTextEdit();
protected:
void keyPressEvent(QKeyEvent *e) override;
void focusInEvent(QFocusEvent *e) override;
private slots:
void insertCompletion(const QString &completion);
private:
QString lineUnderCursor() const;
QString wordUnderCursor() const;
QString prefix;
QCompleter *c = nullptr;
};
} // namespace widgets
} // namespace ui
} // namespace Qv2ray
using namespace Qv2ray::ui::widgets;
| 3,481
|
C++
|
.h
| 78
| 40.25641
| 121
| 0.687574
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,686
|
w_JsonEditor.hpp
|
MatsuriDayo_nekoray/3rdparty/qv2ray/v2/ui/widgets/editors/w_JsonEditor.hpp
|
#pragma once
#include "3rdparty/qv2ray/wrapper.hpp"
#include "3rdparty/qv2ray/v2/ui/widgets/common/QJsonModel.hpp"
#include "ui_w_JsonEditor.h"
#include <QDialog>
class JsonEditor
: public QDialog,
private Ui::JsonEditor {
Q_OBJECT
public:
explicit JsonEditor(const QJsonObject& rootObject, QWidget* parent = nullptr);
~JsonEditor();
QJsonObject OpenEditor();
private slots:
void on_jsonEditor_textChanged();
void on_formatJsonBtn_clicked();
void on_removeCommentsBtn_clicked();
private:
QJsonModel model;
QJsonObject original;
QJsonObject final;
};
| 608
|
C++
|
.h
| 22
| 24
| 82
| 0.750865
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,687
|
GeositeReader.hpp
|
MatsuriDayo_nekoray/3rdparty/qv2ray/v3/components/GeositeReader/GeositeReader.hpp
|
#pragma once
#include <QString>
namespace Qv2ray::components::GeositeReader {
QStringList ReadGeoSiteFromFile(const QString &filepath, bool allowCache = true);
} // namespace Qv2ray::components::GeositeReader
| 215
|
C++
|
.h
| 5
| 40.8
| 85
| 0.807692
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
10,689
|
GroupUpdater.hpp
|
MatsuriDayo_nekoray/sub/GroupUpdater.hpp
|
#pragma once
#include "db/Database.hpp"
namespace NekoGui_sub {
class RawUpdater {
public:
void updateClash(const QString &str);
void update(const QString &str);
int gid_add_to = -1; // 导入到指定组 -1 为当前选中组
QList<std::shared_ptr<NekoGui::ProxyEntity>> updated_order; // 新增的配置,按照导入时处理的先后排序
};
class GroupUpdater : public QObject {
Q_OBJECT
public:
void AsyncUpdate(const QString &str, int _sub_gid = -1, const std::function<void()> &finish = nullptr);
void Update(const QString &_str, int _sub_gid = -1, bool _not_sub_as_url = false);
signals:
void asyncUpdateCallback(int gid);
};
extern GroupUpdater *groupUpdater;
} // namespace NekoGui_sub
// 更新所有订阅 关闭分组窗口时 更新动作继续执行
void UI_update_all_groups(bool onlyAllowed = false);
| 929
|
C++
|
.h
| 22
| 31.681818
| 111
| 0.67087
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,690
|
dialog_manage_routes.h
|
MatsuriDayo_nekoray/ui/dialog_manage_routes.h
|
#pragma once
#include <QDialog>
#include <QMenu>
#include "3rdparty/qv2ray/v2/ui/QvAutoCompleteTextEdit.hpp"
#include "main/NekoGui.hpp"
QT_BEGIN_NAMESPACE
namespace Ui {
class DialogManageRoutes;
}
QT_END_NAMESPACE
class DialogManageRoutes : public QDialog {
Q_OBJECT
public:
explicit DialogManageRoutes(QWidget *parent = nullptr);
~DialogManageRoutes() override;
private:
Ui::DialogManageRoutes *ui;
struct {
QString custom_route;
QString custom_route_global;
} CACHE;
QMenu *builtInSchemesMenu;
Qv2ray::ui::widgets::AutoCompleteTextEdit *directDomainTxt;
Qv2ray::ui::widgets::AutoCompleteTextEdit *proxyDomainTxt;
Qv2ray::ui::widgets::AutoCompleteTextEdit *blockDomainTxt;
//
Qv2ray::ui::widgets::AutoCompleteTextEdit *directIPTxt;
Qv2ray::ui::widgets::AutoCompleteTextEdit *blockIPTxt;
Qv2ray::ui::widgets::AutoCompleteTextEdit *proxyIPTxt;
//
NekoGui::Routing routing_cn_lan = NekoGui::Routing(1);
NekoGui::Routing routing_global = NekoGui::Routing(0);
//
QString title_base;
QString active_routing;
public slots:
void accept() override;
QList<QAction *> getBuiltInSchemes();
QAction *schemeToAction(const QString &name, const NekoGui::Routing &scheme);
void UpdateDisplayRouting(NekoGui::Routing *conf, bool qv);
void SaveDisplayRouting(NekoGui::Routing *conf);
void on_load_save_clicked();
};
| 1,440
|
C++
|
.h
| 43
| 29.232558
| 81
| 0.745112
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,691
|
dialog_vpn_settings.h
|
MatsuriDayo_nekoray/ui/dialog_vpn_settings.h
|
#ifndef NEKORAY_DIALOG_VPN_SETTINGS_H
#define NEKORAY_DIALOG_VPN_SETTINGS_H
#include <QDialog>
QT_BEGIN_NAMESPACE
namespace Ui {
class DialogVPNSettings;
}
QT_END_NAMESPACE
class DialogVPNSettings : public QDialog {
Q_OBJECT
public:
explicit DialogVPNSettings(QWidget *parent = nullptr);
~DialogVPNSettings() override;
private:
Ui::DialogVPNSettings *ui;
public slots:
void accept() override;
void on_troubleshooting_clicked();
};
#endif // NEKORAY_DIALOG_VPN_SETTINGS_H
| 509
|
C++
|
.h
| 20
| 22.55
| 58
| 0.776618
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,693
|
dialog_manage_groups.h
|
MatsuriDayo_nekoray/ui/dialog_manage_groups.h
|
#pragma once
#include <QWidget>
#include <QDialog>
#include <QMenu>
#include <QTableWidgetItem>
#include "db/Group.hpp"
QT_BEGIN_NAMESPACE
namespace Ui {
class DialogManageGroups;
}
QT_END_NAMESPACE
class DialogManageGroups : public QDialog {
Q_OBJECT
public:
explicit DialogManageGroups(QWidget *parent = nullptr);
~DialogManageGroups() override;
private:
Ui::DialogManageGroups *ui;
private slots:
void on_add_clicked();
void on_update_all_clicked();
};
| 494
|
C++
|
.h
| 22
| 19.727273
| 59
| 0.766234
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,694
|
mainwindow.h
|
MatsuriDayo_nekoray/ui/mainwindow.h
|
#pragma once
#include <QMainWindow>
#include "main/NekoGui.hpp"
#ifndef MW_INTERFACE
#include <QTime>
#include <QTableWidgetItem>
#include <QKeyEvent>
#include <QSystemTrayIcon>
#include <QProcess>
#include <QTextDocument>
#include <QShortcut>
#include <QSemaphore>
#include <QMutex>
#include "GroupSort.hpp"
#include "db/ProxyEntity.hpp"
#include "main/GuiUtils.hpp"
#endif
namespace NekoGui_sys {
class CoreProcess;
}
QT_BEGIN_NAMESPACE
namespace Ui {
class MainWindow;
}
QT_END_NAMESPACE
class MainWindow : public QMainWindow {
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow() override;
void refresh_proxy_list(const int &id = -1);
void show_group(int gid);
void refresh_groups();
void refresh_status(const QString &traffic_update = "");
void neko_start(int _id = -1);
void neko_stop(bool crash = false, bool sem = false);
void neko_set_spmode_system_proxy(bool enable, bool save = true);
void neko_set_spmode_vpn(bool enable, bool save = true);
void show_log_impl(const QString &log);
void start_select_mode(QObject *context, const std::function<void(int)> &callback);
void refresh_connection_list(const QJsonArray &arr);
void RegisterHotkey(bool unregister);
bool StopVPNProcess(bool unconditional = false);
signals:
void profile_selected(int id);
public slots:
void on_commitDataRequest();
void on_menu_exit_triggered();
#ifndef MW_INTERFACE
private slots:
void on_masterLogBrowser_customContextMenuRequested(const QPoint &pos);
void on_menu_basic_settings_triggered();
void on_menu_routing_settings_triggered();
void on_menu_vpn_settings_triggered();
void on_menu_hotkey_settings_triggered();
void on_menu_add_from_input_triggered();
void on_menu_add_from_clipboard_triggered();
void on_menu_clone_triggered();
void on_menu_move_triggered();
void on_menu_delete_triggered();
void on_menu_reset_traffic_triggered();
void on_menu_profile_debug_info_triggered();
void on_menu_copy_links_triggered();
void on_menu_copy_links_nkr_triggered();
void on_menu_export_config_triggered();
void display_qr_link(bool nkrFormat = false);
void on_menu_scan_qr_triggered();
void on_menu_clear_test_result_triggered();
void on_menu_manage_groups_triggered();
void on_menu_select_all_triggered();
void on_menu_delete_repeat_triggered();
void on_menu_remove_unavailable_triggered();
void on_menu_update_subscription_triggered();
void on_menu_resolve_domain_triggered();
void on_proxyListTable_itemDoubleClicked(QTableWidgetItem *item);
void on_proxyListTable_customContextMenuRequested(const QPoint &pos);
void on_tabWidget_currentChanged(int index);
private:
Ui::MainWindow *ui;
QSystemTrayIcon *tray;
QShortcut *shortcut_ctrl_f = new QShortcut(QKeySequence("Ctrl+F"), this);
QShortcut *shortcut_esc = new QShortcut(QKeySequence("Esc"), this);
//
NekoGui_sys::CoreProcess *core_process;
qint64 vpn_pid = 0;
//
bool qvLogAutoScoll = true;
QTextDocument *qvLogDocument = new QTextDocument(this);
//
QString title_error;
int icon_status = -1;
std::shared_ptr<NekoGui::ProxyEntity> running;
QString traffic_update_cache;
QTime last_test_time;
//
int proxy_last_order = -1;
bool select_mode = false;
QMutex mu_starting;
QMutex mu_stopping;
QMutex mu_exit;
QSemaphore sem_stopped;
int exit_reason = 0;
QList<std::shared_ptr<NekoGui::ProxyEntity>> get_now_selected_list();
QList<std::shared_ptr<NekoGui::ProxyEntity>> get_selected_or_group();
void dialog_message_impl(const QString &sender, const QString &info);
void refresh_proxy_list_impl(const int &id = -1, GroupSortAction groupSortAction = {});
void refresh_proxy_list_impl_refresh_data(const int &id = -1);
void keyPressEvent(QKeyEvent *event) override;
void closeEvent(QCloseEvent *event) override;
//
void HotkeyEvent(const QString &key);
bool StartVPNProcess();
// grpc and ...
static void setup_grpc();
void speedtest_current_group(int mode, bool test_group);
void speedtest_current();
static void stop_core_daemon();
void CheckUpdate();
protected:
bool eventFilter(QObject *obj, QEvent *event) override;
#endif // MW_INTERFACE
};
inline MainWindow *GetMainWindow() {
return (MainWindow *) mainwindow;
}
void UI_InitMainWindow();
| 4,543
|
C++
|
.h
| 126
| 31.563492
| 91
| 0.726078
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,695
|
dialog_basic_settings.h
|
MatsuriDayo_nekoray/ui/dialog_basic_settings.h
|
#ifndef DIALOG_BASIC_SETTINGS_H
#define DIALOG_BASIC_SETTINGS_H
#include <QDialog>
#include <QJsonObject>
namespace Ui {
class DialogBasicSettings;
}
class DialogBasicSettings : public QDialog {
Q_OBJECT
public:
explicit DialogBasicSettings(QWidget *parent = nullptr);
~DialogBasicSettings();
public slots:
void accept();
private:
Ui::DialogBasicSettings *ui;
struct {
QJsonObject extraCore;
QString custom_inbound;
bool needRestart = false;
} CACHE;
private slots:
void refresh_auth();
void on_set_custom_icon_clicked();
void on_inbound_auth_clicked();
void on_core_settings_clicked();
};
#endif // DIALOG_BASIC_SETTINGS_H
| 711
|
C++
|
.h
| 28
| 21.285714
| 60
| 0.724551
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,696
|
ThemeManager.hpp
|
MatsuriDayo_nekoray/ui/ThemeManager.hpp
|
#pragma once
class ThemeManager {
public:
QString system_style_name = "";
QString current_theme = "0"; // int: 0:system 1+:builtin string: QStyleFactory
void ApplyTheme(const QString &theme);
};
extern ThemeManager *themeManager;
| 245
|
C++
|
.h
| 8
| 27.75
| 82
| 0.739316
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,697
|
Icon.hpp
|
MatsuriDayo_nekoray/ui/Icon.hpp
|
#pragma once
#include <QPixmap>
namespace Icon {
enum TrayIconStatus {
NONE,
RUNNING,
SYSTEM_PROXY,
VPN,
};
QPixmap GetTrayIcon(TrayIconStatus status);
QPixmap GetMaterialIcon(const QString &name);
} // namespace Icon
| 272
|
C++
|
.h
| 12
| 17.166667
| 49
| 0.665354
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,698
|
GroupSort.hpp
|
MatsuriDayo_nekoray/ui/GroupSort.hpp
|
#pragma once
// implement in mainwindow
namespace GroupSortMethod {
enum GroupSortMethod {
Raw,
ByType,
ByAddress,
ByName,
ByLatency,
ById,
};
}
struct GroupSortAction {
GroupSortMethod::GroupSortMethod method = GroupSortMethod::Raw;
bool save_sort = false; // 保存到文件
bool descending = false; // 默认升序,开这个就是降序
bool scroll_to_started = false;
};
| 452
|
C++
|
.h
| 18
| 18.111111
| 67
| 0.658291
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,699
|
ProxyItem.h
|
MatsuriDayo_nekoray/ui/widget/ProxyItem.h
|
#pragma once
#include <QWidget>
#include <QListWidgetItem>
#include "db/ProxyEntity.hpp"
QT_BEGIN_NAMESPACE
namespace Ui {
class ProxyItem;
}
QT_END_NAMESPACE
class QPushButton;
class ProxyItem : public QWidget {
Q_OBJECT
public:
explicit ProxyItem(QWidget *parent, const std::shared_ptr<NekoGui::ProxyEntity> &ent, QListWidgetItem *item);
~ProxyItem() override;
void refresh_data();
QPushButton *get_change_button();
std::shared_ptr<NekoGui::ProxyEntity> ent;
QListWidgetItem *item;
bool remove_confirm = false;
private:
Ui::ProxyItem *ui;
private slots:
void on_remove_clicked();
};
| 642
|
C++
|
.h
| 25
| 22.4
| 113
| 0.745033
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,700
|
GroupItem.h
|
MatsuriDayo_nekoray/ui/widget/GroupItem.h
|
#pragma once
#include <QWidget>
#include <QListWidgetItem>
#include "db/Database.hpp"
QT_BEGIN_NAMESPACE
namespace Ui {
class GroupItem;
}
QT_END_NAMESPACE
class GroupItem : public QWidget {
Q_OBJECT
public:
explicit GroupItem(QWidget *parent, const std::shared_ptr<NekoGui::Group> &ent, QListWidgetItem *item);
~GroupItem() override;
void refresh_data();
std::shared_ptr<NekoGui::Group> ent;
QListWidgetItem *item;
private:
Ui::GroupItem *ui;
QWidget *parentWindow;
signals:
void edit_clicked();
private slots:
void on_update_sub_clicked();
void on_edit_clicked();
void on_remove_clicked();
};
| 663
|
C++
|
.h
| 27
| 21.037037
| 107
| 0.727419
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,701
|
MessageBoxTimer.h
|
MatsuriDayo_nekoray/ui/widget/MessageBoxTimer.h
|
#pragma once
#include <QMessageBox>
#include <QTimer>
class MessageBoxTimer : public QTimer {
public:
QMessageBox *msgbox = nullptr;
bool showed = false;
explicit MessageBoxTimer(QObject *parent, QMessageBox *msgbox, int delayMs) : QTimer(parent) {
connect(this, &QTimer::timeout, this, &MessageBoxTimer::timeoutFunc, Qt::ConnectionType::QueuedConnection);
this->msgbox = msgbox;
setSingleShot(true);
setInterval(delayMs);
start();
};
void cancel() {
QTimer::stop();
if (msgbox != nullptr && showed) {
msgbox->reject(); // return the timeoutFunc
}
};
private:
void timeoutFunc() {
if (msgbox == nullptr) return;
showed = true;
msgbox->exec();
msgbox = nullptr;
}
};
| 811
|
C++
|
.h
| 28
| 22.785714
| 115
| 0.622108
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,702
|
MyTableWidget.h
|
MatsuriDayo_nekoray/ui/widget/MyTableWidget.h
|
#pragma once
#include <QWidget>
#include <QTableWidget>
#include <QDropEvent>
#include <QDebug>
#include <functional>
#include <utility>
class MyTableWidget : public QTableWidget {
public:
explicit MyTableWidget(QWidget *parent = nullptr) : QTableWidget(parent) {
// 拖拽设置
this->setDragDropMode(QAbstractItemView::InternalMove); // 内部移动
this->setDropIndicatorShown(true); // drop位置 提示
this->setSelectionBehavior(QAbstractItemView::SelectRows);
};
QList<int> order; // id sorted (save)
std::map<int, int> id2Row; // id2Row
QList<int> row2Id; // row2Id: use this to refresh data
std::function<void()> callback_save_order;
std::function<void(int id)> refresh_data;
void _save_order(bool saveToFile) {
order.clear();
id2Row.clear();
for (int i = 0; i < this->rowCount(); i++) {
auto id = row2Id[i];
order += id;
id2Row[id] = i;
}
if (callback_save_order != nullptr && saveToFile)
callback_save_order();
}
void update_order(bool saveToFile) {
if (order.isEmpty()) {
_save_order(false);
return;
}
// 纠错: order 里面含有不在当前表格控件的 id
bool needSave = false;
auto deleted_profiles = order;
for (int i = 0; i < this->rowCount(); i++) {
auto id = row2Id[i];
deleted_profiles.removeAll(id);
}
for (auto deleted_profile: deleted_profiles) {
needSave = true;
order.removeAll(deleted_profile);
}
// map(dstRow -> srcId)
QMap<int, int> newRows;
for (int i = 0; i < this->rowCount(); i++) {
auto id = row2Id[i];
auto dst = order.indexOf(id);
if (dst == i) continue;
if (dst == -1) {
// 纠错: 新的profile不需要移动
needSave = true;
continue;
}
newRows[dst] = id;
}
for (int i = 0; i < this->rowCount(); i++) {
if (!newRows.contains(i)) continue;
row2Id[i] = newRows[i];
}
// Then save the order
_save_order(needSave || saveToFile);
};
protected:
/*
* 2021.7.6 by gy
* 拖拽 继承QTableWidget overwrite dropEvent事件
* 功能:拖动一行到鼠标落下的位置
* 注意:DragDropMode相关参数的设置
*/
void dropEvent(QDropEvent *event) override {
if (order.isEmpty()) order = row2Id;
// 原行号与目标行号的确定
int row_src, row_dst;
row_src = this->currentRow(); // 原行号 可加if
auto id_src = row2Id[row_src]; // id_src
QTableWidgetItem *item = this->itemAt(event->pos()); // 获取落点的item
if (item != nullptr) {
// 判断是否为空
row_dst = item->row(); // 不为空 获取其行号
// Modify order
order.removeAt(row_src);
order.insert(row_dst, id_src);
} else {
// 落点没有item 说明拖动到了最下面
return;
}
// Do update order & refresh
clearSelection();
update_order(true);
refresh_data(-1);
};
};
| 3,428
|
C++
|
.h
| 97
| 24.195876
| 78
| 0.529145
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,703
|
FloatCheckBox.h
|
MatsuriDayo_nekoray/ui/widget/FloatCheckBox.h
|
#pragma once
#include <QEvent>
#include <QCheckBox>
class FloatCheckBox : public QCheckBox {
public:
QWidget *parent;
QWidget *window;
void refresh() {
setFixedSize(24, 24);
auto pos = parent->rect().topRight();
pos = parent->mapTo(window, pos);
pos.setX(pos.x() - 48); // ?
move(pos);
raise();
setVisible(parent->isVisible());
};
bool eventFilter(QObject *obj, QEvent *e) override {
if (obj != window || e->type() != QEvent::Resize) return false;
refresh();
return false;
};
explicit FloatCheckBox(QWidget *parent, QWidget *window) : QCheckBox(window) {
this->parent = parent;
this->window = window;
window->installEventFilter(this);
refresh();
};
};
| 801
|
C++
|
.h
| 28
| 22.285714
| 82
| 0.592448
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,704
|
MyLineEdit.h
|
MatsuriDayo_nekoray/ui/widget/MyLineEdit.h
|
#pragma once
#include <QLineEdit>
class MyLineEdit : public QLineEdit {
public slots:
explicit MyLineEdit(QWidget *parent = nullptr) : QLineEdit(parent) {
}
void setText(const QString &s) {
QLineEdit::setText(s);
QLineEdit::home(false);
}
};
| 278
|
C++
|
.h
| 11
| 21
| 72
| 0.680608
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,705
|
edit_socks_http.h
|
MatsuriDayo_nekoray/ui/edit/edit_socks_http.h
|
#pragma once
#include <QWidget>
#include "profile_editor.h"
namespace Ui {
class EditSocksHttp;
}
class EditSocksHttp : public QWidget, public ProfileEditor {
Q_OBJECT
public:
explicit EditSocksHttp(QWidget *parent = nullptr);
~EditSocksHttp() override;
void onStart(std::shared_ptr<NekoGui::ProxyEntity> _ent) override;
bool onEnd() override;
private:
Ui::EditSocksHttp *ui;
std::shared_ptr<NekoGui::ProxyEntity> ent;
};
| 462
|
C++
|
.h
| 17
| 23.823529
| 70
| 0.743707
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,706
|
edit_chain.h
|
MatsuriDayo_nekoray/ui/edit/edit_chain.h
|
#pragma once
#include <QWidget>
#include "profile_editor.h"
QT_BEGIN_NAMESPACE
namespace Ui {
class EditChain;
}
QT_END_NAMESPACE
class ProxyItem;
class EditChain : public QWidget, public ProfileEditor {
Q_OBJECT
public:
explicit EditChain(QWidget *parent = nullptr);
~EditChain() override;
void onStart(std::shared_ptr<NekoGui::ProxyEntity> _ent) override;
bool onEnd() override;
private:
Ui::EditChain *ui;
std::shared_ptr<NekoGui::ProxyEntity> ent;
void AddProfileToListIfExist(int profileId);
static void ReplaceProfile(ProxyItem *w, int profileId);
private slots:
void on_select_profile_clicked();
};
| 663
|
C++
|
.h
| 24
| 24.25
| 70
| 0.753994
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,707
|
edit_naive.h
|
MatsuriDayo_nekoray/ui/edit/edit_naive.h
|
#pragma once
#include <QWidget>
#include "profile_editor.h"
QT_BEGIN_NAMESPACE
namespace Ui {
class EditNaive;
}
QT_END_NAMESPACE
class EditNaive : public QWidget, public ProfileEditor {
Q_OBJECT
public:
explicit EditNaive(QWidget *parent = nullptr);
~EditNaive() override;
void onStart(std::shared_ptr<NekoGui::ProxyEntity> _ent) override;
bool onEnd() override;
QList<QPair<QPushButton *, QString>> get_editor_cached() override;
private:
Ui::EditNaive *ui;
std::shared_ptr<NekoGui::ProxyEntity> ent;
struct {
QString certificate;
QString extra_headers;
} CACHE;
private slots:
void on_certificate_clicked();
void on_extra_headers_clicked();
};
| 727
|
C++
|
.h
| 27
| 22.925926
| 70
| 0.720524
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,708
|
dialog_edit_profile.h
|
MatsuriDayo_nekoray/ui/edit/dialog_edit_profile.h
|
#ifndef DIALOG_EDIT_PROFILE_H
#define DIALOG_EDIT_PROFILE_H
#include <QDialog>
#include "db/Database.hpp"
#include "profile_editor.h"
#include "ui/widget/FloatCheckBox.h"
namespace Ui {
class DialogEditProfile;
}
class DialogEditProfile : public QDialog {
Q_OBJECT
public:
explicit DialogEditProfile(const QString &_type, int profileOrGroupId, QWidget *parent = nullptr);
~DialogEditProfile() override;
public slots:
void accept() override;
private slots:
void on_custom_outbound_edit_clicked();
void on_custom_config_edit_clicked();
void on_certificate_edit_clicked();
void on_apply_to_group_clicked();
private:
Ui::DialogEditProfile *ui;
std::map<QWidget *, FloatCheckBox *> apply_to_group_ui;
QWidget *innerWidget{};
ProfileEditor *innerEditor{};
QString type;
int groupId;
bool newEnt = false;
std::shared_ptr<NekoGui::ProxyEntity> ent;
QString network_title_base;
struct {
QString custom_outbound;
QString custom_config;
QString certificate;
} CACHE;
void typeSelected(const QString &newType);
bool onEnd();
void editor_cache_updated_impl();
void do_apply_to_group(const std::shared_ptr<NekoGui::Group> &group, QWidget *key);
};
#endif // DIALOG_EDIT_PROFILE_H
| 1,310
|
C++
|
.h
| 42
| 26.761905
| 102
| 0.721865
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,709
|
edit_vmess.h
|
MatsuriDayo_nekoray/ui/edit/edit_vmess.h
|
#pragma once
#include <QWidget>
#include "profile_editor.h"
QT_BEGIN_NAMESPACE
namespace Ui {
class EditVMess;
}
QT_END_NAMESPACE
class EditVMess : public QWidget, public ProfileEditor {
Q_OBJECT
public:
explicit EditVMess(QWidget *parent = nullptr);
~EditVMess() override;
void onStart(std::shared_ptr<NekoGui::ProxyEntity> _ent) override;
bool onEnd() override;
private:
Ui::EditVMess *ui;
std::shared_ptr<NekoGui::ProxyEntity> ent;
};
| 478
|
C++
|
.h
| 19
| 22.052632
| 70
| 0.742794
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,710
|
edit_shadowsocks.h
|
MatsuriDayo_nekoray/ui/edit/edit_shadowsocks.h
|
#ifndef EDIT_SHADOWSOCKS_H
#define EDIT_SHADOWSOCKS_H
#include <QWidget>
#include "profile_editor.h"
namespace Ui {
class EditShadowSocks;
}
class EditShadowSocks : public QWidget, public ProfileEditor {
Q_OBJECT
public:
explicit EditShadowSocks(QWidget *parent = nullptr);
~EditShadowSocks() override;
void onStart(std::shared_ptr<NekoGui::ProxyEntity> _ent) override;
bool onEnd() override;
private:
Ui::EditShadowSocks *ui;
std::shared_ptr<NekoGui::ProxyEntity> ent;
};
#endif // EDIT_SHADOWSOCKS_H
| 543
|
C++
|
.h
| 19
| 25.421053
| 70
| 0.757282
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,711
|
dialog_edit_group.h
|
MatsuriDayo_nekoray/ui/edit/dialog_edit_group.h
|
#pragma once
#include <QDialog>
#include "db/Group.hpp"
QT_BEGIN_NAMESPACE
namespace Ui {
class DialogEditGroup;
}
QT_END_NAMESPACE
class DialogEditGroup : public QDialog {
Q_OBJECT
public:
explicit DialogEditGroup(const std::shared_ptr<NekoGui::Group> &ent, QWidget *parent = nullptr);
~DialogEditGroup() override;
private:
Ui::DialogEditGroup *ui;
std::shared_ptr<NekoGui::Group> ent;
struct {
int front_proxy;
} CACHE;
void refresh_front_proxy();
private slots:
void accept() override;
void on_front_proxy_clicked();
};
| 587
|
C++
|
.h
| 24
| 20.791667
| 100
| 0.720508
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,712
|
edit_custom.h
|
MatsuriDayo_nekoray/ui/edit/edit_custom.h
|
#pragma once
#include <QWidget>
#include "profile_editor.h"
QT_BEGIN_NAMESPACE
namespace Ui {
class EditCustom;
}
QT_END_NAMESPACE
class EditCustom : public QWidget, public ProfileEditor {
Q_OBJECT
public:
QString preset_core;
QString preset_command;
QString preset_config;
explicit EditCustom(QWidget *parent = nullptr);
~EditCustom() override;
void onStart(std::shared_ptr<NekoGui::ProxyEntity> _ent) override;
bool onEnd() override;
private:
Ui::EditCustom *ui;
std::shared_ptr<NekoGui::ProxyEntity> ent;
private slots:
void on_as_json_clicked();
};
| 612
|
C++
|
.h
| 24
| 22.041667
| 70
| 0.740035
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,713
|
profile_editor.h
|
MatsuriDayo_nekoray/ui/edit/profile_editor.h
|
#pragma once
#include <QPushButton>
#include "db/ProxyEntity.hpp"
#include "main/GuiUtils.hpp"
class ProfileEditor {
public:
virtual void onStart(std::shared_ptr<NekoGui::ProxyEntity> ent) = 0;
virtual bool onEnd() = 0;
std::function<QWidget *()> get_edit_dialog;
std::function<QString()> get_edit_text_name;
std::function<QString()> get_edit_text_serverAddress;
std::function<QString()> get_edit_text_serverPort;
// cached editor
std::function<void()> editor_cache_updated;
virtual QList<QPair<QPushButton *, QString>> get_editor_cached() { return {}; };
};
| 603
|
C++
|
.h
| 16
| 33.9375
| 84
| 0.711572
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,714
|
edit_quic.h
|
MatsuriDayo_nekoray/ui/edit/edit_quic.h
|
#pragma once
#include <QWidget>
#include <QGridLayout>
#include <QHBoxLayout>
#include "profile_editor.h"
QT_BEGIN_NAMESPACE
namespace Ui {
class EditQUIC;
}
QT_END_NAMESPACE
class EditQUIC : public QWidget, public ProfileEditor {
Q_OBJECT
public:
explicit EditQUIC(QWidget *parent = nullptr);
~EditQUIC() override;
void onStart(std::shared_ptr<NekoGui::ProxyEntity> _ent) override;
bool onEnd() override;
QList<QPair<QPushButton *, QString>> get_editor_cached() override;
private:
Ui::EditQUIC *ui;
std::shared_ptr<NekoGui::ProxyEntity> ent;
struct {
QString caText;
} CACHE;
private slots:
void on_certificate_clicked();
};
| 694
|
C++
|
.h
| 27
| 22.185185
| 70
| 0.728244
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,715
|
edit_trojan_vless.h
|
MatsuriDayo_nekoray/ui/edit/edit_trojan_vless.h
|
#pragma once
#include <QWidget>
#include "profile_editor.h"
QT_BEGIN_NAMESPACE
namespace Ui {
class EditTrojanVLESS;
}
QT_END_NAMESPACE
class EditTrojanVLESS : public QWidget, public ProfileEditor {
Q_OBJECT
public:
explicit EditTrojanVLESS(QWidget *parent = nullptr);
~EditTrojanVLESS() override;
void onStart(std::shared_ptr<NekoGui::ProxyEntity> _ent) override;
bool onEnd() override;
private:
Ui::EditTrojanVLESS *ui;
std::shared_ptr<NekoGui::ProxyEntity> ent;
};
| 508
|
C++
|
.h
| 19
| 23.631579
| 70
| 0.758836
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,716
|
Preset.hpp
|
MatsuriDayo_nekoray/fmt/Preset.hpp
|
#pragma once
namespace Preset {
namespace SingBox {
inline QStringList VpnImplementation = {"gvisor", "system", "mixed"};
inline QStringList DomainStrategy = {"", "ipv4_only", "ipv6_only", "prefer_ipv4", "prefer_ipv6"};
inline QStringList UtlsFingerPrint = {"", "chrome", "firefox", "edge", "safari", "360", "qq", "ios", "android", "random", "randomized"};
inline QStringList ShadowsocksMethods = {"2022-blake3-aes-128-gcm", "2022-blake3-aes-256-gcm", "2022-blake3-chacha20-poly1305", "none", "aes-128-gcm", "aes-192-gcm", "aes-256-gcm", "chacha20-ietf-poly1305", "xchacha20-ietf-poly1305", "aes-128-ctr", "aes-192-ctr", "aes-256-ctr", "aes-128-cfb", "aes-192-cfb", "aes-256-cfb", "rc4-md5", "chacha20-ietf", "xchacha20"};
inline QStringList Flows = {"xtls-rprx-vision"};
} // namespace SingBox
namespace Windows {
inline QStringList system_proxy_format{"{ip}:{http_port}",
"socks={ip}:{socks_port}",
"http={ip}:{http_port};https={ip}:{http_port};ftp={ip}:{http_port};socks={ip}:{socks_port}",
"http=http://{ip}:{http_port};https=http://{ip}:{http_port}"};
} // namespace Windows
} // namespace Preset
| 1,309
|
C++
|
.h
| 16
| 67.875
| 373
| 0.58172
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,717
|
TrojanVLESSBean.hpp
|
MatsuriDayo_nekoray/fmt/TrojanVLESSBean.hpp
|
#pragma once
#include "fmt/AbstractBean.hpp"
#include "fmt/V2RayStreamSettings.hpp"
namespace NekoGui_fmt {
class TrojanVLESSBean : public AbstractBean {
public:
static constexpr int proxy_Trojan = 0;
static constexpr int proxy_VLESS = 1;
int proxy_type = proxy_Trojan;
QString password = "";
QString flow = "";
std::shared_ptr<V2rayStreamSettings> stream = std::make_shared<V2rayStreamSettings>();
explicit TrojanVLESSBean(int _proxy_type) : AbstractBean(0) {
proxy_type = _proxy_type;
_add(new configItem("pass", &password, itemType::string));
_add(new configItem("flow", &flow, itemType::string));
_add(new configItem("stream", dynamic_cast<JsonStore *>(stream.get()), itemType::jsonStore));
};
QString DisplayType() override { return proxy_type == proxy_VLESS ? "VLESS" : "Trojan"; };
CoreObjOutboundBuildResult BuildCoreObjSingBox() override;
bool TryParseLink(const QString &link);
QString ToShareLink() override;
};
} // namespace NekoGui_fmt
| 1,114
|
C++
|
.h
| 24
| 38.583333
| 105
| 0.658965
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,718
|
VMessBean.hpp
|
MatsuriDayo_nekoray/fmt/VMessBean.hpp
|
#pragma once
#include "fmt/AbstractBean.hpp"
#include "fmt/V2RayStreamSettings.hpp"
namespace NekoGui_fmt {
class VMessBean : public AbstractBean {
public:
QString uuid = "";
int aid = 0;
QString security = "auto";
std::shared_ptr<V2rayStreamSettings> stream = std::make_shared<V2rayStreamSettings>();
VMessBean() : AbstractBean(0) {
_add(new configItem("id", &uuid, itemType::string));
_add(new configItem("aid", &aid, itemType::integer));
_add(new configItem("sec", &security, itemType::string));
_add(new configItem("stream", dynamic_cast<JsonStore *>(stream.get()), itemType::jsonStore));
};
QString DisplayType() override { return "VMess"; };
CoreObjOutboundBuildResult BuildCoreObjSingBox() override;
bool TryParseLink(const QString &link);
QString ToShareLink() override;
};
} // namespace NekoGui_fmt
| 957
|
C++
|
.h
| 22
| 35.772727
| 105
| 0.648328
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,719
|
QUICBean.hpp
|
MatsuriDayo_nekoray/fmt/QUICBean.hpp
|
#pragma once
#include "fmt/AbstractBean.hpp"
namespace NekoGui_fmt {
class QUICBean : public AbstractBean {
public:
// static constexpr int proxy_Hysteria = 0;
static constexpr int proxy_TUIC = 1;
static constexpr int proxy_Hysteria2 = 3;
int proxy_type = proxy_Hysteria2;
bool forceExternal = false;
// Hysteria 2
QString obfsPassword = "";
int uploadMbps = 0;
int downloadMbps = 0;
qint64 streamReceiveWindow = 0;
qint64 connectionReceiveWindow = 0;
bool disableMtuDiscovery = false;
int hopInterval = 10;
QString hopPort = "";
// TUIC
QString uuid = "";
QString congestionControl = "bbr";
QString udpRelayMode = "native";
bool zeroRttHandshake = false;
QString heartbeat = "10s";
bool uos = false;
// HY2&TUIC
QString password = "";
// TLS
bool allowInsecure = false;
QString sni = "";
QString alpn = "";
QString caText = "";
bool disableSni = false;
explicit QUICBean(int _proxy_type) : AbstractBean(0) {
proxy_type = _proxy_type;
if (proxy_type == proxy_Hysteria2) {
_add(new configItem("obfsPassword", &obfsPassword, itemType::string));
_add(new configItem("uploadMbps", &uploadMbps, itemType::integer));
_add(new configItem("downloadMbps", &downloadMbps, itemType::integer));
_add(new configItem("streamReceiveWindow", &streamReceiveWindow, itemType::integer64));
_add(new configItem("connectionReceiveWindow", &connectionReceiveWindow, itemType::integer64));
_add(new configItem("disableMtuDiscovery", &disableMtuDiscovery, itemType::boolean));
_add(new configItem("hopInterval", &hopInterval, itemType::integer));
_add(new configItem("hopPort", &hopPort, itemType::string));
_add(new configItem("password", &password, itemType::string));
} else if (proxy_type == proxy_TUIC) {
_add(new configItem("uuid", &uuid, itemType::string));
_add(new configItem("password", &password, itemType::string));
_add(new configItem("congestionControl", &congestionControl, itemType::string));
_add(new configItem("udpRelayMode", &udpRelayMode, itemType::string));
_add(new configItem("zeroRttHandshake", &zeroRttHandshake, itemType::boolean));
_add(new configItem("heartbeat", &heartbeat, itemType::string));
_add(new configItem("uos", &uos, itemType::boolean));
}
_add(new configItem("forceExternal", &forceExternal, itemType::boolean));
// TLS
_add(new configItem("allowInsecure", &allowInsecure, itemType::boolean));
_add(new configItem("sni", &sni, itemType::string));
_add(new configItem("alpn", &alpn, itemType::string));
_add(new configItem("caText", &caText, itemType::string));
_add(new configItem("disableSni", &disableSni, itemType::boolean));
};
QString DisplayAddress() override {
if (!hopPort.trimmed().isEmpty()) return WrapIPV6Host(serverAddress) + ":" + hopPort;
return ::DisplayAddress(serverAddress, serverPort);
}
QString DisplayCoreType() override {
if (NeedExternal(true) == 0) {
return software_core_name;
} else if (proxy_type == proxy_TUIC) {
return "tuic";
} else {
return "hysteria2";
}
}
QString DisplayType() override {
if (proxy_type == proxy_TUIC) {
return "TUIC";
} else {
return "Hysteria2";
}
};
int NeedExternal(bool isFirstProfile) override;
ExternalBuildResult BuildExternal(int mapping_port, int socks_port, int external_stat) override;
CoreObjOutboundBuildResult BuildCoreObjSingBox() override;
bool TryParseLink(const QString &link);
QString ToShareLink() override;
};
} // namespace NekoGui_fmt
| 4,274
|
C++
|
.h
| 90
| 35.977778
| 111
| 0.594666
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,720
|
AbstractBean.hpp
|
MatsuriDayo_nekoray/fmt/AbstractBean.hpp
|
#pragma once
#include <QJsonObject>
#include <QJsonArray>
#include "main/NekoGui.hpp"
namespace NekoGui_fmt {
struct CoreObjOutboundBuildResult {
public:
QJsonObject outbound;
QString error;
};
struct ExternalBuildResult {
public:
QString program;
QStringList env;
QStringList arguments;
//
QString tag;
//
QString error;
QString config_export;
};
class AbstractBean : public JsonStore {
public:
int version;
QString name = "";
QString serverAddress = "127.0.0.1";
int serverPort = 1080;
QString custom_config = "";
QString custom_outbound = "";
explicit AbstractBean(int version);
//
QString ToNekorayShareLink(const QString &type);
void ResolveDomainToIP(const std::function<void()> &onFinished);
//
[[nodiscard]] virtual QString DisplayAddress();
[[nodiscard]] virtual QString DisplayName();
virtual QString DisplayCoreType() { return software_core_name; };
virtual QString DisplayType() { return {}; };
virtual QString DisplayTypeAndName();
//
virtual int NeedExternal(bool isFirstProfile) { return 0; };
virtual CoreObjOutboundBuildResult BuildCoreObjSingBox() { return {}; };
virtual ExternalBuildResult BuildExternal(int mapping_port, int socks_port, int external_stat) { return {}; };
virtual QString ToShareLink() { return {}; };
};
} // namespace NekoGui_fmt
| 1,576
|
C++
|
.h
| 46
| 26.586957
| 118
| 0.639681
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,721
|
NaiveBean.hpp
|
MatsuriDayo_nekoray/fmt/NaiveBean.hpp
|
#pragma once
#include "fmt/AbstractBean.hpp"
namespace NekoGui_fmt {
class NaiveBean : public AbstractBean {
public:
QString username = "";
QString password = "";
QString protocol = "https";
QString extra_headers = "";
QString sni = "";
QString certificate = "";
int insecure_concurrency = 0;
bool disable_log = false;
NaiveBean() : AbstractBean(0) {
_add(new configItem("username", &username, itemType::string));
_add(new configItem("password", &password, itemType::string));
_add(new configItem("protocol", &protocol, itemType::string));
_add(new configItem("extra_headers", &extra_headers, itemType::string));
_add(new configItem("sni", &sni, itemType::string));
_add(new configItem("certificate", &certificate, itemType::string));
_add(new configItem("insecure_concurrency", &insecure_concurrency, itemType::integer));
_add(new configItem("disable_log", &disable_log, itemType::boolean));
};
QString DisplayCoreType() override { return "Naive"; };
QString DisplayType() override { return "Naive"; };
int NeedExternal(bool isFirstProfile) override;
ExternalBuildResult BuildExternal(int mapping_port, int socks_port, int external_stat) override;
bool TryParseLink(const QString &link);
QString ToShareLink() override;
};
} // namespace NekoGui_fmt
| 1,496
|
C++
|
.h
| 31
| 39.354839
| 104
| 0.638736
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,722
|
ShadowSocksBean.hpp
|
MatsuriDayo_nekoray/fmt/ShadowSocksBean.hpp
|
#pragma once
#include "fmt/AbstractBean.hpp"
#include "fmt/V2RayStreamSettings.hpp"
namespace NekoGui_fmt {
class ShadowSocksBean : public AbstractBean {
public:
QString method = "aes-128-gcm";
QString password = "";
QString plugin = "";
int uot = 0;
std::shared_ptr<V2rayStreamSettings> stream = std::make_shared<V2rayStreamSettings>();
ShadowSocksBean() : AbstractBean(0) {
_add(new configItem("method", &method, itemType::string));
_add(new configItem("pass", &password, itemType::string));
_add(new configItem("plugin", &plugin, itemType::string));
_add(new configItem("uot", &uot, itemType::integer));
_add(new configItem("stream", dynamic_cast<JsonStore *>(stream.get()), itemType::jsonStore));
};
QString DisplayType() override { return "Shadowsocks"; };
CoreObjOutboundBuildResult BuildCoreObjSingBox() override;
bool TryParseLink(const QString &link);
QString ToShareLink() override;
};
} // namespace NekoGui_fmt
| 1,091
|
C++
|
.h
| 24
| 37.458333
| 105
| 0.649669
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,723
|
V2RayStreamSettings.hpp
|
MatsuriDayo_nekoray/fmt/V2RayStreamSettings.hpp
|
#pragma once
#include "AbstractBean.hpp"
namespace NekoGui_fmt {
class V2rayStreamSettings : public JsonStore {
public:
QString network = "tcp";
QString security = "";
QString packet_encoding = "";
// ws/http/grpc/tcp-http/httpupgrade
QString path = "";
QString host = "";
// kcp/quic/tcp-http
QString header_type = "";
// tls
QString sni = "";
QString alpn = "";
QString certificate = "";
QString utlsFingerprint = "";
bool allow_insecure = false;
// ws early data
QString ws_early_data_name = "";
int ws_early_data_length = 0;
// reality
QString reality_pbk = "";
QString reality_sid = "";
QString reality_spx = "";
// multiplex
int multiplex_status = 0;
V2rayStreamSettings() : JsonStore() {
_add(new configItem("net", &network, itemType::string));
_add(new configItem("sec", &security, itemType::string));
_add(new configItem("pac_enc", &packet_encoding, itemType::string));
_add(new configItem("path", &path, itemType::string));
_add(new configItem("host", &host, itemType::string));
_add(new configItem("sni", &sni, itemType::string));
_add(new configItem("alpn", &alpn, itemType::string));
_add(new configItem("cert", &certificate, itemType::string));
_add(new configItem("insecure", &allow_insecure, itemType::boolean));
_add(new configItem("h_type", &header_type, itemType::string));
_add(new configItem("ed_name", &ws_early_data_name, itemType::string));
_add(new configItem("ed_len", &ws_early_data_length, itemType::integer));
_add(new configItem("utls", &utlsFingerprint, itemType::string));
_add(new configItem("pbk", &reality_pbk, itemType::string));
_add(new configItem("sid", &reality_sid, itemType::string));
_add(new configItem("spx", &reality_spx, itemType::string));
_add(new configItem("mux_s", &multiplex_status, itemType::integer));
}
void BuildStreamSettingsSingBox(QJsonObject *outbound);
};
inline V2rayStreamSettings *GetStreamSettings(AbstractBean *bean) {
if (bean == nullptr) return nullptr;
auto stream_item = bean->_get("stream");
if (stream_item != nullptr) {
auto stream_store = (JsonStore *) stream_item->ptr;
auto stream = (NekoGui_fmt::V2rayStreamSettings *) stream_store;
return stream;
}
return nullptr;
}
} // namespace NekoGui_fmt
| 2,686
|
C++
|
.h
| 60
| 35.216667
| 85
| 0.590996
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,724
|
CustomBean.hpp
|
MatsuriDayo_nekoray/fmt/CustomBean.hpp
|
#pragma once
#include "fmt/AbstractBean.hpp"
namespace NekoGui_fmt {
class CustomBean : public AbstractBean {
public:
QString core;
QList<QString> command;
QString config_suffix;
QString config_simple;
int mapping_port = 0;
int socks_port = 0;
CustomBean() : AbstractBean(0) {
_add(new configItem("core", &core, itemType::string));
_add(new configItem("cmd", &command, itemType::stringList));
_add(new configItem("cs", &config_simple, itemType::string));
_add(new configItem("cs_suffix", &config_suffix, itemType::string));
_add(new configItem("mapping_port", &mapping_port, itemType::integer));
_add(new configItem("socks_port", &socks_port, itemType::integer));
};
QString DisplayType() override {
if (core == "internal") {
auto obj = QString2QJsonObject(config_simple);
return obj["type"].toString();
} else if (core == "internal-full") {
return software_core_name + " config";
}
return core;
};
QString DisplayCoreType() override { return NeedExternal(true) == 0 ? software_core_name : core; };
QString DisplayAddress() override {
if (core == "internal") {
auto obj = QString2QJsonObject(config_simple);
return ::DisplayAddress(obj["server"].toString(), obj["server_port"].toInt());
} else if (core == "internal-full") {
return {};
}
return AbstractBean::DisplayAddress();
};
int NeedExternal(bool isFirstProfile) override;
ExternalBuildResult BuildExternal(int mapping_port, int socks_port, int external_stat) override;
CoreObjOutboundBuildResult BuildCoreObjSingBox() override;
};
} // namespace NekoGui_fmt
| 1,926
|
C++
|
.h
| 43
| 34.209302
| 107
| 0.593067
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,725
|
SocksHttpBean.hpp
|
MatsuriDayo_nekoray/fmt/SocksHttpBean.hpp
|
#pragma once
#include "fmt/AbstractBean.hpp"
#include "fmt/V2RayStreamSettings.hpp"
namespace NekoGui_fmt {
class SocksHttpBean : public AbstractBean {
public:
static constexpr int type_HTTP = -80;
static constexpr int type_Socks4 = 4;
static constexpr int type_Socks5 = 5;
int socks_http_type = type_Socks5;
QString username = "";
QString password = "";
std::shared_ptr<V2rayStreamSettings> stream = std::make_shared<V2rayStreamSettings>();
explicit SocksHttpBean(int _socks_http_type) : AbstractBean(0) {
this->socks_http_type = _socks_http_type;
_add(new configItem("v", &socks_http_type, itemType::integer));
_add(new configItem("username", &username, itemType::string));
_add(new configItem("password", &password, itemType::string));
_add(new configItem("stream", dynamic_cast<JsonStore *>(stream.get()), itemType::jsonStore));
};
QString DisplayType() override { return socks_http_type == type_HTTP ? "HTTP" : "Socks"; };
CoreObjOutboundBuildResult BuildCoreObjSingBox() override;
bool TryParseLink(const QString &link);
QString ToShareLink() override;
};
} // namespace NekoGui_fmt
| 1,274
|
C++
|
.h
| 26
| 40.884615
| 105
| 0.658596
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,726
|
includes.h
|
MatsuriDayo_nekoray/fmt/includes.h
|
#pragma once
#include "SocksHttpBean.hpp"
#include "ShadowSocksBean.hpp"
#include "ChainBean.hpp"
#include "VMessBean.hpp"
#include "TrojanVLESSBean.hpp"
#include "NaiveBean.hpp"
#include "QUICBean.hpp"
#include "CustomBean.hpp"
| 230
|
C++
|
.h
| 9
| 24.444444
| 30
| 0.809091
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,727
|
ChainBean.hpp
|
MatsuriDayo_nekoray/fmt/ChainBean.hpp
|
#pragma once
#include "main/NekoGui.hpp"
namespace NekoGui_fmt {
class ChainBean : public AbstractBean {
public:
QList<int> list; // in to out
ChainBean() : AbstractBean(0) {
_add(new configItem("list", &list, itemType::integerList));
};
QString DisplayType() override { return QObject::tr("Chain Proxy"); };
QString DisplayAddress() override { return ""; };
};
} // namespace NekoGui_fmt
| 458
|
C++
|
.h
| 13
| 28.923077
| 78
| 0.629545
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,728
|
ExternalProcess.hpp
|
MatsuriDayo_nekoray/sys/ExternalProcess.hpp
|
#pragma once
#include <memory>
#include <QProcess>
namespace NekoGui_sys {
class ExternalProcess : public QProcess {
public:
QString tag;
QString program;
QStringList arguments;
QStringList env;
bool managed = true; // MW_dialog_message
ExternalProcess();
~ExternalProcess();
// start & kill is one time
virtual void Start();
void Kill();
protected:
bool started = false;
bool killed = false;
bool crashed = false;
};
class CoreProcess : public ExternalProcess {
public:
CoreProcess(const QString &core_path, const QStringList &args);
void Start() override;
void Restart();
int start_profile_when_core_is_up = -1;
private:
bool show_stderr = false;
bool failed_to_start = false;
bool restarting = false;
};
// 手动管理
inline std::list<std::shared_ptr<ExternalProcess>> running_ext;
inline QAtomicInt logCounter;
} // namespace NekoGui_sys
| 1,063
|
C++
|
.h
| 36
| 22.222222
| 71
| 0.626494
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,729
|
LinuxCap.h
|
MatsuriDayo_nekoray/sys/linux/LinuxCap.h
|
#pragma once
#include <QString>
QString Linux_GetCapString(const QString &path);
int Linux_Pkexec_SetCapString(const QString &path, const QString &cap);
bool Linux_HavePkexec();
QString Linux_FindCapProgsExec(const QString &name);
| 236
|
C++
|
.h
| 6
| 37.5
| 71
| 0.817778
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,730
|
gRPC.h
|
MatsuriDayo_nekoray/rpc/gRPC.h
|
#pragma once
#ifndef NKR_NO_GRPC
#include "go/grpc_server/gen/libcore.pb.h"
#include <QString>
namespace QtGrpc {
class Http2GrpcChannelPrivate;
}
namespace NekoGui_rpc {
class Client {
public:
explicit Client(std::function<void(const QString &)> onError, const QString &target, const QString &token);
void Exit();
bool KeepAlive();
// QString returns is error string
QString Start(bool *rpcOK, const libcore::LoadConfigReq &request);
QString Stop(bool *rpcOK);
long long QueryStats(const std::string &tag, const std::string &direct);
std::string ListConnections();
libcore::TestResp Test(bool *rpcOK, const libcore::TestReq &request);
libcore::UpdateResp Update(bool *rpcOK, const libcore::UpdateReq &request);
private:
std::function<std::unique_ptr<QtGrpc::Http2GrpcChannelPrivate>()> make_grpc_channel;
std::unique_ptr<QtGrpc::Http2GrpcChannelPrivate> default_grpc_channel;
std::function<void(const QString &)> onError;
};
inline Client *defaultClient;
} // namespace NekoGui_rpc
#endif
| 1,133
|
C++
|
.h
| 28
| 34.357143
| 115
| 0.7
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,731
|
NekoGui_ConfigItem.hpp
|
MatsuriDayo_nekoray/main/NekoGui_ConfigItem.hpp
|
// DO NOT INCLUDE THIS
namespace NekoGui_ConfigItem {
// config 工具
enum itemType {
string,
integer,
integer64,
boolean,
stringList,
integerList,
jsonStore,
};
class configItem {
public:
QString name;
void *ptr;
itemType type;
configItem(QString n, void *p, itemType t) {
name = std::move(n);
ptr = p;
type = t;
}
};
// 可格式化对象
class JsonStore {
public:
QMap<QString, std::shared_ptr<configItem>> _map;
std::function<void()> callback_after_load = nullptr;
std::function<void()> callback_before_save = nullptr;
QString fn;
bool load_control_must = false; // must load from file
bool save_control_compact = false;
bool save_control_no_save = false;
QByteArray last_save_content;
JsonStore() = default;
explicit JsonStore(QString fileName) {
fn = std::move(fileName);
}
void _add(configItem *item);
QString _name(void *p);
std::shared_ptr<configItem> _get(const QString &name);
void _setValue(const QString &name, void *p);
QJsonObject ToJson(const QStringList &without = {});
QByteArray ToJsonBytes();
void FromJson(QJsonObject object);
void FromJsonBytes(const QByteArray &data);
bool Save();
bool Load();
};
} // namespace NekoGui_ConfigItem
using namespace NekoGui_ConfigItem;
| 1,563
|
C++
|
.h
| 51
| 22.058824
| 62
| 0.587678
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,732
|
GuiUtils.hpp
|
MatsuriDayo_nekoray/main/GuiUtils.hpp
|
#pragma once
// Dialogs
#define Dialog_DialogBasicSettings "DialogBasicSettings"
#define Dialog_DialogEditProfile "DialogEditProfile"
#define Dialog_DialogManageGroups "DialogManageGroups"
#define Dialog_DialogManageRoutes "DialogManageRoutes"
// Utils
#define QRegExpValidator_Number new QRegularExpressionValidator(QRegularExpression("^[0-9]+$"), this)
// NekoRay Save&Load
#define P_C_LOAD_STRING(a) CACHE.a = bean->a;
#define P_C_SAVE_STRING(a) bean->a = CACHE.a;
#define D_C_LOAD_STRING(a) CACHE.a = NekoGui::dataStore->a;
#define D_C_SAVE_STRING(a) NekoGui::dataStore->a = CACHE.a;
#define P_LOAD_STRING(a) ui->a->setText(bean->a);
#define P_LOAD_STRING_PLAIN(a) ui->a->setPlainText(bean->a);
#define P_SAVE_STRING(a) bean->a = ui->a->text();
#define P_SAVE_STRING_PLAIN(a) bean->a = ui->a->toPlainText();
#define D_LOAD_STRING(a) ui->a->setText(NekoGui::dataStore->a);
#define D_LOAD_STRING_PLAIN(a) ui->a->setPlainText(NekoGui::dataStore->a);
#define D_SAVE_STRING(a) NekoGui::dataStore->a = ui->a->text();
#define D_SAVE_STRING_PLAIN(a) NekoGui::dataStore->a = ui->a->toPlainText();
#define P_LOAD_INT(a) \
ui->a->setText(Int2String(bean->a)); \
ui->a->setValidator(QRegExpValidator_Number);
#define P_SAVE_INT(a) bean->a = ui->a->text().toInt();
#define D_LOAD_INT(a) \
ui->a->setText(Int2String(NekoGui::dataStore->a)); \
ui->a->setValidator(QRegExpValidator_Number);
#define D_SAVE_INT(a) NekoGui::dataStore->a = ui->a->text().toInt();
#define P_LOAD_COMBO_STRING(a) ui->a->setCurrentText(bean->a);
#define P_SAVE_COMBO_STRING(a) bean->a = ui->a->currentText();
#define D_LOAD_COMBO_STRING(a) ui->a->setCurrentText(NekoGui::dataStore->a);
#define D_SAVE_COMBO_STRING(a) NekoGui::dataStore->a = ui->a->currentText();
#define P_LOAD_COMBO_INT(a) ui->a->setCurrentIndex(bean->a);
#define P_SAVE_COMBO_INT(a) bean->a = ui->a->currentIndex();
#define D_LOAD_BOOL(a) ui->a->setChecked(NekoGui::dataStore->a);
#define D_SAVE_BOOL(a) NekoGui::dataStore->a = ui->a->isChecked();
#define P_LOAD_BOOL(a) ui->a->setChecked(bean->a);
#define P_SAVE_BOOL(a) bean->a = ui->a->isChecked();
#define D_LOAD_INT_ENABLE(i, e) \
if (NekoGui::dataStore->i > 0) { \
ui->e->setChecked(true); \
ui->i->setText(Int2String(NekoGui::dataStore->i)); \
} else { \
ui->e->setChecked(false); \
ui->i->setText(Int2String(-NekoGui::dataStore->i)); \
} \
ui->i->setValidator(QRegExpValidator_Number);
#define D_SAVE_INT_ENABLE(i, e) \
if (ui->e->isChecked()) { \
NekoGui::dataStore->i = ui->i->text().toInt(); \
} else { \
NekoGui::dataStore->i = -ui->i->text().toInt(); \
}
#define C_EDIT_JSON_ALLOW_EMPTY(a) \
auto editor = new JsonEditor(QString2QJsonObject(CACHE.a), this); \
auto result = editor->OpenEditor(); \
CACHE.a = QJsonObject2QString(result, true); \
if (result.isEmpty()) CACHE.a = ""; \
editor->deleteLater();
//
#define ADD_ASTERISK(parent) \
for (auto label: parent->findChildren<QLabel *>()) { \
auto text = label->text(); \
if (!label->toolTip().isEmpty() && !text.endsWith("*")) { \
label->setText(text + "*"); \
} \
} \
for (auto checkBox: parent->findChildren<QCheckBox *>()) { \
auto text = checkBox->text(); \
if (!checkBox->toolTip().isEmpty() && !text.endsWith("*")) { \
checkBox->setText(text + "*"); \
} \
}
| 4,263
|
C++
|
.h
| 74
| 53.648649
| 101
| 0.52494
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,733
|
NekoGui.hpp
|
MatsuriDayo_nekoray/main/NekoGui.hpp
|
#pragma once
#include "Const.hpp"
#include "NekoGui_Utils.hpp"
#include "NekoGui_ConfigItem.hpp"
#include "NekoGui_DataStore.hpp"
// Switch core support
namespace NekoGui {
inline int coreType = CoreType::SING_BOX;
QString FindCoreAsset(const QString &name);
QString FindNekoBoxCoreRealPath();
bool IsAdmin();
} // namespace NekoGui
#define ROUTES_PREFIX_NAME QString("routes_box")
#define ROUTES_PREFIX QString(ROUTES_PREFIX_NAME + "/")
| 461
|
C++
|
.h
| 14
| 30.285714
| 55
| 0.765909
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,734
|
NekoGui_DataStore.hpp
|
MatsuriDayo_nekoray/main/NekoGui_DataStore.hpp
|
// DO NOT INCLUDE THIS
namespace NekoGui {
class Routing : public JsonStore {
public:
QString direct_ip;
QString direct_domain;
QString proxy_ip;
QString proxy_domain;
QString block_ip;
QString block_domain;
QString def_outbound = "proxy";
QString custom = "{\"rules\": []}";
// DNS
QString remote_dns = "https://dns.google/dns-query";
QString remote_dns_strategy = "";
QString direct_dns = "https://doh.pub/dns-query";
QString direct_dns_strategy = "";
bool dns_routing = true;
bool use_dns_object = false;
QString dns_object = "";
QString dns_final_out = "proxy";
// Misc
QString domain_strategy = "AsIs";
QString outbound_domain_strategy = "AsIs";
int sniffing_mode = SniffingMode::FOR_ROUTING;
explicit Routing(int preset = 0);
[[nodiscard]] QString DisplayRouting() const;
static QStringList List();
static bool SetToActive(const QString &name);
};
class ExtraCore : public JsonStore {
public:
QString core_map;
explicit ExtraCore();
[[nodiscard]] QString Get(const QString &id) const;
void Set(const QString &id, const QString &path);
void Delete(const QString &id);
};
class InboundAuthorization : public JsonStore {
public:
QString username;
QString password;
InboundAuthorization();
[[nodiscard]] bool NeedAuth() const;
};
class DataStore : public JsonStore {
public:
// Running
QString core_token;
int core_port = 19810;
int started_id = -1919;
bool core_running = false;
bool prepare_exit = false;
bool spmode_vpn = false;
bool spmode_system_proxy = false;
bool need_keep_vpn_off = false;
QString appdataDir = "";
QStringList ignoreConnTag = {};
std::unique_ptr<Routing> routing;
int imported_count = 0;
bool refreshing_group_list = false;
bool refreshing_group = false;
int resolve_count = 0;
// Flags
QStringList argv = {};
bool flag_use_appdata = false;
bool flag_many = false;
bool flag_tray = false;
bool flag_debug = false;
bool flag_restart_tun_on = false;
bool flag_reorder = false;
// Saved
// Misc
QString log_level = "info";
QString test_latency_url = "http://cp.cloudflare.com/";
QString test_download_url = "http://cachefly.cachefly.net/10mb.test";
int test_download_timeout = 30;
int test_concurrent = 5;
bool old_share_link_format = true;
int traffic_loop_interval = 1000;
bool connection_statistics = false;
int current_group = 0; // group id
QString mux_protocol = "h2mux";
bool mux_padding = false;
int mux_concurrency = 8;
bool mux_default_on = false;
QString theme = "0";
int language = 0;
QString mw_size = "";
bool check_include_pre = false;
QString system_proxy_format = "";
QStringList log_ignore = {};
bool start_minimal = false;
int max_log_line = 200;
QString splitter_state = "";
// Subscription
QString user_agent = ""; // set at main.cpp
bool sub_use_proxy = false;
bool sub_clear = false;
bool sub_insecure = false;
int sub_auto_update = -30;
// Security
bool skip_cert = false;
QString utlsFingerprint = "";
// Remember
QStringList remember_spmode = {};
int remember_id = -1919;
bool remember_enable = false;
// Socks & HTTP Inbound
QString inbound_address = "127.0.0.1";
int inbound_socks_port = 2080; // or Mixed
InboundAuthorization *inbound_auth = new InboundAuthorization;
QString custom_inbound = "{\"inbounds\": []}";
// Routing
QString custom_route_global = "{\"rules\": []}";
QString active_routing = "Default";
// VPN
bool fake_dns = false;
bool vpn_internal_tun = true;
int vpn_implementation = 0;
int vpn_mtu = 9000;
bool vpn_ipv6 = false;
bool vpn_hide_console = true;
bool vpn_strict_route = false;
bool vpn_rule_white = false;
QString vpn_rule_process = "";
QString vpn_rule_cidr = "";
// Hotkey
QString hotkey_mainwindow = "";
QString hotkey_group = "";
QString hotkey_route = "";
QString hotkey_system_proxy_menu = "";
// Core
int core_box_clash_api = -9090;
QString core_box_clash_api_secret = "";
QString core_box_underlying_dns = "";
// Other Core
ExtraCore *extraCore = new ExtraCore;
// Methods
DataStore();
void UpdateStartedId(int id);
QString GetUserAgent(bool isDefault = false) const;
};
extern DataStore *dataStore;
} // namespace NekoGui
| 5,131
|
C++
|
.h
| 145
| 26.655172
| 77
| 0.584765
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,735
|
NekoGui_Utils.hpp
|
MatsuriDayo_nekoray/main/NekoGui_Utils.hpp
|
// DO NOT INCLUDE THIS
#include <functional>
#include <memory>
#include <QObject>
#include <QString>
#include <QDebug>
//
inline QString software_name = "NekoBox";
inline QString software_core_name = "sing-box";
// Main Functions
inline std::function<void()> MF_release_runguard;
// MainWindow functions
class QWidget;
inline QWidget *mainwindow;
inline std::function<void(QString)> MW_show_log;
inline std::function<void(QString, QString)> MW_show_log_ext;
inline std::function<void(QString)> MW_show_log_ext_vt100;
inline std::function<void(QString, QString)> MW_dialog_message;
// Dispatchers
class QThread;
inline QThread *DS_cores;
// Timers
class QTimer;
inline QTimer *TM_auto_update_subsctiption;
inline std::function<void(int)> TM_auto_update_subsctiption_Reset_Minute;
// String
#define FIRST_OR_SECOND(a, b) a.isEmpty() ? b : a
inline const QString UNICODE_LRO = QString::fromUtf8(QByteArray::fromHex("E280AD"));
#define Int2String(num) QString::number(num)
inline QString SubStrBefore(QString str, const QString &sub) {
if (!str.contains(sub)) return str;
return str.left(str.indexOf(sub));
}
inline QString SubStrAfter(QString str, const QString &sub) {
if (!str.contains(sub)) return str;
return str.right(str.length() - str.indexOf(sub) - sub.length());
}
QString QStringList2Command(const QStringList &list);
QStringList SplitLines(const QString &_string);
QStringList SplitLinesSkipSharp(const QString &_string, int maxLine = 0);
// Base64
QByteArray DecodeB64IfValid(const QString &input, QByteArray::Base64Options options = QByteArray::Base64Option::Base64Encoding);
// URL
class QUrlQuery;
#define GetQuery(url) QUrlQuery((url).query(QUrl::ComponentFormattingOption::FullyDecoded));
QString GetQueryValue(const QUrlQuery &q, const QString &key, const QString &def = "");
QString GetRandomString(int randomStringLength);
quint64 GetRandomUint64();
// JSON
class QJsonObject;
class QJsonArray;
QJsonObject QString2QJsonObject(const QString &jsonString);
QString QJsonObject2QString(const QJsonObject &jsonObject, bool compact);
template<typename T>
QJsonArray QList2QJsonArray(const QList<T> &list);
QList<int> QJsonArray2QListInt(const QJsonArray &arr);
#define QJSONARRAY_ADD(arr, add) \
for (const auto &a: (add)) { \
(arr) += a; \
}
#define QJSONOBJECT_COPY(src, dst, key) \
if (src.contains(key)) dst[key] = src[key];
#define QJSONOBJECT_COPY2(src, dst, src_key, dst_key) \
if (src.contains(src_key)) dst[dst_key] = src[src_key];
QList<QString> QJsonArray2QListString(const QJsonArray &arr);
// Files
QByteArray ReadFile(const QString &path);
QString ReadFileText(const QString &path);
// Validators
bool IsIpAddress(const QString &str);
bool IsIpAddressV4(const QString &str);
bool IsIpAddressV6(const QString &str);
// [2001:4860:4860::8888] -> 2001:4860:4860::8888
inline QString UnwrapIPV6Host(QString &str) {
return str.replace("[", "").replace("]", "");
}
// [2001:4860:4860::8888] or 2001:4860:4860::8888 -> [2001:4860:4860::8888]
inline QString WrapIPV6Host(QString &str) {
if (!IsIpAddressV6(str)) return str;
return "[" + UnwrapIPV6Host(str) + "]";
}
inline QString DisplayAddress(QString serverAddress, int serverPort) {
if (serverAddress.isEmpty() && serverPort == 0) return {};
return WrapIPV6Host(serverAddress) + ":" + Int2String(serverPort);
};
// Format & Misc
int MkPort();
QString DisplayTime(long long time, int formatType = 0);
QString ReadableSize(const qint64 &size);
inline bool InRange(unsigned x, unsigned low, unsigned high) {
return (low <= x && x <= high);
}
inline bool IsValidPort(int port) {
return InRange(port, 1, 65535);
}
// UI
QWidget *GetMessageBoxParent();
int MessageBoxWarning(const QString &title, const QString &text);
int MessageBoxInfo(const QString &title, const QString &text);
void ActivateWindow(QWidget *w);
//
void runOnUiThread(const std::function<void()> &callback, QObject *parent = nullptr);
void runOnNewThread(const std::function<void()> &callback);
template<typename EMITTER, typename SIGNAL, typename RECEIVER, typename ReceiverFunc>
inline void connectOnce(EMITTER *emitter, SIGNAL signal, RECEIVER *receiver, ReceiverFunc f,
Qt::ConnectionType connectionType = Qt::AutoConnection) {
auto connection = std::make_shared<QMetaObject::Connection>();
auto onTriggered = [connection, f](auto... arguments) {
std::invoke(f, arguments...);
QObject::disconnect(*connection);
};
*connection = QObject::connect(emitter, signal, receiver, onTriggered, connectionType);
}
void setTimeout(const std::function<void()> &callback, QObject *obj, int timeout = 0);
| 4,729
|
C++
|
.h
| 114
| 38.850877
| 128
| 0.749835
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,736
|
Const.hpp
|
MatsuriDayo_nekoray/main/Const.hpp
|
#pragma once
namespace NekoGui {
namespace DomainMatcher {
enum DomainMatcher {
DEFAULT,
MPH,
};
}
namespace SniffingMode {
enum SniffingMode {
DISABLE,
FOR_ROUTING,
FOR_DESTINATION,
};
}
namespace CoreType {
enum CoreType {
V2RAY, // DO NOT USE
SING_BOX,
};
}
} // namespace NekoGui
| 443
|
C++
|
.h
| 22
| 11.909091
| 32
| 0.497608
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,737
|
HTTPRequestHelper.hpp
|
MatsuriDayo_nekoray/main/HTTPRequestHelper.hpp
|
#pragma once
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QObject>
#include <functional>
namespace NekoGui_network {
struct NekoHTTPResponse {
QString error;
QByteArray data;
QList<QPair<QByteArray, QByteArray>> header;
};
class NetworkRequestHelper : QObject {
Q_OBJECT
explicit NetworkRequestHelper(QObject *parent) : QObject(parent){};
~NetworkRequestHelper() override = default;
;
public:
static NekoHTTPResponse HttpGet(const QUrl &url);
static QString GetHeader(const QList<QPair<QByteArray, QByteArray>> &header, const QString &name);
};
} // namespace NekoGui_network
using namespace NekoGui_network;
| 759
|
C++
|
.h
| 23
| 27.652174
| 106
| 0.718407
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,738
|
main.cc
|
NixOS_nix/tests/functional/test-libstoreconsumer/main.cc
|
#include "globals.hh"
#include "store-api.hh"
#include "build-result.hh"
#include <iostream>
using namespace nix;
int main (int argc, char **argv)
{
try {
if (argc != 2) {
std::cerr << "Usage: " << argv[0] << " store/path/to/something.drv\n";
return 1;
}
std::string drvPath = argv[1];
initLibStore();
auto store = nix::openStore();
// build the derivation
std::vector<DerivedPath> paths {
DerivedPath::Built {
.drvPath = makeConstantStorePathRef(store->parseStorePath(drvPath)),
.outputs = OutputsSpec::Names{"out"}
}
};
const auto results = store->buildPathsWithResults(paths, bmNormal, store);
for (const auto & result : results) {
for (const auto & [outputName, realisation] : result.builtOutputs) {
std::cout << store->printStorePath(realisation.outPath) << "\n";
}
}
return 0;
} catch (const std::exception & e) {
std::cerr << "Error: " << e.what() << "\n";
return 1;
}
}
| 1,133
|
C++
|
.cc
| 34
| 24.823529
| 84
| 0.548713
|
NixOS/nix
| 12,186
| 1,472
| 3,401
|
LGPL-2.1
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,739
|
plugintest.cc
|
NixOS_nix/tests/functional/plugins/plugintest.cc
|
#include "config-global.hh"
#include "primops.hh"
using namespace nix;
struct MySettings : Config
{
Setting<bool> settingSet{this, false, "setting-set",
"Whether the plugin-defined setting was set"};
};
MySettings mySettings;
static GlobalConfig::Register rs(&mySettings);
static void prim_anotherNull (EvalState & state, const PosIdx pos, Value ** args, Value & v)
{
if (mySettings.settingSet)
v.mkNull();
else
v.mkBool(false);
}
static RegisterPrimOp rp({
.name = "anotherNull",
.arity = 0,
.fun = prim_anotherNull,
});
| 576
|
C++
|
.cc
| 22
| 22.727273
| 92
| 0.70073
|
NixOS/nix
| 12,186
| 1,472
| 3,401
|
LGPL-2.1
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
10,740
|
ls.cc
|
NixOS_nix/src/nix/ls.cc
|
#include "command.hh"
#include "store-api.hh"
#include "nar-accessor.hh"
#include "common-args.hh"
#include <nlohmann/json.hpp>
using namespace nix;
struct MixLs : virtual Args, MixJSON
{
std::string path;
bool recursive = false;
bool verbose = false;
bool showDirectory = false;
MixLs()
{
addFlag({
.longName = "recursive",
.shortName = 'R',
.description = "List subdirectories recursively.",
.handler = {&recursive, true},
});
addFlag({
.longName = "long",
.shortName = 'l',
.description = "Show detailed file information.",
.handler = {&verbose, true},
});
addFlag({
.longName = "directory",
.shortName = 'd',
.description = "Show directories rather than their contents.",
.handler = {&showDirectory, true},
});
}
void listText(ref<SourceAccessor> accessor)
{
std::function<void(const SourceAccessor::Stat &, const CanonPath &, std::string_view, bool)> doPath;
auto showFile = [&](const CanonPath & curPath, std::string_view relPath) {
if (verbose) {
auto st = accessor->lstat(curPath);
std::string tp =
st.type == SourceAccessor::Type::tRegular ?
(st.isExecutable ? "-r-xr-xr-x" : "-r--r--r--") :
st.type == SourceAccessor::Type::tSymlink ? "lrwxrwxrwx" :
"dr-xr-xr-x";
auto line = fmt("%s %20d %s", tp, st.fileSize.value_or(0), relPath);
if (st.type == SourceAccessor::Type::tSymlink)
line += " -> " + accessor->readLink(curPath);
logger->cout(line);
if (recursive && st.type == SourceAccessor::Type::tDirectory)
doPath(st, curPath, relPath, false);
} else {
logger->cout(relPath);
if (recursive) {
auto st = accessor->lstat(curPath);
if (st.type == SourceAccessor::Type::tDirectory)
doPath(st, curPath, relPath, false);
}
}
};
doPath = [&](const SourceAccessor::Stat & st, const CanonPath & curPath,
std::string_view relPath, bool showDirectory)
{
if (st.type == SourceAccessor::Type::tDirectory && !showDirectory) {
auto names = accessor->readDirectory(curPath);
for (auto & [name, type] : names)
showFile(curPath / name, relPath + "/" + name);
} else
showFile(curPath, relPath);
};
auto path2 = CanonPath(path);
auto st = accessor->lstat(path2);
doPath(st, path2,
st.type == SourceAccessor::Type::tDirectory ? "." : path2.baseName().value_or(""),
showDirectory);
}
void list(ref<SourceAccessor> accessor)
{
if (json) {
if (showDirectory)
throw UsageError("'--directory' is useless with '--json'");
logger->cout("%s", listNar(accessor, CanonPath(path), recursive));
} else
listText(accessor);
}
};
struct CmdLsStore : StoreCommand, MixLs
{
CmdLsStore()
{
expectArgs({
.label = "path",
.handler = {&path},
.completer = completePath
});
}
std::string description() override
{
return "show information about a path in the Nix store";
}
std::string doc() override
{
return
#include "store-ls.md"
;
}
void run(ref<Store> store) override
{
list(store->getFSAccessor());
}
};
struct CmdLsNar : Command, MixLs
{
Path narPath;
CmdLsNar()
{
expectArgs({
.label = "nar",
.handler = {&narPath},
.completer = completePath
});
expectArg("path", &path);
}
std::string doc() override
{
return
#include "nar-ls.md"
;
}
std::string description() override
{
return "show information about a path inside a NAR file";
}
void run() override
{
list(makeNarAccessor(readFile(narPath)));
}
};
static auto rCmdLsStore = registerCommand2<CmdLsStore>({"store", "ls"});
static auto rCmdLsNar = registerCommand2<CmdLsNar>({"nar", "ls"});
| 4,516
|
C++
|
.cc
| 139
| 22.848921
| 108
| 0.528696
|
NixOS/nix
| 12,186
| 1,472
| 3,401
|
LGPL-2.1
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
10,741
|
diff-closures.cc
|
NixOS_nix/src/nix/diff-closures.cc
|
#include "command.hh"
#include "shared.hh"
#include "store-api.hh"
#include "common-args.hh"
#include "names.hh"
#include <regex>
#include "strings.hh"
namespace nix {
struct Info
{
std::string outputName;
};
// name -> version -> store paths
typedef std::map<std::string, std::map<std::string, std::map<StorePath, Info>>> GroupedPaths;
GroupedPaths getClosureInfo(ref<Store> store, const StorePath & toplevel)
{
StorePathSet closure;
store->computeFSClosure({toplevel}, closure);
GroupedPaths groupedPaths;
for (auto const & path : closure) {
/* Strip the output name. Unfortunately this is ambiguous (we
can't distinguish between output names like "bin" and
version suffixes like "unstable"). */
static std::regex regex("(.*)-([a-z]+|lib32|lib64)");
std::cmatch match;
std::string name{path.name()};
std::string_view const origName = path.name();
std::string outputName;
if (std::regex_match(origName.begin(), origName.end(), match, regex)) {
name = match[1];
outputName = match[2];
}
DrvName drvName(name);
groupedPaths[drvName.name][drvName.version].emplace(path, Info { .outputName = outputName });
}
return groupedPaths;
}
std::string showVersions(const std::set<std::string> & versions)
{
if (versions.empty()) return "∅";
std::set<std::string> versions2;
for (auto & version : versions)
versions2.insert(version.empty() ? "ε" : version);
return concatStringsSep(", ", versions2);
}
void printClosureDiff(
ref<Store> store,
const StorePath & beforePath,
const StorePath & afterPath,
std::string_view indent)
{
auto beforeClosure = getClosureInfo(store, beforePath);
auto afterClosure = getClosureInfo(store, afterPath);
std::set<std::string> allNames;
for (auto & [name, _] : beforeClosure) allNames.insert(name);
for (auto & [name, _] : afterClosure) allNames.insert(name);
for (auto & name : allNames) {
auto & beforeVersions = beforeClosure[name];
auto & afterVersions = afterClosure[name];
auto totalSize = [&](const std::map<std::string, std::map<StorePath, Info>> & versions)
{
uint64_t sum = 0;
for (auto & [_, paths] : versions)
for (auto & [path, _] : paths)
sum += store->queryPathInfo(path)->narSize;
return sum;
};
auto beforeSize = totalSize(beforeVersions);
auto afterSize = totalSize(afterVersions);
auto sizeDelta = (int64_t) afterSize - (int64_t) beforeSize;
auto showDelta = std::abs(sizeDelta) >= 8 * 1024;
std::set<std::string> removed, unchanged;
for (auto & [version, _] : beforeVersions)
if (!afterVersions.count(version)) removed.insert(version); else unchanged.insert(version);
std::set<std::string> added;
for (auto & [version, _] : afterVersions)
if (!beforeVersions.count(version)) added.insert(version);
if (showDelta || !removed.empty() || !added.empty()) {
std::vector<std::string> items;
if (!removed.empty() || !added.empty())
items.push_back(fmt("%s → %s", showVersions(removed), showVersions(added)));
if (showDelta)
items.push_back(fmt("%s%+.1f KiB" ANSI_NORMAL, sizeDelta > 0 ? ANSI_RED : ANSI_GREEN, sizeDelta / 1024.0));
logger->cout("%s%s: %s", indent, name, concatStringsSep(", ", items));
}
}
}
}
using namespace nix;
struct CmdDiffClosures : SourceExprCommand, MixOperateOnOptions
{
std::string _before, _after;
CmdDiffClosures()
{
expectArg("before", &_before);
expectArg("after", &_after);
}
std::string description() override
{
return "show what packages and versions were added and removed between two closures";
}
std::string doc() override
{
return
#include "diff-closures.md"
;
}
void run(ref<Store> store) override
{
auto before = parseInstallable(store, _before);
auto beforePath = Installable::toStorePath(getEvalStore(), store, Realise::Outputs, operateOn, before);
auto after = parseInstallable(store, _after);
auto afterPath = Installable::toStorePath(getEvalStore(), store, Realise::Outputs, operateOn, after);
printClosureDiff(store, beforePath, afterPath, "");
}
};
static auto rCmdDiffClosures = registerCommand2<CmdDiffClosures>({"store", "diff-closures"});
| 4,621
|
C++
|
.cc
| 117
| 32.555556
| 123
| 0.634981
|
NixOS/nix
| 12,186
| 1,472
| 3,401
|
LGPL-2.1
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.