Skip to content

Commit

Permalink
Try Vercel API migration
Browse files Browse the repository at this point in the history
  • Loading branch information
weedeej committed Feb 19, 2022
1 parent 85df620 commit 1e6874c
Show file tree
Hide file tree
Showing 6 changed files with 145 additions and 51 deletions.
1 change: 1 addition & 0 deletions ValorantCC/MainWindow.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,7 @@
<Button Content="Reload" HorizontalAlignment="Left" Margin="0,0,5,0" Style="{DynamicResource MahApps.Styles.Button.MetroWindow.Base}" BorderThickness="0" Background="#FF0079FF" Padding="0" Height="30" Click="btnReload_Click" Cursor="Hand" VerticalAlignment="Center" FontFamily="Quicksand" FontWeight="DemiBold" FontSize="11" TextBlock.FontFamily="Segoe UI Semibold" TextBlock.FontWeight="Bold" Grid.Column="1" Grid.ColumnSpan="2" Width="120"/>
<Button Content="Save" HorizontalAlignment="Left" Margin="0,0,5,0" Style="{DynamicResource MahApps.Styles.Button.MetroWindow.Base}" BorderThickness="0" Background="#FF0079FF" Padding="0" Height="30" Click="btnSave_Click" Cursor="Hand" VerticalAlignment="Center" FontFamily="Quicksand" FontSize="11" FontWeight="DemiBold" TextBlock.FontFamily="Segoe UI Semibold" TextBlock.FontWeight="Bold" Width="124"/>
<Button x:Name="btnShare" HorizontalAlignment="Left" Margin="0,0,5,0" Style="{DynamicResource MahApps.Styles.Button.MetroWindow.Base}" BorderThickness="0" Background="#FF0079FF" Padding="0" Content="Share" Click="btnShare_Click" Cursor="Hand" Height="30" VerticalAlignment="Center" Width="124" FontFamily="Quicksand" FontSize="11" FontWeight="DemiBold" TextBlock.FontFamily="Segoe UI Semibold" TextBlock.FontWeight="Bold"/>
<Button x:Name="btnCopyShareCode" HorizontalAlignment="Left" Margin="0,0,5,0" Style="{DynamicResource MahApps.Styles.Button.MetroWindow.Base}" BorderThickness="0" Background="#FF0079FF" Padding="0" Content="Copy Sharecode" Click="btnCopyShareCode_Click" Cursor="Hand" Height="30" VerticalAlignment="Center" Width="124" FontFamily="Quicksand" FontSize="11" FontWeight="DemiBold" TextBlock.FontFamily="Segoe UI Semibold" TextBlock.FontWeight="Bold" Visibility="Collapsed"/>

<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Button Name="btnCommunityProfiles" HorizontalAlignment="Right" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="{x:Null}" Cursor="Hand" Style="{DynamicResource MahApps.Styles.Button.Flat}" MouseEnter="ClipboardButtonEnter" MouseLeave="ClipboardButtonLeave" Click="btnCommunityProfiles_Click">
Expand Down
46 changes: 43 additions & 3 deletions ValorantCC/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
using Utilities;
using ValorantCC.src;
using ValorantCC.SubWindow;
using Newtonsoft.Json;

