-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathtrade_history.ts
More file actions
178 lines (155 loc) · 6.27 KB
/
Copy pathtrade_history.ts
File metadata and controls
178 lines (155 loc) · 6.27 KB
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
import {SlimTrade} from '../types/float_market';
import {TradeHistoryStatus, TradeHistoryType} from '../bridge/handlers/trade_history_status';
import {AppId, TradeOfferState, TradeStatus} from '../types/steam_constants';
import {clearAccessTokenFromStorage, getAccessToken} from './access_token';
export async function pingTradeHistory(
pendingTrades: SlimTrade[],
steamID?: string | null
): Promise<TradeHistoryStatus[]> {
const {history, type} = await getTradeHistory();
// premature optimization in case it's 100 trades
const assetsToFind = pendingTrades.reduce(
(acc, e) => {
acc[e.contract.item.asset_id] = e;
return acc;
},
{} as {[key: string]: SlimTrade}
);
// We only want to send history that is relevant to verifying trades on CSFloat
const historyForCSFloat = history.filter((e) => {
const received_ids = e.received_assets.map((e) => e.asset_id);
const given_ids = e.given_assets.map((e) => e.asset_id);
const foundSlimTrades = [...received_ids, ...given_ids].map((e) => assetsToFind[e]).filter((e) => !!e);
if (!foundSlimTrades || foundSlimTrades.length === 0) {
return false;
}
// Have we already reported this status as a seller? If so, we can skip doing it again
if (
foundSlimTrades.every((t) => t.steam_offer?.state === TradeOfferState.Accepted && t.seller_id === steamID)
) {
return false;
}
return true;
});
if (historyForCSFloat.length === 0) {
return history;
}
await TradeHistoryStatus.handleRequest({history: historyForCSFloat, type}, {});
return history;
}
async function getTradeHistory(): Promise<{history: TradeHistoryStatus[]; type: TradeHistoryType}> {
try {
const history = await getTradeHistoryFromAPI(250);
if (history.length > 0) {
// Hedge in case this endpoint gets killed, only return if there are results, fallback to HTML parser
return {history, type: TradeHistoryType.API};
} else {
throw new Error('failed to get trade history');
}
} catch (e) {
await clearAccessTokenFromStorage();
// Fallback to HTML parsing
const history = await getTradeHistoryFromHTML();
return {history, type: TradeHistoryType.HTML};
}
}
interface HistoryAsset {
assetid: string;
appid: AppId;
new_assetid: string;
}
interface TradeHistoryAPIResponse {
response: {
trades: {
tradeid: string;
steamid_other: string;
status: number;
assets_given?: HistoryAsset[];
assets_received?: HistoryAsset[];
time_escrow_end?: string;
time_settlement?: number;
rollback_trade?: string;
}[];
};
}
export async function getTradeHistoryFromAPI(maxTrades: number): Promise<TradeHistoryStatus[]> {
const access = await getAccessToken();
// This only works if they have granted permission for https://api.steampowered.com
const resp = await fetch(
`https://api.steampowered.com/IEconService/GetTradeHistory/v1/?access_token=${access.token}&max_trades=${maxTrades}`,
{
credentials: 'include',
}
);
if (resp.status !== 200) {
throw new Error('invalid status');
}
const data = (await resp.json()) as TradeHistoryAPIResponse;
return (data.response?.trades || [])
.filter((e) => e.status === TradeStatus.Complete || e.status === TradeStatus.TradeProtectionRollback) // Ensure we only count _complete_ trades (k_ETradeStatus_Complete) or rolled back (for reporting)
.filter((e) => !e.time_escrow_end || new Date(parseInt(e.time_escrow_end) * 1000).getTime() < Date.now())
.map((e) => {
return {
other_party_url: `https://steamcommunity.com/profiles/${e.steamid_other}`,
received_assets: (e.assets_received || [])
.filter((e) => e.appid === AppId.CSGO)
.map((e) => {
return {asset_id: e.assetid, new_asset_id: e.new_assetid};
}),
given_assets: (e.assets_given || [])
.filter((e) => e.appid === AppId.CSGO)
.map((e) => {
return {asset_id: e.assetid, new_asset_id: e.new_assetid};
}),
trade_id: e.tradeid,
time_settlement: e.time_settlement,
status: e.status,
rollback_trade: e.rollback_trade,
} as TradeHistoryStatus;
})
.filter((e) => {
// Remove non-CS related assets
return e.received_assets.length > 0 || e.given_assets.length > 0;
});
}
async function getTradeHistoryFromHTML(): Promise<TradeHistoryStatus[]> {
const resp = await fetch(`https://steamcommunity.com/id/me/tradehistory`, {
credentials: 'include',
// Expect redirect since we're using `me` above
redirect: 'follow',
});
const body = await resp.text();
if (body.includes('too many requests')) {
throw 'Too many requests';
}
return parseTradeHistoryHTML(body);
}
function parseTradeHistoryHTML(body: string): TradeHistoryStatus[] {
const links = body.matchAll(
/<div class="tradehistory_event_description">.+?<a href="https:\/\/steamcommunity\.com\/(.+?)">/gms
);
const statuses = [...links].map((e) => {
return {
other_party_url: `https://steamcommunity.com/${e[1]}`,
received_assets: [],
given_assets: [],
trade_id: '',
time_settlement: 0,
status: 0,
rollback_trade: '',
} as TradeHistoryStatus;
});
const matches = body.matchAll(
/HistoryPageCreateItemHover\( 'trade(\d+)_(received|given)item\d+', 730, '2', '(\d+)', '1' \);/g
);
for (const match of matches) {
const [text, index, type, assetId] = match;
const tradeIndex = parseInt(index);
if (type === 'received') {
statuses[tradeIndex].received_assets.push({asset_id: assetId});
} else if (type === 'given') {
statuses[tradeIndex].given_assets.push({asset_id: assetId});
}
}
return statuses;
}