Bodil / Twitter Trending Dogs

// ==UserScript==
// @namespace    https://openuserjs.org/users/Bodil
// @name         Twitter Trending Dogs
// @version      1.5
// @description  Replaces the Twitter trending topics sidebar with today's top dogs from the Imgur dog gallery.
// @author       Bodil
// @copyright    Copyright 2020 Bodil Stokke (https://openuserjs.org/users/Bodil)
// @license      GPL-3.0-or-later; http://www.gnu.org/licenses/gpl-3.0.txt
// @match        https://twitter.com/*
// @match        https://mobile.twitter.com/*
// @noframes
// @run-at       document-idle
// @connect      api.imgur.com
// @connect      i.imgur.com
// @grant        GM_log
// @grant        GM_addStyle
// @grant        GM_xmlhttpRequest
// @grant        GM_getValue
// @grant        GM_setValue
// ==/UserScript==

// ==OpenUserJS==
// @author Bodil
// ==/OpenUserJS==

// Configure these to your liking:
const REFRESH_INTERVAL = 30 * 60 * 1000; // 30 minutes in milliseconds
const DOG_COUNT = 4; // number of dogs in sidebar
const MAX_HIDDEN_ITEMS = 256; // number of hidden items to remember (oldest items are trimmed)



// But don't touch these or things will break.
const GALLERY_SORT_ORDERS = ["top", "viral", "time"];
const TRENDING_SELECTOR = "div[aria-label=\"Timeline: Trending now\"]";
const OVERRIDE_CLASS = "override-hidden";
const DOG_ID = "imgur-trending-dogs";

GM_addStyle(`
${TRENDING_SELECTOR} > :not(.${OVERRIDE_CLASS}) {
    display: none;
}

#${DOG_ID} {
    margin: 0;
    font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Ubuntu, "Helvetica Neue", sans-serif;
}

#${DOG_ID}.darkTheme {
    color: white;
}

#${DOG_ID}.blackTheme {
    color: rgb(217, 217, 217);
}

#${DOG_ID} h2 {
    padding: 10px 14px;
    margin: 0;
    font-size: 19px;
    font-weight: 800;
    color: inherit;
}

#${DOG_ID}.lightTheme h2 {
    border-bottom: 1px solid rgb(230, 236, 240);
}

#${DOG_ID}.darkTheme h2 {
    border-bottom: 1px solid rgb(56, 68, 77);
}

#${DOG_ID}.blackTheme h2 {
    border-bottom: 1px solid rgb(47, 51, 54);
}

#${DOG_ID} ul, #${DOG_ID} p {
    margin: 0;
    padding: 10px;
}

#${DOG_ID} li {
    list-style: none;
    margin-bottom: 14px;
}

#${DOG_ID} a {
    color: inherit;
    text-decoration: inherit;
}

#${DOG_ID} img {
    width: 100%;
}

#${DOG_ID} span {
    display: block;
    font-size: 14px;
}

#${DOG_ID} button, #${DOG_ID} select {
    float: right;
}
`);

let lastFetchTime = Date.now();
let lastData = null;
const imageCache = [];
let hiddenItems;
let hiddenKeys;
let sortOrder;

function loadSettings() {
    sortOrder = GM_getValue("trendingDogs.sortOrder", GALLERY_SORT_ORDERS[0]);
    const entries = GM_getValue("trendingDogs.hidden", []);
    hiddenItems = entries;
    hiddenKeys = {};
    for (const entry of entries) {
        hiddenKeys[entry] = true;
    }
}

function setSortOrder(newSortOrder) {
    sortOrder = newSortOrder;
    GM_setValue("trendingDogs.sortOrder", sortOrder);
}

function saveHidden() {
    GM_setValue("trendingDogs.hidden", hiddenItems);
}

function hideKey(key) {
    hiddenItems.unshift(key);
    hiddenKeys[key] = true;
    if (hiddenItems.length > MAX_HIDDEN_ITEMS) {
        const key = hiddenItems.pop();
        hiddenKeys[key] = undefined;
    }
    saveHidden();
}

function cacheCheck(key) {
    for (const entry of imageCache) {
        if (entry.key === key) {
            return entry.value;
        }
    }
    return null;
}

