Display case market value

Display the total market value of items in a display case

  1. // ==UserScript==
  2. // @name Display case market value
  3. // @namespace Violentmonkey Scripts
  4. // @match https://www.torn.com/displaycase.php*
  5. // @grant GM_xmlhttpRequest
  6. // @version 1.0
  7. // @license MIT
  8. // @author BillyBourbon/Bilbosaggings[2323763]
  9. // @description Display the total market value of items in a display case
  10. // ==/UserScript==
  11.  
  12. // ================================
  13. // Input your apikey in between the quote marks ""
  14. const apikey = "";
  15. // ================================
  16.  
  17. (async () => {
  18. // Function to format numbers to currency format (USD)
  19. function formatToCurrency(n) {
  20. n = Number(n);
  21. return new Intl.NumberFormat("en-US", {
  22. style: "currency",
  23. currency: "USD",
  24. minimumFractionDigits: 0,
  25. maximumFractionDigits: 0
  26. }).format(n);
  27. }
  28.  
  29. // Function to load Torn items with caching
  30. async function loadTornItems() {
  31. const cacheKey = "tornItemsCache";
  32. const cacheExpiryKey = "tornItemsCacheExpiry";
  33. const cacheDuration = 60 * 60 * 1000; // 1 hour in milliseconds
  34.  
  35. // Check for cached data
  36. const cachedData = localStorage.getItem(cacheKey);
  37. const cachedExpiry = localStorage.getItem(cacheExpiryKey);
  38.  
  39. if (cachedData && cachedExpiry && Date.now() < cachedExpiry) {
  40. console.log("Using cached data");
  41. return JSON.parse(cachedData);
  42. }
  43.  
  44. let attempt = 0;
  45. let jsonResponse = null;
  46.  
  47. // Retry logic for API request
  48. while (attempt < 3) {
  49. try {
  50. jsonResponse = await new Promise((resolve, reject) => {
  51. GM_xmlhttpRequest({
  52. method: "GET",
  53. url: `https://api.torn.com/v2/torn/items`,
  54. headers: {
  55. "Authorization": `ApiKey ${apikey}`,
  56. },
  57. onload: function (response) {
  58. if (response.status >= 200 && response.status < 300) {
  59. try {
  60. const responseData = JSON.parse(response.responseText);
  61. resolve(responseData);
  62. } catch (error) {
  63. reject(new Error("Failed to parse JSON"));
  64. }
  65. } else {
  66. reject(new Error(`API request failed with status: ${response.status}`));
  67. }
  68. },
  69. onerror: function (error) {
  70. reject(new Error(`API request failed with error: ${error}`));
  71. }
  72. });
  73. });
  74.  
  75. console.log(jsonResponse);
  76.  
  77. // Cache the API response
  78. localStorage.setItem(cacheKey, JSON.stringify(jsonResponse));
  79. localStorage.setItem(cacheExpiryKey, Date.now() + cacheDuration);
  80.  
  81. return jsonResponse;
  82. } catch (error) {
  83. attempt++;
  84. console.error(`Attempt ${attempt} failed: ${error.message}`);
  85.  
  86. if (attempt < 3) {
  87. await new Promise(resolve => setTimeout(resolve, 2000)); // Delay before retrying
  88. }
  89. }
  90. }
  91. }
  92.  
  93. // Function to find a Torn item by its ID
  94. function findTornItem(itemId, tornItems) {
  95. const item = tornItems.find(o => o.id.toString() === itemId.toString());
  96.  
  97. // Return null if item is not found
  98. return item || null;
  99. }
  100.  
  101. // Wait for the display case container to load
  102. while (document.querySelector(".display-cabinet") === null) {
  103. await new Promise(resolve => setTimeout(resolve, 500)); // Delay before retrying
  104. }
  105.  
  106. // Select the display case container
  107. const displayCaseContainer = document.querySelector(".display-cabinet");
  108.  
  109. // Load the Torn items
  110. const { items: tornItems } = await loadTornItems();
  111.  
  112. // Iterate through each item in the display case
  113. displayCaseContainer.querySelectorAll("li").forEach(li => {
  114. const temp = li.querySelector(".item-hover");
  115.  
  116. if (temp === null) return; // Skip if there's no item
  117.  
  118. const itemId = temp.getAttribute("itemId");
  119.  
  120. const ammountField = li.querySelector(".b-item-amount");
  121.  
  122. const ammount = ammountField.innerHTML.trim().substring(1);
  123.  
  124. // Find the item from the loaded Torn items
  125. const item = findTornItem(itemId, tornItems);
  126.  
  127. // Check if item was found
  128. if (item && item.value && item.value.market_price) {
  129. const marketPrice = item.value.market_price;
  130.  
  131. // Calculate total market value
  132. ammountField.innerHTML += `(${formatToCurrency(ammount * marketPrice)})`;
  133. } else {
  134. console.error(`Item with ID ${itemId} not found or missing market price.`);
  135. }
  136. });
  137. })();