YCH Commishes - Hide User Auctions

Hide user auctions from showing up in the main pages.

Tendrás que instalar una extensión para tu navegador como Tampermonkey, Greasemonkey o Violentmonkey si quieres utilizar este script.

You will need to install an extension such as Tampermonkey to install this script.

Tendrás que instalar una extensión como Tampermonkey o Violentmonkey para instalar este script.

Necesitarás instalar una extensión como Tampermonkey o Userscripts para instalar este script.

Tendrás que instalar una extensión como Tampermonkey antes de poder instalar este script.

Necesitarás instalar una extensión para administrar scripts de usuario si quieres instalar este script.

(Ya tengo un administrador de scripts de usuario, déjame instalarlo)

Tendrás que instalar una extensión como Stylus antes de poder instalar este script.

Tendrás que instalar una extensión como Stylus antes de poder instalar este script.

Tendrás que instalar una extensión como Stylus antes de poder instalar este script.

Para poder instalar esto tendrás que instalar primero una extensión de estilos de usuario.

Para poder instalar esto tendrás que instalar primero una extensión de estilos de usuario.

Para poder instalar esto tendrás que instalar primero una extensión de estilos de usuario.

(Ya tengo un administrador de estilos de usuario, déjame instalarlo)

// ==UserScript==
// @name         YCH Commishes - Hide User Auctions
// @namespace    13ulbasaur
// @version      1.2.1
// @description  Hide user auctions from showing up in the main pages.
// @author       Twiggies
// @license      MIT
// @match        *://ych.commishes.com/user/*
// @match        *://ych.commishes.com/category/*
// @match        *://ych.commishes.com/auction/*
// @icon         https://ych.commishes.com/favicon.ico
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_addStyle
// @grant        GM_registerMenuCommand
// ==/UserScript==

//Get the stored blocked users.
let blocklist = GM_getValue("ychBlocklist", null);
console.log("YCH BLOCKLIST");
console.log(blocklist);

const blockButtonClasses = 'blockButton text-white py-2 px-4 rounded-md text-md flex-1 md:flex-none '
const blockRedClass = ['bg-red-500', 'hover:bg-red-600']
//couldn't find a nice pre-existing hover for the grey and im too lazy to find another style.
const blockGreyClass = ['bg-gray-700']

let blockButtonList = [];
let userID, username = "";

//Insert the blocklist dialog in.
const dialoghtml = `<dialog id="blocklistDialog" closedby="any" class="p-5 bg-white border shadow-lg rounded">
	<h1 class="text-xl text-gray-800">Hidden User Auctions <button id="blocklistDialogClose" style="float: right;">&#x00d7;</button></h1>
	<p class="text-xs text-gray-500">These are the users you currently have auctions hidden for.</br>
    Click the x next to them to unhide their auctions.</br>
    You will need to refresh pages to see the changes applied.</p>
	<div class="h-4"></div>
	<div id="blocklistDialogList">Loading...</div>
</dialog>`

const menu_command_id_1 = GM_registerMenuCommand("View Hidden Users", function(){showBlockedUsers()}, {autoClose: true});

document.getElementsByTagName('footer')[0].insertAdjacentHTML('beforebegin',dialoghtml)

const dialog = document.getElementById("blocklistDialog");

document.getElementById("blocklistDialogClose").addEventListener("click", () => {
  dialog.close();
});

function createBlockButton(userID, username) {
    //If the user is already in the blocklist, change the text and classes slightly.
    let userBlocked = false;
    //Check if user already exists in blocklist.
    if (blocklist != null) {
        userBlocked = blocklist.some(obj => obj.userID === userID )
    }

    const finalButtonClasses = blockButtonClasses + (userBlocked ? blockGreyClass.join(" ") : blockRedClass.join(" "))


    const blockButton = document.createElement("button");
    blockButton.className = finalButtonClasses;
    blockButton.innerText = (userBlocked ? "Auctions Hidden" : "Hide Auctions");

    return blockButton;
}

