acedece14 / vk.com clear ads posts/walls

// ==UserScript==
// @name         vk.com clear ads posts/walls
// @namespace    http://tampermonkey.net/
// @version      0.32
// @description  clear ads in vk posts/walls
// @author       Konstantin Chuyasov
// @match        https://vk.com/*
// @icon         https://www.google.com/s2/favicons?domain=vk.com
// @updateURL    https://openuserjs.org/meta/acedece14/vk.com_clear_ads_postswalls.meta.js
// @downloadURL  https://openuserjs.org/install/acedece14/vk.com_clear_ads_postswalls.user.js
// @require      http://userscripts-mirror.org/scripts/source/107941.user.js
// @copyright    2021, acedece14 (https://openuserjs.org/users/acedece14)
// @license      MIT
// ==/UserScript==

function main() {

  var myStorage = window.localStorage;
  var adsStrings;
  var lastPostId = '';
  var tmp = myStorage.getItem('vk_ads');
  if (tmp == null) {
    adsStrings = ['МногоКартин',
      'Идея подарка для девушки',
      'prfl.me',
      'ВСЕМУ ОБУЧУ ЛИЧНО',
      'topzaimtim',
      'Такие ТикТоки тебе должны понравиться',
      'сочный контент должен тебе понравиться',
      'club190259968',
      'evil_crol',
      ' Алексей Ковинов',
      'botzaimovs',
      'видосы по ссылке в источнике',
      'доступен для ВИП участников группы',
      'Ищу сайтоделов'
    ];
  }
  else adsStrings = JSON.parse(tmp);

  var showAdEditorButton = document.createElement("div");
  showAdEditorButton.innerHTML = '<a  class="left_row left_label inl_bl" style="color:#ab2">  <span id="spanAds">Ad editor</span></a>';
  showAdEditorButton.addEventListener("click", createSettingsDiv, false);
  var clearButton = document.createElement("div");
  clearButton.innerHTML = '<a  id="clearAdsButton" class="left_row left_label inl_bl" style="color:#aa3">  <span>Remove ad</span></a>';
  clearButton.addEventListener("click", clearAdsClick, false);
  var clearPostsButton = document.createElement("div");
  clearPostsButton.innerHTML = '<a  id="clearAdsButton" class="left_row left_label inl_bl" style="color:#aa5">  <span>Clear feed posts</span></a>';
  clearPostsButton.addEventListener("click", clearOldPosts, false);
  var clearPostsCbBtn = document.createElement("div");
  clearPostsButton.innerHTML = '<a  id="clearPostsButton" class="left_row left_label inl_bl" style="color:#aa5">  <span id="spanClear">Clear posts SEL</span></a>';
  clearPostsButton.addEventListener("click", clearPostsByCb, false);
  var skipVideoAdBtn = document.createElement("div");
  skipVideoAdBtn.innerHTML = '<a  id="skipVideoAdBtn" class="left_row left_label inl_bl" style="color:#aa5">  <span id="spanClear">Skip video ad</span></a>';
  skipVideoAdBtn.addEventListener("click", skipVideoAd, false);

  var leftNavbar = document.querySelector('#l_doc');
  leftNavbar.parentNode.insertBefore(clearPostsButton, leftNavbar.nextSibling);
  leftNavbar.parentNode.insertBefore(showAdEditorButton, leftNavbar.nextSibling);
  leftNavbar.parentNode.insertBefore(clearButton, leftNavbar.nextSibling);
  leftNavbar.parentNode.insertBefore(clearPostsCbBtn, leftNavbar.nextSibling);
  //leftNavbar.parentNode.insertBefore(skipVideoAdBtn, leftNavbar.nextSibling);

  var spanAds = document.querySelector('#spanAds');
  var adsCount = 0;

  function skipVideoAd() {
    // var video = document.getElementsByTagName('video')[0];
    // video.controls = true;
    //video.seeking = true;
    // video.currentTime = video.duration / 2 - 1;
  }

  function saveNewAdList() {
    adsStrings = [];
    var text = document.getElementById("adList").value;
    var splitted = text.split('\n');
    splitted.forEach(s => {
      if (s.length > 0) adsStrings.push(s);
    });

    adsStrings = adsStrings.sort();
    var myStorage = window.localStorage;
    localStorage.removeItem('vk_ads');
    localStorage.setItem('vk_ads', JSON.stringify(adsStrings));
    var adRemover = document.querySelector('.adRemover');
    adRemover.style.display = "none";
  }

  var selectedText = "";
  $("body").mouseup(function () {
    if (window.getSelection().toString() == "") {
      return;
    }
    selectedText = window.getSelection().toString();
    if (selectedText.length > 15) {
      selectedText = selectedText.slice(0, 15);
    }
    var span = document.querySelector('#spanClear');
    span.innerHTML = "Posts clear: " + selectedText;
  });

  function clearPostsByCb() {
    if (selectedText.toString() == "") {
      return;
    }
    var posts = document.querySelectorAll('.feed_row');
    var stop = false;

    posts.forEach(row => {
      if (row.innerHTML.includes(selectedText)) stop = true;
    });
    if (!stop) {
      alert('not found');
      return;
    }
    stop = false;

    posts.forEach(row => {
      //if (row.innerHTML.includes(text)) {break;};
      //if (row.innerHTML.includes(text)) {return;};
      if (row.innerHTML.includes(selectedText)) stop = true;
      if (!stop) row.parentElement.removeChild(row);
    });
    window.scrollTo(0, 0);

    //var nextNewsBtn = document.querySelector('#show_more_link');
    //if (nextNewsBtn != null) nextNewsBtn.click();

    /*navigator.clipboard.readText()
        .then(text => {
        var posts = document.querySelectorAll('.feed_row');
        var stop = false;
        posts.forEach(row => {
            //if (row.innerHTML.includes(text)) {break;};
            //if (row.innerHTML.includes(text)) {return;};
            if (row.innerHTML.includes(text)) stop = true;
            if (!stop) row.parentElement.removeChild(row);
        });
        var nextNewsBtn = document.querySelector('#show_more_link');
        if (nextNewsBtn != null) nextNewsBtn.click();
    }).catch(err => {
        console.log('Something went wrong', err);
    })
    */
  }

  function createSettingsDiv() {
    var newDiv = document.createElement("div");
    newDiv.style.width = 'auto';
    newDiv.style.height = 'auto';
    newDiv.style.padding = '4px';
    newDiv.style.margin = '4px';
    newDiv.innerHTML = "<textarea id='adList'></textarea rows='41' cols='50'><br><button id=btnSaveAdList>Save zis crap</button>";
    newDiv.classList.add("adRemover");
    leftNavbar.parentNode.insertBefore(newDiv, leftNavbar.nextSibling);

    adsStrings.forEach(s => {
      document.getElementById("adList").value += s + '\n';
    });

    var btnSaveAdList = document.querySelector('#btnSaveAdList');
    btnSaveAdList.addEventListener("click", saveNewAdList, false);

    var adList = document.querySelector("#adList");
    //adList.style.width = "400px";
    adList.style.width = "280px";
    adList.style.height = "230px";
    adList.style.scrollBehavior = "smooth";
    adList.style.top = "50px";
    //adList.style.left = "0px";
    //adList.style.resize = '';
    adList.style.position = "fixed";
    adList.style.display = "block";
  }

  function isAd(text) {
    for (var i = 0; i < adsStrings.length; i++) {
      var tmp = adsStrings[i];
      if (text.toLowerCase().includes(tmp.toLowerCase())) return true;
    }
    return false;
  }

  function clearParentBySelector(selector) {
    var elements = document.querySelectorAll('.wall_marked_as_ads');
    elements.forEach(m => {
      m.parentElement.parentElement.style = "display: none;";
      m.parentElement.parentElement.parentElement.innerHTML = "ebanaya reklama vk";
      m.classList.remove(selector.substring(1));
      adsCount++;
      spanAds.innerHTML = 'Remove ads (' + adsCount + ')';
    });
  }

  function elementInViewport2(el) {
    var top = el.offsetTop;
    var left = el.offsetLeft;
    var width = el.offsetWidth;
    var height = el.offsetHeight;

    while (el.offsetParent) {
      el = el.offsetParent;
      top += el.offsetTop;
      left += el.offsetLeft;
    }

    return (
      top < (window.pageYOffset + window.innerHeight) &&
      left < (window.pageXOffset + window.innerWidth) &&
      (top + height) > window.pageYOffset &&
      (left + width) > window.pageXOffset
    );
  }

  function clearOldPosts() {

    var posts = document.querySelectorAll('.feed_row');
    if (posts != null) {
      console.log('posts in feed: ' + posts.length);

      if (posts.length > 25) {
        var postToScroll = posts[27];
        while (posts.length > 20) {
          posts = document.querySelectorAll('.feed_row');
          console.log('try remove post');
          var node = posts[0];
          if (node.parentNode) {
            node.parentNode.removeChild(node);
          }
        }
        postToScroll.scrollIntoView();
      }
    }
    var msgs = document.querySelectorAll('.im-mess-stack._im_mess_stack ');
    if (msgs != null && msgs.length > 25) {
      console.log(msgs.length);
      while (msgs.length > 25) {
        msgs = document.querySelectorAll('.im-mess-stack._im_mess_stack ');
        var nodeMsgs = msgs[0];
        if (nodeMsgs.parentNode) {
          nodeMsgs.parentNode.removeChild(nodeMsgs);
        }
      }
    }

    //*/
  }

  function clearStorage() {
    var values = [];
    var keys = Object.keys(localStorage);
    var i = keys.length;

    while (i--) {
      var key = keys[i];
      var item = localStorage.getItem(key);
      if (item.includes('vk.com/sticker')) {
        localStorage.removeItem(key);
      }
      //console.log(":: " + key + " : " + item.length);
    }
  }

  function clearAdsClick() {
    console.log('[MyVkAdFucker] clearAdsClick');
    clearStorage();
    var elsTg = document.querySelectorAll('.reply_text');
    elsTg.forEach(e => {
      if (e.textContent.includes('https://t.me/') || e.textContent.includes('https://vk.cc/')) {
        var txtAd = e.textContent;
        e.parentElement.parentElement.parentElement.parentElement.parentElement.parentElement.parentElement.innerHTML = 'reklama govna tg ' + txtAd;
      }
    });
    var posts = document.querySelectorAll('div._post > div:nth-child(1) > div:nth-child(2) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1)');
    posts.forEach(p => {
      if (isAd(p.textContent) == true) {
        p.parentElement.parentElement.style = "display: none;";
        p.parentElement.parentElement.parentElement.innerHTML = "ebanaya reklama govna filtered by list: (" + p.textContent + ")";
        adsCount++;
        spanAds.innerHTML = 'Remove ads (' + adsCount + ')';
      }
    });

    var css = 'span.PostHeaderSubtitle__item';
    var els = document.querySelectorAll(css);
    els.forEach(e => {
      if (e.innerHTML == 'Реклама в сообществе') {
        e.parentElement.parentElement.parentElement.parentElement.remove(e);
      };
    });
  };
  clearAdsClick();
  //var lastCount = -1;
  function timerAction() {
    //var count = document.querySelectorAll('div._post > div:nth-child(1) > div:nth-child(2) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1)').length;
    if (window.location.href.indexOf("feed") != -1) {
      document.querySelector('.LegalRecommendationsLinkLeftMenuAuthorized__link').innerText = (Math.floor(Math.random() * 100) + 1);
      //var allPosts = document.getElementById('feed_rows').getElementsByTagName('div');
      //var postId = document.getElementById('feed_rows').getElementsByTagName('div')[allPosts.length-1].getElementsByTagName('div')[0].id;
      var allPosts = document.querySelectorAll('div._feed_rows > .feed_row > div');
      var postId = allPosts[allPosts.length - 1].id;
      //var myPageBtn = document.querySelector('#l_pr > a:nth-child(1) > span:nth-child(2)');
      if (lastPostId != postId) {
        //if (lastCount != count) {
        //(document.getElementById('clearAdsButton')).click();
        clearAdsClick();
        lastPostId = postId;
        //lastCount = count;
      }
    }
  }
  timerAction();
  let timerId = setInterval(() => timerAction(), 10000);
  // try collapse all big comment threads
  if (document.querySelector('#wall_rmenu') != null) {
    document.querySelectorAll('.replies_deep_collapse').forEach(e => e.click())
  }
  console.log('[ACDC] clear ad script started')
}

(function () {
  'use strict';
  setTimeout(() => main(), 2000);
})();