1
This commit is contained in:
85
src/popup/hook/use-scan.ts
Normal file
85
src/popup/hook/use-scan.ts
Normal file
@@ -0,0 +1,85 @@
|
||||
import {onMounted, onUnmounted, ref} from "vue";
|
||||
import {platformConfigs} from "@/config/platforms";
|
||||
import {CrawlTaskState} from "@/types";
|
||||
import {sendBackgroundMessage} from "@/shared/message";
|
||||
|
||||
export const useScan = () => {
|
||||
//选中id
|
||||
const selectedPlatformId = ref(platformConfigs[0]?.id ?? '');
|
||||
//防抖
|
||||
const isScanning = ref<boolean>(false)
|
||||
//步骤数据
|
||||
const crawlState = ref<CrawlTaskState | null>(null);
|
||||
//爬取时间
|
||||
const elapsedSeconds = ref<number>(0)
|
||||
|
||||
|
||||
let timer: number | undefined;
|
||||
/**
|
||||
* 开始爬取
|
||||
*/
|
||||
const handleScan = async () => {
|
||||
if (isScanning.value) return
|
||||
isScanning.value = true
|
||||
try {
|
||||
updateSeconds()
|
||||
//定时器
|
||||
timer = window.setInterval(() => {
|
||||
updateSeconds();
|
||||
}, 1000);
|
||||
//发送
|
||||
const response = await sendBackgroundMessage<CrawlTaskState>({
|
||||
action: 'START_CRAWL',
|
||||
payload: {platformId: selectedPlatformId.value},
|
||||
});
|
||||
if (response.data) {
|
||||
crawlState.value = response.data;
|
||||
}
|
||||
} finally {
|
||||
isScanning.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 更新时间
|
||||
*/
|
||||
function updateSeconds() {
|
||||
if (!crawlState.value) {
|
||||
elapsedSeconds.value = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
elapsedSeconds.value = Math.max(0, Math.floor((Date.now() - crawlState.value.startedAt) / 1000));
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步爬取状态
|
||||
*/
|
||||
async function refreshCrawlState() {
|
||||
const response = await sendBackgroundMessage<CrawlTaskState | null>({action: 'GET_CRAWL_STATE'});
|
||||
|
||||
if (response.data) {
|
||||
crawlState.value = response.data ?? null;
|
||||
updateSeconds();
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await refreshCrawlState()
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
if (timer) {
|
||||
window.clearInterval(timer);
|
||||
}
|
||||
})
|
||||
|
||||
return {
|
||||
selectedPlatformId,
|
||||
isScanning,
|
||||
crawlState,
|
||||
handleScan,
|
||||
elapsedSeconds,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user