Implemented MC side receive of Public Profile list and public profiles

This commit is contained in:
Matt Moening 2016-06-22 18:05:52 -07:00
parent e926186f6b
commit bc5ef8a5b3
8 changed files with 229 additions and 36 deletions

View file

@ -369,8 +369,10 @@
<Compile Include="SlicerConfiguration\SlicingQueue.cs" />
<Compile Include="Utilities\TupleList.cs" />
<Compile Include="VersionManagement\ContactFormRequest.cs" />
<Compile Include="VersionManagement\RetrievePublicProfileRequest.cs" />
<Compile Include="VersionManagement\LatestVersionRequest.cs" />
<Compile Include="VersionManagement\ClientTokenRequest.cs" />
<Compile Include="VersionManagement\PublicProfilesRequest.cs" />
<Compile Include="VersionManagement\WebRequestHandler.cs" />
<Compile Include="VersionManagement\VersionFileHandler.cs" />
<Compile Include="AboutPage\AboutWidget.cs" />
@ -415,6 +417,7 @@
<Reference Include="System.Data" />
<Reference Include="System.Drawing" />
<Reference Include="System.Management" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
<Reference Include="System.Core" />

View file

@ -181,13 +181,13 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections
activeMake = ((Agg.UI.DropDownList)sender).SelectedValue;
activeModel = null;
List<string> printers;
Dictionary<string, string> printers;
if (!OemSettings.Instance.OemProfiles.TryGetValue(activeMake, out printers))
{
printers = new List<string>();
printers = new Dictionary<string, string>();
}
printerModelSelector.ListSource = printers.Select(name => new KeyValuePair<string, string>(name, name)).ToList();
printerModelSelector.ListSource = printers.Select(profile => new KeyValuePair<string, string>(profile.Key, profile.Value)).ToList();
contentRow.Invalidate();

View file

@ -29,6 +29,7 @@ either expressed or implied, of the FreeBSD Project.
using MatterHackers.Agg.PlatformAbstract;
using MatterHackers.MatterControl.DataStorage;
using MatterHackers.MatterControl.VersionManagement;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
@ -114,7 +115,7 @@ namespace MatterHackers.MatterControl.SettingsManagement
public List<KeyValuePair<string, string>> AllOems { get; private set; }
public Dictionary<string, List<string>> OemProfiles { get; private set; }
public Dictionary<string, Dictionary<string, string>> OemProfiles { get; set; }
[OnDeserialized]
private void Deserialized(StreamingContext context)
@ -125,36 +126,39 @@ namespace MatterHackers.MatterControl.SettingsManagement
// Request the latest content, passing along the ETAG
// Refresh our cache if needed, otherwise stick with the cached data
// For now, refresh every time
string cacheDirectory = Path.Combine(ApplicationDataStorage.ApplicationUserDataPath, "data", "temp", "cache", "profiles");
PublicProfilesRequest profileRequest = new PublicProfilesRequest();
profileRequest.Request();
// Ensure directory exists
Directory.CreateDirectory(cacheDirectory);
//// For now, refresh every time
//string cacheDirectory = Path.Combine(ApplicationDataStorage.ApplicationUserDataPath, "data", "temp", "cache", "profiles");
// Cache file path
string cachePath = Path.Combine(cacheDirectory, "oemprofiles.json");
//// Ensure directory exists
//Directory.CreateDirectory(cacheDirectory);
try
{
var fileInfo = new FileInfo(cachePath);
if (!fileInfo.Exists || (DateTime.Now - fileInfo.LastWriteTime).TotalHours > 1)
{
string url = "http://matterdata.azurewebsites.net/api/oemprofiles";
//// Cache file path
//string cachePath = Path.Combine(cacheDirectory, "oemprofiles.json");
var client = new WebClient();
//try
//{
// var fileInfo = new FileInfo(cachePath);
// if (!fileInfo.Exists || (DateTime.Now - fileInfo.LastWriteTime).TotalHours > 1)
// {
// string url = "http://matterdata.azurewebsites.net/api/oemprofiles";
File.WriteAllText(cachePath, client.DownloadString(url));
}
}
catch (Exception ex)
{
System.Diagnostics.Trace.WriteLine("An unexpected exception occurred while requesting the latest oem profiles: \r\n" + ex.Message);
}
// var client = new WebClient();
string profilesText = File.ReadAllText(cachePath);
OemProfiles = JsonConvert.DeserializeObject<Dictionary<string, List<string>>>(profilesText);
// File.WriteAllText(cachePath, client.DownloadString(url));
// }
//}
//catch (Exception ex)
//{
// System.Diagnostics.Trace.WriteLine("An unexpected exception occurred while requesting the latest oem profiles: \r\n" + ex.Message);
//}
SetManufacturers(OemProfiles.Select(m => new KeyValuePair<string, string>(m.Key, m.Key)).ToList());
//string profilesText = File.ReadAllText(cachePath);
//OemProfiles = JsonConvert.DeserializeObject<Dictionary<string, List<string>>>(profilesText);
//SetManufacturers(OemProfiles.Select(m => new KeyValuePair<string, string>(m.Key, m.Key)).ToList());
}
private OemSettings()

