CharltonAbney / Wikipedia cover voor Reddit

// ==UserScript==
// @author      CharltonAbney
// @namespace   https://openuserjs.org/users/CharltonAbney
// @name        Wikipedia cover voor Reddit
// @description This script will import the content of the reddit homepage into an English Wikipedia page.
// @copyright   2019, CharltonAbney (https://openuserjs.org/users/CharltonAbney)
// @license     MIT
// @version     1.0.0
// @match       https://en.wikipedia.org/wiki/*
// @require     http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @grant       GM_xmlhttpRequest
// @grant       GM_addStyle
// ==/UserScript==

// ==OpenUserJs==
// @author  CharltonAbney
// ==/OpenUserJs==

window.onload = () => {

  /* --------------- Algemene variabelen --------------- */

  const wikiContent = document.querySelector('div[id="mw-content-text"] > div[class="mw-parser-output"]');
  var redditLink = 'https://old.reddit.com/';
  var previousPageLink = '';
  var nextPageLink = '';
  var postPage = '';
  var onPostPage = false;

  /* --------------- Page onload elementen --------------- */

  newReq();

  document.querySelector("#p-namespaces > ul").innerHTML = `
        <ul>
            <li id="ca-nstab-main" class="selected">
                <span>
                    <a id="mainPage" title="View the content page [ctrl-option-c]" accesskey="c">Main Page</a>
                </span>
            </li>
            <li id="ca-talk">
                <span>
                    <a id="previousPage" rel="nofollow next">‹ Previous</a>
                </span>
            </li>
            <li id="ca-talk">
                <span>
                    <a id="nextPage" rel="nofollow next">Next ›</a>
                </span>
            </li>
        </ul>
    `;

  /* --------------- Navigatieknoppen --------------- */

  let mainPage = document.getElementById('mainPage');
  let previous = document.getElementById('previousPage');
  let next = document.getElementById('nextPage');

  mainPage.onclick = () => {
    redditLink = redditLink.replace(redditLink, 'https://old.reddit.com/');
    postPage = '';
    onPostPage = false;
    newReq();
    wikiContent.scrollTop = 0;
  };

  previous.onclick = () => {
    redditLink = redditLink.replace(redditLink, previousPageLink);
    postPage = '';
    onPostPage = false;
    newReq();
    wikiContent.scrollTop = 0;
  };

  next.onclick = () => {
    redditLink = redditLink.replace(redditLink, nextPageLink);
    postPage = '';
    onPostPage = false;
    newReq();
    wikiContent.scrollTop = 0;
  };

  /* --------------- HTTP Request --------------- */

  function newReq() {
    GM_xmlhttpRequest({
      method: 'GET',
      url: redditLink,
      onload: parseResponse,
      onerror: function (e) {
        console.error('**** error ', e);
      },
      onabort: function (e) {
        console.error('**** abort ', e);
      },
      ontimeout: function (e) {
        console.error('**** timeout ', e);
      }
    });
  }

  /* --------------- CSS Styling --------------- */

  GM_addStyle(`
        .awarding-icon {
            max-width: 12px;
            max-height: 12px;
            vertical-align: -2px;
        }
        .awarding-icon-container {
            display: inline-block;
            height: 12px;
            width: 12px;
            margin-right: 2px;
        }
        .awardings-bar {
            margin-left: 4px;
        }
        .mw-parser-output > div > div > ul > li {
            display: inline-block;
            border: none;
            padding-right: 4px;
            line-height: 1.6em;
            white-space: nowrap;
        }
        .mw-parser-output > div > div > ul > li > a, .mw-parser-output > div > div > ul > li > form > span > a {
            color: #AAA;
            font-weight: bold;
        }
        a.thumbnail {
            position: relative;
            display: block;
            float: left;
            font-size: 0;
            margin-bottom: 2px;
            margin-right: 5px;
            margin-top: 0;
            margin-left: 0;
            overflow: hidden;
            width: 70px;
            height: 70px;
        }
        a.thumbnail > img {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
        .entry {
            overflow: hidden;
            margin-left: 3px;
            opacity: 1;
            display: block;
            float: left;
            width: calc(100% - 200px);
        }
        .redPost {
            width: 100%;
            display: inline-block
        }
        .entry > p  {
            overflow: hidden;
            line-height: 1.3em;
        }
        .mw-body-content h1 {
            margin-top: 0.2em;
        }
        .domain {
            color: #888;
            display: inline-block;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
            vertical-align: middle;
            max-width: 19em;
            font-size: x-small;
            text-decoration: none;
            margin-left: .4em;
        }
    `);

  /* --------------- HTTP page content --------------- */

  function parseResponse(response) {

    /* --------------- Pagina variabelen --------------- */

    const parser = new DOMParser();
    const ajaxDoc = parser.parseFromString(response.responseText, "text/html");

    const topMatter = ajaxDoc.querySelector('div[class="top-matter"]');
    const titles = ajaxDoc.querySelectorAll('p[class="title"] > a');
    const image = ajaxDoc.querySelectorAll('#siteTable > div.thing > a.thumbnail');
    const tagline = ajaxDoc.querySelectorAll('#siteTable > div.thing > div.entry.unvoted > div.top-matter > p.tagline');
    const redPost = ajaxDoc.querySelectorAll('#siteTable > div.thing');

    const postTitle = ajaxDoc.querySelector("div.entry.unvoted > div.top-matter > p.title > a");
    const postImage = ajaxDoc.querySelector("div.media-preview > div > a > img");
    const postImageLink = ajaxDoc.querySelector("div.media-preview > div > a");

    const previousPage = ajaxDoc.querySelector("#siteTable > div.nav-buttons > span.nextprev > span.prev-button > a");
    const nextPage = ajaxDoc.querySelector("#siteTable > div.nav-buttons > span.nextprev > span.next-button > a");

    /* --------------- Homepage Reddit posts --------------- */

    wikiContent.innerHTML = '';
    wikiContent.style.cssText = 'overflow: scroll; height: 65vh;';

    if (onPostPage === false) {
      redPost.forEach((elem, index) => {
        let title = elem.querySelectorAll('p[class="title"] > a').item(0);
        let titleLink = elem.querySelectorAll('p[class="title"] > a').item(0);
        let postSource = elem.querySelectorAll("div.entry.unvoted > div.top-matter > p.title > span > a").item(0);
        let postSourceLink = elem.querySelectorAll("div.entry.unvoted > div.top-matter > p.title > span > a").item(0);
        let image = elem.querySelectorAll('a.thumbnail').item(0);
        let imageLink = elem.querySelectorAll('a.thumbnail').item(0);
        let tagline = elem.querySelectorAll('div.entry.unvoted > div.top-matter > p.tagline').item(0);
        let reactions = elem.querySelectorAll('div.entry.unvoted > div.top-matter > ul.flat-list.buttons').item(0);

        if (image.href.indexOf('en.wikipedia.org') > 0) imageLink = image.href.replace(/en.wikipedia.org/g, 'old.reddit.com');
        if (title.href.indexOf('en.wikipedia.org') > 0) titleLink = title.href.replace(/en.wikipedia.org/g, 'old.reddit.com');
        if (postSource.href.indexOf('en.wikipedia.org') > 0) postSourceLink = postSource.href.replace(/en.wikipedia.org/g, 'old.reddit.com');

        wikiContent.innerHTML += `\
                    <div class="redPost" style="margin-bottom: 15px;">\
                        <a class="thumbnail" href="${imageLink}" target="_blank" id="homePostImage">${image.innerHTML}</a>\
                        <div class="entry unvoted">\
                            <p><a href="${titleLink}" target="_blank" id="homePostTitle">${title.innerText}</a><span class="domain">(<a href="${postSourceLink}" target="_blank">${postSource.innerText}</a>)</span></p>\
                            <p style="color: #AAA; font-size: 0.7em; margin-top: -5px;">${tagline.innerHTML}</p>\
                            <ul style="color: grey; font-size: 0.7em; margin-top: -5px; margin-left: 0px; display: block; list-style: none;">${reactions.innerHTML}</ul>\
                        </div>\
                    </div>
                `;

      });
    }

    /* --------------- Homepage Reddit onclick event --------------- */

    let homePostTitle = document.querySelectorAll("#mw-content-text > div.mw-parser-output > div.redPost > div.entry.unvoted > p > a");

    homePostTitle.forEach((elem, index) => {
      elem.onclick = () => {
        let postTitleHome = elem.href;
        redditLink = redditLink.replace(redditLink, postTitleHome);
        postPage = postTitleHome;
        onPostPage = true;
        newReq();
        wikiContent.scrollTop = 0;
        return false;
      };
    });

    /* --------------- Reddit post page --------------- */

    let postPageTitle = ajaxDoc.querySelector("div.entry.unvoted > div.top-matter > p.title > a");
    let postPageImage = ajaxDoc.querySelector("div.entry.unvoted > div.expando > div > div > a > img").src;
    let postPageImageLink = ajaxDoc.querySelector("div.entry.unvoted > div.expando > div > div > a").href;

    // Maak een pagina aan voor de postpagina
    if (redditLink === postPage) {
      wikiContent.innerHTML += `
                <h1>${postPageTitle.innerText}</h1>
                    <div id="bodyContent" class="mw-body-content">
                        <div id="mw-content-text" dir="ltr" class="mw-content-ltr">
                            <div class="mw-parser-output">

                        <table class="toccolours vatop infobox" cellpadding="1" cellspacing="1" style="float:right; clear:right; width:270px; padding:0px; margin:0px 0px 1em 1em; font-size:85%;">
                          <tbody>
                            <tr>
                              <td style="background-color:#e3e3e3; color:#000000;" align="center" colspan="3">
                                <div style="font-weight:bold; font-size:120%; text-align: center;">${postPageTitle.innerText}</div>
                              </td>
                            </tr>

                        <tr>
                          <td align="center" style="padding:0;" colspan="3">
                            <a href="${postPageImageLink}" class="image" target="_blank">
                              <img src="${postPageImage}" width="266" data-file-width="800">
                            </a>
                          </td>
                        </tr>

                          </tbody>
                        </table>
                            </div>
                        </div>
                    </div>
            `;
    }

    // Manieren om op een postpagina te geraken:
    // - Title
    // - Image (Alleen als deze verwijst naar reddit)
    // - Reacties (Deze knop moet verbonden worden met gotoPostPage() via een eventlistener)

    /* --------------- Links navigatieknoppen --------------- */

    if (previousPage) previousPageLink = previousPage.href;
    if (nextPage) nextPageLink = nextPage.href;
    // Op de pagina van een post zijn deze knoppen niet toegankelijk

  }
};