Age-calculator - stashdb.org

9/19/2023, 10:13:09 AM

// ==UserScript==
// @name        Age-calculator - stashdb.org
// @namespace   Violentmonkey Scripts
// @match       https://stashdb.org/performers/*
// @grant       none
// @version     1.1
// @author      Yahigod
// @license MIT
// @description 9/19/2023, 10:13:09 AM
// ==/UserScript==

const mutationObserver = new MutationObserver(entries => {
  // Reset the timer whenever mutations are observed
  clearTimeout(observerTimer);
  observerTimer = setTimeout(() => {
    runScriptIfNoMutations();
  }, timeoutDuration);
});

let observerTimer;
const timeoutDuration = 900; // Set the timeout duration in milliseconds (e.g., 5000ms = 5 seconds)
let isScriptRunning = false; // Track whether the script is already running

// Observe changes in the body element and its subtree
const body = document.querySelector('body');
if (body) {
  mutationObserver.observe(body, { childList: true, subtree: true });
}

// Initial setup of the timer
observerTimer = setTimeout(() => {
  runScriptIfNoMutations();
}, timeoutDuration);

// Function to run your script
function runScriptIfNoMutations() {
  // Check if the script is already running, and if so, exit to avoid recursion
  if (isScriptRunning) {
    return;
  }

  // Disconnect the MutationObserver to prevent it from triggering during script execution
  mutationObserver.disconnect();
  isScriptRunning = true;

  // Check if the "old" text is already present under the date
  const sceneCards = document.querySelectorAll('.SceneCard.card');
  let shouldRunScript = true;

  for (const sceneCard of sceneCards) {
    const ageText = sceneCard.querySelector('.card-footer strong + span');

    if (ageText && ageText.textContent.trim() === 'old') {

      shouldRunScript = false;
      break; // No need to continue checking if we found one instance of "old"
    }
  }

  if (shouldRunScript) {
    // The provided code
    (function() {
      'use strict';

      // Function to calculate age
      function calculateAge(birthdate, sceneDate) {
          const birthDate = new Date(birthdate);
          const sceneDateObject = new Date(sceneDate);

          const ageInMilliseconds = sceneDateObject - birthDate;
          const ageInYears = ageInMilliseconds / (365 * 24 * 60 * 60 * 1000);

          const birthYear = birthDate.getFullYear();
          const sceneYear = sceneDateObject.getFullYear();

          const birthMonth = birthDate.getMonth();
          const sceneMonth = sceneDateObject.getMonth();

          const birthDay = birthDate.getDate();
          const sceneDay = sceneDateObject.getDate();

          let years = sceneYear - birthYear;
          let months = sceneMonth - birthMonth;
          let days = sceneDay - birthDay;

          if (days < 0) {
              months -= 1;
              days += 30; // Assuming an average of 30 days per month
          }

          if (months < 0) {
              years -= 1;
              months += 12;
          }

          let ageText = '';

          if (years > 0) {
              ageText += `${years}y `;
          }

          if (months > 0) {
              ageText += `${months}m `;
          }

          if (days > 0) {
              ageText += `${days}d `;
          }

          ageText += 'old';

          return ageText.trim();
      }

      // Extract and print birthdates
      const rows = document.querySelectorAll('tr'); // Adjust the selector to match your webpage's structure
      let birthdate; // Declare birthdate variable outside the loop

      for (const row of rows) {
          const cells = row.querySelectorAll('td'); // Select all <td> elements in the row

          if (cells.length == 2) { // Assuming birthdate is in the first cell
              const birthdateCell = cells[0].textContent.trim();
              if (birthdateCell === "Birthdate") {
                  birthdate = cells[1].textContent.trim(); // Store the birthdate
              }
          }
      }

      // Add age next to each date in SceneCard elements
      const sceneCards = document.querySelectorAll('.SceneCard.card:not([data-script-applied])'); // Select all elements with class "SceneCard card"

      for (const sceneCard of sceneCards) {
          const dateStrong = sceneCard.querySelector('.card-footer strong'); // Find the strong element inside the card-footer

      if (dateStrong) {
          const dateText = dateStrong.textContent.trim(); // Extract the date text
          const birthYear = parseInt(birthdate.split('-')[0]); // Extract the birth year from the birthdate

          const age = calculateAge(birthdate, dateText); // Calculate the age
          const ageElement = document.createElement('span'); // Create a new <span> element for the age
          ageElement.textContent = age; // Set the age text content

          // Create a <br> element for a line break
          const lineBreak = document.createElement('br');

          // Insert the age element and line break after the date element
          dateStrong.insertAdjacentElement('afterend', ageElement); // Add the age element under the date
          dateStrong.insertAdjacentElement('afterend', lineBreak); // Add a line break under the date
          sceneCard.setAttribute('data-script-applied', 'true');
      }
      }
  })();
  }

  // Reconnect the MutationObserver after script execution is complete
  mutationObserver.observe(body, { childList: true, subtree: true });
  isScriptRunning = false;
}