Danbooru theme toggle (sunrise API)

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

  1. // ==UserScript==
  2. // @name Danbooru theme toggle (sunrise API)
  3. // @namespace Danbooru
  4. // @version 1
  5. // @description Automatically toggle native dark mode on sunset and sunrise on danbooru.donmai.us
  6. // @author Dramorian, fredgido
  7. // @match https://danbooru.donmai.us/*
  8. // @run-at document-start
  9. // @license MIT
  10. // ==/UserScript==
  11.  
  12. // Define the URL for the API that provides sunrise and sunset times
  13. const apiUrl = "https://api.sunrise-sunset.org/json?lat=&lng=&formatted=0";
  14.  
  15. // Fetch the sunrise and sunset times from the API
  16. fetch(apiUrl)
  17. .then(response => response.json())
  18. .then(data => {
  19. // Extract the sunrise and sunset times from the API response
  20. const sunrise = new Date(data.results.sunrise).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit', hour12: false});
  21. const sunset = new Date(data.results.sunset).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit', hour12: false});
  22.  
  23. // Get the current time in hh:mm format
  24. const currentTime = new Date().toLocaleTimeString([], {hour: '2-digit', minute:'2-digit', hour12: false});
  25.  
  26. // Check if the current time is between sunset and sunrise
  27. const isNightTime = (currentTime >= sunset || currentTime < sunrise);
  28.  
  29. // Update the theme based on the time
  30. const currentThemeIsDark = Danbooru.CurrentUser.darkMode();
  31. if((isNightTime && !currentThemeIsDark) || (!isNightTime && currentThemeIsDark) ){
  32. Danbooru.CurrentUser.update({theme: isNightTime ? "dark" : "light"}).then(() => {
  33. Danbooru.Utility.notice("Theme updated.");
  34. window.location = window.location;
  35. });
  36. }
  37. })
  38. .catch(error => console.error(error));