Skip to content

Commit 83e159e

Browse files
author
LAB02 Research
committed
2022.2.0
1 parent 4751d01 commit 83e159e

File tree

7 files changed

+198
-31
lines changed

7 files changed

+198
-31
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Text;
5+
using System.Threading.Tasks;
6+
7+
namespace HASS.Agent.AutoImport.Functions
8+
{
9+
public static class Extensions
10+
{
11+
/// <summary>
12+
/// Replaces all double backslashes into singles
13+
/// </summary>
14+
/// <param name="text"></param>
15+
/// <returns></returns>
16+
public static string RemoveBackslashEscaping(this string text) => text.Replace(@"\\", @"\");
17+
18+
/// <summary>
19+
/// Replaces all single backslashes into doubles
20+
/// </summary>
21+
/// <param name="text"></param>
22+
/// <returns></returns>
23+
public static string AddBackslashEscaping(this string text) => text.Replace(@"\", @"\\");
24+
}
25+
}

src/HASS.Agent.AutoImport/Functions/HelperFunctions.cs

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ internal static bool IsProcessActiveUnderCurrentUser(string process)
6868
}
6969
catch (Exception ex)
7070
{
71-
Log.Fatal(ex, "[PROCESS] [{process}] Error while determining if process is running: {msg}", process, ex.Message);
71+
Log.Fatal(ex, "[PROCESS] [{process}] Error while determining if process is running: {err}", process, ex.Message);
7272
return false;
7373
}
7474
}
@@ -110,9 +110,46 @@ internal static bool CloseProcess(string process)
110110
}
111111
catch (Exception ex)
112112
{
113-
Log.Fatal(ex, "[PROCESS] [{process}] Error while closing process: {msg}", process, ex.Message);
113+
Log.Fatal(ex, "[PROCESS] [{process}] Error while closing process: {err}", process, ex.Message);
114114
return false;
115115
}
116116
}
117+
118+
/// <summary>
119+
/// Attempts to parse the URL section of an .url file
120+
/// </summary>
121+
/// <param name="urlFile"></param>
122+
/// <returns></returns>
123+
internal static (bool parsed, string url) ParseUrl(string urlFile)
124+
{
125+
try
126+
{
127+
if (!File.Exists(urlFile))
128+
{
129+
Log.Error("[SHORTCUTS] Unable to parse, file not found");
130+
return (false, string.Empty);
131+
}
132+
133+
var lnkFile = File.ReadAllLines(urlFile);
134+
135+
var parsed = false;
136+
var url = string.Empty;
137+
138+
foreach (var line in lnkFile)
139+
{
140+
if (!line.StartsWith("URL=")) continue;
141+
142+
url = line.Split('=')[1].Trim();
143+
parsed = true;
144+
}
145+
146+
return (parsed, url);
147+
}
148+
catch (Exception ex)
149+
{
150+
Log.Fatal(ex, "[SHORTCUTS] Error while parsing: {err}", ex.Message);
151+
return (false, string.Empty);
152+
}
153+
}
117154
}
118155
}

src/HASS.Agent.AutoImport/HASS.Agent.AutoImport.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
<TargetFramework>net6.0-windows10.0.17763.0</TargetFramework>
66
<ImplicitUsings>enable</ImplicitUsings>
77
<Nullable>disable</Nullable>
8-
<Version>2022.1.0</Version>
8+
<Version>2022.2.0</Version>
99
<Authors>LAB02 Research</Authors>
1010
<Company>LAB02 Research</Company>
1111
<ApplicationIcon>hassagent.ico</ApplicationIcon>

src/HASS.Agent.AutoImport/Managers/HASSAgentManager.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,7 @@ internal static void Restart()
274274
// wait a bit
275275
Thread.Sleep(TimeSpan.FromSeconds(2));
276276
}
277+
else Log.Information("[HASS.Agent] Not currently running, no need to close");
277278

278279
// relaunch
279280
Log.Information("[HASS.Agent] Starting new instance ..");

src/HASS.Agent.AutoImport/Managers/SettingsManager.cs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ internal static (bool success, string error) LoadSettings()
4343
}
4444

4545
// attempt to parse
46-
var settings = JsonConvert.DeserializeObject<AppSettings>(settingsStr);
46+
var settings = JsonConvert.DeserializeObject<AppSettings>(settingsStr.AddBackslashEscaping());
4747
if (settings == null) return (false, "unable to parse settings file");
4848

4949
// check if the ShortcutSourceFolder exists
@@ -114,7 +114,7 @@ internal static (bool success, string error) LoadProcessedShortcuts()
114114
}
115115

116116
// attempt to parse
117-
var shortcuts = JsonConvert.DeserializeObject<List<ProcessedShortcut>>(shortcutsStr);
117+
var shortcuts = JsonConvert.DeserializeObject<List<ProcessedShortcut>>(shortcutsStr.AddBackslashEscaping());
118118
if (shortcuts == null) return (false, "unable to parse processedshortcuts file");
119119

