Full_Black_List

Supprime totalement les sujets des pseudo blacklistés depuis la blacklist JVC.

// ==UserScript==
// @name         Full_Black_List
// @namespace    Full_Black_List
// @version      0.18.6
// @description  Supprime totalement les sujets des pseudo blacklistés depuis la blacklist JVC.
// @author       Atlantis
// @match        *://www.jeuxvideo.com/recherche/forums/0-*
// @match        *://www.jeuxvideo.com/forums/0-*
// @match        *://www.jeuxvideo.com/forums/42-*
// @match        *://www.jeuxvideo.com/forums/1-*
// @match        *://www.jeuxvideo.com/forums/message*
// @match        *://www.jeuxvideo.com/messages-prives/message.php*
// @match        *://www.jeuxvideo.com/messages-prives/indesirables.php
// @match        *://www.jeuxvideo.com/sso/blacklist.php
// @match        *://www.jeuxvideo.com/login*
// @icon         https://images.emojiterra.com/google/noto-emoji/unicode-16.0/color/128px/274c.png
// @license      MIT
// @grant        none
// ==/UserScript==

//___FETCH___SYNCH__BL___(FECTH)___
async function synchfetchpseudos() {
    let response = await fetch('/sso/blacklist.php');
    let htmlText = await response.text();

    let parser = new DOMParser();
    let doc = parser.parseFromString(htmlText, 'text/html');

    let pseudos = doc.querySelectorAll('#blacklist span');

    let pseudoList = [];
    pseudos.forEach(span => {
        pseudoList.push(span.textContent.trim());
    });

    localStorage.setItem('fullblacklistJVC', JSON.stringify(pseudoList));

}



//___Fetch_MP_LIST_______(FETCH)___
let idListF = [];
let haListF = [];

async function fetchOnce() {
    let response = await fetch('/messages-prives/indesirables.php');
    let htmlfofo = await response.text();
    let parser = new DOMParser();
    let doc = parser.parseFromString(htmlfofo, 'text/html');
    let listItems = doc.querySelectorAll('#blacklist i');
    
    listItems.forEach(i => {
        let idAlias = i.getAttribute('data-id');
        let hashtempo = i.getAttribute('data-hash');
        idListF.push(idAlias);
        haListF.push(hashtempo);
    });
}

//___Clean_MP_LIST_ONE__(FETCH)___

function deleteblacklistMP(cross) {
    let listItem = cross.closest('li');  // Trouver l'élément <li> parent
    let idAlias = listItem.getAttribute('data-id-alias');  // Récupérer l'id depuis le parent
    let index = idListF.indexOf(idAlias);  // Trouver l'index de l'élément dans idListF

    if (index !== -1) {
        let hashtempo = haListF[index];
        let url = `/messages-prives/message.php?del_blacklist=${idAlias}&h=${hashtempo}`; 
        fetch(url);
    }
}

//___Clean_MP_LIST_ALL__(FETCH)___
async function removeFromBlacklistMP() {
    let fetchPromises = idListF.map((idAlias, index) => {
        let hashtempo = haListF[index];  // Récupérer le hash associé à l'index
        let url = `/messages-prives/message.php?del_blacklist=${idAlias}&h=${hashtempo}`;
        return fetch(url);  // Effectuer la suppression
    });

    await Promise.all(fetchPromises);
}

//_______PAGE_DE______CONNEXION___(Login)___
if (window.location.href.indexOf('jeuxvideo.com/login') > -1) {
    localStorage.removeItem('fullblacklistJVC');
}

//______MASQUAGE_____BLOC____MESSAGE____FORUM__(Topic_1_42)____
if (window.location.href.indexOf('jeuxvideo.com/forums/1-') > -1 || window.location.href.indexOf('jeuxvideo.com/forums/42-') > -1 || window.location.href.indexOf('jeuxvideo.com/forums/message/') > -1) {

    //masquage_message
    let blacklistBlocks = document.querySelectorAll('.msg-pseudo-blacklist');
    blacklistBlocks.forEach(block => {
        block.remove();
    });

    //ajout dun event au bouton blacklist
    let blacklisterBtns = document.querySelectorAll('.picto-msg-tronche');
    blacklisterBtns.forEach(function(btn) {
        btn.addEventListener('click', function() {
            sessionStorage.setItem('fullblacklistJVCAwait', 'true');
        });
    });

    // Mise à jour de la Blacklist du script apres actualisation
    let bljvcawait = sessionStorage.getItem('fullblacklistJVCAwait');
    if (bljvcawait === 'true') {
        synchfetchpseudos(); // fullblacklistJVCAwait est 'true'
        sessionStorage.removeItem('fullblacklistJVCAwait'); // Supprime la clé 'fullblacklistJVCAwait'
    }

}

