sinkesol / Huawei Relevance Tools

// ==UserScript==
// @name         Huawei Relevance Tools
// @version      0.151
// @author       sinkesol
// @match        iframe-toloka.com
// @grant        none
// @downloadURL  https://openuserjs.org/install/sinkesol/Huawei_Relevance_Tools.user.js
// @updateURL    https://openuserjs.org/meta/sinkesol/Huawei_Relevance_Tools.meta.js
// @license      MIT
// ==/UserScript==

/* jshint esversion: 6 */

/* 

    ХОТКЕИ:

    D - открыть Google выдачу с инфой по доставке 

    Z - открыть Google перевод текущего урла  

    X - открыть Яндекс перевод текущего урла 

*/

let init = false;
let readyStateCheckInterval;

const EMPTY_SANDBOX_DOMAINS = ["vk.com", "play.google", "chrome.google", "medium.com", "otvet.mail.ru"];

const SEARCH_DATA = {
  "shipping_keywords": {
    "KeyD": {
      "ie": ["ireland", "irish", "international shipping", "international orders", "shipping delivery", "shipping", "delivery", "worldwide"],
      "ru": ["доставка", "регионы", "регионы доставки", "почта россии", "EMS", "курьер", "постамат", "наложенный платёж", "в пределах города"],
      "ua": []
    }
  },
  "translate_link": {
    "KeyZ": "https://translate.google.ru/translate?sl=auto&tl=ru&u=",
    "KeyX": "https://translate.yandex.ru/translate?lang=ru&url="
  }
};

const REGION_CODE_DATA = {
  "Россия": "ru",
  "Ирландия": "ie",
  "Украина": "ua"
};

/* ------------------------------------------------------------- */

function relevanceHuawei(tasks, taskSuite) {

  const nodes = document.querySelectorAll(".task-suite > .task");

  if (init) {
    document.addEventListener("keydown", listenerKeydown);
  }

  init = false;

  for (const node of nodes) {

    const {
      url,
      region_code,
      region
    } = tasks[node.dataset.microtaskIndex].input_values;

    node.dataset.url = url;
    node.dataset.regionCode = region_code || REGION_CODE_DATA[region];

    setSandbox(node, url);

  }

}

/* ------------------------------------------------------------- */

function start() {
  readyStateCheckInterval = setInterval(() => window.addEventListener("message", listenerMessage), 100);
}

function listenerKeydown(event) {

  const currentNode = document.querySelector(".task_focused");
  const isTextareaFocused = currentNode.querySelector(".textarea_focus_yes");

  if (isTextareaFocused) return;
  const {
    url,
    regionCode
  } = currentNode.dataset;

  if (event.code in SEARCH_DATA.shipping_keywords) {
    const shippingInfoSearchLink = createSearchLink(getDomain(url), SEARCH_DATA.shipping_keywords[event.code][regionCode]);
    if (shippingInfoSearchLink) window.open(shippingInfoSearchLink);
  }

  if (event.code in SEARCH_DATA.translate_link) {
    const translateLink = SEARCH_DATA.translate_link[event.code] + url;
    if (translateLink) window.open(translateLink);
  }

}

function listenerMessage(event) {

  const {
    data
  } = event;

  if ('workspace:init' === data.eventType) init = true;

  if (isTolokaTemplateLoaded(data)) {
    clearInterval(readyStateCheckInterval);
    selectProject(data);
  }

}

function selectProject(data) {

  const {
    projectId,
    tasks,
    taskSuite
  } = data.data;

  switch (projectId) {
    case 33010: //
    case 36106: //
    case 35791: //
      relevanceHuawei(tasks, taskSuite);
      break;
  }
}

function getDomain(url) {
  return (new URL(url)).host;
}

function createSearchLink(site, keywords = []) {
  const query = `site:${site} ${keywords.map(word => `"${word}"`).join(" | ")}`;
  return `https://www.google.com/search?q=${encodeURIComponent(query)}`;
}

function isTolokaTemplateLoaded(data) {
  return data && data.eventType && data.eventType === "assignment:resume";
}

function setSandbox(node, url) {

  const iframes = node.querySelectorAll("iframe");
  const domain = getDomain(url);

  for (const iframe of iframes) {
    const isMatched = EMPTY_SANDBOX_DOMAINS.some(i => domain.includes(i));
    const sandboxValue = !isMatched ? "allow-same-origin allow-scripts" : "";
    iframe.setAttribute("sandbox", sandboxValue);
  }

}

start();