Program.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. using MediaBrowser.Model.Logging;
  2. using MediaBrowser.Server.Implementations;
  3. using Microsoft.Win32;
  4. using System;
  5. using System.Diagnostics;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Runtime.InteropServices;
  9. using System.Text;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using Emby.Common.Implementations.EnvironmentInfo;
  13. using Emby.Common.Implementations.IO;
  14. using Emby.Common.Implementations.Logging;
  15. using Emby.Common.Implementations.Networking;
  16. using Emby.Drawing;
  17. using Emby.Server.Core;
  18. using Emby.Server.Implementations.Browser;
  19. using Emby.Server.Implementations.IO;
  20. using MediaBrowser.Common.Net;
  21. using Emby.Server.IO;
  22. using Emby.Server.Implementations;
  23. namespace Emby.Server
  24. {
  25. public class Program
  26. {
  27. private static ApplicationHost _appHost;
  28. private static ILogger _logger;
  29. private static bool _appHostDisposed;
  30. [DllImport("kernel32.dll", SetLastError = true)]
  31. static extern bool SetDllDirectory(string lpPathName);
  32. /// <summary>
  33. /// Defines the entry point of the application.
  34. /// </summary>
  35. public static void Main(string[] args)
  36. {
  37. var options = new StartupOptions(Environment.GetCommandLineArgs());
  38. var environmentInfo = new EnvironmentInfo();
  39. var baseDirectory = System.AppContext.BaseDirectory;
  40. string archPath = baseDirectory;
  41. if (environmentInfo.SystemArchitecture == MediaBrowser.Model.System.Architecture.X64)
  42. {
  43. archPath = Path.Combine(archPath, "x64");
  44. }
  45. else if (environmentInfo.SystemArchitecture == MediaBrowser.Model.System.Architecture.X86)
  46. {
  47. archPath = Path.Combine(archPath, "x86");
  48. }
  49. else
  50. {
  51. archPath = Path.Combine(archPath, "arm");
  52. }
  53. //Wand.SetMagickCoderModulePath(architecturePath);
  54. if (environmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows)
  55. {
  56. SetDllDirectory(archPath);
  57. }
  58. var appPaths = CreateApplicationPaths(baseDirectory);
  59. SetSqliteProvider();
  60. var logManager = new NlogManager(appPaths.LogDirectoryPath, "server");
  61. logManager.ReloadLogger(LogSeverity.Debug);
  62. logManager.AddConsoleOutput();
  63. var logger = _logger = logManager.GetLogger("Main");
  64. ApplicationHost.LogEnvironmentInfo(logger, appPaths, true);
  65. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  66. //if (IsAlreadyRunning(applicationPath, currentProcess))
  67. //{
  68. // logger.Info("Shutting down because another instance of Emby Server is already running.");
  69. // return;
  70. //}
  71. if (PerformUpdateIfNeeded(appPaths, logger))
  72. {
  73. logger.Info("Exiting to perform application update.");
  74. return;
  75. }
  76. RunApplication(appPaths, logManager, options, environmentInfo);
  77. }
  78. private static void SetSqliteProvider()
  79. {
  80. SQLitePCL.raw.SetProvider(new SQLitePCL.SQLite3Provider_sqlite3());
  81. }
  82. /// <summary>
  83. /// Determines whether [is already running] [the specified current process].
  84. /// </summary>
  85. /// <param name="applicationPath">The application path.</param>
  86. /// <param name="currentProcess">The current process.</param>
  87. /// <returns><c>true</c> if [is already running] [the specified current process]; otherwise, <c>false</c>.</returns>
  88. private static bool IsAlreadyRunning(string applicationPath, Process currentProcess)
  89. {
  90. var duplicate = Process.GetProcesses().FirstOrDefault(i =>
  91. {
  92. try
  93. {
  94. if (currentProcess.Id == i.Id)
  95. {
  96. return false;
  97. }
  98. }
  99. catch (Exception)
  100. {
  101. return false;
  102. }
  103. try
  104. {
  105. //_logger.Info("Module: {0}", i.MainModule.FileName);
  106. if (string.Equals(applicationPath, i.MainModule.FileName, StringComparison.OrdinalIgnoreCase))
  107. {
  108. return true;
  109. }
  110. return false;
  111. }
  112. catch (Exception)
  113. {
  114. return false;
  115. }
  116. });
  117. if (duplicate != null)
  118. {
  119. _logger.Info("Found a duplicate process. Giving it time to exit.");
  120. if (!duplicate.WaitForExit(30000))
  121. {
  122. _logger.Info("The duplicate process did not exit.");
  123. return true;
  124. }
  125. }
  126. return false;
  127. }
  128. /// <summary>
  129. /// Creates the application paths.
  130. /// </summary>
  131. private static ServerApplicationPaths CreateApplicationPaths(string appDirectory)
  132. {
  133. var resourcesPath = appDirectory;
  134. return new ServerApplicationPaths(ApplicationPathHelper.GetProgramDataPath(appDirectory), appDirectory, resourcesPath);
  135. }
  136. /// <summary>
  137. /// Gets a value indicating whether this instance can self restart.
  138. /// </summary>
  139. /// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
  140. public static bool CanSelfRestart
  141. {
  142. get
  143. {
  144. return true;
  145. }
  146. }
  147. /// <summary>
  148. /// Gets a value indicating whether this instance can self update.
  149. /// </summary>
  150. /// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
  151. public static bool CanSelfUpdate
  152. {
  153. get
  154. {
  155. return false;
  156. }
  157. }
  158. private static readonly TaskCompletionSource<bool> ApplicationTaskCompletionSource = new TaskCompletionSource<bool>();
  159. /// <summary>
  160. /// Runs the application.
  161. /// </summary>
  162. /// <param name="appPaths">The app paths.</param>
  163. /// <param name="logManager">The log manager.</param>
  164. /// <param name="options">The options.</param>
  165. private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager, StartupOptions options, EnvironmentInfo environmentInfo)
  166. {
  167. var fileSystem = new ManagedFileSystem(logManager.GetLogger("FileSystem"), true, true, true);
  168. fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
  169. var imageEncoder = new NullImageEncoder();
  170. _appHost = new CoreAppHost(appPaths,
  171. logManager,
  172. options,
  173. fileSystem,
  174. new PowerManagement(),
  175. "emby.windows.zip",
  176. environmentInfo,
  177. imageEncoder,
  178. new CoreSystemEvents(),
  179. new MemoryStreamFactory(),
  180. new NetworkManager(logManager.GetLogger("NetworkManager")),
  181. GenerateCertificate,
  182. () => "EmbyUser");
  183. var initProgress = new Progress<double>();
  184. // Not crazy about this but it's the only way to suppress ffmpeg crash dialog boxes
  185. SetErrorMode(ErrorModes.SEM_FAILCRITICALERRORS | ErrorModes.SEM_NOALIGNMENTFAULTEXCEPT |
  186. ErrorModes.SEM_NOGPFAULTERRORBOX | ErrorModes.SEM_NOOPENFILEERRORBOX);
  187. var task = _appHost.Init(initProgress);
  188. Task.WaitAll(task);
  189. task = task.ContinueWith(new Action<Task>(a => _appHost.RunStartupTasks()), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent);
  190. Task.WaitAll(task);
  191. task = ApplicationTaskCompletionSource.Task;
  192. Task.WaitAll(task);
  193. }
  194. private static void GenerateCertificate(string certPath, string certHost)
  195. {
  196. //CertificateGenerator.CreateSelfSignCertificatePfx(certPath, certHost, _logger);
  197. }
  198. /// <summary>
  199. /// Handles the UnhandledException event of the CurrentDomain control.
  200. /// </summary>
  201. /// <param name="sender">The source of the event.</param>
  202. /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
  203. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  204. {
  205. var exception = (Exception)e.ExceptionObject;
  206. new UnhandledExceptionWriter(_appHost.ServerConfigurationManager.ApplicationPaths, _logger, _appHost.LogManager).Log(exception);
  207. ShowMessageBox("Unhandled exception: " + exception.Message);
  208. if (!Debugger.IsAttached)
  209. {
  210. Environment.Exit(Marshal.GetHRForException(exception));
  211. }
  212. }
  213. /// <summary>
  214. /// Performs the update if needed.
  215. /// </summary>
  216. /// <param name="appPaths">The app paths.</param>
  217. /// <param name="logger">The logger.</param>
  218. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  219. private static bool PerformUpdateIfNeeded(ServerApplicationPaths appPaths, ILogger logger)
  220. {
  221. return false;
  222. }
  223. private static void ShowMessageBox(string msg)
  224. {
  225. }
  226. public static void Shutdown()
  227. {
  228. DisposeAppHost();
  229. //_logger.Info("Calling Application.Exit");
  230. //Application.Exit();
  231. _logger.Info("Calling Environment.Exit");
  232. Environment.Exit(0);
  233. _logger.Info("Calling ApplicationTaskCompletionSource.SetResult");
  234. ApplicationTaskCompletionSource.SetResult(true);
  235. }
  236. public static void Restart()
  237. {
  238. DisposeAppHost();
  239. // todo: start new instance
  240. Shutdown();
  241. }
  242. private static void DisposeAppHost()
  243. {
  244. if (!_appHostDisposed)
  245. {
  246. _logger.Info("Disposing app host");
  247. _appHostDisposed = true;
  248. _appHost.Dispose();
  249. }
  250. }
  251. /// <summary>
  252. /// Sets the error mode.
  253. /// </summary>
  254. /// <param name="uMode">The u mode.</param>
  255. /// <returns>ErrorModes.</returns>
  256. [DllImport("kernel32.dll")]
  257. static extern ErrorModes SetErrorMode(ErrorModes uMode);
  258. /// <summary>
  259. /// Enum ErrorModes
  260. /// </summary>
  261. [Flags]
  262. public enum ErrorModes : uint
  263. {
  264. /// <summary>
  265. /// The SYSTE m_ DEFAULT
  266. /// </summary>
  267. SYSTEM_DEFAULT = 0x0,
  268. /// <summary>
  269. /// The SE m_ FAILCRITICALERRORS
  270. /// </summary>
  271. SEM_FAILCRITICALERRORS = 0x0001,
  272. /// <summary>
  273. /// The SE m_ NOALIGNMENTFAULTEXCEPT
  274. /// </summary>
  275. SEM_NOALIGNMENTFAULTEXCEPT = 0x0004,
  276. /// <summary>
  277. /// The SE m_ NOGPFAULTERRORBOX
  278. /// </summary>
  279. SEM_NOGPFAULTERRORBOX = 0x0002,
  280. /// <summary>
  281. /// The SE m_ NOOPENFILEERRORBOX
  282. /// </summary>
  283. SEM_NOOPENFILEERRORBOX = 0x8000
  284. }
  285. }
  286. }