Skip to content

Commit

Permalink
Download
Browse files Browse the repository at this point in the history
  • Loading branch information
Christoph Decker authored and Christoph Decker committed Oct 28, 2024
1 parent e3a2351 commit eb03a38
Show file tree
Hide file tree
Showing 6 changed files with 117 additions and 6 deletions.
19 changes: 18 additions & 1 deletion src/chdTour.App/Components/Pages/Settings.razor
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
@page "/settings"
@using chdTour.App.Implementations
@using chdTour.Contracts.Constants
@using chdTour.Persistence.EF
@inherits PageComponentBase<int,int>

@inject IDownloadService downloader


<ThemeModeButton />

<IconButton FAClass="download" OnClick="this.DownloadDBFile">Save Database File</IconButton>>


@code {
Expand All @@ -14,4 +17,18 @@
this.Title = PageTitleConstants.Settings;
return base.OnInitializedAsync();
}

private async Task DownloadDBFile()
{
var file = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "chdTour", $"{nameof(chdTourContext)}.db");
var file2 = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "chdTour", $"{nameof(chdTourContext)}_bak.db");

File.Copy(file, file2, true);

using Stream fs = File.OpenRead(file2);
using MemoryStream ms = new MemoryStream();
await fs.CopyToAsync(ms);
await downloader.DownloadFileFromStream("db.db", ms.ToArray());
}

}
1 change: 1 addition & 0 deletions src/chdTour.App/Extensions/DIExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ public static IServiceCollection AddUI(this IServiceCollection services, IConfig

services.AddMauiModalHandler();

services.AddTransient<IDownloadService, DownloadService>();
services.AddTransient<ICustomFilePicker, CustomFilePicker>();

services.AddSingleton<IVibrationHelper, VibrationHelper>();
Expand Down
38 changes: 38 additions & 0 deletions src/chdTour.App/Implementations/DownloadService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
using Microsoft.JSInterop;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace chdTour.App.Implementations
{
public class DownloadService : IDownloadService
{
private readonly IJSRuntime _jSRuntime;

public DownloadService(IJSRuntime jSRuntime)
{
this._jSRuntime = jSRuntime;
}

public async Task DownloadFileFromStream(string name, byte[] data)
{
var fileStream = GetFileStream(data);
var fileName = name;

using var streamRef = new DotNetStreamReference(stream: fileStream);
await this._jSRuntime.InvokeVoidAsync("downloadFileFromStream", fileName, streamRef);
}

private Stream GetFileStream(byte[] data)
{
var fileStream = new MemoryStream(data);
return fileStream;
}
}
public interface IDownloadService
{
Task DownloadFileFromStream(string name, byte[] data);
}
}
53 changes: 48 additions & 5 deletions src/chdTour.App/MainPage.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
#if ANDROID
using Android.Webkit;
using AndroidX.Activity;
using Bumptech.Glide.Load.Engine;
using chdTour.App.Platforms.Android;
#endif
using Microsoft.AspNetCore.Components.WebView;
using Microsoft.Maui.Platform;
using System.Text.RegularExpressions;

namespace chdTour.App
{
Expand Down Expand Up @@ -40,7 +43,6 @@ private partial void BlazorWebViewInitializing(object? sender, BlazorWebViewInit

private partial void BlazorWebViewInitialized(object? sender, BlazorWebViewInitializedEventArgs e)
{

}
#endif

Expand All @@ -56,20 +58,18 @@ private partial void BlazorWebViewInitialized(object? sender, BlazorWebViewIniti
private partial void BlazorWebViewInitializing(object? sender, BlazorWebViewInitializingEventArgs e)
{
}

private async Task CheckPermissions()
{

#if ANDROID
PermissionStatus statusNotification = await Permissions.RequestAsync<PermissionValidator>();
#endif
}


private partial void BlazorWebViewInitialized(object? sender, BlazorWebViewInitializedEventArgs e)
{
try
{
e.WebView.Download += this.WebView_DownloadAsync;

if (e.WebView.Context?.GetActivity() is not ComponentActivity activity)
{
throw new InvalidOperationException($"The permission-managing WebChromeClient requires that the current activity be a '{nameof(ComponentActivity)}'.");
Expand All @@ -87,6 +87,49 @@ private partial void BlazorWebViewInitialized(object? sender, BlazorWebViewIniti
}

}

private async void WebView_DownloadAsync(object sender, DownloadEventArgs e)
{
Uri uri = new Uri(e.Url);
await DownloadAsync(uri, e.Mimetype);
}


public static string DataUrl2Filename(string base64encodedstring)
{
var filename = Regex.Match(base64encodedstring, @"data:text/(?<filename>.+?);(?<type2>.+?),(?<data>.+)").Groups["filename"].Value;
return filename;
}
public static byte[] DataUrl2Bytes(string base64encodedstring)
{
var base64Data = Regex.Match(base64encodedstring, @"data:text/(?<type>.+?),(?<data>.+)").Groups["data"].Value;
var bytes = Convert.FromBase64String(base64Data);
return bytes;
}

#endif

private async Task DownloadAsync(Uri uri, string? mimeType = null)
{
var UploadPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "uploads");

string fileName = Path.GetFileName(uri.LocalPath);
var httpClient = new HttpClient();
var filePath = Path.Combine(UploadPath, fileName);
#if ANDROID
if (uri.Scheme == "data")
{
fileName = DataUrl2Filename(uri.OriginalString);
filePath = Path.Combine(UploadPath, $"{DateTime.Now.ToString("yyyy-MM-dd-hhmmss")}-{fileName}");
var bytes = DataUrl2Bytes(uri.OriginalString);
File.WriteAllBytes(filePath, bytes);
await DisplayAlert("Download", $"Fertig {fileName}", "OK");
return;
}
#endif
byte[] fileBytes = await httpClient.GetByteArrayAsync(uri);
File.WriteAllBytes(filePath, fileBytes);
await DisplayAlert("Download", $"Fertig {fileName}", "OK");
}
}
}
1 change: 1 addition & 0 deletions src/chdTour.App/wwwroot/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
<script src="_content/chd.UI.Base.Components/js/qrcode.js"></script>

<script src="_framework/blazor.webview.js" autostart="false"></script>
<script src="js/app.js" autostart="false"></script>

</body>

Expand Down
11 changes: 11 additions & 0 deletions src/chdTour.App/wwwroot/js/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
window.downloadFileFromStream = async (fileName, contentStreamReference) => {
const arrayBuffer = await contentStreamReference.arrayBuffer();
const blob = new Blob([arrayBuffer]);
const url = URL.createObjectURL(blob);
const anchorElement = document.createElement('a');
anchorElement.href = url;
anchorElement.download = fileName ?? '';
anchorElement.click();
anchorElement.remove();
URL.revokeObjectURL(url);
}

0 comments on commit eb03a38

Please sign in to comment.