namespace ValorantCC
{
Expand All @@ -26,7 +27,8 @@ public partial class MainWindow : MetroWindow
public API ValCCAPI;
public int SelectedIndex;
public bool LoggedIn;

private string _sharecode;
private FetchResponse? sharedProfileResp;
public MainWindow()
{
// Create logging dir
Expand Down Expand Up @@ -69,7 +71,7 @@ private async void btnSave_Click(object sender, RoutedEventArgs e)
return;
}

private void profiles_SelectionChanged(object sender, SelectionChangedEventArgs e)
private async void profiles_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (profiles.SelectedIndex == -1) return;

Expand All @@ -91,6 +93,30 @@ private void profiles_SelectionChanged(object sender, SelectionChangedEventArgs
ads_color.SelectedColor = Color.FromRgb(SelectedProfile.aDS.Color.R, SelectedProfile.aDS.Color.G, SelectedProfile.aDS.Color.B);
ads_outline_color.SelectedColor = Color.FromRgb(SelectedProfile.aDS.OutlineColor.R, SelectedProfile.aDS.OutlineColor.G, SelectedProfile.aDS.OutlineColor.B);
sniper_dot_color.SelectedColor = Color.FromRgb(SelectedProfile.Sniper.CenterDotColor.R, SelectedProfile.Sniper.CenterDotColor.G, SelectedProfile.Sniper.CenterDotColor.B);
if (!sharedProfileResp.HasValue)
{
if (ValCCAPI != null) sharedProfileResp = await ValCCAPI.ObtainSelfSaved();
}
else
{
var respData = sharedProfileResp.Value;
if (respData.success && respData.data != null)
{
var data = respData.data.FirstOrDefault();
_sharecode = data.shareCode;
CrosshairProfile fromDb = JsonConvert.DeserializeObject<CrosshairProfile>(data.settings);
if (SelectedProfile.ProfileName == fromDb.ProfileName)
{
chkbxShareable.IsChecked = data.shareable;
btnCopyShareCode.Visibility = Visibility.Visible;
}
else
{
chkbxShareable.IsChecked = false;
btnCopyShareCode.Visibility = Visibility.Collapsed;
}
}
}
Crosshair_load();
}
private void StackPanel_MouseDown(object sender, MouseButtonEventArgs e)
Expand Down Expand Up @@ -321,7 +347,13 @@ private async void btnShare_Click(object sender, RoutedEventArgs e)
ValCCAPI.Shareable = (bool)chkbxShareable.IsChecked;
ValCCAPI.profile = SelectedProfile;
SetCallResponse response = await ValCCAPI.Set();
String sharecode = response.data.shareCode;
if (!response.success)
{
Utilities.Utils.Log($"Unable to share crosshair: {response.message}");
Utilities.Utils.MessageText("Unable to share crosshair: Internal Error/Conflict", Brushes.Red);
return;
}
String sharecode = response.message;
Clipboard.SetText(sharecode);
MessageWindow.Show($"Your sharecode is: \"{sharecode}\" and is copied.\nIf you want this profile accessible across the community,\nPlease be sure that you have the 'shareable' checkbox checked.", "Profile shared!");

Expand All @@ -330,6 +362,8 @@ private async void btnShare_Click(object sender, RoutedEventArgs e)

private async void spinner_Loaded(object sender, RoutedEventArgs e)
{
Trace.WriteLine(ValorantCC.src.Community.SCGen.GenerateShareCode("64f8b630-64c6-5838-9daa-916f8bbf5587"));
Trace.WriteLine(ValorantCC.src.Community.SCGen.GenerateShareCode("b19f4928-e1ed-5f63-a9d0-8a7fd202e3b2"));
Updater.CustomLogger = Utilities.Utils.Log;
Updater.OriginalFileName = "ValorantCC";
Updater.LogInterfix = " | ";
Expand All @@ -351,5 +385,11 @@ private async void spinner_Loaded(object sender, RoutedEventArgs e)
update.ShowDialog();
}
}

