public void Initalize()
        {
            logger.Info("Starting Jackett " + configService.GetVersion());
            try
            {
                var x          = Environment.OSVersion;
                var runtimedir = RuntimeEnvironment.GetRuntimeDirectory();
                logger.Info("Environment version: " + Environment.Version.ToString() + " (" + runtimedir + ")");
                logger.Info("OS version: " + Environment.OSVersion.ToString() + (Environment.Is64BitOperatingSystem ? " (64bit OS)" : "") + (Environment.Is64BitProcess ? " (64bit process)" : ""));

                try
                {
                    int workerThreads;
                    int completionPortThreads;
                    ThreadPool.GetMaxThreads(out workerThreads, out completionPortThreads);
                    logger.Info("ThreadPool MaxThreads: " + workerThreads + " workerThreads, " + completionPortThreads + " completionPortThreads");
                }
                catch (Exception e)
                {
                    logger.Error("Error while getting MaxThreads details: " + e);
                }

                try
                {
                    var issuefile = "/etc/issue";
                    if (File.Exists(issuefile))
                    {
                        using (StreamReader reader = new StreamReader(issuefile))
                        {
                            string firstLine;
                            firstLine = reader.ReadLine();
                            if (firstLine != null)
                            {
                                logger.Info("issue: " + firstLine);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    logger.Error(e, "Error while reading the issue file");
                }

                Type monotype = Type.GetType("Mono.Runtime");
                if (monotype != null)
                {
                    MethodInfo displayName = monotype.GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static);
                    var        monoVersion = "unknown";
                    if (displayName != null)
                    {
                        monoVersion = displayName.Invoke(null, null).ToString();
                    }
                    logger.Info("mono version: " + monoVersion);

                    var monoVersionO = new Version(monoVersion.Split(' ')[0]);

                    if (monoVersionO.Major < 4)
                    {
                        logger.Error("Your mono version is to old (mono 3 is no longer supported). Please update to the latest version from http://www.mono-project.com/download/");
                        Environment.Exit(2);
                    }
                    else if (monoVersionO.Major == 4 && monoVersionO.Minor == 2)
                    {
                        var notice = "mono version 4.2.* is known to cause problems with Jackett. If you experience any problems please try updating to the latest mono version from http://www.mono-project.com/download/ first.";
                        _notices.Add(notice);
                        logger.Error(notice);
                    }

                    try
                    {
                        // Check for mono-devel
                        // Is there any better way which doesn't involve a hard cashes?
                        var mono_devel_file = Path.Combine(runtimedir, "mono-api-info.exe");
                        if (!File.Exists(mono_devel_file))
                        {
                            var notice = "It looks like the mono-devel package is not installed, please make sure it's installed to avoid crashes.";
                            _notices.Add(notice);
                            logger.Error(notice);
                        }
                    }
                    catch (Exception e)
                    {
                        logger.Error(e, "Error while checking for mono-devel");
                    }

                    try
                    {
                        // Check for ca-certificates-mono
                        var mono_cert_file = Path.Combine(runtimedir, "cert-sync.exe");
                        if (!File.Exists(mono_cert_file))
                        {
                            if ((monoVersionO.Major >= 4 && monoVersionO.Minor >= 8) || monoVersionO.Major >= 5)
                            {
                                var notice = "The ca-certificates-mono package is not installed, HTTPS trackers won't work. Please install it.";
                                _notices.Add(notice);
                                logger.Error(notice);
                            }
                            else
                            {
                                logger.Info("The ca-certificates-mono package is not installed, it will become mandatory once mono >= 4.8 is used.");
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        logger.Error(e, "Error while checking for ca-certificates-mono");
                    }

                    try
                    {
                        Encoding.GetEncoding("windows-1255");
                    }
                    catch (NotSupportedException e)
                    {
                        logger.Debug(e);
                        logger.Error(e.Message + " Most likely the mono-locale-extras package is not installed.");
                        Environment.Exit(2);
                    }
                }
            }
            catch (Exception e)
            {
                logger.Error("Error while getting environment details: " + e);
            }

            CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("en-US");
            // Load indexers
            indexerService.InitIndexers();
            foreach (string dir in configService.GetCardigannDefinitionsFolders())
            {
                indexerService.InitCardigannIndexers(dir);
            }
            indexerService.InitAggregateIndexer();
            indexerService.SortIndexers();
            client.Init();
            updater.CleanupTempDir();
        }
        public void UpdateConfig([FromBody] Models.DTO.ServerConfig config)
        {
            var    originalPort          = serverConfig.Port;
            var    originalAllowExternal = serverConfig.AllowExternal;
            int    port             = config.port;
            bool   external         = config.external;
            string saveDir          = config.blackholedir;
            bool   updateDisabled   = config.updatedisabled;
            bool   preRelease       = config.prerelease;
            bool   logging          = config.logging;
            string basePathOverride = config.basepathoverride;

            if (basePathOverride != null)
            {
                basePathOverride = basePathOverride.TrimEnd('/');
                if (!string.IsNullOrWhiteSpace(basePathOverride) && !basePathOverride.StartsWith("/"))
                {
                    throw new Exception("The Base Path Override must start with a /");
                }
            }

            string omdbApiKey = config.omdbkey;

            serverConfig.UpdateDisabled           = updateDisabled;
            serverConfig.UpdatePrerelease         = preRelease;
            serverConfig.BasePathOverride         = basePathOverride;
            serverConfig.RuntimeSettings.BasePath = Engine.Server.BasePath();
            configService.SaveConfig(serverConfig);

            Engine.SetLogLevel(logging ? LogLevel.Debug : LogLevel.Info);
            serverConfig.RuntimeSettings.TracingEnabled = logging;

            if (omdbApiKey != serverConfig.OmdbApiKey)
            {
                serverConfig.OmdbApiKey = omdbApiKey;
                configService.SaveConfig(serverConfig);
                // HACK
                indexerService.InitAggregateIndexer();
            }

            if (config.proxy_type != serverConfig.ProxyType ||
                config.proxy_url != serverConfig.ProxyUrl ||
                config.proxy_port != serverConfig.ProxyPort ||
                config.proxy_username != serverConfig.ProxyUsername ||
                config.proxy_password != serverConfig.ProxyPassword)
            {
                if (config.proxy_port < 1 || config.proxy_port > 65535)
                {
                    throw new Exception("The port you have selected is invalid, it must be below 65535.");
                }

                serverConfig.ProxyUrl      = config.proxy_url;
                serverConfig.ProxyType     = config.proxy_type;
                serverConfig.ProxyPort     = config.proxy_port;
                serverConfig.ProxyUsername = config.proxy_username;
                serverConfig.ProxyPassword = config.proxy_password;
                configService.SaveConfig(serverConfig);
            }

            if (port != serverConfig.Port || external != serverConfig.AllowExternal)
            {
                if (ServerUtil.RestrictedPorts.Contains(port))
                {
                    throw new Exception("The port you have selected is restricted, try a different one.");
                }

                if (port < 1 || port > 65535)
                {
                    throw new Exception("The port you have selected is invalid, it must be below 65535.");
                }

                // Save port to the config so it can be picked up by the if needed when running as admin below.
                serverConfig.AllowExternal = external;
                serverConfig.Port          = port;
                configService.SaveConfig(serverConfig);

                // On Windows change the url reservations
                if (System.Environment.OSVersion.Platform != PlatformID.Unix)
                {
                    if (!ServerUtil.IsUserAdministrator())
                    {
                        try
                        {
                            processService.StartProcessAndLog(System.Windows.Forms.Application.ExecutablePath, "--ReserveUrls", true);
                        }
                        catch
                        {
                            serverConfig.Port          = originalPort;
                            serverConfig.AllowExternal = originalAllowExternal;
                            configService.SaveConfig(serverConfig);

                            throw new Exception("Failed to acquire admin permissions to reserve the new port.");
                        }
                    }
                    else
                    {
                        serverService.ReserveUrls(true);
                    }
                }

                (new Thread(() =>
                {
                    Thread.Sleep(500);
                    serverService.Stop();
                    Engine.BuildContainer(serverConfig.RuntimeSettings, new WebApi2Module());
                    Engine.Server.Initalize();
                    Engine.Server.Start();
                })).Start();
            }

            if (saveDir != serverConfig.BlackholeDir)
            {
                if (!string.IsNullOrEmpty(saveDir))
                {
                    if (!Directory.Exists(saveDir))
                    {
                        throw new Exception("Blackhole directory does not exist");
                    }
                }

                serverConfig.BlackholeDir = saveDir;
                configService.SaveConfig(serverConfig);
            }

            serverConfig.ConfigChanged();
        }
Exemple #3
0
        public IActionResult UpdateConfig([FromBody] Common.Models.DTO.ServerConfig config)
        {
            var webHostRestartNeeded = false;

            var originalPort          = serverConfig.Port;
            var originalAllowExternal = serverConfig.AllowExternal;
            var port             = config.port;
            var external         = config.external;
            var saveDir          = config.blackholedir;
            var updateDisabled   = config.updatedisabled;
            var preRelease       = config.prerelease;
            var logging          = config.logging;
            var basePathOverride = config.basepathoverride;

            if (basePathOverride != null)
            {
                basePathOverride = basePathOverride.TrimEnd('/');
                if (!string.IsNullOrWhiteSpace(basePathOverride) && !basePathOverride.StartsWith("/"))
                {
                    throw new Exception("The Base Path Override must start with a /");
                }
            }

            var omdbApiKey = config.omdbkey;
            var omdbApiUrl = config.omdburl;

            if (config.basepathoverride != serverConfig.BasePathOverride)
            {
                webHostRestartNeeded = true;
            }

            serverConfig.UpdateDisabled           = updateDisabled;
            serverConfig.UpdatePrerelease         = preRelease;
            serverConfig.BasePathOverride         = basePathOverride;
            serverConfig.RuntimeSettings.BasePath = serverService.BasePath();
            configService.SaveConfig(serverConfig);

            Helper.SetLogLevel(logging ? LogLevel.Debug : LogLevel.Info);
            serverConfig.RuntimeSettings.TracingEnabled = logging;

            if (omdbApiKey != serverConfig.OmdbApiKey || omdbApiUrl != serverConfig.OmdbApiUrl)
            {
                serverConfig.OmdbApiKey = omdbApiKey;
                serverConfig.OmdbApiUrl = omdbApiUrl.TrimEnd('/');
                configService.SaveConfig(serverConfig);
                // HACK
                indexerService.InitAggregateIndexer();
            }

            if (config.proxy_type != serverConfig.ProxyType ||
                config.proxy_url != serverConfig.ProxyUrl ||
                config.proxy_port != serverConfig.ProxyPort ||
                config.proxy_username != serverConfig.ProxyUsername ||
                config.proxy_password != serverConfig.ProxyPassword)
            {
                if (config.proxy_port < 1 || config.proxy_port > 65535)
                {
                    throw new Exception("The port you have selected is invalid, it must be below 65535.");
                }

                serverConfig.ProxyUrl      = config.proxy_url;
                serverConfig.ProxyType     = config.proxy_type;
                serverConfig.ProxyPort     = config.proxy_port;
                serverConfig.ProxyUsername = config.proxy_username;
                serverConfig.ProxyPassword = config.proxy_password;
                configService.SaveConfig(serverConfig);
                webHostRestartNeeded = true;
            }

            if (port != serverConfig.Port || external != serverConfig.AllowExternal)
            {
                if (ServerUtil.RestrictedPorts.Contains(port))
                {
                    throw new Exception("The port you have selected is restricted, try a different one.");
                }

                if (port < 1 || port > 65535)
                {
                    throw new Exception("The port you have selected is invalid, it must be below 65535.");
                }

                // Save port to the config so it can be picked up by the if needed when running as admin below.
                serverConfig.AllowExternal = external;
                serverConfig.Port          = port;
                configService.SaveConfig(serverConfig);

                // On Windows change the url reservations
                if (System.Environment.OSVersion.Platform != PlatformID.Unix)
                {
                    if (!ServerUtil.IsUserAdministrator())
                    {
                        try
                        {
                            var consoleExePath = System.Reflection.Assembly.GetExecutingAssembly().CodeBase.Replace(".dll", ".exe");
                            processService.StartProcessAndLog(consoleExePath, "--ReserveUrls", true);
                        }
                        catch
                        {
                            serverConfig.Port          = originalPort;
                            serverConfig.AllowExternal = originalAllowExternal;
                            configService.SaveConfig(serverConfig);

                            throw new Exception("Failed to acquire admin permissions to reserve the new port.");
                        }
                    }
                    else
                    {
                        serverService.ReserveUrls(true);
                    }
                }

                webHostRestartNeeded = true;
            }

            if (saveDir != serverConfig.BlackholeDir)
            {
                if (!string.IsNullOrEmpty(saveDir))
                {
                    if (!Directory.Exists(saveDir))
                    {
                        throw new Exception("Blackhole directory does not exist");
                    }
                }

                serverConfig.BlackholeDir = saveDir;
                configService.SaveConfig(serverConfig);
            }

            if (webHostRestartNeeded)
            {
                Thread.Sleep(500);
                logger.Info("Restarting webhost due to configuration change");
                Helper.RestartWebHost();
            }

            serverConfig.ConfigChanged();

            return(Json(serverConfig));
        }
        public IActionResult UpdateConfig([FromBody] Common.Models.DTO.ServerConfig config)
        {
            var webHostRestartNeeded = false;

            var originalPort          = serverConfig.Port;
            var originalAllowExternal = serverConfig.AllowExternal;
            var port            = config.port;
            var external        = config.external;
            var saveDir         = config.blackholedir;
            var updateDisabled  = config.updatedisabled;
            var preRelease      = config.prerelease;
            var enhancedLogging = config.logging;

            var basePathOverride = config.basepathoverride;

            if (basePathOverride != null)
            {
                basePathOverride = basePathOverride.TrimEnd('/');
                if (!string.IsNullOrWhiteSpace(basePathOverride) && !basePathOverride.StartsWith("/"))
                {
                    throw new Exception("The Base Path Override must start with a /");
                }
            }

            var cacheEnabled = config.cache_enabled;
            var cacheTtl     = config.cache_ttl;
            var cacheMaxResultsPerIndexer = config.cache_max_results_per_indexer;
            var omdbApiKey = config.omdbkey;
            var omdbApiUrl = config.omdburl;

            if (config.basepathoverride != serverConfig.BasePathOverride)
            {
                webHostRestartNeeded = true;
            }

            if (config.flaresolverrurl != serverConfig.FlareSolverrUrl)
            {
                serverConfig.FlareSolverrUrl = config.flaresolverrurl;
                configService.SaveConfig(serverConfig);
                webHostRestartNeeded = true;
            }

            serverConfig.UpdateDisabled            = updateDisabled;
            serverConfig.UpdatePrerelease          = preRelease;
            serverConfig.BasePathOverride          = basePathOverride;
            serverConfig.CacheEnabled              = cacheEnabled;
            serverConfig.CacheTtl                  = cacheTtl;
            serverConfig.CacheMaxResultsPerIndexer = cacheMaxResultsPerIndexer;

            serverConfig.RuntimeSettings.BasePath = serverService.BasePath();
            configService.SaveConfig(serverConfig);

            if (omdbApiKey != serverConfig.OmdbApiKey || omdbApiUrl != serverConfig.OmdbApiUrl)
            {
                serverConfig.OmdbApiKey = omdbApiKey;
                serverConfig.OmdbApiUrl = omdbApiUrl.TrimEnd('/');
                configService.SaveConfig(serverConfig);
                // HACK
                indexerService.InitAggregateIndexer();
            }

            if (config.proxy_type != serverConfig.ProxyType ||
                config.proxy_url != serverConfig.ProxyUrl ||
                config.proxy_port != serverConfig.ProxyPort ||
                config.proxy_username != serverConfig.ProxyUsername ||
                config.proxy_password != serverConfig.ProxyPassword)
            {
                if (config.proxy_port < 1 || config.proxy_port > 65535)
                {
                    throw new Exception("The port you have selected is invalid, it must be below 65535.");
                }

                serverConfig.ProxyType     = string.IsNullOrWhiteSpace(config.proxy_url) ? ProxyType.Disabled : config.proxy_type;
                serverConfig.ProxyUrl      = config.proxy_url;
                serverConfig.ProxyPort     = config.proxy_port;
                serverConfig.ProxyUsername = config.proxy_username;
                serverConfig.ProxyPassword = config.proxy_password;
                configService.SaveConfig(serverConfig);
                webHostRestartNeeded = true;

                // Remove all results from cache so we can test the new proxy
                cacheService.CleanCache();
            }

            if (port != serverConfig.Port || external != serverConfig.AllowExternal)
            {
                if (ServerUtil.RestrictedPorts.Contains(port))
                {
                    throw new Exception("The port you have selected is restricted, try a different one.");
                }

                if (port < 1 || port > 65535)
                {
                    throw new Exception("The port you have selected is invalid, it must be below 65535.");
                }

                // Save port to the config so it can be picked up by the if needed when running as admin below.
                serverConfig.AllowExternal = external;
                serverConfig.Port          = port;
                configService.SaveConfig(serverConfig);

                // On Windows change the url reservations
                if (Environment.OSVersion.Platform != PlatformID.Unix)
                {
                    if (!ServerUtil.IsUserAdministrator())
                    {
                        try
                        {
                            var consoleExePath = EnvironmentUtil.JackettExecutablePath().Replace(".dll", ".exe");
                            processService.StartProcessAndLog(consoleExePath, "--ReserveUrls", true);
                        }
                        catch
                        {
                            serverConfig.Port          = originalPort;
                            serverConfig.AllowExternal = originalAllowExternal;
                            configService.SaveConfig(serverConfig);

                            throw new Exception("Failed to acquire admin permissions to reserve the new port.");
                        }
                    }
                    else
                    {
                        serverService.ReserveUrls();
                    }
                }

                webHostRestartNeeded = true;
            }

            if (saveDir != serverConfig.BlackholeDir)
            {
                if (!string.IsNullOrEmpty(saveDir))
                {
                    if (!Directory.Exists(saveDir))
                    {
                        throw new Exception("Blackhole directory does not exist");
                    }
                }

                serverConfig.BlackholeDir = saveDir;
                configService.SaveConfig(serverConfig);
            }

            if (webHostRestartNeeded)
            {
                // we have to restore log level when the server restarts because we are not saving the state in the
                // configuration. when the server restarts the UI is inconsistent with the active log level
                // https://github.com/Jackett/Jackett/issues/8315
                SetEnhancedLogLevel(false);

                Thread.Sleep(500);
                logger.Info("Restarting webhost due to configuration change");
                Helper.RestartWebHost();
            }
            else
            {
                SetEnhancedLogLevel(enhancedLogging);
            }

            serverConfig.ConfigChanged();

            return(Json(serverConfig));
        }