//______BLACKLIST____LISTE_SUJETS___(Liste_Sujet)(Recherche)___
if (window.location.href.indexOf('jeuxvideo.com/forums/0-') > -1 || window.location.href.indexOf('jeuxvideo.com/recherche/forums/0-') > -1) {
    // Fonction pour récupérer la liste des pseudos blacklistés depuis JVC ou le local storage
    function getListeBlacklist() {
        let liste = localStorage.getItem('fullblacklistJVC');
        if (liste) {
            return JSON.parse(liste);
        } else {
            synchfetchpseudos().then(() => location.reload());
        }
    }

    // Fonction pour supprimer des éléments insensible à la casse
    function supprimerParListeDePseudos(pseudos) {
        let pseudosLower = pseudos.map(pseudo => pseudo.toLowerCase()); // liste tout les pseudo en miniusucle
        document.querySelectorAll('li').forEach(item => {
            let auteur = item.querySelector('.topic-author');
            if (auteur && pseudosLower.includes(auteur.textContent.trim().toLowerCase())) {
                // Supprimer le sujet si ateur
                item.remove();
            }
        });
    }



    let pseudosBlacklist = getListeBlacklist();
    supprimerParListeDePseudos(pseudosBlacklist);
}

//_______BOUTON_____BLACKLIST___LISTE_SUJET_(Liste_Sujet)_____
if (window.location.href.indexOf('jeuxvideo.com/forums/0-') > -1) {

    var divContainer = document.createElement('div');
    divContainer.classList.add('custom-btn-container');

    // Créer les spans à l'intérieur de la div
    var span1 = document.createElement('span');
    //span1.classList.add('btn');
    span1.classList.add('btn', 'btn-actu-new-list-forum', 'btn-actualiser-forum', 'icon-refresh');
    span1.textContent = 'Actu BL';
    span1.title = 'Actualiser la blacklist des Sujets';
    span1.style.borderRadius = '6px';
    span1.style.minWidth = '5rem';
    //span1.style.textDecoration = 'underline';
    span1.addEventListener('click', synchfetchpseudos);
    span1.addEventListener('click', function () { alert('Filtrage des topics actualisés avec la blacklist JVC ✅'); });
    span1.addEventListener('click', function () { location.reload(); });

    // Vous pouvez ajouter d'autres spans si nécessaire
    var span2 = document.createElement('span');
    //span2.classList.add('btn');
    span2.classList.add('btn', 'btn-actu-new-list-forum', 'btn-actualiser-forum');
    span2.textContent = 'Voir BL';
    span2.title = 'Voir/Editer/Eporter la BlackList';
    span2.style.borderRadius = '6px';
    span2.style.minWidth = '4rem';
    //span2.style.textDecoration = 'underline';
    span2.addEventListener('click', function() { window.open('/sso/blacklist.php', '_blank'); });

    // Ajouter les spans à la div
    divContainer.appendChild(span1);
    divContainer.appendChild(document.createTextNode('\u00A0\u00A0'));
    divContainer.appendChild(span2);

    // Trouver l'élément avec la classe 'bloc-pagi-default px-3 px-lg-0'
    var blocPagiDefault = document.querySelector('.bloc-pagi-default.px-3.px-lg-0');
    var pagiBeforeListTopic = document.querySelector('.pagi-before-list-topic');

    // Ajouter la div juste après cette div spécifique
    pagiBeforeListTopic.parentNode.insertBefore(divContainer, pagiBeforeListTopic.nextSibling);

}