private void btnCopyShareCode_Click(object sender, RoutedEventArgs e)
{
Clipboard.SetText(_sharecode);
Utilities.Utils.MessageText("Your sharecode has been copied!", Brushes.Lime);
}
}
}
10 changes: 7 additions & 3 deletions ValorantCC/SubWindow/ProfilesWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,16 +74,20 @@ private async Task<bool> InitialFetch(String sharecode = null)
if (!string.IsNullOrWhiteSpace(sharecode))
{
Utilities.Utils.Log($"Fetching profile with code: {sharecode}");
ValCCApi.Action = 3;
FetchResponse fetchResponse = await ValCCApi.Fetch(sharecode);
if (!fetchResponse.success) return false;
if (fetchResponse.data.Count < 1)
{
fetchErrorTxt.Text = "User with corresponding sharecode was not found.";
btnSearchCode.IsEnabled = true;
return false;
}
Shareables = fetchResponse.data;
}
else
{
Utilities.Utils.Log($"Fetching profiles from server");
ValCCApi.Action = 2;
FetchResponse fetchResponse = await ValCCApi.Fetch(sharecode);
FetchResponse fetchResponse = await ValCCApi.Fetch();
if (!fetchResponse.success) return false;
Shareables = fetchResponse.data;
}
Expand Down
4 changes: 2 additions & 2 deletions ValorantCC/ValorantCC.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -75,11 +75,11 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="EZ_Updater" Version="0.5.1.1" />
<PackageReference Include="EZ_Updater" Version="0.5.2" />
<PackageReference Include="FontAwesome.WPF" Version="4.7.0.9" />
<PackageReference Include="MahApps.Metro" Version="2.4.9" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="RestSharp" Version="107.2.1" />
<PackageReference Include="RestSharp" Version="107.3.0" />
<PackageReference Include="WpfAnimatedGif" Version="2.0.2" />
</ItemGroup>

Expand Down
112 changes: 69 additions & 43 deletions ValorantCC/src/API.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,20 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using Utilities;

using ValorantCC.src.Community;
namespace ValorantCC
{
public struct SetCallResponse
{
public bool success { get; set; }
public SetResponse data { get; set; }
}

public struct SetResponse
{
public string settings { get; set; }
public string displayName { get; set; }
public string gameTag { get; set; }
public string shareCode { get; set; }
public bool shareable { get; set; }
public string message { get; set; }
}

public struct FetchResponse
{
public bool success { get; set; }
public List<ShareableProfile> data { get; set; }
public string message { get; set; }
}

public struct ShareableProfile
Expand All @@ -36,77 +28,111 @@ public struct ShareableProfile
public String displayName { get; set; }
}

public partial class PostPayload
public partial class Payload
{
public String subject { get; set; }
public String settings { get; set; }
public bool shareable { get; set; }
public String sharecode { get; set; } = null;
public int action { get; set; }
public String sharecode { get; set; }
}
public class API
{
private static AuthTokens AuthTokens;
private static RestClient client = new RestClient("https://valorantcc.000webhostapp.com/api.php");
private static RestClient client = new RestClient("https://vtools-next.vercel.app/api");

public CrosshairProfile profile;
public int Action;
public bool Shareable;
public API(AuthTokens Tokens, CrosshairProfile TargetProfile, int ActionInt, bool isShareable)
{
AuthTokens = Tokens;
profile = TargetProfile;
Action = ActionInt;
Shareable = isShareable;
}

public async Task<FetchResponse> Fetch(String sharecode = null)
{
PostPayload payload = new PostPayload()
RestRequest request;
if (sharecode != null)
request = new RestRequest($"/sharecode/{sharecode}", Method.Get);
else
request = new RestRequest("/profiles", Method.Get);

RestResponse response = await client.ExecuteAsync(request);
if (!response.IsSuccessful && response.StatusCode != System.Net.HttpStatusCode.NotFound)
{
subject = AuthTokens.Subject,
settings = JsonConvert.SerializeObject(profile),
shareable = Shareable,
action = Action
};
if (sharecode != null)
Utils.Log(response.Content.ToString());
return new FetchResponse() { success = false };
}
if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
{
payload.sharecode = sharecode;
payload.action = Action;
return new FetchResponse() { success = true, data = new List<ShareableProfile>()};
}
RestRequest request = new RestRequest() { Method = Method.Post };
request.AddJsonBody(payload);

return new FetchResponse()
{
success = true,
data = JsonConvert.DeserializeObject<List<ShareableProfile>>(response.Content)
};
}

