2
0

Program.cs 13 KB

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