120120
// done
@@ -136,8 +136,11 @@ private static void SaveDefaultSettings()
136136
// create the settings dir
137137
if (!Directory.Exists(Variables.SettingsPath)) Directory.CreateDirectory(Variables.SettingsPath);
138138

139+
// serialize the settings
140+
var serializedSettings = JsonConvert.SerializeObject(Variables.Settings, Formatting.Indented).RemoveBackslashEscaping();
141+
139142
// write the config
140-
File.WriteAllText(Variables.AppSettingsFile, JsonConvert.SerializeObject(Variables.Settings, Formatting.Indented));
143+
File.WriteAllText(Variables.AppSettingsFile, serializedSettings);
141144
}
142145
}
143146
}

src/HASS.Agent.AutoImport/Managers/ShortcutManager.cs

Lines changed: 125 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -31,39 +31,78 @@ internal static bool ProcessImport()
3131

3232
// get the shortcuts
3333
var searchOption = Variables.Settings.ShortcutSearchRecusively ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
34-
var shortcuts = Directory.EnumerateFiles(Variables.Settings.ShortcutSourceFolder, "*.lnk", searchOption)?.ToArray();
34+
var (lnkSuccesful, lnkNewFiles) = ProcessLnks(searchOption);
35+
var (urlSuccesful, urlNewFiles) = ProcessUrls(searchOption);
3536

