08-13-2024, 04:52 AM
// script "download with progress.cs"
string url = "https://www.quickmacros.com/quickmac.exe";
url = "https://www.libreautomate.com/LibreAutomateSetup.exe";
string file = folders.Downloads + pathname.getName(url);
try {
#if !true //standard dialog
if (!internet.http.Get(url, dontWait: true).Download(file)) { print.it("canceled"); return; }
#else //custom dialog
if (!internet.http.Get(url, dontWait: true).Download2(file)) { print.it("canceled"); return; }
#endif
}
catch (Exception e1) {
print.warning($"Failed to download. {e1.ToStringWithoutStack()}");
return;
}
print.it("downloaded");
static class MyInternetExt {
/// <inheritdoc cref="ExtInternet.Download(System.Net.Http.HttpResponseMessage, string, Action{ProgressArgs}, CancellationToken)"/>
public static bool Download2(this System.Net.Http.HttpResponseMessage t, string file, CancellationToken cancel = default) {
t.EnsureSuccessStatusCode();
long size = t.Content.Headers.ContentLength ?? 0;
string filename = pathname.getName(t.RequestMessage.RequestUri.AbsolutePath);
string _DialogText(long bytes) => $"{filename}\n{bytes / 1048576d:0.#} MB";
var pd = dialog.showProgress(size == 0, "TODO: change this text", _DialogText(size));
Action<ProgressArgs> progress = pa => {
if (!pd.IsOpen) { pd = null; throw new OperationCanceledException(); }
if (size > 0) pd.Send.Progress(pa.Percent);
else pd.Send.ChangeText2(_DialogText(pa.Current), resizeDialog: false);
};
try {
if (!t.Download(file, progress, cancel)) return false;
}
catch (OperationCanceledException) { return false; }
finally { pd?.Send.Close(); }
return true;
}
}