Program.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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, appPaths.TempDirectory);
  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. if (environmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows)
  185. {
  186. // Not crazy about this but it's the only way to suppress ffmpeg crash dialog boxes
  187. SetErrorMode(ErrorModes.SEM_FAILCRITICALERRORS | ErrorModes.SEM_NOALIGNMENTFAULTEXCEPT |
  188. ErrorModes.SEM_NOGPFAULTERRORBOX | ErrorModes.SEM_NOOPENFILEERRORBOX);
  189. }
  190. var task = _appHost.Init(initProgress);
  191. Task.WaitAll(task);
  192. task = task.ContinueWith(new Action<Task>(a => _appHost.RunStartupTasks()), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent);
  193. Task.WaitAll(task);
  194. task = ApplicationTaskCompletionSource.Task;
  195. Task.WaitAll(task);
  196. }
  197. private static void GenerateCertificate(string certPath, string certHost)
  198. {
  199. //CertificateGenerator.CreateSelfSignCertificatePfx(certPath, certHost, _logger);
  200. }
  201. /// <summary>
  202. /// Handles the UnhandledException event of the CurrentDomain control.
  203. /// </summary>
  204. /// <param name="sender">The source of the event.</param>
  205. /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
  206. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  207. {
  208. var exception = (Exception)e.ExceptionObject;
  209. new UnhandledExceptionWriter(_appHost.ServerConfigurationManager.ApplicationPaths, _logger, _appHost.LogManager).Log(exception);
  210. ShowMessageBox("Unhandled exception: " + exception.Message);
  211. if (!Debugger.IsAttached)
  212. {
  213. Environment.Exit(Marshal.GetHRForException(exception));
  214. }
  215. }
  216. /// <summary>
  217. /// Performs the update if needed.
  218. /// </summary>
  219. /// <param name="appPaths">The app paths.</param>
  220. /// <param name="logger">The logger.</param>
  221. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  222. private static bool PerformUpdateIfNeeded(ServerApplicationPaths appPaths, ILogger logger)
  223. {
  224. return false;
  225. }
  226. private static void ShowMessageBox(string msg)
  227. {
  228. }
  229. public static void Shutdown()
  230. {
  231. DisposeAppHost();
  232. //_logger.Info("Calling Application.Exit");
  233. //Application.Exit();
  234. _logger.Info("Calling Environment.Exit");
  235. Environment.Exit(0);
  236. _logger.Info("Calling ApplicationTaskCompletionSource.SetResult");
  237. ApplicationTaskCompletionSource.SetResult(true);
  238. }
  239. public static void Restart()
  240. {
  241. DisposeAppHost();
  242. // todo: start new instance
  243. Shutdown();
  244. }
  245. private static void DisposeAppHost()
  246. {
  247. if (!_appHostDisposed)
  248. {
  249. _logger.Info("Disposing app host");
  250. _appHostDisposed = true;
  251. _appHost.Dispose();
  252. }
  253. }
  254. /// <summary>
  255. /// Sets the error mode.
  256. /// </summary>
  257. /// <param name="uMode">The u mode.</param>
  258. /// <returns>ErrorModes.</returns>
  259. [DllImport("kernel32.dll")]
  260. static extern ErrorModes SetErrorMode(ErrorModes uMode);
  261. /// <summary>
  262. /// Enum ErrorModes
  263. /// </summary>
  264. [Flags]
  265. public enum ErrorModes : uint
  266. {
  267. /// <summary>
  268. /// The SYSTE m_ DEFAULT
  269. /// </summary>
  270. SYSTEM_DEFAULT = 0x0,
  271. /// <summary>
  272. /// The SE m_ FAILCRITICALERRORS
  273. /// </summary>
  274. SEM_FAILCRITICALERRORS = 0x0001,
  275. /// <summary>
  276. /// The SE m_ NOALIGNMENTFAULTEXCEPT
  277. /// </summary>
  278. SEM_NOALIGNMENTFAULTEXCEPT = 0x0004,
  279. /// <summary>
  280. /// The SE m_ NOGPFAULTERRORBOX
  281. /// </summary>
  282. SEM_NOGPFAULTERRORBOX = 0x0002,
  283. /// <summary>
  284. /// The SE m_ NOOPENFILEERRORBOX
  285. /// </summary>
  286. SEM_NOOPENFILEERRORBOX = 0x8000
  287. }
  288. }
  289. }