//______________MASQUAGE____BLOC__MESSAGE_MP__(Message_MP)____
if (window.location.href.indexOf('jeuxvideo.com/messages-prives/message.php') > -1) {



    //ajout dun event au bouton blacklist
    let blacklisterBtns = document.querySelectorAll('.picto-msg-tronche');
    blacklisterBtns.forEach(function(btn) {
        btn.addEventListener('click', function() {
            let dataUrl = btn.getAttribute('data-url');
            sessionStorage.setItem('fullblacklistJVCIDMP', dataUrl);
            sessionStorage.setItem('fullblacklistJVCAwait', 'true');
        });
    });

    // Mise à jour de la Blacklist fofo du script apres actualisation
    let bljvcawait = sessionStorage.getItem('fullblacklistJVCAwait');
    if (bljvcawait === 'true') {
        (async () => {
            // Fetch recuperer hash preference forum
            let response = await fetch('/forums/0-36-0-1-0-1-0-0.htm');
            let htmlfofo = await response.text();
            let parser = new DOMParser();
            let doc = parser.parseFromString(htmlfofo, 'text/html');
            let ajaxHashpref = doc.querySelector('#ajax_hash_preference_user');
            // preference_user_hash => necassaire pour ajouter à la blacklist JVC
            let fullidmp = sessionStorage.getItem('fullblacklistJVCIDMP');
            let match = fullidmp.match(/add_blacklist=(\d+)/); //id_pseudo
            let idAlias = match ? match[1] : null;
            let url = `/forums/ajax_forum_blacklist.php?id_alias_msg=${idAlias}&action=add&ajax_hash=${ajaxHashpref.value}`;
            let result = await fetch(url);
            await synchfetchpseudos();
            sessionStorage.removeItem('fullblacklistJVCAwait'); // Supprime la clé 'fullblacklistJVCAwait'
            sessionStorage.removeItem('fullblacklistJVCIDMP'); // Supprime la clé
            let newUrl = location.href.replace(/&add_blacklist=[^&]+&h=[^&]+/, "");
            if (newUrl !== location.href) location.replace(newUrl);
        })();
    }



    //liste_local_storage_blacklist_les_MP_+_masquage
    function supprimerParListeDePseudos(pseudos) {
        let pseudosLower = pseudos.map(pseudo => pseudo.toLowerCase()); // Liste tous les pseudos en minuscules
        let blacklistBlocks = document.querySelectorAll('.bloc-message-forum');
        let clicked;
        blacklistBlocks.forEach(block => {
            let auteur = block.querySelector('.bloc-pseudo-msg'); // Cibler l'élément avec le pseudo
            let boutonBlacklist = block.querySelector('.picto-msg-tronche');
            if (auteur && pseudosLower.includes(auteur.textContent.trim().toLowerCase())) {
                boutonBlacklist.click(); // BL_MP
            }
        });
    }


    //masquage_message_BL_CLASSIQUE
    let blacklistBlocks = document.querySelectorAll('.msg-pseudo-blacklist');
    blacklistBlocks.forEach(block => {
        block.remove();
    });



    //recup_local_storage
    function getListeBlacklist() {
        let liste = localStorage.getItem('fullblacklistJVC');
        if (liste) {
            return JSON.parse(liste);
        } else {
            synchfetchpseudos().then(() => location.reload());
        }
    }

    let pseudosBlacklist = getListeBlacklist();
    supprimerParListeDePseudos(pseudosBlacklist);

}


//________________Suuppression_combiné_BL___(Page_BlackList_MP)____
if (window.location.href.indexOf('jeuxvideo.com/messages-prives/indesirables.php') > -1) {
    document.querySelectorAll('.mp_delete_blacklist').forEach(function(button) {
        button.addEventListener('click', function() {
            let userId = this.getAttribute('data-id'); // Récupère l'ID depuis l'attribut data-id
            fetch(`/sso/ajax_delete_blacklist.php?id_alias_unblacklist=${userId}`)
                .then(() => {
                    localStorage.removeItem('fullblacklistJVC'); //vide black list local storage
                });
        });
    });
}

//________________MISE_A_JOUR_PAGE_BLACK_LISTE__(Page_BlackList_Forums)____
if (window.location.href.indexOf('jeuxvideo.com/sso/blacklist.php') > -1) {

    updatepseudos();

    // Parcourt chaque élément et ajoute un gestionnaire d'événement
    let crosses = document.querySelectorAll('.icon-cross-entypo');
    crosses.forEach(cross => {
        cross.addEventListener('click', async () => {
            updatepseudos();  // Mettre à jour les pseudos si nécessaire
            if (typeof hasFetched === 'undefined') {
                await fetchOnce();  // Fetch une seule fois idListF et haListF
                hasFetched = true;  // Marquer que le fetch a été effectué
            }
            deleteblacklistMP(cross);  // Interagir avec l'élément après avoir effectué la suppression
        });
    });

    function updatepseudos() {
        setTimeout(() => {
            let pseudos = document.querySelectorAll('#blacklist span');

            let pseudoList = [];
            pseudos.forEach(span => {
                pseudoList.push(span.textContent.trim());
            });

            localStorage.setItem('fullblacklistJVC', JSON.stringify(pseudoList));
        }, 1000); //delais pour capturer la page à jour
    }
}

