brunolm / Gogoanime Highlighter

// ==UserScript==
// @name         Gogoanime Highlighter
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Highlight favorite animes on Gogoanime
// @author       You
// @license      MIT
// @match        https://www1.gogoanime.in/*
// @grant        GM_setValue
// @grant        GM_getValue
// ==/UserScript==

function get() {
  return JSON.parse(GM_getValue('urls') || '[]');
}

function set(value) {
  value.sort();
  GM_setValue('urls', JSON.stringify(value));
}

function parseUrl(url) {
  const { groups } = url.match(/(?:gogoanime[.]in)(?<link>\/[\S\s]+)-episode/);

  if (groups && groups.link) {
    return groups.link;
  }

  return url;
}

function find(url) {
  url = parseUrl(url);

  return get().find((link) => link === url);
}

function add(url) {
  url = parseUrl(url);

  const urls = get();
  urls.push(url);

  const urlsToSave = Array.from(new Set(urls));
  set(urlsToSave);
}

function remove(url) {
  url = parseUrl(url);

  const urls = get().filter((link) => link !== url);

  set(urls);
}

function checkLinks(target) {
  target.querySelectorAll('a[href]').forEach((element) => {
    const link = element.getAttribute('href');
    if (get().some((url) => link.includes(url))) {
      const li = element.closest('li');

      if (li) {
        li.style.background = 'green';
      }
    }
  });
}

function isFavoriteButton(target) {
  return (
    target &&
    target.classList &&
    (target.classList.contains('favorites') ||
      (target.closest('li') && target.closest('li').classList.contains('favorites')))
  );
}

document.addEventListener('click', (event) => {
  const { target } = event;

  if (isFavoriteButton(target) && confirm('Would you like to store/remove from Gogohighlight?')) {
    const hasUrl = find(window.location.href);

    if (hasUrl) {
      remove(window.location.href);
    } else {
      add(window.location.href);
    }
  }

  console.log(get());
});

document.addEventListener('DOMNodeInserted', (event) => {
  const { target } = event;

  if (target && target.classList && target.classList.contains('last_episodes')) {
    checkLinks(target);
  }
});

checkLinks(document.body);