Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 14 additions & 4 deletions AutotuneWeb/Controllers/HomeController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace AutotuneWeb.Controllers
{
Expand Down Expand Up @@ -51,7 +52,9 @@ public ActionResult Autotune(Uri nsUrl, decimal? cr, decimal? sens)
}

ModelState.SetModelValue(nameof(nsUrl), nsUrl, nsUrl.ToString());
ViewBag.ApiSecret = HttpUtility.ParseQueryString(nsUrl.Query)["token"]?.Split(",")[^1];
ViewBag.NSUrl = nsUrl;
ViewBag.NSUrlBase = new Uri(nsUrl.GetLeftPart(UriPartial.Path));
ViewBag.ProfileActivation = profileActivation;
ViewBag.PreviousResults = HasPreviousResults(nsUrl);

Expand Down Expand Up @@ -113,8 +116,11 @@ class NSTempBasal

private bool TempBasalIncludesRateProperty(Uri url)
{
var profileSwitchUrl = new Uri(url, "/api/v1/treatments.json?find[eventType][$eq]=Temp%20Basal&count=10");
var req = WebRequest.CreateHttp(profileSwitchUrl);
var queryString = "find[eventType][$eq]=Temp%20Basal&count=10";
var profileSwitchUrl = new UriBuilder(url);
profileSwitchUrl.Path = "/api/v1/treatments.json";
profileSwitchUrl.Query = profileSwitchUrl.Query.Length > 1 ? $"{profileSwitchUrl.Query}&{queryString}" : queryString;
var req = WebRequest.CreateHttp(profileSwitchUrl.Uri);
using (var resp = req.GetResponse())
using (var stream = resp.GetResponseStream())
using (var reader = new StreamReader(stream))
Expand All @@ -139,7 +145,7 @@ private NSValueWithTime[] CombineAdjacentTimeBlocks(NSValueWithTime[] values)
return combined.ToArray();
}

