From 199f1bb9fd0f5ad433836f07a31ae7d2e604066f Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Fri, 8 Apr 2016 14:39:09 -0400 Subject: install 4.6 framework --- MediaBrowser.ServerApplication/MainStartup.cs | 90 +++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) (limited to 'MediaBrowser.ServerApplication/MainStartup.cs') diff --git a/MediaBrowser.ServerApplication/MainStartup.cs b/MediaBrowser.ServerApplication/MainStartup.cs index 87acd652e..5f528926b 100644 --- a/MediaBrowser.ServerApplication/MainStartup.cs +++ b/MediaBrowser.ServerApplication/MainStartup.cs @@ -256,6 +256,9 @@ namespace MediaBrowser.ServerApplication task = InstallVcredistIfNeeded(_appHost, _logger); Task.WaitAll(task); + task = InstallFrameworkV46IfNeeded(_logger); + Task.WaitAll(task); + SystemEvents.SessionEnding += SystemEvents_SessionEnding; SystemEvents.SessionSwitch += SystemEvents_SessionSwitch; @@ -573,6 +576,93 @@ namespace MediaBrowser.ServerApplication } } + private static async Task InstallFrameworkV46IfNeeded(ILogger logger) + { + bool installFrameworkV46 = false; + + try + { + using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32) + .OpenSubKey("SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full\\")) + { + if (ndpKey != null && ndpKey.GetValue("Release") != null) + { + if ((int)ndpKey.GetValue("Release") <= 393295) + { + //Found framework V4, but not yet V4.6 + installFrameworkV46 = true; + } + } + else + { + //Nothing found in the registry for V4 + installFrameworkV46 = true; + } + } + } + catch (Exception ex) + { + logger.ErrorException("Error getting .NET Framework version", ex); + } + + _logger.Info(".NET Framework 4.6 found: {0}", !installFrameworkV46); + + if (installFrameworkV46) + { + try + { + await InstallFrameworkV46().ConfigureAwait(false); + } + catch (Exception ex) + { + logger.ErrorException("Error installing .NET Framework version 4.6", ex); + } + } + } + + private static async Task InstallFrameworkV46() + { + var httpClient = _appHost.HttpClient; + + var tmp = await httpClient.GetTempFile(new HttpRequestOptions + { + Url = "https://github.com/MediaBrowser/Emby.Resources/raw/master/netframeworkV46/NDP46-KB3045560-Web.exe", + Progress = new Progress() + + }).ConfigureAwait(false); + + var exePath = Path.ChangeExtension(tmp, ".exe"); + File.Copy(tmp, exePath); + + var startInfo = new ProcessStartInfo + { + FileName = exePath, + + CreateNoWindow = true, + WindowStyle = ProcessWindowStyle.Hidden, + Verb = "runas", + ErrorDialog = false, + Arguments = "/q /norestart" + }; + + + _logger.Info("Running {0}", startInfo.FileName); + + using (var process = Process.Start(startInfo)) + { + process.WaitForExit(); + //process.ExitCode + /* + 0 --> Installation completed successfully. + 1602 --> The user canceled installation. + 1603 --> A fatal error occurred during installation. + 1641 --> A restart is required to complete the installation. This message indicates success. + 3010 --> A restart is required to complete the installation. This message indicates success. + 5100 --> The user's computer does not meet system requirements. + */ + } + } + private static async Task InstallVcredistIfNeeded(ApplicationHost appHost, ILogger logger) { try -- cgit v1.2.3 From baca0d6244185facf899c15ce39e5e858c6f7df3 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Mon, 11 Apr 2016 00:24:16 -0400 Subject: update scroll styles --- MediaBrowser.Controller/Entities/BaseItem.cs | 2 +- MediaBrowser.ServerApplication/MainStartup.cs | 1 + .../MediaBrowser.ServerApplication.csproj | 1 + .../Native/LnkShortcutHandler.cs | 402 +++++++++++++++++++++ 4 files changed, 405 insertions(+), 1 deletion(-) create mode 100644 MediaBrowser.ServerApplication/Native/LnkShortcutHandler.cs (limited to 'MediaBrowser.ServerApplication/MainStartup.cs') diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index 26aae285d..438c5cf23 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -686,7 +686,7 @@ namespace MediaBrowser.Controller.Entities get { var id = DisplayParentId; - if (!id.HasValue) + if (!id.HasValue || id.Value == Guid.Empty) { return null; } diff --git a/MediaBrowser.ServerApplication/MainStartup.cs b/MediaBrowser.ServerApplication/MainStartup.cs index 5f528926b..ac1b7ca99 100644 --- a/MediaBrowser.ServerApplication/MainStartup.cs +++ b/MediaBrowser.ServerApplication/MainStartup.cs @@ -217,6 +217,7 @@ namespace MediaBrowser.ServerApplication { var fileSystem = new WindowsFileSystem(new PatternsLogger(logManager.GetLogger("FileSystem"))); fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem)); + //fileSystem.AddShortcutHandler(new LnkShortcutHandler(fileSystem)); var nativeApp = new WindowsApp(fileSystem, _logger) { diff --git a/MediaBrowser.ServerApplication/MediaBrowser.ServerApplication.csproj b/MediaBrowser.ServerApplication/MediaBrowser.ServerApplication.csproj index f1a2915fe..26a9cd8b3 100644 --- a/MediaBrowser.ServerApplication/MediaBrowser.ServerApplication.csproj +++ b/MediaBrowser.ServerApplication/MediaBrowser.ServerApplication.csproj @@ -110,6 +110,7 @@ MainForm.cs + diff --git a/MediaBrowser.ServerApplication/Native/LnkShortcutHandler.cs b/MediaBrowser.ServerApplication/Native/LnkShortcutHandler.cs new file mode 100644 index 000000000..67d2e83f0 --- /dev/null +++ b/MediaBrowser.ServerApplication/Native/LnkShortcutHandler.cs @@ -0,0 +1,402 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices; +using System.Security; +using System.Text; +using System.Threading.Tasks; +using CommonIO; + +namespace MediaBrowser.ServerApplication.Native +{ + public class LnkShortcutHandler : IShortcutHandler + { + public string Extension + { + get { return ".lnk"; } + } + + public string Resolve(string shortcutPath) + { + var link = new ShellLink(); + ((IPersistFile)link).Load(shortcutPath, NativeMethods.STGM_READ); + // ((IShellLinkW)link).Resolve(hwnd, 0) + var sb = new StringBuilder(NativeMethods.MAX_PATH); + WIN32_FIND_DATA data; + ((IShellLinkW)link).GetPath(sb, sb.Capacity, out data, 0); + return sb.ToString(); + } + + public void Create(string shortcutPath, string targetPath) + { + throw new NotImplementedException(); + } + } + + /// + /// Class NativeMethods + /// + [SuppressUnmanagedCodeSecurity] + public static class NativeMethods + { + /// + /// The MA x_ PATH + /// + public const int MAX_PATH = 260; + /// + /// The MA x_ ALTERNATE + /// + public const int MAX_ALTERNATE = 14; + /// + /// The INVALI d_ HANDL e_ VALUE + /// + public static IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); + /// + /// The STG m_ READ + /// + public const uint STGM_READ = 0; + } + + /// + /// Struct FILETIME + /// + [StructLayout(LayoutKind.Sequential)] + public struct FILETIME + { + /// + /// The dw low date time + /// + public uint dwLowDateTime; + /// + /// The dw high date time + /// + public uint dwHighDateTime; + } + + /// + /// Struct WIN32_FIND_DATA + /// + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + public struct WIN32_FIND_DATA + { + /// + /// The dw file attributes + /// + public FileAttributes dwFileAttributes; + /// + /// The ft creation time + /// + public FILETIME ftCreationTime; + /// + /// The ft last access time + /// + public FILETIME ftLastAccessTime; + /// + /// The ft last write time + /// + public FILETIME ftLastWriteTime; + /// + /// The n file size high + /// + public int nFileSizeHigh; + /// + /// The n file size low + /// + public int nFileSizeLow; + /// + /// The dw reserved0 + /// + public int dwReserved0; + /// + /// The dw reserved1 + /// + public int dwReserved1; + + /// + /// The c file name + /// + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = NativeMethods.MAX_PATH)] + public string cFileName; + + /// + /// This will always be null when FINDEX_INFO_LEVELS = basic + /// + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = NativeMethods.MAX_ALTERNATE)] + public string cAlternate; + + /// + /// Gets or sets the path. + /// + /// The path. + public string Path { get; set; } + + /// + /// Returns a that represents this instance. + /// + /// A that represents this instance. + public override string ToString() + { + return Path ?? string.Empty; + } + } + + /// + /// Enum SLGP_FLAGS + /// + [Flags] + public enum SLGP_FLAGS + { + /// + /// Retrieves the standard short (8.3 format) file name + /// + SLGP_SHORTPATH = 0x1, + /// + /// Retrieves the Universal Naming Convention (UNC) path name of the file + /// + SLGP_UNCPRIORITY = 0x2, + /// + /// Retrieves the raw path name. A raw path is something that might not exist and may include environment variables that need to be expanded + /// + SLGP_RAWPATH = 0x4 + } + /// + /// Enum SLR_FLAGS + /// + [Flags] + public enum SLR_FLAGS + { + /// + /// Do not display a dialog box if the link cannot be resolved. When SLR_NO_UI is set, + /// the high-order word of fFlags can be set to a time-out value that specifies the + /// maximum amount of time to be spent resolving the link. The function returns if the + /// link cannot be resolved within the time-out duration. If the high-order word is set + /// to zero, the time-out duration will be set to the default value of 3,000 milliseconds + /// (3 seconds). To specify a value, set the high word of fFlags to the desired time-out + /// duration, in milliseconds. + /// + SLR_NO_UI = 0x1, + /// + /// Obsolete and no longer used + /// + SLR_ANY_MATCH = 0x2, + /// + /// If the link object has changed, update its path and list of identifiers. + /// If SLR_UPDATE is set, you do not need to call IPersistFile::IsDirty to determine + /// whether or not the link object has changed. + /// + SLR_UPDATE = 0x4, + /// + /// Do not update the link information + /// + SLR_NOUPDATE = 0x8, + /// + /// Do not execute the search heuristics + /// + SLR_NOSEARCH = 0x10, + /// + /// Do not use distributed link tracking + /// + SLR_NOTRACK = 0x20, + /// + /// Disable distributed link tracking. By default, distributed link tracking tracks + /// removable media across multiple devices based on the volume name. It also uses the + /// Universal Naming Convention (UNC) path to track remote file systems whose drive letter + /// has changed. Setting SLR_NOLINKINFO disables both types of tracking. + /// + SLR_NOLINKINFO = 0x40, + /// + /// Call the Microsoft Windows Installer + /// + SLR_INVOKE_MSI = 0x80 + } + + /// + /// The IShellLink interface allows Shell links to be created, modified, and resolved + /// + [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("000214F9-0000-0000-C000-000000000046")] + public interface IShellLinkW + { + /// + /// Retrieves the path and file name of a Shell link object + /// + /// The PSZ file. + /// The CCH max path. + /// The PFD. + /// The f flags. + void GetPath([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszFile, int cchMaxPath, out WIN32_FIND_DATA pfd, SLGP_FLAGS fFlags); + /// + /// Retrieves the list of item identifiers for a Shell link object + /// + /// The ppidl. + void GetIDList(out IntPtr ppidl); + /// + /// Sets the pointer to an item identifier list (PIDL) for a Shell link object. + /// + /// The pidl. + void SetIDList(IntPtr pidl); + /// + /// Retrieves the description string for a Shell link object + /// + /// Name of the PSZ. + /// Name of the CCH max. + void GetDescription([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName, int cchMaxName); + /// + /// Sets the description for a Shell link object. The description can be any application-defined string + /// + /// Name of the PSZ. + void SetDescription([MarshalAs(UnmanagedType.LPWStr)] string pszName); + /// + /// Retrieves the name of the working directory for a Shell link object + /// + /// The PSZ dir. + /// The CCH max path. + void GetWorkingDirectory([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszDir, int cchMaxPath); + /// + /// Sets the name of the working directory for a Shell link object + /// + /// The PSZ dir. + void SetWorkingDirectory([MarshalAs(UnmanagedType.LPWStr)] string pszDir); + /// + /// Retrieves the command-line arguments associated with a Shell link object + /// + /// The PSZ args. + /// The CCH max path. + void GetArguments([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszArgs, int cchMaxPath); + /// + /// Sets the command-line arguments for a Shell link object + /// + /// The PSZ args. + void SetArguments([MarshalAs(UnmanagedType.LPWStr)] string pszArgs); + /// + /// Retrieves the hot key for a Shell link object + /// + /// The pw hotkey. + void GetHotkey(out short pwHotkey); + /// + /// Sets a hot key for a Shell link object + /// + /// The w hotkey. + void SetHotkey(short wHotkey); + /// + /// Retrieves the show command for a Shell link object + /// + /// The pi show CMD. + void GetShowCmd(out int piShowCmd); + /// + /// Sets the show command for a Shell link object. The show command sets the initial show state of the window. + /// + /// The i show CMD. + void SetShowCmd(int iShowCmd); + /// + /// Retrieves the location (path and index) of the icon for a Shell link object + /// + /// The PSZ icon path. + /// The CCH icon path. + /// The pi icon. + void GetIconLocation([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszIconPath, + int cchIconPath, out int piIcon); + /// + /// Sets the location (path and index) of the icon for a Shell link object + /// + /// The PSZ icon path. + /// The i icon. + void SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] string pszIconPath, int iIcon); + /// + /// Sets the relative path to the Shell link object + /// + /// The PSZ path rel. + /// The dw reserved. + void SetRelativePath([MarshalAs(UnmanagedType.LPWStr)] string pszPathRel, int dwReserved); + /// + /// Attempts to find the target of a Shell link, even if it has been moved or renamed + /// + /// The HWND. + /// The f flags. + void Resolve(IntPtr hwnd, SLR_FLAGS fFlags); + /// + /// Sets the path and file name of a Shell link object + /// + /// The PSZ file. + void SetPath([MarshalAs(UnmanagedType.LPWStr)] string pszFile); + + } + + /// + /// Interface IPersist + /// + [ComImport, Guid("0000010c-0000-0000-c000-000000000046"), + InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + public interface IPersist + { + /// + /// Gets the class ID. + /// + /// The p class ID. + [PreserveSig] + void GetClassID(out Guid pClassID); + } + + /// + /// Interface IPersistFile + /// + [ComImport, Guid("0000010b-0000-0000-C000-000000000046"), + InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + public interface IPersistFile : IPersist + { + /// + /// Gets the class ID. + /// + /// The p class ID. + new void GetClassID(out Guid pClassID); + /// + /// Determines whether this instance is dirty. + /// + [PreserveSig] + int IsDirty(); + + /// + /// Loads the specified PSZ file name. + /// + /// Name of the PSZ file. + /// The dw mode. + [PreserveSig] + void Load([In, MarshalAs(UnmanagedType.LPWStr)] + string pszFileName, uint dwMode); + + /// + /// Saves the specified PSZ file name. + /// + /// Name of the PSZ file. + /// if set to true [remember]. + [PreserveSig] + void Save([In, MarshalAs(UnmanagedType.LPWStr)] string pszFileName, + [In, MarshalAs(UnmanagedType.Bool)] bool remember); + + /// + /// Saves the completed. + /// + /// Name of the PSZ file. + [PreserveSig] + void SaveCompleted([In, MarshalAs(UnmanagedType.LPWStr)] string pszFileName); + + /// + /// Gets the cur file. + /// + /// Name of the PPSZ file. + [PreserveSig] + void GetCurFile([In, MarshalAs(UnmanagedType.LPWStr)] string ppszFileName); + } + + // CLSID_ShellLink from ShlGuid.h + /// + /// Class ShellLink + /// + [ + ComImport, + Guid("00021401-0000-0000-C000-000000000046") + ] + public class ShellLink + { + } +} -- cgit v1.2.3 From c94706d6eec63f705eb69ec87a4887f314986dc0 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Fri, 22 Apr 2016 12:12:20 -0400 Subject: update shutdown --- .../HttpServer/HttpListenerHost.cs | 17 +++++++++++++++++ .../ServerManager/ServerManager.cs | 19 +++++++++++++++++++ MediaBrowser.ServerApplication/MainStartup.cs | 5 +++-- 3 files changed, 39 insertions(+), 2 deletions(-) (limited to 'MediaBrowser.ServerApplication/MainStartup.cs') diff --git a/MediaBrowser.Server.Implementations/HttpServer/HttpListenerHost.cs b/MediaBrowser.Server.Implementations/HttpServer/HttpListenerHost.cs index 25463b660..c5cb810e5 100644 --- a/MediaBrowser.Server.Implementations/HttpServer/HttpListenerHost.cs +++ b/MediaBrowser.Server.Implementations/HttpServer/HttpListenerHost.cs @@ -179,6 +179,11 @@ namespace MediaBrowser.Server.Implementations.HttpServer private void OnWebSocketConnecting(WebSocketConnectingEventArgs args) { + if (_disposed) + { + return; + } + if (WebSocketConnecting != null) { WebSocketConnecting(this, args); @@ -187,6 +192,11 @@ namespace MediaBrowser.Server.Implementations.HttpServer private void OnWebSocketConnected(WebSocketConnectEventArgs args) { + if (_disposed) + { + return; + } + if (WebSocketConnected != null) { WebSocketConnected(this, args); @@ -331,6 +341,13 @@ namespace MediaBrowser.Server.Implementations.HttpServer var httpRes = httpReq.Response; + if (_disposed) + { + httpRes.StatusCode = 503; + httpRes.Close(); + return Task.FromResult(true); + } + var operationName = httpReq.OperationName; var localPath = url.LocalPath; diff --git a/MediaBrowser.Server.Implementations/ServerManager/ServerManager.cs b/MediaBrowser.Server.Implementations/ServerManager/ServerManager.cs index 8719f5448..33d106916 100644 --- a/MediaBrowser.Server.Implementations/ServerManager/ServerManager.cs +++ b/MediaBrowser.Server.Implementations/ServerManager/ServerManager.cs @@ -71,6 +71,8 @@ namespace MediaBrowser.Server.Implementations.ServerManager /// The web socket listeners. private readonly List _webSocketListeners = new List(); + private bool _disposed; + /// /// Initializes a new instance of the class. /// @@ -143,6 +145,11 @@ namespace MediaBrowser.Server.Implementations.ServerManager /// The instance containing the event data. void HttpServer_WebSocketConnected(object sender, WebSocketConnectEventArgs e) { + if (_disposed) + { + return; + } + var connection = new WebSocketConnection(e.WebSocket, e.Endpoint, _jsonSerializer, _logger) { OnReceive = ProcessWebSocketMessageReceived, @@ -164,6 +171,11 @@ namespace MediaBrowser.Server.Implementations.ServerManager /// The result. private async void ProcessWebSocketMessageReceived(WebSocketMessageInfo result) { + if (_disposed) + { + return; + } + //_logger.Debug("Websocket message received: {0}", result.MessageType); var tasks = _webSocketListeners.Select(i => Task.Run(async () => @@ -244,6 +256,11 @@ namespace MediaBrowser.Server.Implementations.ServerManager throw new ArgumentNullException("dataFunction"); } + if (_disposed) + { + throw new ObjectDisposedException(GetType().Name); + } + cancellationToken.ThrowIfCancellationRequested(); var connectionsList = connections.Where(s => s.State == WebSocketState.Open).ToList(); @@ -301,6 +318,8 @@ namespace MediaBrowser.Server.Implementations.ServerManager /// public void Dispose() { + _disposed = true; + Dispose(true); GC.SuppressFinalize(this); } diff --git a/MediaBrowser.ServerApplication/MainStartup.cs b/MediaBrowser.ServerApplication/MainStartup.cs index ac1b7ca99..f83c7d545 100644 --- a/MediaBrowser.ServerApplication/MainStartup.cs +++ b/MediaBrowser.ServerApplication/MainStartup.cs @@ -555,9 +555,10 @@ namespace MediaBrowser.ServerApplication private static void ShutdownWindowsApplication() { - _logger.Info("Calling Application.Exit"); - Application.Exit(); + //_logger.Info("Calling Application.Exit"); + //Application.Exit(); + _logger.Info("Calling Environment.Exit"); Environment.Exit(0); _logger.Info("Calling ApplicationTaskCompletionSource.SetResult"); -- cgit v1.2.3 From 9807448fce0bba3b1aaf9fcb249efc5efe7b3146 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sat, 23 Apr 2016 14:38:36 -0400 Subject: update sleep prevention --- .../People/MovieDbPersonProvider.cs | 2 +- MediaBrowser.Server.Mono/Native/BaseMonoApp.cs | 5 +++ .../EntryPoints/KeepServerAwake.cs | 31 ++++++++--------- MediaBrowser.Server.Startup.Common/INativeApp.cs | 2 ++ MediaBrowser.ServerApplication/MainStartup.cs | 5 +++ MediaBrowser.ServerApplication/Native/Standby.cs | 40 ++++++++++++++-------- .../Native/WindowsApp.cs | 8 ++++- MediaBrowser.ServerApplication/ServerNotifyIcon.cs | 7 +++- 8 files changed, 67 insertions(+), 33 deletions(-) (limited to 'MediaBrowser.ServerApplication/MainStartup.cs') diff --git a/MediaBrowser.Providers/People/MovieDbPersonProvider.cs b/MediaBrowser.Providers/People/MovieDbPersonProvider.cs index 2b37d0462..40ce6ad47 100644 --- a/MediaBrowser.Providers/People/MovieDbPersonProvider.cs +++ b/MediaBrowser.Providers/People/MovieDbPersonProvider.cs @@ -97,7 +97,7 @@ namespace MediaBrowser.Providers.People var requestCount = _requestCount; - if (requestCount >= 30) + if (requestCount >= 40) { //_logger.Debug("Throttling Tmdb people"); diff --git a/MediaBrowser.Server.Mono/Native/BaseMonoApp.cs b/MediaBrowser.Server.Mono/Native/BaseMonoApp.cs index 6d19c3275..72c191121 100644 --- a/MediaBrowser.Server.Mono/Native/BaseMonoApp.cs +++ b/MediaBrowser.Server.Mono/Native/BaseMonoApp.cs @@ -69,6 +69,11 @@ namespace MediaBrowser.Server.Mono.Native } + public void AllowSystemStandby() + { + + } + public List GetAssembliesWithParts() { var list = new List(); diff --git a/MediaBrowser.Server.Startup.Common/EntryPoints/KeepServerAwake.cs b/MediaBrowser.Server.Startup.Common/EntryPoints/KeepServerAwake.cs index 20d4c6b2a..dbfd6f4e8 100644 --- a/MediaBrowser.Server.Startup.Common/EntryPoints/KeepServerAwake.cs +++ b/MediaBrowser.Server.Startup.Common/EntryPoints/KeepServerAwake.cs @@ -27,28 +27,27 @@ namespace MediaBrowser.Server.Startup.Common.EntryPoints _timer = new PeriodicTimer(obj => { var now = DateTime.UtcNow; - if (_sessionManager.Sessions.Any(i => (now - i.LastActivityDate).TotalMinutes < 15)) + var nativeApp = ((ApplicationHost)_appHost).NativeApp; + + try + { + if (_sessionManager.Sessions.Any(i => (now - i.LastActivityDate).TotalMinutes < 15)) + { + nativeApp.PreventSystemStandby(); + } + else + { + nativeApp.AllowSystemStandby(); + } + } + catch (Exception ex) { - KeepAlive(); + _logger.ErrorException("Error resetting system standby timer", ex); } }, null, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5)); } - private void KeepAlive() - { - var nativeApp = ((ApplicationHost)_appHost).NativeApp; - - try - { - nativeApp.PreventSystemStandby(); - } - catch (Exception ex) - { - _logger.ErrorException("Error resetting system standby timer", ex); - } - } - public void Dispose() { if (_timer != null) diff --git a/MediaBrowser.Server.Startup.Common/INativeApp.cs b/MediaBrowser.Server.Startup.Common/INativeApp.cs index 121d4192e..00f987d3c 100644 --- a/MediaBrowser.Server.Startup.Common/INativeApp.cs +++ b/MediaBrowser.Server.Startup.Common/INativeApp.cs @@ -93,6 +93,8 @@ namespace MediaBrowser.Server.Startup.Common /// void PreventSystemStandby(); + void AllowSystemStandby(); + /// /// Gets the power management. /// diff --git a/MediaBrowser.ServerApplication/MainStartup.cs b/MediaBrowser.ServerApplication/MainStartup.cs index f83c7d545..4dc8a47f5 100644 --- a/MediaBrowser.ServerApplication/MainStartup.cs +++ b/MediaBrowser.ServerApplication/MainStartup.cs @@ -321,6 +321,11 @@ namespace MediaBrowser.ServerApplication } } + public static void Invoke(Action action) + { + _serverNotifyIcon.Invoke(action); + } + /// /// Starts the service. /// diff --git a/MediaBrowser.ServerApplication/Native/Standby.cs b/MediaBrowser.ServerApplication/Native/Standby.cs index 274c72b25..919709538 100644 --- a/MediaBrowser.ServerApplication/Native/Standby.cs +++ b/MediaBrowser.ServerApplication/Native/Standby.cs @@ -1,4 +1,5 @@ -using System.Runtime.InteropServices; +using System; +using System.Runtime.InteropServices; namespace MediaBrowser.ServerApplication.Native { @@ -7,11 +8,33 @@ namespace MediaBrowser.ServerApplication.Native /// public static class Standby { - public static void PreventSystemStandby() + public static void PreventSleepAndMonitorOff() { - SystemHelper.ResetStandbyTimer(); + NativeMethods.SetThreadExecutionState(NativeMethods.ES_CONTINUOUS | NativeMethods.ES_SYSTEM_REQUIRED | NativeMethods.ES_DISPLAY_REQUIRED); } + public static void PreventSleep() + { + NativeMethods.SetThreadExecutionState(NativeMethods.ES_CONTINUOUS | NativeMethods.ES_SYSTEM_REQUIRED); + } + + // Clear EXECUTION_STATE flags to allow the system to sleep and turn off monitor normally + public static void AllowSleep() + { + NativeMethods.SetThreadExecutionState(NativeMethods.ES_CONTINUOUS); + } + + internal static class NativeMethods + { + // Import SetThreadExecutionState Win32 API and necessary flags + [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] + public static extern uint SetThreadExecutionState(uint esFlags); + public const uint ES_CONTINUOUS = 0x80000000; + public const uint ES_SYSTEM_REQUIRED = 0x00000001; + public const uint ES_DISPLAY_REQUIRED = 0x00000002; + } + + [Flags] internal enum EXECUTION_STATE : uint { ES_NONE = 0, @@ -21,16 +44,5 @@ namespace MediaBrowser.ServerApplication.Native ES_AWAYMODE_REQUIRED = 0x00000040, ES_CONTINUOUS = 0x80000000 } - - public class SystemHelper - { - [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] - static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags); - - public static void ResetStandbyTimer() - { - EXECUTION_STATE es = SetThreadExecutionState(EXECUTION_STATE.ES_SYSTEM_REQUIRED); - } - } } } diff --git a/MediaBrowser.ServerApplication/Native/WindowsApp.cs b/MediaBrowser.ServerApplication/Native/WindowsApp.cs index 146a4372b..ff5fe4d84 100644 --- a/MediaBrowser.ServerApplication/Native/WindowsApp.cs +++ b/MediaBrowser.ServerApplication/Native/WindowsApp.cs @@ -5,6 +5,7 @@ using MediaBrowser.ServerApplication.Networking; using System.Collections.Generic; using System.IO; using System.Reflection; +using System.Windows.Forms; using CommonIO; using MediaBrowser.Controller.Power; using MediaBrowser.Server.Startup.Common.FFMpeg; @@ -134,7 +135,12 @@ namespace MediaBrowser.ServerApplication.Native public void PreventSystemStandby() { - Standby.PreventSystemStandby(); + MainStartup.Invoke(Standby.PreventSleep); + } + + public void AllowSystemStandby() + { + MainStartup.Invoke(Standby.AllowSleep); } public IPowerManagement GetPowerManagement() diff --git a/MediaBrowser.ServerApplication/ServerNotifyIcon.cs b/MediaBrowser.ServerApplication/ServerNotifyIcon.cs index 673c6cddd..2146274af 100644 --- a/MediaBrowser.ServerApplication/ServerNotifyIcon.cs +++ b/MediaBrowser.ServerApplication/ServerNotifyIcon.cs @@ -36,10 +36,15 @@ namespace MediaBrowser.ServerApplication set { Action act = () => notifyIcon1.Visible = false; - contextMenuStrip1.Invoke(act); + Invoke(act); } } + public void Invoke(Action action) + { + contextMenuStrip1.Invoke(action); + } + public ServerNotifyIcon(ILogManager logManager, IServerApplicationHost appHost, IServerConfigurationManager configurationManager, -- cgit v1.2.3 From ebf0eeb3bd68cd5532e965167936537223521658 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sat, 23 Apr 2016 23:03:49 -0400 Subject: update browser launcher --- MediaBrowser.Controller/IServerApplicationHost.cs | 4 +- MediaBrowser.Server.Mono/Native/BaseMonoApp.cs | 5 ++ .../ApplicationHost.cs | 5 ++ .../Browser/BrowserLauncher.cs | 59 ++++++---------------- .../EntryPoints/StartupWizard.cs | 2 +- MediaBrowser.Server.Startup.Common/INativeApp.cs | 2 + MediaBrowser.ServerApplication/MainStartup.cs | 2 +- .../Native/WindowsApp.cs | 41 ++++++++++++++- MediaBrowser.ServerApplication/ServerNotifyIcon.cs | 8 +-- 9 files changed, 76 insertions(+), 52 deletions(-) (limited to 'MediaBrowser.ServerApplication/MainStartup.cs') diff --git a/MediaBrowser.Controller/IServerApplicationHost.cs b/MediaBrowser.Controller/IServerApplicationHost.cs index e4eecec18..65eed1a23 100644 --- a/MediaBrowser.Controller/IServerApplicationHost.cs +++ b/MediaBrowser.Controller/IServerApplicationHost.cs @@ -12,7 +12,7 @@ namespace MediaBrowser.Controller public interface IServerApplicationHost : IApplicationHost { event EventHandler HasUpdateAvailableChanged; - + /// /// Gets the system info. /// @@ -86,5 +86,7 @@ namespace MediaBrowser.Controller /// The ip address. /// System.String. string GetLocalApiUrl(IPAddress ipAddress); + + void LaunchUrl(string url); } } diff --git a/MediaBrowser.Server.Mono/Native/BaseMonoApp.cs b/MediaBrowser.Server.Mono/Native/BaseMonoApp.cs index 72c191121..fbfef9a34 100644 --- a/MediaBrowser.Server.Mono/Native/BaseMonoApp.cs +++ b/MediaBrowser.Server.Mono/Native/BaseMonoApp.cs @@ -222,6 +222,11 @@ namespace MediaBrowser.Server.Mono.Native return GetInfo(Environment); } + public void LaunchUrl(string url) + { + throw new NotImplementedException(); + } + public static FFMpegInstallInfo GetInfo(NativeEnvironment environment) { var info = new FFMpegInstallInfo(); diff --git a/MediaBrowser.Server.Startup.Common/ApplicationHost.cs b/MediaBrowser.Server.Startup.Common/ApplicationHost.cs index 93dbe2945..2e2b42ba2 100644 --- a/MediaBrowser.Server.Startup.Common/ApplicationHost.cs +++ b/MediaBrowser.Server.Startup.Common/ApplicationHost.cs @@ -1404,5 +1404,10 @@ namespace MediaBrowser.Server.Startup.Common return externalDns; } } + + public void LaunchUrl(string url) + { + NativeApp.LaunchUrl(url); + } } } diff --git a/MediaBrowser.Server.Startup.Common/Browser/BrowserLauncher.cs b/MediaBrowser.Server.Startup.Common/Browser/BrowserLauncher.cs index a4504f25a..db48d1110 100644 --- a/MediaBrowser.Server.Startup.Common/Browser/BrowserLauncher.cs +++ b/MediaBrowser.Server.Startup.Common/Browser/BrowserLauncher.cs @@ -15,87 +15,58 @@ namespace MediaBrowser.Server.Startup.Common.Browser /// /// The page. /// The app host. - /// The logger. - public static void OpenDashboardPage(string page, IServerApplicationHost appHost, ILogger logger) + public static void OpenDashboardPage(string page, IServerApplicationHost appHost) { var url = appHost.GetLocalApiUrl("localhost") + "/web/" + page; - OpenUrl(url, logger); + OpenUrl(appHost, url); } /// /// Opens the community. /// - /// The logger. - public static void OpenCommunity(ILogger logger) + public static void OpenCommunity(IServerApplicationHost appHost) { - OpenUrl("http://emby.media/community", logger); + OpenUrl(appHost, "http://emby.media/community"); } /// /// Opens the web client. /// /// The app host. - /// The logger. - public static void OpenWebClient(IServerApplicationHost appHost, ILogger logger) + public static void OpenWebClient(IServerApplicationHost appHost) { - OpenDashboardPage("index.html", appHost, logger); + OpenDashboardPage("index.html", appHost); } /// /// Opens the dashboard. /// /// The app host. - /// The logger. - public static void OpenDashboard(IServerApplicationHost appHost, ILogger logger) + public static void OpenDashboard(IServerApplicationHost appHost) { - OpenDashboardPage("dashboard.html", appHost, logger); + OpenDashboardPage("dashboard.html", appHost); } /// /// Opens the URL. /// /// The URL. - /// The logger. - private static void OpenUrl(string url, ILogger logger) + private static void OpenUrl(IServerApplicationHost appHost, string url) { - var process = new Process - { - StartInfo = new ProcessStartInfo - { - FileName = url - }, - - EnableRaisingEvents = true, - }; - - process.Exited += ProcessExited; - try { - process.Start(); + appHost.LaunchUrl(url); + } + catch (NotImplementedException) + { + } catch (Exception ex) { - logger.ErrorException("Error launching url: {0}", ex, url); - - Console.WriteLine("Error launching url: {0}", ex.Message); + Console.WriteLine("Error launching url: " + url); Console.WriteLine(ex.Message); - -//#if !__MonoCS__ -// System.Windows.Forms.MessageBox.Show("There was an error launching your web browser. Please check your default browser settings."); -//#endif } } - - /// - /// Processes the exited. - /// - /// The sender. - /// The instance containing the event data. - private static void ProcessExited(object sender, EventArgs e) - { - ((Process)sender).Dispose(); - } } } diff --git a/MediaBrowser.Server.Startup.Common/EntryPoints/StartupWizard.cs b/MediaBrowser.Server.Startup.Common/EntryPoints/StartupWizard.cs index 854fa44c1..f9d173c59 100644 --- a/MediaBrowser.Server.Startup.Common/EntryPoints/StartupWizard.cs +++ b/MediaBrowser.Server.Startup.Common/EntryPoints/StartupWizard.cs @@ -46,7 +46,7 @@ namespace MediaBrowser.Server.Startup.Common.EntryPoints /// private void LaunchStartupWizard() { - BrowserLauncher.OpenDashboardPage("wizardstart.html", _appHost, _logger); + BrowserLauncher.OpenDashboardPage("wizardstart.html", _appHost); } /// diff --git a/MediaBrowser.Server.Startup.Common/INativeApp.cs b/MediaBrowser.Server.Startup.Common/INativeApp.cs index 00f987d3c..c0758b47f 100644 --- a/MediaBrowser.Server.Startup.Common/INativeApp.cs +++ b/MediaBrowser.Server.Startup.Common/INativeApp.cs @@ -102,5 +102,7 @@ namespace MediaBrowser.Server.Startup.Common IPowerManagement GetPowerManagement(); FFMpegInstallInfo GetFfmpegInstallInfo(); + + void LaunchUrl(string url); } } diff --git a/MediaBrowser.ServerApplication/MainStartup.cs b/MediaBrowser.ServerApplication/MainStartup.cs index 4dc8a47f5..454c415a1 100644 --- a/MediaBrowser.ServerApplication/MainStartup.cs +++ b/MediaBrowser.ServerApplication/MainStartup.cs @@ -317,7 +317,7 @@ namespace MediaBrowser.ServerApplication { if (e.Reason == SessionSwitchReason.SessionLogon) { - BrowserLauncher.OpenDashboard(_appHost, _logger); + BrowserLauncher.OpenDashboard(_appHost); } } diff --git a/MediaBrowser.ServerApplication/Native/WindowsApp.cs b/MediaBrowser.ServerApplication/Native/WindowsApp.cs index ff5fe4d84..10cd59436 100644 --- a/MediaBrowser.ServerApplication/Native/WindowsApp.cs +++ b/MediaBrowser.ServerApplication/Native/WindowsApp.cs @@ -1,14 +1,17 @@ -using MediaBrowser.Common.Net; +using System; +using MediaBrowser.Common.Net; using MediaBrowser.Model.Logging; using MediaBrowser.Server.Startup.Common; using MediaBrowser.ServerApplication.Networking; using System.Collections.Generic; +using System.Diagnostics; using System.IO; using System.Reflection; using System.Windows.Forms; using CommonIO; using MediaBrowser.Controller.Power; using MediaBrowser.Server.Startup.Common.FFMpeg; +using OperatingSystem = MediaBrowser.Server.Startup.Common.OperatingSystem; namespace MediaBrowser.ServerApplication.Native { @@ -162,6 +165,42 @@ namespace MediaBrowser.ServerApplication.Native return info; } + public void LaunchUrl(string url) + { + var process = new Process + { + StartInfo = new ProcessStartInfo + { + FileName = url + }, + + EnableRaisingEvents = true, + }; + + process.Exited += ProcessExited; + + try + { + process.Start(); + } + catch (Exception ex) + { + _logger.ErrorException("Error launching url: {0}", ex, url); + + throw; + } + } + + /// + /// Processes the exited. + /// + /// The sender. + /// The instance containing the event data. + private static void ProcessExited(object sender, EventArgs e) + { + ((Process)sender).Dispose(); + } + private string[] GetDownloadUrls() { switch (Environment.SystemArchitecture) diff --git a/MediaBrowser.ServerApplication/ServerNotifyIcon.cs b/MediaBrowser.ServerApplication/ServerNotifyIcon.cs index 2146274af..27816db5a 100644 --- a/MediaBrowser.ServerApplication/ServerNotifyIcon.cs +++ b/MediaBrowser.ServerApplication/ServerNotifyIcon.cs @@ -168,7 +168,7 @@ namespace MediaBrowser.ServerApplication void notifyIcon1_DoubleClick(object sender, EventArgs e) { - BrowserLauncher.OpenDashboard(_appHost, _logger); + BrowserLauncher.OpenDashboard(_appHost); } private void LocalizeText() @@ -199,17 +199,17 @@ namespace MediaBrowser.ServerApplication void cmdBrowse_Click(object sender, EventArgs e) { - BrowserLauncher.OpenWebClient(_appHost, _logger); + BrowserLauncher.OpenWebClient(_appHost); } void cmdCommunity_Click(object sender, EventArgs e) { - BrowserLauncher.OpenCommunity(_logger); + BrowserLauncher.OpenCommunity(_appHost); } void cmdConfigure_Click(object sender, EventArgs e) { - BrowserLauncher.OpenDashboard(_appHost, _logger); + BrowserLauncher.OpenDashboard(_appHost); } void cmdRestart_Click(object sender, EventArgs e) -- cgit v1.2.3 From c7e99f424eb394f4a3b1e8d4239642c4a3b69cfd Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Wed, 27 Apr 2016 21:59:38 -0400 Subject: update standby --- MediaBrowser.ServerApplication/MainStartup.cs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) (limited to 'MediaBrowser.ServerApplication/MainStartup.cs') diff --git a/MediaBrowser.ServerApplication/MainStartup.cs b/MediaBrowser.ServerApplication/MainStartup.cs index 454c415a1..dc61dcda8 100644 --- a/MediaBrowser.ServerApplication/MainStartup.cs +++ b/MediaBrowser.ServerApplication/MainStartup.cs @@ -273,11 +273,13 @@ namespace MediaBrowser.ServerApplication } private static ServerNotifyIcon _serverNotifyIcon; + private static TaskScheduler _mainTaskScheduler; private static void ShowTrayIcon() { //Application.EnableVisualStyles(); //Application.SetCompatibleTextRenderingDefault(false); _serverNotifyIcon = new ServerNotifyIcon(_appHost.LogManager, _appHost, _appHost.ServerConfigurationManager, _appHost.LocalizationManager); + _mainTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext(); Application.Run(); } @@ -323,7 +325,14 @@ namespace MediaBrowser.ServerApplication public static void Invoke(Action action) { - _serverNotifyIcon.Invoke(action); + if (_isRunningAsService) + { + action(); + } + else + { + Task.Factory.StartNew(action, CancellationToken.None, TaskCreationOptions.None, _mainTaskScheduler ?? TaskScheduler.Current); + } } /// -- cgit v1.2.3 From abb3c8a1d39fb33bb35eef1c36e702d3d9da0280 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Mon, 23 May 2016 23:06:51 -0400 Subject: rework transitions --- MediaBrowser.ServerApplication/MainStartup.cs | 12 ++++++------ MediaBrowser.WebDashboard/Api/PackageCreator.cs | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) (limited to 'MediaBrowser.ServerApplication/MainStartup.cs') diff --git a/MediaBrowser.ServerApplication/MainStartup.cs b/MediaBrowser.ServerApplication/MainStartup.cs index dc61dcda8..706e9c8ed 100644 --- a/MediaBrowser.ServerApplication/MainStartup.cs +++ b/MediaBrowser.ServerApplication/MainStartup.cs @@ -254,7 +254,7 @@ namespace MediaBrowser.ServerApplication { Task.WaitAll(task); - task = InstallVcredistIfNeeded(_appHost, _logger); + task = InstallVcredist2013IfNeeded(_appHost, _logger); Task.WaitAll(task); task = InstallFrameworkV46IfNeeded(_logger); @@ -679,7 +679,7 @@ namespace MediaBrowser.ServerApplication } } - private static async Task InstallVcredistIfNeeded(ApplicationHost appHost, ILogger logger) + private static async Task InstallVcredist2013IfNeeded(ApplicationHost appHost, ILogger logger) { try { @@ -693,7 +693,7 @@ namespace MediaBrowser.ServerApplication try { - await InstallVcredist().ConfigureAwait(false); + await InstallVcredist2013().ConfigureAwait(false); } catch (Exception ex) { @@ -701,13 +701,13 @@ namespace MediaBrowser.ServerApplication } } - private async static Task InstallVcredist() + private async static Task InstallVcredist2013() { var httpClient = _appHost.HttpClient; var tmp = await httpClient.GetTempFile(new HttpRequestOptions { - Url = GetVcredistUrl(), + Url = GetVcredist2013Url(), Progress = new Progress() }).ConfigureAwait(false); @@ -733,7 +733,7 @@ namespace MediaBrowser.ServerApplication } } - private static string GetVcredistUrl() + private static string GetVcredist2013Url() { if (Environment.Is64BitProcess) { diff --git a/MediaBrowser.WebDashboard/Api/PackageCreator.cs b/MediaBrowser.WebDashboard/Api/PackageCreator.cs index d8de98abe..883c02914 100644 --- a/MediaBrowser.WebDashboard/Api/PackageCreator.cs +++ b/MediaBrowser.WebDashboard/Api/PackageCreator.cs @@ -274,7 +274,7 @@ namespace MediaBrowser.WebDashboard.Api } var mainFile = File.ReadAllText(GetDashboardResourcePath("index.html")); - html = ReplaceFirst(mainFile, "
", "
" + html + "
"); + html = ReplaceFirst(mainFile, "
", "
" + html + "
"); } if (!string.IsNullOrWhiteSpace(localizationCulture)) -- cgit v1.2.3 From 29dbc95254ba5e0db3c293dcc0e08827dd09f870 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Tue, 24 May 2016 14:17:12 -0400 Subject: update startup error handling --- MediaBrowser.ServerApplication/MainStartup.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'MediaBrowser.ServerApplication/MainStartup.cs') diff --git a/MediaBrowser.ServerApplication/MainStartup.cs b/MediaBrowser.ServerApplication/MainStartup.cs index 706e9c8ed..3a3b10188 100644 --- a/MediaBrowser.ServerApplication/MainStartup.cs +++ b/MediaBrowser.ServerApplication/MainStartup.cs @@ -244,7 +244,9 @@ namespace MediaBrowser.ServerApplication var task = _appHost.Init(initProgress); - task = task.ContinueWith(new Action(a => _appHost.RunStartupTasks())); + Task.WaitAll(task); + + task = task.ContinueWith(new Action(a => _appHost.RunStartupTasks()), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent); if (runService) { -- cgit v1.2.3 From 8c7f39913bacd280efe6e1170c157e1eea450a95 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sat, 18 Jun 2016 13:26:42 -0400 Subject: continue jquery removal --- .../Dto/DtoService.cs | 33 ++++---- .../Persistence/SqliteItemRepository.cs | 6 +- MediaBrowser.ServerApplication/MainStartup.cs | 90 ---------------------- 3 files changed, 18 insertions(+), 111 deletions(-) (limited to 'MediaBrowser.ServerApplication/MainStartup.cs') diff --git a/MediaBrowser.Server.Implementations/Dto/DtoService.cs b/MediaBrowser.Server.Implementations/Dto/DtoService.cs index bb9fcc924..6339fb7b1 100644 --- a/MediaBrowser.Server.Implementations/Dto/DtoService.cs +++ b/MediaBrowser.Server.Implementations/Dto/DtoService.cs @@ -471,30 +471,16 @@ namespace MediaBrowser.Server.Implementations.Dto { var folder = (Folder)item; - if (fields.Contains(ItemFields.SyncInfo)) - { - var userData = _userDataRepository.GetUserData(user, item); - - // Skip the user data manager because we've already looped through the recursive tree and don't want to do it twice - // TODO: Improve in future - dto.UserData = GetUserItemDataDto(userData); + // Skip the user data manager because we've already looped through the recursive tree and don't want to do it twice + // TODO: Improve in future + dto.UserData = GetUserItemDataDto(_userDataRepository.GetUserData(user, item)); - if (item.SourceType == SourceType.Library && folder.SupportsUserDataFromChildren) - { - SetSpecialCounts(folder, user, dto, fields, syncProgress); - } + if (item.SourceType == SourceType.Library && folder.SupportsUserDataFromChildren) + { + SetSpecialCounts(folder, user, dto, fields, syncProgress); dto.UserData.Played = dto.UserData.PlayedPercentage.HasValue && dto.UserData.PlayedPercentage.Value >= 100; } - else if (item.SourceType == SourceType.Library) - { - dto.UserData = _userDataRepository.GetUserDataDto(item, user); - } - else - { - var userData = _userDataRepository.GetUserData(user, item); - dto.UserData = GetUserItemDataDto(userData); - } if (item.SourceType == SourceType.Library) { @@ -549,6 +535,13 @@ namespace MediaBrowser.Server.Implementations.Dto private int GetChildCount(Folder folder, User user) { + // Right now this is too slow to calculate for top level folders on a per-user basis + // Just return something so that apps that are expecting a value won't think the folders are empty + if (folder is ICollectionFolder || folder is UserView) + { + return new Random().Next(1, 10); + } + return folder.GetChildCount(user); } diff --git a/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs b/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs index 878fcbe0c..e8b39a1fe 100644 --- a/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs +++ b/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs @@ -1735,6 +1735,8 @@ namespace MediaBrowser.Server.Implementations.Persistence var now = DateTime.UtcNow; + var list = new List(); + using (var cmd = _connection.CreateCommand()) { cmd.CommandText = "select " + string.Join(",", GetFinalColumnsToSelect(query, _retriveItemColumns, cmd)) + GetFromText(); @@ -1778,11 +1780,13 @@ namespace MediaBrowser.Server.Implementations.Persistence var item = GetItem(reader); if (item != null) { - yield return item; + list.Add(item); } } } } + + return list; } private void LogQueryTime(string methodName, IDbCommand cmd, DateTime startDate) diff --git a/MediaBrowser.ServerApplication/MainStartup.cs b/MediaBrowser.ServerApplication/MainStartup.cs index 3a3b10188..fb4fb86ff 100644 --- a/MediaBrowser.ServerApplication/MainStartup.cs +++ b/MediaBrowser.ServerApplication/MainStartup.cs @@ -259,9 +259,6 @@ namespace MediaBrowser.ServerApplication task = InstallVcredist2013IfNeeded(_appHost, _logger); Task.WaitAll(task); - task = InstallFrameworkV46IfNeeded(_logger); - Task.WaitAll(task); - SystemEvents.SessionEnding += SystemEvents_SessionEnding; SystemEvents.SessionSwitch += SystemEvents_SessionSwitch; @@ -594,93 +591,6 @@ namespace MediaBrowser.ServerApplication } } - private static async Task InstallFrameworkV46IfNeeded(ILogger logger) - { - bool installFrameworkV46 = false; - - try - { - using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32) - .OpenSubKey("SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full\\")) - { - if (ndpKey != null && ndpKey.GetValue("Release") != null) - { - if ((int)ndpKey.GetValue("Release") <= 393295) - { - //Found framework V4, but not yet V4.6 - installFrameworkV46 = true; - } - } - else - { - //Nothing found in the registry for V4 - installFrameworkV46 = true; - } - } - } - catch (Exception ex) - { - logger.ErrorException("Error getting .NET Framework version", ex); - } - - _logger.Info(".NET Framework 4.6 found: {0}", !installFrameworkV46); - - if (installFrameworkV46) - { - try - { - await InstallFrameworkV46().ConfigureAwait(false); - } - catch (Exception ex) - { - logger.ErrorException("Error installing .NET Framework version 4.6", ex); - } - } - } - - private static async Task InstallFrameworkV46() - { - var httpClient = _appHost.HttpClient; - - var tmp = await httpClient.GetTempFile(new HttpRequestOptions - { - Url = "https://github.com/MediaBrowser/Emby.Resources/raw/master/netframeworkV46/NDP46-KB3045560-Web.exe", - Progress = new Progress() - - }).ConfigureAwait(false); - - var exePath = Path.ChangeExtension(tmp, ".exe"); - File.Copy(tmp, exePath); - - var startInfo = new ProcessStartInfo - { - FileName = exePath, - - CreateNoWindow = true, - WindowStyle = ProcessWindowStyle.Hidden, - Verb = "runas", - ErrorDialog = false, - Arguments = "/q /norestart" - }; - - - _logger.Info("Running {0}", startInfo.FileName); - - using (var process = Process.Start(startInfo)) - { - process.WaitForExit(); - //process.ExitCode - /* - 0 --> Installation completed successfully. - 1602 --> The user canceled installation. - 1603 --> A fatal error occurred during installation. - 1641 --> A restart is required to complete the installation. This message indicates success. - 3010 --> A restart is required to complete the installation. This message indicates success. - 5100 --> The user's computer does not meet system requirements. - */ - } - } - private static async Task InstallVcredist2013IfNeeded(ApplicationHost appHost, ILogger logger) { try -- cgit v1.2.3 From 1f443097b7fa6f9ff829157120c4589d3ed65754 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Wed, 13 Jul 2016 22:36:42 -0400 Subject: improve prevention of simultaneous instances --- .../ApplicationHost.cs | 2 +- MediaBrowser.ServerApplication/MainStartup.cs | 58 ++++++++++++++++++++-- .../MediaBrowser.ServerApplication.csproj | 1 + 3 files changed, 56 insertions(+), 5 deletions(-) (limited to 'MediaBrowser.ServerApplication/MainStartup.cs') diff --git a/MediaBrowser.Server.Startup.Common/ApplicationHost.cs b/MediaBrowser.Server.Startup.Common/ApplicationHost.cs index bcd2ed8bd..b7ea5bdad 100644 --- a/MediaBrowser.Server.Startup.Common/ApplicationHost.cs +++ b/MediaBrowser.Server.Startup.Common/ApplicationHost.cs @@ -274,7 +274,7 @@ namespace MediaBrowser.Server.Startup.Common { get { - return "Media Browser Server"; + return "Emby Server"; } } diff --git a/MediaBrowser.ServerApplication/MainStartup.cs b/MediaBrowser.ServerApplication/MainStartup.cs index fb4fb86ff..0f2fea155 100644 --- a/MediaBrowser.ServerApplication/MainStartup.cs +++ b/MediaBrowser.ServerApplication/MainStartup.cs @@ -12,6 +12,7 @@ using System.Configuration.Install; using System.Diagnostics; using System.IO; using System.Linq; +using System.Management; using System.Runtime.InteropServices; using System.ServiceProcess; using System.Threading; @@ -102,7 +103,7 @@ namespace MediaBrowser.ServerApplication if (IsAlreadyRunning(applicationPath, currentProcess)) { - logger.Info("Shutting down because another instance of Media Browser Server is already running."); + logger.Info("Shutting down because another instance of Emby Server is already running."); return; } @@ -130,13 +131,28 @@ namespace MediaBrowser.ServerApplication /// true if [is already running] [the specified current process]; otherwise, false. private static bool IsAlreadyRunning(string applicationPath, Process currentProcess) { - var filename = Path.GetFileName(applicationPath); - var duplicate = Process.GetProcesses().FirstOrDefault(i => { try { - return string.Equals(filename, Path.GetFileName(i.MainModule.FileName)) && currentProcess.Id != i.Id; + if (currentProcess.Id == i.Id) + { + return false; + } + } + catch (Exception) + { + return false; + } + + try + { + //_logger.Info("Module: {0}", i.MainModule.FileName); + if (string.Equals(applicationPath, i.MainModule.FileName, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + return false; } catch (Exception) { @@ -155,6 +171,40 @@ namespace MediaBrowser.ServerApplication } } + if (!_isRunningAsService) + { + return IsAlreadyRunningAsService(applicationPath); + } + + return false; + } + + private static bool IsAlreadyRunningAsService(string applicationPath) + { + var serviceName = BackgroundService.GetExistingServiceName(); + + WqlObjectQuery wqlObjectQuery = new WqlObjectQuery(string.Format("SELECT * FROM Win32_Service WHERE State = 'Running' AND Name = '{0}'", serviceName)); + ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(wqlObjectQuery); + ManagementObjectCollection managementObjectCollection = managementObjectSearcher.Get(); + + foreach (ManagementObject managementObject in managementObjectCollection) + { + var obj = managementObject.GetPropertyValue("PathName"); + if (obj == null) + { + continue; + } + var path = obj.ToString(); + + _logger.Info("Service path: {0}", path); + // Need to use indexOf instead of equality because the path will have the full service command line + if (path.IndexOf(applicationPath, StringComparison.OrdinalIgnoreCase) != -1) + { + _logger.Info("The windows service is already running"); + return true; + } + } + return false; } diff --git a/MediaBrowser.ServerApplication/MediaBrowser.ServerApplication.csproj b/MediaBrowser.ServerApplication/MediaBrowser.ServerApplication.csproj index fcd6f7faf..b01d8c43f 100644 --- a/MediaBrowser.ServerApplication/MediaBrowser.ServerApplication.csproj +++ b/MediaBrowser.ServerApplication/MediaBrowser.ServerApplication.csproj @@ -88,6 +88,7 @@ True + -- cgit v1.2.3 From 7e52b0d3041bd0881cd9b8c6e2e1103a700b57be Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Wed, 13 Jul 2016 23:36:23 -0400 Subject: add service message --- MediaBrowser.Server.Implementations/Dto/DtoService.cs | 2 +- MediaBrowser.ServerApplication/MainStartup.cs | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) (limited to 'MediaBrowser.ServerApplication/MainStartup.cs') diff --git a/MediaBrowser.Server.Implementations/Dto/DtoService.cs b/MediaBrowser.Server.Implementations/Dto/DtoService.cs index de6c23cac..975e292f0 100644 --- a/MediaBrowser.Server.Implementations/Dto/DtoService.cs +++ b/MediaBrowser.Server.Implementations/Dto/DtoService.cs @@ -1322,7 +1322,7 @@ namespace MediaBrowser.Server.Implementations.Dto } } - if (fields.Contains(ItemFields.SeriesPrimaryImage)) + //if (fields.Contains(ItemFields.SeriesPrimaryImage)) { episodeSeries = episodeSeries ?? episode.Series; if (episodeSeries != null) diff --git a/MediaBrowser.ServerApplication/MainStartup.cs b/MediaBrowser.ServerApplication/MainStartup.cs index 0f2fea155..2440eab7c 100644 --- a/MediaBrowser.ServerApplication/MainStartup.cs +++ b/MediaBrowser.ServerApplication/MainStartup.cs @@ -201,6 +201,7 @@ namespace MediaBrowser.ServerApplication if (path.IndexOf(applicationPath, StringComparison.OrdinalIgnoreCase) != -1) { _logger.Info("The windows service is already running"); + MessageBox.Show("Emby Server is already running as a Windows Service. Only one instance is allowed at a time. To run as a tray icon, shut down the Windows Service."); return true; } } -- cgit v1.2.3 From d08f7df3c3607193252889a79b635a48e993fb37 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Mon, 18 Jul 2016 23:58:13 -0400 Subject: update vcc 2013 check --- MediaBrowser.ServerApplication/MainStartup.cs | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) (limited to 'MediaBrowser.ServerApplication/MainStartup.cs') diff --git a/MediaBrowser.ServerApplication/MainStartup.cs b/MediaBrowser.ServerApplication/MainStartup.cs index 2440eab7c..bdfd7d1bb 100644 --- a/MediaBrowser.ServerApplication/MainStartup.cs +++ b/MediaBrowser.ServerApplication/MainStartup.cs @@ -644,14 +644,32 @@ namespace MediaBrowser.ServerApplication private static async Task InstallVcredist2013IfNeeded(ApplicationHost appHost, ILogger logger) { + // Reference + // http://stackoverflow.com/questions/12206314/detect-if-visual-c-redistributable-for-visual-studio-2012-is-installed + try { - var version = ImageMagickEncoder.GetVersion(); - return; + var subkey = Environment.Is64BitProcess + ? "SOFTWARE\\WOW6432Node\\Microsoft\\VisualStudio\\12.0\\VC\\Runtimes\\x64" + : "SOFTWARE\\Microsoft\\VisualStudio\\12.0\\VC\\Runtimes\\x86"; + + using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default) + .OpenSubKey(subkey)) + { + if (ndpKey != null && ndpKey.GetValue("Version") != null) + { + var installedVersion = ((string)ndpKey.GetValue("Version")).TrimStart('v'); + if (installedVersion.StartsWith("12", StringComparison.OrdinalIgnoreCase)) + { + return; + } + } + } } catch (Exception ex) { - logger.ErrorException("Error loading ImageMagick", ex); + logger.ErrorException("Error getting .NET Framework version", ex); + return; } try -- cgit v1.2.3