36-
if (!shortcuts.Any())
37+
// new shortcuts?
38+
if (lnkNewFiles || urlNewFiles)
3739
{
38-
Log.Information("[SHORTCUTS] No shortcuts found, nothing to process");
39-
return true;
40+
// yep, store them
41+
var serializedShortcuts = JsonConvert.SerializeObject(Variables.ProcessedShortcuts, Formatting.Indented).RemoveBackslashEscaping();
42+
File.WriteAllText(Variables.ProcessedShortcutsFile, serializedShortcuts);
43+
44+
// restart hass.agent
45+
if (Variables.Settings.RestartHASSAgentOnNewItems) HASSAgentManager.Restart();
4046
}
47+
else Log.Information("[SHORTCUTS] No shortcuts found, nothing to process");
48+
49+
// done
50+
return lnkSuccesful && urlSuccesful;
51+
}
52+
catch (Exception ex)
53+
{
54+
Log.Fatal(ex, "[SHORTCUTS] Importing failed: {err}", ex.Message);
55+
return false;
56+
}
57+
}
58+
59+
private static (bool succesful, bool newFiles) ProcessLnks(SearchOption searchOption)
60+
{
61+
var newFiles = 0;
62+
63+
try
64+
{
65+
var shortcuts = Directory.EnumerateFiles(Variables.Settings.ShortcutSourceFolder, "*.lnk", searchOption)?.ToArray();
66+
if (!shortcuts.Any()) return (true, false);
4167

4268
// iterate them
43-
var newFiles = 0;
4469
foreach (var shortcutFile in shortcuts)
4570
{
71+
var fileName = Path.GetFileName(shortcutFile);
72+
4673
var shortcut = Shortcut.ReadFromFile(shortcutFile);
4774
if (shortcut == null)
4875
{
49-
Log.Warning("[SHORTCUTS] Shortcut parsing failed for: {file}", Path.GetFileName(shortcutFile));
76+
Log.Warning("[SHORTCUTS] Shortcut parsing failed for: {file}", fileName);
5077
continue;
5178
}
52-
79+
5380
if (Variables.ProcessedShortcuts.Any(x => x.LinkFile == shortcutFile))
5481
{
5582
// already know it, skip
5683
continue;
5784
}
5885

5986
var name = Path.GetFileNameWithoutExtension(shortcutFile);
60-
var target = shortcut.LinkTargetIDList.Path;
61-
var args = shortcut.StringData.CommandLineArguments;
62-
63-
Log.Information("[SHORTCUTS] New shortcut found, importing into HASS.Agent:");
87+
var target = shortcut.LinkTargetIDList?.Path ?? string.Empty;
88+
var args = shortcut.StringData?.CommandLineArguments ?? string.Empty;
89+
90+
if (string.IsNullOrWhiteSpace(target))
91+
{
92+
Log.Warning("[SHORTCUTS] Shortcut contained empty or no target: {file}", fileName);
93+
continue;
94+
}
95+
96+
Log.Information("[SHORTCUTS] New shortcut found, importing into HASS.Agent:\r\n");
97+
Log.Information("[SHORTCUTS] Type: {type}", ".lnk");
6498
Log.Information("[SHORTCUTS] Name: {name}", name);
65-
Log.Information("[SHORTCUTS] Target: {target}", target);
66-
if (!string.IsNullOrWhiteSpace(args)) Log.Information("[SHORTCUTS] Arguments: {args}", args);
99+
if (string.IsNullOrWhiteSpace(args)) Log.Information("[SHORTCUTS] Target: {target}\r\n", target);
100+
else
101+
{
102+
Log.Information("[SHORTCUTS] Target: {target}", target);
103+
Log.Information("[SHORTCUTS] Arguments: {args}\r\n", args);
104+
105+
}
67106

68107
var processedShortcut = new ProcessedShortcut
69108
{
@@ -74,7 +113,7 @@ internal static bool ProcessImport()
74113
CommandGuid = Guid.NewGuid().ToString(),
75114
SensorGuid = Guid.NewGuid().ToString()
76115
};
77-
116+
78117
var imported = HASSAgentManager.ProcessShortcut(processedShortcut);
79118
if (!imported)
80119
{
@@ -88,23 +127,85 @@ internal static bool ProcessImport()
88127
Log.Information("[SHORTCUTS] Succesfully imported\r\n");
89128
}
90129

91-
// new shortcuts?
92-
if (newFiles > 0)
130+
return (true, newFiles > 0);
131+
}
132+
catch (Exception ex)
133+
{
134+
return (false, newFiles > 0);
135+
}
136+
}
137+
138+
private static (bool succesful, bool newFiles) ProcessUrls(SearchOption searchOption)
139+
{
140+
var newFiles = 0;
141+
142+
try
143+
{
144+
var shortcuts = Directory.EnumerateFiles(Variables.Settings.ShortcutSourceFolder, "*.url", searchOption)?.ToArray();
145+
if (!shortcuts.Any()) return (true, false);
146+
147+
// iterate them
148+
foreach (var shortcutFile in shortcuts)
93149
{
94-
// yep, store them
95-
File.WriteAllText(Variables.ProcessedShortcutsFile, JsonConvert.SerializeObject(Variables.ProcessedShortcuts, Formatting.Indented));
150+
var fileName = Path.GetFileName(shortcutFile);
96151

97-
// restart hass.agent
98-
if (Variables.Settings.RestartHASSAgentOnNewItems) HASSAgentManager.Restart();
152+
var (parsed, target) = HelperFunctions.ParseUrl(shortcutFile);
153+
if (!parsed)
154+
{
155+
Log.Warning("[SHORTCUTS] Shortcut parsing failed for: {file}", fileName);
156+
continue;
157+
}
158+
159+
if (string.IsNullOrEmpty(target))
160+
{
161+
Log.Warning("[SHORTCUTS] Shortcut contained empty or no URL: {file}", fileName);
162+
continue;
163+
}
164+
165+
if (Variables.ProcessedShortcuts.Any(x => x.LinkFile == shortcutFile))
166+
{
167+
// already know it, skip
168+
continue;
169+
}
170+
171+
var name = Path.GetFileNameWithoutExtension(shortcutFile);
172+
173+
Log.Information("[SHORTCUTS] New shortcut found, importing into HASS.Agent:\r\n");
174+
Log.Information("[SHORTCUTS] Type: {type}", ".url");
175+
Log.Information("[SHORTCUTS] Name: {name}", name);
176+
Log.Information("[SHORTCUTS] Target: {target}\r\n", target);
177+
178+
// create the shortcut with the right command
179+
var processedShortcut = new ProcessedShortcut
180+
{
181+
LinkFile = shortcutFile,
182+
Name = name,
183+
Target = $"start {target}",
184+
CommandGuid = Guid.NewGuid().ToString(),
185+
SensorGuid = Guid.NewGuid().ToString()
186+
};
187+
188+
var imported = HASSAgentManager.ProcessShortcut(processedShortcut);
189+
if (!imported)
190+
{
191+
Log.Error("[SHORTCUTS] Import failed\r\n");
192+
continue;
193+
}
194+
195+
// restore the target
196+
processedShortcut.Target = target;
197+
198+
newFiles++;
199+
Variables.ProcessedShortcuts.Add(processedShortcut);
200+
201+
Log.Information("[SHORTCUTS] Succesfully imported\r\n");
99202
}
100203

101-
// done
102-
return true;
204+
return (true, newFiles > 0);
103205
}
104206
catch (Exception ex)
105207
{
106-
Log.Fatal(ex, "[SHORTCUTS] Importing failed: {err}", ex.Message);
107-
return false;
208+
return (false, newFiles > 0);
108209
}
109210
}
110211
}

src/HASS.Agent.AutoImport/Models/AppSettings.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ public AppSettings()
1919
public string ShortcutSourceFolder { get; set; } = string.Empty;
2020
public bool ShortcutSearchRecusively { get; set; } = false;
2121
public bool CreateCustomCommands { get; set; } = true;
22-
public bool CreateProcessActiveSensors { get; set; } = true;
22+
public bool CreateProcessActiveSensors { get; set; } = false;
2323
public bool RestartHASSAgentOnNewItems { get; set; } = true;
2424
}
2525
}

0 commit comments

Comments
 (0)