Reddit View Imgur Deleted Gif

Restore imgur gif if have a copy in reddit

// ==UserScript==
// @name               Reddit View Imgur Deleted Gif
// @namespace          https://greasyfork.org/users/821661
// @match              https://www.reddit.com/*
// @match              https://new.reddit.com/*
// @match              https://sh.reddit.com/*
// @grant              GM_xmlhttpRequest
// @version            0.2.3
// @author             hdyzen
// @description        Restore imgur gif if have a copy in reddit
// @license            MIT
// ==/UserScript==
'use strict';

function getGifState(url) {
    return new Promise(resolve => {
        GM_xmlhttpRequest({
            url: url,
            onload: e => {
                if (e.response.includes('!doctype')) {
                    resolve(true);
                }
            },
        });
    });
}

function tryGetGifFromReddit(url) {
    return new Promise(resolve => {
        GM_xmlhttpRequest({
            url: url,
            onload: e => {
                const srcMatched = e.responseText.match(/(?<=")https:\/\/packaged-media\.redd\.it\/.*?(?=")/gm);
                if (srcMatched) {
                    resolve(decodeURIComponent(JSON.parse(`"${srcMatched.at(-1)}"`)));
                } else {
                    resolve(false);
                }
            },
        });
    });
}

function getVideoElement(src) {
    return `<video style="height: 512px; width: 100%; background: #000;" controls src="${src}"></video>`;
}

async function postsHandler(post) {
    post.setAttribute('getted', '');

    const imgurLink = [...post.getElementsByTagName('a')].filter(link => link.hostname.includes('imgur.com') && link.pathname.endsWith('.gifv') && link.className)[0];

    if (!imgurLink) return;

    imgurLink.parentNode.style.width = '100%';
    imgurLink.style.width = '100%';
    imgurLink.innerHTML = getVideoElement(imgurLink.href.replace('.gifv', '.mp4'));

    imgurLink.firstChild.onerror = async e => {
        console.log(e);
        const imgurRemoved = await getGifState(imgurLink.href);
        console.log(imgurRemoved);
        if (imgurRemoved) {
            const title = post.querySelector('[data-adclicklocation="title"] a[href*="/comments/"][class]');
            const tryGet = await tryGetGifFromReddit(title ? title.href : window.location.href);
            console.log('o', tryGet, title ? title.href : window.location.href);
            if (tryGet) {
                imgurLink.innerHTML = getVideoElement(tryGet);
            } else {
                imgurLink.style.border = '1px solid red';
            }
        }
    };
}

const observer = new MutationObserver(mutations => {
    const postsWImgur = document.querySelectorAll('[data-testid="post-container"]:has(a[href*="imgur.com/"][data-testid="outbound-link"][class]):not([getted])');

    postsWImgur.forEach(postsHandler);
});

window.addEventListener('load', e => {
    const postsWImgur = document.querySelectorAll('[data-testid="post-container"]:has(a[href*="imgur.com/"][data-testid="outbound-link"][class]):not([getted])');
    postsWImgur.forEach(postsHandler);

    observer.observe(document.body, { childList: true });
});