summaryrefslogtreecommitdiffstats
path: root/vendor/github.com/Philipp15b/go-steam/tradeoffer/client.go
blob: 7bf171c3a868c0953dbf914d991f831303c6ef91 (plain) (blame)
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
package tradeoffer

import (
	"encoding/json"
	"fmt"
	"github.com/Philipp15b/go-steam/community"
	"github.com/Philipp15b/go-steam/economy/inventory"
	"github.com/Philipp15b/go-steam/netutil"
	"github.com/Philipp15b/go-steam/steamid"
	"io/ioutil"
	"net/http"
	"strconv"
	"time"
)

type APIKey string

const apiUrl = "https://api.steampowered.com/IEconService/%s/v%d"

type Client struct {
	client    *http.Client
	key       APIKey
	sessionId string
}

func NewClient(key APIKey, sessionId, steamLogin, steamLoginSecure string) *Client {
	c := &Client{
		new(http.Client),
		key,
		sessionId,
	}
	community.SetCookies(c.client, sessionId, steamLogin, steamLoginSecure)
	return c
}

func (c *Client) GetOffer(offerId uint64) (*TradeOfferResult, error) {
	resp, err := c.client.Get(fmt.Sprintf(apiUrl, "GetTradeOffer", 1) + "?" + netutil.ToUrlValues(map[string]string{
		"key":          string(c.key),
		"tradeofferid": strconv.FormatUint(offerId, 10),
		"language":     "en_us",
	}).Encode())
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	t := new(struct {
		Response *TradeOfferResult
	})
	if err = json.NewDecoder(resp.Body).Decode(t); err != nil {
		return nil, err
	}
	if t.Response == nil || t.Response.Offer == nil {
		return nil, newSteamErrorf("steam returned empty offer result\n")
	}

	return t.Response, nil
}

func (c *Client) GetOffers(getSent bool, getReceived bool, getDescriptions bool, activeOnly bool, historicalOnly bool, timeHistoricalCutoff *uint32) (*TradeOffersResult, error) {
	if !getSent && !getReceived {
		return nil, fmt.Errorf("getSent and getReceived can't be both false\n")
	}

	params := map[string]string{
		"key": string(c.key),
	}
	if getSent {
		params["get_sent_offers"] = "1"
	}
	if getReceived {
		params["get_received_offers"] = "1"
	}
	if getDescriptions {
		params["get_descriptions"] = "1"
		params["language"] = "en_us"
	}
	if activeOnly {
		params["active_only"] = "1"
	}
	if historicalOnly {
		params["historical_only"] = "1"
	}
	if timeHistoricalCutoff != nil {
		params["time_historical_cutoff"] = strconv.FormatUint(uint64(*timeHistoricalCutoff), 10)
	}
	resp, err := c.client.Get(fmt.Sprintf(apiUrl, "GetTradeOffers", 1) + "?" + netutil.ToUrlValues(params).Encode())
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	t := new(struct {
		Response *TradeOffersResult
	})
	if err = json.NewDecoder(resp.Body).Decode(t); err != nil {
		return nil, err
	}
	if t.Response == nil {
		return nil, newSteamErrorf("steam returned empty offers result\n")
	}
	return t.Response, nil
}

// action() is used by Decline() and Cancel()
// Steam only return success and error fields for malformed requests,
// hence client shall use GetOffer() to check action result
// It is also possible to implement Decline/Cancel using steamcommunity,
// which have more predictable responses
func (c *Client) action(method string, version uint, offerId uint64) error {
	resp, err := c.client.Do(netutil.NewPostForm(fmt.Sprintf(apiUrl, method, version), netutil.ToUrlValues(map[string]string{
		"key":          string(c.key),
		"tradeofferid": strconv.FormatUint(offerId, 10),
	})))
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode != 200 {
		return fmt.Errorf(method+" error: status code %d", resp.StatusCode)
	}
	return nil
}

func (c *Client) Decline(offerId uint64) error {
	return c.action("DeclineTradeOffer", 1, offerId)
}