//_______________EXPORT_PAGE__BLACKLIST___(Page_BlackList_Forums)____
if (window.location.href.indexOf('jeuxvideo.com/sso/blacklist.php') > -1) {
    'use strict';

    //fonction suppression totale black list
    async function deleteBlacklist() {
        strikeBtn.textContent = 'Loading...';
        // Récupérer tous les éléments <li> dans #blacklist
        let listItems = document.querySelectorAll('#blacklist li');
        let idList = [];
        listItems.forEach(li => {
            let idAlias = li.getAttribute('data-id-alias');
            idList.push(idAlias);
        });
    
        // Créer un tableau de promesses pour les requêtes Ajax
        let fetchPromises = idList.map(idAlias => {
                let url = `/sso/ajax_delete_blacklist.php?id_alias_unblacklist=${idAlias}`;
                return fetch(url);
        });
        // Attendre que toutes les requêtes se terminent
        if (typeof hasFetched === 'undefined') {
            await fetchOnce();  // Fetch une seule fois idList et haListF
            hasFetched = true;  // Marquer que le fetch a été effectué
        }
        await removeFromBlacklistMP();
        let results = await Promise.all(fetchPromises);

        window.location.reload();
    }



    // Fonction d'exportation de la Blacklist
    function exportBlacklist() {

        let listItems = document.querySelectorAll('#blacklist li');
        let idList = [];
        listItems.forEach(li => {
            let idAlias = li.getAttribute('data-id-alias');
            idList.push(idAlias);
        });
        let jsonBlob = new Blob([JSON.stringify(idList, null, 2)], { type: 'application/json' });

        //creation_lien_telechargement
        let link = document.createElement('a');
        link.href = URL.createObjectURL(jsonBlob);
        link.download = 'Blacklist_JVC.json';
        link.click();
    }

    // Fonction d'importation de la Blacklist depuis un fichier JSON
    async function importBlacklist(event) {
        let file = event.target.files[0];
        if (!file) return;

        // Fetch recuperer hash preference forum
        let response = await fetch('/forums/0-36-0-1-0-1-0-0.htm');
        let htmlfofo = await response.text();
        let parser = new DOMParser();
        let doc = parser.parseFromString(htmlfofo, 'text/html');
        let ajaxHashpref = doc.querySelector('#ajax_hash_preference_user');
        // preference_user => necassaire pour ajouter à la blacklist JVC

        let reader = new FileReader();
        reader.onload = async e => {
            try {
                importBtn.textContent = 'Load...';
                // Lecture et parsing du fichier JSON
                let blacklist = JSON.parse(e.target.result);

                // Boucle ajax pour ajouter pseudo blacklist de la liste
                let fetchPromises = blacklist.map(idAlias => {
                    let url = `/forums/ajax_forum_blacklist.php?id_alias_msg=${idAlias}&action=add&ajax_hash=${ajaxHashpref.value}`;
                    return fetch(url);
                });
                //attendre resultat pour refresh
                let results = await Promise.all(fetchPromises);
                window.location.reload();
            } catch (error) {
                alert("Fichier JSON invalide");
                window.location.reload();
            }
        };
        reader.readAsText(file);
    }


    // Creation Boutons Groupes
    let container = document.querySelector('.layout__row.layout__content.layout__row--gutter.mb-5');
    if (!container) return; // Si le container n'existe pas, ne rien faire
    let ull1 = document.createElement('ul');
    let ull2 = document.createElement('ul');

    // Création du bouton d'export
    let exportBtn = document.createElement('button');
    exportBtn.textContent = 'Exporter';
    exportBtn.title = 'Exporter BlackList JVC en Fichier';
    exportBtn.className = 'simpleButton';
    exportBtn.style.borderRadius = '6px';
    exportBtn.addEventListener('click', exportBlacklist);

    // Création du bouton d'import
    let importBtn = document.createElement('button');
    importBtn.textContent = 'Importer';
    importBtn.title = 'Importer BlackList depuis un Fichier';
    importBtn.className = 'simpleButton';
    importBtn.style.borderRadius = '6px';
    importBtn.addEventListener('click', function() {
        let input = document.createElement('input');
        input.type = 'file';
        input.accept = '.json';
        input.addEventListener('change', importBlacklist);
        input.click();
    });

    let strikeBtn = document.createElement('button');
    strikeBtn.textContent = 'Vider BL Forum et MP';
    strikeBtn.title = 'Vider toute la blacklist JVC + MP + Script';
    strikeBtn.className = 'simpleButton';
    strikeBtn.style.borderRadius = '6px';
    strikeBtn.style.backgroundColor = 'red';
    strikeBtn.addEventListener('click', () => window.confirm('⚠️ Supprimer toute la blacklist (JVC + MP + Script) ??⚠️') ? deleteBlacklist() : null);

    /*
    let linkBtn = document.createElement('button');
    linkBtn.textContent = 'BL MP';
    linkBtn.title = 'BlackList MP';
    linkBtn.className = 'simpleButton';
    linkBtn.style.borderRadius = '6px';
    linkBtn.addEventListener('click', () => window.location.href = '/messages-prives/indesirables.php');
    */

    // Ajouter les boutons au container
    ull1.appendChild(importBtn);
    ull1.appendChild(document.createTextNode('\u00A0\u00A0'));
    ull1.appendChild(exportBtn);
    ull2.appendChild(strikeBtn);
    /*
    ull2.appendChild(document.createTextNode('\u00A0\u00A0'));
    ull2.appendChild(linkBtn);
    */
    container.appendChild(ull1);
    container.appendChild(ull2);
}