Skip to content

Commit

Permalink
🐛 修复include、GM.*和ExternalMessage问题
Browse files Browse the repository at this point in the history
  • Loading branch information
CodFrm committed Oct 31, 2022
1 parent 1067285 commit fe96990
Show file tree
Hide file tree
Showing 21 changed files with 205 additions and 66 deletions.
8 changes: 4 additions & 4 deletions build/pack.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,16 +33,16 @@ str = str.replace(/"version": "(.*?)"/, `"version": "${manifest.version}"`);
fs.writeFileSync("./src/manifest.json", str);

// 处理configSystem version
let configSystem = fs.readFileSync("./src/pkg/config/config.ts").toString();
let configSystem = fs.readFileSync("./src/app/const.ts").toString();
// 如果是由github action的分支触发的构建,在版本中再加上commit id
if (process.env.GITHUB_REF_TYPE === "branch") {
package.version += `+${process.env.GITHUB_SHA.substring(0, 7)}`;
}
configSystem = configSystem.replace(
/\/\* version \*\/ "(.*?)"/,
`/* version */ "${package.version}"`
/ExtVersion = "(.*?)";/,
`ExtVersion = "${package.version}";`
);
fs.writeFileSync("./src/pkg/config/config.ts", configSystem);
fs.writeFileSync("./src/app/const.ts", configSystem);

execSync("npm run build", { stdio: "inherit" });

Expand Down
12 changes: 12 additions & 0 deletions src/app/const.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export const ExtVersion = "0.10.0-alpha.1";

export const Server = "https://sc.icodef.com/";

export const ExternalWhitelist = [
"greasyfork.org",
"scriptcat.org",
"tampermonkey.net.cn",
"openuserjs.org",
];

export const ExternalMessage = "externalMessage";
38 changes: 34 additions & 4 deletions src/app/service/system/manager.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { ExternalMessage, ExtVersion, Server } from "@App/app/const";
import IoC from "@App/app/ioc";
import { MessageHander } from "@App/app/message/message";
import { ScriptDAO } from "@App/app/repo/scripts";
import { SystemConfig } from "@App/pkg/config/config";
import Manager from "../manager";

