index.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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 errorMessage from './error-message';
  7. import referenceData from '@/utils/reference-data';
  8. import workflowState from '../workflow-state';
  9. import * as blocksHandler from './blocks-handler';
  10. let reloadTimeout;
  11. function tabRemovedHandler(tabId) {
  12. if (tabId !== this.tabId) return;
  13. delete this.tabId;
  14. if (tasks[this.currentBlock.name].category === 'interaction') {
  15. this.destroy('error', 'Current active tab is removed');
  16. }
  17. workflowState.update(this.id, this.state);
  18. }
  19. function tabUpdatedHandler(tabId, changeInfo) {
  20. const listener = this.tabUpdatedListeners[tabId];
  21. if (listener) {
  22. listener.callback(tabId, changeInfo, () => {
  23. delete this.tabUpdatedListeners[tabId];
  24. });
  25. } else if (this.tabId === tabId) {
  26. if (!reloadTimeout) {
  27. reloadTimeout = setTimeout(() => {
  28. this.isPaused = false;
  29. }, 15000);
  30. }
  31. this.isPaused = true;
  32. if (changeInfo.status === 'complete') {
  33. clearTimeout(reloadTimeout);
  34. reloadTimeout = null;
  35. browser.tabs
  36. .executeScript(tabId, {
  37. file: './contentScript.bundle.js',
  38. })
  39. .then(() => {
  40. this.tabId = tabId;
  41. this.isPaused = false;
  42. })
  43. .catch((error) => {
  44. console.error(error);
  45. this.isPaused = false;
  46. });
  47. }
  48. }
  49. }
  50. class WorkflowEngine {
  51. constructor(workflow, { tabId = null, isInCollection, collectionLogId }) {
  52. this.id = nanoid();
  53. this.tabId = tabId;
  54. this.workflow = workflow;
  55. this.isInCollection = isInCollection;
  56. this.collectionLogId = collectionLogId;
  57. this.data = {};
  58. this.blocks = {};
  59. this.frames = {};
  60. this.eventListeners = {};
  61. this.repeatedTasks = {};
  62. this.loopList = {};
  63. this.loopData = {};
  64. this.logs = [];
  65. this.isPaused = false;
  66. this.isDestroyed = false;
  67. this.currentBlock = null;
  68. this.workflowTimeout = null;
  69. this.windowId = null;
  70. this.tabUpdatedListeners = {};
  71. this.tabUpdatedHandler = tabUpdatedHandler.bind(this);
  72. this.tabRemovedHandler = tabRemovedHandler.bind(this);
  73. }
  74. init() {
  75. const drawflowData =
  76. typeof this.workflow.drawflow === 'string'
  77. ? JSON.parse(this.workflow.drawflow || '{}')
  78. : this.workflow.drawflow;
  79. const blocks = drawflowData?.drawflow.Home.data;
  80. if (!blocks) {
  81. console.error(errorMessage('no-block', this.workflow));
  82. return;
  83. }
  84. const blocksArr = Object.values(blocks);
  85. const triggerBlock = blocksArr.find(({ name }) => name === 'trigger');
  86. if (!triggerBlock) {
  87. console.error(errorMessage('no-trigger-block', this.workflow));
  88. return;
  89. }
  90. browser.tabs.onUpdated.addListener(this.tabUpdatedHandler);
  91. browser.tabs.onRemoved.addListener(this.tabRemovedHandler);
  92. const dataColumns = Array.isArray(this.workflow.dataColumns)
  93. ? this.workflow.dataColumns
  94. : Object.values(this.workflow.dataColumns);
  95. this.blocks = blocks;
  96. this.startedTimestamp = Date.now();
  97. this.workflow.dataColumns = dataColumns;
  98. this.data = dataColumns.reduce(
  99. (acc, column) => {
  100. acc[column.name] = [];
  101. return acc;
  102. },
  103. { column: [] }
  104. );
  105. workflowState
  106. .add(this.id, {
  107. state: this.state,
  108. workflowId: this.workflow.id,
  109. isInCollection: this.isInCollection,
  110. })
  111. .then(() => {
  112. this._blockHandler(triggerBlock);
  113. });
  114. }
  115. on(name, listener) {
  116. (this.eventListeners[name] = this.eventListeners[name] || []).push(
  117. listener
  118. );
  119. }
  120. pause(pause = true) {
  121. this.isPaused = pause;
  122. workflowState.update(this.id, this.state);
  123. }
  124. stop(message) {
  125. this.logs.push({
  126. message,
  127. type: 'stop',
  128. name: 'Workflow is stopped',
  129. });
  130. this.destroy('stopped');
  131. }
  132. async destroy(status, message) {
  133. try {
  134. this.dispatchEvent('destroyed', { id: this.id, status, message });
  135. this.eventListeners = {};
  136. this.tabUpdatedListeners = {};
  137. await browser.tabs.onRemoved.removeListener(this.tabRemovedHandler);
  138. await browser.tabs.onUpdated.removeListener(this.tabUpdatedHandler);
  139. await workflowState.delete(this.id);
  140. clearTimeout(this.workflowTimeout);
  141. this.isDestroyed = true;
  142. this.endedTimestamp = Date.now();
  143. if (!this.workflow.isTesting) {
  144. const { logs } = await browser.storage.local.get('logs');
  145. const { name, icon, id } = this.workflow;
  146. logs.push({
  147. name,
  148. icon,
  149. status,
  150. id: this.id,
  151. workflowId: id,
  152. data: this.data,
  153. history: this.logs,
  154. endedAt: this.endedTimestamp,
  155. startedAt: this.startedTimestamp,
  156. isInCollection: this.isInCollection,
  157. collectionLogId: this.collectionLogId,
  158. });
  159. await browser.storage.local.set({ logs });
  160. }
  161. } catch (error) {
  162. console.error(error);
  163. }
  164. }
  165. dispatchEvent(name, params) {
  166. const listeners = this.eventListeners[name];
  167. if (!listeners) return;
  168. listeners.forEach((callback) => {
  169. callback(params);
  170. });
  171. }
  172. get state() {
  173. const keys = [
  174. 'tabId',
  175. 'isPaused',
  176. 'isDestroyed',
  177. 'currentBlock',
  178. 'isInCollection',
  179. 'startedTimestamp',
  180. ];
  181. const state = keys.reduce((acc, key) => {
  182. acc[key] = this[key];
  183. return acc;
  184. }, {});
  185. state.name = this.workflow.name;
  186. state.icon = this.workflow.icon;
  187. return state;
  188. }
  189. _blockHandler(block, prevBlockData) {
  190. if (this.isDestroyed) return;
  191. if (this.isPaused) {
  192. setTimeout(() => {
  193. this._blockHandler(block, prevBlockData);
  194. }, 1000);
  195. return;
  196. }
  197. const disableTimeoutKeys = ['delay', 'javascript-code'];
  198. if (!disableTimeoutKeys.includes(block.name)) {
  199. this.workflowTimeout = setTimeout(() => {
  200. if (!this.isDestroyed) this.stop('Workflow stopped because of timeout');
  201. }, this.workflow.settings.timeout || 120000);
  202. }
  203. this.currentBlock = block;
  204. workflowState.update(this.id, this.state);
  205. this.dispatchEvent('update', this.state);
  206. const started = Date.now();
  207. const isInteraction = tasks[block.name].category === 'interaction';
  208. const handlerName = isInteraction
  209. ? 'interactionHandler'
  210. : toCamelCase(block?.name);
  211. const handler = blocksHandler[handlerName];
  212. if (handler) {
  213. const replacedBlock = referenceData(block, {
  214. prevBlockData,
  215. data: this.data,
  216. loopData: this.loopData,
  217. });
  218. handler
  219. .call(this, replacedBlock, prevBlockData)
  220. .then((result) => {
  221. clearTimeout(this.workflowTimeout);
  222. this.workflowTimeout = null;
  223. if (result.nextBlockId) {
  224. this.logs.push({
  225. type: 'success',
  226. name: tasks[block.name].name,
  227. data: result.data,
  228. duration: Math.round(Date.now() - started),
  229. });
  230. this._blockHandler(this.blocks[result.nextBlockId], result.data);
  231. } else {
  232. this.logs.push({
  233. type: 'finish',
  234. message: 'Workflow finished running',
  235. name: 'Finish',
  236. });
  237. this.dispatchEvent('finish');
  238. this.destroy('success');
  239. }
  240. })
  241. .catch((error) => {
  242. this.logs.push({
  243. type: 'error',
  244. message: error.message,
  245. name: tasks[block.name].name,
  246. });
  247. if (
  248. this.workflow.settings.onError === 'keep-running' &&
  249. error.nextBlockId
  250. ) {
  251. this._blockHandler(
  252. this.blocks[error.nextBlockId],
  253. error.data || ''
  254. );
  255. } else {
  256. this.destroy('error', error.message);
  257. }
  258. clearTimeout(this.workflowTimeout);
  259. this.workflowTimeout = null;
  260. console.error(error);
  261. });
  262. } else {
  263. console.error(`"${block.name}" block doesn't have a handler`);
  264. }
  265. }
  266. _sendMessageToTab(block, options = {}) {
  267. return new Promise((resolve, reject) => {
  268. if (!this.tabId) {
  269. const message = errorMessage('no-tab', tasks[block.name]);
  270. reject(new Error(message));
  271. }
  272. browser.tabs
  273. .sendMessage(this.tabId, { isBlock: true, ...block }, options)
  274. .then(resolve)
  275. .catch(reject);
  276. });
  277. }
  278. _listener({ id, name, callback, once = true, ...options }) {
  279. const listenerNames = {
  280. event: 'eventListener',
  281. 'tab-updated': 'tabUpdatedListeners',
  282. };
  283. this[listenerNames[name]][id] = { callback, once, ...options };
  284. return () => {
  285. delete this.tabMessageListeners[id];
  286. };
  287. }
  288. }
  289. export default WorkflowEngine;