Skip to content

Commit

Permalink
Updated settings
Browse files Browse the repository at this point in the history
- Removed Bing API key that was hardcoded
- API keys now can be entered through program
- Fixed some incorrect usage of path variables in FileManager.SaveSettings()
  • Loading branch information
laptop מיכאל קושניר committed Sep 14, 2023
1 parent 6cd93af commit 7b3d24a
Show file tree
Hide file tree
Showing 5 changed files with 121 additions and 40 deletions.
62 changes: 56 additions & 6 deletions Optimeet/FileManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,13 @@ namespace Optimeet
public sealed class FileManager
{
readonly string path_contacts = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.MyDoc‌​uments), "Optimeet", "contacts.xml");
Environment.SpecialFolder.MyDoc‌​uments), "Optimeet", "contacts.xml");
readonly string path_meetings = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.MyDoc‌​uments), "Optimeet", "meetings.xml");
Environment.SpecialFolder.MyDoc‌​uments), "Optimeet", "meetings.xml");
readonly string path_settings = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.MyDoc‌​uments), "Optimeet", "settings.csv");
Environment.SpecialFolder.MyDoc‌​uments), "Optimeet", "settings.csv");
readonly string path_keysCSV = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.MyDocuments), "Optimeet", "keys.csv");
public static readonly string path_keys = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.MyDoc‌​uments), "Optimeet", "keys.json");
public Trie<Contact> Contacts;
Expand All @@ -28,11 +30,19 @@ public sealed class FileManager
public const string SETTING_2 = "Search radius (metres)";
public const string SETTING_3 = "Meeting duration (minutes)";
public const string SETTING_4 = "Define upcoming meetings deadline (weeks)";
public const string KEY_0 = "Bing maps key";
public const string KEY_1 = "Google Places API key";
public const string KEY_2 = "PositionStack API key";
public const string KEY_3 = "OAuth credentials json directory address";

public Dictionary<string, string> Keys { get; private set; }

private FileManager()
{
LoadContacts();
LoadMeetings();
LoadSettings();
LoadKeys();
}
/// <summary>
/// Initiates the singleton object
Expand All @@ -46,7 +56,6 @@ public static FileManager GetInstance()
}
return _instance;
}

