-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathprices-tf-pricer.ts
183 lines (155 loc) · 5.55 KB
/
prices-tf-pricer.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
import Currencies from '@tf2autobot/tf2-currencies';
import PricesTfSocketManager from './prices-tf-socket-manager';
import IPricer, {
GetItemPriceResponse,
GetPricelistResponse,
Item,
PricerOptions,
RequestCheckResponse
} from '../../../types/interfaces/IPricer';
import PricesTfApi, { PricesTfGetPricesResponse, PricesTfItem, PricesTfItemMessageEvent } from './prices-tf-api';
import log from '../../logger';
export default class PricesTfPricer implements IPricer {
private socketManager: PricesTfSocketManager;
private attempts = 0;
public constructor(private api: PricesTfApi) {
this.socketManager = new PricesTfSocketManager(api);
}
getOptions(): PricerOptions {
return this.api.getOptions();
}
async getPrice(sku: string): Promise<GetItemPriceResponse> {
const response = await this.api.getPrice(sku);
return this.parsePrices2Item(response);
}
async getPricelist(): Promise<GetPricelistResponse> {
if (JSON.parse(process.env.DEV) === true) {
try {
const pricelist = await PricesTfApi.apiRequest(
'GET',
'/json/pricelist-array',
undefined,
undefined,
undefined,
'https://autobot.tf'
);
return pricelist;
} catch (err) {
log.error('Failed to get pricelist from autobot.tf: ', err);
}
}
let prices: PricesTfItem[] = [];
let currentPage = 1;
let totalPages = 0;
let delay = 0;
const minDelay = 100;
let response: PricesTfGetPricesResponse;
log.debug('Requesting pricelist pages...');
do {
await new Promise(resolve => setTimeout(resolve, delay));
const start = new Date().getTime();
try {
log.debug(`Getting page ${currentPage}${totalPages === 0 ? '' : ` of ${totalPages}`}...`);
response = await this.api.getPricelistPage(currentPage);
currentPage++;
totalPages = response.meta.totalPages;
} catch (e) {
if (currentPage > 1) {
await new Promise(resolve => setTimeout(resolve, 60 * 1000));
continue;
} else {
if (this.attempts < 3) {
this.attempts++;
return this.getPricelist();
}
this.attempts = 0;
throw e;
}
}
prices = prices.concat(response.items);
const time = new Date().getTime() - start;
delay = Math.max(0, minDelay - time);
} while (currentPage < totalPages);
const parsed: Item[] = prices.map(v => this.parseItem(this.parsePrices2Item(v)));
return { items: parsed };
}
async requestCheck(sku: string): Promise<RequestCheckResponse> {
const r = await this.api.requestCheck(sku);
if (r.enqueued) {
return {
sku: sku
};
} else {
return {
sku: null
};
}
}
shutdown(): void {
this.socketManager.shutDown();
}
isPricerConnecting(): boolean {
return this.socketManager.isConnecting();
}
connect(): void {
this.socketManager.connect();
}
init(): void {
return this.socketManager.init();
}
parsePricesTfMessageEvent(raw: string): PricesTfItemMessageEvent {
return JSON.parse(raw) as PricesTfItemMessageEvent;
}
parsePrices2Item(item: PricesTfItem): GetItemPriceResponse {
return {
sku: item.sku,
buy: new Currencies({
keys: item.buyKeys,
metal: Currencies.toRefined(item.buyHalfScrap / 2)
}),
sell: new Currencies({
keys: item.sellKeys,
metal: Currencies.toRefined(item.sellHalfScrap / 2)
}),
source: 'bptf',
time: Math.floor(new Date(item.updatedAt).getTime() / 1000)
};
}
parseItem(r: GetItemPriceResponse): Item {
return {
buy: r.buy,
sell: r.sell,
sku: r.sku,
source: r.source,
time: r.time
};
}
parsePriceUpdatedData(e: PricesTfItemMessageEvent): Item {
return this.parseItem(this.parsePrices2Item(e.data));
}
bindHandlePriceEvent(onPriceChange: (item: GetItemPriceResponse) => void): void {
this.socketManager.on('message', (message: MessageEvent) => {
try {
const data = this.parsePricesTfMessageEvent(message.data as string);
if (data.type === 'AUTH_REQUIRED') {
// might be nicer to put this elsewhere
void this.api.setupToken().then(() => {
this.socketManager.send(
JSON.stringify({
type: 'AUTH',
data: {
accessToken: this.api.token
}
})
);
});
} else if (data.type === 'PRICE_UPDATED') {
const item = this.parsePriceUpdatedData(data);
onPriceChange(item);
}
} catch (e) {
log.error(e as Error);
}
});
}
}