aboutsummaryrefslogtreecommitdiff
path: root/Jellyfin.Server/Program.cs
blob: dd5e427df22f2fbdd132d5d49082745b29d34b74 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Emby.Drawing;
using Emby.Drawing.ImageMagick;
using Emby.Drawing.Skia;
using Emby.Server.Implementations;
using Emby.Server.Implementations.EnvironmentInfo;
using Emby.Server.Implementations.IO;
using Emby.Server.Implementations.Networking;
using Jellyfin.Server.Native;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.AspNetCore;
using ILogger = Microsoft.Extensions.Logging.ILogger;

namespace Jellyfin.Server
{
    public static class Program
    {
        private static readonly TaskCompletionSource<bool> ApplicationTaskCompletionSource = new TaskCompletionSource<bool>();
        private static ILoggerFactory _loggerFactory;
        private static ILogger _logger;
        private static bool _restartOnShutdown;

        public static async Task<int> Main(string[] args)
        {
            StartupOptions options = new StartupOptions(args);

            Assembly entryAssembly = Assembly.GetEntryAssembly();

            if (options.ContainsOption("-v") || options.ContainsOption("--version"))
            {
                Console.WriteLine(entryAssembly.GetName().Version.ToString());
                return 0;
            }

            string dataPath = options.GetOption("-programdata");
            string binPath = entryAssembly.Location;
            ServerApplicationPaths appPaths = CreateApplicationPaths(binPath, dataPath);

            await createLogger(appPaths);
            _loggerFactory = new SerilogLoggerFactory();
            _logger = _loggerFactory.CreateLogger("Main");

            AppDomain.CurrentDomain.UnhandledException += (sender, e) 
                => _logger.LogCritical((Exception)e.ExceptionObject, "Unhandled Exception");;

            _logger.LogInformation("Jellyfin version: {Version}", entryAssembly.GetName().Version);

            EnvironmentInfo environmentInfo = getEnvironmentInfo();
            ApplicationHost.LogEnvironmentInfo(_logger, appPaths, environmentInfo);

            SQLitePCL.Batteries_V2.Init();

            // Allow all https requests
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });

            var fileSystem = new ManagedFileSystem(_loggerFactory.CreateLogger("FileSystem"), environmentInfo, null, appPaths.TempDirectory, true);

            using (var appHost = new CoreAppHost(
                appPaths,
                _loggerFactory,
                options,
                fileSystem,
                new PowerManagement(),
                "embyserver-mono_{version}.zip",
                environmentInfo,
                new NullImageEncoder(),
                new SystemEvents(_loggerFactory.CreateLogger("SystemEvents")),
                new NetworkManager(_loggerFactory.CreateLogger("NetworkManager"), environmentInfo)))
            {
                appHost.Init();

                appHost.ImageProcessor.ImageEncoder = GetImageEncoder(_logger, fileSystem, options, () => appHost.HttpClient, appPaths, environmentInfo, appHost.LocalizationManager);

                _logger.LogInformation("Running startup tasks");

                await appHost.RunStartupTasks();

                // TODO: read input for a stop command
                // Block main thread until shutdown
                await ApplicationTaskCompletionSource.Task;

                _logger.LogInformation("Disposing app host");
            }

            if (_restartOnShutdown)
            {
                StartNewInstance(options);
            }

