Skip to content

Commit

Permalink
refactor: remove old plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
Pylogmon committed Jun 21, 2024
1 parent 5c8093c commit 6153af1
Show file tree
Hide file tree
Showing 14 changed files with 183 additions and 45 deletions.
4 changes: 2 additions & 2 deletions src-tauri/src/cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,9 +138,9 @@ pub fn install_plugin(path_list: Vec<String>) -> Result<i32, Error> {
let path = std::path::Path::new(&path);
let file_name = path.file_name().unwrap().to_str().unwrap();
let file_name = file_name.replace(".potext", "");
if !file_name.starts_with("[plugin]") {
if !file_name.starts_with("plugin") {
return Err(Error::Error(
"Invalid Plugin: file name must start with [plugin]".into(),
"Invalid Plugin: file name must start with plugin".into(),
));
}

Expand Down
140 changes: 139 additions & 1 deletion src-tauri/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::APP;
use crate::{error::Error, APP};
use dirs::config_dir;
use log::{info, warn};
use serde_json::{json, Value};
Expand All @@ -23,6 +23,144 @@ pub fn init_config(app: &mut tauri::App) {
}
}
app.manage(StoreWrapper(Mutex::new(store)));
let _ = check_service_available();
}

fn check_available(list: Vec<String>, builtin: Vec<&str>, plugin: Vec<String>, key: &str) {
let origin_length = list.len();
let mut new_list = list.clone();
for service in list {
let name = service.split("@").collect::<Vec<&str>>()[0];
let mut is_available = true;
if name.starts_with("plugin") {
if !plugin.contains(&name.to_string()) {
is_available = false;
}
} else {
if !builtin.contains(&name) {
is_available = false;
}
}
if !is_available {
new_list.retain(|x| x != &service);
}
}
if new_list.len() != origin_length {
set(key, new_list);
}
}

pub fn check_service_available() -> Result<(), Error> {
let builtin_recognize_list: Vec<&str> = vec![
"baidu_ocr",
"baidu_accurate_ocr",
"baidu_img_ocr",
"iflytek_ocr",
"iflytek_intsig_ocr",
"iflytek_latex_ocr",
"qrcode",
"simple_latex_ocr",
"system",
"tencent_ocr",
"tencent_accurate_ocr",
"tencent_img_ocr",
"tesseract",
"volcengine_ocr",
"volcengine_multi_lang_ocr",
];
let builtin_translate_list: Vec<&str> = vec![
"alibaba",
"baidu",
"baidu_field",
"bing",
"bing_dict",
"caiyun",
"cambridge_dict",
"chatglm",
"deepl",
"geminipro",
"niutrans",
"ollama",
"openai",
"google",
"tencent",
"transmart",
"volcengine",
"yandex",
"youdao",
];
let builtin_tts_list: Vec<&str> = vec!["lingva_tts"];
let builtin_collection_list: Vec<&str> = vec!["anki", "eudic"];

let plugin_recognize_list: Vec<String> = get_plugin_list("recognize").unwrap_or_default();
let plugin_translate_list: Vec<String> = get_plugin_list("translate").unwrap_or_default();
let plugin_tts_list: Vec<String> = get_plugin_list("tts").unwrap_or_default();
let plugin_collection_list: Vec<String> = get_plugin_list("collection").unwrap_or_default();
if let Some(recognize_service_list) = get("recognize_service_list") {
let recognize_service_list: Vec<String> = serde_json::from_value(recognize_service_list)?;
check_available(
recognize_service_list,
builtin_recognize_list,
plugin_recognize_list,
"recognize_service_list",
);
}
if let Some(translate_service_list) = get("translate_service_list") {
let translate_service_list: Vec<String> = serde_json::from_value(translate_service_list)?;
check_available(
translate_service_list,
builtin_translate_list,
plugin_translate_list,
"translate_service_list",
);
}
if let Some(tts_service_list) = get("tts_service_list") {
let tts_service_list: Vec<String> = serde_json::from_value(tts_service_list)?;
check_available(
tts_service_list,
builtin_tts_list,
plugin_tts_list,
"tts_service_list",
);
}
if let Some(collection_service_list) = get("collection_service_list") {
let collection_service_list: Vec<String> = serde_json::from_value(collection_service_list)?;
check_available(
collection_service_list,
builtin_collection_list,
plugin_collection_list,
"tts_service_list",
);
}
Ok(())
}

