-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEvolutionScraper.cs
More file actions
318 lines (263 loc) · 12.1 KB
/
Copy pathEvolutionScraper.cs
File metadata and controls
318 lines (263 loc) · 12.1 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
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
using Microsoft.Extensions.Logging;
using PuppeteerSharp;
using PuppeteerSharp.Input;
using System.Diagnostics;
using System.Text.Json;
namespace EvolutionScraper
{
public record EvolutionScraperOptions(string ChromePath, string Username, string Password)
{
public EvolutionScraperOptions() : this(string.Empty, string.Empty, string.Empty)
{
}
}
public class EvolutionScraper(EvolutionScraperOptions options, ILogger logger) : IDisposable, IAsyncDisposable
{
private readonly EvolutionScraperOptions _options = options;
private readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web);
private IBrowser? _browser = null!;
protected IPage? _page = null!;
protected virtual async Task RunBrowserAsync()
{
// Download and initialize browser
LaunchOptions launchOptions = new()
{
Headless = true,
Args = [
"--disable-blink-features=AutomationControlled",
"--disable-dev-shm-usage",
"--no-sandbox",
"--disable-setuid-sandbox",
"--disable-infobars",
"--window-size=1920,1080",
"--start-maximized",
"--disable-extensions",
],
IgnoredDefaultArgs = ["--enable-automation"],
ExecutablePath = _options.ChromePath
};
_browser = await Puppeteer.LaunchAsync(launchOptions).ConfigureAwait(false);
_page = await _browser.NewPageAsync().ConfigureAwait(false);
_jsonOptions.Converters.Add(new DateTimeConverter());
await _page.SetViewportAsync(new ViewPortOptions { Width = 1920, Height = 1080 }).ConfigureAwait(false);
await _page.EvaluateExpressionOnNewDocumentAsync(@"
Object.defineProperty(navigator, 'webdriver', { get: () => undefined });
Object.defineProperty(navigator, 'plugins', { get: () => [1, 2, 3, 4, 5] });
Object.defineProperty(navigator, 'languages', { get: () => ['en-US', 'en'] });
window.chrome = { runtime: {} };
Object.defineProperty(navigator, 'permissions', {
query: (parameters) => (
parameters.name === 'notifications'
? Promise.resolve({ state: Notification.permission })
: navigator.permissions.query(parameters)
)
});
").ConfigureAwait(false);
// Set a realistic user agent
await _page.SetUserAgentAsync("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36").ConfigureAwait(false);
await _page.SetExtraHttpHeadersAsync(new Dictionary<string, string>
{
["accept-language"] = "en-US,en;q=0.9",
["accept"] = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
["sec-ch-ua"] = "\"Not:A-Brand\";v=\"99\", \"Google Chrome\";v=\"145\", \"Chromium\";v=\"145\"",
["sec-ch-ua-mobile"] = "?0",
["sec-ch-ua-platform"] = "\"Windows\"",
["upgrade-insecure-requests"] = "1"
})
.ConfigureAwait(false);
}
protected virtual async Task LoginAsync()
{
if (_page is null)
{
throw new InvalidOperationException("Browser is not initialized");
}
string currentUrlDate = Extensions.GetURLDate();
// Navigate to login page
await _page.GoToAsync($"https://clients.mindbodyonline.com/ASP/su1.asp?studioid=531524&tg=&vt=&lvl=&stype=&view=&trn=0&page=&catid=&prodid=&date={currentUrlDate}&classid=0&prodGroupId=&sSU=&optForwardingLink=&qParam=&justloggedin=&nLgIn=&pMode=0&loc=1",
new NavigationOptions { WaitUntil = [WaitUntilNavigation.DOMContentLoaded] })
.ConfigureAwait(false);
// Wait for login form to load
await _page.WaitForSelectorAsync("#su1UserName").ConfigureAwait(false);
await _page.WaitForSelectorAsync("#su1Password").ConfigureAwait(false);
// Fill credentials
await _page.TypeAsync("#su1UserName", _options.Username, new TypeOptions { Delay = 100 }).ConfigureAwait(false);
await _page.TypeAsync("#su1Password", _options.Password, new TypeOptions { Delay = 100 }).ConfigureAwait(false);
// Submit form and wait for navigation
await _page.ClickAsync("#btnSu1Login", new ClickOptions { Delay = 100 }).ConfigureAwait(false);
await _page.WaitAsync().ConfigureAwait(false);
await VerifySuccessulLoginAsync().ConfigureAwait(false);
}
private async Task VerifySuccessulLoginAsync()
{
if (_page is null)
{
throw new InvalidOperationException("Browser is not initialized");
}
// Verify successful login
bool isLoggedIn = await _page.EvaluateExpressionAsync<bool>(
"document.querySelector('#myInfoContainer') !== null")
.ConfigureAwait(false);
if (!isLoggedIn)
{
await ThrowLoggingPageAsync(new InvalidOperationException("Unable to login")).ConfigureAwait(false);
}
}
protected virtual async Task FindClassesPageAsync(bool shouldGoToNextWeek)
{
if (_page is null)
{
throw new InvalidOperationException("Browser is not initialized");
}
if (!shouldGoToNextWeek)
{
await WaitUntilDueTimeAsync(9, 5, 120).ConfigureAwait(false);
}
await _page.ClickAsync(".tab-c-firstTab > a").ConfigureAwait(false);
await _page.WaitAsync().ConfigureAwait(false);
if (shouldGoToNextWeek)
{
await WaitUntilDueTimeAsync(9, 5, 120).ConfigureAwait(false);
await _page.ClickAsync("#week-arrow-r").ConfigureAwait(false);
await _page.WaitAsync().ConfigureAwait(false);
}
}
private async ValueTask WaitUntilDueTimeAsync(short hour, short maxMinutesToWait, short secondsToWaitAfterDueTime)
{
if (Debugger.IsAttached || DateTime.Now.Hour >= hour)
{
return;
}
if (DateTime.Now.Hour != hour - 1
|| (60 - DateTime.Now.Minute > maxMinutesToWait))
{
throw new NotSupportedException($"Current time is past or too far from the due hour ({DateTime.Now})");
}
while (DateTime.Now.Hour != hour)
{
logger.LogInformation($"Waiting for the right time ({DateTime.Now})");
await Task.Delay(1000).ConfigureAwait(false);
}
logger.LogInformation($"Waiting extra {secondsToWaitAfterDueTime} seconds after due time");
await Task.Delay(secondsToWaitAfterDueTime * 1000).ConfigureAwait(false);
}
protected virtual async Task<ClassScheduleItem[]> ScrapeClassSchedulesAsync()
{
if (_page is null)
{
throw new InvalidOperationException("Browser is not initialized");
}
string script = File.ReadAllText("class_selector.js");
JsonDocument o = await _page.EvaluateFunctionAsync<JsonDocument>(script).ConfigureAwait(false);
List<ClassScheduleItem> items = JsonSerializer.Deserialize<List<ClassScheduleItem>>(o.RootElement.GetRawText(), _jsonOptions) ?? [];
return items.ToArray();
}
public async Task<bool> BookClassAsync(string className, DayOfWeek day, TimeOnly time)
{
if (_page is null)
{
await RunBrowserAsync().ConfigureAwait(false);
if (_page is null)
{
throw new InvalidOperationException("Browser is not initialized");
}
try
{
await LoginAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
await ThrowLoggingPageAsync(ex).ConfigureAwait(false);
}
}
else
{
await GoToMainPageAsync().ConfigureAwait(false);
}
bool shouldGoToNextWeek = BookingHelper.IsBookingDayNextWeek(day, DateTime.Today);
await FindClassesPageAsync(shouldGoToNextWeek).ConfigureAwait(false);
ClassScheduleItem[] items = await ScrapeClassSchedulesAsync().ConfigureAwait(false);
ClassScheduleItem? classToBook =
items
.FirstOrDefault(x => x.ClassName.Equals(className, StringComparison.OrdinalIgnoreCase)
&& x.Date == Extensions.GetNextDateTime(day, time));
if (classToBook is null)
{
logger.LogDebug("All classes scraped:");
foreach (ClassScheduleItem item in items)
{
logger.LogDebug(JsonSerializer.Serialize(item, _jsonOptions));
}
await ThrowLoggingPageAsync(new InvalidOperationException("Unable to find any class to book")).ConfigureAwait(false);
return false;
}
await _page.ClickAsync($"input[name=\"{classToBook.Button}\"]").ConfigureAwait(false);
await _page.WaitAsync().ConfigureAwait(false);
await _page.ClickAsync($"#SubmitEnroll2").ConfigureAwait(false);
await _page.WaitAsync().ConfigureAwait(false);
bool isBooked = await _page.EvaluateExpressionAsync<bool>(
"document.querySelector('#notifyBooking') !== null")
.ConfigureAwait(false);
return isBooked;
}
protected virtual async Task GoToMainPageAsync()
{
if (_page is null)
{
throw new InvalidOperationException("Browser is not initialized");
}
string currentUrlDate = Extensions.GetURLDate();
await _page.GoToAsync($"https://clients.mindbodyonline.com/ASP/main_info.asp?studioid=531524&tg=&vt=&lvl=&stype=&view=&trn=0&page=&catid=&prodid=&date={currentUrlDate}&classid=0&prodGroupId=&sSU=&optForwardingLink=&qParam=&justloggedin=&nLgIn=&pMode=0&loc=1",
new NavigationOptions { WaitUntil = [WaitUntilNavigation.DOMContentLoaded] }).ConfigureAwait(false);
await VerifySuccessulLoginAsync().ConfigureAwait(false);
}
private async Task ThrowLoggingPageAsync(Exception ex)
{
if (_page is null)
{
throw ex;
}
string content = await _page.GetContentAsync().ConfigureAwait(false);
await File.WriteAllTextAsync($"page_dump_{DateTime.Now:yyyyMMddHHmmss}.html", content).ConfigureAwait(false);
throw ex;
}
public void Dispose()
{
if (_page is not null)
{
if (!_page.IsClosed)
{
_page.CloseAsync().ConfigureAwait(false).GetAwaiter().GetResult();
}
_page.Dispose();
}
if (_browser is not null)
{
if (!_browser.IsClosed)
{
_browser.CloseAsync().ConfigureAwait(false).GetAwaiter().GetResult();
}
_browser.Dispose();
}
}
public async ValueTask DisposeAsync()
{
if (_page is not null)
{
if (!_page.IsClosed)
{
await _page.CloseAsync().ConfigureAwait(false);
}
await _page.DisposeAsync().ConfigureAwait(false);
}
if (_browser is not null)
{
if (!_browser.IsClosed)
{
await _browser.CloseAsync().ConfigureAwait(false);
}
await _browser.DisposeAsync().ConfigureAwait(false);
}
}
}
}