archwhite
4/19/2019 - 5:37 AM

set random background

// ==UserScript==
// @name         New Userscript
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        http://*/*
// @grant        none
// ==/UserScript==

(function() {
  'use strict';

    // set initial states
    let state = {
      self: this,
      wallid: 0,
      url: '',
      tries: 0
    }

    // init dom elements
    var imgTest = document.createElement('img');
    var body = document.getElementsByTagName('body')[0];

    // hide the horizontal and vertical stripes
    document.querySelector('div#stripH').style.display = 'none';
    document.getElementById('stripV').style.display = 'none';
    var v = document.getElementById('vertical');
    v.style.color = 'white';
    v.style.opacity = 1.0;

    // set styles for background image
    body.style.backgroundRepeat = 'no-repeat';
    body.style.backgroundSize = 'cover';
    body.style.backgroundPosition = "center center";

    body.style.backgroundAttachment = 'fixed';
    body.style.minHeight = "100%";
    body.style.minWidth = "100%";

    // set event handlers
    imgTest.onload = function(ev) {
      console.log('loaded ', state.url);
      body.style.backgroundImage = `url(${state.url})`;
    };

    imgTest.onerror = function(ev) {
      console.log('error ', state.url);
      setRandomBackground();
    };

    // random int, max is not included
    function getRandomInt(min, max) {
      return Math.floor(Math.random() * (max - min)) + min;
    }


    function getRandomImageUrl(hashlen = 6) {
    	function range(size, startAt = 0) {
    	    return [...Array(size).keys()].map(i => i + startAt);
    	}

    	function characterRange(startChar, endChar) {
    	    return String.fromCharCode(...range(1 + endChar.charCodeAt(0) -
    	            startChar.charCodeAt(0), startChar.charCodeAt(0)))
    	}

    	let digitOrChar = 0;
    	const digitRange = range(10);
    	const charRange = characterRange('a', 'z');

    	let result = "";

    	for (var i = 0; i < 6; ++i) {
    		digitOrChar = Math.round(Math.random());
    		if (digitOrChar === 0) { // digit
    			result += digitRange(getRandomInt(0, digitRange.length));
            } else {
    			result += charRange(getRandomInt(0, charRange.length));
            }
    	}

    	return result;
    }

    function getUrl(wallId, ext = 'jpg') {
    	return
    	`https://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-${wallId}.${ext}`;
    	//`https://w.wallhaven.cc/full/${wallId.slice(0,2)}/wallhaven-${wallId}.${ext}`;
    }

    function getRandomUrlUsingAPI() {
		return fetch('https://wallhaven.cc/api/v1/search?sorting=random');
    }

    // main func
    function setRandomBackground() {
      if (state.tries == 1)
      {
        // try png now (second try)
        state.url = getUrl(state.wallid, 'png');
        state.tries = 2;
        imgTest.src = state.url;
      } else {
        //state.wallid = getRandomInt(0, 999999);
        //state.wallid = getRandomImageUrl();
        //console.log('wall id = ', state.wallid);
        //state.url = getUrl(state.wallid, 'jpg');
        getRandomUrlUsingAPI()
        .then(resp => resp.json())
        .then(images => { 
        	state.url = images.data[0].path;
        	state.tries = 1;
        	imgTest.src = state.url;
        });
      }
    }

    setRandomBackground();

})();