func (c *Client) Cancel(offerId uint64) error {
	return c.action("CancelTradeOffer", 1, offerId)
}

// Accept received trade offer
// It is best to confirm that offer was actually accepted
// by calling GetOffer after Accept and checking offer state
func (c *Client) Accept(offerId uint64) error {
	baseurl := fmt.Sprintf("https://steamcommunity.com/tradeoffer/%d/", offerId)
	req := netutil.NewPostForm(baseurl+"accept", netutil.ToUrlValues(map[string]string{
		"sessionid":    c.sessionId,
		"serverid":     "1",
		"tradeofferid": strconv.FormatUint(offerId, 10),
	}))
	req.Header.Add("Referer", baseurl)

	resp, err := c.client.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	t := new(struct {
		StrError string `json:"strError"`
	})
	if err = json.NewDecoder(resp.Body).Decode(t); err != nil {
		return err
	}
	if t.StrError != "" {
		return newSteamErrorf("accept error: %v\n", t.StrError)
	}
	if resp.StatusCode != 200 {
		return fmt.Errorf("accept error: status code %d", resp.StatusCode)
	}
	return nil
}

type TradeItem struct {
	AppId      uint32 `json:"appid"`
	ContextId  uint64 `json:"contextid,string"`
	Amount     uint64 `json:"amount"`
	AssetId    uint64 `json:"assetid,string,omitempty"`
	CurrencyId uint64 `json:"currencyid,string,omitempty"`
}

// Sends a new trade offer to the given Steam user. You can optionally specify an access token if you've got one.
// In addition, `counteredOfferId` can be non-nil, indicating the trade offer this is a counter for.
// On success returns trade offer id
func (c *Client) Create(other steamid.SteamId, accessToken *string, myItems, theirItems []TradeItem, counteredOfferId *uint64, message string) (uint64, error) {
	// Create new trade offer status
	to := map[string]interface{}{
		"newversion": true,
		"version":    3,
		"me": map[string]interface{}{
			"assets":   myItems,
			"currency": make([]struct{}, 0),
			"ready":    false,
		},
		"them": map[string]interface{}{
			"assets":   theirItems,
			"currency": make([]struct{}, 0),
			"ready":    false,
		},
	}

	jto, err := json.Marshal(to)
	if err != nil {
		panic(err)
	}

	// Create url parameters for request
	data := map[string]string{
		"sessionid":         c.sessionId,
		"serverid":          "1",
		"partner":           other.ToString(),
		"tradeoffermessage": message,
		"json_tradeoffer":   string(jto),
	}

	var referer string
	if counteredOfferId != nil {
		referer = fmt.Sprintf("https://steamcommunity.com/tradeoffer/%d/", *counteredOfferId)
		data["tradeofferid_countered"] = strconv.FormatUint(*counteredOfferId, 10)
	} else {
		// Add token for non-friend offers
		if accessToken != nil {
			params := map[string]string{
				"trade_offer_access_token": *accessToken,
			}
			paramsJson, err := json.Marshal(params)
			if err != nil {
				panic(err)
			}

			data["trade_offer_create_params"] = string(paramsJson)

			referer = "https://steamcommunity.com/tradeoffer/new/?partner=" + strconv.FormatUint(uint64(other.GetAccountId()), 10) + "&token=" + *accessToken
		} else {

			referer = "https://steamcommunity.com/tradeoffer/new/?partner=" + strconv.FormatUint(uint64(other.GetAccountId()), 10)
		}
	}

	// Create request
	req := netutil.NewPostForm("https://steamcommunity.com/tradeoffer/new/send", netutil.ToUrlValues(data))
	req.Header.Add("Referer", referer)

	// Send request
	resp, err := c.client.Do(req)
	if err != nil {
		return 0, err
	}
	defer resp.Body.Close()
	t := new(struct {
		StrError     string `json:"strError"`
		TradeOfferId uint64 `json:"tradeofferid,string"`
	})
	if err = json.NewDecoder(resp.Body).Decode(t); err != nil {
		return 0, err
	}
	// strError code descriptions:
	// 15	invalide trade access token
	// 16	timeout
	// 20	wrong contextid
	// 25	can't send more offers until some is accepted/cancelled...
	// 26	object is not in our inventory
	// error code names are in internal/steamlang/enums.go EResult_name
	if t.StrError != "" {
		return 0, newSteamErrorf("create error: %v\n", t.StrError)
	}
	if resp.StatusCode != 200 {
		return 0, fmt.Errorf("create error: status code %d", resp.StatusCode)
	}
	if t.TradeOfferId == 0 {
		return 0, newSteamErrorf("create error: steam returned 0 for trade offer id")
	}
	return t.TradeOfferId, nil
}

