-
Notifications
You must be signed in to change notification settings - Fork 2
/
web-client.ts
149 lines (133 loc) · 5.05 KB
/
web-client.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
import cheerio from 'cheerio';
import { RequestAPI, RequiredUriUrl, Response } from 'request';
import { RequestPromise, RequestPromiseOptions } from 'request-promise-native';
import { ParseError } from './parse-error';
const resources = {
loginForm: '/home',
submitLoginForm: '/sessions',
codeForm: '/code_redemptions/new',
checkCode: '/entitlement_offer_codes', // ?code=<code>
submitCodeForm: '/code_redemptions'
};
Object.freeze(resources);
/**
* WebClient is responsible for interacting with the SHiFT website.
*/
export class WebClient {
/**
* @param http an object that can GET and POST data over HTTP.
* @param baseUrl the SHiFT website location without any path segments, i.e. 'https://shift.gearboxsoftware.com'.
*/
constructor(
private http: RequestAPI<RequestPromise, RequestPromiseOptions, RequiredUriUrl>,
private baseUrl: string
) {
}
/**
* Gets a page and returns its CSRF token (A.K.A. authenticity token).
* @param url the location of the page.
*/
async getToken(url: string): Promise<string> {
console.log('GET', url);
let $: CheerioStatic = await this.http
.get({
uri: url,
transform: body => cheerio.load(body)
});
return $('meta[name=csrf-token]').attr('content');
}
/**
* Submits a login form and returns the entire response.
* @param email a valid SHiFT account name
* @param password a valid password
*/
async login(email: string, password: string) {
let token = await this.getToken(this.baseUrl + resources.loginForm);
console.log('POST', this.baseUrl + resources.submitLoginForm);
return this.http.post({
uri: this.baseUrl + resources.submitLoginForm,
formData: {
'authenticity_token': token,
'user[email]': email,
'user[password]': password
}
});
}
async getRedemptionForm(code: string): Promise<any> {
let token = await this.getToken(this.baseUrl + resources.codeForm);
console.log('GET', `${this.baseUrl}${resources.checkCode}?code=${code}`);
let $: CheerioStatic = await this.http.get({
uri: `${this.baseUrl}${resources.checkCode}?code=${code}`,
headers: {
'x-csrf-token': token,
'x-requested-with': 'XMLHttpRequest'
},
transform: body => cheerio.load(body)
});
if ($('form.new_archway_code_redemption').length === 0) {
return Promise.reject($.root().text().trim());
} else {
return {
'authenticity_token': $('input[name=authenticity_token]').val(),
'archway_code_redemption[code]': $('#archway_code_redemption_code').val(),
'archway_code_redemption[check]': $('#archway_code_redemption_check').val(),
'archway_code_redemption[service]': $('#archway_code_redemption_service').val()
};
}
}
async redeem(formData: any): Promise<string | null> {
console.log('POST', this.baseUrl + resources.submitCodeForm);
let response = await this.http.post({
uri: this.baseUrl + resources.submitCodeForm,
formData,
resolveWithFullResponse: true,
followRedirect: false
});
let redirectLocation = await this.checkRedemptionStatus(response);
console.log('GET', this.baseUrl + redirectLocation);
let body = await this.http.get({
uri: this.baseUrl + redirectLocation
});
return this.getAlert(body);
}
private async checkRedemptionStatus(response: Response): Promise<string> {
if (response.statusCode === 302) {
return Promise.resolve(response.headers.location!);
}
const alert = this.getAlert(response.body);
if (alert != null) {
return Promise.reject(alert);
}
const { status, url } = this.getStatus(response.body);
console.log(status);
await this.wait(500);
let nextResponse = await this.http.get({
uri: this.baseUrl + url,
resolveWithFullResponse: true,
followRedirect: false
});
// retry recursively
return this.checkRedemptionStatus(nextResponse);
}
private wait(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
private getAlert(body: any): string | null {
const $ = cheerio.load(body);
if ($('div.notice').length === 0) {
return null;
}
return $('div.notice').text().trim();
}
private getStatus(body: any): { status: string; url: string } {
const $ = cheerio.load(body);
const div = $('div#check_redemption_status');
if (div.length === 0) {
throw new ParseError('Could not find div#check_redemption_status.');
}
return {
status: div.text().trim(),
url: div.data('url')
};
}
}