            return 0;
        }

        private static ServerApplicationPaths CreateApplicationPaths(string applicationPath, string programDataPath)
        {
            if (string.IsNullOrEmpty(programDataPath))
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    programDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                }
                else
                {
                    // $XDG_DATA_HOME defines the base directory relative to which user specific data files should be stored.
                    programDataPath = Environment.GetEnvironmentVariable("XDG_DATA_HOME");
                    // If $XDG_DATA_HOME is either not set or empty, $HOME/.local/share should be used.
                    if (string.IsNullOrEmpty(programDataPath)){
                        programDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".local", "share");
                    }
                }
                programDataPath = Path.Combine(programDataPath, "jellyfin");
            }

            string appFolderPath = Path.GetDirectoryName(applicationPath);

            return new ServerApplicationPaths(programDataPath, appFolderPath, appFolderPath);
        }

        private static async Task createLogger(IApplicationPaths appPaths)
        {
            string logDir = Environment.GetEnvironmentVariable("JELLYFIN_LOG_DIR");
            if (string.IsNullOrEmpty(logDir)){
                logDir = Path.Combine(appPaths.ProgramDataPath, "logs");
                Environment.SetEnvironmentVariable("JELLYFIN_LOG_DIR", logDir);
            }
            try
            {
                string path = Path.Combine(appPaths.ConfigurationDirectoryPath, "logging.json");

                if (!File.Exists(path))
                {
                    // For some reason the csproj name is used instead of the assembly name
                    using (Stream rscstr = typeof(Program).Assembly
                        .GetManifestResourceStream("Jellyfin.Server.Resources.Configuration.logging.json"))
                    using (Stream fstr = File.Open(path, FileMode.CreateNew))
                    {
                        await rscstr.CopyToAsync(fstr);
                    }
                }
                var configuration = new ConfigurationBuilder()
                    .SetBasePath(appPaths.ConfigurationDirectoryPath)
                    .AddJsonFile("logging.json")
                    .AddEnvironmentVariables("JELLYFIN_")
                    .Build();

                // Serilog.Log is used by SerilogLoggerFactory when no logger is specified
                Serilog.Log.Logger = new LoggerConfiguration()
                    .ReadFrom.Configuration(configuration)
                    .Enrich.FromLogContext()
                    .CreateLogger();
            }
            catch (Exception ex)
            {
                Serilog.Log.Logger = new LoggerConfiguration()
                    .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}")
                    .WriteTo.File(
                        Path.Combine(logDir, "log_.log"),
                        rollingInterval: RollingInterval.Day,
                        outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}")
                    .Enrich.FromLogContext()
                    .CreateLogger();

                Serilog.Log.Logger.Fatal(ex, "Failed to create/read logger configuration");
            }
        }

        public static IImageEncoder GetImageEncoder(
            ILogger logger, 
            IFileSystem fileSystem, 
            StartupOptions startupOptions, 
            Func<IHttpClient> httpClient,
            IApplicationPaths appPaths,
            IEnvironmentInfo environment,
            ILocalizationManager localizationManager)
        {
            if (!startupOptions.ContainsOption("-enablegdi"))
            {
                try
                {
                    return new SkiaEncoder(logger, appPaths, httpClient, fileSystem, localizationManager);
                }
                catch (Exception ex)
                {
                    logger.LogInformation("Skia not available. Will try next image processor. {0}", ex.Message);
                }

                try
                {
                    return new ImageMagickEncoder(logger, appPaths, httpClient, fileSystem, environment);
                }
                catch
                {
                    logger.LogInformation("ImageMagick not available. Will try next image processor.");
                }
            }

            return new NullImageEncoder();
        }

        private static EnvironmentInfo getEnvironmentInfo()
            => new EnvironmentInfo()
            {
                SystemArchitecture = RuntimeInformation.OSArchitecture,
                OperatingSystem = getOperatingSystem()
            };

        private static MediaBrowser.Model.System.OperatingSystem getOperatingSystem() {
            switch (Environment.OSVersion.Platform)
            {
                case PlatformID.MacOSX:
                    return MediaBrowser.Model.System.OperatingSystem.OSX;
                case PlatformID.Win32NT:
                    return MediaBrowser.Model.System.OperatingSystem.Windows;
                case PlatformID.Unix:
                {
                    string osDescription = RuntimeInformation.OSDescription;
                    if (osDescription.Contains("linux", StringComparison.OrdinalIgnoreCase))
                    {
                        return MediaBrowser.Model.System.OperatingSystem.Linux;
                    }
                    else if (osDescription.Contains("darwin", StringComparison.OrdinalIgnoreCase))
                    {
                        return MediaBrowser.Model.System.OperatingSystem.OSX;
                    }
                    else if (osDescription.Contains("bsd", StringComparison.OrdinalIgnoreCase))
                    {
                        return MediaBrowser.Model.System.OperatingSystem.BSD;
                    }
                    throw new Exception($"Can't resolve OS with description: {Environment.OSVersion.Platform}");
                }
                default: throw new Exception($"Can't resolve OS with description: {Environment.OSVersion.Platform}");
            }
        }

        public static  void Shutdown()
        {
            ApplicationTaskCompletionSource.SetResult(true);
        }

        public static void Restart()
        {
            _restartOnShutdown = true;

            Shutdown();
        }

        private static void StartNewInstance(StartupOptions startupOptions)
        {
            _logger.LogInformation("Starting new instance");

            string module = startupOptions.GetOption("-restartpath");

            if (string.IsNullOrWhiteSpace(module))
            {
                module = Environment.GetCommandLineArgs().First();
            }

            string commandLineArgsString;

            if (startupOptions.ContainsOption("-restartargs"))
            {
                commandLineArgsString = startupOptions.GetOption("-restartargs") ?? string.Empty;
            }
            else
            {
                commandLineArgsString = string .Join(" ", 
                    Environment.GetCommandLineArgs()
                        .Skip(1)
                        .Select(NormalizeCommandLineArgument)
                    );
            }

            _logger.LogInformation("Executable: {0}", module);
            _logger.LogInformation("Arguments: {0}", commandLineArgsString);

            Process.Start(module, commandLineArgsString);
        }

        private static string NormalizeCommandLineArgument(string arg)
        {
            if (!arg.Contains(" ", StringComparison.OrdinalIgnoreCase))
            {
                return arg;
            }

            return "\"" + arg + "\"";
        }
    }
}