Better Rule34

A script to improve the use of rule34!

Versión del día 1/2/2023. Echa un vistazo a la versión más reciente.

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 or Violentmonkey 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         Better Rule34
// @name:fr      Meilleure règle 34
// @namespace    http://tampermonkey.net/
// @version      0.3
// @description  A script to improve the use of rule34!
// @description:fr Un script pour améliorer l'utilisation de rule34! 
// @author       You
// @match        https://rule34.xxx/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=rule34.xxx
// @grant        GM_addStyle
// @license MIT
// ==/UserScript==

const settings = `{
    "theme": "dark",
    "undeletePosts" : "true",
    "smallerPosts" : "false"
}`;
const settingsObject = JSON.parse(settings);

const dark = {
    "primary": "#121212",
    "secondary": "#000011",
    "contrast" : "gray",
    "complementary" : "#545676"
};



const themes = {
    "dark": dark
}

function setTheme(){
    let currentTheme = themes[settingsObject.theme];
    if(currentTheme){
        const css = `
            body {
                background-color: ${currentTheme.primary};
            }
            .flat-list{
                background-color: ${currentTheme.secondary};
            }
            div#header ul#subnavbar {
                background-color: ${currentTheme.secondary};
            }
            div#header ul#navbar li.current-page {
                background-image: url(https://imgs.search.brave.com/77L3MmxBu09NuN5WiX4HlbmWjjUe7eAsmBbakS7-DTo/rs:fit:120:120:1/g:ce/aHR0cHM6Ly91cGxv/YWQud2lraW1lZGlh/Lm9yZy93aWtpcGVk/aWEvY29tbW9ucy90/aHVtYi8wLzAyL1Ry/YW5zcGFyZW50X3Nx/dWFyZS5zdmcvMTIw/cHgtVHJhbnNwYXJl/bnRfc3F1YXJlLnN2/Zy5wbmc);;
            }
            .current-page {
                background-color: ${currentTheme.secondary};
                background-color: brightness(110%);
            }
            .manual-page-chooser>input[type=text]{
                background-color: ${currentTheme.secondary};
            }
            .manual-page-chooser>input[type=submit]{
                background-color: ${currentTheme.secondary};
                color: ${currentTheme.contrast};
            }
            div.tag-search input[type=text]{
                background-color: ${currentTheme.secondary};
                color: ${currentTheme.contrast};
            }
            div.tag-search input[type=submit]{
                background-color: ${currentTheme.secondary};
                color: ${currentTheme.contrast};
            }
            .col2 {
                color: ${currentTheme.contrast};
            }
        `;
        GM_addStyle(css);
        const thumbs = document.querySelectorAll(".thumb");
        thumbs.forEach(thumb => {
            const images = thumb.getElementsByTagName("img");
            for (let i = 0; i < images.length; i++) {
                images[i].style.border = `3px solid ${currentTheme.complementary}`;
            }
        });


        if(settingsObject.resizePosts == "true" && window.location.href.startsWith("https://rule34.xxx/index.php?page=post&s=view")){
            GM_addStyle(".content{max-height: 45%; max-width: 45%; overflow: auto;}");
            document.getElementById("image").style.maxHeight = "50%";
            document.getElementById("image").style.maxWidth = "fit-content";
            document.getElementById("image").style.overflow = "auto";
        }
    }
}


function getFromRule34(tags, index, isId = 0) {
    if(isId == 0){
        return fetch(`https://rule34.xxx/index.php?page=dapi&s=post&q=index&tags=${tags}`)
            .then(response => response.text())
            .then(xml => {
            const parser = new DOMParser();
            const xmlDoc = parser.parseFromString(xml, "application/xml");
            const posts = xmlDoc.getElementsByTagName("post");
            if(posts.length > 0) {
                if (index !== undefined) {
                    const specificElement = posts[index];
                    if(specificElement.hasAttribute("id")) {
                        const id = specificElement.getAttribute("id");
                        return id;
                    } else {
                        console.error("The specific element does not have an id attribute")
                    }
                } else {
                    const randomElement = posts[Math.floor(Math.random() * posts.length)];
                    if(randomElement.hasAttribute("id")) {
                        const id = randomElement.getAttribute("id");
                        return id;
                    } else {
                        console.error("The random element does not have an id attribute")
                    }
                }
            } else {
                console.error("No post elements found in the xml")
            }
        });
    } else {
            return fetch(`https://rule34.xxx/index.php?page=dapi&s=post&q=index&id=${tags}`)
            .then(response => response.text())
            .then(xml => {
            const parser = new DOMParser();
            const xmlDoc = parser.parseFromString(xml, "application/xml");
            const post = xmlDoc.getElementsByTagName("post")[0];
            if(post) {
                return post.getAttribute("file_url");
            } else {
                console.error("No post element found in the xml with the provided id")
            }
        });
    }
}