func (c *Client) GetOwnInventory(contextId uint64, appId uint32) (*inventory.Inventory, error) {
	return inventory.GetOwnInventory(c.client, contextId, appId)
}

func (c *Client) GetPartnerInventory(other steamid.SteamId, contextId uint64, appId uint32, offerId *uint64) (*inventory.Inventory, error) {
	return inventory.GetFullInventory(func() (*inventory.PartialInventory, error) {
		return c.getPartialPartnerInventory(other, contextId, appId, offerId, nil)
	}, func(start uint) (*inventory.PartialInventory, error) {
		return c.getPartialPartnerInventory(other, contextId, appId, offerId, &start)
	})
}

func (c *Client) getPartialPartnerInventory(other steamid.SteamId, contextId uint64, appId uint32, offerId *uint64, start *uint) (*inventory.PartialInventory, error) {
	data := map[string]string{
		"sessionid": c.sessionId,
		"partner":   other.ToString(),
		"contextid": strconv.FormatUint(contextId, 10),
		"appid":     strconv.FormatUint(uint64(appId), 10),
	}
	if start != nil {
		data["start"] = strconv.FormatUint(uint64(*start), 10)
	}

	baseUrl := "https://steamcommunity.com/tradeoffer/%v/"
	if offerId != nil {
		baseUrl = fmt.Sprintf(baseUrl, *offerId)
	} else {
		baseUrl = fmt.Sprintf(baseUrl, "new")
	}

	req, err := http.NewRequest("GET", baseUrl+"partnerinventory/?"+netutil.ToUrlValues(data).Encode(), nil)
	if err != nil {
		panic(err)
	}
	req.Header.Add("Referer", baseUrl+"?partner="+strconv.FormatUint(uint64(other.GetAccountId()), 10))

	return inventory.DoInventoryRequest(c.client, req)
}

// Can be used to verify accepted tradeoffer and find out received asset ids
func (c *Client) GetTradeReceipt(tradeId uint64) ([]*TradeReceiptItem, error) {
	url := fmt.Sprintf("https://steamcommunity.com/trade/%d/receipt", tradeId)
	resp, err := c.client.Get(url)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	items, err := parseTradeReceipt(respBody)
	if err != nil {
		return nil, newSteamErrorf("failed to parse trade receipt: %v", err)
	}
	return items, nil
}

// Get duration of escrow in days. Call this before sending a trade offer
func (c *Client) GetPartnerEscrowDuration(other steamid.SteamId, accessToken *string) (*EscrowDuration, error) {
	data := map[string]string{
		"partner": strconv.FormatUint(uint64(other.GetAccountId()), 10),
	}
	if accessToken != nil {
		data["token"] = *accessToken
	}
	return c.getEscrowDuration("https://steamcommunity.com/tradeoffer/new/?" + netutil.ToUrlValues(data).Encode())
}

// Get duration of escrow in days. Call this after receiving a trade offer
func (c *Client) GetOfferEscrowDuration(offerId uint64) (*EscrowDuration, error) {
	return c.getEscrowDuration("http://steamcommunity.com/tradeoffer/" + strconv.FormatUint(offerId, 10))
}