public async Task<FetchResponse> ObtainSelfSaved()
{
RestRequest request = new RestRequest($"/profiles/{AuthTokens.Subject}/fetch", Method.Get);

RestResponse response = await client.ExecuteAsync(request);
if (!response.IsSuccessful)
if (!response.IsSuccessful && response.StatusCode != System.Net.HttpStatusCode.NotFound)
{
Utilities.Utils.Log(response.Content.ToString());
return new FetchResponse() { success = false };
Utils.Log(response.Content.ToString());
return new FetchResponse() { success = false, message = response.Content.ToString() };
}

if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
return new FetchResponse() { success = true, message = response.Content.ToString() };

return JsonConvert.DeserializeObject<FetchResponse>(response.Content);
return new FetchResponse()
{
success = true,
data = new List<ShareableProfile>() { JsonConvert.DeserializeObject<ShareableProfile>(response.Content) }
};
}

public async Task<SetCallResponse> Set()
{
PostPayload payload = new PostPayload()
Payload payload = new Payload()
{
subject = AuthTokens.Subject,
settings = JsonConvert.SerializeObject(profile),
shareable = Shareable,
action = 1
sharecode = SCGen.GenerateShareCode(AuthTokens.Subject)
};
RestRequest request = new RestRequest() { Method = Method.Post };
request.RequestFormat = DataFormat.Json;
RestRequest request = new RestRequest($"/profiles/{AuthTokens.Subject}/set", Method.Put) { RequestFormat = DataFormat.Json };
request.AddJsonBody(payload);
request.AddOrUpdateHeader("Authorization", $"Bearer {AuthTokens.AccessToken}"); // Pass to server so nobody can set somebody's saved profile.
RestResponse response = await client.ExecuteAsync(request);
if (!response.IsSuccessful)
if (!response.IsSuccessful)
{
Utilities.Utils.Log(response.Content.ToString());
return new SetCallResponse() { success = false };
Utils.Log(response.Content.ToString());
int retry = 0;
while (response.StatusCode == System.Net.HttpStatusCode.Conflict)
{
await Task.Delay(500);
if (response.StatusCode != System.Net.HttpStatusCode.Conflict) break;
// Retry until 5 retries or removed the conflict.
payload.sharecode = SCGen.GenerateShareCode(AuthTokens.Subject);
request = new RestRequest($"/profiles/{AuthTokens.Subject}/set", Method.Put) { RequestFormat = DataFormat.Json };
request.AddJsonBody(payload);
request.AddOrUpdateHeader("Authorization", $"Bearer {AuthTokens.AccessToken}");
response = await client.ExecuteAsync(request);
retry++;
Utils.Log($"Conflict removal retry: {retry}: {response.Content}");
if (retry >= 5) break;
}
if (response.StatusCode != System.Net.HttpStatusCode.Conflict)
{
Utils.Log(response.Content.ToString());
return new SetCallResponse() { success = false, message = response.Content.ToString() };
}
Utils.Log($"Failure to remove the conflict. Sharecode: {payload.sharecode} | {response.Content}");
return new SetCallResponse() { success = false, message = response.Content.ToString() };
}
return JsonConvert.DeserializeObject<SetCallResponse>(response.Content);
return new SetCallResponse() { success = true, message = payload.sharecode };
}

}
Expand Down
23 changes: 23 additions & 0 deletions ValorantCC/src/Community/SCGen.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Numerics;

namespace ValorantCC.src.Community
{
public class SCGen
{
private static Random rand = new Random();
public static string GenerateShareCode(string input)
{
input = input.Replace("-", String.Empty);

return new string(
Enumerable.Repeat(input, 12)
.Select(s => s[rand.Next(s.Length)])
.ToArray()).ToUpper();
}
}
}

0 comments on commit 1e6874c

Please # to comment.