public async Task<ActionResult> RunJob(Uri nsUrl, string oapsProfile, string units, string timezone, bool? uamAsBasal, double pumpBasalIncrement, decimal? min5MCarbImpact, string curve, string emailResultsTo, int days)
public async Task<ActionResult> RunJob(Uri nsUrl, string apiSecret, string oapsProfile, string units, string timezone, bool? uamAsBasal, double pumpBasalIncrement, decimal? min5MCarbImpact, string curve, string emailResultsTo, int days)
{
if (min5MCarbImpact != null || !String.IsNullOrEmpty(curve))
{
Expand All @@ -162,6 +168,7 @@ public async Task<ActionResult> RunJob(Uri nsUrl, string oapsProfile, string uni
{
PartitionKey = GetPartitionKey(nsUrl.ToString()),
NSUrl = nsUrl.ToString(),
ApiSecret = apiSecret,
Units = units,
TimeZone = timezone,
UAMAsBasal = uamAsBasal.GetValueOrDefault(),
Expand Down Expand Up @@ -369,6 +376,9 @@ private async Task<int> CreateBatchJobAsync(string jobName, Job jobDetails, stri
job.OnAllTasksComplete = OnAllTasksComplete.TerminateJob;
await job.CommitAsync();

var nsHost = (new Uri(jobDetails.NSUrl)).GetLeftPart(UriPartial.Path);
var nsApiSecret = jobDetails.ApiSecret != "" ? $"API_SECRET='{jobDetails.ApiSecret}' " : "";

// Add a task to the job to run Autotune
var commandLine = "/bin/sh -c '" +
"cd \"$AZ_BATCH_TASK_WORKING_DIR\" && " +
Expand All @@ -378,7 +388,7 @@ private async Task<int> CreateBatchJobAsync(string jobName, Job jobDetails, stri
"cp settings/profile.json settings/autotune.json && " +
$"TZ='{jobDetails.TimeZone}' && " +
"export TZ && " +
$"oref0-autotune --dir=$AZ_BATCH_TASK_WORKING_DIR --ns-host={jobDetails.NSUrl} --start-date={DateTime.Now.AddDays(-jobDetails.Days):yyyy-MM-dd} --end-date={DateTime.Now.AddDays(-1):yyyy-MM-dd} --categorize-uam-as-basal={(jobDetails.UAMAsBasal ? "true" : "false")}" +
$"{nsApiSecret}oref0-autotune --dir=$AZ_BATCH_TASK_WORKING_DIR --ns-host={nsHost} --start-date={DateTime.Now.AddDays(-jobDetails.Days):yyyy-MM-dd} --end-date={DateTime.Now.AddDays(-1):yyyy-MM-dd} --categorize-uam-as-basal={(jobDetails.UAMAsBasal ? "true" : "false")}" +
"'";

var task = new CloudTask("Autotune", commandLine);
Expand Down
1 change: 1 addition & 0 deletions AutotuneWeb/Models/Job.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ namespace AutotuneWeb.Models
public class Job : TableEntity
{
public string NSUrl { get; set; }
public string ApiSecret { get; set; }
public double PumpBasalIncrement { get; set; }
public string EmailResultsTo { get; set; }
public string Units { get; set; }
Expand Down
18 changes: 13 additions & 5 deletions AutotuneWeb/Models/NSProfile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,15 +52,23 @@ public static NSProfileDetails LoadFromNightscout(ref Uri url, out DateTime prof

// Get the profile from NS
// Try looking for a Profile Switch event first
var profileSwitchUrl = new Uri(url, $"/api/v1/treatments.json?find[eventType][$eq]=Profile%20Switch&find[created_at][$lte]={DateTime.UtcNow:yyyy-MM-ddTHH:mmzzz}&count=1");
var req = WebRequest.CreateHttp(profileSwitchUrl);
var queryString = $"find[eventType][$eq]=Profile%20Switch&find[created_at][$lte]={DateTime.UtcNow:yyyy-MM-ddTHH:mmzzz}&count=1";

var baseUrl = new UriBuilder(url) { Path = "/" };
var profileSwitchUrl = new UriBuilder(baseUrl.Uri) {
Path = "/api/v1/treatments.json",
Query = baseUrl.Query.Length > 1 ? $"{baseUrl.Query}&{queryString}" : queryString
};

var req = WebRequest.CreateHttp(profileSwitchUrl.Uri);
using (var resp = req.GetResponse())
using (var stream = resp.GetResponseStream())
using (var reader = new StreamReader(stream))
{
// Change the URL based on any redirects we've followed and remove any trailing path elements that might have
// been included in the input.
url = new Uri(resp.ResponseUri, "/");
baseUrl = new UriBuilder(resp.ResponseUri) { Path = "/", Query = baseUrl.Query };
url = baseUrl.Uri;

var json = reader.ReadToEnd();
var profileSwitches = JsonConvert.DeserializeObject<NSProfileSwitch[]>(json);
Expand All @@ -79,9 +87,9 @@ public static NSProfileDetails LoadFromNightscout(ref Uri url, out DateTime prof
}

// If there wasn't a profile switch, try again looking at the latest profile
var profileUrl = new Uri(url, "/api/v1/profile/current");
var profileUrl = new UriBuilder(baseUrl.Uri) { Path = "/api/v1/profile/current" };

req = WebRequest.CreateHttp(profileUrl);
req = WebRequest.CreateHttp(profileUrl.Uri);
using (var resp = req.GetResponse())
using (var stream = resp.GetResponseStream())
using (var reader = new StreamReader(stream))
Expand Down
2 changes: 1 addition & 1 deletion AutotuneWeb/Views/Home/About.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
by Autotune may be misleading.</dd>

<dt>I get a 401 error below my URL and it doesn't run.</dt>
<dd>AutotuneWeb pulls from your Nightscout. Nightscout must be set with "readable" in AUTH_DEFAULT_ROLES in order for your Nightscout to be readable by AutotuneWeb</dd>
<dd>AutotuneWeb pulls from your Nightscout. In order for your Nightscout to be readable by AutotuneWeb, you must either have your Nightscout's AUTH_DEFAULT_ROLES be set to "readable" or provide AutotuneWeb with a token URL that has the "readable" role. <a href="https://nightscout.github.io/nightscout/security/#create-a-token">You can find information on how to create a token in Nightscout's documentation.</a></dd>

<dt>I get a warning about missing "rate" property in my temp basal data</dt>
<dd>This is an extra bit of information that Autotune expects in the Nightscout data that isn't always added. If this data is missing then
Expand Down
12 changes: 10 additions & 2 deletions AutotuneWeb/Views/Home/Converted.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
<div class="alert alert-info">
<p>Looking for your previous results?</p>
<p>
<a href="/Results/Index?nsUrl=@ViewBag.NSUrl" class="btn btn-success">View Results</a>
<a href="/Results/Index?nsUrl=@Uri.EscapeDataString(ViewBag.NSUrl.ToString())" class="btn btn-success">View Results</a>
</p>
</div>
}
Expand Down Expand Up @@ -162,7 +162,14 @@
</li>
<li>
Run Autotune with
<code>oref0-autotune --dir=~/myopenaps --ns-host=@ViewBag.NSUrl --start-date=YYYY-MM-DD</code>
@if (String.IsNullOrEmpty(ViewBag.ApiSecret))
{
<code>oref0-autotune --dir=~/myopenaps --ns-host=@ViewBag.NSUrlBase --start-date=YYYY-MM-DD</code>
}
else
{
<code>API_SECRET=@ViewBag.ApiSecret oref0-autotune --dir=~/myopenaps --ns-host=@ViewBag.NSUrlBase --start-date=YYYY-MM-DD</code>
}
</li>
</ol>

Expand All @@ -175,6 +182,7 @@
@using (Html.BeginForm("RunJob", "Home"))
{
@Html.Hidden("nsUrl", (Uri)ViewBag.NSUrl)
@Html.Hidden("apiSecret", (string)ViewBag.ApiSecret)
@Html.Hidden("oapsProfile", profileJson)
@Html.Hidden("units", (string)ViewBag.Units)
@Html.Hidden("timezone", (string)ViewBag.TimeZone)
Expand Down
2 changes: 1 addition & 1 deletion AutotuneWeb/Views/Home/MultipleValues.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
<div class="alert alert-info">
<p>Looking for your previous results?</p>
<p>
<a href="/Results/Index?nsUrl=@ViewBag.NSUrl" class="btn btn-success">View Results</a>
<a href="/Results/Index?nsUrl=@Uri.EscapeDataString(ViewBag.NSUrl.ToString())" class="btn btn-success">View Results</a>
</p>
</div>
}
Expand Down
2 changes: 1 addition & 1 deletion AutotuneWeb/Views/Results/FailureDetails.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,6 @@
@foreach (var log in (string[])ViewBag.Logs)
{
<p>
<a href="/Results/DownloadLog?nsUrl=@Model.NSUrl&jobId=@Model.RowKey&filename=@log" class="btn btn-primary">Download Log</a>
<a href="/Results/DownloadLog?nsUrl=@Uri.EscapeDataString(Model.NSUrl.ToString())&jobId=@Model.RowKey&filename=@log" class="btn btn-primary">Download Log</a>
</p>
}
2 changes: 1 addition & 1 deletion AutotuneWeb/Views/Results/Index.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
<td>
@if (job.ProcessingCompleted != null)
{
<a href="/Results/Details?nsUrl=@ViewBag.NSUrl&jobId=@job.RowKey">
<a href="/Results/Details?nsUrl=@Uri.EscapeDataString(ViewBag.NSUrl.ToString())&jobId=@job.RowKey">
@if (job.Failed)
{
<i class="fa fa-times-circle" style="color: tomato"></i> @:Error
Expand Down
2 changes: 1 addition & 1 deletion AutotuneWeb/Views/Results/Success.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@
<body style="font-family: Helvetica Neue,Helvetica,Arial,sans-serif; font-size: 14px; color: rgb(51, 51, 51);">
<h1>Autotune Results</h1>

<h2><a href="@Model.Job.NSUrl">@Model.Job.NSUrl</a></h2>
<h2><a href="@Uri.EscapeDataString(Model.Job.NSUrl.ToString())">@Model.Job.NSUrl</a></h2>
<p>Based on data entered between @(startDate.ToString("yyyy-MM-dd")) and @(endDate.ToString("yyyy-MM-dd"))</p>

@if (Model.Job.UAMAsBasal)
Expand Down
4 changes: 2 additions & 2 deletions AutotuneWeb/Views/Results/SuccessDetails.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@

<h1>Autotune Results</h1>

<h2><a href="@Model.Job.NSUrl">@Model.Job.NSUrl</a></h2>
<h2><a href="@Uri.EscapeDataString(Model.Job.NSUrl.ToString())">@Model.Job.NSUrl</a></h2>
<p>Based on data entered between @(startDate.ToString("yyyy-MM-dd")) and @(endDate.ToString("yyyy-MM-dd"))</p>

@if (Model.Job.UAMAsBasal)
Expand Down Expand Up @@ -124,6 +124,6 @@ else
@foreach (var log in (string[])ViewBag.Logs)
{
<p>
<a href="/Results/DownloadLog?nsUrl=@Model.Job.NSUrl&jobId=@Model.Job.RowKey&filename=@log" class="btn btn-default">Download Log</a>
<a href="/Results/DownloadLog?nsUrl=@Uri.EscapeDataString(Model.Job.NSUrl.ToString())&jobId=@Model.Job.RowKey&filename=@log" class="btn btn-default">Download Log</a>
</p>
}