123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284 |
- /* eslint-disable no-underscore-dangle */
- import browser from 'webextension-polyfill';
- import { nanoid } from 'nanoid';
- import { toCamelCase } from '@/utils/helper';
- import { tasks } from '@/utils/shared';
- import errorMessage from './error-message';
- import workflowState from './workflow-state';
- import * as blocksHandler from './blocks-handler';
- let reloadTimeout;
- function tabMessageHandler({ type, data }) {
- const listener = this.tabMessageListeners[type];
- if (listener) {
- setTimeout(() => {
- listener.callback(data);
- }, listener.delay || 0);
- if (listener.once) delete this.tabMessageListeners[type];
- }
- }
- function tabRemovedHandler(tabId) {
- if (tabId !== this.tabId) return;
- this.connectedTab?.onMessage.removeListener(this.tabMessageHandler);
- this.connectedTab?.disconnect();
- delete this.connectedTab;
- delete this.tabId;
- }
- function tabUpdatedHandler(tabId, changeInfo) {
- const listener = this.tabUpdatedListeners[tabId];
- if (listener) {
- listener.callback(tabId, changeInfo, () => {
- delete this.tabUpdatedListeners[tabId];
- });
- } else if (this.tabId === tabId) {
- if (!reloadTimeout) {
- console.log('===Register Timeout===');
- reloadTimeout = setTimeout(() => {
- this.isPaused = false;
- }, 15000);
- }
- this.isPaused = true;
- if (changeInfo.status === 'complete') {
- console.log('clearTimeout');
- clearTimeout(reloadTimeout);
- reloadTimeout = null;
- browser.tabs
- .executeScript(tabId, {
- file: './contentScript.bundle.js',
- })
- .then(() => {
- console.log(this.currentBlock);
- if (this.connectedTab) this._connectTab(this.tabId);
- this.isPaused = false;
- })
- .catch((error) => {
- console.error(error);
- this.isPaused = false;
- });
- }
- }
- }
- class WorkflowEngine {
- constructor(workflow) {
- this.id = nanoid();
- this.workflow = workflow;
- this.data = {};
- this.blocks = {};
- this.eventListeners = {};
- this.repeatedTasks = {};
- this.logs = [];
- this.blocksArr = [];
- this.isPaused = false;
- this.isDestroyed = false;
- this.currentBlock = null;
- this.workflowTimeout = null;
- this.tabMessageListeners = {};
- this.tabUpdatedListeners = {};
- this.tabMessageHandler = tabMessageHandler.bind(this);
- this.tabUpdatedHandler = tabUpdatedHandler.bind(this);
- this.tabRemovedHandler = tabRemovedHandler.bind(this);
- }
- init() {
- const drawflowData =
- typeof this.workflow.drawflow === 'string'
- ? JSON.parse(this.workflow.drawflow || '{}')
- : this.workflow.drawflow;
- const blocks = drawflowData?.drawflow.Home.data;
- if (!blocks) {
- console.error(errorMessage('no-block', this.workflow));
- return;
- }
- const blocksArr = Object.values(blocks);
- const triggerBlock = blocksArr.find(({ name }) => name === 'trigger');
- if (!triggerBlock) {
- console.error(errorMessage('no-trigger-block', this.workflow));
- return;
- }
- browser.tabs.onUpdated.addListener(this.tabUpdatedHandler);
- browser.tabs.onRemoved.addListener(this.tabRemovedHandler);
- this.blocks = blocks;
- this.blocksArr = blocksArr;
- this.startedTimestamp = Date.now();
- workflowState.add(this.id, this.state).then(() => {
- this._blockHandler(triggerBlock);
- });
- }
- on(name, listener) {
- (this.eventListeners[name] = this.eventListeners[name] || []).push(
- listener
- );
- }
- pause(pause = true) {
- this.isPaused = pause;
- workflowState.update(this.tabId, this.state);
- }
- stop() {
- /* to-do add stop log */
- console.log('stoppp');
- this.destroy();
- }
- destroy() {
- // save log
- this.dispatchEvent('destroyed', this.workflow.id);
- this.eventListeners = {};
- this.tabMessageListeners = {};
- this.tabUpdatedListeners = {};
- browser.tabs.onRemoved.removeListener(this.tabRemovedHandler);
- browser.tabs.onUpdated.removeListener(this.tabUpdatedHandler);
- workflowState.delete(this.id);
- this.isDestroyed = true;
- this.endedTimestamp = Date.now();
- }
- dispatchEvent(name, params) {
- const listeners = this.eventListeners[name];
- console.log(name, this.eventListeners);
- if (!listeners) return;
- listeners.forEach((callback) => {
- callback(params);
- });
- }
- get state() {
- const keys = ['tabId', 'isPaused', 'isDestroyed', 'currentBlock'];
- return keys.reduce((acc, key) => {
- acc[key] = this[key];
- return acc;
- }, {});
- }
- _blockHandler(block, prevBlockData) {
- if (this.isDestroyed) {
- console.log(
- '%cDestroyed',
- 'color: red; font-size: 24px; font-weight: bold'
- );
- return;
- }
- if (this.isPaused) {
- console.log(this.isPaused, 'pause');
- setTimeout(() => {
- this._blockHandler(block, prevBlockData);
- }, 1000);
- return;
- }
- console.log(this.workflow);
- this.workflowTimeout = setTimeout(
- () => this.stop(),
- this.workflow.settings.timeout || 120000
- );
- workflowState.update(this.id, this.state);
- console.log(`${block.name}:`, block);
- this.currentBlock = block;
- const isInteraction = tasks[block.name].category === 'interaction';
- const handlerName = isInteraction
- ? 'interactionHandler'
- : toCamelCase(block?.name);
- const handler = blocksHandler[handlerName];
- if (handler) {
- handler
- .call(this, block, prevBlockData)
- .then((result) => {
- if (result.nextBlockId) {
- this._blockHandler(this.blocks[result.nextBlockId], result.data);
- } else {
- this.dispatchEvent('finish');
- this.stop();
- console.log('Done', this);
- }
- clearTimeout(this.workflowTimeout);
- this.workflowTimeout = null;
- })
- .catch((error) => {
- if (
- this.workflow.settings.onError === 'keep-running' &&
- error.nextBlockId
- ) {
- this._blockHandler(
- this.blocks[error.nextBlockId],
- error.data || ''
- );
- } else {
- this.stop();
- }
- clearTimeout(this.workflowTimeout);
- this.workflowTimeout = null;
- console.dir(error);
- console.error(error, 'new');
- });
- } else {
- console.error(`"${block.name}" block doesn't have a handler`);
- }
- }
- _connectTab(tabId) {
- const connectedTab = browser.tabs.connect(tabId, {
- name: `${this.workflow.id}--${this.workflow.name.slice(0, 10)}`,
- });
- if (this.connectedTab) {
- this.connectedTab.onMessage.removeListener(this.tabMessageHandler);
- this.connectedTab.disconnect();
- }
- connectedTab.onMessage.addListener(this.tabMessageHandler);
- this.connectedTab = connectedTab;
- this.tabId = tabId;
- return connectedTab;
- }
- _listener({ id, name, callback, once = true, ...options }) {
- const listenerNames = {
- event: 'eventListener',
- 'tab-updated': 'tabUpdatedListeners',
- 'tab-message': 'tabMessageListeners',
- };
- this[listenerNames[name]][id] = { callback, once, ...options };
- return () => {
- delete this.tabMessageListeners[id];
- };
- }
- }
- export default WorkflowEngine;
|