mirror of
https://github.com/v2rayA/v2rayA.git
synced 2026-11-20 23:02:25 +03:00
Merge pull request #2072 from wywywywycloud/feat/routinga-url-import
Add RoutingA import and scheduled updates from URL
This commit is contained in:
17 files changed
+732
-36
No files matched your search
+19
-3
@@ -140,9 +140,25 @@ export const postCustomInbound = (body: CustomInbound) =>
|
||||
export const deleteCustomInbound = (body: { tag: string }) =>
|
||||
call<unknown>({ url: "customInbound", method: "delete", data: body });
|
||||
export const getRoutingA = () =>
|
||||
call<{ routingA: string }>({ url: "routingA", method: "get" });
|
||||
export const putRoutingA = (body: { routingA: string }) =>
|
||||
call<unknown>({ url: "routingA", method: "put", data: body });
|
||||
call<{ routingA: string; source: RoutingASource }>({
|
||||
url: "routingA",
|
||||
method: "get",
|
||||
});
|
||||
export interface RoutingASource {
|
||||
url: string;
|
||||
directUpdate: boolean;
|
||||
intervalHours: number;
|
||||
}
|
||||
export const importRoutingAFromURL = (source: RoutingASource) =>
|
||||
call<{ routingA: string }>({
|
||||
url: "routingA/import",
|
||||
method: "post",
|
||||
data: source,
|
||||
});
|
||||
export const putRoutingA = (body: {
|
||||
routingA: string;
|
||||
source?: RoutingASource;
|
||||
}) => call<unknown>({ url: "routingA", method: "put", data: body });
|
||||
export const getDnsRules = () =>
|
||||
call<DnsRulesResponse>({ url: "dnsRules", method: "get" });
|
||||
export const putDnsRules = (body: DnsRule[]) =>
|
||||
|
||||
@@ -19,7 +19,11 @@ import RuleDialog from "./routingA/RuleDialog.vue";
|
||||
import { template } from "./routingA/template";
|
||||
import { russia } from "./routingA/russia";
|
||||
|
||||
const api = vi.hoisted(() => ({ getRoutingA: vi.fn(), putRoutingA: vi.fn() }));
|
||||
const api = vi.hoisted(() => ({
|
||||
getRoutingA: vi.fn(),
|
||||
putRoutingA: vi.fn(),
|
||||
importRoutingAFromURL: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/api", () => api);
|
||||
const rules = "default: direct\n# inbound(http, 8080)\n";
|
||||
const button = (wrapper: Pick<VueWrapper, "findAll">, label: string) =>
|
||||
@@ -40,6 +44,7 @@ beforeEach(() => {
|
||||
localStorage.clear();
|
||||
api.getRoutingA.mockReset().mockResolvedValue({ routingA: rules });
|
||||
api.putRoutingA.mockReset().mockResolvedValue(null);
|
||||
api.importRoutingAFromURL.mockReset();
|
||||
});
|
||||
afterEach(() => {
|
||||
closeAllDialogs();
|
||||
@@ -49,6 +54,78 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe("RoutingA dialog", () => {
|
||||
test("imports URL rules, previews them read-only, and saves the update schedule", async () => {
|
||||
const imported = "default: proxy\n";
|
||||
api.importRoutingAFromURL.mockResolvedValue({ routingA: imported });
|
||||
const wrapper = mountWithApp(RoutingA);
|
||||
await flushPromises();
|
||||
await button(wrapper, en.routingA.urlImport.title).trigger("click");
|
||||
await wrapper
|
||||
.get('input[type="url"]')
|
||||
.setValue("https://example.com/rules.txt");
|
||||
await button(wrapper, en.routingA.urlImport.import).trigger("click");
|
||||
await flushPromises();
|
||||
expect(api.importRoutingAFromURL).toHaveBeenCalledWith({
|
||||
url: "https://example.com/rules.txt",
|
||||
directUpdate: false,
|
||||
intervalHours: 24,
|
||||
});
|
||||
const editor = wrapper.get("textarea");
|
||||
expect(editor.element.value).toBe(imported);
|
||||
expect(editor.attributes("readonly")).toBeDefined();
|
||||
expect(wrapper.find(".routing-editor--source").exists()).toBe(true);
|
||||
await button(wrapper, en.operations.save).trigger("click");
|
||||
await flushPromises();
|
||||
expect(api.putRoutingA).toHaveBeenCalledWith({
|
||||
routingA: imported,
|
||||
source: {
|
||||
url: "https://example.com/rules.txt",
|
||||
directUpdate: false,
|
||||
intervalHours: 24,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("keeps the prior rules and shows a fetch error when URL import fails", async () => {
|
||||
api.importRoutingAFromURL.mockRejectedValue(
|
||||
new Error("invalid RoutingA rules"),
|
||||
);
|
||||
const wrapper = mountWithApp(RoutingA);
|
||||
await flushPromises();
|
||||
await button(wrapper, en.routingA.urlImport.title).trigger("click");
|
||||
await wrapper.get('input[type="url"]').setValue("https://example.com/page");
|
||||
await button(wrapper, en.routingA.urlImport.import).trigger("click");
|
||||
await flushPromises();
|
||||
expect(wrapper.get("textarea").element.value).toBe(rules);
|
||||
expect(wrapper.get('[data-testid="routing-error"]').text()).toContain(
|
||||
"invalid RoutingA rules",
|
||||
);
|
||||
expect(api.putRoutingA).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("shows import progress until validation finishes", async () => {
|
||||
let finish!: (result: { routingA: string }) => void;
|
||||
api.importRoutingAFromURL.mockReturnValue(
|
||||
new Promise((resolve) => {
|
||||
finish = resolve;
|
||||
}),
|
||||
);
|
||||
const wrapper = mountWithApp(RoutingA);
|
||||
await flushPromises();
|
||||
await button(wrapper, en.routingA.urlImport.title).trigger("click");
|
||||
await wrapper.get('input[type="url"]').setValue("https://example.com/rules.txt");
|
||||
await button(wrapper, en.routingA.urlImport.import).trigger("click");
|
||||
expect(button(wrapper, en.routingA.urlImport.import).classes()).toContain(
|
||||
"v-btn--loading",
|
||||
);
|
||||
expect(button(wrapper, en.operations.save).attributes("disabled")).toBeDefined();
|
||||
finish({ routingA: "default: proxy\n" });
|
||||
await flushPromises();
|
||||
expect(button(wrapper, en.routingA.urlImport.import).classes()).not.toContain(
|
||||
"v-btn--loading",
|
||||
);
|
||||
});
|
||||
|
||||
test("offers the Russia rule set as a confirmed replacement", async () => {
|
||||
const wrapper = mountWithApp(RoutingA);
|
||||
await flushPromises();
|
||||
|
||||
@@ -8,8 +8,15 @@ import {
|
||||
mdiFormSelect,
|
||||
mdiMenuDown,
|
||||
mdiOpenInNew,
|
||||
mdiLinkVariant,
|
||||
mdiHelpCircleOutline,
|
||||
} from "@mdi/js";
|
||||
import { getRoutingA, putRoutingA } from "@/api";
|
||||
import {
|
||||
getRoutingA,
|
||||
importRoutingAFromURL,
|
||||
putRoutingA,
|
||||
type RoutingASource,
|
||||
} from "@/api";
|
||||
import { errorText } from "@/api/errors";
|
||||
import { useConfirm, useNotify, useUnsavedGuard } from "@/composables";
|
||||
import RoutingEditor from "./routingA/RoutingEditor.vue";
|
||||
@@ -36,7 +43,27 @@ const confirm = useConfirm();
|
||||
const notify = useNotify();
|
||||
const routingA = ref("");
|
||||
const original = ref("");
|
||||
useUnsavedGuard(() => routingA.value !== original.value);
|
||||
const url = ref("");
|
||||
const directUpdate = ref(false);
|
||||
const intervalHours = ref(24);
|
||||
const validatedURL = ref("");
|
||||
const originalSource = ref<RoutingASource>({
|
||||
url: "",
|
||||
directUpdate: false,
|
||||
intervalHours: 24,
|
||||
});
|
||||
const importing = ref(false);
|
||||
const instructions = ref(false);
|
||||
const source = computed<RoutingASource>(() => ({
|
||||
url: view.value === "url" ? url.value.trim() : "",
|
||||
directUpdate: directUpdate.value,
|
||||
intervalHours: Number(intervalHours.value),
|
||||
}));
|
||||
useUnsavedGuard(
|
||||
() =>
|
||||
routingA.value !== original.value ||
|
||||
JSON.stringify(source.value) !== JSON.stringify(originalSource.value),
|
||||
);
|
||||
const loading = ref(true);
|
||||
const saving = ref(false);
|
||||
const confirming = ref(false);
|
||||
@@ -46,7 +73,7 @@ const editor = ref<InstanceType<typeof RoutingEditor>>();
|
||||
const referenceId = useId();
|
||||
const wide = computed(() => width.value >= 840);
|
||||
const referencePreference = ref<string | null>(null);
|
||||
const view = ref<"form" | "text">("form");
|
||||
const view = ref<"form" | "text" | "url">("form");
|
||||
const picker = ref<HTMLInputElement>();
|
||||
try {
|
||||
referencePreference.value = localStorage.getItem("routingA.reference");
|
||||
@@ -62,7 +89,9 @@ const showReference = computed(() =>
|
||||
const hasInboundDef = computed(() =>
|
||||
routingA.value.split("\n").some((line) => /^\s*inbound\s*\(/.test(line)),
|
||||
);
|
||||
const busy = computed(() => loading.value || saving.value || confirming.value);
|
||||
const busy = computed(
|
||||
() => loading.value || saving.value || confirming.value || importing.value,
|
||||
);
|
||||
watch(routingA, () => {
|
||||
backendError.value = "";
|
||||
warningDismissed.value = false;
|
||||
@@ -135,6 +164,20 @@ async function importRules(event: Event) {
|
||||
confirming.value = false;
|
||||
}
|
||||
}
|
||||
async function importFromURL() {
|
||||
if (busy.value || !url.value.trim()) return;
|
||||
importing.value = true;
|
||||
backendError.value = "";
|
||||
try {
|
||||
const result = await importRoutingAFromURL(source.value);
|
||||
routingA.value = result.routingA;
|
||||
validatedURL.value = url.value.trim();
|
||||
} catch (err) {
|
||||
backendError.value = errorText(err);
|
||||
} finally {
|
||||
importing.value = false;
|
||||
}
|
||||
}
|
||||
function toggleReference() {
|
||||
referencePreference.value = String(!showReference.value);
|
||||
try {
|
||||
@@ -147,6 +190,16 @@ onMounted(async () => {
|
||||
try {
|
||||
const res = await getRoutingA();
|
||||
routingA.value = original.value = res.routingA;
|
||||
const saved = res.source ?? {
|
||||
url: "",
|
||||
directUpdate: false,
|
||||
intervalHours: 24,
|
||||
};
|
||||
originalSource.value = saved;
|
||||
url.value = validatedURL.value = saved.url;
|
||||
directUpdate.value = saved.directUpdate;
|
||||
intervalHours.value = saved.intervalHours;
|
||||
if (saved.url) view.value = "url";
|
||||
} catch (err) {
|
||||
notify.warning(errorText(err));
|
||||
emit("close");
|
||||
@@ -159,7 +212,9 @@ async function close() {
|
||||
confirming.value = true;
|
||||
try {
|
||||
if (
|
||||
routingA.value !== original.value &&
|
||||
(routingA.value !== original.value ||
|
||||
JSON.stringify(source.value) !==
|
||||
JSON.stringify(originalSource.value)) &&
|
||||
!(await confirm({
|
||||
message: t("routingA.discard"),
|
||||
confirmText: t("operations.confirm"),
|
||||
@@ -190,6 +245,16 @@ async function reset() {
|
||||
}
|
||||
async function save() {
|
||||
if (busy.value) return;
|
||||
if (
|
||||
view.value === "url" &&
|
||||
(url.value.trim() !== validatedURL.value ||
|
||||
!Number.isInteger(Number(intervalHours.value)) ||
|
||||
Number(intervalHours.value) < 1 ||
|
||||
Number(intervalHours.value) > 8760)
|
||||
) {
|
||||
backendError.value = t("routingA.urlImport.importFirst");
|
||||
return;
|
||||
}
|
||||
saving.value = true;
|
||||
try {
|
||||
if (
|
||||
@@ -201,7 +266,11 @@ async function save() {
|
||||
}))
|
||||
)
|
||||
return;
|
||||
const res = await putRoutingA({ routingA: routingA.value });
|
||||
const res = await putRoutingA(
|
||||
view.value === "url" || originalSource.value.url
|
||||
? { routingA: routingA.value, source: source.value }
|
||||
: { routingA: routingA.value },
|
||||
);
|
||||
if (res && typeof res === "object" && "warning" in res && res.warning) {
|
||||
notify.warning(t("routingA.savedWithWarning", { warning: res.warning }), {
|
||||
timeout: 8000,
|
||||
@@ -218,7 +287,7 @@ async function save() {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<v-card>
|
||||
<v-card class="routing-card">
|
||||
<v-card-item class="routing-title px-6 pt-6 pb-4">
|
||||
<v-card-title class="md3-headline-small pa-0">{{
|
||||
t("routingA.title")
|
||||
@@ -245,6 +314,9 @@ async function save() {
|
||||
:aria-label="t('routingA.form.text')"
|
||||
:title="t('routingA.form.text')"
|
||||
/>
|
||||
<v-btn value="url" :prepend-icon="mdiLinkVariant" :disabled="busy">{{
|
||||
t("routingA.urlImport.title")
|
||||
}}</v-btn>
|
||||
</v-btn-toggle>
|
||||
<v-menu>
|
||||
<template #activator="{ props: menu }">
|
||||
@@ -291,6 +363,65 @@ async function save() {
|
||||
</template>
|
||||
</v-card-item>
|
||||
<v-card-text class="px-6">
|
||||
<template v-if="view === 'url'">
|
||||
<div class="routing-url-row mb-3">
|
||||
<v-text-field
|
||||
v-model="url"
|
||||
type="url"
|
||||
variant="outlined"
|
||||
density="comfortable"
|
||||
hide-details
|
||||
:label="t('routingA.urlImport.url')"
|
||||
:disabled="busy"
|
||||
@update:model-value="backendError = ''"
|
||||
@keydown.enter="importFromURL"
|
||||
/>
|
||||
<v-btn
|
||||
color="primary"
|
||||
variant="flat"
|
||||
:loading="importing"
|
||||
:disabled="busy || !url.trim()"
|
||||
@click="importFromURL"
|
||||
>{{ t("routingA.urlImport.import") }}</v-btn
|
||||
>
|
||||
</div>
|
||||
<div class="routing-url-options mb-4">
|
||||
<v-switch
|
||||
v-model="directUpdate"
|
||||
color="primary"
|
||||
hide-details
|
||||
:label="t('routingA.urlImport.direct')"
|
||||
:disabled="busy"
|
||||
/>
|
||||
<v-tooltip :text="t('routingA.urlImport.directHelp')">
|
||||
<template #activator="{ props: tip }">
|
||||
<v-btn
|
||||
v-bind="tip"
|
||||
:icon="mdiHelpCircleOutline"
|
||||
variant="text"
|
||||
size="small"
|
||||
:aria-label="t('routingA.urlImport.directHelp')"
|
||||
/>
|
||||
</template>
|
||||
</v-tooltip>
|
||||
<v-text-field
|
||||
v-model.number="intervalHours"
|
||||
type="number"
|
||||
min="1"
|
||||
max="8760"
|
||||
step="1"
|
||||
variant="outlined"
|
||||
density="compact"
|
||||
hide-details
|
||||
class="routing-url-interval"
|
||||
:label="t('routingA.urlImport.interval')"
|
||||
:disabled="busy"
|
||||
/>
|
||||
<v-btn variant="text" @click="instructions = true">{{
|
||||
t("routingA.urlImport.instructions")
|
||||
}}</v-btn>
|
||||
</div>
|
||||
</template>
|
||||
<v-alert
|
||||
v-if="hasInboundDef && !warningDismissed"
|
||||
type="warning"
|
||||
@@ -322,7 +453,8 @@ async function save() {
|
||||
ref="editor"
|
||||
v-model="routingA"
|
||||
:disabled="loading"
|
||||
:readonly="saving || confirming"
|
||||
:readonly="saving || confirming || view === 'url'"
|
||||
:source-preview="view === 'url'"
|
||||
@save="save"
|
||||
/>
|
||||
<v-expand-transition>
|
||||
@@ -379,15 +511,36 @@ async function save() {
|
||||
color="primary"
|
||||
variant="flat"
|
||||
:loading="saving"
|
||||
:disabled="loading || confirming"
|
||||
:disabled="
|
||||
loading ||
|
||||
confirming ||
|
||||
importing ||
|
||||
(view === 'url' && url.trim() !== validatedURL)
|
||||
"
|
||||
@click="save"
|
||||
>{{ t("operations.save") }}</v-btn
|
||||
>
|
||||
</v-card-actions>
|
||||
<v-dialog v-model="instructions" max-width="520">
|
||||
<v-card :title="t('routingA.urlImport.instructions')">
|
||||
<v-card-text>{{
|
||||
t("routingA.urlImport.instructionsText")
|
||||
}}</v-card-text>
|
||||
<v-card-actions
|
||||
><v-spacer /><v-btn variant="text" @click="instructions = false">{{
|
||||
t("operations.close")
|
||||
}}</v-btn></v-card-actions
|
||||
>
|
||||
</v-card>
|
||||
</v-dialog>
|
||||
</v-card>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.routing-card {
|
||||
max-height: 95vh;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.routing-layout {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
@@ -402,15 +555,53 @@ async function save() {
|
||||
overflow-wrap: anywhere;
|
||||
font-family: ui-monospace, "Cascadia Mono", "Fira Mono", Menlo, monospace;
|
||||
}
|
||||
@media (max-width: 599px) {
|
||||
.routing-url-row,
|
||||
.routing-url-options {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
.routing-url-row :deep(.v-input) {
|
||||
flex: 1 1 320px;
|
||||
}
|
||||
.routing-url-options :deep(.v-switch) {
|
||||
flex: 0 1 auto;
|
||||
}
|
||||
.routing-url-interval {
|
||||
flex: 0 0 160px;
|
||||
}
|
||||
@media (max-width: 839px) {
|
||||
.routing-card {
|
||||
max-height: 90vh;
|
||||
}
|
||||
.routing-card :deep(.v-card-text) {
|
||||
flex: 0 0 auto;
|
||||
overflow: visible;
|
||||
}
|
||||
.routing-title {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
.routing-title :deep(.v-card-item__append) {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-start;
|
||||
gap: 4px;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
flex: 1 1 100%;
|
||||
padding-inline-start: 0;
|
||||
margin-inline-start: auto;
|
||||
margin-inline-start: 0;
|
||||
}
|
||||
.routing-title :deep(.v-card-item__content) {
|
||||
flex: 1 1 100%;
|
||||
}
|
||||
.routing-layout :deep(.routing-editor) {
|
||||
height: 40vh;
|
||||
min-height: 220px;
|
||||
max-height: none;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -9,6 +9,7 @@ const props = defineProps<{
|
||||
modelValue: string;
|
||||
disabled?: boolean;
|
||||
readonly?: boolean;
|
||||
sourcePreview?: boolean;
|
||||
}>();
|
||||
const emit = defineEmits<{ "update:modelValue": [value: string]; save: [] }>();
|
||||
const { t } = useI18n();
|
||||
@@ -110,6 +111,7 @@ defineExpose({ insert });
|
||||
<template>
|
||||
<v-sheet
|
||||
class="routing-editor"
|
||||
:class="{ 'routing-editor--source': sourcePreview }"
|
||||
rounded="lg"
|
||||
color="surface-container-lowest"
|
||||
dir="ltr"
|
||||
@@ -188,6 +190,12 @@ defineExpose({ insert });
|
||||
border-color: rgb(var(--v-theme-primary));
|
||||
box-shadow: inset 0 0 0 1px rgb(var(--v-theme-primary));
|
||||
}
|
||||
.routing-editor--source {
|
||||
background: rgb(var(--v-theme-surface-container)) !important;
|
||||
}
|
||||
.routing-editor--source .routing-editor__input {
|
||||
cursor: text;
|
||||
}
|
||||
.routing-editor__gutter {
|
||||
overflow: hidden;
|
||||
padding: 16px 8px 32px;
|
||||
|
||||
@@ -489,6 +489,20 @@ export default {
|
||||
title: "Import",
|
||||
confirm: "Replace the current rules with the imported file?",
|
||||
},
|
||||
urlImport: {
|
||||
title: "Import from URL",
|
||||
url: "Raw rules URL",
|
||||
import: "Import",
|
||||
direct: "Always update without proxy",
|
||||
directHelp:
|
||||
"When off, URL updates use the rule port and require the core to be running. When on, they bypass the proxy.",
|
||||
interval: "Update every (hours)",
|
||||
instructions: "Instructions",
|
||||
instructionsText:
|
||||
"Enter an HTTP or HTTPS link to a raw text file containing RoutingA syntax. HTML pages, downloads and invalid rules are rejected. Import the file, review the read-only preview, then save. The source is checked automatically at the chosen interval.",
|
||||
importFirst:
|
||||
"Import a valid URL and enter an update interval between 1 and 8760 hours before saving.",
|
||||
},
|
||||
form: {
|
||||
title: "Form",
|
||||
text: "Text",
|
||||
|
||||
@@ -484,6 +484,20 @@ export default {
|
||||
title: "درونریزی",
|
||||
confirm: "قوانین فعلی با محتوای فایل واردشده جایگزین شوند؟",
|
||||
},
|
||||
urlImport: {
|
||||
title: "درونریزی از URL",
|
||||
url: "نشانی فایل خام قوانین",
|
||||
import: "درونریزی",
|
||||
direct: "همیشه بدون پروکسی بهروزرسانی شود",
|
||||
directHelp:
|
||||
"وقتی خاموش است، بهروزرسانی از درگاه قوانین انجام میشود و هسته باید فعال باشد؛ وقتی روشن است، پروکسی دور زده میشود.",
|
||||
interval: "فاصلهٔ بهروزرسانی (ساعت)",
|
||||
instructions: "راهنما",
|
||||
instructionsText:
|
||||
"پیوند HTTP یا HTTPS به فایل متنی خام با نحو RoutingA را وارد کنید. صفحات HTML، دانلودها و قوانین نامعتبر رد میشوند. فایل را وارد کنید، پیشنمایش فقطخواندنی را بررسی و ذخیره کنید. منبع در فاصلهٔ تعیینشده خودکار بهروزرسانی میشود.",
|
||||
importFirst:
|
||||
"پیش از ذخیره، URL معتبر را وارد کنید و فاصلهای بین ۱ تا ۸۷۶۰ ساعت تعیین کنید.",
|
||||
},
|
||||
form: {
|
||||
title: "فرم",
|
||||
text: "متن",
|
||||
|
||||
@@ -481,6 +481,20 @@ export default {
|
||||
title: "가져오기",
|
||||
confirm: "현재 규칙을 가져온 파일의 내용으로 바꾸시겠습니까?",
|
||||
},
|
||||
urlImport: {
|
||||
title: "URL에서 가져오기",
|
||||
url: "원본 규칙 파일 URL",
|
||||
import: "가져오기",
|
||||
direct: "항상 프록시를 거치지 않고 업데이트",
|
||||
directHelp:
|
||||
"끄면 URL 업데이트가 규칙 포트를 사용하며 코어가 실행 중이어야 합니다. 켜면 프록시를 우회합니다.",
|
||||
interval: "업데이트 간격(시간)",
|
||||
instructions: "안내",
|
||||
instructionsText:
|
||||
"RoutingA 구문이 담긴 원본 텍스트 파일의 HTTP 또는 HTTPS 링크를 입력하세요. HTML 페이지, 다운로드 및 잘못된 규칙은 거부됩니다. 가져온 뒤 읽기 전용 미리보기를 확인하고 저장하세요. 지정한 간격으로 자동 업데이트됩니다.",
|
||||
importFirst:
|
||||
"저장하기 전에 유효한 URL을 가져오고 업데이트 간격을 1~8760시간으로 설정하세요.",
|
||||
},
|
||||
form: {
|
||||
title: "양식",
|
||||
text: "텍스트",
|
||||
|
||||
@@ -493,6 +493,20 @@ export default {
|
||||
confirm:
|
||||
"Substituir as regras atuais pelo conteúdo do arquivo importado?",
|
||||
},
|
||||
urlImport: {
|
||||
title: "Importar de URL",
|
||||
url: "URL do arquivo bruto de regras",
|
||||
import: "Importar",
|
||||
direct: "Sempre atualizar sem proxy",
|
||||
directHelp:
|
||||
"Desativado: as atualizações pela URL usam a porta de regras e exigem que o núcleo esteja em execução. Ativado: ignoram o proxy.",
|
||||
interval: "Intervalo (horas)",
|
||||
instructions: "Instruções",
|
||||
instructionsText:
|
||||
"Informe um link HTTP ou HTTPS para um arquivo de texto bruto com sintaxe RoutingA. Páginas HTML, downloads e regras inválidas são rejeitados. Importe, confira a prévia somente leitura e salve. A fonte é atualizada automaticamente no intervalo escolhido.",
|
||||
importFirst:
|
||||
"Antes de salvar, importe uma URL válida e defina um intervalo de 1 a 8760 horas.",
|
||||
},
|
||||
form: {
|
||||
title: "Formulário",
|
||||
text: "Texto",
|
||||
|
||||
@@ -488,6 +488,20 @@ export default {
|
||||
title: "Импорт",
|
||||
confirm: "Заменить текущие правила содержимым импортируемого файла?",
|
||||
},
|
||||
urlImport: {
|
||||
title: "Импорт из URL",
|
||||
url: "URL raw-файла с правилами",
|
||||
import: "Импорт",
|
||||
direct: "Всегда обновлять мимо прокси",
|
||||
directHelp:
|
||||
"Когда выключено, обновление из URL идёт через порт правил; ядро должно работать. Когда включено — в обход прокси.",
|
||||
interval: "Интервал (часы)",
|
||||
instructions: "Инструкция",
|
||||
instructionsText:
|
||||
"Укажите HTTP- или HTTPS-ссылку на raw-текстовый файл с синтаксисом RoutingA. HTML-страницы, загрузки и некорректные правила отклоняются. Импортируйте файл, проверьте содержимое в поле только для чтения и сохраните. Источник обновляется автоматически с указанным интервалом.",
|
||||
importFirst:
|
||||
"Перед сохранением импортируйте корректный URL и укажите интервал от 1 до 8760 часов.",
|
||||
},
|
||||
form: {
|
||||
title: "Форма",
|
||||
text: "Текст",
|
||||
|
||||
@@ -472,6 +472,19 @@ export default {
|
||||
title: "导入",
|
||||
confirm: "将当前规则替换为导入文件的内容?",
|
||||
},
|
||||
urlImport: {
|
||||
title: "从 URL 导入",
|
||||
url: "原始规则文件 URL",
|
||||
import: "导入",
|
||||
direct: "始终绕过代理更新",
|
||||
directHelp:
|
||||
"关闭时,URL 更新通过规则端口,且需要运行内核;开启时绕过代理。",
|
||||
interval: "更新间隔(小时)",
|
||||
instructions: "说明",
|
||||
instructionsText:
|
||||
"输入包含 RoutingA 语法的原始文本文件的 HTTP 或 HTTPS 链接。HTML 页面、下载文件和无效规则会被拒绝。导入后检查只读预览并保存;系统会按指定间隔自动更新。",
|
||||
importFirst: "保存前请导入有效 URL,并设置 1 至 8760 小时的更新间隔。",
|
||||
},
|
||||
form: {
|
||||
title: "表单",
|
||||
text: "文本",
|
||||
|
||||
@@ -78,6 +78,7 @@ type Configure struct {
|
||||
Ports Ports `json:"ports"`
|
||||
DnsRules []DnsRule `json:"dnsRules"`
|
||||
RoutingA *string `json:"routingA"`
|
||||
RoutingASource RoutingASource `json:"routingASource"`
|
||||
DomainsExcluded *string `json:"domainsExcluded"`
|
||||
TproxyWhiteIpGroups TproxyWhiteIpGroups `json:"tproxyWhiteIpGroups"`
|
||||
}
|
||||
@@ -145,6 +146,9 @@ func SetConfigure(cfg *Configure) error {
|
||||
if err := SetRoutingA(cfg.RoutingA); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := SetRoutingASource(cfg.RoutingASource); err != nil {
|
||||
return err
|
||||
}
|
||||
if cfg.DnsRules != nil {
|
||||
if err := SetDnsRules(cfg.DnsRules); err != nil {
|
||||
return err
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package configure
|
||||
|
||||
import "github.com/v2rayA/v2rayA/db"
|
||||
|
||||
type RoutingASource struct {
|
||||
URL string `json:"url"`
|
||||
DirectUpdate bool `json:"directUpdate"`
|
||||
IntervalHours int `json:"intervalHours"`
|
||||
}
|
||||
|
||||
func GetRoutingASource() (source RoutingASource) {
|
||||
_ = db.Get("system", "routingASource", &source)
|
||||
if source.IntervalHours <= 0 {
|
||||
source.IntervalHours = 24
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func SetRoutingASource(source RoutingASource) error {
|
||||
return db.Set("system", "routingASource", source)
|
||||
}
|
||||
@@ -79,6 +79,27 @@ func initUpdatingTicker() {
|
||||
updateSubscriptions()
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
ticker := time.NewTicker(time.Minute)
|
||||
defer ticker.Stop()
|
||||
var previous configure.RoutingASource
|
||||
var lastAttempt time.Time
|
||||
for range ticker.C {
|
||||
source := configure.GetRoutingASource()
|
||||
if source.URL == "" {
|
||||
previous = source
|
||||
continue
|
||||
}
|
||||
if source == previous && time.Since(lastAttempt) < configure.IntervalHours(source.IntervalHours) {
|
||||
continue
|
||||
}
|
||||
previous = source
|
||||
lastAttempt = time.Now()
|
||||
if err := service.UpdateRoutingAFromSource(); err != nil {
|
||||
log.Warn("[AutoUpdate] RoutingA: %v", err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func checkUpdate() {
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/v2rayA/RoutingA"
|
||||
"github.com/v2rayA/v2rayA/common"
|
||||
"github.com/v2rayA/v2rayA/db/configure"
|
||||
"github.com/v2rayA/v2rayA/server/service"
|
||||
@@ -15,8 +12,22 @@ import (
|
||||
func GetRoutingA(ctx *gin.Context) {
|
||||
common.ResponseSuccess(ctx, gin.H{
|
||||
"routingA": configure.GetRoutingA(),
|
||||
"source": configure.GetRoutingASource(),
|
||||
})
|
||||
}
|
||||
func PostRoutingAImport(ctx *gin.Context) {
|
||||
var source configure.RoutingASource
|
||||
if err := ctx.ShouldBindJSON(&source); err != nil {
|
||||
common.ResponseError(ctx, badRequest("source", "invalid RoutingA source"))
|
||||
return
|
||||
}
|
||||
text, err := service.FetchRoutingA(source)
|
||||
if err != nil {
|
||||
common.ResponseError(ctx, logError(err))
|
||||
return
|
||||
}
|
||||
common.ResponseSuccess(ctx, gin.H{"routingA": text})
|
||||
}
|
||||
func PutRoutingA(ctx *gin.Context) {
|
||||
release, ok := beginMutation(ctx)
|
||||
if !ok {
|
||||
@@ -24,25 +35,31 @@ func PutRoutingA(ctx *gin.Context) {
|
||||
}
|
||||
defer release()
|
||||
var data struct {
|
||||
RoutingA string `json:"routingA"`
|
||||
RoutingA string `json:"routingA"`
|
||||
Source configure.RoutingASource `json:"source"`
|
||||
}
|
||||
err := ctx.ShouldBindJSON(&data)
|
||||
if err != nil {
|
||||
common.ResponseError(ctx, badRequest("routingA", "request body must be {\"routingA\": string}"))
|
||||
return
|
||||
}
|
||||
// remove hardcode replacement and try parsing
|
||||
lines := strings.Split(data.RoutingA, "\n")
|
||||
hardcodeReplacement := regexp.MustCompile(`\$\$.+?\$\$`)
|
||||
for i := range lines {
|
||||
hardcodes := hardcodeReplacement.FindAllString(lines[i], -1)
|
||||
for _, hardcode := range hardcodes {
|
||||
lines[i] = strings.Replace(lines[i], hardcode, "", 1)
|
||||
}
|
||||
if data.Source.URL != "" && (data.Source.IntervalHours < 1 || data.Source.IntervalHours > 8760) {
|
||||
common.ResponseError(ctx, badRequest("intervalHours", "RoutingA update interval must be between 1 and 8760 hours"))
|
||||
return
|
||||
}
|
||||
_, err = RoutingA.Parse(strings.Join(lines, "\n"))
|
||||
if err != nil {
|
||||
common.ResponseError(ctx, logError(fmt.Errorf("invalid RoutingA rules: %w", err)))
|
||||
if data.Source.URL != "" {
|
||||
if err := service.ValidateRoutingASource(data.Source); err != nil {
|
||||
common.ResponseError(ctx, badRequest("source", err))
|
||||
return
|
||||
}
|
||||
data.Source.URL = strings.TrimSpace(data.Source.URL)
|
||||
}
|
||||
if data.Source.URL == "" {
|
||||
data.Source = configure.RoutingASource{IntervalHours: 24}
|
||||
}
|
||||
lines := strings.Split(data.RoutingA, "\n")
|
||||
if err := service.ValidateRoutingA(data.RoutingA); err != nil {
|
||||
common.ResponseError(ctx, logError(err))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -56,12 +73,7 @@ func PutRoutingA(ctx *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
err = service.ApplyCoreConfig(func() func() error {
|
||||
previous := configure.GetRoutingA()
|
||||
return func() error { return configure.SetRoutingA(&previous) }
|
||||
}, func() error {
|
||||
return configure.SetRoutingA(&data.RoutingA)
|
||||
})
|
||||
err = service.SaveRoutingA(data.RoutingA, data.Source)
|
||||
if err != nil {
|
||||
common.ResponseError(ctx, logError(err))
|
||||
return
|
||||
|
||||
@@ -298,6 +298,7 @@ func Run() error {
|
||||
auth.GET("dnsRules", controller.GetDnsRules)
|
||||
auth.PUT("dnsRules", controller.PutDnsRules)
|
||||
auth.GET("routingA", controller.GetRoutingA)
|
||||
auth.POST("routingA/import", controller.PostRoutingAImport)
|
||||
auth.GET("params", controller.GetParams)
|
||||
auth.PUT("routingA", controller.PutRoutingA)
|
||||
auth.GET("outbounds", controller.GetOutbounds)
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/v2rayA/RoutingA"
|
||||
"github.com/v2rayA/v2rayA/common/httpClient"
|
||||
"github.com/v2rayA/v2rayA/conf"
|
||||
"github.com/v2rayA/v2rayA/db/configure"
|
||||
"github.com/v2rayA/v2rayA/kernel/v2ray"
|
||||
)
|
||||
|
||||
const maxRoutingASourceBytes = 1024 * 1024
|
||||
|
||||
var routingAUpdate sync.Mutex
|
||||
var hardcodeReplacement = regexp.MustCompile(`\$\$.+?\$\$`)
|
||||
|
||||
func ValidateRoutingA(text string) error {
|
||||
_, err := parseRoutingA(text)
|
||||
return err
|
||||
}
|
||||
|
||||
func parseRoutingA(text string) (int, error) {
|
||||
lines := strings.Split(text, "\n")
|
||||
for i := range lines {
|
||||
lines[i] = hardcodeReplacement.ReplaceAllString(lines[i], "")
|
||||
}
|
||||
parsed, err := RoutingA.Parse(strings.Join(lines, "\n"))
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("invalid RoutingA rules: %w", err)
|
||||
}
|
||||
return len(parsed), nil
|
||||
}
|
||||
|
||||
func routingAClient(direct bool) (*http.Client, error) {
|
||||
var client *http.Client
|
||||
if direct {
|
||||
client = &http.Client{Transport: &http.Transport{
|
||||
DialContext: httpClient.DirectDialer(10*time.Second, v2ray.IsTransparentOn(configure.GetSettingNotNil())).DialContext,
|
||||
}}
|
||||
} else {
|
||||
var err error
|
||||
client, err = httpClient.GetHttpClientWithv2rayAPac()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
client.Timeout = 30 * time.Second
|
||||
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
|
||||
if len(via) >= 5 || (req.URL.Scheme != "https" && req.URL.Scheme != "http") {
|
||||
return fmt.Errorf("invalid redirect from RoutingA URL")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func ValidateRoutingASource(source configure.RoutingASource) error {
|
||||
u, err := url.Parse(strings.TrimSpace(source.URL))
|
||||
if err != nil || u.Hostname() == "" || u.User != nil || (u.Scheme != "https" && u.Scheme != "http") {
|
||||
return fmt.Errorf("enter an HTTP or HTTPS URL to a raw RoutingA text file")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func FetchRoutingA(source configure.RoutingASource) (string, error) {
|
||||
if err := ValidateRoutingASource(source); err != nil {
|
||||
return "", err
|
||||
}
|
||||
u, _ := url.Parse(strings.TrimSpace(source.URL))
|
||||
client, err := routingAClient(source.DirectUpdate)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
req, err := http.NewRequest(http.MethodGet, u.String(), nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
req.Header.Set("User-Agent", "v2rayA/"+conf.Version+" RoutingA")
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("could not fetch RoutingA URL: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("RoutingA URL returned %s", resp.Status)
|
||||
}
|
||||
if resp.ContentLength > maxRoutingASourceBytes {
|
||||
return "", fmt.Errorf("RoutingA file exceeds 1 MiB")
|
||||
}
|
||||
if disposition := resp.Header.Get("Content-Disposition"); disposition != "" {
|
||||
kind, _, err := mime.ParseMediaType(disposition)
|
||||
if err != nil || kind == "attachment" {
|
||||
return "", fmt.Errorf("RoutingA URL must return raw text, not a download")
|
||||
}
|
||||
}
|
||||
if contentType := resp.Header.Get("Content-Type"); contentType != "" {
|
||||
mediaType, _, err := mime.ParseMediaType(contentType)
|
||||
if err != nil || (mediaType != "text/plain" && mediaType != "application/octet-stream") {
|
||||
return "", fmt.Errorf("RoutingA URL must return a raw text file")
|
||||
}
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, maxRoutingASourceBytes+1))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(body) > maxRoutingASourceBytes {
|
||||
return "", fmt.Errorf("RoutingA file exceeds 1 MiB")
|
||||
}
|
||||
if strings.HasPrefix(http.DetectContentType(body), "text/html") {
|
||||
return "", fmt.Errorf("RoutingA URL returned an HTML page, not raw rules")
|
||||
}
|
||||
text := strings.TrimPrefix(string(body), "\ufeff")
|
||||
if !utf8.ValidString(text) || strings.ContainsRune(text, 0) || strings.TrimSpace(text) == "" {
|
||||
return "", fmt.Errorf("RoutingA URL must contain UTF-8 rules")
|
||||
}
|
||||
rules, err := parseRoutingA(text)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if rules == 0 {
|
||||
return "", fmt.Errorf("invalid RoutingA rules: no rules found")
|
||||
}
|
||||
return text, nil
|
||||
}
|
||||
|
||||
func SaveRoutingA(text string, source configure.RoutingASource) error {
|
||||
routingAUpdate.Lock()
|
||||
defer routingAUpdate.Unlock()
|
||||
var previous string
|
||||
return ApplyCoreConfig(func() func() error {
|
||||
previous = configure.GetRoutingA()
|
||||
previousSource := configure.GetRoutingASource()
|
||||
return func() error {
|
||||
if err := configure.SetRoutingA(&previous); err != nil {
|
||||
return err
|
||||
}
|
||||
return configure.SetRoutingASource(previousSource)
|
||||
}
|
||||
}, func() error {
|
||||
if err := configure.SetRoutingA(&text); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := configure.SetRoutingASource(source); err != nil {
|
||||
_ = configure.SetRoutingA(&previous)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateRoutingAFromSource() error {
|
||||
source := configure.GetRoutingASource()
|
||||
if source.URL == "" {
|
||||
return nil
|
||||
}
|
||||
text, err := FetchRoutingA(source)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
routingAUpdate.Lock()
|
||||
defer routingAUpdate.Unlock()
|
||||
if configure.GetRoutingASource() != source || configure.GetRoutingA() == text {
|
||||
return nil
|
||||
}
|
||||
return ApplyCoreConfig(func() func() error {
|
||||
previous := configure.GetRoutingA()
|
||||
return func() error { return configure.SetRoutingA(&previous) }
|
||||
}, func() error { return configure.SetRoutingA(&text) })
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/v2rayA/v2rayA/db/configure"
|
||||
)
|
||||
|
||||
func TestFetchRoutingA(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
contentType string
|
||||
disposition string
|
||||
body string
|
||||
wantError string
|
||||
}{
|
||||
{"valid", "text/plain; charset=utf-8", "", "default: direct\ndomain(domain: example.com) -> proxy\n", ""},
|
||||
{"html", "text/html", "", "<html>default: direct</html>", "raw text"},
|
||||
{"download", "text/plain", "attachment; filename=rules.txt", "default: direct", "not a download"},
|
||||
{"invalid", "text/plain", "", "not RoutingA syntax", "invalid RoutingA"},
|
||||
{"comments", "text/plain", "", "# no rules\n", "no rules found"},
|
||||
{"binary", "application/octet-stream", "", "default: direct\x00", "UTF-8 rules"},
|
||||
{"too large", "text/plain", "", strings.Repeat("# comment\n", 120000), "exceeds 1 MiB"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", tt.contentType)
|
||||
if tt.disposition != "" {
|
||||
w.Header().Set("Content-Disposition", tt.disposition)
|
||||
}
|
||||
fmt.Fprint(w, tt.body)
|
||||
}))
|
||||
defer server.Close()
|
||||
got, err := FetchRoutingA(configure.RoutingASource{URL: server.URL, DirectUpdate: true})
|
||||
if tt.wantError == "" {
|
||||
if err != nil || got != tt.body {
|
||||
t.Fatalf("FetchRoutingA() = %q, %v", got, err)
|
||||
}
|
||||
} else if err == nil || !strings.Contains(err.Error(), tt.wantError) {
|
||||
t.Fatalf("FetchRoutingA() error = %v, want %q", err, tt.wantError)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchRoutingARejectsNonHTTP(t *testing.T) {
|
||||
for _, source := range []string{"file:///etc/passwd", "javascript:alert(1)", "https://user:pass@example.com/rules.txt"} {
|
||||
if _, err := FetchRoutingA(configure.RoutingASource{URL: source}); err == nil {
|
||||
t.Fatalf("FetchRoutingA(%q) accepted invalid URL", source)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateRoutingAFromSourceKeepsLastGoodRules(t *testing.T) {
|
||||
previousRules := configure.GetRoutingA()
|
||||
previousSource := configure.GetRoutingASource()
|
||||
t.Cleanup(func() {
|
||||
_ = configure.SetRoutingA(&previousRules)
|
||||
_ = configure.SetRoutingASource(previousSource)
|
||||
})
|
||||
body := "default: direct\n"
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
fmt.Fprint(w, body)
|
||||
}))
|
||||
defer server.Close()
|
||||
source := configure.RoutingASource{URL: server.URL, DirectUpdate: true, IntervalHours: 24}
|
||||
if err := configure.SetRoutingASource(source); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := UpdateRoutingAFromSource(); err != nil || configure.GetRoutingA() != body {
|
||||
t.Fatalf("first update: %v, %q", err, configure.GetRoutingA())
|
||||
}
|
||||
body = "<html>not raw rules</html>"
|
||||
if err := UpdateRoutingAFromSource(); err == nil || configure.GetRoutingA() != "default: direct\n" {
|
||||
t.Fatalf("invalid update replaced last good rules: %v, %q", err, configure.GetRoutingA())
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user