[HFR] Links preview

Previsualise le contenu des liens dans les posts

2018-11-04 일자. 최신 버전을 확인하세요.

질문, 리뷰하거나, 이 스크립트를 신고하세요.
// ==UserScript==
// @name         [HFR] Links preview
// @namespace    http://tampermonkey.net/
// @version      0.3
// @description  Previsualise le contenu des liens dans les posts
// @icon         http://reho.st/self/40f387c9f48884a57e8bbe05e108ed4bd59b72ce.png
// @author       Garath_
// @include      https://forum.hardware.fr/forum2.php*
// @include      https://forum.hardware.fr/hfr/*
// @grant        GM_xmlhttpRequest
// ==/UserScript==


var auSurvol = false;

var links = document.querySelectorAll("td.messCase2 > div[id^='para'] > p > a.cLink, table.spoiler a.cLink");

function truncate(str, n)
{
    var isTooLong = str.length > n,
    s_ = isTooLong ? str.substr(0,n-1) : str;
    //s_ = isTooLong ? s_.substr(0,s_.lastIndexOf(' ')) : s_;
    return isTooLong ? s_ + '...' : s_;
}

function linkify(text) {
    var urlRegex =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;\(\)]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(urlRegex, function(url) {
        return '<a href="' + url + '">lien</a>';
    });
}

function extractHostname(url) {
    var hostname;
    //find & remove protocol (http, ftp, etc.) and get hostname

    if (url.indexOf("//") > -1) {
        hostname = url.split('/')[2];
    }
    else {
        hostname = url.split('/')[0];
    }

    //find & remove port number
    hostname = hostname.split(':')[0];
    //find & remove "?"
    hostname = hostname.split('?')[0];

    return hostname;
}

function getAsin(url) {
    var asinRegex = /(?:[/dp/]|$)([A-Z0-9]{10})/;
    var match = asinRegex.exec(url);
    return match[1];
}

function format(txt, href) {
    var parser = new DOMParser();
    var xmlDoc = parser.parseFromString(txt, 'text/html');

    const metas = xmlDoc.getElementsByTagName('meta');
    var des = "";
    var title = "";
    var image = "";
    var site = "";
    var resolve = false;


    for (let i = 0; i < metas.length; i++) {
        if ( (metas[i].getAttribute('name') === "description") || (metas[i].getAttribute('name') === "twitter:description") ) {
            des = metas[i].getAttribute('content');
        }
        if (metas[i].getAttribute('property') === "og:title") {
            title = metas[i].getAttribute('content');
        }
        if (metas[i].getAttribute('property') === "og:image") {
            image = metas[i].getAttribute('content');
        }
        if (metas[i].getAttribute('property') === "og:site_name") {
            site = metas[i].getAttribute('content');
        }
    }

    if (title === "") {
        var t = xmlDoc.getElementsByTagName('title')[0];
        if (t) {
            title = t.innerText;
        }
    }

    if (site === "") {
        site = extractHostname(href);
    }

    // Traitement spécial pour ces connards d'amazon
    if (site.includes("amazon")) {
        if (image == "") {
            image = xmlDoc.getElementById("imgTagWrapperId").firstElementChild.getAttribute("data-old-hires");
            //image = "http://images.amazon.com/images/P/" + getAsin(href) + "._PE30_PI_SCMZZZZZZZ_.jpg";
        }
    }

    var newLink = document.createElement("div");
    newLink.style.cssText = "background-color: white; border:1px; border-style:solid; border-color:#C0C0C0; padding: 5px; overflow:hidden; max-width:500px; box-shadow: 0px 5px 15px #888888;"

    if (image) {
        var img = document.createElement("img");
        img.setAttribute("src", image);
        img.style.cssText = "float:left; margin-right:3px; max-height:100px; max-width:100px";
        newLink.appendChild(img);

        resolve = true;
    }

    if (title) {
        var a = document.createElement("a");
        a.setAttribute("href", href);
        a.style.cssText = "color: black; font-weight: 550; font-size: 10px;";
        a.appendChild(document.createTextNode(truncate(title, 100)));
        newLink.appendChild(a);
    }

    if (site) {
        newLink.appendChild(document.createElement("br"));
        var s = document.createElement("span");
        s.style.cssText = "color: #808080; font-size: 0.8em;"
        s.appendChild(document.createTextNode(truncate(site, 50)));
        newLink.appendChild(s);
    }

    if (des) {
        if (des.localeCompare(title) != 0) {
            newLink.appendChild(document.createElement("br"));
            newLink.appendChild(document.createElement("br"));
            var desc = document.createElement("div");
            if (image) {
                desc.style.cssText = "margin-left: 103px;";
            }
            desc.innerHTML += linkify(truncate(des, 150));
            newLink.appendChild(desc);

            resolve = true;
        }
    }

    if (resolve) {
        return newLink;
    }
    else {
        return document.createElement("div");
    }
}

function requestContentOnMouse() {
    var target = this;
    GM_xmlhttpRequest({
            method: "GET",
            url: target.href,
            mozAnon: true,
            anonymous: true,
            onload: function(response) {
                var newLink = format(response.responseText, target.href);
                if (newLink.innerHTML != "") {
                    target.parentNode.replaceChild(newLink, target);
                }
            }
     });
}

function requestContent(link) {
    GM_xmlhttpRequest({
            method: "GET",
            url: link.href,
            mozAnon: true,
            anonymous: true,
            onload: function(response) {
                var newLink = format(response.responseText, link.href);
                if (newLink.innerHTML != "") {
                    link.parentNode.replaceChild(newLink, link);
                }
            }
     });
}

function filter(link) {
    if (link.firstChild.nodeName == "IMG") {
        return false;
    }
    else {
        return true;
    }
}

function replace(links) {
  for(let link of links) {
      if (filter(link)) {
          if (auSurvol) {
               link.addEventListener("mouseover", requestContentOnMouse, false);
          }
          else {
               requestContent(link);
          }
      }
  }
}

replace(links);