Prechádzať zdrojové kódy

feat: implement geofiles update in panel (#2971)

solves #2672

Co-authored-by: Sanaei <[email protected]>
Shishkevich D. 1 deň pred
rodič
commit
1aed2d8cdc

+ 8 - 1
web/controller/server.go

@@ -44,6 +44,7 @@ func (a *ServerController) initRouter(g *gin.RouterGroup) {
 	g.POST("/stopXrayService", a.stopXrayService)
 	g.POST("/restartXrayService", a.restartXrayService)
 	g.POST("/installXray/:version", a.installXray)
+	g.POST("/updateGeofile/:fileName", a.updateGeofile)
 	g.POST("/logs/:count", a.getLogs)
 	g.POST("/getConfigJson", a.getConfigJson)
 	g.GET("/getDb", a.getDb)
@@ -95,7 +96,13 @@ func (a *ServerController) getXrayVersion(c *gin.Context) {
 func (a *ServerController) installXray(c *gin.Context) {
 	version := c.Param("version")
 	err := a.serverService.UpdateXray(version)
-	jsonMsg(c, I18nWeb(c, "install")+" xray", err)
+	jsonMsg(c, I18nWeb(c, "pages.index.xraySwitchVersionPopover"), err)
+}
+
+func (a *ServerController) updateGeofile(c *gin.Context) {
+	fileName := c.Param("fileName")
+	err := a.serverService.UpdateGeofile(fileName)
+	jsonMsg(c, I18nWeb(c, "pages.index.geofileUpdatePopover"), err)
 }
 
 func (a *ServerController) stopXrayService(c *gin.Context) {

+ 40 - 11
web/html/index.html

@@ -22,11 +22,14 @@
   .ant-backup-list-item {
     gap: 10px;
   }
-  .ant-xray-version-list-item {
+  .ant-version-list-item {
     --padding: 12px;
     padding: var(--padding) !important;
     gap: var(--padding);
   }
+  .dark .ant-version-list-item svg{
+    color: var(--dark-color-text-primary);
+  }
   .dark .ant-backup-list-item svg,
   .dark .ant-badge-status-text,
   .dark .ant-card-extra {
@@ -43,7 +46,7 @@
     border-color: var(--color-primary-100);
   }
   .dark .ant-backup-list, 
-  .dark .ant-xray-version-list,
+  .dark .ant-version-list,
   .dark .ant-card-actions,
   .dark .ant-card-actions>li:not(:last-child) {
     border-color: var(--dark-color-stroke);
@@ -353,14 +356,25 @@
     </a-layout>
     <a-modal id="version-modal" v-model="versionModal.visible" title='{{ i18n "pages.index.xraySwitch" }}' :closable="true"
         @ok="() => versionModal.visible = false" :class="themeSwitcher.currentTheme" footer="">
-      <a-alert type="warning" :style="{ marginBottom: '12px', width: '100%' }"
-        message='{{ i18n "pages.index.xraySwitchClickDesk" }}' show-icon></a-alert>
-      <a-list class="ant-xray-version-list" bordered :style="{ width: '100%' }">
-        <a-list-item class="ant-xray-version-list-item" v-for="version, index in versionModal.versions">
-          <a-tag :color="index % 2 == 0 ? 'purple' : 'green'">[[ version ]]</a-tag>
-          <a-radio :class="themeSwitcher.currentTheme" :checked="version === `v${status.xray.version}`" @click="switchV2rayVersion(version)"></a-radio>
-        </a-list-item>
-      </a-list>
+      <a-collapse default-active-key="1">
+        <a-collapse-panel key="1" header='Xray'>
+          <a-alert type="warning" :style="{ marginBottom: '12px', width: '100%' }" message='{{ i18n "pages.index.xraySwitchClickDesk" }}' show-icon></a-alert>
+          <a-list class="ant-version-list" bordered :style="{ width: '100%' }">
+            <a-list-item class="ant-version-list-item" v-for="version, index in versionModal.versions">
+              <a-tag :color="index % 2 == 0 ? 'purple' : 'green'">[[ version ]]</a-tag>
+              <a-radio :class="themeSwitcher.currentTheme" :checked="version === `v${status.xray.version}`" @click="switchV2rayVersion(version)"></a-radio>
+            </a-list-item>
+          </a-list>
+        </a-collapse-panel>
+        <a-collapse-panel key="2" header='Geofiles'>
+          <a-list class="ant-version-list" bordered :style="{ width: '100%' }">
+            <a-list-item class="ant-version-list-item" v-for="file, index in ['geosite.dat', 'geoip.dat', 'geosite_IR.dat', 'geoip_IR.dat', 'geosite_RU.dat', 'geoip_RU.dat']">
+              <a-tag :color="index % 2 == 0 ? 'purple' : 'green'">[[ file ]]</a-tag>
+              <a-icon type="reload" @click="updateGeofile(file)" :style="{ marginRight: '8px' }"/>
+            </a-list-item>
+          </a-list>
+        </a-collapse-panel>
+      </a-collapse>
     </a-modal>
     <a-modal id="log-modal" v-model="logModal.visible"
         :closable="true" @cancel="() => logModal.visible = false"
@@ -645,7 +659,7 @@
             switchV2rayVersion(version) {
                 this.$confirm({
                     title: '{{ i18n "pages.index.xraySwitchVersionDialog"}}',
-                    content: '{{ i18n "pages.index.xraySwitchVersionDialogDesc"}}' + ` ${version}?`,
+                    content: '{{ i18n "pages.index.xraySwitchVersionDialogDesc"}}'.replace('#version#', version),
                     okText: '{{ i18n "confirm"}}',
                     class: themeSwitcher.currentTheme,
                     cancelText: '{{ i18n "cancel"}}',
@@ -657,6 +671,21 @@
                     },
                 });
             },
+            updateGeofile(fileName) {
+                this.$confirm({
+                    title: '{{ i18n "pages.index.geofileUpdateDialog" }}',
+                    content: '{{ i18n "pages.index.geofileUpdateDialogDesc" }}'.replace("#filename#", fileName),
+                    okText: '{{ i18n "confirm"}}',
+                    class: themeSwitcher.currentTheme,
+                    cancelText: '{{ i18n "cancel"}}',
+                    onOk: async () => {
+                        versionModal.hide();
+                        this.loading(true, '{{ i18n "pages.index.dontRefresh"}}');
+                        await HttpUtil.post(`/server/updateGeofile/${fileName}`);
+                        this.loading(false);
+                    },
+                });
+            },
             async stopXrayService() {
                 this.loading(true);
                 const msg = await HttpUtil.post('server/stopXrayService');

+ 60 - 0
web/service/server.go

@@ -591,6 +591,66 @@ func (s *ServerService) ImportDB(file multipart.File) error {
 	return nil
 }
 
+func (s *ServerService) UpdateGeofile(fileName string) error {
+    files := []struct {
+        URL      string
+        FileName string
+    }{
+        {"https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geoip.dat", "geoip.dat"},
+        {"https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat", "geosite.dat"},
+        {"https://github.com/chocolate4u/Iran-v2ray-rules/releases/latest/download/geoip.dat", "geoip_IR.dat"},
+        {"https://github.com/chocolate4u/Iran-v2ray-rules/releases/latest/download/geosite.dat", "geosite_IR.dat"},
+        {"https://github.com/runetfreedom/russia-v2ray-rules-dat/releases/latest/download/geoip.dat", "geoip_RU.dat"},
+        {"https://github.com/runetfreedom/russia-v2ray-rules-dat/releases/latest/download/geosite.dat", "geosite_RU.dat"},
+    }
+
+    downloadFile := func(url, destPath string) error {
+        resp, err := http.Get(url)
+        if err != nil {
+            return common.NewErrorf("Failed to download Geofile from %s: %v", url, err)
+        }
+        defer resp.Body.Close()
+
+        file, err := os.Create(destPath)
+        if err != nil {
+            return common.NewErrorf("Failed to create Geofile %s: %v", destPath, err)
+        }
+        defer file.Close()
+
+        _, err = io.Copy(file, resp.Body)
+        if err != nil {
+            return common.NewErrorf("Failed to save Geofile %s: %v", destPath, err)
+        }
+
+        return nil
+    }
+
+    var fileURL string
+    for _, file := range files {
+        if file.FileName == fileName {
+            fileURL = file.URL
+            break
+        }
+    }
+
+    if fileURL == "" {
+        return common.NewErrorf("File '%s' not found in the list of Geofiles", fileName)
+    }
+
+    destPath := fmt.Sprintf("%s/%s", config.GetBinFolderPath(), fileName)
+
+    if err := downloadFile(fileURL, destPath); err != nil {
+        return common.NewErrorf("Error downloading Geofile '%s': %v", fileName, err)
+    }
+
+    err := s.RestartXrayService()
+    if err != nil {
+        return common.NewErrorf("Updated Geofile '%s' but Failed to start Xray: %v", fileName, err)
+    }
+
+    return nil
+}
+
 func (s *ServerService) GetNewX25519Cert() (any, error) {
 	// Run the command
 	cmd := exec.Command(xray.GetBinaryPath(), "x25519")

+ 6 - 2
web/translation/translate.ar_EG.toml

@@ -122,8 +122,12 @@
 "totalData" = "إجمالي البيانات"
 "sent" = "مرسل"
 "received" = "مستقبل"
-"xraySwitchVersionDialog" = "تغيير نسخة Xray"
-"xraySwitchVersionDialogDesc" = "متأكد إنك عايز تغير نسخة Xray لـ"
+"xraySwitchVersionDialog" = "هل تريد حقًا تغيير إصدار Xray؟"
+"xraySwitchVersionDialogDesc" = "سيؤدي هذا إلى تغيير إصدار Xray إلى #version#."
+"xraySwitchVersionPopover" = "تم تحديث Xray بنجاح"
+"geofileUpdateDialog" = "هل تريد حقًا تحديث ملف الجغرافيا؟"
+"geofileUpdateDialogDesc" = "سيؤدي هذا إلى تحديث ملف #filename#."
+"geofileUpdatePopover" = "تم تحديث ملف الجغرافيا بنجاح"
 "dontRefresh" = "التثبيت شغال، متعملش Refresh للصفحة"
 "logs" = "السجلات"
 "config" = "الإعدادات"

+ 6 - 2
web/translation/translate.en_US.toml

@@ -122,8 +122,12 @@
 "totalData" = "Total Data"
 "sent" = "Sent"
 "received" = "Received"
-"xraySwitchVersionDialog" = "Change Xray Version"
-"xraySwitchVersionDialogDesc" = "Are you sure you want to change the Xray version to"
+"xraySwitchVersionDialog" = "Do you really want to change the Xray version?"
+"xraySwitchVersionDialogDesc" = "This will change the Xray version to #version#."
+"xraySwitchVersionPopover" = "Xray updated successfully"
+"geofileUpdateDialog" = "Do you really want to update the geofile?"
+"geofileUpdateDialogDesc" = "This will update the #filename# file."
+"geofileUpdatePopover" = "Geofile updated successfully"
 "dontRefresh" = "Installation is in progress, please do not refresh this page"
 "logs" = "Logs"
 "config" = "Config"

+ 6 - 2
web/translation/translate.es_ES.toml

@@ -124,8 +124,12 @@
 "totalData" = "Datos totales"
 "sent" = "Enviado"
 "received" = "Recibido"
-"xraySwitchVersionDialog" = "Cambiar Versión de Xray"
-"xraySwitchVersionDialogDesc" = "¿Estás seguro de que deseas cambiar la versión de Xray a"
+"xraySwitchVersionDialog" = "¿Realmente deseas cambiar la versión de Xray?"
+"xraySwitchVersionDialogDesc" = "Esto cambiará la versión de Xray a #version#."
+"xraySwitchVersionPopover" = "Xray se actualizó correctamente"
+"geofileUpdateDialog" = "¿Realmente deseas actualizar el geofichero?"
+"geofileUpdateDialogDesc" = "Esto actualizará el archivo #filename#."
+"geofileUpdatePopover" = "Geofichero actualizado correctamente"
 "dontRefresh" = "La instalación está en progreso, por favor no actualices esta página."
 "logs" = "Registros"
 "config" = "Configuración"

+ 6 - 2
web/translation/translate.fa_IR.toml

@@ -124,8 +124,12 @@
 "totalData" = "داده‌های کل"
 "sent" = "ارسال شده"
 "received" = "دریافت شده"
-"xraySwitchVersionDialog" = "تغییر نسخه ایکس‌ری"
-"xraySwitchVersionDialogDesc" = "آیا از تغییر نسخه‌ مطمئن هستید؟"
+"xraySwitchVersionDialog" = "آیا واقعاً می‌خواهید نسخه Xray را تغییر دهید؟"
+"xraySwitchVersionDialogDesc" = "این کار نسخه Xray را به #version# تغییر می‌دهد."
+"xraySwitchVersionPopover" = "Xray با موفقیت به‌روز شد"
+"geofileUpdateDialog" = "آیا واقعاً می‌خواهید فایل جغرافیایی را به‌روز کنید؟"
+"geofileUpdateDialogDesc" = "این عمل فایل #filename# را به‌روز می‌کند."
+"geofileUpdatePopover" = "فایل جغرافیایی با موفقیت به‌روز شد"
 "dontRefresh" = "در حال نصب، لطفا صفحه را رفرش نکنید"
 "logs" = "گزارش‌ها"
 "config" = "پیکربندی"

+ 6 - 2
web/translation/translate.id_ID.toml

@@ -124,8 +124,12 @@
 "totalData" = "Total data"
 "sent" = "Dikirim"
 "received" = "Diterima"
-"xraySwitchVersionDialog" = "Ganti Versi Xray"
-"xraySwitchVersionDialogDesc" = "Apakah Anda yakin ingin mengubah versi Xray menjadi"
+"xraySwitchVersionDialog" = "Apakah Anda yakin ingin mengubah versi Xray?"
+"xraySwitchVersionDialogDesc" = "Ini akan mengubah versi Xray ke #version#."
+"xraySwitchVersionPopover" = "Xray berhasil diperbarui"
+"geofileUpdateDialog" = "Apakah Anda yakin ingin memperbarui geofile?"
+"geofileUpdateDialogDesc" = "Ini akan memperbarui file #filename#."
+"geofileUpdatePopover" = "Geofile berhasil diperbarui"
 "dontRefresh" = "Instalasi sedang berlangsung, harap jangan menyegarkan halaman ini"
 "logs" = "Log"
 "config" = "Konfigurasi"

+ 6 - 2
web/translation/translate.ja_JP.toml

@@ -124,8 +124,12 @@
 "totalData" = "総データ量"
 "sent" = "送信"
 "received" = "受信"
-"xraySwitchVersionDialog" = "Xrayバージョン切り替え"
-"xraySwitchVersionDialogDesc" = "Xrayのバージョンを切り替えますか?"
+"xraySwitchVersionDialog" = "Xrayのバージョンを本当に変更しますか?"
+"xraySwitchVersionDialogDesc" = "Xrayのバージョンが#version#に変更されます。"
+"xraySwitchVersionPopover" = "Xrayの更新が成功しました"
+"geofileUpdateDialog" = "ジオファイルを本当に更新しますか?"
+"geofileUpdateDialogDesc" = "これにより#filename#ファイルが更新されます。"
+"geofileUpdatePopover" = "ジオファイルの更新が成功しました"
 "dontRefresh" = "インストール中、このページをリロードしないでください"
 "logs" = "ログ"
 "config" = "設定"

+ 6 - 2
web/translation/translate.pt_BR.toml

@@ -124,8 +124,12 @@
 "totalData" = "Dados totais"
 "sent" = "Enviado"
 "received" = "Recebido"
-"xraySwitchVersionDialog" = "Alterar Versão do Xray"
-"xraySwitchVersionDialogDesc" = "Tem certeza de que deseja alterar a versão do Xray para"
+"xraySwitchVersionDialog" = "Você realmente deseja alterar a versão do Xray?"
+"xraySwitchVersionDialogDesc" = "Isso mudará a versão do Xray para #version#."
+"xraySwitchVersionPopover" = "Xray atualizado com sucesso"
+"geofileUpdateDialog" = "Você realmente deseja atualizar o geofile?"
+"geofileUpdateDialogDesc" = "Isso atualizará o arquivo #filename#."
+"geofileUpdatePopover" = "Geofile atualizado com sucesso"
 "dontRefresh" = "Instalação em andamento, por favor não atualize a página"
 "logs" = "Logs"
 "config" = "Configuração"

+ 6 - 2
web/translation/translate.ru_RU.toml

@@ -124,8 +124,12 @@
 "totalData" = "Общий объем данных"
 "sent" = "Отправлено"
 "received" = "Получено"
-"xraySwitchVersionDialog" = "Переключить версию Xray"
-"xraySwitchVersionDialogDesc" = "Вы точно хотите сменить версию Xray?"
+"xraySwitchVersionDialog" = "Вы действительно хотите изменить версию Xray?"
+"xraySwitchVersionDialogDesc" = "Это изменит версию Xray на #version#."
+"xraySwitchVersionPopover" = "Xray успешно обновлён"
+"geofileUpdateDialog" = "Вы действительно хотите обновить геофайл?"
+"geofileUpdateDialogDesc" = "Это обновит файл #filename#."
+"geofileUpdatePopover" = "Геофайл успешно обновлён"
 "dontRefresh" = "Установка в процессе. Не обновляйте страницу"
 "logs" = "Журнал"
 "config" = "Конфигурация"

+ 6 - 2
web/translation/translate.tr_TR.toml

@@ -124,8 +124,12 @@
 "totalData" = "Toplam veri"
 "sent" = "Gönderilen"
 "received" = "Alınan"
-"xraySwitchVersionDialog" = "Xray Sürümünü Değiştir"
-"xraySwitchVersionDialogDesc" = "Xray sürümünü değiştirmek istediğinizden emin misiniz"
+"xraySwitchVersionDialog" = "Xray sürümünü gerçekten değiştirmek istiyor musunuz?"
+"xraySwitchVersionDialogDesc" = "Bu işlem Xray sürümünü #version# olarak değiştirecektir."
+"xraySwitchVersionPopover" = "Xray başarıyla güncellendi"
+"geofileUpdateDialog" = "Geofile'ı gerçekten güncellemek istiyor musunuz?"
+"geofileUpdateDialogDesc" = "Bu işlem #filename# dosyasını güncelleyecektir."
+"geofileUpdatePopover" = "Geofile başarıyla güncellendi"
 "dontRefresh" = "Kurulum devam ediyor, lütfen bu sayfayı yenilemeyin"
 "logs" = "Günlükler"
 "config" = "Yapılandırma"

+ 6 - 2
web/translation/translate.uk_UA.toml

@@ -124,8 +124,12 @@
 "totalData" = "Загальний обсяг даних"
 "sent" = "Відправлено"
 "received" = "Отримано"
-"xraySwitchVersionDialog" = "Змінити версію Xray"
-"xraySwitchVersionDialogDesc" = "Ви впевнені, що бажаєте змінити версію Xray на"
+"xraySwitchVersionDialog" = "Ви дійсно хочете змінити версію Xray?"
+"xraySwitchVersionDialogDesc" = "Це змінить версію Xray на #version#."
+"xraySwitchVersionPopover" = "Xray успішно оновлено"
+"geofileUpdateDialog" = "Ви дійсно хочете оновити геофайл?"
+"geofileUpdateDialogDesc" = "Це оновить файл #filename#."
+"geofileUpdatePopover" = "Геофайл успішно оновлено"
 "dontRefresh" = "Інсталяція триває, будь ласка, не оновлюйте цю сторінку"
 "logs" = "Журнали"
 "config" = "Конфігурація"

+ 6 - 2
web/translation/translate.vi_VN.toml

@@ -124,8 +124,12 @@
 "totalData" = "Tổng dữ liệu"
 "sent" = "Đã gửi"
 "received" = "Đã nhận"
-"xraySwitchVersionDialog" = "Chuyển đổi Phiên bản Xray"
-"xraySwitchVersionDialogDesc" = "Bạn có chắc chắn muốn chuyển đổi phiên bản Xray sang"
+"xraySwitchVersionDialog" = "Bạn có chắc chắn muốn thay đổi phiên bản Xray không?"
+"xraySwitchVersionDialogDesc" = "Hành động này sẽ thay đổi phiên bản Xray thành #version#."
+"xraySwitchVersionPopover" = "Xray đã được cập nhật thành công"
+"geofileUpdateDialog" = "Bạn có chắc chắn muốn cập nhật geofile không?"
+"geofileUpdateDialogDesc" = "Hành động này sẽ cập nhật tệp #filename#."
+"geofileUpdatePopover" = "Geofile đã được cập nhật thành công"
 "dontRefresh" = "Đang tiến hành cài đặt, vui lòng không làm mới trang này."
 "logs" = "Nhật ký"
 "config" = "Cấu hình"

+ 6 - 2
web/translation/translate.zh_CN.toml

@@ -124,8 +124,12 @@
 "totalData" = "总数据"
 "sent" = "已发送"
 "received" = "已接收"
-"xraySwitchVersionDialog" = "切换 Xray 版本"
-"xraySwitchVersionDialogDesc" = "是否切换 Xray 版本至"
+"xraySwitchVersionDialog" = "您确定要更改Xray版本吗?"
+"xraySwitchVersionDialogDesc" = "这将把Xray版本更改为#version#。"
+"xraySwitchVersionPopover" = "Xray 更新成功"
+"geofileUpdateDialog" = "您确定要更新地理文件吗?"
+"geofileUpdateDialogDesc" = "这将更新 #filename# 文件。"
+"geofileUpdatePopover" = "地理文件更新成功"
 "dontRefresh" = "安装中,请勿刷新此页面"
 "logs" = "日志"
 "config" = "配置"

+ 6 - 2
web/translation/translate.zh_TW.toml

@@ -124,8 +124,12 @@
 "totalData" = "總數據"
 "sent" = "已發送"
 "received" = "已接收"
-"xraySwitchVersionDialog" = "切換 Xray 版本"
-"xraySwitchVersionDialogDesc" = "是否切換 Xray 版本至"
+"xraySwitchVersionDialog" = "您確定要變更Xray版本嗎?"
+"xraySwitchVersionDialogDesc" = "這將會把Xray版本變更為#version#。"
+"xraySwitchVersionPopover" = "Xray 更新成功"
+"geofileUpdateDialog" = "您確定要更新地理檔案嗎?"
+"geofileUpdateDialogDesc" = "這將更新 #filename# 檔案。"
+"geofileUpdatePopover" = "地理檔案更新成功"
 "dontRefresh" = "安裝中,請勿重新整理此頁面"
 "logs" = "日誌"
 "config" = "配置"