Level Progress Estimation

Adds a fractional level pill to the PDA header tray.

15.04.2026 itibariyledir. En son verisyonu görün.

Bu betiği kurabilmeniz için Tampermonkey, Greasemonkey ya da Violentmonkey gibi bir kullanıcı betiği eklentisini kurmanız gerekmektedir.

Bu betiği yüklemek için Tampermonkey gibi bir uzantı yüklemeniz gerekir.

Bu betiği kurabilmeniz için Tampermonkey ya da Violentmonkey gibi bir kullanıcı betiği eklentisini kurmanız gerekmektedir.

Bu betiği kurabilmeniz için Tampermonkey ya da Userscripts gibi bir kullanıcı betiği eklentisini kurmanız gerekmektedir.

Bu betiği indirebilmeniz için ayrıca Tampermonkey gibi bir eklenti kurmanız gerekmektedir.

Bu komut dosyasını yüklemek için bir kullanıcı komut dosyası yöneticisi uzantısı yüklemeniz gerekecek.

(Zaten bir kullanıcı komut dosyası yöneticim var, kurmama izin verin!)

Bu stili yüklemek için Stylus gibi bir uzantı yüklemeniz gerekir.

Bu stili yüklemek için Stylus gibi bir uzantı kurmanız gerekir.

Bu stili yükleyebilmek için Stylus gibi bir uzantı yüklemeniz gerekir.

Bu stili yüklemek için bir kullanıcı stili yöneticisi uzantısı yüklemeniz gerekir.

Bu stili yüklemek için bir kullanıcı stili yöneticisi uzantısı kurmanız gerekir.

Bu stili yükleyebilmek için bir kullanıcı stili yöneticisi uzantısı yüklemeniz gerekir.

(Zateb bir user-style yöneticim var, yükleyeyim!)

// ==UserScript==
// @name         Level Progress Estimation
// @namespace    http://tampermonkey.net/
// @version      1.2.3
// @description  Adds a fractional level pill to the PDA header tray. 
// @author       Pint-Shot-Riot / Gemini
// @match        https://www.torn.com/*
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_xmlhttpRequest
// @connect      api.torn.com
// @license MIT
// ==/UserScript==

(function () {
  "use strict";

  // Reduced threshold to 90 days for better reliability
  const INACTIVE_THRESHOLD = 90 * 24 * 60 * 60; 
  const PAGE_SIZE = 100;

  async function getApiKey() {
    let key = localStorage.getItem("APIKey");
    if (!key || key.length < 10) key = await GM_getValue("torn_api_key", "");
    if (!key || key.length < 10) {
      key = prompt("Please enter your (limited) Torn API Key:");
      if (key) await GM_setValue("torn_api_key", key.trim());
    }
    return key ? key.trim() : null;
  }

  async function fetchTorn(url) {
    return new Promise((resolve, reject) => {
      GM_xmlhttpRequest({
        method: "GET",
        url: url,
        onload: (res) => {
          try {
            const data = JSON.parse(res.responseText);
            if (data.error) reject(data.error.error);
            else resolve(data);
          } catch (e) { reject("JSON Error"); }
        },
        onerror: (err) => reject(err)
      });
    });
  }

  async function getAccurateLevel() {
    const key = await getApiKey();
    if (!key) return null;

    try {
      const user = await fetchTorn(`https://api.torn.com/v2/user/hof?key=${key}`);
      const { value: level, rank } = user.hof.level;
      
      if (level >= 100) return "100.00";
      
      // Fetch HoF around your rank
      const offset = Math.max(0, rank - 50);
      const hofData = await fetchTorn(`https://api.torn.com/v2/torn/hof?limit=${PAGE_SIZE}&offset=${offset}&cat=level&key=${key}`);
      const players = hofData.hof || [];
      
      // Find the highest ranked person at your level (Current Level Ceiling)
      let currentAnchor = players
        .filter(p => p.level === level && (Date.now()/1000 - p.last_action) > INACTIVE_THRESHOLD)
        .sort((a, b) => a.position - b.position)[0];

      // Find the highest ranked person at the level below (Lower Level Ceiling)
      let lowerAnchor = players
        .filter(p => p.level === (level - 1) && (Date.now()/1000 - p.last_action) > INACTIVE_THRESHOLD)
        .sort((a, b) => a.position - b.position)[0];

      // FALLBACK: If no inactive anchors found, use raw level boundaries
      if (!currentAnchor) currentAnchor = players.find(p => p.level === level);
      if (!lowerAnchor) lowerAnchor = players.find(p => p.level === (level - 1));

      // If we still can't find boundaries, we can't calculate
      if (!currentAnchor || !lowerAnchor) return level.toFixed(2);

      const range = lowerAnchor.position - currentAnchor.position;
      const yourProgress = lowerAnchor.position - rank;
      const fraction = Math.max(0, Math.min(0.99, yourProgress / range));
      
      return (level + fraction).toFixed(2);
    } catch (e) {
      console.error("Accurate Level Error:", e);
      return null;
    }
  }

  function injectIcon(val) {
    const existingPill = document.getElementById('acc-lvl-pill');
    if (existingPill) {
      document.getElementById('acc-lvl-val').textContent = val;
      return;
    }

    const header = document.querySelector('#header-root') || document.querySelector('.header-wrapper');
    if (!header) return;

    const tray = header.querySelector('[class*="right_"]') || 
                 header.querySelector('[class*="header-buttons"]') ||
                 header.querySelector('.header-navigation');

    if (!tray) return;

    const pill = document.createElement('div');
    pill.id = 'acc-lvl-pill';
    pill.style = "display: inline-flex; align-items: center; background: #333; border: 1px solid #444; border-radius: 10px; padding: 2px 8px; margin: 0 4px; height: 22px; vertical-align: middle; cursor: pointer; box-shadow: 0 1px 3px rgba(0,0,0,0.5); flex-shrink: 0; z-index: 999;";
    pill.innerHTML = `
      <span style="color: #85b200; font-size: 10px; font-weight: bold; margin-right: 4px; font-family: sans-serif;">LV</span>
      <span id="acc-lvl-val" style="color: #fff; font-size: 11px; font-family: 'Courier New', monospace; font-weight: bold;">${val}</span>
    `;

    pill.onclick = (e) => {
        e.preventDefault();
        window.location.href = "/halloffame.php#/type=level";
    };

    tray.prepend(pill);
  }

  async function run() {
    let currentVal = await getAccurateLevel();
    if (currentVal) {
      injectIcon(currentVal);
      setInterval(async () => {
        const updated = await getAccurateLevel();
        if (updated) { currentVal = updated; injectIcon(currentVal); }
      }, 600000);
      
      setInterval(() => {
          if (!document.getElementById('acc-lvl-pill')) injectIcon(currentVal);
      }, 2000);
    }
  }

  if (document.readyState === "complete") run();
  else window.addEventListener("load", run);

})();