· 6 years ago · Feb 18, 2020, 01:38 PM
1// ==UserScript==
2// @name Bazaar Auto Price
3// @namespace tos
4// @version 0.6
5// @description description
6// @author tos
7// @match *.torn.com/bazaar.php*
8// @grant GM_xmlhttpRequest
9// ==/UserScript==
10
11const apikey = ''
12
13const torn_api = async (args) => {
14 const a = args.split('.')
15 if (a.length!==3) throw(`Bad argument in torn_api(args, key): ${args}`)
16 return new Promise((resolve, reject) => {
17 GM_xmlhttpRequest ( {
18 method: "POST",
19 url: `https://api.torn.com/${a[0]}/${a[1]}?selections=${a[2]}&key=${apikey}`,
20 headers: {
21 "Content-Type": "application/json"
22 },
23 onload: (response) => {
24 try {
25 const resjson = JSON.parse(response.responseText)
26 resolve(resjson)
27 } catch(err) {
28 reject(err)
29 }
30 },
31 onerror: (err) => {
32 reject(err)
33 }
34 })
35 })
36}
37
38var event = new Event('keyup')
39var APIERROR = false
40
41async function lmp(itemID) {
42 if(APIERROR === true) return 'API key error'
43 const prices = await torn_api(`market.${itemID}.bazaar`)
44 if (prices.error) {APIERROR = true; return 'API key error'}
45 let lowest_market_price = null
46 for (const market in prices) {
47 for (const lid in prices[market]) {
48 if (lowest_market_price === null) lowest_market_price = prices[market][lid].cost
49 else if (prices[market][lid].cost < lowest_market_price) lowest_market_price = prices[market][lid].cost
50 }
51 }
52 return Math.round(lowest_market_price * 1)
53}
54
55const observer = new MutationObserver((mutations) => {
56 for (const mutation of mutations) {
57 for (const node of mutation.addedNodes) {
58 if (node.classList && node.classList.contains('input-money-group')) {
59 const li = node.closest('li.clearfix') || node.closest('li[id^=item]')
60 const input = node.querySelector('.input-money[type=text]')
61 if (li) {
62 const itemID = li.querySelector('img').src.split('items/')[1].split('/medium')[0]
63 input.addEventListener('focus', function(e) {
64 if (this.id.includes('price-item')) this.value = ''
65 if (this.value === '') {
66 lmp(itemID).then((price) => {
67 this.value = price
68 this.dispatchEvent(event)
69 })
70 }
71 })
72 }
73 }
74 }
75 }
76})
77
78const wrapper = document.querySelector('#bazaar-page-wrap')
79observer.observe(wrapper, { subtree: true, childList: true })