func (c *Client) getEscrowDuration(queryUrl string) (*EscrowDuration, error) {
	resp, err := c.client.Get(queryUrl)
	if err != nil {
		return nil, fmt.Errorf("failed to retrieve escrow duration: %v", err)
	}
	defer resp.Body.Close()
	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	escrowDuration, err := parseEscrowDuration(respBody)
	if err != nil {
		return nil, newSteamErrorf("failed to parse escrow duration: %v", err)
	}
	return escrowDuration, nil
}

func (c *Client) GetOfferWithRetry(offerId uint64, retryCount int, retryDelay time.Duration) (*TradeOfferResult, error) {
	var res *TradeOfferResult
	return res, withRetry(
		func() (err error) {
			res, err = c.GetOffer(offerId)
			return err
		}, retryCount, retryDelay)
}

func (c *Client) GetOffersWithRetry(getSent bool, getReceived bool, getDescriptions bool, activeOnly bool, historicalOnly bool, timeHistoricalCutoff *uint32, retryCount int, retryDelay time.Duration) (*TradeOffersResult, error) {
	var res *TradeOffersResult
	return res, withRetry(
		func() (err error) {
			res, err = c.GetOffers(getSent, getReceived, getDescriptions, activeOnly, historicalOnly, timeHistoricalCutoff)
			return err
		}, retryCount, retryDelay)
}

func (c *Client) DeclineWithRetry(offerId uint64, retryCount int, retryDelay time.Duration) error {
	return withRetry(
		func() error {
			return c.Decline(offerId)
		}, retryCount, retryDelay)
}

func (c *Client) CancelWithRetry(offerId uint64, retryCount int, retryDelay time.Duration) error {
	return withRetry(
		func() error {
			return c.Cancel(offerId)
		}, retryCount, retryDelay)
}

func (c *Client) AcceptWithRetry(offerId uint64, retryCount int, retryDelay time.Duration) error {
	return withRetry(
		func() error {
			return c.Accept(offerId)
		}, retryCount, retryDelay)
}

func (c *Client) CreateWithRetry(other steamid.SteamId, accessToken *string, myItems, theirItems []TradeItem, counteredOfferId *uint64, message string, retryCount int, retryDelay time.Duration) (uint64, error) {
	var res uint64
	return res, withRetry(
		func() (err error) {
			res, err = c.Create(other, accessToken, myItems, theirItems, counteredOfferId, message)
			return err
		}, retryCount, retryDelay)
}

func (c *Client) GetOwnInventoryWithRetry(contextId uint64, appId uint32, retryCount int, retryDelay time.Duration) (*inventory.Inventory, error) {
	var res *inventory.Inventory
	return res, withRetry(
		func() (err error) {
			res, err = c.GetOwnInventory(contextId, appId)
			return err
		}, retryCount, retryDelay)
}

func (c *Client) GetPartnerInventoryWithRetry(other steamid.SteamId, contextId uint64, appId uint32, offerId *uint64, retryCount int, retryDelay time.Duration) (*inventory.Inventory, error) {
	var res *inventory.Inventory
	return res, withRetry(
		func() (err error) {
			res, err = c.GetPartnerInventory(other, contextId, appId, offerId)
			return err
		}, retryCount, retryDelay)
}

func (c *Client) GetTradeReceiptWithRetry(tradeId uint64, retryCount int, retryDelay time.Duration) ([]*TradeReceiptItem, error) {
	var res []*TradeReceiptItem
	return res, withRetry(
		func() (err error) {
			res, err = c.GetTradeReceipt(tradeId)
			return err
		}, retryCount, retryDelay)
}

func withRetry(f func() error, retryCount int, retryDelay time.Duration) error {
	if retryCount <= 0 {
		panic("retry count must be more than 0")
	}
	i := 0
	for {
		i++
		if err := f(); err != nil {
			// If we got steam error do not retry
			if _, ok := err.(*SteamError); ok {
				return err
			}
			if i == retryCount {
				return err
			}
			time.Sleep(retryDelay)
			continue
		}
		break
	}
	return nil
}