Expand All @@ -8,17 +10,18 @@ import Manager from "../manager";
export class SystemManager extends Manager {
systemConfig: SystemConfig;

scriptDAO: ScriptDAO;

constructor(message: MessageHander, systemConfig: SystemConfig) {
super(message);
super(message, "system");
this.scriptDAO = new ScriptDAO();
this.systemConfig = systemConfig;
}

init() {
// 两小时检查一次更新
const checkUpdate = () => {
fetch(
`${this.systemConfig.server}api/v1/system/version?version=${this.systemConfig.version}`
)
fetch(`${Server}api/v1/system/version?version=${ExtVersion}`)
.then((resp) => resp.json())
.then((resp: { data: { notice: string; version: string } }) => {
chrome.storage.local.get(["notice"], (items) => {
Expand Down Expand Up @@ -50,6 +53,33 @@ export class SystemManager extends Manager {
}
});
}
// 处理
this.message.setHandler(
ExternalMessage,
async (
_action,
{
action,
name,
namespace,
}: { action: string; name: string; namespace: string }
) => {
if (action === "isInstalled") {
const script = await this.scriptDAO.findByNameAndNamespace(
name,
namespace
);
if (script) {
return Promise.resolve({
installed: true,
version: script.metadata.version && script.metadata.version[0],
});
}
return Promise.resolve({ installed: false });
}
return Promise.resolve(false);
}
);
}

getNotice(): Promise<{ notice: string; isRead: boolean }> {
Expand Down
4 changes: 1 addition & 3 deletions src/inject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@ const logger = new LoggerCore({

message.setHandler("pageLoad", (_action, data) => {
logger.logger().debug("inject start");

const runtime = new InjectRuntime(data.scripts, flag);

const runtime = new InjectRuntime(message, data.scripts, flag);
runtime.start();
});
1 change: 0 additions & 1 deletion src/pages/components/ScriptStorage/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ const ScriptStorage: React.FC<{
// 监听值变化
const channel = valueCtrl.watchValue(script);
channel.setHandler((value: Value) => {
console.log("value changed", value);
setData((prev) => {
const index = prev.findIndex((item) => item.key === value.key);
if (index === -1) {
Expand Down
2 changes: 1 addition & 1 deletion src/pages/components/UserConfigPanel/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ const UserConfigPanel: React.FC<{
placeholder={item.description}
>
{options!.map((option) => (
<Select.Option value={option}>
<Select.Option key={option} value={option}>
{option}
</Select.Option>
))}
Expand Down
6 changes: 3 additions & 3 deletions src/pages/components/layout/MainLayout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -75,17 +75,17 @@ const MainLayout: React.FC<{
</Space>
</a>
</Menu.Item>
<Menu.Item key="dark">
<Menu.Item key="background">
<a href="#/script/editor?template=background">
<RiTerminalBoxLine /> 添加后台脚本
</a>
</Menu.Item>
<Menu.Item key="auto">
<Menu.Item key="crontab">
<a href="#/script/editor?template=crontab">
<RiTimerLine /> 添加定时脚本
</a>
</Menu.Item>
<Menu.Item key="auto">
<Menu.Item key="link">
<IconLink /> 链接导入
</Menu.Item>
</Menu>
Expand Down
2 changes: 1 addition & 1 deletion src/pages/components/layout/Sider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ if (!hash.length) {

const Sider: React.FC = () => {
const [menuSelect, setMenuSelect] = useState(hash);
const [collapsed, setCollapsed] = useState(true);
const [collapsed, setCollapsed] = useState(false);

return (
<HashRouter>
Expand Down
3 changes: 0 additions & 3 deletions src/pages/options/routes/Logger.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -147,9 +147,6 @@ function Subscribe() {
<Card
bordered={false}
title="运行日志"
style={{
padding: 8,
}}
extra={
<Space size="large">
<DatePicker.RangePicker
Expand Down
8 changes: 8 additions & 0 deletions src/pages/options/routes/ScriptList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import {
RiPlayFill,
RiSettings3Fill,
RiStopFill,
RiUploadCloudFill,
} from "react-icons/ri";
import { Link, useNavigate, useSearchParams } from "react-router-dom";
import ScriptController from "@App/app/service/script/controller";
Expand Down Expand Up @@ -615,6 +616,13 @@ function ScriptList() {
}}
/>
))}
<Button
type="text"
icon={<RiUploadCloudFill />}
style={{
color: "var(--color-text-2)",
}}
/>
</Button.Group>
);
},
Expand Down
1 change: 1 addition & 0 deletions src/pages/options/routes/Setting.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ function Setting() {
}
actionButton={[
<Button
key="save"
type="primary"
onClick={async () => {
// 保存到配置中去
Expand Down
2 changes: 2 additions & 0 deletions src/pages/options/routes/Tools.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ function Tools() {
}}
actionButton={[
<Button
key="backup"
type="primary"
loading={loading.cloud}
onClick={() => {
Expand Down Expand Up @@ -115,6 +116,7 @@ function Tools() {
备份
</Button>,
<Button
key="list"
type="primary"
onClick={async () => {
let fs = await FileSystemFactory.create(
Expand Down
10 changes: 7 additions & 3 deletions src/pages/options/routes/script/ScriptEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -397,6 +397,7 @@ function ScriptEditor() {
// 没有子菜单
return (
<Button
key={`m_${item.title}`}
size="mini"
onClick={() => {
setEditors((prev) => {
Expand Down Expand Up @@ -428,6 +429,7 @@ function ScriptEditor() {
{item.items.map((menuItem, i) => {
const btn = (
<Button
key={`sm_${menuItem.title}`}
size="mini"
onClick={() => {
setEditors((prev) => {
Expand Down Expand Up @@ -481,7 +483,9 @@ function ScriptEditor() {
trigger="click"
position="bl"
>
<Button size="mini">{item.title}</Button>
<Button key={`m_${item.title}`} size="mini">
{item.title}
</Button>
</Dropdown>
);
})}
Expand Down Expand Up @@ -517,9 +521,9 @@ function ScriptEditor() {
>
已安装脚本
</Button>
{scriptList.map((script, index) => (
{scriptList.map((script) => (
<Button
key={`s_${index.toString()}`}
key={`s_${script.id}`}
size="mini"
className="text-left"
style={{
Expand Down
9 changes: 4 additions & 5 deletions src/pages/popup/App.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { ExtVersion } from "@App/app/const";
import IoC from "@App/app/ioc";
import MessageInternal from "@App/app/message/internal";
import SystemManager from "@App/app/service/system/manager";
Expand Down Expand Up @@ -41,7 +42,7 @@ function App() {
const [showAlert, setShowAlert] = useState(false);
const [notice, setNotice] = useState("");
const [isRead, setIsRead] = useState(true);
const [version, setVersion] = useState(systemManage.systemConfig.version);
const [version, setVersion] = useState(ExtVersion);

const message = IoC.instance(MessageInternal) as MessageInternal;
useEffect(() => {
Expand Down Expand Up @@ -196,10 +197,8 @@ function App() {
</CollapseItem>
</Collapse>
<div className="flex flex-row arco-card-header !h-6">
<span className="text-1 font-500">
v{systemManage.systemConfig.version}
</span>
{semver.lt(systemManage.systemConfig.version, version) && (
<span className="text-1 font-500">v{ExtVersion}</span>
{semver.lt(ExtVersion, version) && (
// eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions
<span
onClick={() => {
Expand Down
17 changes: 0 additions & 17 deletions src/pkg/config/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,23 +73,6 @@ export class SystemConfig {
return ret;
}

get version() {
return /* version */ "0.10.0-alpha.1";
}

get server() {
return "https://sc.icodef.com/";
}

get externalWhitelist() {
return [
"greasyfork.org",
"scriptcat.org",
"tampermonkey.net.cn",
"openuserjs.org",
];
}

public get changetime() {
return <number>this.cache.get("changetime") || 0;
}
Expand Down
7 changes: 7 additions & 0 deletions src/pkg/utils/match.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,13 @@ describe("UrlInclude-2", () => {
expect(url.match("http://domain2.com/")).toEqual(["ok4"]);
expect(url.match("http://domain2/123")).toEqual(["ok4"]);
});
it("nomral", () => {
const url = new UrlInclude<string>();
url.add("*://*.bilibili.com/bangumi/play/*", "ok1");
expect(url.match("https://www.bilibili.com/bangumi/play/ep691613")).toEqual(
["ok1"]
);
});
});

describe("match *", () => {
Expand Down
52 changes: 32 additions & 20 deletions src/runtime/background/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ export default class Runtime extends Manager {
"queryPageScript",
(action: string, { url, tabId }: any) => {
const tabMap = scriptMenu.get(tabId);
const matchScripts = this.match.match(url);
const matchScripts = this.matchUrl(url, false);
const scriptList: ScriptMenu[] = [];
matchScripts.forEach((item) => {
const menus: ScriptMenuItem[] = [];
Expand Down Expand Up @@ -328,25 +328,10 @@ export default class Runtime extends Manager {
return;
}

const scripts = this.match.match(sender.url);
const filter: ScriptRunResouce[] = [];

scripts.forEach((script) => {
if (script.status !== SCRIPT_STATUS_ENABLE) {
return;
}
if (script.metadata.noframes) {
if (sender.frameId !== 0) {
return;
}
}
filter.push(script);
});
if (!filter.length) {
return;
}

resolve({ flag: scriptFlag, scripts: filter });
const filter: ScriptRunResouce[] = this.matchUrl(
sender.url,
sender.frameId !== 0
);

// 注入运行框架
chrome.tabs.executeScript(sender.tabId, {
Expand All @@ -361,6 +346,14 @@ export default class Runtime extends Manager {
}())`,
runAt: "document_start",
});

if (!filter.length) {
resolve({ flag: scriptFlag, scripts: [] });
return;
}

resolve({ flag: scriptFlag, scripts: filter });

// 注入脚本
filter.forEach((script) => {
let runAt = "document_idle";
Expand Down Expand Up @@ -450,6 +443,25 @@ export default class Runtime extends Manager {
return this.disable(script);
}

matchUrl(url: string, frame: boolean) {
const scripts = this.match.match(url);
// 再include中匹配
scripts.push(...this.include.match(url));
const filter: { [key: string]: ScriptRunResouce } = {};
// 去重
scripts.forEach((script) => {
if (script.status !== SCRIPT_STATUS_ENABLE) {
return;
}
if (frame && script.metadata.noframes) {
return;
}
filter[script.id] = script;
});
// 转换成数组
return Object.keys(filter).map((key) => filter[key]);
}

// 脚本删除
async scriptDelete(script: Script): Promise<boolean> {
// 清理匹配资源
Expand Down
Loading

0 comments on commit fe96990

Please sign in to comment.