Skip to content

Commit

Permalink
Upload function integrated.
Browse files Browse the repository at this point in the history
Button itself not yet optimally formatted.
  • Loading branch information
PhilippDex committed Jun 3, 2024
1 parent b793489 commit c75b5ba
Show file tree
Hide file tree
Showing 18 changed files with 380 additions and 157 deletions.
2 changes: 1 addition & 1 deletion NAPS2.Lib/Config/InternalDefaults.cs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ public static CommonConfig GetCommonConfig() =>
SQZClient = "Mandant",
SQZUserName = "Benutzername",
SQZPassword = "",
SQZClassID = "1"
SQZClassID = 1
},
RememberSqueezeSettings = false,

Expand Down
3 changes: 3 additions & 0 deletions NAPS2.Lib/EtoForms/Desktop/ImageListActions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -101,4 +101,7 @@ public async Task RotateFlip(double angle) =>
public Task SaveSelectedAsPdfOrImages() => _exportController.SavePdfOrImages(_imageList.Selection, _notify);
public Task EmailAllAsPdf() => _exportController.EmailPdf(_imageList.Images);
public Task EmailSelectedAsPdf() => _exportController.EmailPdf(_imageList.Selection);
//Squueze
public Task UploadAllToSqueeze() => _exportController.UploadPdfToSqueeze(_imageList.Images, _notify);
public Task UploadSelectedToSqueeze() => _exportController.UploadPdfToSqueeze(_imageList.Selection, _notify);
}
2 changes: 2 additions & 0 deletions NAPS2.Lib/EtoForms/Notifications/ISaveNotify.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,6 @@ public interface ISaveNotify
/// <param name="imageCount"></param>
/// <param name="path"></param>
void ImagesSaved(int imageCount, string path);
// Massage for Squeeze Upload
void PdfUploaded();
}
5 changes: 5 additions & 0 deletions NAPS2.Lib/EtoForms/Notifications/Notify.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,9 @@ public void UpdateAvailable(IUpdateChecker updateChecker, UpdateInfo update)
{
_notificationManager.Show(new UpdateNotification(updateChecker, update));
}
//Squeeze change
public void PdfUploaded()
{
_notificationManager.Show(new UploadedNotification(MiscResources.PdfUploaded));
}
}
4 changes: 4 additions & 0 deletions NAPS2.Lib/EtoForms/Notifications/SaveNotifyStub.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,8 @@ public void PdfSaved(string path)
public void ImagesSaved(int imageCount, string path)
{
}
//Squeeze change
public void PdfUploaded()
{
}
}
4 changes: 4 additions & 0 deletions NAPS2.Lib/EtoForms/Notifications/StubNotify.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,8 @@ public void OperationProgress(OperationProgress progress, IOperation op)
public void UpdateAvailable(IUpdateChecker updateChecker, UpdateInfo update)
{
}
//Squeeze change
public void PdfUploaded()
{
}
}
22 changes: 22 additions & 0 deletions NAPS2.Lib/EtoForms/Notifications/UploadedNotification.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NAPS2.EtoForms.Notifications;

public class UploadedNotification : NotificationModel
{
public UploadedNotification(string title)
{
Title = title;
}

public string Title { get; }

public override NotificationView CreateView()
{
return new UploadedNotificationView(this);
}
}
16 changes: 16 additions & 0 deletions NAPS2.Lib/EtoForms/Notifications/UploadedNotificationView.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NAPS2.EtoForms.Notifications;

public class UploadedNotificationView : LinkNotificationView
{
public UploadedNotificationView(UploadedNotification model)
: base(model, model.Title, "", "", "")
{
HideTimeout = HIDE_SHORT;
}
}
20 changes: 19 additions & 1 deletion NAPS2.Lib/EtoForms/Ui/DesktopCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public DesktopCommands(DesktopController desktopController, DesktopScanControlle
// Squeeze Icon Shortcut?
Squeeze = new ActionCommand(desktopController.Squeeze)
{
Text = UiStrings.Squeeze,
Text = UiStrings.UploadToSqueeze,
Image = iconProvider.GetIcon("SQZUpload")
};
SqueezeAll = new ActionCommand(_imageListActions.SelectAll)
Expand Down Expand Up @@ -334,6 +334,21 @@ public DesktopCommands(DesktopController desktopController, DesktopScanControlle
Text = UiStrings.Paste,
Shortcut = Application.Instance.CommonModifier | Keys.V
};
//Squeeze
UploadAllToSqueeze = new ActionCommand(imageListActions.UploadAllToSqueeze)
{
Text = UiStrings.UploadAllToSqueeze
};
UploadSelectedToSqueeze = new ActionCommand(imageListActions.UploadSelectedToSqueeze)
{
Text = UiStrings.UploadSelectedToSqueeze
};

UploadToSqueeze = new ActionCommand(imageListActions.UploadAllToSqueeze)
{
Text = UiStrings.UploadToSqueeze,
Image = iconProvider.GetIcon("SQZUpload")
};
}

