Skip to content

Commit

Permalink
using HKCU for printer output path, starting file watcher when receiv…
Browse files Browse the repository at this point in the history
…ing first job and restart file watcher, if output path in registry has changed
  • Loading branch information
mba2811 committed Apr 14, 2021
1 parent 4a23f4f commit 2811a2e
Show file tree
Hide file tree
Showing 13 changed files with 94 additions and 46 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
namespace AmagnoVirtualPrinter.Agent.Core.Interfaces
using JetBrains.Annotations;

namespace AmagnoVirtualPrinter.Agent.Core.Interfaces
{
public interface IDirectoryHelper
{
string GetOutputDirectory(IExConfig config);
[NotNull]
string GetOutputDirectory([NotNull] IUserConfig config);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,6 @@ public interface IExConfig : IConfig
[NotNull]
Tuple<string, string> ResolvedPostconverter { get; }

/// <summary>
/// The full path of the output directory.
/// </summary>
[NotNull]
string ResolvedOutputDirectory { get; }

/// <summary>
/// An intermediate format which is read by the printer or similar.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,5 +43,12 @@ public interface IJobService
/// <param name="iniPath">The path to the ini file</param>
/// <returns><see cref="JobStatus"/></returns>
JobStatus ReadJobStatus(string iniPath);

/// <summary>
/// Gets the <see cref="SessionInfo" from ini file./>
/// </summary>
/// <param name="iniFile">The path to the ini file</param>
/// <returns><see cref="SessionInfo"/></returns>
SessionInfo GetSessionInfo(string iniFile);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,11 @@ public interface IUserConfig
/// <remarks>Intital value is PDF</remarks>
[NotNull]
string Format { get; }

/// <summary>
/// The full path of the output directory.
/// </summary>
[NotNull]
string ResolvedOutputDirectory { get; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@ public class RegistryConfig : IExConfig

public string Preconverter { get; set; }

public string OutputDirectory { get; set; }

public string FileNameMask { get; set; }

public short PrinterPort { get; set; }
Expand All @@ -29,11 +27,6 @@ public Tuple<string, string> ResolvedPostconverter
get { return GetResolvedArgs(Postconverter); }
}

public string ResolvedOutputDirectory
{
get { return string.IsNullOrWhiteSpace(OutputDirectory) ? "" : Path.GetFullPath(OutputDirectory); }
}

public IntermediateFormat IntermediateFormat { get; set; }

[NotNull]
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using AmagnoVirtualPrinter.Agent.Core.Interfaces;
using System.IO;
using AmagnoVirtualPrinter.Agent.Core.Interfaces;

namespace AmagnoVirtualPrinter.Agent.Core.Model
{
Expand All @@ -11,5 +12,12 @@ public class UserRegistryConfig : IUserConfig
public double? UserRenderDpi { get; set; }

public string Format { get; set; }

public string OutputDirectory { get; set; }

public string ResolvedOutputDirectory
{
get { return string.IsNullOrWhiteSpace(OutputDirectory) ? "" : Path.GetFullPath(OutputDirectory); }
}
}
}
6 changes: 4 additions & 2 deletions Common/AmagnoVirtualPrinter.Agent.Lib/Misc/JobFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,15 +66,17 @@ public IJob Create(string printerName, Stream stream)
try
{
var now = DateTime.Now;
var config = _registryRepository.GetRegistryConfig();
var root = _directoryHelper.GetOutputDirectory(config);

var jobInfo = GetCurrentPrintJobs(printerName).FirstOrDefault();
if (jobInfo == null)
{
throw new InvalidOperationException();
}

var session = GetCurrentSessions(jobInfo).FirstOrDefault();
var config = _registryRepository.GetRegistryConfig();
var userConfig = _registryRepository.GetUserRegistryConfig(session.Sid);
var root = _directoryHelper.GetOutputDirectory(userConfig);
var iniName = GenerateFileName(now, jobInfo.JobId, 0, config.FileNameMask, "ini");
var iniPath = Path.Combine(root, iniName);
var extension = GetRawFileExtension(config.IntermediateFormat);
Expand Down
2 changes: 1 addition & 1 deletion Common/AmagnoVirtualPrinter.Agent.Lib/Misc/JobProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ public void Process(IJob job, IUserConfig userConfig)
}

var targetFile = $"{Path.GetFileNameWithoutExtension(job.RawDataPath)}";
var config = _registryRepository.GetRegistryConfig();
var config = _registryRepository.GetUserRegistryConfig(job.SessionInfo.Sid);
var dir = _directoryHelper.GetOutputDirectory(config);
targetFile = Path.Combine(dir, targetFile);

Expand Down
10 changes: 6 additions & 4 deletions Common/AmagnoVirtualPrinter.Agent.Lib/Misc/JobService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -98,9 +98,11 @@ public JobStatus ReadJobStatus(string iniPath)

public void Finish(IJob job)
{
var config = _registryRepository.GetRegistryConfig();
WriteJobFinishIni(job.IniDataPath, config);
var userConfig = _registryRepository.GetUserRegistryConfig(job.SessionInfo.Sid);
WriteJobFinishIni(job.IniDataPath, userConfig);

var iniFile = Path.GetFullPath(job.IniDataPath);
var config = _registryRepository.GetRegistryConfig();
var post = config.ResolvedPostconverter;

_shell.Execute(job.JobInfo, job.SessionInfo, post.Item1, $"{post.Item2} \"{iniFile}\"");
Expand All @@ -122,7 +124,7 @@ private void WriteJobStartIni([NotNull]IJob job, PrintStatus status)
_shell.WriteIniEntry("Preconverting", "Status", status.ToIni(), job.IniDataPath);
}

private SessionInfo GetSessionInfo(string iniFile)
public SessionInfo GetSessionInfo(string iniFile)
{
var sessionInfo = new SessionInfo
{
Expand Down Expand Up @@ -152,7 +154,7 @@ private JobInfo GetJobInfo(string iniFile)
return jobInfo;
}

private void WriteJobFinishIni(string iniPath, [NotNull]IExConfig config)
private void WriteJobFinishIni(string iniPath, [NotNull]IUserConfig config)
{
const PrintStatus status = PrintStatus.Complete;
const PrintJobStatus spoolerState = PrintJobStatus.Printed;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,27 +54,37 @@ [NotNull]IDirectoryHelper directoryHelper

public void Dispose()
{
_watcher.Dispose();
_watcher?.Dispose();
_socket.Stop();
}

public void Init()
{
var config = GetRegistryConfig();
try
{
var config = GetRegistryConfig();
_socket = new TcpListener(IPAddress.Loopback, config.PrinterPort);
_socket.Start();
_socket.BeginAcceptTcpClient(HandleClient, _socket);

var dir = _directoryHelper.GetOutputDirectory(config);
LogDebug($"Waiting on {_socket.LocalEndpoint}...");
}
catch (Exception e)
{
LogError(e, "Error initializing tcp input printer");
}
}

private void StartFileWatcher([NotNull] string dir)
{
_watcher = new FileSystemWatcher(dir, "*.ini")
{
IncludeSubdirectories = false,
NotifyFilter = NotifyFilters.LastWrite,
EnableRaisingEvents = true
};
_watcher.Changed += IniFileChanged;
_socket = new TcpListener(IPAddress.Loopback, config.PrinterPort);
_socket.Start();
_socket.BeginAcceptTcpClient(HandleClient, _socket);

LogDebug($"Waiting on {_socket.LocalEndpoint}...");
LogDebug("Setting file watcher on folder @{dir}", dir);
}

private void HandleClient([NotNull]IAsyncResult ar)
Expand All @@ -101,6 +111,19 @@ private void HandleClient([NotNull]IAsyncResult ar)
socket.BeginAcceptTcpClient(HandleClient, ar.AsyncState);

_jobService.Start(job);

RestartFileWatcherIfNeeded(job.SessionInfo.Sid);
}

private void RestartFileWatcherIfNeeded(string sid)
{
var config = GetUserRegistryConfig(sid);
var dir = _directoryHelper.GetOutputDirectory(config);

if (_watcher == null || _watcher.Path != dir)
{
StartFileWatcher(dir);
}
}

private void IniFileChanged(object sender, [NotNull]FileSystemEventArgs e)
Expand All @@ -112,7 +135,8 @@ private void IniFileChanged(object sender, [NotNull]FileSystemEventArgs e)
}

var rawName = $"{Path.GetFileNameWithoutExtension(ini)}.ps";
var config = GetRegistryConfig();
var sessionInfo = _jobService.GetSessionInfo(ini);
var config = GetUserRegistryConfig(sessionInfo.Sid);
var dir = _directoryHelper.GetOutputDirectory(config);
var rawFile = Path.Combine(dir, rawName);
var status = _jobService.ReadStatus(ini);
Expand Down Expand Up @@ -195,6 +219,12 @@ private bool IsFileLocked(string filePath)
}
}

