workflow-engine.js 6.1 KB

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