fix: after importing a subscription, it cannot be automatically switched to the current subscription.

This commit is contained in:
huzibaca 2024-09-13 18:17:14 +08:00
parent 983d1ea361
commit a0b266fef8
5 changed files with 45 additions and 28 deletions

View File

@ -32,12 +32,8 @@ pub async fn enhance_profiles() -> CmdResult {
}
#[tauri::command]
pub async fn import_profile(
url: String,
name: Option<String>,
option: Option<PrfOption>,
) -> CmdResult {
let item = wrap_err!(PrfItem::from_url(&url, name, None, option).await)?;
pub async fn import_profile(url: String, option: Option<PrfOption>) -> CmdResult {
let item = wrap_err!(PrfItem::from_url(&url, None, None, option).await)?;
wrap_err!(Config::profiles().data().append_item(item))
}

View File

@ -1,8 +1,7 @@
use crate::cmds::import_profile;
use crate::config::IVerge;
use crate::utils::error;
use crate::{config::Config, core::*, utils::init, utils::server};
use crate::{error as er, log_err, trace_err};
use crate::{config::Config, config::PrfItem, core::*, utils::init, utils::server};
use crate::{log_err, trace_err, wrap_err};
use anyhow::{bail, Result};
use once_cell::sync::OnceCell;
use percent_encoding::percent_decode_str;
@ -265,13 +264,17 @@ pub async fn resolve_scheme(param: String) -> Result<()> {
match encode_url {
Some(url) => {
let decoded_url = percent_decode_str(url.as_ref()).decode_utf8_lossy();
let url = percent_decode_str(url.as_ref())
.decode_utf8_lossy()
.to_string();
let handle = handle::Handle::global();
let app_handle = handle.app_handle.lock().clone();
if let Some(app_handle) = app_handle.as_ref() {
er!(format!("decode_url: {}", decoded_url));
match import_profile(decoded_url.to_string(), name.clone(), None).await {
Ok(_) => {
match PrfItem::from_url(url.as_ref(), name, None, None).await {
Ok(item) => {
let uid = item.uid.clone().unwrap();
let _ = wrap_err!(Config::profiles().data().append_item(item));
app_handle
.notification()
.builder()
@ -279,7 +282,8 @@ pub async fn resolve_scheme(param: String) -> Result<()> {
.body("Import profile success")
.show()
.unwrap();
handle::Handle::notice_message("import_sub_url::ok", "ok");
handle::Handle::notice_message("import_sub_url::ok", uid);
}
Err(e) => {
app_handle
@ -289,8 +293,8 @@ pub async fn resolve_scheme(param: String) -> Result<()> {
.body(format!("Import profile failed: {e}"))
.show()
.unwrap();
handle::Handle::notice_message("import_sub_url::error", e.clone());
bail!("Import profile failed: {e}");
handle::Handle::notice_message("import_sub_url::error", e.to_string());
bail!("Failed to add subscriptions: {e}");
}
}
}

View File

@ -4,7 +4,7 @@ import relativeTime from "dayjs/plugin/relativeTime";
import { SWRConfig, mutate } from "swr";
import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { useLocation, useRoutes } from "react-router-dom";
import { useLocation, useRoutes, useNavigate } from "react-router-dom";
import { List, Paper, ThemeProvider, SvgIcon } from "@mui/material";
import { listen } from "@tauri-apps/api/event";
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
@ -25,7 +25,6 @@ import getSystem from "@/utils/get-system";
import "dayjs/locale/ru";
import "dayjs/locale/zh-cn";
import { getPortableFlag } from "@/services/cmds";
import { useNavigate } from "react-router-dom";
import React from "react";
import { TransitionGroup, CSSTransition } from "react-transition-group";
const appWindow = getCurrentWebviewWindow();
@ -73,9 +72,12 @@ const Layout = () => {
const [status, msg] = payload as [string, string];
switch (status) {
case "import_sub_url::ok":
navigate("/profile", { state: { current: msg } });
Notice.success(t("Import Subscription Successful"));
break;
case "import_sub_url::error":
navigate("/profile");
Notice.error(msg);
break;
case "set_config::ok":

View File

@ -50,9 +50,11 @@ import { BaseStyledTextField } from "@/components/base/base-styled-text-field";
import { listen } from "@tauri-apps/api/event";
import { readTextFile } from "@tauri-apps/plugin-fs";
import { readText } from "@tauri-apps/plugin-clipboard-manager";
import { useLocation } from "react-router-dom";
const ProfilePage = () => {
const { t } = useTranslation();
const location = useLocation();
const [url, setUrl] = useState("");
const [disabled, setDisabled] = useState(false);
@ -64,6 +66,7 @@ const ProfilePage = () => {
coordinateGetter: sortableKeyboardCoordinates,
})
);
const { current } = location.state || {};
useEffect(() => {
const unlisten = listen("tauri://file-drop", async (event) => {
@ -138,11 +141,11 @@ const ProfilePage = () => {
const remoteItem = newProfiles.items?.find((e) => e.type === "remote");
const profilesCount = newProfiles.items?.filter(
const itemsCount = newProfiles.items?.filter(
(e) => e.type === "remote" || e.type === "local"
).length as number;
if (remoteItem && (profilesCount == 1 || !newProfiles.current)) {
if (remoteItem && (itemsCount == 1 || !newProfiles.current)) {
const current = remoteItem.uid;
await patchProfiles({ current });
mutateLogs();
@ -168,27 +171,40 @@ const ProfilePage = () => {
}
};
const onSelect = useLockFn(async (current: string, force: boolean) => {
if (!force && current === profiles.current) return;
const activateProfile = async (profile: string) => {
// 避免大多数情况下loading态闪烁
const reset = setTimeout(() => {
setActivatings([...currentActivatings(), current]);
setActivatings((prev) => [...prev, profile]);
}, 100);
try {
await patchProfiles({ current });
await patchProfiles({ current: profile });
await mutateLogs();
closeAllConnections();
activateSelected().then(() => {
await activateSelected();
Notice.success(t("Profile Switched"), 1000);
});
} catch (err: any) {
Notice.error(err?.message || err.toString(), 4000);
} finally {
clearTimeout(reset);
setActivatings([]);
}
};
const onSelect = useLockFn(async (current: string, force: boolean) => {
if (!force && current === profiles.current) return;
await activateProfile(current);
});
useEffect(() => {
(async () => {
if (current && current !== profiles.current) {
console.log("current:", current);
await activateProfile(current);
}
})();
}, current);
const onEnhance = useLockFn(async () => {
setActivatings(currentActivatings());
try {

View File

@ -63,7 +63,6 @@ export async function saveProfileFile(index: string, fileData: string) {
export async function importProfile(url: string) {
return invoke<void>("import_profile", {
url,
name: null,
option: { with_proxy: true },
});
}