Compare commits

..

10 Commits

9 changed files with 284 additions and 46 deletions
+3
View File
@@ -1,4 +1,7 @@
[Pp]assword.txt [Pp]assword.txt
CVV.txt
CardDetails.txt
run.bat
# ---> VisualStudioCode # ---> VisualStudioCode
.vscode/* .vscode/*
+9
View File
@@ -7,6 +7,13 @@
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<Compile Remove="Scheduler/**" />
<Content Remove="Scheduler/**" />
<EmbeddedResource Remove="Scheduler/**" />
<None Remove="Scheduler/**" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.Playwright" Version="1.59.0" /> <PackageReference Include="Microsoft.Playwright" Version="1.59.0" />
<PackageReference Include="Soenneker.Playwrights.Extensions.Stealth" Version="4.0.62" /> <PackageReference Include="Soenneker.Playwrights.Extensions.Stealth" Version="4.0.62" />
@@ -14,6 +21,8 @@
<ItemGroup> <ItemGroup>
<None Include="Password.txt" CopyToOutputDirectory="PreserveNewest" /> <None Include="Password.txt" CopyToOutputDirectory="PreserveNewest" />
<None Include="CardDetails.txt" CopyToOutputDirectory="PreserveNewest" />
<None Include="CVV.txt" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup> </ItemGroup>
</Project> </Project>
+64
View File
@@ -0,0 +1,64 @@
using System.Text.RegularExpressions;
using Microsoft.Playwright;
namespace BadmintonBooker;
public static class GoogleMessages
{
public static async Task<string?> GetEgovOTP(IBrowserContext context, IPage originalPage)
{
var msgPage = await context.NewPageAsync();
await msgPage.GotoAsync("https://messages.google.com/web/u/0/conversations/CgjwUsdGGwxxGhIBNw", new PageGotoOptions { WaitUntil = WaitUntilState.Load });
var messageElement = msgPage.Locator("mws-text-message-part").Last;
string messageText = await messageElement.InnerTextAsync();
await originalPage.BringToFrontAsync();
var match = Regex.Match(messageText, @"\b\d{5,}\b");
if (match.Success)
{
return match.Value;
}
else
{
Console.WriteLine("No OTP found in the message.");
return null;
}
}
public static async Task<string?> GetBMLOTP(IBrowserContext context, IPage originalPage)
{
var msgPage = await context.NewPageAsync();
await msgPage.GotoAsync("https://messages.google.com/web/u/0/conversations/Cgj4KNDeDzFopxIBMQ", new PageGotoOptions { WaitUntil = WaitUntilState.Load });
var messageElement = msgPage.Locator("mws-text-message-part").Last;
string messageText = await messageElement.InnerTextAsync();
await originalPage.BringToFrontAsync();
var match = Regex.Match(messageText, @"\b\d{6,}\b");
if (match.Success)
{
return match.Value;
}
else
{
Console.WriteLine("No OTP found in the message.");
return null;
}
}
public static async Task<string> GetMessageFromHDC(IBrowserContext context, IPage originalPage)
{
var msgPage = await context.NewPageAsync();
await msgPage.GotoAsync("https://messages.google.com/web/u/0/conversations/Cghm7Ql96iXyyhIBMg", new PageGotoOptions { WaitUntil = WaitUntilState.Load });
var messageElement = msgPage.Locator("mws-text-message-part").Last;
string messageText = await messageElement.InnerTextAsync();
await originalPage.BringToFrontAsync();
await msgPage.CloseAsync();
return messageText;
}
}
-29
View File
@@ -1,29 +0,0 @@
using System.Text.RegularExpressions;
using Microsoft.Playwright;
namespace BadmintonBooker;
public static class OTPExtractor
{
public static async Task<string?> GetEgovOTP(IBrowserContext context, IPage originalPage)
{
var msgPage = await context.NewPageAsync();
await msgPage.GotoAsync("https://messages.google.com/web/u/0/conversations/CgjwUsdGGwxxGhIBNw", new PageGotoOptions { WaitUntil = WaitUntilState.Load });
var messageElement = msgPage.Locator("mws-text-message-part").Last;
string messageText = await messageElement.InnerTextAsync();
await originalPage.BringToFrontAsync();
var match = Regex.Match(messageText, @"\b\d{5,}\b");
if (match.Success)
{
return match.Value;
}
else
{
Console.WriteLine("No OTP found in the message.");
return null;
}
}
}
+120 -17
View File
@@ -1,32 +1,135 @@
using BadmintonBooker; using System.Text.RegularExpressions;
using BadmintonBooker;
using Microsoft.Playwright; using Microsoft.Playwright;
var argsLength = args.Length;
if(argsLength < 1)
{
Console.WriteLine("Useage: BadmintonBooker <endtime (HH:mm)> <debug? (true/false)>");
return;
}
var endTime = args[0];
if (!TimeSpan.TryParse(endTime, out var endTimeSpan))
{
Console.WriteLine("Invalid end time format. Use HH:mm");
return;
}
var debug = false;
if (argsLength == 2)
{
if (!bool.TryParse(args[1], out debug))
{
Console.WriteLine("Invalid debug value. Use true or false");
return;
}
}
using var playwright = await Playwright.CreateAsync(); using var playwright = await Playwright.CreateAsync();
var context = await BrowserManager.GetContextAsync(playwright); var context = await BrowserManager.GetContextAsync(playwright);
var page = context.Pages.Count > 0 ? context.Pages[0] : await context.NewPageAsync(); var page = context.Pages.Count > 0 ? context.Pages[0] : await context.NewPageAsync();
await page.GotoAsync("https://my.hdc.mv/"); await page.GotoAsync("https://my.hdc.mv/");
await page.GetByRole(AriaRole.Link, new() { Name = "Login" }).ClickAsync(); try
await page.GetByRole(AriaRole.Button, new() { Name = "eFaas" }).ClickAsync(); {
await page.GetByRole(AriaRole.Tab, new() { Name = "Password Login" }).ClickAsync(new () { Delay = 1000 }); await page.GetByRole(AriaRole.Link, new() { Name = "Login" }).ClickAsync();
await page.GetByPlaceholder("Username").FillAsync("A384347"); await page.GetByRole(AriaRole.Button, new() { Name = "eFaas" }).ClickAsync();
var password = File.ReadAllText("password.txt"); await page.GetByRole(AriaRole.Tab, new() { Name = "Password Login" }).ClickAsync(new () { Delay = 1000 });
await page.GetByPlaceholder("Password").FillAsync(password); await page.GetByPlaceholder("Username").FillAsync("A384347");
await page.GetByRole(AriaRole.Button, new() { Name = "LOGIN" }).ClickAsync(); var password = File.ReadAllText("password.txt");
await page.GetByRole(AriaRole.Button, new() { Name = "CONTINUE" }).ClickAsync(new () { Delay = 1000 }); await page.GetByPlaceholder("Password").FillAsync(password);
await Task.Delay(5000); await page.GetByRole(AriaRole.Button, new() { Name = "LOGIN" }).ClickAsync();
await page.GetByRole(AriaRole.Button, new() { Name = "CONTINUE" }).ClickAsync(new () { Delay = 1000 });
await Task.Delay(5000);
var egovOtp = await OTPExtractor.GetEgovOTP(context, page); var egovOtp = await GoogleMessages.GetEgovOTP(context, page);
if (egovOtp is not null) if (egovOtp is not null)
Console.WriteLine($"Extracted eGov OTP: {egovOtp}"); Console.WriteLine($"Extracted eGov OTP: {egovOtp}");
else else
return;
await page.GetByPlaceholder("OTP").FillAsync(egovOtp);
await page.GetByRole(AriaRole.Button, new() { Name = "CONTINUE" }).ClickAsync();
}
catch (Exception ex)
{
Console.WriteLine($"Error during login: {ex.Message}\nAssuming already logged in, proceeding with booking...");
await page.CloseAsync();
return; return;
}
await page.GetByPlaceholder("OTP").FillAsync(egovOtp);
await page.GetByRole(AriaRole.Button, new() { Name = "CONTINUE" }).ClickAsync();
await page.GetByText("Make a booking").ClickAsync(); await page.GetByText("Make a booking").ClickAsync();
await page.GetByText("Fahiveni").ClickAsync(); await page.GetByText("Fahiveni").ClickAsync();
await page.GetByText("Sports and Leisure").ClickAsync(); await page.GetByText("Sports and Leisure").ClickAsync();
await page.GetByText(" Fahiveni Community Center ").First.ClickAsync(new () { Delay = 1500 }); await page.GetByText(" Fahiveni Community Center ").First.ClickAsync(new () { Delay = 1500 });
await page.GetByText("Badminton Court 1").ClickAsync(new () { Delay = 1500 }); await page.GetByText("Badminton Court 1").ClickAsync(new () { Delay = 1500 });
Console.ReadLine(); var currentDateTime = DateTime.Now;
var upperBound = new DateTime(currentDateTime.Year, currentDateTime.Month, currentDateTime.Day,
hour: 8, minute: 15, second: 0);
var lowerBound = new DateTime(currentDateTime.Year, currentDateTime.Month, currentDateTime.Day,
hour: 8, minute: 0, second: 0, millisecond: 0);
var lastReloadTime = DateTime.Now;
while (!debug && (currentDateTime < lowerBound || currentDateTime >= upperBound))
{
//Don't reload if 10 sec away from 8AM
//Reload every 2 minutes to avoid logout
if(lowerBound - currentDateTime > TimeSpan.FromSeconds(10) &&
lastReloadTime - currentDateTime > TimeSpan.FromMinutes(2))
{
await page.ReloadAsync();
lastReloadTime = DateTime.Now;
}
await Task.Delay(5);
currentDateTime = DateTime.Now;
}
// Click the next button to load tomorrow's time slots
await page.Locator("div.flex.items-center.justify-end > div > div:nth-child(2) > svg").ClickAsync();
try
{
Console.WriteLine($"{DateTime.Now:HH:mm:ss}: Clicking next for tomorrow's time slots...");
await page.Locator("div.grid.bg-gray-100.rounded-lg.anim").Filter(new () { HasText = endTime }).ClickAsync( new() { Timeout = 2000 });
Console.WriteLine($"{DateTime.Now:HH:mm:ss}: Timeslot found and clicked.");
}
catch (PlaywrightException)
{
Console.WriteLine($"{DateTime.Now:HH:mm:ss}: Could not find the specified end time slot: {endTime}");
await page.ScreenshotAsync(new PageScreenshotOptions { Path = "ErrorScreenshot.png" });
await page.CloseAsync();
return;
}
await page.GetByRole(AriaRole.Button, new() { Name = "Submit" }).ClickAsync();
await page.GetByRole(AriaRole.Link, new() { Name = "Proceed to payment" }).ClickAsync();
await page.GetByRole(AriaRole.Button, new() { Name = "Pay Now" }).ClickAsync(new () { Delay = 3500 });
await page.GetByRole(AriaRole.Checkbox, new()).ClickAsync();
await page.GetByRole(AriaRole.Button, new() { Name = "Pay now" }).ClickAsync();
var cardDetails = File.ReadAllLines("CardDetails.txt");
await page.GetByPlaceholder("Name on card").FillAsync(cardDetails[0]);
await page.GetByPlaceholder("1234 1234 1234 1234").FillAsync(cardDetails[1]);
await page.GetByPlaceholder("MM/YY").FillAsync(cardDetails[2]);
var cvv = File.ReadAllText("CVV.txt");
await page.GetByPlaceholder("CVV").FillAsync(cvv);
await page.GetByText(new Regex("^Pay")).ClickAsync(new () { Delay = 1000 });
await Task.Delay(15000);
var bmlOtp = await GoogleMessages.GetBMLOTP(context, page);
if (bmlOtp is not null)
Console.WriteLine($"Extracted BML OTP: {bmlOtp}");
else
{
await page.CloseAsync();
return;
}
await page.Locator("input[name='otpValue']").FillAsync(bmlOtp);
await page.GetByRole(AriaRole.Button, new() { Name = "CONFIRM" }).ClickAsync();
await Task.Delay(15000);
var hdcMessage = await GoogleMessages.GetMessageFromHDC(context, page);
Console.WriteLine($"Message from HDC: {hdcMessage}");
await page.CloseAsync();
+11
View File
@@ -1,2 +1,13 @@
# BadmintonBooker # BadmintonBooker
Helps me book the badminton court from HDC automatically.
Right now now configuration is added but password's been removed from the repo and I will need to create a file called "Password.txt" to work on the project.
In the future perhaps it would be much better if I can deploy as a webapp that can be used by friends to schedule an auto purchase of a slot at a perticular time.
## Example Useage
**`dotnet run -- 22:00`**
Where `22:00` is the end time of the prefered time. `22:00` is the slot from `21:00 - 22:00`.
Preferably the application will be run close to 8AM around 7:45AM so that there's need to perpetually keep refreshing the site for a long time.
**``OWO``**
+1
View File
@@ -0,0 +1 @@
C:\Users\Shaamil\Desktop\BadmintonBooker\Scheduler
+59
View File
@@ -0,0 +1,59 @@
using System.Reflection;
using System.Text;
using Microsoft.Win32.TaskScheduler;
if(args.Length != 1)
{
Console.WriteLine("Usage: Scheduler <timeslot>");
return;
}
var timeslot = args[0];
if (!TimeSpan.TryParse(timeslot, out var _))
{
Console.WriteLine("Invalid timeslot format. Use HH:mm");
return;
}
var dir = new DirectoryInfo(File.ReadAllText("AppSettings.txt"))!;
var builder = new StringBuilder();
builder.AppendLine($"cd {dir.Parent!.FullName}");
builder.AppendLine($"dotnet run -- {timeslot}");
File.WriteAllText("run.bat", builder.ToString());
using (TaskService taskService = new TaskService())
{
try
{
var existingTask = taskService.GetTask("BadmintonBooker");
if (existingTask != null)
{
taskService.RootFolder.DeleteTask("BadmintonBooker", false);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error deleting existing task: {ex.Message}");
}
TaskDefinition taskDef = taskService.NewTask();
taskDef.RegistrationInfo.Description = "Scheduled Task with Credentials";
taskDef.Principal.RunLevel = TaskRunLevel.Highest;
taskDef.Triggers.Add(new TimeTrigger
{
StartBoundary = DateTime.Today.AddDays(1) + TimeSpan.Parse("07:40")
});
taskDef.Actions.Add(new ExecAction("cmd", $"/c \"{Path.Combine(dir.FullName, "run.bat")}\" > C:\\Output.log 2>&1"));
var pass = File.ReadAllText("Password.txt");
taskService.RootFolder.RegisterTaskDefinition(
"BadmintonBooker",
taskDef,
TaskCreation.CreateOrUpdate,
"Shaamil",
pass,
TaskLogonType.Password
);
}
+17
View File
@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<None Include="AppSettings.txt" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="TaskScheduler" Version="2.12.0" />
</ItemGroup>
</Project>