diff --git a/Agent.Installer.Win/Services/Logger.cs b/Agent.Installer.Win/Services/Logger.cs index ffaba451..59ab607c 100644 --- a/Agent.Installer.Win/Services/Logger.cs +++ b/Agent.Installer.Win/Services/Logger.cs @@ -15,7 +15,7 @@ namespace Remotely.Agent.Installer.Win.Services #if DEBUG CheckLogFileExists(); - File.AppendAllText(LogPath, $"{DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}\t[DEBUG]\t{message}{Environment.NewLine}"); + File.AppendAllText(LogPath, $"{DateTimeOffset.Now:yyyy-MM-dd HH:mm:ss.fff}\t[Debug]\t{message}{Environment.NewLine}"); #endif System.Diagnostics.Debug.WriteLine(message); @@ -30,7 +30,7 @@ namespace Remotely.Agent.Installer.Win.Services lock (WriteLock) { CheckLogFileExists(); - File.AppendAllText(LogPath, $"{DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}\t[INFO]\t{message}{Environment.NewLine}"); + File.AppendAllText(LogPath, $"{DateTimeOffset.Now:yyyy-MM-dd HH:mm:ss.fff}\t[Info]\t{message}{Environment.NewLine}"); Console.WriteLine(message); } } @@ -49,7 +49,7 @@ namespace Remotely.Agent.Installer.Win.Services while (exception != null) { - File.AppendAllText(LogPath, $"{DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}\t[ERROR]\t{exception?.Message}\t{exception?.StackTrace}\t{exception?.Source}{Environment.NewLine}"); + File.AppendAllText(LogPath, $"{DateTimeOffset.Now:yyyy-MM-dd HH:mm:ss.fff}\t[Error]\t{exception?.Message}\t{exception?.StackTrace}\t{exception?.Source}{Environment.NewLine}"); Console.WriteLine(exception.Message); exception = exception.InnerException; } diff --git a/Agent/Program.cs b/Agent/Program.cs index e63321ba..f5295eab 100644 --- a/Agent/Program.cs +++ b/Agent/Program.cs @@ -46,7 +46,6 @@ namespace Remotely.Agent serviceCollection.AddTransient(); serviceCollection.AddTransient(); serviceCollection.AddScoped(); - serviceCollection.AddScoped(); serviceCollection.AddSingleton(); serviceCollection.AddScoped(); serviceCollection.AddScoped(); diff --git a/Agent/Services/DeviceSocket.cs b/Agent/Services/DeviceSocket.cs index 76173dca..d994a5b8 100644 --- a/Agent/Services/DeviceSocket.cs +++ b/Agent/Services/DeviceSocket.cs @@ -13,6 +13,8 @@ using Remotely.Shared.Win32; using Microsoft.Extensions.DependencyInjection; using System.Text.Json; using System.Threading; +using Remotely.Shared.Utilities; +using Remotely.Shared.Enums; namespace Remotely.Agent.Services { @@ -45,52 +47,67 @@ namespace Remotely.Agent.Services private Uninstaller Uninstaller { get; } public async Task Connect() { - ConnectionInfo = ConfigService.GetConnectionInfo(); - - HubConnection = new HubConnectionBuilder() - .WithUrl(ConnectionInfo.Host + "/DeviceHub") - .Build(); - - RegisterMessageHandlers(); - - await HubConnection.StartAsync(); - - var device = await DeviceInformation.Create(ConnectionInfo.DeviceID, ConnectionInfo.OrganizationID); - - var result = await HubConnection.InvokeAsync("DeviceCameOnline", device); - - if (!result) + try { - // Orgnanization ID wasn't found, or this device is already connected. - // The above can be caused by temporary issues on the server. So we'll do - // nothing here and wait for it to get resolved. - Logger.Write("There was an issue registering with the server. The server might be undergoing maintenance, or the supplied organization ID might be incorrect."); - await Task.Delay(TimeSpan.FromMinutes(1)); - await HubConnection.StopAsync(); + ConnectionInfo = ConfigService.GetConnectionInfo(); + + HubConnection = new HubConnectionBuilder() + .WithUrl(ConnectionInfo.Host + "/DeviceHub") + .Build(); + + RegisterMessageHandlers(); + + await HubConnection.StartAsync(); + } + catch (Exception ex) + { + Logger.Write(ex, "Failed to connect to server. Internet connection may be unavailable.", EventType.Warning); return; } - if (string.IsNullOrWhiteSpace(ConnectionInfo.ServerVerificationToken)) + try { - IsServerVerified = true; - ConnectionInfo.ServerVerificationToken = Guid.NewGuid().ToString(); - await HubConnection.SendAsync("SetServerVerificationToken", ConnectionInfo.ServerVerificationToken); - ConfigService.SaveConnectionInfo(ConnectionInfo); - } - else - { - await HubConnection.SendAsync("SendServerVerificationToken"); - } + var device = await DeviceInformation.Create(ConnectionInfo.DeviceID, ConnectionInfo.OrganizationID); - if (ConfigService.TryGetDeviceSetupOptions(out DeviceSetupOptions options)) - { - await HubConnection.SendAsync("DeviceSetupOptions", options, ConnectionInfo.DeviceID); - } + var result = await HubConnection.InvokeAsync("DeviceCameOnline", device); - HeartbeatTimer?.Dispose(); - HeartbeatTimer = new System.Timers.Timer(TimeSpan.FromMinutes(5).TotalMilliseconds); - HeartbeatTimer.Elapsed += HeartbeatTimer_Elapsed; - HeartbeatTimer.Start(); + if (!result) + { + // Orgnanization ID wasn't found, or this device is already connected. + // The above can be caused by temporary issues on the server. So we'll do + // nothing here and wait for it to get resolved. + Logger.Write("There was an issue registering with the server. The server might be undergoing maintenance, or the supplied organization ID might be incorrect."); + await Task.Delay(TimeSpan.FromMinutes(1)); + await HubConnection.StopAsync(); + return; + } + + if (string.IsNullOrWhiteSpace(ConnectionInfo.ServerVerificationToken)) + { + IsServerVerified = true; + ConnectionInfo.ServerVerificationToken = Guid.NewGuid().ToString(); + await HubConnection.SendAsync("SetServerVerificationToken", ConnectionInfo.ServerVerificationToken); + ConfigService.SaveConnectionInfo(ConnectionInfo); + } + else + { + await HubConnection.SendAsync("SendServerVerificationToken"); + } + + if (ConfigService.TryGetDeviceSetupOptions(out DeviceSetupOptions options)) + { + await HubConnection.SendAsync("DeviceSetupOptions", options, ConnectionInfo.DeviceID); + } + + HeartbeatTimer?.Dispose(); + HeartbeatTimer = new System.Timers.Timer(TimeSpan.FromMinutes(5).TotalMilliseconds); + HeartbeatTimer.Elapsed += HeartbeatTimer_Elapsed; + HeartbeatTimer.Start(); + } + catch (Exception ex) + { + Logger.Write(ex, "Error starting websocket connection.", EventType.Error); + } } public async Task HandleConnection() diff --git a/Agent/Services/Logger.cs b/Agent/Services/Logger.cs deleted file mode 100644 index e5c3a26d..00000000 --- a/Agent/Services/Logger.cs +++ /dev/null @@ -1,85 +0,0 @@ -using System; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Runtime.InteropServices; - -namespace Remotely.Agent.Services -{ - public class Logger - { - private static string LogPath => Path.Combine(Path.GetTempPath(), "Remotely_Logs.log"); - private static object WriteLock { get; } = new object(); - public static void Debug(string message) - { - lock (WriteLock) - { -#if DEBUG - CheckLogFileExists(); - - File.AppendAllText(LogPath, $"{DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}\t[DEBUG]\t{message}{Environment.NewLine}"); - -#endif - System.Diagnostics.Debug.WriteLine(message); - } - - } - - public static void Write(string message) - { - try - { - lock (WriteLock) - { - CheckLogFileExists(); - File.AppendAllText(LogPath, $"{DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}\t[INFO]\t{message}{Environment.NewLine}"); - Console.WriteLine(message); - } - } - catch { } - } - - public static void Write(Exception ex) - { - lock (WriteLock) - { - try - { - CheckLogFileExists(); - - var exception = ex; - - while (exception != null) - { - File.AppendAllText(LogPath, $"{DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}\t[ERROR]\t{exception?.Message}\t{exception?.StackTrace}\t{exception?.Source}{Environment.NewLine}"); - Console.WriteLine(exception.Message); - exception = exception.InnerException; - } - } - catch { } - } - } - - private static void CheckLogFileExists() - { - if (!File.Exists(LogPath)) - { - File.Create(LogPath).Close(); - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - Process.Start("sudo", $"chmod 666 {LogPath}").WaitForExit(); - } - } - if (File.Exists(LogPath)) - { - var fi = new FileInfo(LogPath); - while (fi.Length > 1000000) - { - var content = File.ReadAllLines(LogPath); - File.WriteAllLines(LogPath, content.Skip(10)); - fi = new FileInfo(LogPath); - } - } - } - } -} diff --git a/Agent/Services/Updater.cs b/Agent/Services/Updater.cs index 5e6c8611..0402322e 100644 --- a/Agent/Services/Updater.cs +++ b/Agent/Services/Updater.cs @@ -86,8 +86,6 @@ namespace Remotely.Agent.Services Logger.Write("Service Updater: Version is current."); return; } - - File.WriteAllText("etag.txt", response.Headers["ETag"]); } catch (WebException ex) when ((ex.Response as HttpWebResponse).StatusCode == HttpStatusCode.NotModified) { @@ -137,7 +135,7 @@ namespace Remotely.Agent.Services serverUrl + $"/api/AgentUpdate/DownloadPackage/win-{platform}/{downloadId}", zipPath); - WebRequest.CreateHttp(serverUrl + $"/api/AgentUpdate/ClearDownload/{downloadId}").GetResponse(); + await WebRequest.CreateHttp(serverUrl + $"/api/AgentUpdate/ClearDownload/{downloadId}").GetResponseAsync(); foreach (var proc in Process.GetProcessesByName("Remotely_Installer")) @@ -145,6 +143,8 @@ namespace Remotely.Agent.Services proc.Kill(); } + Logger.Write("Launching installer to perform update."); + Process.Start(installerPath, $"-install -quiet -path {zipPath} -serverurl {serverUrl} -organizationid {connectionInfo.OrganizationID}"); } else if (EnvironmentHelper.IsLinux) @@ -159,13 +159,19 @@ namespace Remotely.Agent.Services serverUrl + $"/api/AgentUpdate/DownloadPackage/linux/{downloadId}", zipPath); - WebRequest.CreateHttp(serverUrl + $"/api/AgentUpdate/ClearDownload/{downloadId}").GetResponse(); + await WebRequest.CreateHttp(serverUrl + $"/api/AgentUpdate/ClearDownload/{downloadId}").GetResponseAsync(); + + Logger.Write("Launching installer to perform update."); Process.Start("sudo", $"chmod +x {installerPath}").WaitForExit(); Process.Start("sudo", $"{installerPath} --path {zipPath} & disown"); } } + catch (WebException ex) when (ex.Status == WebExceptionStatus.Timeout) + { + Logger.Write("Timed out while waiting to downloaod update.", Shared.Enums.EventType.Warning); + } catch (Exception ex) { Logger.Write(ex); diff --git a/Desktop.Win/App.xaml.cs b/Desktop.Win/App.xaml.cs index 6947e2a1..d5f02191 100644 --- a/Desktop.Win/App.xaml.cs +++ b/Desktop.Win/App.xaml.cs @@ -1,6 +1,7 @@ using Microsoft.Extensions.DependencyInjection; using Remotely.ScreenCast.Core; using Remotely.ScreenCast.Core.Services; +using Remotely.Shared.Utilities; using Remotely.Shared.Win32; using System; using System.Diagnostics; diff --git a/Desktop.Win/ViewModels/MainWindowViewModel.cs b/Desktop.Win/ViewModels/MainWindowViewModel.cs index 54ef8b29..8a82dbcb 100644 --- a/Desktop.Win/ViewModels/MainWindowViewModel.cs +++ b/Desktop.Win/ViewModels/MainWindowViewModel.cs @@ -19,6 +19,7 @@ using Remotely.ScreenCast.Core.Communication; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Remotely.Shared.Win32; +using Remotely.Shared.Utilities; namespace Remotely.Desktop.Win.ViewModels { diff --git a/ScreenCast.Core/Communication/CasterSocket.cs b/ScreenCast.Core/Communication/CasterSocket.cs index 9c3c56ce..9ac50bd9 100644 --- a/ScreenCast.Core/Communication/CasterSocket.cs +++ b/ScreenCast.Core/Communication/CasterSocket.cs @@ -10,6 +10,7 @@ using System.Net; using Remotely.ScreenCast.Core.Services; using Remotely.ScreenCast.Core.Interfaces; using Microsoft.Extensions.DependencyInjection; +using Remotely.Shared.Utilities; namespace Remotely.ScreenCast.Core.Communication { diff --git a/ScreenCast.Core/Communication/WebRtcSession.cs b/ScreenCast.Core/Communication/WebRtcSession.cs index f1f9acad..ed032f5c 100644 --- a/ScreenCast.Core/Communication/WebRtcSession.cs +++ b/ScreenCast.Core/Communication/WebRtcSession.cs @@ -3,6 +3,7 @@ using Microsoft.MixedReality.WebRTC; using Remotely.ScreenCast.Core.Services; using Remotely.Shared.Models; using Remotely.Shared.Models.RtcDtos; +using Remotely.Shared.Utilities; using System; using System.Collections.Generic; using System.Linq; diff --git a/ScreenCast.Core/Conductor.cs b/ScreenCast.Core/Conductor.cs index 8d29607a..9d6b8054 100644 --- a/ScreenCast.Core/Conductor.cs +++ b/ScreenCast.Core/Conductor.cs @@ -7,6 +7,7 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading.Tasks; +using Remotely.Shared.Utilities; namespace Remotely.ScreenCast.Core { diff --git a/ScreenCast.Core/Models/Viewer.cs b/ScreenCast.Core/Models/Viewer.cs index 4b88ac4e..6386a740 100644 --- a/ScreenCast.Core/Models/Viewer.cs +++ b/ScreenCast.Core/Models/Viewer.cs @@ -2,6 +2,7 @@ using Remotely.ScreenCast.Core.Interfaces; using Remotely.ScreenCast.Core.Services; using Remotely.Shared.Models; +using Remotely.Shared.Utilities; using System; using System.Drawing.Imaging; using System.Threading.Tasks; diff --git a/ScreenCast.Core/Services/IdleTimer.cs b/ScreenCast.Core/Services/IdleTimer.cs index fee7e967..9a5c6189 100644 --- a/ScreenCast.Core/Services/IdleTimer.cs +++ b/ScreenCast.Core/Services/IdleTimer.cs @@ -1,4 +1,5 @@ using Remotely.ScreenCast.Core.Models; +using Remotely.Shared.Utilities; using System; using System.Collections.Concurrent; using System.Timers; diff --git a/ScreenCast.Core/Services/RtcMessageHandler.cs b/ScreenCast.Core/Services/RtcMessageHandler.cs index 8a40e7a5..bfe29ec2 100644 --- a/ScreenCast.Core/Services/RtcMessageHandler.cs +++ b/ScreenCast.Core/Services/RtcMessageHandler.cs @@ -4,6 +4,7 @@ using Remotely.ScreenCast.Core.Interfaces; using Remotely.ScreenCast.Core.Models; using Remotely.Shared.Enums; using Remotely.Shared.Models.RtcDtos; +using Remotely.Shared.Utilities; using System; using System.Collections.Generic; using System.Dynamic; diff --git a/ScreenCast.Linux/Program.cs b/ScreenCast.Linux/Program.cs index f53d1ff2..1155f1bb 100644 --- a/ScreenCast.Linux/Program.cs +++ b/ScreenCast.Linux/Program.cs @@ -9,6 +9,7 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System.Linq; using Remotely.ScreenCast.Core.Models; +using Remotely.Shared.Utilities; namespace Remotely.ScreenCast.Linux { diff --git a/ScreenCast.Linux/Services/ClipboardServiceLinux.cs b/ScreenCast.Linux/Services/ClipboardServiceLinux.cs index c9deaedf..5e703f07 100644 --- a/ScreenCast.Linux/Services/ClipboardServiceLinux.cs +++ b/ScreenCast.Linux/Services/ClipboardServiceLinux.cs @@ -1,5 +1,6 @@ using Remotely.ScreenCast.Core.Interfaces; using Remotely.ScreenCast.Core.Services; +using Remotely.Shared.Utilities; using System; using System.Diagnostics; using System.IO; diff --git a/ScreenCast.Linux/Services/KeyboardMouseInputLinux.cs b/ScreenCast.Linux/Services/KeyboardMouseInputLinux.cs index 6fc70b3b..93d1ade6 100644 --- a/ScreenCast.Linux/Services/KeyboardMouseInputLinux.cs +++ b/ScreenCast.Linux/Services/KeyboardMouseInputLinux.cs @@ -3,6 +3,7 @@ using Remotely.ScreenCast.Core.Services; using Remotely.ScreenCast.Linux.X11Interop; using System; using Remotely.ScreenCast.Core.Models; +using Remotely.Shared.Utilities; namespace Remotely.ScreenCast.Linux.Services { diff --git a/ScreenCast.Linux/Services/ScreenCapturerLinux.cs b/ScreenCast.Linux/Services/ScreenCapturerLinux.cs index fef1b51f..505f01b7 100644 --- a/ScreenCast.Linux/Services/ScreenCapturerLinux.cs +++ b/ScreenCast.Linux/Services/ScreenCapturerLinux.cs @@ -1,6 +1,7 @@ using Remotely.ScreenCast.Core.Interfaces; using Remotely.ScreenCast.Core.Services; using Remotely.ScreenCast.Linux.X11Interop; +using Remotely.Shared.Utilities; using System; using System.Collections.Generic; using System.Drawing; diff --git a/ScreenCast.Win/Program.cs b/ScreenCast.Win/Program.cs index b2f679a7..3bd352b9 100644 --- a/ScreenCast.Win/Program.cs +++ b/ScreenCast.Win/Program.cs @@ -12,6 +12,7 @@ using Remotely.ScreenCast.Core.Communication; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Remotely.ScreenCast.Core.Models; +using Remotely.Shared.Utilities; namespace Remotely.ScreenCast.Win { diff --git a/ScreenCast.Win/Services/ClipboardServiceWin.cs b/ScreenCast.Win/Services/ClipboardServiceWin.cs index 3ed9e9cb..f55e563e 100644 --- a/ScreenCast.Win/Services/ClipboardServiceWin.cs +++ b/ScreenCast.Win/Services/ClipboardServiceWin.cs @@ -1,5 +1,6 @@ using Remotely.ScreenCast.Core.Interfaces; using Remotely.ScreenCast.Core.Services; +using Remotely.Shared.Utilities; using Remotely.Shared.Win32; using System; using System.Threading; diff --git a/ScreenCast.Win/Services/KeyboardMouseInputWin.cs b/ScreenCast.Win/Services/KeyboardMouseInputWin.cs index afb48bd4..5c45c242 100644 --- a/ScreenCast.Win/Services/KeyboardMouseInputWin.cs +++ b/ScreenCast.Win/Services/KeyboardMouseInputWin.cs @@ -10,6 +10,7 @@ using System.Collections.Concurrent; using System.Threading.Tasks; using Remotely.ScreenCast.Core; using System.Runtime.InteropServices; +using Remotely.Shared.Utilities; namespace Remotely.ScreenCast.Win.Services { diff --git a/ScreenCast.Win/Services/ScreenCapturerWin.cs b/ScreenCast.Win/Services/ScreenCapturerWin.cs index 95457b63..f721bf60 100644 --- a/ScreenCast.Win/Services/ScreenCapturerWin.cs +++ b/ScreenCast.Win/Services/ScreenCapturerWin.cs @@ -25,6 +25,7 @@ using Microsoft.Win32; using Remotely.ScreenCast.Core.Interfaces; using Remotely.ScreenCast.Core.Services; using Remotely.ScreenCast.Win.Models; +using Remotely.Shared.Utilities; using Remotely.Shared.Win32; using SharpDX; using SharpDX.Direct3D11; diff --git a/Server/API/AgentUpdateController.cs b/Server/API/AgentUpdateController.cs index b9f6033d..35d70d6f 100644 --- a/Server/API/AgentUpdateController.cs +++ b/Server/API/AgentUpdateController.cs @@ -2,6 +2,7 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Caching.Memory; using Remotely.Server.Services; +using Remotely.Shared.Enums; using System; using System.IO; using System.Net; @@ -13,7 +14,8 @@ namespace Remotely.Server.API [ApiController] public class AgentUpdateController : ControllerBase { - private static readonly MemoryCache downloadingAgents = new MemoryCache(new MemoryCacheOptions()); + private static readonly MemoryCache downloadingAgents = new MemoryCache(new MemoryCacheOptions() + { ExpirationScanFrequency = TimeSpan.FromSeconds(10) }); public AgentUpdateController(IWebHostEnvironment hostingEnv, @@ -33,6 +35,7 @@ namespace Remotely.Server.API [HttpGet("[action]/{downloadId}")] public ActionResult ClearDownload(string downloadId) { + DataService.WriteEvent($"Clearing download ID {downloadId}.", EventType.Debug, null); downloadingAgents.Remove(downloadId); return Ok(); } @@ -60,10 +63,12 @@ namespace Remotely.Server.API await Task.Delay(new Random().Next(100, 10000)); } var waitTime = DateTimeOffset.Now - startWait; - DataService.WriteEvent($"Download started after wait time of {waitTime}.", Shared.Models.EventType.Debug, string.Empty); downloadingAgents.Set(downloadId, string.Empty, TimeSpan.FromMinutes(10)); + DataService.WriteEvent($"Download started after wait time of {waitTime}. " + "" + + $"Current Downloads: {downloadingAgents.Count}. Max Allowed: {AppConfig.MaxConcurrentUpdates}", EventType.Debug, null); + byte[] fileBytes; string filePath; @@ -89,6 +94,7 @@ namespace Remotely.Server.API } catch (Exception ex) { + downloadingAgents.Remove(downloadId); DataService.WriteEvent(ex, null); return StatusCode((int)HttpStatusCode.InternalServerError); } diff --git a/Server/Areas/Identity/Pages/Account/Manage/ServerConfig.cshtml b/Server/Areas/Identity/Pages/Account/Manage/ServerConfig.cshtml index 6fa50ffc..d637a19f 100644 --- a/Server/Areas/Identity/Pages/Account/Manage/ServerConfig.cshtml +++ b/Server/Areas/Identity/Pages/Account/Manage/ServerConfig.cshtml @@ -12,6 +12,9 @@
+
+ Environment: @Model.Environment +

