workflow-engine.js 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. /* eslint-disable no-underscore-dangle */
  2. import browser from 'webextension-polyfill';
  3. import { nanoid } from 'nanoid';
  4. import { toCamelCase } from '@/utils/helper';
  5. import { tasks } from '@/utils/shared';
  6. import * as blocksHandler from './blocks-handler';
  7. import workflowState from './workflow-state';
  8. let reloadTimeout;
  9. function tabMessageHandler({ type, data }) {
  10. const listener = this.tabMessageListeners[type];
  11. if (listener) {
  12. setTimeout(() => {
  13. listener.callback(data);
  14. }, listener.delay || 0);
  15. if (listener.once) delete this.tabMessageListeners[type];
  16. }
  17. }
  18. function tabRemovedHandler(tabId) {
  19. if (tabId !== this.tabId) return;
  20. this.connectedTab?.onMessage.removeListener(this.tabMessageHandler);
  21. this.connectedTab?.disconnect();
  22. delete this.connectedTab;
  23. delete this.tabId;
  24. }
  25. function tabUpdatedHandler(tabId, changeInfo) {
  26. const listener = this.tabUpdatedListeners[tabId];
  27. if (listener) {
  28. listener.callback(tabId, changeInfo, () => {
  29. delete this.tabUpdatedListeners[tabId];
  30. });
  31. } else if (this.tabId === tabId) {
  32. if (!reloadTimeout) {
  33. console.log('===Register Timeout===');
  34. reloadTimeout = setTimeout(() => {
  35. this.isPaused = false;
  36. }, 15000);
  37. }
  38. this.isPaused = true;
  39. if (changeInfo.status === 'complete') {
  40. console.log('clearTimeout');
  41. clearTimeout(reloadTimeout);
  42. reloadTimeout = null;
  43. browser.tabs
  44. .executeScript(tabId, {
  45. file: './contentScript.bundle.js',
  46. })
  47. .then(() => {
  48. console.log(this.currentBlock);
  49. if (this.connectedTab) this._connectTab(this.tabId);
  50. this.isPaused = false;
  51. })
  52. .catch((error) => {
  53. console.error(error);
  54. this.isPaused = false;
  55. });
  56. }
  57. }
  58. }
  59. class WorkflowEngine {
  60. constructor(workflow) {
  61. this.id = nanoid();
  62. this.workflow = workflow;
  63. this.data = {};
  64. this.blocks = {};
  65. this.eventListeners = {};
  66. this.repeatedTasks = {};
  67. this.logs = [];
  68. this.blocksArr = [];
  69. this.isPaused = false;
  70. this.isDestroyed = false;
  71. this.currentBlock = null;
  72. this.tabMessageListeners = {};
  73. this.tabUpdatedListeners = {};
  74. this.tabMessageHandler = tabMessageHandler.bind(this);
  75. this.tabUpdatedHandler = tabUpdatedHandler.bind(this);
  76. this.tabRemovedHandler = tabRemovedHandler.bind(this);
  77. }
  78. init() {
  79. const drawflowData =
  80. typeof this.workflow.drawflow === 'string'
  81. ? JSON.parse(this.workflow.drawflow || '{}')
  82. : this.workflow.drawflow;
  83. const blocks = drawflowData?.drawflow.Home.data;
  84. if (!blocks) {
  85. console.error('No block is found');
  86. return;
  87. }
  88. const blocksArr = Object.values(blocks);
  89. const triggerBlock = blocksArr.find(({ name }) => name === 'trigger');
  90. if (!triggerBlock) {
  91. console.error('A trigger block is required');
  92. return;
  93. }
  94. browser.tabs.onUpdated.addListener(this.tabUpdatedHandler);
  95. browser.tabs.onRemoved.addListener(this.tabRemovedHandler);
  96. this.blocks = blocks;
  97. this.blocksArr = blocksArr;
  98. this.startedTimestamp = Date.now();
  99. workflowState.add(this.id, this.state).then(() => {
  100. this._blockHandler(triggerBlock);
  101. });
  102. }
  103. on(name, listener) {
  104. (this.eventListeners[name] = this.eventListeners[name] || []).push(
  105. listener
  106. );
  107. }
  108. pause(pause = true) {
  109. this.isPaused = pause;
  110. workflowState.update(this.tabId, this.state);
  111. }
  112. destroy() {
  113. // save log
  114. this.dispatchEvent('destroyed', this.workflow.id);
  115. this.eventListeners = {};
  116. this.tabMessageListeners = {};
  117. this.tabUpdatedListeners = {};
  118. browser.tabs.onRemoved.removeListener(this.tabRemovedHandler);
  119. browser.tabs.onUpdated.removeListener(this.tabUpdatedHandler);
  120. workflowState.delete(this.id);
  121. this.isDestroyed = true;
  122. this.endedTimestamp = Date.now();
  123. }
  124. dispatchEvent(name, params) {
  125. const listeners = this.eventListeners[name];
  126. console.log(name, this.eventListeners);
  127. if (!listeners) return;
  128. listeners.forEach((callback) => {
  129. callback(params);
  130. });
  131. }
  132. get state() {
  133. const keys = ['tabId', 'isPaused', 'isDestroyed', 'currentBlock'];
  134. return keys.reduce((acc, key) => {
  135. acc[key] = this[key];
  136. return acc;
  137. }, {});
  138. }
  139. _blockHandler(block, prevBlockData) {
  140. if (this.isDestroyed) {
  141. console.log(
  142. '%cDestroyed',
  143. 'color: red; font-size: 24px; font-weight: bold'
  144. );
  145. return;
  146. }
  147. if (this.isPaused) {
  148. console.log(this.isPaused, 'pause');
  149. setTimeout(() => {
  150. this._blockHandler(block, prevBlockData);
  151. }, 1000);
  152. return;
  153. }
  154. workflowState.update(this.id, this.state);
  155. console.log(`${block.name}:`, block);
  156. this.currentBlock = block;
  157. const isInteraction = tasks[block.name].category === 'interaction';
  158. const handlerName = isInteraction
  159. ? 'interactionHandler'
  160. : toCamelCase(block?.name);
  161. const handler = blocksHandler[handlerName];
  162. if (handler) {
  163. handler
  164. .call(this, block, prevBlockData)
  165. .then((result) => {
  166. if (result.nextBlockId) {
  167. this._blockHandler(this.blocks[result.nextBlockId], result.data);
  168. } else {
  169. this.dispatchEvent('finish');
  170. this.destroy();
  171. console.log('Done', this);
  172. }
  173. })
  174. .catch((error) => {
  175. workflowState.console.error(error, 'new');
  176. });
  177. } else {
  178. console.error(`"${block.name}" block doesn't have a handler`);
  179. }
  180. }
  181. _connectTab(tabId) {
  182. const connectedTab = browser.tabs.connect(tabId, {
  183. name: `${this.workflow.id}--${this.workflow.name.slice(0, 10)}`,
  184. });
  185. if (this.connectedTab) {
  186. this.connectedTab.onMessage.removeListener(this.tabMessageHandler);
  187. this.connectedTab.disconnect();
  188. }
  189. connectedTab.onMessage.addListener(this.tabMessageHandler);
  190. this.connectedTab = connectedTab;
  191. this.tabId = tabId;
  192. return connectedTab;
  193. }
  194. _listener({ id, name, callback, once = true, ...options }) {
  195. const listenerNames = {
  196. event: 'eventListener',
  197. 'tab-updated': 'tabUpdatedListeners',
  198. 'tab-message': 'tabMessageListeners',
  199. };
  200. this[listenerNames[name]][id] = { callback, once, ...options };
  201. return () => {
  202. delete this.tabMessageListeners[id];
  203. };
  204. }
  205. }
  206. export default WorkflowEngine;