· 6 years ago · Oct 07, 2019, 05:24 AM
1'use strict'
2// ==UserScript==
3// @name Lowest Bazaar Price
4// @author nepherius[2009878]
5// @description Display the lowest bazaar price, on itemmarket/bazzar add item page.
6// @match https://www.torn.com/bazaar.php*
7// @include https://www.torn.com/imarket.php*
8// @connect api.torn.com
9// @version 0.0.1
10// @updateURL https://github.com/Nepherius/userscripts/raw/master/lowest_bazaar_price.user.js
11// @require http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js
12// @require https://gist.github.com/raw/2625891/waitForKeyElements.js
13// @grant GM_xmlhttpRequest
14// @grant GM_getValue
15// @grant GM_setValue
16// @grant GM_deleteValue
17// @run-at document-start
18// ==/UserScript==
19
20
21let API_KEY;
22let Items;
23if (!GM_getValue('api_key')) {
24 let key = prompt('Please enter your Torn API Key, this will be stored locally!')
25 GM_setValue('api_key', key)
26 API_KEY = key
27} else {
28 API_KEY = GM_getValue('api_key')
29}
30
31waitForKeyElements(".info-active.item-active.actions-active", setup)
32
33function setup() {
34 let item = $('.info-active.item-active.actions-active')
35 let itemId = $(item).find('.image-wrap img').attr('src').match(/(?<=items\/)(\d+)(?=\/)/gi)[0]
36 console.log('result:', itemId)
37 bazaarList(API_KEY, itemId).then(async (list) => {
38 let lowestPrice = findLowestPrice(list)
39 let boXtoReplace = $(item).find('.show-item-info .info-content .t-right')[0]
40 $(boXtoReplace).html(`<div class="title">Bazaar buy:</div>
41 <div class="desc">${toCurrency(lowestPrice)}</div>
42 <div class="clear"></div>`)
43 })
44}
45
46
47function findLowestPrice(list) {
48 let lowest;
49 for (let bazaar in list) {
50 if (!lowest) {
51 lowest = list[bazaar]['cost']
52 } else if (list[bazaar]['cost'] < lowest) {
53 lowest = list[bazaar]['cost']
54 }
55 }
56 return lowest
57}
58
59function toCurrency(amount) {
60 return amount.toLocaleString(
61 'en', {
62 style: 'currency',
63 currency: 'USD',
64 minimumFractionDigits: 0,
65 maximumFractionDigits: 3,
66 },
67 )
68}
69
70function bazaarList(api_key, itemId) {
71 return new Promise((resolve, reject) => {
72 let ret = GM_xmlhttpRequest({
73 method: "GET",
74 url: `https://api.torn.com/market/${itemId}?selections=bazaar&key=${api_key}`,
75 onreadystatechange: function (res) {
76 if (res.readyState === 4 && res.status === 200) {
77 const parsedRes = JSON.parse(res.responseText)
78 list = parsedRes.bazaar
79 resolve(list)
80 }
81 },
82 onerror: function (err) {
83 console.log(err)
84 }
85 })
86 }).catch(e => {
87 console.log(e)
88 });
89}