Danbooru theme toggle (sunrise API)

Automatically toggle native dark mode on sunset and sunrise on danbooru.donmai.us

// ==UserScript==
// @name         Danbooru theme toggle (sunrise API)
// @namespace    Danbooru
// @version      1
// @description  Automatically toggle native dark mode on sunset and sunrise on danbooru.donmai.us
// @author       Dramorian, fredgido
// @match        https://danbooru.donmai.us/*
// @run-at       document-start
// @license      MIT
// ==/UserScript==

// Define the URL for the API that provides sunrise and sunset times
const apiUrl = "https://api.sunrise-sunset.org/json?lat=&lng=&formatted=0";

// Fetch the sunrise and sunset times from the API
fetch(apiUrl)
  .then(response => response.json())
  .then(data => {
    // Extract the sunrise and sunset times from the API response
    const sunrise = new Date(data.results.sunrise).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit', hour12: false});
    const sunset = new Date(data.results.sunset).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit', hour12: false});

    // Get the current time in hh:mm format
    const currentTime = new Date().toLocaleTimeString([], {hour: '2-digit', minute:'2-digit', hour12: false});

    // Check if the current time is between sunset and sunrise
    const isNightTime = (currentTime >= sunset || currentTime < sunrise);

    // Update the theme based on the time
    const currentThemeIsDark = Danbooru.CurrentUser.darkMode();
    if((isNightTime && !currentThemeIsDark) || (!isNightTime && currentThemeIsDark) ){
      Danbooru.CurrentUser.update({theme: isNightTime ? "dark" : "light"}).then(() => {
        Danbooru.Utility.notice("Theme updated.");
        window.location = window.location;
      });
    }
  })
  .catch(error => console.error(error));