public DesktopCommands WithSelection(Func<ListSelection<UiImage>> selectionFunc)
Expand Down Expand Up @@ -412,4 +427,7 @@ public DesktopCommands WithSelection(Func<ListSelection<UiImage>> selectionFunc)
public ActionCommand SelectAll { get; set; }
public ActionCommand Copy { get; set; }
public ActionCommand Paste { get; set; }
public ActionCommand UploadToSqueeze { get; set; }
public ActionCommand UploadAllToSqueeze { get; set; }
public ActionCommand UploadSelectedToSqueeze { get; set; }
}
10 changes: 3 additions & 7 deletions NAPS2.Lib/EtoForms/Ui/DesktopForm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,12 +69,8 @@ public DesktopForm(
_desktopSubFormController = desktopSubFormController;
Commands = commands;

if (!EtoPlatform.Current.IsMac)
{
// For Mac the menu shortcuts work without needing manual hooks
// Maybe at some point we can support custom assignment on Mac, though we'll need to fix Ctrl vs Command
_keyboardShortcuts.Assign(Commands);
}

_keyboardShortcuts.Assign(Commands);
CreateToolbarsAndMenus();
UpdateScanButton();
UpdateProfilesToolbar();
Expand Down Expand Up @@ -260,7 +256,7 @@ protected virtual void CreateToolbarsAndMenus()
// CreateToolbarSeparator();
// Anpassung für den Squeeze Button
if (!hiddenButtons.HasFlag(ToolbarButtons.Squeeze))
CreateToolbarButtonWithMenu(Commands.Squeeze, DesktopToolbarMenuType.Squeeze, new MenuProvider()
CreateToolbarButtonWithMenu(Commands.UploadToSqueeze, DesktopToolbarMenuType.Squeeze, new MenuProvider()
.Append(Commands.SqueezeAll)
.Append(Commands.SqueezeSelected)
.Separator()
Expand Down
7 changes: 4 additions & 3 deletions NAPS2.Lib/EtoForms/Ui/SqueezeSettingsForm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ internal class SqueezeSettingsForm : EtoDialogBase
private readonly TextBox _client = new();
private readonly TextBox _user = new();
private readonly PasswordBoxWithToggle _ownerPassword = new();
private readonly TextBox _class = new();
private readonly NumericStepper _class = new NumericStepper { MinValue = 1, MaxValue = int.MaxValue, Value = 1 };
private readonly CheckBox _keepSettings = new() { Text = UiStrings.RememberTheseSettings };
private readonly Button _restoreDefaults = new() { Text = UiStrings.RestoreDefaults };

Expand All @@ -27,6 +27,7 @@ public SqueezeSettingsForm(Naps2Config config, DesktopSubFormController desktopS
{
_desktopFormProvider = desktopFormProvider;
UpdateValues(Config);
//BuildLayout();

_restoreDefaults.Click += RestoreDefaults_Click;
}
Expand Down Expand Up @@ -70,7 +71,7 @@ private void UpdateValues(Naps2Config config)
_client.Text = config.Get(c => c.SqueezeSettings.SQZClient);
_user.Text = config.Get(c => c.SqueezeSettings.SQZUserName);
_ownerPassword.Text = config.Get(c => c.SqueezeSettings.SQZPassword);
_class.Text = config.Get(c => c.SqueezeSettings.SQZClassID);
_class.Value = config.Get(c => c.SqueezeSettings.SQZClassID);


void UpdateCheckbox(CheckBox checkBox, Expression<Func<CommonConfig, bool>> accessor)
Expand All @@ -96,7 +97,7 @@ private void Save()
SQZClient = _client.Text ?? "",
SQZUserName = _user.Text ?? "",
SQZPassword = _ownerPassword.Text ?? "",
SQZClassID = _class.Text ?? ""
SQZClassID = (int)_class.Value

};

Expand Down
87 changes: 86 additions & 1 deletion NAPS2.Lib/ImportExport/ExportController.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
using NAPS2.EtoForms;
using Eto.Forms;
using NAPS2.EtoForms;
using NAPS2.EtoForms.Notifications;
using NAPS2.EtoForms.Ui;
using NAPS2.ImportExport.Email;
using NAPS2.ImportExport.Images;
using NAPS2.Pdf;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Text;
using Eto.Forms;

Check warning on line 11 in NAPS2.Lib/ImportExport/ExportController.cs

View workflow job for this annotation

GitHub Actions / build (ubuntu-22.04)

The using directive for 'Eto.Forms' appeared previously in this namespace

Check warning on line 11 in NAPS2.Lib/ImportExport/ExportController.cs

View workflow job for this annotation

GitHub Actions / build (ubuntu-22.04)

The using directive for 'Eto.Forms' appeared previously in this namespace

Check warning on line 11 in NAPS2.Lib/ImportExport/ExportController.cs

View workflow job for this annotation

GitHub Actions / build (ubuntu-22.04)

The using directive for 'Eto.Forms' appeared previously in this namespace

Check warning on line 11 in NAPS2.Lib/ImportExport/ExportController.cs

View workflow job for this annotation

GitHub Actions / build (ubuntu-22.04)

The using directive for 'Eto.Forms' appeared previously in this namespace

Check warning on line 11 in NAPS2.Lib/ImportExport/ExportController.cs

View workflow job for this annotation

GitHub Actions / build (macos-14)

The using directive for 'Eto.Forms' appeared previously in this namespace

Check warning on line 11 in NAPS2.Lib/ImportExport/ExportController.cs

View workflow job for this annotation

GitHub Actions / build (macos-14)

The using directive for 'Eto.Forms' appeared previously in this namespace

namespace NAPS2.ImportExport;

Expand Down Expand Up @@ -243,4 +248,84 @@ private void MaybeDeleteAfterSaving(ICollection<UiImage> uiImages)
_imageList.Mutate(new ImageListMutation.DeleteSelected(), ListSelection.From(uiImages));
}
}
//Squeeze upload
public async Task<bool> UploadPdfToSqueeze(ICollection<UiImage> uiImages, ISaveNotify notify)
{
using var images = GetSnapshots(uiImages);
//var imageCount = images.Count;
if (!images.Any())
{
return false;
}

// Save the Pdf to a temporary file
var tempFolder = new DirectoryInfo(Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()));
tempFolder.Create();
string tempPdfPath = Path.Combine(tempFolder.FullName, "naps2Output.pdf");

try
{
if (!await DoSavePdf(images, notify, tempPdfPath))
{
return false;
}

// Upload the Pdf
var url = _config.Get(c => c.SqueezeSettings.SQZURL);
var client = _config.Get(c => c.SqueezeSettings.SQZClient);
var userName = _config.Get(c => c.SqueezeSettings.SQZUserName);
var password = _config.Get(c => c.SqueezeSettings.SQZPassword);
var batchClassId = _config.Get(c => c.SqueezeSettings.SQZClassID);
var (uploadSuccess, reasonPhrase) = await UploadPdfFile(tempPdfPath, url, userName, password, batchClassId);

if (uploadSuccess)
{
MaybeDeleteAfterSaving(uiImages);
notify.PdfUploaded();
return true;
}
else
{
MessageBox.Show($"Upload failed: {reasonPhrase}", MessageBoxType.Error);
return false;
}
}
finally
{
if (File.Exists(tempPdfPath))
{
File.Delete(tempPdfPath);
}
tempFolder.Delete(true);
}
}
// Squeeze Upload
private async Task<(bool IsSuccess, string? ReasonPhrase)> UploadPdfFile(string filePath, string url, string username, string password, int batchClassId)
{
try
{
using var httpClient = new HttpClient();
var authToken = Encoding.ASCII.GetBytes($"{username}:{password}");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(authToken));

using var form = new MultipartFormDataContent();
using var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
using var fileContent = new StreamContent(fileStream);

fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/pdf");
form.Add(fileContent, "file", Path.GetFileName(filePath));

// Add additional field here
form.Add(new StringContent(batchClassId.ToString()), "batchClassId");

HttpResponseMessage response = await httpClient.PostAsync(url, form);

return (response.IsSuccessStatusCode, response.ReasonPhrase);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, MessageBoxType.Error);
return (false, ex.Message);
}
}
}
2 changes: 2 additions & 0 deletions NAPS2.Lib/ImportExport/IExportController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,6 @@ public interface IExportController
Task<bool> SaveImages(ICollection<UiImage> uiImages, ISaveNotify notify);
Task<bool> SavePdfOrImages(ICollection<UiImage> uiImages, ISaveNotify notify);
Task<bool> EmailPdf(ICollection<UiImage> uiImages);
//Squeeze
Task<bool> UploadPdfToSqueeze(ICollection<UiImage> uiImages, ISaveNotify notify);
}
31 changes: 27 additions & 4 deletions NAPS2.Lib/ImportExport/Squeeze/SqueezeSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,32 @@

public record SqueezeSettings
{
public string SQZURL { get; init; } = "test";
public string SQZClient { get; init; } = "test";
public string SQZUserName { get; init; } = "test";
private string _sqzurl = "";
public string SQZURL
{
get
{
const string appendString = "/api/v2/documents";
// Ensure there is no trailing slash before appending
if (_sqzurl.EndsWith("/"))
{
_sqzurl = _sqzurl.TrimEnd('/');
}
if (!_sqzurl.EndsWith(appendString))
{
return _sqzurl + appendString;
}
return _sqzurl;
}
set
{
// Ensure the value does not end with a slash
_sqzurl = (value ?? "").TrimEnd('/');
}
}

public string SQZClient { get; init; } = "";
public string SQZUserName { get; init; } = "";
public string SQZPassword { get; init; } = "";
public string SQZClassID { get; init; } = "1";
public int SQZClassID { get; init; } = 1;
}
Loading

0 comments on commit c75b5ba

Please sign in to comment.