View file

@ -38,6 +38,7 @@ namespace MatterHackers.MatterControl.SlicerConfiguration
{
using Agg;
using Localizations;
using VersionManagement;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Net;
@ -272,18 +273,14 @@ namespace MatterHackers.MatterControl.SlicerConfiguration
private static OemProfile LoadHttpOemProfile(string make, string model)
{
string url = string.Format(
"http://matterdata.azurewebsites.net/api/oemprofiles?manufacturer={0}&model={1}",
WebUtility.UrlEncode(make),
WebUtility.UrlEncode(model));
var client = new WebClient();
string profileText = client.DownloadString(url);
var printerProfile = JsonConvert.DeserializeObject<OemProfile>(profileText);
RetrievePublicProfileRequest profileRequest = new RetrievePublicProfileRequest();
string profText = profileRequest.getPrinterProfileByMakeModel(make, model);
var printerProfile = JsonConvert.DeserializeObject<OemProfile>(profText);
return printerProfile;
}
private static void Profiles_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
// Any time the list changes, persist the updates to disk

View file

@ -68,6 +68,7 @@
<Compile Include="PartPreviewTests.cs" />
<Compile Include="PrintQueueTests.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="RetrievePublicProfileTest.cs" />
<Compile Include="SliceSetingsTests.cs" />
<Compile Include="SqLiteLibraryProvider.cs" />
</ItemGroup>

View file

@ -0,0 +1,77 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using MatterHackers.MatterControl.VersionManagement;
using System.IO;
using MatterHackers.MatterControl.DataStorage;
using MatterHackers.MatterControl.SettingsManagement;
using System.Threading;
using MatterHackers.MatterControl.Tests.Automation;
using MatterHackers.Agg.UI.Tests;
using MatterHackers.GuiAutomation;
using MatterHackers.Agg.UI;
using Newtonsoft.Json;
using MatterHackers.Agg.PlatformAbstract;
namespace MatterControl.Tests.MatterControl
{
[TestFixture, RunInApplicationDomain]
public class RetrievePublicProfileTest
{
private string deviceToken = null;
[Test,RunInApplicationDomain]
public void RetrievePrinterProfileListWorking()
{
StaticData.Instance = new MatterHackers.Agg.FileSystemStaticData(Path.Combine("..", "..", "..", "..", "StaticData"));
string profilePath = Path.Combine(ApplicationDataStorage.ApplicationUserDataPath, "data", "temp", "cache", "profiles", "oemprofiles.json");
if(File.Exists(profilePath))
{
File.Delete(profilePath);
}
//MatterControlUtilities.OverrideAppDataLocation();
AutoResetEvent requestCompleteWaiter = new AutoResetEvent(false);
PublicProfilesRequest retrieveProfiles = new PublicProfilesRequest();
retrieveProfiles.URI = "https://mattercontrol-test.appspot.com/api/1/device/get-public-profile-list";
retrieveProfiles.RequestComplete += (sender, eArgs) => { requestCompleteWaiter.Set(); };
retrieveProfiles.Request();
Assert.IsTrue(requestCompleteWaiter.WaitOne());
Assert.IsTrue(File.Exists(profilePath));
//Call Retrieve Profile next
RetrievePrinterProfileWorking();
}
//[Test,Category("CloudProfiles")]
public void RetrievePrinterProfileWorking()
{
string make = OemSettings.Instance.OemProfiles.First().Key;
string model = OemSettings.Instance.OemProfiles[make].First().Key;
deviceToken = OemSettings.Instance.OemProfiles[make][model];
string expectedProfilePath = Path.Combine(ApplicationDataStorage.ApplicationUserDataPath, "Profiles", string.Format("{0}.json", deviceToken));
if (File.Exists(expectedProfilePath))
{
File.Delete(expectedProfilePath);
}
RetrievePublicProfileRequest request = new RetrievePublicProfileRequest();
RetrievePublicProfileRequest.DownloadBaseUrl = "https://mattercontrol-test.appspot.com/api/1/device/get-public-profile";
string recievedPrinterProfile = request.getPrinterProfileByMakeModel(make,model);
RetrievePublicProfileRequest.DownloadBaseUrl = "https://mattercontrol.appspot.com/api/1/device/get-public-profile";
Assert.IsNotNullOrEmpty(recievedPrinterProfile);
//Assert.AreEqual(expectedProfilePath, recievedProfilePath,"Recieved Profile path does not match expected path.");
//Assert.IsTrue(File.Exists(expectedProfilePath));
}
}
}

View file

@ -0,0 +1,44 @@
using MatterHackers.MatterControl.DataStorage;
using MatterHackers.MatterControl.SettingsManagement;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MatterHackers.MatterControl.VersionManagement
{
class PublicProfilesRequest : WebRequestBase
{
public PublicProfilesRequest()
{
//requestValues["ProjectToken"] = VersionInfo.Instance.ProjectToken;
#if DEBUG
uri = "https://mattercontrol-test.appspot.com/api/1/device/get-public-profile-list";
#else
uri = "https://mattercontrol.appspot.com/api/1/device/get-public-profile-list";
#endif
}
internal string URI { get { return uri; } set { uri = value; } }
public override void ProcessSuccessResponse(JsonResponseDictionary responseValues)
{
//For now, refresh every time
string cacheDirectory = Path.Combine(ApplicationDataStorage.ApplicationUserDataPath, "data", "temp", "cache", "profiles");
//Ensure directory exists
Directory.CreateDirectory(cacheDirectory);
//Cache File Path
string cachePath = Path.Combine(cacheDirectory, "oemprofiles.json");
File.WriteAllText(cachePath, responseValues["ProfileList"]);
OemSettings.Instance.OemProfiles = JsonConvert.DeserializeObject<Dictionary<string,Dictionary<string,string>>>(responseValues["ProfileList"]);
OemSettings.Instance.SetManufacturers(OemSettings.Instance.OemProfiles.Select(m => new KeyValuePair<string, string>(m.Key, m.Key)).ToList());
}
}
}

View file

@ -0,0 +1,67 @@
using MatterHackers.MatterControl.DataStorage;
using MatterHackers.MatterControl.SettingsManagement;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
namespace MatterHackers.MatterControl.VersionManagement
{
class RetrievePublicProfileRequest
{
internal static string DownloadBaseUrl { get; set; }
public RetrievePublicProfileRequest()
{
#if DEBUG
DownloadBaseUrl = "https://mattercontrol-test.appspot.com/api/1/device/get-public-profile";
#else
DownloadBaseUrl = "https://mattercontrol.appspot.com/api/1/device/get-public-profile";
#endif
}
public string getPrinterProfileByMakeModel(string make, string model)
{
string deviceToken = OemSettings.Instance.OemProfiles[make][model];
string profiletext = DownloadPrinterProfile(deviceToken);
return profiletext;
}
internal static string DownloadPrinterProfile(string deviceToken)
{
// TODO: Enable caching
//Keept track of version. When retrieving check version
string url = DownloadBaseUrl + string.Format("/{0}",deviceToken);
string profilePath = Path.Combine(ApplicationDataStorage.ApplicationUserDataPath,"Profiles",string.Format("{0}.json",deviceToken));
WebClient client = new WebClient();
string profileText = client.DownloadString(url);
//File.WriteAllText(profileText, profilePath);
return profileText;
//HttpClient client = new HttpClient();
//Get a pemporaty path to write to during download. If download completes without error we move this file to the proper path
//string tempFilePath = ApplicationDataStorage.Instance.GetTempFileName(".json");
//byte[] buffer = new byte[65536];
//using (var writeStream = File.Create(tempFilePath))
//using (var instream = await client.GetStreamAsync(url))
//{
// int bytesRead = await instream.ReadAsync(buffer, 0, buffer.Length);
// while(bytesRead != 0)
// {
// writeStream.Write(buffer, 0, bytesRead);
// bytesRead = await instream.ReadAsync(buffer, 0, buffer.Length);
// }
//}
//File.Move(tempFilePath, profilePath);
//return profilePath;
}
//Used in test to access test server before changes go onto live server
}
}