Application Settings

diff --git a/Server/Areas/Identity/Pages/Account/Manage/ServerConfig.cshtml.cs b/Server/Areas/Identity/Pages/Account/Manage/ServerConfig.cshtml.cs index 99720a4c..5daf8b34 100644 --- a/Server/Areas/Identity/Pages/Account/Manage/ServerConfig.cshtml.cs +++ b/Server/Areas/Identity/Pages/Account/Manage/ServerConfig.cshtml.cs @@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; using Remotely.Server.Services; using Remotely.Shared.Enums; using Remotely.Shared.Models; @@ -41,6 +42,7 @@ namespace Remotely.Server.Areas.Identity.Pages.Account.Manage public ConnectionStringsModel ConnectionStrings { get; set; } = new ConnectionStringsModel(); public bool IsServerAdmin { get; set; } + public string Environment { get; set; } [BindProperty] [Display(Name = "Server Admins")] @@ -57,6 +59,7 @@ namespace Remotely.Server.Areas.Identity.Pages.Account.Manage public async Task OnGet() { IsServerAdmin = (await UserManager.GetUserAsync(User)).IsServerAdmin; + Environment = HostEnv.EnvironmentName; if (!IsServerAdmin) { return Unauthorized(); @@ -104,11 +107,16 @@ namespace Remotely.Server.Areas.Identity.Pages.Account.Manage { string savePath; var prodSettings = HostEnv.ContentRootFileProvider.GetFileInfo("appsettings.Production.json"); + var stagingSettings = HostEnv.ContentRootFileProvider.GetFileInfo("appsettings.Staging.json"); var settings = HostEnv.ContentRootFileProvider.GetFileInfo("appsettings.json"); - if (prodSettings.Exists) + if (HostEnv.IsProduction() && prodSettings.Exists) { savePath = prodSettings.PhysicalPath; } + else if (HostEnv.IsStaging() && stagingSettings.Exists) + { + savePath = stagingSettings.PhysicalPath; + } else if (settings.Exists) { savePath = settings.PhysicalPath; diff --git a/Server/Pages/EditDevice.cshtml.cs b/Server/Pages/EditDevice.cshtml.cs index aaae78f0..e85d385f 100644 --- a/Server/Pages/EditDevice.cshtml.cs +++ b/Server/Pages/EditDevice.cshtml.cs @@ -6,6 +6,7 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.Mvc.Rendering; using Remotely.Server.Services; +using Remotely.Shared.Enums; namespace Remotely.Server.Pages { @@ -41,7 +42,7 @@ namespace Remotely.Server.Pages else if (!DataService.DoesUserHaveAccessToDevice(deviceID, user)) { DataService.WriteEvent($"Edit device attempted by unauthorized user. Device ID: {deviceID}. User Name: {user.UserName}.", - Remotely.Shared.Models.EventType.Warning, + EventType.Warning, targetDevice.OrganizationID); return Unauthorized(); } diff --git a/Server/Pages/Error.cshtml.cs b/Server/Pages/Error.cshtml.cs index eda5e639..31406484 100644 --- a/Server/Pages/Error.cshtml.cs +++ b/Server/Pages/Error.cshtml.cs @@ -3,6 +3,7 @@ using Remotely.Server.Services; using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; +using Remotely.Shared.Enums; namespace Remotely.Server.Pages { @@ -33,7 +34,7 @@ namespace Remotely.Server.Pages { var logEntry = new Remotely.Shared.Models.EventLog() { - EventType = Remotely.Shared.Models.EventType.Error, + EventType = EventType.Error, Message = error.Message, Source = error.Source, StackTrace = error.StackTrace, diff --git a/Server/Services/BrowserHub.cs b/Server/Services/BrowserHub.cs index 547518a5..10287537 100644 --- a/Server/Services/BrowserHub.cs +++ b/Server/Services/BrowserHub.cs @@ -8,6 +8,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using Remotely.Shared.Enums; namespace Remotely.Server.Services { diff --git a/Server/Services/DataService.cs b/Server/Services/DataService.cs index b7541e73..4e3d9d54 100644 --- a/Server/Services/DataService.cs +++ b/Server/Services/DataService.cs @@ -10,6 +10,7 @@ using Remotely.Shared.ViewModels.Organization; using Remotely.Server.Data; using Microsoft.Extensions.Hosting; using System.Threading.Tasks; +using Remotely.Shared.Enums; namespace Remotely.Server.Services { @@ -638,16 +639,25 @@ namespace Remotely.Server.Services public IEnumerable GetEventLogs(string userName, DateTimeOffset from, DateTimeOffset to) { - var orgID = RemotelyContext.Users - .FirstOrDefault(x => x.UserName == userName) - ?.OrganizationID; + var user = RemotelyContext.Users + .FirstOrDefault(x => x.UserName == userName); var fromDate = from.Date; var toDate = to.Date.AddDays(1); - return RemotelyContext.EventLogs - .Where(x => x.OrganizationID == orgID && x.TimeStamp >= fromDate && x.TimeStamp <= toDate) - .OrderByDescending(x => x.TimeStamp); + if (user.IsServerAdmin) + { + return RemotelyContext.EventLogs + .Where(x => x.TimeStamp >= fromDate && x.TimeStamp <= toDate) + .OrderByDescending(x => x.TimeStamp); + } + else + { + var orgID = user.OrganizationID; + return RemotelyContext.EventLogs + .Where(x => x.OrganizationID == orgID && x.TimeStamp >= fromDate && x.TimeStamp <= toDate) + .OrderByDescending(x => x.TimeStamp); + } } public int GetOrganizationCount() diff --git a/Server/Services/DeviceHub.cs b/Server/Services/DeviceHub.cs index dd6d2f0c..eec2ddbc 100644 --- a/Server/Services/DeviceHub.cs +++ b/Server/Services/DeviceHub.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Caching.Memory; +using Remotely.Shared.Enums; namespace Remotely.Server.Services { diff --git a/Shared/Enums/EventType.cs b/Shared/Enums/EventType.cs new file mode 100644 index 00000000..3d2d5daf --- /dev/null +++ b/Shared/Enums/EventType.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Remotely.Shared.Enums +{ + public enum EventType + { + Info = 0, + Error = 1, + Debug = 2, + Warning = 3 + } +} diff --git a/Shared/Models/EventLog.cs b/Shared/Models/EventLog.cs index 45c5a1ad..d8beb87d 100644 --- a/Shared/Models/EventLog.cs +++ b/Shared/Models/EventLog.cs @@ -1,4 +1,5 @@ -using System; +using Remotely.Shared.Enums; +using System; using System.ComponentModel.DataAnnotations; using System.Text.Json.Serialization; @@ -17,11 +18,4 @@ namespace Remotely.Shared.Models [JsonIgnore] public Organization Organization { get; set; } } - public enum EventType - { - Info = 0, - Error = 1, - Debug = 2, - Warning = 3 - } } diff --git a/ScreenCast.Core/Services/Logger.cs b/Shared/Utilities/Logger.cs similarity index 67% rename from ScreenCast.Core/Services/Logger.cs rename to Shared/Utilities/Logger.cs index 78c7fe25..79ca0336 100644 --- a/ScreenCast.Core/Services/Logger.cs +++ b/Shared/Utilities/Logger.cs @@ -1,10 +1,12 @@ -using System; +using Remotely.Shared.Enums; +using Remotely.Shared.Utilities; +using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; -namespace Remotely.ScreenCast.Core.Services +namespace Remotely.Shared.Utilities { public static class Logger { @@ -14,32 +16,33 @@ namespace Remotely.ScreenCast.Core.Services { lock (WriteLock) { -#if DEBUG - CheckLogFileExists(); + if (EnvironmentHelper.IsDebug) + { + CheckLogFileExists(); - File.AppendAllText(LogPath, $"{DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}\t[DEBUG]\t{message}{Environment.NewLine}"); - -#endif + File.AppendAllText(LogPath, $"{DateTimeOffset.Now:yyyy-MM-dd HH:mm:ss.fff}\t[Debug]\t{message}{Environment.NewLine}"); + } + System.Diagnostics.Debug.WriteLine(message); } } - public static void Write(string message) + public static void Write(string message, EventType eventType = EventType.Info) { try { lock (WriteLock) { CheckLogFileExists(); - File.AppendAllText(LogPath, $"{DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}\t[INFO]\t{message}{Environment.NewLine}"); + File.AppendAllText(LogPath, $"{DateTimeOffset.Now:yyyy-MM-dd HH:mm:ss.fff}\t[{eventType}]\t{message}{Environment.NewLine}"); Console.WriteLine(message); } } catch { } } - public static void Write(Exception ex) + public static void Write(Exception ex, EventType eventType = EventType.Error) { lock (WriteLock) { @@ -51,7 +54,7 @@ namespace Remotely.ScreenCast.Core.Services while (exception != null) { - File.AppendAllText(LogPath, $"{DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}\t[ERROR]\t{exception?.Message}\t{exception?.StackTrace}\t{exception?.Source}{Environment.NewLine}"); + File.AppendAllText(LogPath, $"{DateTimeOffset.Now:yyyy-MM-dd HH:mm:ss.fff}\t[{eventType}]\t{exception?.Message}\t{exception?.StackTrace}\t{exception?.Source}{Environment.NewLine}"); Console.WriteLine(exception.Message); exception = exception.InnerException; } @@ -60,6 +63,12 @@ namespace Remotely.ScreenCast.Core.Services } } + public static void Write(Exception ex, string message, EventType eventType = EventType.Error) + { + Write(message, eventType); + Write(ex, eventType); + } + private static void CheckLogFileExists() { if (!File.Exists(LogPath))