<commit_before>// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

import browser from "webextension-polyfill";
import UiState from "../../stores/view/UiState";
import record from "./record";
import { sendRecordNotification } from "../notifications";
import { Logger, Channels } from "../../stores/view/Logs";

const logger = new Logger(Channels.PLAYBACK);

function getSelectedCase() {
  return {
    id: UiState.selectedTest.test.id
  };
}

function hasRecorded() {
  return !!UiState.selectedTest.test.commands.length;
}

export default class BackgroundRecorder {
  constructor(windowSession) {
    // The only way to know if a tab is recordable is to assume it is, and verify it sends a record
    // In order to do that we need to optimistically attach the recorder to all tabs, and try to
    // remove it, even if it's in a priviledged tab
    this.windowSession = windowSession;
    this.lastAttachedTabId = undefined;
    this.isAttaching = false;
    this.attached = false;
    this.rebind();
    if (browser && browser.runtime && browser.runtime.onMessage) {
      browser.runtime.onMessage.addListener(this.attachRecorderRequestHandler);
    }
  }

  async attachToTab(tabId) {
    await browser.tabs.sendMessage(tabId, { attachRecorder: true });
  }

  async detachFromTab(tabId) {
    await browser.tabs.sendMessage(tabId, { detachRecorder: true }).catch(() => {
      // the tab was deleted during the test, ignoring
    });
  }

  async reattachToTab(tabId) {
    if (tabId !== this.lastAttachedTabId) {
      if (this.lastAttachedTabId && this.lastAttachedTabId !== tabId) {
        await this.detachFromTab(this.lastAttachedTabId);
      }
      await this.attachToTab(tabId);
      this.lastAttachedTabId = tabId;
    }
  }

  // TODO: rename method
  tabsOnActivatedHandler(activeInfo) {
    console.log("tabs.onActivated");
    let testCase = getSelectedCase();
    if (!testCase) {
      return;
    }
    let testCaseId = testCase.id;
    if (!this.windowSession.openedTabIds[testCaseId]) {
      return;
    }

    if (this.windowSession.openedTabIds[testCaseId] && this.doesTabBelongToRecording(activeInfo.tabId)) {
      this.reattachToTab(activeInfo.tabId);
    }

    // Because event listener is so fast that selectWindow command is added
    // before other commands like clicking a link to browse in new tab.
    // Delay a little time to add command in order.
    setTimeout(function() {
      if (this.windowSession.currentRecordingTabId[testCaseId] === activeInfo.tabId && this.windowSession.currentRecordingWindowId[testCaseId] === activeInfo.windowId)
        return;
      // If no command has been recorded, ignore selectWindow command
      // until the user has select a starting page to record the commands
      if (!hasRecorded())
        return;
      // Ignore all unknown tabs, the activated tab may not derived from
      // other opened tabs, or it may managed by other SideeX panels
      if (this.windowSession.openedTabIds[testCaseId][activeInfo.tabId] == undefined)
        return;
      // Tab information has existed, add selectWindow command
      this.windowSession.currentRecordingTabId[testCaseId] = activeInfo.tabId;
      this.windowSession.currentRecordingWindowId[testCaseId] = activeInfo.windowId;
      this.windowSession.currentRecordingFrameLocation[testCaseId] = "root";
      record("selectWindow", [[this.windowSession.openedTabIds[testCaseId][activeInfo.tabId]]], "");
    }, 150);
  }

  windowsOnFocusChangedHandler(windowId) {
    console.log("windows.onFocusChanged");
    let testCase = getSelectedCase();
    if (!testCase) {
      return;
    }
    let testCaseId = testCase.id;
    if (!this.windowSession.openedTabIds[testCaseId]) {<commit_msg>fixed a bug while recording window changes<commit_after>// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

import browser from "webextension-polyfill";
import UiState from "../../stores/view/UiState";
import record from "./record";
import { sendRecordNotification } from "../notifications";
import { Logger, Channels } from "../../stores/view/Logs";

const logger = new Logger(Channels.PLAYBACK);

function getSelectedCase() {
  return {
    id: UiState.selectedTest.test.id
  };
}

function hasRecorded() {
  return !!UiState.selectedTest.test.commands.length;
}

export default class BackgroundRecorder {
  constructor(windowSession) {
    // The only way to know if a tab is recordable is to assume it is, and verify it sends a record
    // In order to do that we need to optimistically attach the recorder to all tabs, and try to
    // remove it, even if it's in a priviledged tab
    this.windowSession = windowSession;
    this.lastAttachedTabId = undefined;
    this.isAttaching = false;
    this.attached = false;
    this.rebind();
    if (browser && browser.runtime && browser.runtime.onMessage) {
      browser.runtime.onMessage.addListener(this.attachRecorderRequestHandler);
    }
  }

  async attachToTab(tabId) {
    await browser.tabs.sendMessage(tabId, { attachRecorder: true });
  }

  async detachFromTab(tabId) {
    await browser.tabs.sendMessage(tabId, { detachRecorder: true }).catch(() => {
      // the tab was deleted during the test, ignoring
    });
  }

  async reattachToTab(tabId) {
    if (tabId !== this.lastAttachedTabId) {
      if (this.lastAttachedTabId && this.lastAttachedTabId !== tabId) {
        await this.detachFromTab(this.lastAttachedTabId);
      }
      await this.attachToTab(tabId);
      this.lastAttachedTabId = tabId;
    }
  }

  // TODO: rename method
  tabsOnActivatedHandler(activeInfo) {
    console.log("tabs.onActivated");
    let testCase = getSelectedCase();
    if (!testCase) {
      return;
    }
    let testCaseId = testCase.id;
    if (!this.windowSession.openedTabIds[testCaseId]) {
      return;
    }

    if (this.windowSession.openedTabIds[testCaseId] && this.doesTabBelongToRecording(activeInfo.tabId)) {
      this.reattachToTab(activeInfo.tabId);
    }

    // Because event listener is so fast that selectWindow command is added
    // before other commands like clicking a link to browse in new tab.
    // Delay a little time to add command in order.
    setTimeout(() => {
      if (this.windowSession.currentRecordingTabId[testCaseId] === activeInfo.tabId && this.windowSession.currentRecordingWindowId[testCaseId] === activeInfo.windowId)
        return;
      // If no command has been recorded, ignore selectWindow command
      // until the user has select a starting page to record the commands
      if (!hasRecorded())
        return;
      // Ignore all unknown tabs, the activated tab may not derived from
      // other opened tabs, or it may managed by other SideeX panels
      if (this.windowSession.openedTabIds[testCaseId][activeInfo.tabId] == undefined)
        return;
      // Tab information has existed, add selectWindow command
      this.windowSession.currentRecordingTabId[testCaseId] = activeInfo.tabId;
      this.windowSession.currentRecordingWindowId[testCaseId] = activeInfo.windowId;
      this.windowSession.currentRecordingFrameLocation[testCaseId] = "root";
      record("selectWindow", [[this.windowSession.openedTabIds[testCaseId][activeInfo.tabId]]], "");
    }, 150);
  }

  windowsOnFocusChangedHandler(windowId) {
    console.log("windows.onFocusChanged");
    let testCase = getSelectedCase();
    if (!testCase) {
      return;
    }
    let testCaseId = testCase.id;
    if (!this.windowSession.openedTabIds[testCaseId]) {
{'fraction_non_alphanumeric': 0.10095832404724761, 'fraction_numerical': 0.0015600624024961, 'mean_word_length': 3.4474727452923686, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 6, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2975022', 'n_tokens_mistral': 2548, 'n_tokens_neox': 2511, 'n_words': 784}