function cacheAdd(key, value) {
    for (const entry of imageCache) {
        if (entry.key === key) {
            entry.value = value;
            return;
        }
    }
    if (imageCache.length >= DOG_COUNT) {
        imageCache.pop();
    }
    imageCache.unshift({key: key, value: value});
}

function dataUrl(mimeType, data) {
    return `data:${mimeType};base64,${data}`;
}

function loadImage(url, callback) {
    const data = cacheCheck(url);
    if (data) {
        callback(data);
    } else {
        GM_xmlhttpRequest({
            method: "GET",
            url: url,
            responseType: "arraybuffer",
            onload: (res) => {
                if (res.response && res.status >= 200 && res.status < 300) {
                    let data = base64ArrayBuffer(res.response);
                    cacheAdd(url, data);
                    callback(data);
                } else {
                    GM_log(`Imgur image load failed: ${res.status} ${res.statusText}`, res);
                    callback(null, res);
                }
            }
        });
    }
}

function findValidImage(dog) {
    if (!dog.images) {
        return null;
    }
    for (const image of dog.images) {
        // Videos won't play because of CSP evil
        if (!image.animated) {
            return image;
        }
    }
    return null;
}

function buildDog(dog, callback) {
    const image = findValidImage(dog);
    loadImage(image.link, (res, err) => {
        if (err) {
            return callback(null, err);
        }
        const li = document.createElement("li");
        const link = document.createElement("a");
        link.setAttribute("href", dog.link);
        link.setAttribute("target", "_blank");
        if (image.animated) {
            const video = document.createElement("video");
            video.setAttribute("muted", "true");
            video.setAttribute("src", dataUrl(image.type, res));
            link.appendChild(video);
        } else {
            const img = document.createElement("img");
            img.setAttribute("src", dataUrl(image.type, res));
            img.setAttribute("alt", dog.title);
            link.appendChild(img);
        }
        const hide = document.createElement("button");
        hide.setAttribute("class", "hide");
        hide.innerHTML = "Hide";
        hide.onclick = (event) => {
            event.preventDefault();
            hideKey(dog.id);
            updateDogs();
        };
        link.appendChild(hide);
        const title = document.createElement("span");
        title.innerHTML = dog.title;
        link.appendChild(title);
        li.appendChild(link);
        callback(li);
    });
}

function appendDogs(dogs, target, callback) {
    const header = document.createElement("h2");
    header.innerHTML = "Top Dogs on Imgur";
    const sortSelector = document.createElement("select");
    for (const order of GALLERY_SORT_ORDERS) {
        const option = document.createElement("option");
        option.setAttribute("value", order);
        if (order === sortOrder) {
            option.setAttribute("selected", "");
        }
        option.innerHTML = order;
        sortSelector.appendChild(option);
    }
    sortSelector.onchange = (event) => {
        setSortOrder(event.target.value);
        updateDogs();
    };
    header.appendChild(sortSelector);
    target.appendChild(header);
    const loading = document.createElement("p");
    loading.innerHTML = "Loading...";
    target.appendChild(loading);
    const dogList = document.createElement("ul");
    const items = dogs.items.filter((dog) => !hiddenKeys[dog.id] && !dog.nsfw && !!findValidImage(dog)).slice(0, DOG_COUNT);
    let processed = 0;
    items.forEach((dog, index) => {
        buildDog(dog, (dog, err) => {
            processed += 1;
            if (err) {
                items[index] = null;
            } else {
                items[index] = dog;
            }
            if (processed >= items.length) {
                items.forEach((dog) => {
                    if (dog) {
                        dogList.appendChild(dog);
                    }
                });
                target.removeChild(loading);
                target.appendChild(dogList);
                callback();
            }
        });
    });
}

function fetchImgur(callback) {
    let time = Date.now();
    if (lastData === null || time > lastFetchTime + REFRESH_INTERVAL) {
        const req = GM_xmlhttpRequest({
            method: "GET",
            url: `https://api.imgur.com/3/gallery/t/dog/${sortOrder}/day/0.json`,
            responseType: "json",
            headers: {
                "Authorization": "Client-ID 5510a87eac56d7f",
            },
            onload: (res) => {
                if (res.response.success) {
                    callback(res.response.data);
                } else {
                    GM_log(`Imgur request failed: ${res.status} ${res.statusText}`);
                    callback(null, res);
                }
            }
        });
    } else {
        callback(lastData);
    }
}