[NotNull]
private IUserConfig GetUserRegistryConfig(string sid)
{
return _registryRepository.GetUserRegistryConfig(sid);
}

[NotNull]
private IExConfig GetRegistryConfig()
{
Expand Down
11 changes: 8 additions & 3 deletions Common/AmagnoVirtualPrinter.Utils/DirectoryHelper.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
using System.IO;
using System;
using System.IO;
using AmagnoVirtualPrinter.Agent.Core.Interfaces;
using AmagnoVirtualPrinter.Agent.Core;

namespace AmagnoVirtualPrinter.Utils
{
public class DirectoryHelper : IDirectoryHelper
{
public string GetOutputDirectory(IExConfig config)
public string GetOutputDirectory(IUserConfig config)
{
if (config == null)
{
throw new ArgumentNullException(nameof(config));
}

if (string.IsNullOrWhiteSpace(config.ResolvedOutputDirectory))
{
var outputDir = Path.Combine(Path.GetTempPath(), "PrinterOutput");
Expand Down
4 changes: 1 addition & 3 deletions Common/AmagnoVirtualPrinter.Utils/RegistryRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@

using Microsoft.Win32;

using AmagnoVirtualPrinter.Agent.Core;

namespace AmagnoVirtualPrinter.Utils
{
public class RegistryRepository : IRegistryRepository
Expand Down Expand Up @@ -84,7 +82,6 @@ public IExConfig GetRegistryConfig()
using (var key = driver.OpenSubKey(Keys.CONVERTER_KEY))
{
CheckForNull(key, Keys.CONVERTER_KEY);
registryConfig.OutputDirectory = key.GetValue(KeyNames.OUTPUT_DIR).ToString();
registryConfig.FileNameMask = key.GetValue(KeyNames.FILE_NAME_MASK).ToString();
var portStr = key.GetValue(KeyNames.SERVER_PORT).ToString();
registryConfig.PrinterPort = short.TryParse(portStr, out var portVal) ? portVal : DefaultServerPort;
Expand Down Expand Up @@ -120,6 +117,7 @@ public IUserConfig GetUserRegistryConfig(string sid)
using (var converter = driver.OpenSubKey(Keys.CONVERTER_KEY))
{
CheckForNull(converter, Keys.CONVERTER_KEY);
userConfig.OutputDirectory = converter.GetValue(KeyNames.OUTPUT_DIR).ToString();

subKey = "Redirect";
using (var redirect = converter.OpenSubKey(subKey))
Expand Down
16 changes: 8 additions & 8 deletions Installer/AmagnoVirtualPrinter.WixSharpInstaller/Script.cs
Original file line number Diff line number Diff line change
Expand Up @@ -134,8 +134,8 @@ File printerServiceFile
@"%ProgramFiles%\AmagnoPrinterDriver\",
new DirFiles(feature, _filesDir + @"\*", s => !s.EndsWith(".exe")),
new File(new Id(SetupDriverId), feature, Path.Combine(_filesDir, Utils.Files.SETUP_DRIVER_EXE)),
new File(feature, Path.Combine(_filesDir, Utils.Files.DILIVERY_EXE)),
new File(feature, Path.Combine(_filesDir, Utils.Files.AGENT_PROGRESS_EXE)),
new File(feature, Path.Combine(_filesDir, Files.DILIVERY_EXE)),
new File(feature, Path.Combine(_filesDir, Files.AGENT_PROGRESS_EXE)),
printerServiceFile
)
};
Expand All @@ -154,7 +154,7 @@ private static Action[] CreateActions()
[NotNull]
private static IEnumerable<RegValue> CreateRegValues(Feature feature)
{
var converterKey = $@"{Utils.Keys.PRINTER_DRIVER_KEY32}\{Utils.Keys.CONVERTER_KEY}";
var converterKey = $@"{Keys.PRINTER_DRIVER_KEY32}\{Keys.CONVERTER_KEY}";

var regValues = new List<RegValue>();
regValues.AddRange(CreateLocalMachineValues(feature, converterKey));
Expand All @@ -166,10 +166,10 @@ private static IEnumerable<RegValue> CreateRegValues(Feature feature)
[NotNull]
private static IEnumerable<RegValue> CreateLocalMachineValues(Feature feature, string converterKey)
{
var postConverterKey = $@"{Utils.Keys.PRINTER_DRIVER_KEY32}\{Utils.Keys.POSTCONVERTER_KEY}";
var preConverterKey = $@"{Utils.Keys.PRINTER_DRIVER_KEY32}\{Utils.Keys.PRECONVERTER_KEY}";
var converterPdfKey = $@"{Utils.Keys.PRINTER_DRIVER_KEY32}\{Utils.Keys.CONVERTER_PDF_KEY}";
var converterTiffKey = $@"{Utils.Keys.PRINTER_DRIVER_KEY32}\{Utils.Keys.CONVERTER_TIFF_KEY}";
var postConverterKey = $@"{Keys.PRINTER_DRIVER_KEY32}\{Keys.POSTCONVERTER_KEY}";
var preConverterKey = $@"{Keys.PRINTER_DRIVER_KEY32}\{Keys.PRECONVERTER_KEY}";
var converterPdfKey = $@"{Keys.PRINTER_DRIVER_KEY32}\{Keys.CONVERTER_PDF_KEY}";
var converterTiffKey = $@"{Keys.PRINTER_DRIVER_KEY32}\{Keys.CONVERTER_TIFF_KEY}";
var registryHive = RegistryHive.LocalMachine;

var result = new List<RegValue>
Expand All @@ -180,7 +180,6 @@ private static IEnumerable<RegValue> CreateLocalMachineValues(Feature feature, s
new RegValue(feature, registryHive, converterKey, KeyNames.SHOW_PROGRESS, 1) {AttributesDefinition = "Type=integer"},
new RegValue(feature, registryHive, converterKey, KeyNames.PAGES_PER_SHEET, 1),
new RegValue(feature, registryHive, converterKey, KeyNames.FILE_NAME_MASK, "{yyyy}{MM}{DD}{hh}{mm}{ss}{job05}{page03}"),
new RegValue(feature, registryHive, converterKey, KeyNames.OUTPUT_DIR, string.Empty),
new RegValue(feature, registryHive, converterKey, KeyNames.FORMAT, "ps"),
new RegValue(feature, registryHive, converterPdfKey, KeyNames.ENABLED, 1) {AttributesDefinition = "Type=integer"},
new RegValue(feature, registryHive, converterPdfKey, KeyNames.MULTIPAGE, 1) {AttributesDefinition = "Type=integer"},
Expand Down Expand Up @@ -221,6 +220,7 @@ private static IEnumerable<RegValue> CreateCurrentUserValues(Feature feature, st
{
new RegValue(feature, registryHive, converterKey, KeyNames.PRINT_FORMAT, "PDF"),
new RegValue(feature, registryHive, converterKey, KeyNames.RENDER_DPI, 300) {AttributesDefinition = "Type=integer"},
new RegValue(feature, registryHive, converterKey, KeyNames.OUTPUT_DIR, string.Empty),
new RegValue(feature, registryHive, redirectKey, KeyNames.ENABLED, 1) {AttributesDefinition = "Type=integer"},
new RegValue(feature, registryHive, redirectKey, KeyNames.PRINTER, "")
};
Expand Down

0 comments on commit 2811a2e

Please sign in to comment.