//If it is a user page, don't block anything, instead add option to block.
if (window.location.href.includes("ych.commishes.com/user/")) {
    //Get user ID and user name.
    userID = document.getElementsByName("user")[0].value;
    username = document.querySelector('div#profile>span.hidden').textContent
    //Insert the block button. In 2 separate places, lol.
    const blockButton = createBlockButton(userID, username)

    const blockButton1 = document.getElementsByClassName('user profile hero')[0].querySelector('div.hidden:nth-child(3)').appendChild(blockButton.cloneNode(true));
    blockButton1.style.marginLeft = '5px';
    blockButton1.addEventListener("click", blockUser, false);

    document.getElementsByClassName('user profile hero')[0].querySelector('div.gap-2').appendChild(blockButton.cloneNode(true)).addEventListener("click", blockUser, false);

    blockButtonList = document.getElementsByClassName("blockButton");
}
//If it is an auction page, as above, slightly different methods.
else if (window.location.href.includes("ych.commishes.com/auction/show/")) {
    //Get user ID
    userID = configuration.auction.USER
    //Get username, storing this element to put button next to.
    const usernameElement = document.querySelector('#auction > div.p-4 .px-2 a');
    username = usernameElement.href.match(/.*\.commishes\.com\/user\/([^/]*)\/*/)[1];
    //username = document.querySelector("#portfolio-container a[href^='https://portfolio.commishes.com/user/']").href.replace(/.*portfolio\.commishes\.com\/user\//,'')
    //Insert the block button.
    const blockButton = createBlockButton(userID, username);
    blockButton.classList.remove('text-md');
    blockButton.classList.add('text-sm');
    blockButton.style.display = "block";
    usernameElement.insertAdjacentElement('afterend',blockButton.cloneNode(true)).addEventListener("click", blockUser, false);
    //usernameElement.appendChild(blockButton.cloneNode(true)).addEventListener("click", blockUser, false);
    blockButtonList = document.getElementsByClassName("blockButton");
}
//Not a user page, and blocklist isn't null or empty, let's get blocking.
else if (blocklist != null && blocklist.length > 0) {
    //Build the CSS to hide em :)
    console.log("BLOCKLIST TEST");
    let blockCSSArray = blocklist.map(function(blockitem) {
        return `[userid="${blockitem.userID}"]`;
    })
    let blocklistCSS = `${blockCSSArray.join(', ')} { display: none; }`;
    console.log(blocklistCSS);
    GM_addStyle(blocklistCSS);
}

//For when the user clicks to Hide Auctions on an artist's page.
function blockUser() {
    //get user id and name again if its empty for some reason...
    if (userID == "" || username == "") {
        userID = document.getElementsByName("user")[0].value;
        username = document.querySelector('div#profile>span.hidden').textContent
    }
    //if still empty then abort.
    if (userID == "" || username == "") {
        alert("Failed to find userid/username. try refreshing page.");
        return false;
    }
    //Get the list again. This is to help handle if the user opens up multiple tabs and then block block block so it tries to get the more recent list to check against.
    blocklist = GM_getValue("ychBlocklist", null);
    //Check if user already exists in blocklist.
    let indexID = -1;
    if (blocklist != null) {
        indexID = blocklist.findIndex(obj => obj.userID == userID )
    }
    //If they do, different beheaviour will apply.
    //Either way, prompt.
    //If user does not exist in list, "Do you want to hide this user's auctions?"
    //If user does exist in list, "User auctions are hidden. Do you want to show this user's auctions again?"
    if (confirm((indexID == -1 ? `Do you want to hide ${username}'s auctions?` : `${username}'s auctions are hidden. Do you want to show ${username}'s auctions again?`))) {
        //And then update accordingly if person clicks Yes.
        //If indexID == -1, then we will ADD new item to blockList.
        if (indexID == -1) {
            //if the blocklist is still null we will create the empty list.
            if (blocklist == null) {
                blocklist = [];
            }
            blocklist.push({
                userID: userID,
                username: username
            })
        }
        //If indexID <> -1, then we will REMOVE that index element.
        else {
            blocklist.splice(indexID, 1);
        }
        //Then we will store this updated list.
        GM_setValue("ychBlocklist",blocklist);
        //And then update the buttons on the page.
        for (const blockBtn of blockButtonList) {
            if (indexID == -1) {
                blockBtn.classList.add(...blockGreyClass);
                blockBtn.classList.remove(...blockRedClass);
                blockBtn.innerText = "Auctions Hidden";
            }
            else {
                blockBtn.classList.remove(...blockGreyClass);
                blockBtn.classList.add(...blockRedClass);
                blockBtn.innerText = "Hide Auctions";
            }
        }
    }
    //User clicked No on the confirm, so nothing happens.
}

//Pop up box with list of blocked artists so the user can remove them. Not adding functionality to add them from here due to needing the user ID and that is not easily accessible without digging into html lol.
function showBlockedUsers() {
    console.log("SHOW BLOCKED USERS CALLED")
    //Get the list again. This is to help handle if the user opens up multiple tabs and then block block block so it tries to get the more recent list to check against.
    blocklist = GM_getValue("ychBlocklist", null);

    //If the list os null or empty, display accordingly.
    if (blocklist == null || blocklist.length == 0) {
        document.getElementById('blocklistDialogList').innerHTML = 'No users are hidden.'
    }
    else {
        let tableHTML = '<table class="prose w-full">'
        //Build the table.
        blocklist.forEach((item, index) => {
            tableHTML += `<tr><td><a href="/user/${item.userID}" target="_blank">${item.username}</a></td><td class="text-xs text-gray-500">${item.userID}</td><td><button>&#10006;</button></td></tr>`
        })
        tableHTML += '</table>'
        document.getElementById('blocklistDialogList').innerHTML = tableHTML

        //Then add event listeners for clicking to each button.
        document.querySelectorAll('#blocklistDialogList button').forEach(item => {
            item.addEventListener("click", removeUserFromList, false);
        })
    }

    //Activate dialog.
    document.getElementById('blocklistDialog').showModal();

    //Check if user already exists in blocklist.
    let indexID = -1;
    if (blocklist != null) {
        indexID = blocklist.findIndex(obj => obj.userID == userID )
    }

}

function removeUserFromList() {
    console.log('removeUserFromList CALLED')
    console.log(this);
    //Get the ID of the user from the previous column.
    console.log(this.closest("td").previousSibling.innerText);
    const idToRemove = this.closest("td").previousSibling.innerText;


    //Look for the user in the blocklist.
    let indexID = blocklist.findIndex(obj => obj.userID == idToRemove )

    //If indexID is -1 then something went wrong.
    if (indexID == -1) {
        alert("Failed to find userid. Has it already been removed?");
        return false;
    }
    //Index ID isn't one, so remove it from the user list and push it back up.
    blocklist.splice(indexID, 1);
    GM_setValue("ychBlocklist",blocklist);


    //If the blocklist is now length = 0, replace table with text..
    if (blocklist.length == 0) {
        document.getElementById('blocklistDialogList').innerHTML = 'No users are hidden.';
    }
    //Else, remove the row from the table.
    else {
        this.closest("tr").remove();
    }

}