/// <summary>
/// Loads the settings from settings.csv file
/// </summary>
Expand Down Expand Up @@ -87,14 +96,55 @@ public void SaveSettings()
{
if (!Directory.Exists(path_meetings))
{
string[] splits = path_meetings.Split('\\');
string rootpath = path_meetings.Substring(0, path_meetings.Length - splits[splits.Length - 1].Length);
string[] splits = path_settings.Split('\\');
string rootpath = path_settings.Substring(0, path_settings.Length - splits[splits.Length - 1].Length);
Directory.CreateDirectory(rootpath);
}
string csv = string.Join(Environment.NewLine, Settings.Select(d => $"{d.Key},{d.Value[0]},{d.Value[1]},{d.Value[2]},{d.Value[3]}"));
File.WriteAllText(path_settings, csv);
}
/// <summary>
/// Loads the settings from settings.csv file
/// </summary>
private void LoadKeys()
{
Keys = new Dictionary<string, string>();
try
{
using (var reader = new StreamReader(path_keysCSV))
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
Keys.Add(values[0], values[1]);
}
}
}
catch (Exception e) when (e is FileNotFoundException || e is DirectoryNotFoundException)
{
Keys.Add(KEY_0, "");
Keys.Add(KEY_1, "");
Keys.Add(KEY_2, "");
Keys.Add(KEY_3, "");
SaveKeys();
}
}
/// <summary>
/// Saves the keys to keys.csv
/// </summary>
public void SaveKeys()
{
if (!Directory.Exists(path_meetings))
{
string[] splits = path_keysCSV.Split('\\');
string rootpath = path_keysCSV.Substring(0, path_keysCSV.Length - splits[splits.Length - 1].Length);
Directory.CreateDirectory(rootpath);
}
string csv = string.Join(Environment.NewLine, Keys.Select(d => $"{d.Key},{d.Value}"));
File.WriteAllText(path_keysCSV, csv);
}
/// <summary>
/// Loads the contacts from contacts.csv file
/// </summary>
private void LoadContacts()
Expand Down
2 changes: 1 addition & 1 deletion Optimeet/MainWindow.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
<DropShadowEffect Direction="250" BlurRadius="10" ShadowDepth="2"/>
</Rectangle.Effect>
</Rectangle>
<m:Map Grid.Column="1" Grid.RowSpan="2" x:Name="ApplicationMap" Grid.IsSharedSizeScope="True" CredentialsProvider="4oUdxuNmhAKkfVowia1L~4voqLmANS1b8b6BGRoj3XA~AtcXDNfgrjV1BBWaBQ490TvRjTvJmh33G4wXmkz27TmkhiHE6jQ3-brbFjXdKIYc" Mode="Road" ZoomLevel="10" Panel.ZIndex="1">
<m:Map Grid.Column="1" Grid.RowSpan="2" x:Name="ApplicationMap" Grid.IsSharedSizeScope="True" CredentialsProvider="" Mode="Road" ZoomLevel="10" Panel.ZIndex="1">
<m:Map.Effect>
<DropShadowEffect BlurRadius="15" Direction="100" RenderingBias="Quality"/>
</m:Map.Effect>
Expand Down
57 changes: 51 additions & 6 deletions Optimeet/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NodaTime;
using Optimeet.Properties;
using System;
using System.Collections.Generic;
using System.Diagnostics;
Expand Down Expand Up @@ -41,10 +42,8 @@ public partial class MainWindow : Window
//Google API variables
private CalendarService service;
private UserCredential credential;
private readonly string secretsPath = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.MyDoc‌​uments), "Optimeet", "client_secrets.json");
private readonly string credPath = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.MyDoc‌​uments), "Optimeet", "token.json");
Environment.SpecialFolder.MyDoc‌​uments), "Optimeet", "token.json");
//Used for picking a meeting location
private Location FinalChoice;
private Location CreateContactLocation; //Used for saving a new contact
Expand All @@ -53,10 +52,11 @@ public MainWindow()
{
InitializeComponent();
//Initialize singleton objects
helper = MapsHelper.GetInstance();
fm = FileManager.GetInstance();
helper = MapsHelper.GetInstance();
//Create map UI layer
mapLayer = new MapLayer();
ApplicationMap.CredentialsProvider = new ApplicationIdCredentialsProvider(fm.Keys[FileManager.KEY_0]);
ApplicationMap.Children.Add(mapLayer);
ResetViews();
//Preload all menus
Expand Down Expand Up @@ -1301,6 +1301,46 @@ private void LoadSettingsUI()
//Continue to next setting
count++;
}
foreach (KeyValuePair<string, string> pair in fm.Keys)
{
//Settings Key name
TextBlock t = new TextBlock()
{
Text = pair.Key,
Margin = new Thickness(0, 10, 0, 0),
TextWrapping = TextWrapping.WrapWithOverflow,
Name = "block_" + count
};
//Textbox which represents the value
TextBox val = new TextBox()
{
Text = pair.Value.ToString(),
Width = 300,
HorizontalAlignment = HorizontalAlignment.Left,
TextAlignment = TextAlignment.Left,
Name = "val_" + count,
Tag = pair.Key
};
val.TextChanged += (object sender, TextChangedEventArgs args) =>
{
fm.Keys[val.Tag.ToString()] = val.Text;
fm.SaveKeys();
};
//A stack panel that acts as a wrapper object
StackPanel sp = new StackPanel()
{
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(10),
Orientation = Orientation.Vertical,
};
//Wrap in stackpanel
sp.Children.Add(t);
sp.Children.Add(val);
// Add the elements to settings menu
SettingsMenu.Children.Add(sp);
//Continue to next setting key
count++;
}
}
/// <summary>
/// Open or closes Settings menu
Expand Down Expand Up @@ -1359,7 +1399,7 @@ private async void SignInOutGoogleAccount(object sender, RoutedEventArgs e)
try
{
//Retrieve Google OAuth2.0 secret keys
using (var stream = new FileStream(secretsPath, FileMode.Open, FileAccess.Read))
using (var stream = new FileStream(fm.Keys[FileManager.KEY_3], FileMode.Open, FileAccess.Read))
{
var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
Expand Down Expand Up @@ -1389,7 +1429,7 @@ private async void SignInOutGoogleAccount(object sender, RoutedEventArgs e)
if (b == null)
return;
//User sign attempt --> Create new user --> log in to service
using (var stream = new FileStream(secretsPath, FileMode.Open, FileAccess.Read))
using (var stream = new FileStream(fm.Keys[FileManager.KEY_3], FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.FromStream(stream).Secrets,
Expand All @@ -1399,6 +1439,11 @@ private async void SignInOutGoogleAccount(object sender, RoutedEventArgs e)
new FileDataStore(credPath, true));
}
}
catch (ArgumentException)
{
//No client_secrets set
MessageBox.Show("Please provide Oauth secret's directory in settings");
}
//Create the Google Calendar service
service = new CalendarService(new BaseClientService.Initializer()
{
Expand Down
31 changes: 8 additions & 23 deletions Optimeet/MapsHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,36 +40,21 @@ public static MapsHelper GetInstance()
if (_instance == null)
{
_instance = new MapsHelper();
Initialzie();
Initialize();
}
return _instance;
}
/// <summary>
/// Gets the API keys from the stored file and appends them to the url strings
/// </summary>
private static void Initialzie()
private static void Initialize()
{
try
{
using (var reader = new StreamReader(FileManager.path_keys))
{
while (!reader.EndOfStream)
{
var data = reader.ReadToEnd();
JObject file = JsonConvert.DeserializeObject<JObject>(data);
ApiKey = file["ApiKey"].ToString();
GKey = file["GKey"].ToString();
}
baseUrlGC += GKey;
baseUrlPR += GKey;
baseUrlPhotoRequest += GKey;
AutocompleteRequest += GKey;
}
}
catch (Exception e)
{
MessageBox.Show("Could not load all map services because some keys are missing: "+e.Message+". "+FileManager.path_keys, "Error");
}
GKey = FileManager.GetInstance().Keys[FileManager.KEY_1];
ApiKey = FileManager.GetInstance().Keys[FileManager.KEY_2];
baseUrlGC += GKey;
baseUrlPR += GKey;
baseUrlPhotoRequest += GKey;
AutocompleteRequest += GKey;
}
/// <summary>
/// Converts an address into a WGS84 coordinates
Expand Down
9 changes: 5 additions & 4 deletions Optimeet/Optimeet.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,10 @@
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<ManifestCertificateThumbprint>8F3DF6FFD8455AD240D8EA93BC52F461C046202A</ManifestCertificateThumbprint>
<ManifestCertificateThumbprint>CA030973571444363EF1365DD3A8C6F02539E3BD</ManifestCertificateThumbprint>
</PropertyGroup>
<PropertyGroup>
<ManifestKeyFile>Optimeet_TemporaryKey.pfx</ManifestKeyFile>
<ManifestKeyFile>Optimeet_1_TemporaryKey.pfx</ManifestKeyFile>
</PropertyGroup>
<PropertyGroup>
<GenerateManifests>true</GenerateManifests>
Expand All @@ -72,10 +72,10 @@
<ApplicationIcon>logo-dark.ico</ApplicationIcon>
</PropertyGroup>
<PropertyGroup>
<SignAssembly>false</SignAssembly>
<SignAssembly>true</SignAssembly>
</PropertyGroup>
<PropertyGroup>
<AssemblyOriginatorKeyFile>Optimeet_TemporaryKey.pfx</AssemblyOriginatorKeyFile>
<AssemblyOriginatorKeyFile>Optimeet_1_TemporaryKey.pfx</AssemblyOriginatorKeyFile>
</PropertyGroup>
<ItemGroup>
<Reference Include="FontAwesome.WPF, Version=4.7.0.37774, Culture=neutral, PublicKeyToken=0758b07a11a4f466, processorArchitecture=MSIL">
Expand Down Expand Up @@ -212,6 +212,7 @@
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
<None Include="Optimeet_1_TemporaryKey.pfx" />
<None Include="Optimeet_TemporaryKey.pfx" />
<None Include="packages.config" />
<None Include="Properties\Settings.settings">
Expand Down

0 comments on commit 7b3d24a

Please sign in to comment.