jnaskali / Invidious Quick Mirrors

// ==UserScript==
// @name        Invidious Quick Mirrors
// @author      jnaskali
// @copyright   2020, Juhani Naskali (www.naskali.fi)
// @license     MIT
// @version     1.5
// @namespace   https://www.naskali.fi
// @downloadURL https://openuserjs.org/install/jnaskali/Invidious_Quick_Mirrors.user.js
//
// @include       https://invidio.*/*
// @include       https://invidiou.*/*
// @include       https://invidious.*/*
// @include       https://yewtu.be/*
// @include       https://watch.nettohikari.com/*
// @grant       none
//
// @description Shows a quick mirror numberbar in the top-right corner of Invidious pages and video thumbnails.
// ==/UserScript==

/* CONFIG: instance list - add your own */
var instances = [
  "invidious.13ad.de",
  "invidious.snopyta.org",
  "yewtu.be",
  "invidious.toot.koeln",
  "invidiou.site",
  "invidious.ggc-project.de",
  "invidious.fdn.fr"
];


/* Add mirrors for current page to top-left corner of hover-catcher, if exists, or body */
var loc = window.location.pathname + window.location.search + window.location.hash;
document.querySelector('.navbar').appendChild( mirrorDiv(loc) );

/* Add mirrors for thumbnails */
thumbnails = document.querySelectorAll('div.thumbnail');
for(var i = 0; i < thumbnails.length; i++) {
  links = mirrorDiv( thumbnails[i].parentElement.href.replace(/^.*\/\/[^\/]+/,'') );
  thumbnails[i].appendChild( links );
}


/* Add styles for quick-mirrors and thumbnail link hovers */
var style = document.createElement('style');
style.innerHTML = `
  .quick-mirrors {
    background: #000;
    position: absolute;
    top: 0;
    right: 0;
    z-index: 10;
    letter-spacing: initial;
  }
  .quick-mirrors > a {
    display: inline-block;
    padding: 2px 3px;
  }
  .thumbnail > .quick-mirrors > a { display:none; }
  .thumbnail:hover > .quick-mirrors > a {display: inline; }
`;
document.head.appendChild(style);


/* Dynamically update current page mirror links startTime */
function updateTime() {
  if (typeof player !== 'undefined') {
    var url = new URL(this.href);
    url.searchParams.set( "start", Math.floor(player.currentTime()) );
    this.href = url;
  }
}
var updateLinks = document.querySelectorAll('.navbar > .quick-mirrors > a');
for (var i = 0; i < updateLinks.length; ++i) {
  updateLinks[i].addEventListener("mouseover", updateTime);
}

/* Create quick mirrors div for URL */
function mirrorDiv(link) {
  var div = document.createElement('div');
  for(var i = 0; i < instances.length; i++) {
    var url = new URL('https://' + instances[i] + link);
    //url.searchParams.set("quality", "dash");
    div.innerHTML += '  <a href="' + url + '" title="' + instances[i] + '">' + (i+1) + '</a>';
  }
  div.className = 'quick-mirrors';
  return div
}