function getTagsFromUrl(currentUrl) {
    if(currentUrl.startsWith("https://rule34.xxx/index.php?page=post&s=list&tags=")) {
        return currentUrl.replace("https://rule34.xxx/index.php?page=post&s=list&tags=", "");
    }
}

function creatLinks(){
    if(window.location.href.startsWith("https://rule34.xxx/index.php?page=post&s=list&tags=")) {
        var anchors = document.getElementsByClassName("image-list")[0].getElementsByTagName("a");

        for (var i = 0; i < anchors.length; i++) {
            anchors[i].href = anchors[i].href + "&srchTags=" + getTagsFromUrl(window.location.href) + "&index=" + i.toString()
        }
    }
}

function nextPost(){
    const urlParts = window.location.href.split("&");

    const srchTags = urlParts.find(part => part.startsWith("srchTags="));
    const index = urlParts.find(part => part.startsWith("index="));
    console.log(srchTags, index)
    getFromRule34(srchTags.replace("srchTags=", ""),Number(index.replace("index=", "")) + 2).then(id => {
            window.location.href = "https://rule34.xxx/index.php?page=post&s=view&id=" + id + "&" + srchTags + "&index=" + (Number(index.replace("index=", "")) + 1).toString();
    });
}

function backPost(){
    const urlParts = window.location.href.split("&");

    const srchTags = urlParts.find(part => part.startsWith("srchTags="));
    const index = urlParts.find(part => part.startsWith("index="));
    console.log(srchTags, index)
    getFromRule34(srchTags.replace("srchTags=", ""),Number(index.replace("index=", "")) - 1).then(id => {
            window.location.href = "https://rule34.xxx/index.php?page=post&s=view&id=" + id + "&" + srchTags + "&index=" + (Number(index.replace("index=", "")) - 1).toString();
    });
}

function makeButtons(){
    function randomVideo(){
        let tags = document.querySelector("input[name='tags']").value.replace(/ /g, "+");
        const currentUrl = window.location.href;
        const tagsFromUrl = getTagsFromUrl(currentUrl);
        if(tagsFromUrl) {
            tags = tagsFromUrl;
        }
        getFromRule34(tags).then(id => {
            window.location.href = `https://rule34.xxx/index.php?page=post&s=view&id=${id}`;
        });
    }
    let btn = document.createElement("button");
    btn.innerHTML = "Random";
    btn.onclick = randomVideo;
    if(document.getElementsByClassName("tag-search")[0]){document.getElementsByClassName("tag-search")[0].appendChild(btn)};
    if(document.getElementsByClassName("image-sublinks")[0]){
        let btn3 = document.createElement("button");
        btn3.innerHTML = "back";
        btn3.onclick = backPost;
        document.getElementsByClassName("image-sublinks")[0].appendChild(btn3);
        let btn2 = document.createElement("button");
        btn2.innerHTML = "next";
        btn2.onclick = nextPost;
        document.getElementsByClassName("image-sublinks")[0].appendChild(btn2);
    }
}

const imageSublinks = document.getElementsByClassName("image-sublinks")[0];
if (imageSublinks) {
    document.addEventListener("keydown", function(event) {
        if (event.keyCode === 39) {
            nextPost();
        } else if (event.keyCode === 37) {
            backPost();
        }
    });
}

async function addDeletedPosts(id){
    if(document.getElementById("status-notices")){
        if(document.getElementsByClassName("status-notice")[0].firstChild.data.startsWith("This post was")){
            const urlParts = window.location.href.split("&");
            let notices = document.getElementById("status-notices");
            let video = document.createElement("video");
            try {
                const videoUrl = await getFromRule34(id, 0 ,1);
                video.src = videoUrl;
                video.controls = true;
                video.style = "max-height: 70%; max-width: 70%; overflow: auto;";
                document.getElementById("fit-to-screen").appendChild(video);
                document.getElementById("status-notices").remove()
            } catch (e) {
                console.error(e);
            }
        } else {
            console.log("This post is not deleted.")
        }
    } else {
        console.log("The status-notices element is not present on this page.")
    }
}

makeButtons();
creatLinks()
setTheme()
if(settingsObject.undeletePosts == "true"){setTimeout(addDeletedPosts(window.location.href.split("&").find(part => part.startsWith("id=")).replace("id=", "")), 500);}