pub fn get_plugin_list(plugin_type: &str) -> Option<Vec<String>> {
let app_handle = APP.get().unwrap();
let config_dir = dirs::config_dir()?;
let config_dir = config_dir.join(app_handle.config().tauri.bundle.identifier.clone());
let plugin_dir = config_dir.join("plugins");
let plugin_dir = plugin_dir.join(plugin_type);

// dirs in plugin_dir
let mut plugin_list = vec![];
if plugin_dir.exists() {
let read_dir = std::fs::read_dir(plugin_dir).ok()?;
for entry in read_dir {
let entry = entry.ok()?;

if entry.path().is_dir() {
let name = entry.file_name().to_str()?.to_string();
if name.starts_with("plugin") {
plugin_list.push(name);
} else {
// Remove old plugin
let _ = std::fs::remove_dir_all(entry.path());
}
}
}
}
Some(plugin_list)
}

pub fn get(key: &str) -> Option<Value> {
Expand Down
34 changes: 17 additions & 17 deletions src/utils/service_instance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ export enum ServiceType {
TRANSLATE = 'translate',
RECOGNIZE = 'recognize',
TTS = 'tts',
COLLECTION = 'Collection'
COLLECTION = 'Collection',
}

export enum ServiceSourceType {
Expand All @@ -11,40 +11,40 @@ export enum ServiceSourceType {
}

export function getServiceSouceType(serviceInstanceKey: string): ServiceSourceType {
if (serviceInstanceKey.startsWith('[plugin]')) {
return ServiceSourceType.PLUGIN
if (serviceInstanceKey.startsWith('plugin')) {
return ServiceSourceType.PLUGIN;
} else {
return ServiceSourceType.BUILDIN
return ServiceSourceType.BUILDIN;
}
}

export function whetherPluginService(serviceInstanceKey: string): boolean {
return getServiceSouceType(serviceInstanceKey) === ServiceSourceType.PLUGIN
return getServiceSouceType(serviceInstanceKey) === ServiceSourceType.PLUGIN;
}


// The serviceInstanceKey consists of the service name and it's id, separated by @
// In earlier versions, the @ separator and id were optional, so they all have only one instance.
export function createServiceInstanceKey(serviceName: string): string {
const randomId = Math.random().toString(36).substring(2)
return `${serviceName}@${randomId}`
const randomId = Math.random().toString(36).substring(2);
return `${serviceName}@${randomId}`;
}


// if the serviceInstanceKey is from a plugin, serviceName is it's pluginId
export function getServiceName(serviceInstanceKey: string): string {
return serviceInstanceKey.split('@')[0]
return serviceInstanceKey.split('@')[0];
}

export function getDisplayInstanceName(instanceName: string, serviceNameSupplier: () => string): string {
return instanceName || serviceNameSupplier()
return instanceName || serviceNameSupplier();
}

export const INSTANCE_NAME_CONFIG_KEY = 'instanceName'

export function whetherAvailableService(serviceInstanceKey: string, availableServices: Record<ServiceSourceType, Record<string, any>>) {
const serviceSourceType = getServiceSouceType(serviceInstanceKey)
const serviceName = getServiceName(serviceInstanceKey)
return availableServices[serviceSourceType]?.[serviceName] !== undefined
export const INSTANCE_NAME_CONFIG_KEY = 'instanceName';

export function whetherAvailableService(
serviceInstanceKey: string,
availableServices: Record<ServiceSourceType, Record<string, any>>
) {
const serviceSourceType = getServiceSouceType(serviceInstanceKey);
const serviceName = getServiceName(serviceInstanceKey);
return availableServices[serviceSourceType]?.[serviceName] !== undefined;
}
8 changes: 4 additions & 4 deletions src/window/Config/pages/History/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ export default function History() {
}) && (
<TableRow key={item.id}>
<TableCell>
{item.service.startsWith('[plugin]') ? (
{item.service.startsWith('plugin') ? (
<img
src={pluginList['translate'][item.service].icon}
className='h-[18px] w-[18px] my-auto mr-[8px]'
Expand Down Expand Up @@ -233,7 +233,7 @@ export default function History() {
<>
<ModalHeader>
<div className='flex justify-start'>
{selectedItem.service.startsWith('[plugin]') ? (
{selectedItem.service.startsWith('plugin') ? (
<img
src={pluginList['translate'][selectedItem.service].icon}
className='h-[24px] w-[24px] my-auto'
Expand Down Expand Up @@ -281,7 +281,7 @@ export default function History() {
isIconOnly
variant='light'
onPress={async () => {
if (serviceName.startsWith('[plugin]')) {
if (serviceName.startsWith('plugin')) {
const pluginConfig =
(await store.get(serviceName)) ?? {};
let [func, utils] = await invoke_plugin(
Expand Down Expand Up @@ -334,7 +334,7 @@ export default function History() {
>
<img
src={
serviceName.startsWith('[plugin]')
serviceName.startsWith('plugin')
? pluginList['collection'][serviceName].icon
: builtinCollectionServices[serviceName].info
.icon
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ import { PluginConfig } from '../../PluginConfig';

export default function ConfigModal(props) {
const { isOpen, onOpenChange, name, updateServiceList, pluginList } = props;
const serviceType = name.startsWith('[plugin]') ? 'plugin' : 'builtin';
const serviceType = name.startsWith('plugin') ? 'plugin' : 'builtin';
const { t } = useTranslation();
const ConfigComponent = name.startsWith('[plugin]') ? PluginConfig : builtinServices[name].Config;
const ConfigComponent = name.startsWith('plugin') ? PluginConfig : builtinServices[name].Config;

return serviceType === 'plugin' && !(name in pluginList) ? (
<></>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import * as builtinServices from '../../../../../../services/collection';

export default function ServiceItem(props) {
const { name, deleteService, setConfigName, onConfigOpen, pluginList, ...drag } = props;
const serviceType = name.startsWith('[plugin]') ? 'plugin' : 'builtin';
const serviceType = name.startsWith('plugin') ? 'plugin' : 'builtin';
const { t } = useTranslation();

return serviceType === 'plugin' && !(name in pluginList) ? (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ import { PluginConfig } from '../../PluginConfig';

export default function ConfigModal(props) {
const { isOpen, onOpenChange, name, updateServiceList, pluginList } = props;
const serviceType = name.startsWith('[plugin]') ? 'plugin' : 'builtin';
const serviceType = name.startsWith('plugin') ? 'plugin' : 'builtin';
const { t } = useTranslation();
const ConfigComponent = name.startsWith('[plugin]') ? PluginConfig : builtinServices[name].Config;
const ConfigComponent = name.startsWith('plugin') ? PluginConfig : builtinServices[name].Config;

return serviceType === 'plugin' && !(name in pluginList) ? (
<></>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { osType } from '../../../../../../utils/env';

export default function ServiceItem(props) {
const { name, deleteService, setConfigName, onConfigOpen, pluginList, ...drag } = props;
const serviceType = name.startsWith('[plugin]') ? 'plugin' : 'builtin';
const serviceType = name.startsWith('plugin') ? 'plugin' : 'builtin';
const { t } = useTranslation();

return serviceType === 'plugin' && !(name in pluginList) ? (
Expand Down
4 changes: 2 additions & 2 deletions src/window/Config/pages/Service/Tts/ConfigModal/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ import { PluginConfig } from '../../PluginConfig';

export default function ConfigModal(props) {
const { isOpen, onOpenChange, name, updateServiceList, pluginList } = props;
const serviceType = name.startsWith('[plugin]') ? 'plugin' : 'builtin';
const serviceType = name.startsWith('plugin') ? 'plugin' : 'builtin';
const { t } = useTranslation();
const ConfigComponent = name.startsWith('[plugin]') ? PluginConfig : builtinServices[name].Config;
const ConfigComponent = name.startsWith('plugin') ? PluginConfig : builtinServices[name].Config;

return serviceType === 'plugin' && !(name in pluginList) ? (
<></>
Expand Down
2 changes: 1 addition & 1 deletion src/window/Config/pages/Service/Tts/ServiceItem/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import * as builtinServices from '../../../../../../services/tts';

export default function ServiceItem(props) {
const { name, deleteService, setConfigName, onConfigOpen, pluginList, ...drag } = props;
const serviceType = name.startsWith('[plugin]') ? 'plugin' : 'builtin';
const serviceType = name.startsWith('plugin') ? 'plugin' : 'builtin';
const { t } = useTranslation();

return serviceType === 'plugin' && !(name in pluginList) ? (
Expand Down
8 changes: 4 additions & 4 deletions src/window/Recognize/ControlArea/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export default function ControlArea() {
<img
className='h-[16px] w-[16px] my-auto'
src={
serviceName.startsWith('[plugin]')
serviceName.startsWith('plugin')
? pluginList[serviceName].icon
: builtinService[serviceName].info.icon === 'system'
? `logo/${osType}.svg`
Expand All @@ -60,7 +60,7 @@ export default function ControlArea() {
/>
}
>
{serviceName.startsWith('[plugin]')
{serviceName.startsWith('plugin')
? pluginList[serviceName].display
: t(`services.recognize.${serviceName}.title`)}
</Button>
Expand All @@ -87,7 +87,7 @@ export default function ControlArea() {
<img
className='h-[16px] w-[16px] my-auto'
src={
name.startsWith('[plugin]')
name.startsWith('plugin')
? pluginList[name].icon
: builtinService[name].info.icon === 'system'
? `logo/${osType}.svg`
Expand All @@ -96,7 +96,7 @@ export default function ControlArea() {
/>
}
>
{name.startsWith('[plugin]')
{name.startsWith('plugin')
? pluginList[name].display
: t(`services.recognize.${name}.title`)}
</DropdownItem>
Expand Down
2 changes: 1 addition & 1 deletion src/window/Recognize/TextArea/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export default function TextArea() {
setError('');
if (base64 !== '' && serviceName && autoCopy !== null && deleteNewline !== null && hideWindow !== null) {
setLoading(true);
if (serviceName.startsWith('[plugin]')) {
if (serviceName.startsWith('plugin')) {
if (language in pluginList[serviceName].language) {
let id = nanoid();
recognizeId = id;
Expand Down
6 changes: 3 additions & 3 deletions src/window/Translate/components/SourceArea/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export default function SourceArea(props) {
setWindowType('[IMAGE_TRANSLATE]');
const base64 = await invoke('get_base64');
const serviceName = recognizeServiceList[0];
if (serviceName.startsWith('[plugin]')) {
if (serviceName.startsWith('plugin')) {
if (recognizeLanguage in pluginList['recognize'][serviceName].language) {
const pluginConfig = (await store.get(serviceName)) ?? {};
let [func, utils] = await invoke_plugin('recognize', serviceName);
Expand Down Expand Up @@ -170,7 +170,7 @@ export default function SourceArea(props) {
detected = await detect(sourceText);
setDetectLanguage(detected);
}
if (serviceName.startsWith('[plugin]')) {
if (serviceName.startsWith('plugin')) {
if (!(detected in ttsPluginInfo.language)) {
throw new Error('Language not supported');
}
Expand Down Expand Up @@ -208,7 +208,7 @@ export default function SourceArea(props) {
}, [hideWindow]);

useEffect(() => {
if (ttsServiceList && ttsServiceList[0].startsWith('[plugin]')) {
if (ttsServiceList && ttsServiceList[0].startsWith('plugin')) {
readTextFile(`plugins/tts/${ttsServiceList[0]}/info.json`, {
dir: BaseDirectory.AppConfig,
}).then((infoStr) => {
Expand Down
Loading

0 comments on commit 6153af1

Please sign in to comment.