Program.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. using System;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Net.Security;
  7. using System.Reflection;
  8. using System.Runtime.InteropServices;
  9. using System.Threading.Tasks;
  10. using Emby.Drawing;
  11. using Emby.Drawing.ImageMagick;
  12. using Emby.Drawing.Skia;
  13. using Emby.Server.Implementations;
  14. using Emby.Server.Implementations.EnvironmentInfo;
  15. using Emby.Server.Implementations.IO;
  16. using Emby.Server.Implementations.Networking;
  17. using Jellyfin.Server.Native;
  18. using MediaBrowser.Common.Configuration;
  19. using MediaBrowser.Common.Net;
  20. using MediaBrowser.Controller.Drawing;
  21. using MediaBrowser.Model.IO;
  22. using MediaBrowser.Model.Globalization;
  23. using MediaBrowser.Model.System;
  24. using Microsoft.Extensions.Configuration;
  25. using Microsoft.Extensions.Logging;
  26. using Serilog;
  27. using Serilog.AspNetCore;
  28. using ILogger = Microsoft.Extensions.Logging.ILogger;
  29. namespace Jellyfin.Server
  30. {
  31. public static class Program
  32. {
  33. private static readonly TaskCompletionSource<bool> ApplicationTaskCompletionSource = new TaskCompletionSource<bool>();
  34. private static ILoggerFactory _loggerFactory;
  35. private static ILogger _logger;
  36. private static bool _restartOnShutdown;
  37. public static async Task<int> Main(string[] args)
  38. {
  39. StartupOptions options = new StartupOptions(args);
  40. Assembly entryAssembly = Assembly.GetEntryAssembly();
  41. if (options.ContainsOption("-v") || options.ContainsOption("--version"))
  42. {
  43. Console.WriteLine(entryAssembly.GetName().Version.ToString());
  44. return 0;
  45. }
  46. string dataPath = options.GetOption("-programdata");
  47. string binPath = entryAssembly.Location;
  48. ServerApplicationPaths appPaths = CreateApplicationPaths(binPath, dataPath);
  49. await createLogger(appPaths);
  50. _loggerFactory = new SerilogLoggerFactory();
  51. _logger = _loggerFactory.CreateLogger("Main");
  52. AppDomain.CurrentDomain.UnhandledException += (sender, e)
  53. => _logger.LogCritical((Exception)e.ExceptionObject, "Unhandled Exception");;
  54. ApplicationHost.LogEnvironmentInfo(_logger, appPaths, true);
  55. SQLitePCL.Batteries_V2.Init();
  56. // Allow all https requests
  57. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
  58. EnvironmentInfo environmentInfo = getEnvironmentInfo();
  59. var fileSystem = new ManagedFileSystem(_loggerFactory.CreateLogger("FileSystem"), environmentInfo, null, appPaths.TempDirectory, true);
  60. using (var appHost = new CoreAppHost(
  61. appPaths,
  62. _loggerFactory,
  63. options,
  64. fileSystem,
  65. new PowerManagement(),
  66. "embyserver-mono_{version}.zip",
  67. environmentInfo,
  68. new NullImageEncoder(),
  69. new SystemEvents(_loggerFactory.CreateLogger("SystemEvents")),
  70. new NetworkManager(_loggerFactory.CreateLogger("NetworkManager"), environmentInfo)))
  71. {
  72. appHost.Init();
  73. appHost.ImageProcessor.ImageEncoder = GetImageEncoder(_logger, fileSystem, options, () => appHost.HttpClient, appPaths, environmentInfo, appHost.LocalizationManager);
  74. _logger.LogInformation("Running startup tasks");
  75. await appHost.RunStartupTasks();
  76. // TODO: read input for a stop command
  77. // Block main thread until shutdown
  78. await ApplicationTaskCompletionSource.Task;
  79. _logger.LogInformation("Disposing app host");
  80. }
  81. if (_restartOnShutdown)
  82. {
  83. StartNewInstance(options);
  84. }
  85. return 0;
  86. }
  87. private static ServerApplicationPaths CreateApplicationPaths(string applicationPath, string programDataPath)
  88. {
  89. if (string.IsNullOrEmpty(programDataPath))
  90. {
  91. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  92. {
  93. programDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
  94. }
  95. else
  96. {
  97. // $XDG_DATA_HOME defines the base directory relative to which user specific data files should be stored.
  98. programDataPath = Environment.GetEnvironmentVariable("XDG_DATA_HOME");
  99. // If $XDG_DATA_HOME is either not set or empty, $HOME/.local/share should be used.
  100. if (string.IsNullOrEmpty(programDataPath)){
  101. programDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".local", "share");
  102. }
  103. }
  104. programDataPath = Path.Combine(programDataPath, "jellyfin");
  105. }
  106. string appFolderPath = Path.GetDirectoryName(applicationPath);
  107. return new ServerApplicationPaths(programDataPath, appFolderPath, appFolderPath);
  108. }
  109. private static async Task createLogger(IApplicationPaths appPaths)
  110. {
  111. string logDir = Environment.GetEnvironmentVariable("JELLYFIN_LOG_DIR");
  112. if (string.IsNullOrEmpty(logDir)){
  113. logDir = Path.Combine(appPaths.ProgramDataPath, "logs");
  114. Environment.SetEnvironmentVariable("JELLYFIN_LOG_DIR", logDir);
  115. }
  116. try
  117. {
  118. string path = Path.Combine(appPaths.ConfigurationDirectoryPath, "logging.json");
  119. if (!File.Exists(path))
  120. {
  121. // For some reason the csproj name is used instead of the assembly name
  122. using (Stream rscstr = typeof(Program).Assembly
  123. .GetManifestResourceStream("EmbyServer.Resources.Configuration.logging.json"))
  124. using (Stream fstr = File.Open(path, FileMode.CreateNew))
  125. {
  126. await rscstr.CopyToAsync(fstr);
  127. }
  128. }
  129. var configuration = new ConfigurationBuilder()
  130. .SetBasePath(appPaths.ConfigurationDirectoryPath)
  131. .AddJsonFile("logging.json")
  132. .AddEnvironmentVariables("JELLYFIN_")
  133. .Build();
  134. // Serilog.Log is used by SerilogLoggerFactory when no logger is specified
  135. Serilog.Log.Logger = new LoggerConfiguration()
  136. .ReadFrom.Configuration(configuration)
  137. .Enrich.FromLogContext()
  138. .CreateLogger();
  139. }
  140. catch (Exception ex)
  141. {
  142. Serilog.Log.Logger = new LoggerConfiguration()
  143. .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}")
  144. .WriteTo.File(
  145. Path.Combine(logDir, "log_.log"),
  146. rollingInterval: RollingInterval.Day,
  147. outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}")
  148. .Enrich.FromLogContext()
  149. .CreateLogger();
  150. Serilog.Log.Logger.Fatal(ex, "Failed to create/read logger configuration");
  151. }
  152. }
  153. public static IImageEncoder GetImageEncoder(
  154. ILogger logger,
  155. IFileSystem fileSystem,
  156. StartupOptions startupOptions,
  157. Func<IHttpClient> httpClient,
  158. IApplicationPaths appPaths,
  159. IEnvironmentInfo environment,
  160. ILocalizationManager localizationManager)
  161. {
  162. if (!startupOptions.ContainsOption("-enablegdi"))
  163. {
  164. try
  165. {
  166. return new SkiaEncoder(logger, appPaths, httpClient, fileSystem, localizationManager);
  167. }
  168. catch (Exception ex)
  169. {
  170. logger.LogInformation("Skia not available. Will try next image processor. {0}", ex.Message);
  171. }
  172. try
  173. {
  174. return new ImageMagickEncoder(logger, appPaths, httpClient, fileSystem, environment);
  175. }
  176. catch
  177. {
  178. logger.LogInformation("ImageMagick not available. Will try next image processor.");
  179. }
  180. }
  181. return new NullImageEncoder();
  182. }
  183. private static EnvironmentInfo getEnvironmentInfo()
  184. => new EnvironmentInfo()
  185. {
  186. SystemArchitecture = RuntimeInformation.OSArchitecture,
  187. OperatingSystem = getOperatingSystem()
  188. };
  189. private static MediaBrowser.Model.System.OperatingSystem getOperatingSystem() {
  190. switch (Environment.OSVersion.Platform)
  191. {
  192. case PlatformID.MacOSX:
  193. return MediaBrowser.Model.System.OperatingSystem.OSX;
  194. case PlatformID.Win32NT:
  195. return MediaBrowser.Model.System.OperatingSystem.Windows;
  196. case PlatformID.Unix:
  197. {
  198. string osDescription = RuntimeInformation.OSDescription;
  199. if (osDescription.Contains("linux", StringComparison.OrdinalIgnoreCase))
  200. {
  201. return MediaBrowser.Model.System.OperatingSystem.Linux;
  202. }
  203. else if (osDescription.Contains("darwin", StringComparison.OrdinalIgnoreCase))
  204. {
  205. return MediaBrowser.Model.System.OperatingSystem.OSX;
  206. }
  207. else if (osDescription.Contains("bsd", StringComparison.OrdinalIgnoreCase))
  208. {
  209. return MediaBrowser.Model.System.OperatingSystem.BSD;
  210. }
  211. throw new Exception($"Can't resolve OS with description: {Environment.OSVersion.Platform}");
  212. }
  213. default: throw new Exception($"Can't resolve OS with description: {Environment.OSVersion.Platform}");
  214. }
  215. }
  216. public static void Shutdown()
  217. {
  218. ApplicationTaskCompletionSource.SetResult(true);
  219. }
  220. public static void Restart()
  221. {
  222. _restartOnShutdown = true;
  223. Shutdown();
  224. }
  225. private static void StartNewInstance(StartupOptions startupOptions)
  226. {
  227. _logger.LogInformation("Starting new instance");
  228. string module = startupOptions.GetOption("-restartpath");
  229. if (string.IsNullOrWhiteSpace(module))
  230. {
  231. module = Environment.GetCommandLineArgs().First();
  232. }
  233. string commandLineArgsString;
  234. if (startupOptions.ContainsOption("-restartargs"))
  235. {
  236. commandLineArgsString = startupOptions.GetOption("-restartargs") ?? string.Empty;
  237. }
  238. else
  239. {
  240. commandLineArgsString = string .Join(" ",
  241. Environment.GetCommandLineArgs()
  242. .Skip(1)
  243. .Select(NormalizeCommandLineArgument)
  244. );
  245. }
  246. _logger.LogInformation("Executable: {0}", module);
  247. _logger.LogInformation("Arguments: {0}", commandLineArgsString);
  248. Process.Start(module, commandLineArgsString);
  249. }
  250. private static string NormalizeCommandLineArgument(string arg)
  251. {
  252. if (!arg.Contains(" ", StringComparison.OrdinalIgnoreCase))
  253. {
  254. return arg;
  255. }
  256. return "\"" + arg + "\"";
  257. }
  258. }
  259. }