index.js 8.8 KB

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