function updateDogs() {
    const dogDiv = document.getElementById(DOG_ID);
    if (dogDiv) {
        dogDiv.innerHTML = ``;
        fetchImgur((dogs, err) => {
            if (err) {
                dogDiv.innerHTML = `<p>Couldn't load dogs from Imgur 😢</p>`;
            } else {
                appendDogs(dogs, dogDiv, () => {});
            }
        });
    }
}

function updateThemeHint() {
    const dogDiv = document.getElementById(DOG_ID);
    const themeClue = document.body.getAttribute("style");
    if (themeClue.indexOf("background-color: rgb(21, 32, 43)") >= 0 || themeClue.indexOf("background-color: #15202B")) {
        dogDiv.setAttribute("class", `${OVERRIDE_CLASS} darkTheme`);
    } else if (themeClue.indexOf("background-color: rgb(0, 0, 0)") >= 0 || themeClue.indexOf("background-color: #000000")) {
        dogDiv.setAttribute("class", `${OVERRIDE_CLASS} blackTheme`);
    } else {
        dogDiv.setAttribute("class", `${OVERRIDE_CLASS} lightTheme`);
    }
}

function replaceIt() {
    const trendingDiv = document.querySelector(TRENDING_SELECTOR);
    if (!trendingDiv) {
        return;
    }
    if (!trendingDiv.querySelector(`.${OVERRIDE_CLASS}`)) {
        trendingDiv.innerHTML = `<div id="${DOG_ID}"></div>`;
        updateThemeHint();
        updateDogs();
    }
}

loadSettings();
setInterval(replaceIt, 500);
setInterval(updateDogs, REFRESH_INTERVAL);





// This bit below is a purportedly faster Base64 encoder for the data URLs,
// its own copyright and licence apply.





// Converts an ArrayBuffer directly to base64, without any intermediate 'convert to string then
// use window.btoa' step. According to my tests, this appears to be a faster approach:
// http://jsperf.com/encoding-xhr-image-data/5

/*
MIT LICENSE
Copyright 2011 Jon Leighton
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

function base64ArrayBuffer(arrayBuffer) {
  var base64    = ''
  var encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'

  var bytes         = new Uint8Array(arrayBuffer)
  var byteLength    = bytes.byteLength
  var byteRemainder = byteLength % 3
  var mainLength    = byteLength - byteRemainder

  var a, b, c, d
  var chunk

  // Main loop deals with bytes in chunks of 3
  for (var i = 0; i < mainLength; i = i + 3) {
    // Combine the three bytes into a single integer
    chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]

    // Use bitmasks to extract 6-bit segments from the triplet
    a = (chunk & 16515072) >> 18 // 16515072 = (2^6 - 1) << 18
    b = (chunk & 258048)   >> 12 // 258048   = (2^6 - 1) << 12
    c = (chunk & 4032)     >>  6 // 4032     = (2^6 - 1) << 6
    d = chunk & 63               // 63       = 2^6 - 1

    // Convert the raw binary segments to the appropriate ASCII encoding
    base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d]
  }

  // Deal with the remaining bytes and padding
  if (byteRemainder == 1) {
    chunk = bytes[mainLength]

    a = (chunk & 252) >> 2 // 252 = (2^6 - 1) << 2

    // Set the 4 least significant bits to zero
    b = (chunk & 3)   << 4 // 3   = 2^2 - 1

    base64 += encodings[a] + encodings[b] + '=='
  } else if (byteRemainder == 2) {
    chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1]

    a = (chunk & 64512) >> 10 // 64512 = (2^6 - 1) << 10
    b = (chunk & 1008)  >>  4 // 1008  = (2^6 - 1) << 4

    // Set the 2 least significant bits to zero
    c = (chunk & 15)    <<  2 // 15    = 2^4 - 1

    base64 += encodings[a] + encodings[b] + encodings[c] + '='
  }

  return base64
}