Hypnohub arrow control

A helper to browse hypnohub with the arrow key

// ==UserScript==
// @name         Hypnohub arrow control
// @version      0.6
// @description  A helper to browse hypnohub with the arrow key
// @author       Mattlau04
// @namespace    https://gist.github.com/Mattlau04
// @match        *hypnohub.net/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // Your code here...
    //console.log(location.pathname);

    function get_pool_id() { //returns the pool id of the current page as a string
        var tmp = document.getElementsByClassName("status-notice"); //get all the notices
        for ( var i = 0; i < tmp.length; i++ ) { //for each notices
            if (tmp[i].id.startsWith("pool")) { //if it's the pool notice
                return tmp[i].id.replace('pool',''); //return the id
            }
        }
        return null //that means that we aren't on a pool
    }

    function move_in_pool(go_to_start) { //moves to the first or last page of a pool
        //if go_to_start is false then we go to the last page instead of the first
        var pool_id = get_pool_id()
        if (pool_id === null) { //if we aren't in a pool, we silently exit
            return 
        }
        fetch('https://hypnohub.net/pool/show.json?id=' + pool_id)
        .then(res => res.json())
        .then(function(data) {
            // Warning: the code under here is ugly af do to .then() and promise chains being the most retarded things i ever saw
            if (go_to_start) { //we go to the first page
                var post_id = data.posts[0].id
                window.location.href = `https://hypnohub.net/post/show/${post_id}?pool_id=${pool_id}`
            }
            else { //we go to the last page, we have to do some more magic bc we aren't getting all pages at once
                var pool_page = Math.floor(data.post_count / 24) + 1; //since 24 posts per page, something that hopefully won't change since you can't specify the limit
                fetch(`https://hypnohub.net/pool/show.json?id=${pool_id}&page=${pool_page}`)
                .then(res2 => res2.json())
                .then(function(data2) {
                    post_id = data2.posts[data2.posts.length - 1].id
                    window.location.href = `https://hypnohub.net/post/show/${post_id}?pool_id=${pool_id}`
                })
            }   
        });
    }

    document.addEventListener("keydown", function (e) {
        if (document.activeElement.nodeName !== 'TEXTAREA' && document.activeElement.nodeName !== 'INPUT') { //do it doesn't move when we're in a text area (e.g: tag field, response field...)
            //console.log(e);
            //console.log(e.keyCode);

            if (/post\/show\/*/.test (location.pathname) ) { // Post page code
                if (e.keyCode === 37) { //left arrow key press
                    if (e.ctrlKey) { //go back to first page
                        move_in_pool(true)
                    }
                    else { //go back to previous page
                        var prevbutton = document.evaluate("//a[text()='« Previous']", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; //find the Previous button
                        if (prevbutton !== null) { //so it doesn't spam on pages not in pools or 1st pages
                            prevbutton.click(); //Click it
                        }
                    }
                }
                else if (e.keyCode === 39) { //right arrow key
                    if (e.ctrlKey) { //go to the last page
                        move_in_pool(false)
                    }
                    else { 
                        var nextbutton = document.evaluate("//a[text()='Next »']", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; //find the Next button
                        if (nextbutton !== null) { //so it doesn't spam on pages not in pools
                            nextbutton.click(); //Click it
                        }
                    }
                }
            }
            //else if (/post/.test (location.pathname) ) { 

            // Post index / forums / basicly most browsable things code
            else if (document.getElementById("paginator")) { //if it's not a post page but there is pagination 
                if (e.keyCode === 37) { //left arrow key press
                    if (/.*[?,&]page=.*/.test (document.URL) ) { //if there's no ?page param then we're at page 1, can't go to previous page
                        if (e.ctrlKey) { //has control pressed
                            window.location.href = document.URL.replace(/[?,&]page=[0-9]*/.exec(document.URL),'').replace('post&','post?'); //removes page parameter
                        }
                        else { //Control isn't pressed
                            /// All the commented out code below is what was used before (getting current page number and removing one instead of clicking previous)
                            //var currentpage = /[?,&]page=([1-9]*)/.exec(document.URL)[1] //Very much unoptimised so replaced with getting via HTML
                            //var currentpage = document.getElementsByClassName("current");
                            //if (currentpage.length > 0) { // in case there's only one page and there's no element named current
                            //    if (currentpage[0].textContent > 1) { //check if this is page 1 (or 0 and negative since they also work for some reason)
                            //        var newurlprevious = new URL(window.location.href) //can't make it work without vars sadly
                            //        newurlprevious.searchParams.set('page', currentpage[0].textContent-1)
                            //        window.location.href = newurlprevious.toString()
                            var previouspage = document.getElementsByClassName("previousPage hhhz-visited");
                            if (previouspage.length > 0) { // in case we're at the first page / there are no pages
                                previouspage[0].click()
                            }
                        }
                    }
                }
                else if (e.keyCode === 39) { //right arrow key press
                    if (e.ctrlKey) { //has control pressed
                        if (document.getElementsByClassName("nextPage disabled").length == 0) { //check if we're not already on the last page (necesary otherwise we'll go back one page)
                            var lastpagelist = document.getElementsByClassName("hhhz-visited");
                            lastpagelist = Array.from(lastpagelist).filter(stuff => /\/.*[?,&]page=[0-9]*.*[^#]$/.test(stuff.href) && /^[0-9]*$/.test(stuff.textContent)); //Only keep the page buttons at the bottom (excluding the next and previous one)
                            if (lastpagelist.length > 0) { //in case there are no pages
                                const lastpage = lastpagelist.reduce(function(prev, current) { //get the object with the highest number
                                    return (parseInt(prev.textContent) > parseInt(current.textContent)) ? prev : current
                                })
                                window.location.href = lastpage.href
                            }
                        }
                    }
                    else { //Control isn't pressed
                        var nextpage = document.getElementsByClassName("nextPage hhhz-visited");
                        if (nextpage.length > 0) { // in case we're at the last page
                            nextpage[0].click()
                        }
                    }
                }
            }
        }
    });
})();