Beispiel #1
0
        /// <summary>
        /// Create a new Product
        /// </summary>
        /// <returns></returns>
        public Response Create(Objects.Product product)
        {
            //Props
            int      statusCode = 201;
            Response response   = new Response();

            //Random Tokens
            product.Id = ServerUtil.GenerateToken(TokenLengths.ProductIdLength);
            var color             = ColorUtil.ToHEXColor(product.Color);
            var isBalanceRequired = Func.ToString(product.IsBalanceRequired);

            try
            {
                //Database.Reconnect();
                Database.Connection.Open();
                var query = " INSERT INTO Products (ProductId, Barcode, Name, Description, Stock, IsBalanceRequired, SupplyPrice, RetailPrice, Markup," +
                            " TaxId, TypeId, BrandId, SupplierId, ImageBlobId, Color) " +
                            " VALUES (@ProductId, @Barcode, @Name, @Description, @Stock, @IsBalanceRequired, @SupplyPrice, @RetailPrice, @Markup," +
                            " @TaxId, @TypeId, @BrandId, @SupplierId, @ImageBlobId, @Color) ";
                MySqlCommand Command = new MySqlCommand(query, Database.Connection);

                Command.Parameters.AddWithValue("ProductId", product.Id);
                Command.Parameters.AddWithValue("Barcode", product.Barcode);
                Command.Parameters.AddWithValue("Name", product.Name);
                Command.Parameters.AddWithValue("Description", product.Description);
                Command.Parameters.AddWithValue("Stock", product.Stock);
                Command.Parameters.AddWithValue("IsBalanceRequired", isBalanceRequired);
                Command.Parameters.AddWithValue("SupplyPrice", product.SupplyPrice);
                Command.Parameters.AddWithValue("RetailPrice", product.RetailPrice);
                Command.Parameters.AddWithValue("Markup", product.Markup);
                Command.Parameters.AddWithValue("Color", color);

                Command.Parameters.AddWithValue("TaxId", product.Tax.Id);
                Command.Parameters.AddWithValue("TypeId", product.Type.Id);
                Command.Parameters.AddWithValue("BrandId", product.Brand.Id);
                Command.Parameters.AddWithValue("SupplierId", product.Supplier.Id);
                Command.Parameters.AddWithValue("ImageBlobId", product.ImageBlobId);

                Command.ExecuteNonQuery();

                Database.Connection.Close();

                // Status Code
                statusCode = 201;
            }
            catch (MySqlException e)
            {
                if (e.Message.Contains("Duplicate entry"))
                {
                    //Duplicate Key or Conflict
                    statusCode = 409;
                }
                else
                {
                    // Internal Server Error
                    statusCode = 500;
                }
                Logger.QueryError(e, "Product", "Create");
            }
            //Close Connection if Open
            if (Database.Connection.State == ConnectionState.Open)
            {
                Database.Connection.Close();
            }

            //Response

            response.StatusCode = statusCode;
            response.Data       = product;

            return(response);
        }
Beispiel #2
0
        static void Main(string[] args)
        {
            var config = ServerUtil.LoadConfig().GetServerConfig(EServerType.GameServer);

            ServerUtil.RunServer <GameServer>(config);
        }
Beispiel #3
0
        private void ProcessUpdate(UpdaterConsoleOptions options)
        {
            var updateLocation = GetUpdateLocation();

            if (!(updateLocation.EndsWith("\\") || updateLocation.EndsWith("/")))
            {
                updateLocation += Path.DirectorySeparatorChar;
            }

            var pids = new int[] { };

            if (options.KillPids != null)
            {
                var pidsStr = options.KillPids.Split(',').Where(pid => !string.IsNullOrWhiteSpace(pid)).ToArray();
                pids = Array.ConvertAll(pidsStr, pid => int.Parse(pid));
            }

            var isWindows     = Environment.OSVersion.Platform == PlatformID.Win32NT;
            var trayRunning   = false;
            var trayProcesses = Process.GetProcessesByName("JackettTray");

            if (isWindows)
            {
                if (trayProcesses.Length > 0)
                {
                    foreach (var proc in trayProcesses)
                    {
                        try
                        {
                            logger.Info("Killing tray process " + proc.Id);
                            proc.Kill();
                            trayRunning = true;
                        }
                        catch { }
                    }
                }

                // on unix we don't have to wait (we can overwrite files which are in use)
                // On unix we kill the PIDs after the update so e.g. systemd can automatically restart the process
                KillPids(pids);
            }

            var variants = new Variants();

            if (variants.IsNonWindowsDotNetCoreVariant(variant))
            {
                // On Linux you can't modify an executable while it is executing
                // https://github.com/Jackett/Jackett/issues/5022
                // https://stackoverflow.com/questions/16764946/what-generates-the-text-file-busy-message-in-unix#comment32135232_16764967
                // Delete the ./jackett executable
                // pdb files are also problematic https://github.com/Jackett/Jackett/issues/5167#issuecomment-489301150

                var jackettExecutable = options.Path.TrimEnd('/') + "/jackett";
                var pdbFiles          = Directory.EnumerateFiles(options.Path, "*.pdb", SearchOption.AllDirectories).ToList();
                var removeList        = pdbFiles;
                removeList.Add(jackettExecutable);

                foreach (var fileForDelete in removeList)
                {
                    try
                    {
                        logger.Info("Attempting to remove: " + fileForDelete);

                        if (File.Exists(fileForDelete))
                        {
                            File.Delete(fileForDelete);
                            logger.Info("Deleted " + fileForDelete);
                        }
                        else
                        {
                            logger.Info("File for deleting not found: " + fileForDelete);
                        }
                    }
                    catch (Exception e)
                    {
                        logger.Error(e);
                    }
                }
            }

            logger.Info("Finding files in: " + updateLocation);
            var files = Directory.GetFiles(updateLocation, "*.*", SearchOption.AllDirectories).OrderBy(x => x).ToList();

            logger.Info($"{files.Count()} update files found");

            try
            {
                foreach (var file in files)
                {
                    var fileName = Path.GetFileName(file).ToLowerInvariant();

                    if (fileName.EndsWith(".zip") || fileName.EndsWith(".tar") || fileName.EndsWith(".gz"))
                    {
                        continue;
                    }

                    var fileCopySuccess = CopyUpdateFile(options.Path, file, updateLocation, false);

                    if (!fileCopySuccess)
                    {
                        //Perform second attempt, this time removing the target file first
                        CopyUpdateFile(options.Path, file, updateLocation, true);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }

            logger.Info("File copying complete");

            // delete old dirs
            var oldDirs = new string[] { "Content/logos" };

            foreach (var oldDir in oldDirs)
            {
                try
                {
                    var deleteDir = Path.Combine(options.Path, oldDir);
                    if (Directory.Exists(deleteDir))
                    {
                        logger.Info("Deleting directory " + deleteDir);
                        Directory.Delete(deleteDir, true);
                    }
                }
                catch (Exception e)
                {
                    logger.Error(e);
                }
            }

            // delete old files
            var oldFiles = new string[] {
                "appsettings.Development.json",
                "Autofac.Integration.WebApi.dll",
                "Content/congruent_outline.png",
                "Content/crissXcross.png",
                "Content/css/jquery.dataTables.css",
                "Content/css/jquery.dataTables_themeroller.css",
                "CsQuery.dll",
                "CurlSharp.dll",
                "CurlSharp.pdb",
                "Definitions/420files.yml",
                "Definitions/alein.yml",
                "Definitions/anidex.yml", // migrated to C#
                "Definitions/aox.yml",
                "Definitions/apollo.yml", // migrated to C# gazelle base tracker
                "Definitions/archetorrent.yml",
                "Definitions/asiandvdclub.yml",
                "Definitions/avg.yml",
                "Definitions/awesomehd.yml", // migrated to C#
                "Definitions/b2s-share.yml",
                "Definitions/bithq.yml",
                "Definitions/bitme.yml",
                "Definitions/bittorrentam.yml",
                "Definitions/blubits.yml",
                "Definitions/bt-scene.yml",
                "Definitions/btbit.yml",
                "Definitions/btkitty.yml",
                "Definitions/btstornet.yml",
                "Definitions/btxpress.yml",
                "Definitions/cinefilhd.yml",
                "Definitions/czteam.yml",
                "Definitions/digbt.yml",
                "Definitions/dragonworld.yml",
                "Definitions/dreamteam.yml",
                "Definitions/eggmeon.yml",
                "Definitions/elitehd.yml",
                "Definitions/elittracker.yml",
                "Definitions/eotforum.yml",
                "Definitions/evolutionpalace.yml",
                "Definitions/extratorrentclone.yml",
                "Definitions/feedurneed.yml",
                "Definitions/freakstrackingsystem.yml",
                "Definitions/freedomhd.yml",
                "Definitions/gdf76.yml",
                "Definitions/gfxnews.yml",
                "Definitions/gods.yml",
                "Definitions/gormogon.yml",
                "Definitions/greeklegends.yml",
                "Definitions/hachede-c.yml",
                "Definitions/hd4free.yml",
                "Definitions/hdbc.yml", // renamed to hdbitscom
                "Definitions/hdclub.yml",
                "Definitions/hdplus.yml",
                "Definitions/hon3yhd-net.yml",
                "Definitions/horriblesubs.yml",
                "Definitions/hyperay.yml",
                "Definitions/idopeclone.yml",
                "Definitions/iloveclassics.yml",
                "Definitions/infinityt.yml",
                "Definitions/isohunt.yml",
                "Definitions/katcrs.yml",
                "Definitions/kikibt.yml",
                "Definitions/lapausetorrents.yml",
                "Definitions/lemencili.yml",
                "Definitions/leparadisdunet.yml",
                "Definitions/maniatorrent.yml",
                "Definitions/manicomioshare.yml",
                "Definitions/megabliz.yml",
                "Definitions/mkvcage.yml",
                "Definitions/music-master.yml",
                "Definitions/nachtwerk.yml",
                "Definitions/nexttorrent.yml",
                "Definitions/nordichd.yml",
                "Definitions/nyaa.yml",
                "Definitions/nyoo.yml",
                "Definitions/passionetorrent.yml",
                "Definitions/polishtracker.yml",
                "Definitions/qctorrent.yml",
                "Definitions/qxr.yml",
                "Definitions/rapidetracker.yml",
                "Definitions/rarbg.yml",
                "Definitions/redtopia.yml",
                "Definitions/rgu.yml",
                "Definitions/rockethd.yml",
                "Definitions/rockhardlossless.yml",
                "Definitions/scenehd.yml", // migrated to C# (use JSON API)
                "Definitions/scenereactor.yml",
                "Definitions/scenexpress.yml",
                "Definitions/secretcinema.yml", // migrated to C# gazelle base tracker
                "Definitions/seedpeer.yml",
                "Definitions/sharingue.yml",
                "Definitions/skytorrents.yml",
                "Definitions/solidtorrents.yml", // migrated to C#
                "Definitions/speed-share.yml",
                "Definitions/t411.yml",
                "Definitions/t411v2.yml",
                "Definitions/tazmaniaden.yml",
                "Definitions/tbplus.yml",
                "Definitions/tehconnection.yml",
                "Definitions/tfile.yml",
                "Definitions/themoviecave.yml",
                "Definitions/theresurrection.yml",
                "Definitions/thetorrents.yml",
                "Definitions/tigers-dl.yml",
                "Definitions/torrentcouch.yml",
                "Definitions/torrentkim.yml",
                "Definitions/torrentproject.yml",
                "Definitions/torrentseeds.yml", // migrated to c#
                "Definitions/torrentsmd.yml",
                "Definitions/torrentvault.yml",
                "Definitions/torrentwal.yml",
                "Definitions/torrentwtf.yml",
                "Definitions/torrof.yml",
                "Definitions/torviet.yml",
                "Definitions/tspate.yml",
                "Definitions/ultimategamerclub.yml",
                "Definitions/ultrahdclub.yml",
                "Definitions/utorrents.yml", // same as SzeneFZ now
                "Definitions/waffles.yml",
                "Definitions/worldofp2p.yml",
                "Definitions/worldwidetorrents.yml",
                "Definitions/xktorrent.yml",
                "Definitions/zetorrents.yml",
                "Microsoft.Owin.dll",
                "Microsoft.Owin.FileSystems.dll",
                "Microsoft.Owin.Host.HttpListener.dll",
                "Microsoft.Owin.Hosting.dll",
                "Microsoft.Owin.StaticFiles.dll",
                "Owin.dll",
                "System.ServiceModel.dll",
                "System.Web.Http.dll",
                "System.Web.Http.Owin.dll",
                "System.Web.Http.Tracing.dll",
                "System.Xml.XPath.XmlDocument.dll"
            };

            foreach (var oldFile in oldFiles)
            {
                try
                {
                    var deleteFile = Path.Combine(options.Path, oldFile);
                    if (File.Exists(deleteFile))
                    {
                        logger.Info("Deleting file " + deleteFile);
                        File.Delete(deleteFile);
                    }
                }
                catch (Exception e)
                {
                    logger.Error(e);
                }
            }

            // kill pids after the update on UNIX
            if (!isWindows)
            {
                KillPids(pids);
            }

            if (!options.NoRestart)
            {
                if (isWindows && (trayRunning || options.StartTray) && !string.Equals(options.Type, "WindowsService", StringComparison.OrdinalIgnoreCase))
                {
                    var startInfo = new ProcessStartInfo()
                    {
                        Arguments       = $"--UpdatedVersion \" {EnvironmentUtil.JackettVersion}\"",
                        FileName        = Path.Combine(options.Path, "JackettTray.exe"),
                        UseShellExecute = true
                    };

                    logger.Info("Starting Tray: " + startInfo.FileName + " " + startInfo.Arguments);
                    Process.Start(startInfo);

                    if (!windowsService.ServiceExists())
                    {
                        //User was running the tray icon, but not using the Windows service, starting Tray icon will start JackettConsole as well
                        return;
                    }
                }

                if (string.Equals(options.Type, "WindowsService", StringComparison.OrdinalIgnoreCase))
                {
                    logger.Info("Starting Windows service");

                    if (ServerUtil.IsUserAdministrator())
                    {
                        windowsService.Start();
                    }
                    else
                    {
                        try
                        {
                            var consolePath = Path.Combine(options.Path, "JackettConsole.exe");
                            processService.StartProcessAndLog(consolePath, "--Start", true);
                        }
                        catch
                        {
                            logger.Error("Failed to get admin rights to start the service.");
                        }
                    }
                }
                else
                {
                    var startInfo = new ProcessStartInfo()
                    {
                        Arguments       = options.Args,
                        FileName        = GetJackettConsolePath(options.Path),
                        UseShellExecute = true
                    };

                    if (isWindows)
                    {
                        //User didn't initiate the update from Windows service and wasn't running Jackett via the tray, must have started from the console
                        startInfo.Arguments      = $"/K {startInfo.FileName} {startInfo.Arguments}";
                        startInfo.FileName       = "cmd.exe";
                        startInfo.CreateNoWindow = false;
                        startInfo.WindowStyle    = ProcessWindowStyle.Normal;
                    }

                    if (variant == Variants.JackettVariant.Mono)
                    {
                        startInfo.Arguments = startInfo.FileName + " " + startInfo.Arguments;
                        startInfo.FileName  = "mono";
                    }

                    if (variant == Variants.JackettVariant.CoreMacOs || variant == Variants.JackettVariant.CoreLinuxAmdx64 ||
                        variant == Variants.JackettVariant.CoreLinuxArm32 || variant == Variants.JackettVariant.CoreLinuxArm64)
                    {
                        startInfo.UseShellExecute = false;
                        startInfo.CreateNoWindow  = true;
                    }

                    logger.Info("Starting Jackett: " + startInfo.FileName + " " + startInfo.Arguments);
                    Process.Start(startInfo);
                }
            }
        }
Beispiel #4
0
        static void Main(string[] args)
        {
            try
            {
                var options = new ConsoleOptions();
                if (!Parser.Default.ParseArguments(args, options) || options.ShowHelp == true)
                {
                    if (options.LastParserState != null && options.LastParserState.Errors.Count > 0)
                    {
                        var help   = new HelpText();
                        var errors = help.RenderParsingErrorsText(options, 2); // indent with two spaces
                        Console.WriteLine("Jackett v" + Engine.ConfigService.GetVersion());
                        Console.WriteLine("Switch error: " + errors);
                        Console.WriteLine("See --help for further details on switches.");
                        Environment.ExitCode = 1;
                        return;
                    }
                    else
                    {
                        var text = HelpText.AutoBuild(options, (HelpText current) => HelpText.DefaultParsingErrorsHandler(options, current));
                        text.Copyright = " ";
                        text.Heading   = "Jackett v" + Engine.ConfigService.GetVersion() + " options:";
                        Console.WriteLine(text);
                        Environment.ExitCode = 1;
                        return;
                    }
                }
                else
                {
                    if (options.ListenPublic && options.ListenPrivate)
                    {
                        Console.WriteLine("You can only use listen private OR listen publicly.");
                        Environment.ExitCode = 1;
                        return;
                    }
                    /*  ======     Options    =====  */

                    // SSL Fix
                    Startup.DoSSLFix = options.SSLFix;

                    // Use curl
                    if (options.Client != null)
                    {
                        Startup.ClientOverride = options.Client.ToLowerInvariant();
                    }

                    // Use Proxy
                    if (options.ProxyConnection != null)
                    {
                        Startup.ProxyConnection = options.ProxyConnection.ToLowerInvariant();
                        Engine.Logger.Info("Proxy enabled. " + Startup.ProxyConnection);
                    }
                    // Logging
                    if (options.Logging)
                    {
                        Startup.LogRequests = true;
                    }

                    // Tracing
                    if (options.Tracing)
                    {
                        Startup.TracingEnabled = true;
                    }

                    // Log after the fact as using the logger will cause the options above to be used

                    if (options.Logging)
                    {
                        Engine.Logger.Info("Logging enabled.");
                    }

                    if (options.Tracing)
                    {
                        Engine.Logger.Info("Tracing enabled.");
                    }

                    if (options.SSLFix == true)
                    {
                        Engine.Logger.Info("SSL ECC workaround enabled.");
                    }
                    else if (options.SSLFix == false)
                    {
                        Engine.Logger.Info("SSL ECC workaround has been disabled.");
                    }

                    // Ignore SSL errors on Curl
                    Startup.IgnoreSslErrors = options.IgnoreSslErrors;
                    if (options.IgnoreSslErrors == true)
                    {
                        Engine.Logger.Info("Jackett will ignore SSL certificate errors.");
                    }

                    // Choose Data Folder
                    if (!string.IsNullOrWhiteSpace(options.DataFolder))
                    {
                        Startup.CustomDataFolder = options.DataFolder.Replace("\"", string.Empty).Replace("'", string.Empty).Replace(@"\\", @"\");
                        Engine.Logger.Info("Jackett Data will be stored in: " + Startup.CustomDataFolder);
                    }

                    /*  ======     Actions    =====  */

                    // Install service
                    if (options.Install)
                    {
                        Engine.ServiceConfig.Install();
                        return;
                    }

                    // Uninstall service
                    if (options.Uninstall)
                    {
                        Engine.Server.ReserveUrls(doInstall: false);
                        Engine.ServiceConfig.Uninstall();
                        return;
                    }

                    // Reserve urls
                    if (options.ReserveUrls)
                    {
                        Engine.Server.ReserveUrls(doInstall: true);
                        return;
                    }

                    // Start Service
                    if (options.StartService)
                    {
                        if (!Engine.ServiceConfig.ServiceRunning())
                        {
                            Engine.ServiceConfig.Start();
                        }
                        return;
                    }

                    // Stop Service
                    if (options.StopService)
                    {
                        if (Engine.ServiceConfig.ServiceRunning())
                        {
                            Engine.ServiceConfig.Stop();
                        }
                        return;
                    }

                    // Migrate settings
                    if (options.MigrateSettings)
                    {
                        Engine.ConfigService.PerformMigration();
                        return;
                    }


                    // Show Version
                    if (options.ShowVersion)
                    {
                        Console.WriteLine("Jackett v" + Engine.ConfigService.GetVersion());
                        return;
                    }

                    /*  ======     Overrides    =====  */

                    // Override listen public
                    if (options.ListenPublic || options.ListenPrivate)
                    {
                        if (Engine.Server.Config.AllowExternal != options.ListenPublic)
                        {
                            Engine.Logger.Info("Overriding external access to " + options.ListenPublic);
                            Engine.Server.Config.AllowExternal = options.ListenPublic;
                            if (System.Environment.OSVersion.Platform != PlatformID.Unix)
                            {
                                if (ServerUtil.IsUserAdministrator())
                                {
                                    Engine.Server.ReserveUrls(doInstall: true);
                                }
                                else
                                {
                                    Engine.Logger.Error("Unable to switch to public listening without admin rights.");
                                    Environment.ExitCode = 1;
                                    return;
                                }
                            }

                            Engine.Server.SaveConfig();
                        }
                    }

                    // Override port
                    if (options.Port != 0)
                    {
                        if (Engine.Server.Config.Port != options.Port)
                        {
                            Engine.Logger.Info("Overriding port to " + options.Port);
                            Engine.Server.Config.Port = options.Port;
                            if (System.Environment.OSVersion.Platform != PlatformID.Unix)
                            {
                                if (ServerUtil.IsUserAdministrator())
                                {
                                    Engine.Server.ReserveUrls(doInstall: true);
                                }
                                else
                                {
                                    Engine.Logger.Error("Unable to switch ports when not running as administrator");
                                    Environment.ExitCode = 1;
                                    return;
                                }
                            }

                            Engine.Server.SaveConfig();
                        }
                    }
                }

                Engine.Server.Initalize();
                Engine.Server.Start();
                Engine.RunTime.Spin();
                Engine.Logger.Info("Server thread exit");
            }
            catch (Exception e)
            {
                Engine.Logger.Error(e, "Top level exception");
            }
        }
Beispiel #5
0
        /// <summary>
        /// Create a new User
        /// </summary>
        /// <param name="username"> Username</param>
        /// <param name="email"> User Email</param>
        /// <param name="password"> User Password</param>
        /// <param name="pin"> User PIN </param>
        /// <returns></returns>
        public Response Register(Objects.User user, Objects.Store store)
        {
            //Props
            int      statusCode = 201;
            Response response   = new Response();

            //Random Tokens
            string userId    = ServerUtil.GenerateToken(TokenLengths.UserIdLength);
            string userToken = ServerUtil.GenerateToken(TokenLengths.UserTokenLength);

            user.PinCode = user.PinCode ?? ServerUtil.GenerateRandomNum(minChar: 100000, maxChar: 999999).ToString();
            store.Id     = store.Id ?? Properties.Settings.Default.StoreId;
            var _color = ColorUtil.ToHEXColor(user.Color);

            try
            {
                //Open MySqlConnection
                Database.Connection.Open();
                //Query
                string query = "INSERT INTO Users (UserId, Token, StoreId, Username, Password, FirstName, LastName, Email, " +
                               " PinCode, Role, Locale, Color, ImageBlobId) " +
                               "VALUES (@UserId, @Token, @StoreId, @Username, @Password, @FirstName, @LastName, @Email, " +
                               " @PinCode, @Role, @Locale, @Color, @ImageBlobId)";

                //Execute Query With MySqlConnection
                MySqlCommand Command = new MySqlCommand(query, Database.Connection);

                //Parameters For Security Purpose
                Command.Parameters.AddWithValue("UserId", userId);
                Command.Parameters.AddWithValue("Token", userToken);
                Command.Parameters.AddWithValue("StoreId", store.Id);
                Command.Parameters.AddWithValue("Username", user.Username);
                Command.Parameters.AddWithValue("Password", user.Password);
                Command.Parameters.AddWithValue("FirstName", user.FirstName);
                Command.Parameters.AddWithValue("LastName", user.LastName);
                Command.Parameters.AddWithValue("Email", user.Email);
                Command.Parameters.AddWithValue("PinCode", user.PinCode);
                Command.Parameters.AddWithValue("Role", user.Role);
                Command.Parameters.AddWithValue("Locale", user.Locale);
                Command.Parameters.AddWithValue("Color", _color);
                Command.Parameters.AddWithValue("ImageBlobId", user.ImageBlobId);

                Command.ExecuteNonQuery();

                //Close Connection
                Database.Connection.Close();

                // Status Code
                statusCode = 201;
            }
            catch (MySqlException e)
            {
                if (e.Message.Contains("Duplicate entry"))
                {
                    //Duplicate Key or Conflict
                    statusCode = 409;
                }
                else
                {
                    // Internal Server Error
                    statusCode = 500;
                }
                Logger.QueryError(e, "User", "Register");
            }
            //Close Connection if Open
            if (Database.Connection.State == ConnectionState.Open)
            {
                Database.Connection.Close();
            }

            //Response

            response.StatusCode = statusCode;
            response.Data       = user;

            return(response);
        }
        override protected async Task <WebClientByteResult> Run(WebRequest request)
        {
            var args = new StringBuilder();

            if (Startup.ProxyConnection != null)
            {
                args.AppendFormat("-x " + Startup.ProxyConnection + " ");
            }

            args.AppendFormat("--url \"{0}\" ", request.Url);

            if (request.EmulateBrowser)
            {
                args.AppendFormat("-i  -sS --user-agent \"{0}\" ", BrowserUtil.ChromeUserAgent);
            }
            else
            {
                args.AppendFormat("-i  -sS --user-agent \"{0}\" ", "Jackett/" + configService.GetVersion());
            }

            if (!string.IsNullOrWhiteSpace(request.Cookies))
            {
                args.AppendFormat("--cookie \"{0}\" ", request.Cookies);
            }

            if (!string.IsNullOrWhiteSpace(request.Referer))
            {
                args.AppendFormat("--referer \"{0}\" ", request.Referer);
            }

            if (!string.IsNullOrEmpty(request.RawBody))
            {
                var postString = StringUtil.PostDataFromDict(request.PostData);
                args.AppendFormat("--data \"{0}\" ", request.RawBody.Replace("\"", "\\\""));
            }
            else if (request.PostData != null && request.PostData.Count() > 0)
            {
                var postString = StringUtil.PostDataFromDict(request.PostData);
                args.AppendFormat("--data \"{0}\" ", postString);
            }

            var tempFile = Path.GetTempFileName();

            args.AppendFormat("--output \"{0}\" ", tempFile);

            if (Startup.DoSSLFix == true)
            {
                // http://stackoverflow.com/questions/31107851/how-to-fix-curl-35-cannot-communicate-securely-with-peer-no-common-encryptio
                // https://git.fedorahosted.org/cgit/mod_nss.git/plain/docs/mod_nss.html
                args.Append("--cipher " + SSLFix.CipherList);
            }
            if (Startup.IgnoreSslErrors == true)
            {
                args.Append("-k ");
            }
            args.Append("-H \"Accept-Language: en-US,en\" ");
            args.Append("-H \"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\" ");
            string stdout = null;
            await Task.Run(() =>
            {
                stdout = processService.StartProcessAndGetOutput(System.Environment.OSVersion.Platform == PlatformID.Unix ? "curl" : "curl.exe", args.ToString(), true);
            });

            var outputData = File.ReadAllBytes(tempFile);

            File.Delete(tempFile);
            stdout = Encoding.UTF8.GetString(outputData);
            var result    = new WebClientByteResult();
            var headSplit = stdout.IndexOf("\r\n\r\n");

            if (headSplit < 0)
            {
                throw new Exception("Invalid response");
            }
            var headers = stdout.Substring(0, headSplit);

            if (Startup.ProxyConnection != null)
            {
                // the proxy provided headers too so we need to split headers again
                var headSplit1 = stdout.IndexOf("\r\n\r\n", headSplit + 4);
                if (headSplit1 > 0)
                {
                    headers   = stdout.Substring(headSplit + 4, headSplit1 - (headSplit + 4));
                    headSplit = headSplit1;
                }
            }
            var headerCount   = 0;
            var cookieBuilder = new StringBuilder();
            var cookies       = new List <Tuple <string, string> >();

            foreach (var header in headers.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries))
            {
                if (headerCount == 0)
                {
                    var responseCode = int.Parse(header.Split(' ')[1]);
                    result.Status = (HttpStatusCode)responseCode;
                }
                else
                {
                    var headerSplitIndex = header.IndexOf(':');
                    if (headerSplitIndex > 0)
                    {
                        var name  = header.Substring(0, headerSplitIndex).ToLowerInvariant();
                        var value = header.Substring(headerSplitIndex + 1);
                        switch (name)
                        {
                        case "set-cookie":
                            var nameSplit = value.IndexOf('=');
                            if (nameSplit > -1)
                            {
                                cookies.Add(new Tuple <string, string>(value.Substring(0, nameSplit), value.Substring(0, value.IndexOf(';') + 1)));
                            }
                            break;

                        case "location":
                            result.RedirectingTo = value.Trim();
                            break;

                        case "refresh":
                            //"Refresh: 8;URL=/cdn-cgi/l/chk_jschl?pass=1451000679.092-1vJFUJLb9R"
                            var redirval = "";
                            var start    = value.IndexOf("=");
                            var end      = value.IndexOf(";");
                            var len      = value.Length;
                            if (start > -1)
                            {
                                redirval             = value.Substring(start + 1);
                                result.RedirectingTo = redirval;
                                // normally we don't want a serviceunavailable (503) to be a redirect, but that's the nature
                                // of this cloudflare approach..don't want to alter BaseWebResult.IsRedirect because normally
                                // it shoudln't include service unavailable..only if we have this redirect header.
                                result.Status = System.Net.HttpStatusCode.Redirect;
                                var redirtime = Int32.Parse(value.Substring(0, end));
                                System.Threading.Thread.Sleep(redirtime * 1000);
                            }
                            break;
                        }
                    }
                }
                headerCount++;
            }

            foreach (var cookieGroup in cookies.GroupBy(c => c.Item1))
            {
                cookieBuilder.AppendFormat("{0} ", cookieGroup.Last().Item2);
            }

            result.Cookies = cookieBuilder.ToString().Trim();
            result.Content = new byte[outputData.Length - (headSplit + 3)];
            var dest = 0;

            for (int i = headSplit + 4; i < outputData.Length; i++)
            {
                result.Content[dest] = outputData[i];
                dest++;
            }

            logger.Debug("WebClientByteResult returned " + result.Status);
            ServerUtil.ResureRedirectIsFullyQualified(request, result);
            return(result);
        }
        /// <summary>
        /// Tries to start feedback.
        /// </summary>
        private void TryStartFeedback(Action <Exception> onOncompleted)
        {
            _onCompleted = onOncompleted;
            Exception completedResult = null;

            try
            {
                _outputPath = GetOuputPath();
                MessageBoxResult result = Popup.Show("Your actions are now being recorded. When you are ready to send your feedback please click 'Stop recording feedback' in the top right corner.", "Recording In Progress", MessageBoxButton.OK, MessageBoxImage.Information, null);
                if (result == MessageBoxResult.None)
                {
                    if (onOncompleted != null)
                    {
                        onOncompleted(null);
                    }
                    return;
                }
                FeedBackRecorder.StartRecording(_outputPath);
            }
            catch (FeedbackRecordingInprogressException feedbackRecordingInprogressException)
            {
                MessageBoxResult result = Popup.Show("A recording session is already in progress, would you like to try end it?", "Recording In Progress", MessageBoxButton.YesNoCancel, MessageBoxImage.Error, null);
                if (result == MessageBoxResult.Yes)
                {
                    FeedBackRecorder.KillAllRecordingTasks();
                    TryStartFeedback(onOncompleted);
                }
                else
                {
                    completedResult = feedbackRecordingInprogressException;
                }
            }
            //2013.02.06: Ashley Lewis - Bug 8611
            catch (FeedbackRecordingProcessFailedToStartException feedbackRecordingProcessFailedToStartException)
            {
                MessageBoxResult result = Popup.Show("The recording session cannot start at this time, would you like to send a standard email feedback?", "Recording Not Started", MessageBoxButton.YesNoCancel, MessageBoxImage.Error, null);
                if (result == MessageBoxResult.Yes)
                {
                    new FeedbackInvoker().InvokeFeedback(Factory.FeedbackFactory.CreateEmailFeedbackAction(new Dictionary <string, string>(), ServerUtil.GetLocalhostServer()));
                    TryCancelFeedback();
                }
                else
                {
                    completedResult = feedbackRecordingProcessFailedToStartException;
                }
            }
            catch (Exception e)
            {
                if (onOncompleted != null)
                {
                    completedResult = e;
                }
                else
                {
                    throw;
                }
            }

            if (onOncompleted != null && completedResult != null)
            {
                onOncompleted(completedResult);
            }
        }
Beispiel #8
0
        protected void RefreshUrlMappingData()
        {
            if (HttpContext.Current.Cache[kCACHE_KEY] != null)
            {
                return;
            }

            lock (_synclock)
            {
                if (HttpContext.Current.Cache[kCACHE_KEY] != null)
                {
                    return;
                }

                _urlMappings.Clear();
                _menuItems.Clear();

                List <string> routefiles = new List <string>();

                string root = ServerUtil.MapPath("~");

                foreach (var item in AreaInitializer.Areas.Keys)
                {
                    if (item.Equals("/"))
                    {
                        routefiles.Add(Path.Combine(root, "App_Data" + Path.DirectorySeparatorChar + "routes.config"));
                    }
                    else
                    {
                        routefiles.Add(Path.Combine(root, item.Substring(1) + Path.DirectorySeparatorChar + "routes.config"));
                    }
                }

                foreach (var item in routefiles)
                {
                    string vp = Path.GetFileName(Path.GetDirectoryName(item)).ToLowerInvariant();
                    if (string.Equals(vp, "App_Data", StringComparison.InvariantCultureIgnoreCase))
                    {
                        vp = "/";
                    }
                    else
                    {
                        vp = "/" + vp;
                    }

                    if (!AreaInitializer.Areas.ContainsKey(vp))
                    {
                        throw new WebException("virtual path not found: {0}", vp);
                    }

                    IArea site = AreaInitializer.Areas[vp];

                    UrlMappingItemCollection         routes = new UrlMappingItemCollection();
                    Dictionary <int, NavigationItem> menus  = new Dictionary <int, NavigationItem>();

                    XmlUrlMappingProvider.ParseXml(item, routes, menus, IncomingQueryStringBehavior.PassThrough);

                    _urlMappings[site.AreaKey] = routes;
                    _menuItems[site.AreaKey]   = menus;
                }

                _fileDependency = new CacheDependency(Path.Combine(root, "App_Data" + Path.DirectorySeparatorChar + "routes.config"));
                HttpRuntime.Cache.Insert(kCACHE_KEY, "dummyValue", _fileDependency, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.High, null);

                _latestRefresh = DateTime.Now;
            }
        }
Beispiel #9
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 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 baseUrlOverride = config.baseurloverride;

            if (baseUrlOverride != serverConfig.BaseUrlOverride)
            {
                baseUrlOverride = baseUrlOverride.TrimEnd('/');
                if (string.IsNullOrWhiteSpace(baseUrlOverride))
                {
                    baseUrlOverride = "";
                }
                else if (!Uri.TryCreate(baseUrlOverride, UriKind.Absolute, out var uri) ||
                         !(uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps))
                {
                    throw new Exception("Base URL Override is invalid. Example: http://jackett:9117");
                }

                serverConfig.BaseUrlOverride = baseUrlOverride;
                configService.SaveConfig(serverConfig);
            }

            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;
            }

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

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

            if (config.flaresolverrurl != serverConfig.FlareSolverrUrl ||
                config.flaresolverr_maxtimeout != serverConfig.FlareSolverrMaxTimeout)
            {
                if (string.IsNullOrWhiteSpace(config.flaresolverrurl))
                {
                    config.flaresolverrurl = "";
                }
                else if (!Uri.TryCreate(config.flaresolverrurl, UriKind.Absolute, out var uri) ||
                         !(uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps))
                {
                    throw new Exception("FlareSolverr API URL is invalid. Example: http://127.0.0.1:8191");
                }

                if (config.flaresolverr_maxtimeout < 5000)
                {
                    throw new Exception("FlareSolverr Max Timeout must be greater than 5000 ms.");
                }

                serverConfig.FlareSolverrUrl        = config.flaresolverrurl;
                serverConfig.FlareSolverrMaxTimeout = config.flaresolverr_maxtimeout;
                configService.SaveConfig(serverConfig);
                webHostRestartNeeded = true;
            }

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

            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));
        }
Beispiel #10
0
        private void CollectConfigurationOnOpening(object source, DocumentOpeningEventArgs args)
        {
            try
            {
                string pathName = args.PathName;
                if (!string.IsNullOrEmpty(pathName) && args.DocumentType == DocumentType.Project)
                {
                    BasicFileInfo fileInfo = BasicFileInfo.Extract(pathName);
                    if (fileInfo.IsWorkshared)
                    {
                        if (!socketOn)
                        {
                            ConnectSocket();
                        }

                        string centralPath = fileInfo.CentralPath;
                        if (!string.IsNullOrEmpty(centralPath))
                        {
                            //serch for config
                            LogUtil.AppendLog(centralPath + " Opening.");
                            Configuration configFound = ServerUtil.GetConfigurationByCentralPath(centralPath);
                            if (null != configFound)
                            {
                                //check if the single session should be activated
                                if (SingleSessionMonitor.CancelOpening(centralPath, configFound))
                                {
                                    if (args.Cancellable)
                                    {
                                        SingleSessionWindow ssWindow = new SingleSessionWindow(centralPath);
                                        if ((bool)ssWindow.ShowDialog())
                                        {
                                            args.Cancel();
                                            return;
                                        }
                                    }
                                }

                                if (configDictionary.ContainsKey(centralPath))
                                {
                                    configDictionary.Remove(centralPath);
                                }
                                configDictionary.Add(centralPath, configFound);

                                Project projectFound = ServerUtil.GetProjectByConfigurationId(configFound._id);
                                if (null != projectFound)
                                {
                                    if (projectDictionary.ContainsKey(centralPath))
                                    {
                                        projectDictionary.Remove(centralPath);
                                    }
                                    projectDictionary.Add(centralPath, projectFound);
                                }

                                LogUtil.AppendLog("Configuration Found: " + configFound._id);
                            }
                            else
                            {
                                //not a seed file, just check if the single session is activated
                                if (SingleSessionMonitor.SingleSessionActivated)
                                {
                                    SingleSessionWindow ssWindow = new SingleSessionWindow(centralPath);
                                    if ((bool)ssWindow.ShowDialog())
                                    {
                                        args.Cancel();
                                        return;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message;
                LogUtil.AppendLog("CollectConfigurationOnOpening:" + ex.Message);
            }
        }
Beispiel #11
0
        public string render_lazy_include()
        {
            if (!ViewData.ContainsKey("_lazy_include_"))
            {
                return(string.Empty);
            }

            ClientScriptProxy csp = ClientScriptProxy.Current;

            Dictionary <string, List <string> > includes = JContext.Current.ViewData["_lazy_include_"] as Dictionary <string, List <string> >;

            List <string> cssfiles = new List <string>();
            Dictionary <string, string> jsfiles = new Dictionary <string, string>();
            List <string> scripts = new List <string>();

            bool is_css = false;

            foreach (var item in includes.Keys)
            {
                string url = item;

                if (item.Contains(";"))
                {
                    is_css = item.Contains(".css");

                    List <string> hrefs = new List <string>();

                    string[] strs = StringUtil.Split(item, ";", true, true);
                    for (int i = 0; i < strs.Length; i++)
                    {
                        string href = strs[i];
                        if (!href.Contains("/"))
                        {
                            href = Resources.Utility.GetResourceUrl(href);
                        }

                        if (csp.IsScriptRended(href))
                        {
                            continue;
                        }

                        csp.SetScriptRended(href);

                        if (is_css && !Area.CombineCss)
                        {
                            cssfiles.Add(href);
                        }
                        else
                        {
                            hrefs.Add(href);
                        }
                    }

                    for (int i = hrefs.Count - 1; i >= 0; i--)
                    {
                        string href = hrefs[i];

                        if (jsfiles.ContainsKey(href))
                        {
                            jsfiles[href] = includes[item].Join(";");
                        }
                    }

                    string ahref = hrefs.Count == 0 ? cssfiles[0] : hrefs[0];
                    ahref = ahref.Replace(AreaConfig.Instance.VirtualPath, "/").TrimStart('/');

                    string path = "/";
                    if (ahref.IndexOf("/") != -1)
                    {
                        path = ahref.Substring(0, ahref.IndexOf("/") + 1);
                    }

                    // comine url
                    if (is_css && Area.CombineCss)
                    {
                        url = Utility.FormatCssUrl(Area, string.Format("{2}_resc.aspx?f={0}&t=text/css&v={1}",
                                                                       ServerUtil.UrlEncode(StringUtil.CollectionToCommaDelimitedString(hrefs)),
                                                                       AreaConfig.Instance.CssVersion,
                                                                       path));
                    }
                    else if (!is_css)
                    {
                        url = Utility.FormatJsUrl(AreaConfig.Instance, string.Format("{2}_resc.aspx?f={0}&t=text/javascript&v={1}",
                                                                                     ServerUtil.UrlEncode(StringUtil.CollectionToCommaDelimitedString(hrefs)),
                                                                                     AreaConfig.Instance.CssVersion,
                                                                                     path));
                    }
                    else
                    {
                        continue;
                    }
                }
                else if (!item.Contains("/"))
                {
                    url = Resources.Utility.GetResourceUrl(item);

                    is_css = item.Contains(".css");
                }
                else
                {
                    is_css = url.Contains(".css");
                }

                if (csp.IsScriptRended(url))
                {
                    scripts.AddRange(includes[item]);
                    continue;
                }

                csp.SetScriptRended(url);

                if (is_css)
                {
                    cssfiles.Add(url);
                }
                else
                {
                    jsfiles.Add(url, includes[item].Join(";"));
                }
            }

            StringBuilder sb = new StringBuilder();

            sb.Append("<script type='text/javascript'>");

            sb.Append("$(function(){");

            if (cssfiles.Count > 0 || jsfiles.Count > 0)
            {
                sb.Append("lazy_include({");
                sb.AppendFormat("cssFiles:[{0}],", StringUtil.CollectionToDelimitedString(cssfiles, StringUtil.Comma, "'"));
                sb.Append("jsFiles:[");

                var i = 0;
                foreach (var item in jsfiles.Keys)
                {
                    if (i != 0)
                    {
                        sb.Append(",");
                    }

                    i++;

                    sb.Append("{url:'" + item + "', cb: function(){" + jsfiles[item] + "} }");
                }

                sb.Append("]");

                sb.Append("});");
            }

            sb.Append(scripts.Join(";"));

            sb.Append("});");

            sb.Append("</script>");

            return(sb.ToString());
        }
        public void ApplyExecuted(object param)
        {
            try
            {
                string content = "";
                string errMsg  = "";

                HttpStatusCode deleted = HttpStatusCode.Unused;
                HttpStatusCode updated = HttpStatusCode.Unused;
                HttpStatusCode added   = HttpStatusCode.Unused;
                //delete
                var existingKeynoteIds = from keynote in keynoteList where KeynoteToDelete.Contains(keynote._id) select keynote._id;
                if (existingKeynoteIds.Count() > 0)
                {
                    foreach (string keynoteId in existingKeynoteIds)
                    {
                        deleted = ServerUtil.DeleteKeynote(out content, out errMsg, keynoteId);
                    }
                }
                else
                {
                    deleted = HttpStatusCode.OK;
                }

                var keynoteToUpdateIds = from keynoteId in KeynoteToUpdate.Keys where !KeynoteToDelete.Contains(keynoteId) select keynoteId;
                if (keynoteToUpdateIds.Count() > 0)
                {
                    foreach (string keynoteId in keynoteToUpdateIds)
                    {
                        updated = ServerUtil.UpdateKeynote(out content, out errMsg, KeynoteToUpdate[keynoteId]);
                    }
                }
                else
                {
                    updated = HttpStatusCode.Accepted;
                }

                var pureAddedList = from keynote in KeynoteToAdd.Values where !KeynoteToDelete.Contains(keynote._id) && !KeynoteToUpdate.ContainsKey(keynote._id) select keynote;
                if (pureAddedList.Count() > 0)
                {
                    added = ServerUtil.PostKeynote(out content, out errMsg, pureAddedList.ToList());
                }
                else
                {
                    added = HttpStatusCode.OK;
                }

                if (deleted == HttpStatusCode.OK && updated == HttpStatusCode.Accepted && added == HttpStatusCode.OK)
                {
                    UserChanged     = false;
                    this.StatusText = "Ready";
                    KeynoteToDelete.Clear();
                    KeynoteToUpdate.Clear();
                    KeynoteToAdd.Clear();
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message;
            }
        }
Beispiel #13
0
            internal static readonly string ServerFolderUrl = "YOUR_FOLDER_GOES_HERE"; // ex. //var/www/rigle/vendstor/uploads
            /// <summary>
            /// Upload File => returns folder/token.extension as Response
            /// </summary>
            /// <returns></returns>
            public static Response Upload(Objects.File file)
            {
                int      statusCode = 200;
                Response response   = new Response();

                try
                {
                    //Get Paths
                    var fileName      = $@"{ ( (!file.UseCustomName) ? ServerUtil.GenerateToken(10) : file.SaveName ) }{ file.Extension }";
                    var serverAddress = $@"{ftpServerPath}{ file.ServerFolder }{ fileName }";

                    //Create Request
                    ftpWebRequest             = WebRequest.Create(new Uri(string.Format(serverAddress))) as FtpWebRequest;
                    ftpWebRequest.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
                    ftpWebRequest.Method      = WebRequestMethods.Ftp.UploadFile;

                    ftpWebRequest.UseBinary  = true;
                    ftpWebRequest.UsePassive = true;
                    ftpWebRequest.KeepAlive  = false;

                    using (FileStream fileStream = System.IO.File.OpenRead(file.SystemFileName))
                    {
                        //Request Stream
                        Stream ftpRequestStream = ftpWebRequest.GetRequestStream();
                        fileStream.CopyTo(ftpRequestStream);
                        ftpRequestStream.Close();
                    }

                    // OK, Accepted
                    statusCode = 200;

                    //Send Path Without Server Domain Name
                    file.Path     = serverAddress.Replace(ftpServerPath, "").Replace(ServerFolderUrl, "");
                    file.FullPath = serverAddress.Replace("ftp", "http").Replace(ServerFolderUrl, "/");

                    response.Data       = file;
                    response.StatusCode = statusCode;
                }

                catch (WebException e)
                {
                    FtpWebResponse ftpWebResponse = (FtpWebResponse)e.Response;
                    if (ftpWebResponse.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
                    {
                        ftpWebResponse.Close();
                        Logger.Error(e, 500, "FileTransfer", "Upload");
                    }
                    else
                    {
                        ftpWebResponse.Close();
                    }
                }
                catch (Exception e)
                {
                    //[HTTP Status Code] Internal Server Error
                    response.StatusCode = 500;
                    Logger.Error(e, 500, "FileTransfer", "Upload");
                }

                return(response);
            }
 static Action <Type> CreateShowExampleWorkflowAction()
 {
     return(type => WorkflowDesignerUtils.ShowExampleWorkflow(type.Name, ServerUtil.GetLocalhostServer(), null));
 }
        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();
        }
        protected override void CreateChildControls()
        {
            if (!IsFile)
            {
                return;
            }

            Controls.Clear();

            bool loaded = false;

            string skinFilename = GetSkinFileName(SkinName);

            string skinFile = GetSkinFileFullPath(GetSkinFolder(ThemeName), skinFilename);

            if (File.Exists(ServerUtil.MapPath(skinFile)))
            {
                jc.ViewData["_skinfile_"] = skinFile;
                loaded = LoadSkin(skinFile);
            }

            if (!loaded)
            {
                string format = ThemeName;

                if (format.IndexOf('.') != -1)
                {
                    format = format.Split('.')[0];
                }

                string default_formatskinFile = GetSkinFileFullPath(GetSkinFolder(format), skinFilename);
                if (File.Exists(ServerUtil.MapPath(default_formatskinFile)))
                {
                    jc.ViewData["_skinfile_"] = default_formatskinFile;
                    loaded = LoadSkin(default_formatskinFile);
                }

                string default_skinFile = null;

                string defaultTheme = MobileDetect.Instance.IsMobile ? "default_mobile" : "default";

                if (!loaded && !string.Equals(format, defaultTheme, System.StringComparison.InvariantCultureIgnoreCase))
                {
                    default_skinFile = GetSkinFileFullPath(GetSkinFolder(defaultTheme), skinFilename);
                    if (File.Exists(ServerUtil.MapPath(default_skinFile)))
                    {
                        jc.ViewData["_skinfile_"] = default_skinFile;
                        loaded = LoadSkin(default_skinFile);
                    }
                }

                if (!loaded && ThrowExceptionOnSkinFileNotFound)
                {
                    throw new WebException("Skin file not found in {0} nor in {1}{2}",
                                           skinFile,
                                           default_formatskinFile,
                                           string.IsNullOrEmpty(default_skinFile) ? string.Empty : " nor in " + default_skinFile);
                }
            }

            if (loaded)
            {
                AttachChildControls();
            }
        }
Beispiel #17
0
        private async Task <WebClientByteResult> Run(WebRequest webRequest)
        {
            ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;

            var cookies = new CookieContainer();

            if (!string.IsNullOrEmpty(webRequest.Cookies))
            {
                var uri = new Uri(webRequest.Url);
                foreach (var c in webRequest.Cookies.Split(';'))
                {
                    try
                    {
                        cookies.SetCookies(uri, c);
                    }
                    catch (CookieException ex)
                    {
                        logger.Info("(Non-critical) Problem loading cookie {0}, {1}, {2}", uri, c, ex.Message);
                    }
                }
            }
            var      useProxy    = false;
            WebProxy proxyServer = null;

            if (Startup.ProxyConnection != null)
            {
                proxyServer = new WebProxy(Startup.ProxyConnection, false);
                useProxy    = true;
            }

            ClearanceHandler  clearanceHandlr = new ClearanceHandler();
            HttpClientHandler clientHandlr    = new HttpClientHandler
            {
                CookieContainer   = cookies,
                AllowAutoRedirect = false, // Do not use this - Bugs ahoy! Lost cookies and more.
                UseCookies        = true,
                Proxy             = proxyServer,
                UseProxy          = useProxy
            };

            clearanceHandlr.InnerHandler = clientHandlr;
            var client = new HttpClient(clearanceHandlr);

            if (webRequest.EmulateBrowser)
            {
                client.DefaultRequestHeaders.Add("User-Agent", BrowserUtil.ChromeUserAgent);
            }
            else
            {
                client.DefaultRequestHeaders.Add("User-Agent", "Jackett/" + configService.GetVersion());
            }

            HttpResponseMessage response = null;
            var request = new HttpRequestMessage();

            request.Headers.ExpectContinue = false;
            request.RequestUri             = new Uri(webRequest.Url);

            if (webRequest.Headers != null)
            {
                foreach (var header in webRequest.Headers)
                {
                    if (header.Key != "Content-Type")
                    {
                        request.Headers.Add(header.Key, header.Value);
                    }
                }
            }

            if (!string.IsNullOrEmpty(webRequest.RawBody))
            {
                var type = webRequest.Headers.Where(h => h.Key == "Content-Type").Cast <KeyValuePair <string, string>?>().FirstOrDefault();
                if (type.HasValue)
                {
                    var str = new StringContent(webRequest.RawBody);
                    str.Headers.Remove("Content-Type");
                    str.Headers.Add("Content-Type", type.Value.Value);
                    request.Content = str;
                }
                else
                {
                    request.Content = new StringContent(webRequest.RawBody);
                }
                request.Method = HttpMethod.Post;
            }
            else if (webRequest.Type == RequestType.POST)
            {
                request.Content = new FormUrlEncodedContent(webRequest.PostData);
                request.Method  = HttpMethod.Post;
            }
            else
            {
                request.Method = HttpMethod.Get;
            }

            response = await client.SendAsync(request);

            var result = new WebClientByteResult();

            result.Content = await response.Content.ReadAsByteArrayAsync();

            // some cloudflare clients are using a refresh header
            // Pull it out manually
            if (response.StatusCode == System.Net.HttpStatusCode.ServiceUnavailable && response.Headers.Contains("Refresh"))
            {
                var refreshHeaders = response.Headers.GetValues("Refresh");
                var redirval       = "";
                var redirtime      = 0;
                if (refreshHeaders != null)
                {
                    foreach (var value in refreshHeaders)
                    {
                        var start = value.IndexOf("=");
                        var end   = value.IndexOf(";");
                        var len   = value.Length;
                        if (start > -1)
                        {
                            redirval             = value.Substring(start + 1);
                            result.RedirectingTo = redirval;
                            // normally we don't want a serviceunavailable (503) to be a redirect, but that's the nature
                            // of this cloudflare approach..don't want to alter BaseWebResult.IsRedirect because normally
                            // it shoudln't include service unavailable..only if we have this redirect header.
                            response.StatusCode = System.Net.HttpStatusCode.Redirect;
                            redirtime           = Int32.Parse(value.Substring(0, end));
                            System.Threading.Thread.Sleep(redirtime * 1000);
                        }
                    }
                }
            }
            if (response.Headers.Location != null)
            {
                result.RedirectingTo = response.Headers.Location.ToString();
            }
            result.Status = response.StatusCode;

            // Compatiblity issue between the cookie format and httpclient
            // Pull it out manually ignoring the expiry date then set it manually
            // http://stackoverflow.com/questions/14681144/httpclient-not-storing-cookies-in-cookiecontainer
            IEnumerable <string> cookieHeaders;
            var responseCookies = new List <Tuple <string, string> >();

            if (response.Headers.TryGetValues("set-cookie", out cookieHeaders))
            {
                foreach (var value in cookieHeaders)
                {
                    var nameSplit = value.IndexOf('=');
                    if (nameSplit > -1)
                    {
                        responseCookies.Add(new Tuple <string, string>(value.Substring(0, nameSplit), value.Substring(0, value.IndexOf(';') == -1 ? value.Length : (value.IndexOf(';') + 1))));
                    }
                }

                var cookieBuilder = new StringBuilder();
                foreach (var cookieGroup in responseCookies.GroupBy(c => c.Item1))
                {
                    cookieBuilder.AppendFormat("{0} ", cookieGroup.Last().Item2);
                }
                result.Cookies = cookieBuilder.ToString().Trim();
            }

            ServerUtil.ResureRedirectIsFullyQualified(webRequest, result);
            return(result);
        }
        private async Task <WebClientByteResult> Run(WebRequest request)
        {
            Jackett.CurlHelper.CurlResponse response;
            if (request.Type == RequestType.GET)
            {
                response = await CurlHelper.GetAsync(request.Url, request.Cookies, request.Referer);
            }
            else
            {
                if (!string.IsNullOrEmpty(request.RawBody))
                {
                    logger.Debug("UnixLibCurlWebClient: Posting " + request.RawBody);
                }
                else if (request.PostData != null && request.PostData.Count() > 0)
                {
                    logger.Debug("UnixLibCurlWebClient: Posting " + StringUtil.PostDataFromDict(request.PostData));
                }

                response = await CurlHelper.PostAsync(request.Url, request.PostData, request.Cookies, request.Referer, request.RawBody);
            }

            var result = new WebClientByteResult()
            {
                Content = response.Content,
                Cookies = response.Cookies,
                Status  = response.Status
            };

            if (response.HeaderList != null)
            {
                foreach (var header in response.HeaderList)
                {
                    switch (header[0].ToLowerInvariant())
                    {
                    case "location":
                        result.RedirectingTo = header[1];
                        break;

                    case "refresh":
                        if (response.Status == System.Net.HttpStatusCode.ServiceUnavailable)
                        {
                            //"Refresh: 8;URL=/cdn-cgi/l/chk_jschl?pass=1451000679.092-1vJFUJLb9R"
                            var redirval = "";
                            var value    = header[1];
                            var start    = value.IndexOf("=");
                            var end      = value.IndexOf(";");
                            var len      = value.Length;
                            if (start > -1)
                            {
                                redirval             = value.Substring(start + 1);
                                result.RedirectingTo = redirval;
                                // normally we don't want a serviceunavailable (503) to be a redirect, but that's the nature
                                // of this cloudflare approach..don't want to alter BaseWebResult.IsRedirect because normally
                                // it shoudln't include service unavailable..only if we have this redirect header.
                                result.Status = System.Net.HttpStatusCode.Redirect;
                                var redirtime = Int32.Parse(value.Substring(0, end));
                                System.Threading.Thread.Sleep(redirtime * 1000);
                            }
                        }
                        break;
                    }
                }
            }

            ServerUtil.ResureRedirectIsFullyQualified(request, result);
            return(result);
        }
Beispiel #19
0
        private void DoTheThing()
        {
            try {
                //throw new Exception();
                //Get update info json.
                Console.WriteLine("Getting update info json...");

                //if (Environment.GetCommandLineArgs().Length != 0) {
                //    //Get json from arguments.
                //    updateInfoJson = Environment.GetCommandLineArgs()[0];
                //} else {
                Console.WriteLine("Update info json wasn't in arguments, which means the program was probably ran manually.");
                updateInfoJson = ServerUtil.GetUpdateInfoJson(); //Download update info.
                //}

                updateInfo = JsonConvert.DeserializeObject <UpdateInfo>(updateInfoJson); //Convert the json.

                Console.WriteLine($"Downloading file {updateInfo.downloadUrl}...");

                ServerUtil.DownloadFile(updateInfo.downloadUrl, downloadPath); //Download the package.

                //Kill all instances of Lenny Facer
                foreach (Process instance in Process.GetProcessesByName(lennyFacerExe))
                {
                    Console.WriteLine($"Killing instance of Lenny Facer with PID of {instance.Id}.");
                    instance.Kill();
                }

                string lennyFacerExeBackup = lennyFacerExe + ".backup";

                //Try to delete the current backup.
                try {
                    File.Delete(lennyFacerExeBackup);
                } catch (Exception) { }

                try {
                    File.Copy(lennyFacerExe, lennyFacerExeBackup); //Backup the current version in case anything happens.
                } catch (Exception) { }

                ZipFile package = ZipFile.Read(downloadPath); //Read package as zip file.
                foreach (ZipEntry entry in package.Entries)
                {
                    try {
                        entry.Extract(Directory.GetCurrentDirectory(), ExtractExistingFileAction.OverwriteSilently);
                    } catch (Exception) {
                        Console.WriteLine($"Failed to overwrite {entry.FileName}.");
                    }
                }
                //package.ExtractAll(Directory.GetCurrentDirectory(), ExtractExistingFileAction.OverwriteSilently); //Extract the package, overwriting everything.

                Console.WriteLine("Launching Lenny Facer...");
                Process.Start(lennyFacerExe, "-uf");

                Application.Exit();
            } catch (Exception ex) {
                Opacity = 0;

                UpdateFailedForm updateFailedForm = new UpdateFailedForm();
                updateFailedForm.ChangeExceptionText($"{ex.ToString()}");
                updateFailedForm.Show();
            }
        }
        override protected async Task <WebClientByteResult> Run(WebRequest webRequest)
        {
            ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;

            var cookies = new CookieContainer();

            if (!string.IsNullOrEmpty(webRequest.Cookies))
            {
                var uri       = new Uri(webRequest.Url);
                var cookieUrl = new Uri(uri.Scheme + "://" + uri.Host); // don't include the path, Scheme is needed for mono compatibility
                foreach (var c in webRequest.Cookies.Split(';'))
                {
                    try
                    {
                        cookies.SetCookies(cookieUrl, c.Trim());
                    }
                    catch (CookieException ex)
                    {
                        logger.Info("(Non-critical) Problem loading cookie {0}, {1}, {2}", uri, c, ex.Message);
                    }
                }
            }

            using (ClearanceHandler clearanceHandlr = new ClearanceHandler())
            {
                clearanceHandlr.MaxRetries = 30;
                using (HttpClientHandler clientHandlr = new HttpClientHandler
                {
                    CookieContainer = cookies,
                    AllowAutoRedirect = false, // Do not use this - Bugs ahoy! Lost cookies and more.
                    UseCookies = true,
                    Proxy = webProxy,
                    UseProxy = (webProxy != null),
                    AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
                })
                {
                    clearanceHandlr.InnerHandler = clientHandlr;
                    using (var client = new HttpClient(clearanceHandlr))
                    {
                        if (webRequest.EmulateBrowser == true)
                        {
                            client.DefaultRequestHeaders.Add("User-Agent", BrowserUtil.ChromeUserAgent);
                        }
                        else
                        {
                            client.DefaultRequestHeaders.Add("User-Agent", "Jackett/" + configService.GetVersion());
                        }

                        HttpResponseMessage response = null;
                        using (var request = new HttpRequestMessage())
                        {
                            request.Headers.ExpectContinue = false;
                            request.RequestUri             = new Uri(webRequest.Url);

                            if (webRequest.Headers != null)
                            {
                                foreach (var header in webRequest.Headers)
                                {
                                    if (header.Key != "Content-Type")
                                    {
                                        request.Headers.TryAddWithoutValidation(header.Key, header.Value);
                                    }
                                }
                            }

                            if (!string.IsNullOrEmpty(webRequest.Referer))
                            {
                                request.Headers.Referrer = new Uri(webRequest.Referer);
                            }

                            if (!string.IsNullOrEmpty(webRequest.RawBody))
                            {
                                var type = webRequest.Headers.Where(h => h.Key == "Content-Type").Cast <KeyValuePair <string, string>?>().FirstOrDefault();
                                if (type.HasValue)
                                {
                                    var str = new StringContent(webRequest.RawBody);
                                    str.Headers.Remove("Content-Type");
                                    str.Headers.Add("Content-Type", type.Value.Value);
                                    request.Content = str;
                                }
                                else
                                {
                                    request.Content = new StringContent(webRequest.RawBody);
                                }
                                request.Method = HttpMethod.Post;
                            }
                            else if (webRequest.Type == RequestType.POST)
                            {
                                if (webRequest.PostData != null)
                                {
                                    request.Content = new FormUrlEncodedContent(webRequest.PostData);
                                }
                                request.Method = HttpMethod.Post;
                            }
                            else
                            {
                                request.Method = HttpMethod.Get;
                            }

                            using (response = await client.SendAsync(request))
                            {
                                var result = new WebClientByteResult
                                {
                                    Content = await response.Content.ReadAsByteArrayAsync()
                                };

                                foreach (var header in response.Headers)
                                {
                                    IEnumerable <string> value = header.Value;
                                    result.Headers[header.Key.ToLowerInvariant()] = value.ToArray();
                                }

                                // some cloudflare clients are using a refresh header
                                // Pull it out manually
                                if (response.StatusCode == HttpStatusCode.ServiceUnavailable && response.Headers.Contains("Refresh"))
                                {
                                    var refreshHeaders = response.Headers.GetValues("Refresh");
                                    var redirval       = "";
                                    var redirtime      = 0;
                                    if (refreshHeaders != null)
                                    {
                                        foreach (var value in refreshHeaders)
                                        {
                                            var start = value.IndexOf("=");
                                            var end   = value.IndexOf(";");
                                            var len   = value.Length;
                                            if (start > -1)
                                            {
                                                redirval             = value.Substring(start + 1);
                                                result.RedirectingTo = redirval;
                                                // normally we don't want a serviceunavailable (503) to be a redirect, but that's the nature
                                                // of this cloudflare approach..don't want to alter BaseWebResult.IsRedirect because normally
                                                // it shoudln't include service unavailable..only if we have this redirect header.
                                                response.StatusCode = System.Net.HttpStatusCode.Redirect;
                                                redirtime           = Int32.Parse(value.Substring(0, end));
                                                System.Threading.Thread.Sleep(redirtime * 1000);
                                            }
                                        }
                                    }
                                }
                                if (response.Headers.Location != null)
                                {
                                    result.RedirectingTo = response.Headers.Location.ToString();
                                }
                                // Mono won't add the baseurl to relative redirects.
                                // e.g. a "Location: /index.php" header will result in the Uri "file:///index.php"
                                // See issue #1200
                                if (result.RedirectingTo != null && result.RedirectingTo.StartsWith("file://"))
                                {
                                    // URL decoding apparently is needed to, without it e.g. Demonoid download is broken
                                    // TODO: is it always needed (not just for relative redirects)?
                                    var newRedirectingTo = WebUtilityHelpers.UrlDecode(result.RedirectingTo, webRequest.Encoding);
                                    if (newRedirectingTo.StartsWith("file:////")) // Location without protocol but with host (only add scheme)
                                    {
                                        newRedirectingTo = newRedirectingTo.Replace("file://", request.RequestUri.Scheme + ":");
                                    }
                                    else
                                    {
                                        newRedirectingTo = newRedirectingTo.Replace("file://", request.RequestUri.Scheme + "://" + request.RequestUri.Host);
                                    }
                                    logger.Debug("[MONO relative redirect bug] Rewriting relative redirect URL from " + result.RedirectingTo + " to " + newRedirectingTo);
                                    result.RedirectingTo = newRedirectingTo;
                                }
                                result.Status = response.StatusCode;

                                // Compatiblity issue between the cookie format and httpclient
                                // Pull it out manually ignoring the expiry date then set it manually
                                // http://stackoverflow.com/questions/14681144/httpclient-not-storing-cookies-in-cookiecontainer
                                IEnumerable <string> cookieHeaders;
                                var responseCookies = new List <Tuple <string, string> >();

                                if (response.Headers.TryGetValues("set-cookie", out cookieHeaders))
                                {
                                    foreach (var value in cookieHeaders)
                                    {
                                        var nameSplit = value.IndexOf('=');
                                        if (nameSplit > -1)
                                        {
                                            responseCookies.Add(new Tuple <string, string>(value.Substring(0, nameSplit), value.Substring(0, value.IndexOf(';') == -1 ? value.Length : (value.IndexOf(';'))) + ";"));
                                        }
                                    }

                                    var cookieBuilder = new StringBuilder();
                                    foreach (var cookieGroup in responseCookies.GroupBy(c => c.Item1))
                                    {
                                        cookieBuilder.AppendFormat("{0} ", cookieGroup.Last().Item2);
                                    }
                                    result.Cookies = cookieBuilder.ToString().Trim();
                                }
                                ServerUtil.ResureRedirectIsFullyQualified(webRequest, result);
                                return(result);
                            }
                        }
                    }
                }
            }
        }
Beispiel #21
0
        public async Task <IHttpActionResult> SetConfig()
        {
            var originalPort          = Engine.Server.Config.Port;
            var originalAllowExternal = Engine.Server.Config.AllowExternal;
            var jsonReply             = new JObject();

            try
            {
                var postData = await ReadPostDataJson();

                int    port     = (int)postData["port"];
                bool   external = (bool)postData["external"];
                string saveDir  = (string)postData["blackholedir"];

                if (port != Engine.Server.Config.Port || external != Engine.Server.Config.AllowExternal)
                {
                    if (ServerUtil.RestrictedPorts.Contains(port))
                    {
                        jsonReply["result"] = "error";
                        jsonReply["error"]  = "The port you have selected is restricted, try a different one.";
                        return(Json(jsonReply));
                    }

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

                    // On Windows change the url reservations
                    if (System.Environment.OSVersion.Platform != PlatformID.Unix)
                    {
                        if (!ServerUtil.IsUserAdministrator())
                        {
                            try
                            {
                                processService.StartProcessAndLog(Application.ExecutablePath, "--ReserveUrls", true);
                            }
                            catch
                            {
                                Engine.Server.Config.Port          = originalPort;
                                Engine.Server.Config.AllowExternal = originalAllowExternal;
                                Engine.Server.SaveConfig();
                                jsonReply["result"] = "error";
                                jsonReply["error"]  = "Failed to acquire admin permissions to reserve the new port.";
                                return(Json(jsonReply));
                            }
                        }
                        else
                        {
                            serverService.ReserveUrls(true);
                        }
                    }

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


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

                    Engine.Server.Config.BlackholeDir = saveDir;
                    Engine.Server.SaveConfig();
                }

                jsonReply["result"]   = "success";
                jsonReply["port"]     = port;
                jsonReply["external"] = external;
            }
            catch (Exception ex)
            {
                logger.Error(ex, "Exception in set_port");
                jsonReply["result"] = "error";
                jsonReply["error"]  = ex.Message;
            }
            return(Json(jsonReply));
        }
Beispiel #22
0
        private async Task <WebClientByteResult> Run(WebRequest request)
        {
            var args = new StringBuilder();

            args.AppendFormat("--url \"{0}\" ", request.Url);

            if (request.EmulateBrowser)
            {
                args.AppendFormat("-i  -sS --user-agent \"{0}\" ", BrowserUtil.ChromeUserAgent);
            }
            else
            {
                args.AppendFormat("-i  -sS --user-agent \"{0}\" ", "Jackett/" + configService.GetVersion());
            }

            if (!string.IsNullOrWhiteSpace(request.Cookies))
            {
                args.AppendFormat("--cookie \"{0}\" ", request.Cookies);
            }

            if (!string.IsNullOrWhiteSpace(request.Referer))
            {
                args.AppendFormat("--referer \"{0}\" ", request.Referer);
            }

            if (!string.IsNullOrEmpty(request.RawBody))
            {
                var postString = StringUtil.PostDataFromDict(request.PostData);
                args.AppendFormat("--data \"{0}\" ", request.RawBody.Replace("\"", "\\\""));
            }
            else if (request.PostData != null && request.PostData.Count() > 0)
            {
                var postString = StringUtil.PostDataFromDict(request.PostData);
                args.AppendFormat("--data \"{0}\" ", postString);
            }

            var tempFile = Path.GetTempFileName();

            args.AppendFormat("--output \"{0}\" ", tempFile);

            if (Startup.DoSSLFix == true)
            {
                // http://stackoverflow.com/questions/31107851/how-to-fix-curl-35-cannot-communicate-securely-with-peer-no-common-encryptio
                // https://git.fedorahosted.org/cgit/mod_nss.git/plain/docs/mod_nss.html
                args.Append("--cipher " + SSLFix.CipherList);
            }

            string stdout = null;
            await Task.Run(() =>
            {
                stdout = processService.StartProcessAndGetOutput(System.Environment.OSVersion.Platform == PlatformID.Unix ? "curl" : "curl.exe", args.ToString(), true);
            });

            var outputData = File.ReadAllBytes(tempFile);

            File.Delete(tempFile);
            stdout = Encoding.UTF8.GetString(outputData);
            var result    = new WebClientByteResult();
            var headSplit = stdout.IndexOf("\r\n\r\n");

            if (headSplit < 0)
            {
                throw new Exception("Invalid response");
            }
            var headers       = stdout.Substring(0, headSplit);
            var headerCount   = 0;
            var cookieBuilder = new StringBuilder();
            var cookies       = new List <Tuple <string, string> >();

            foreach (var header in headers.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries))
            {
                if (headerCount == 0)
                {
                    var responseCode = int.Parse(header.Split(' ')[1]);
                    result.Status = (HttpStatusCode)responseCode;
                }
                else
                {
                    var headerSplitIndex = header.IndexOf(':');
                    if (headerSplitIndex > 0)
                    {
                        var name  = header.Substring(0, headerSplitIndex).ToLowerInvariant();
                        var value = header.Substring(headerSplitIndex + 1);
                        switch (name)
                        {
                        case "set-cookie":
                            var nameSplit = value.IndexOf('=');
                            if (nameSplit > -1)
                            {
                                cookies.Add(new Tuple <string, string>(value.Substring(0, nameSplit), value.Substring(0, value.IndexOf(';') + 1)));
                            }
                            break;

                        case "location":
                            result.RedirectingTo = value.Trim();
                            break;
                        }
                    }
                }
                headerCount++;
            }

            foreach (var cookieGroup in cookies.GroupBy(c => c.Item1))
            {
                cookieBuilder.AppendFormat("{0} ", cookieGroup.Last().Item2);
            }

            result.Cookies = cookieBuilder.ToString().Trim();
            result.Content = new byte[outputData.Length - (headSplit + 3)];
            var dest = 0;

            for (int i = headSplit + 4; i < outputData.Length; i++)
            {
                result.Content[dest] = outputData[i];
                dest++;
            }

            logger.Debug("WebClientByteResult returned " + result.Status);
            ServerUtil.ResureRedirectIsFullyQualified(request, result);
            return(result);
        }
Beispiel #23
0
    /// <summary>
    /// 检测资源
    /// </summary>
    private IEnumerator DownLoadRes(System.Action callback)
    {
        // 公司的服务器地址
        string url = ServerUtil.GetAssetBundleURL() + PathUtil.GetPlatformName();

        string fileUrl = url + "/" + "file.txt";

        WWW www = new WWW(fileUrl);

        yield return(www);

        if (www.error != null)
        {
            Debug.LogError("Error" + www.error);
        }


        // 判断本地有没有这个目录
        // 如果发布到安卓端 : 游戏一运行,就把 streamingAssetsPath 的文件 拷贝到 persistentDataPath 路径下;


        if (!Directory.Exists(downloadPath))
        {
            Directory.CreateDirectory(downloadPath);
        }
        // 把下载的文件写入本地
        File.WriteAllBytes(downloadPath + "/file.txt", www.bytes);

        // 读取里面的内容
        string fileText = www.text;

        string[] lines = fileText.Split(new string[] { "\r\n" }, StringSplitOptions.None); // 2020.03.17 注意这里是 \r\n , 如果只\n的话,md5值不相同

        for (int i = 0; i < lines.Length; i++)
        {
            if (string.IsNullOrEmpty(lines[i])) //有空行,就continue
            {
                continue;
            }

            string[] kv = lines[i].Split('|');
            //kv =  scene1/character.assetbundle | 2503fdd66fea3185fa83930bc972bad2
            string fileName = kv[0];

            // 再拿到本地的这个文件
            string localFile = (downloadPath + "/" + fileName).Trim();

            // 如果没有本地文件 , 就下载
            if (!File.Exists(localFile))
            {
                string dir = Path.GetDirectoryName(localFile);
                Directory.CreateDirectory(dir);

                // 开始网络下载
                string tempUrl = url + "/" + fileName;
                Debug.LogWarning(tempUrl);

                WWW tmpwww = new WWW(tempUrl);
                yield return(tmpwww);

                if (tmpwww.error != null)
                {
                    Debug.LogError("加载 " + fileName + "出错 , Error : " + tmpwww.error);
                }
                else
                {
                    File.WriteAllBytes(localFile, tmpwww.bytes);
                }
            }
            else //如果文件有的话 , 就开始比对MD5 ,检测是否更新了
            {
                string md5      = kv[1];
                string localMD5 = GetFileMD5(localFile);

                // 开始比对
                if (md5 == localMD5)
                {
                    // 相等的话,没更新
                    Debug.Log("没更新");
                }
                else
                {
                    // 不相等,说明更新了
                    // 删除本地原来的旧文件
                    File.Delete(localFile);

                    //下载新文件
                    string tmpUrl = url + "/" + fileName;
                    WWW    Twww   = new WWW(tmpUrl);
                    yield return(Twww);

                    //进行一些网络的检测
                    if (Twww.error != null)
                    {
                        Debug.LogError("加载 " + fileName + "出错 , Error : " + Twww.error);
                    }
                    else
                    {
                        File.WriteAllBytes(localFile, Twww.bytes);
                    }
                }
            }
        }

        yield return(new WaitForEndOfFrame());

        Debug.Log("更新完成,可以开始游戏了");
        callback();
    }
Beispiel #24
0
        /// <summary>
        /// Add a Item to a Sale
        /// </summary>
        /// <returns></returns>
        public Response AddItem(Objects.SaleItem item, Objects.Sale sale)
        {
            int      statusCode = 201;
            Response response   = new Response();

            item.Id = ServerUtil.GenerateToken(TokenLengths.TokensLength);
            try
            {
                Database.Connection.Open();

                string query = " INSERT INTO SaleItems (SaleItemId, SaleId, ProductId, DiscountId, Quantity, SupplyPrice, Price, DiscountPrice, TaxAmount, " +
                               " TotalPrice, Note, Status, IsDiscounted, IsBalanceRequired )" +
                               " VALUES (@SaleItemId,@SaleId, @ProductId, @DiscountId, @Quantity, @SupplyPrice, @Price, @DiscountPrice, @TaxAmount, " +
                               " @TotalPrice, @Note, @Status, @IsDiscounted, @IsBalanceRequired ) ";

                MySqlCommand Command = new MySqlCommand(query, Database.Connection);
                Command.Parameters.AddWithValue("SaleItemId", item.Id);
                Command.Parameters.AddWithValue("SaleId", sale.Id);
                Command.Parameters.AddWithValue("ProductId", item.Product.Id);
                Command.Parameters.AddWithValue("DiscountId", item.Discount.Id);
                Command.Parameters.AddWithValue("Quantity", item.Quantity);

                Command.Parameters.AddWithValue("SupplyPrice", item.SupplyPrice);
                Command.Parameters.AddWithValue("Price", item.Price);
                Command.Parameters.AddWithValue("DiscountPrice", item.DiscountPrice);
                Command.Parameters.AddWithValue("TaxAmount", item.TaxAmount);
                Command.Parameters.AddWithValue("TotalPrice", item.TotalPrice);

                Command.Parameters.AddWithValue("Note", item.Note);
                Command.Parameters.AddWithValue("Status", item.Status);

                Command.Parameters.AddWithValue("IsDiscounted", Func.ToString(item.IsDiscounted));
                Command.Parameters.AddWithValue("IsBalanceRequired", Func.ToString(item.IsBalanceRequired));

                Command.ExecuteNonQuery();

                Database.Connection.Close();

                // Created
                statusCode = 201;
            }
            catch (MySqlException e)
            {
                if (e.Message.Contains("Duplicate entry"))
                {
                    //Duplicate Key or Conflict
                    statusCode = 409;
                }
                else
                {
                    // Internal Server Error
                    statusCode = 500;
                }
                Logger.QueryError(e, "Sale", "AddProduct");
            }
            //Close Connection if Open
            if (Database.Connection.State == ConnectionState.Open)
            {
                Database.Connection.Close();
            }

            //Response

            response.StatusCode = statusCode;
            response.Data       = item;

            return(response);
        }
Beispiel #25
0
        override protected async Task <WebClientByteResult> Run(WebRequest webRequest)
        {
            HttpResponseMessage response = null;
            var request = new HttpRequestMessage();

            request.Headers.ExpectContinue = false;
            request.RequestUri             = new Uri(webRequest.Url);

            if (webRequest.EmulateBrowser == true)
            {
                request.Headers.UserAgent.ParseAdd(BrowserUtil.ChromeUserAgent);
            }
            else
            {
                request.Headers.UserAgent.ParseAdd("Jackett/" + configService.GetVersion());
            }

            // clear cookies from cookiecontainer
            var oldCookies = cookies.GetCookies(request.RequestUri);

            foreach (Cookie oldCookie in oldCookies)
            {
                oldCookie.Expired = true;
            }

            if (!string.IsNullOrEmpty(webRequest.Cookies))
            {
                // add cookies to cookiecontainer
                var cookieUrl = new Uri(request.RequestUri.Scheme + "://" + request.RequestUri.Host); // don't include the path, Scheme is needed for mono compatibility
                foreach (var ccookiestr in webRequest.Cookies.Split(';'))
                {
                    var cookiestrparts = ccookiestr.Split('=');
                    var name           = cookiestrparts[0].Trim();
                    if (string.IsNullOrWhiteSpace(name))
                    {
                        continue;
                    }
                    var value = "";
                    if (cookiestrparts.Length >= 2)
                    {
                        value = cookiestrparts[1].Trim();
                    }
                    var cookie = new Cookie(name, value);
                    cookies.Add(cookieUrl, cookie);
                }
            }

            if (webRequest.Headers != null)
            {
                foreach (var header in webRequest.Headers)
                {
                    if (header.Key != "Content-Type")
                    {
                        request.Headers.TryAddWithoutValidation(header.Key, header.Value);
                    }
                }
            }

            if (!string.IsNullOrEmpty(webRequest.Referer))
            {
                request.Headers.Referrer = new Uri(webRequest.Referer);
            }

            if (!string.IsNullOrEmpty(webRequest.RawBody))
            {
                var type = webRequest.Headers.Where(h => h.Key == "Content-Type").Cast <KeyValuePair <string, string>?>().FirstOrDefault();
                if (type.HasValue)
                {
                    var str = new StringContent(webRequest.RawBody);
                    str.Headers.Remove("Content-Type");
                    str.Headers.Add("Content-Type", type.Value.Value);
                    request.Content = str;
                }
                else
                {
                    request.Content = new StringContent(webRequest.RawBody);
                }
                request.Method = HttpMethod.Post;
            }
            else if (webRequest.Type == RequestType.POST)
            {
                if (webRequest.PostData != null)
                {
                    request.Content = new FormUrlEncodedContent(webRequest.PostData);
                }
                request.Method = HttpMethod.Post;
            }
            else
            {
                request.Method = HttpMethod.Get;
            }

            response = await client.SendAsync(request);

            var result = new WebClientByteResult();

            result.Content = await response.Content.ReadAsByteArrayAsync();

            foreach (var header in response.Headers)
            {
                IEnumerable <string> value = header.Value;
                result.Headers[header.Key.ToLowerInvariant()] = value.ToArray();
            }

            // some cloudflare clients are using a refresh header
            // Pull it out manually
            if (response.StatusCode == System.Net.HttpStatusCode.ServiceUnavailable && response.Headers.Contains("Refresh"))
            {
                var refreshHeaders = response.Headers.GetValues("Refresh");
                var redirval       = "";
                var redirtime      = 0;
                if (refreshHeaders != null)
                {
                    foreach (var value in refreshHeaders)
                    {
                        var start = value.IndexOf("=");
                        var end   = value.IndexOf(";");
                        var len   = value.Length;
                        if (start > -1)
                        {
                            redirval             = value.Substring(start + 1);
                            result.RedirectingTo = redirval;
                            // normally we don't want a serviceunavailable (503) to be a redirect, but that's the nature
                            // of this cloudflare approach..don't want to alter BaseWebResult.IsRedirect because normally
                            // it shoudln't include service unavailable..only if we have this redirect header.
                            response.StatusCode = System.Net.HttpStatusCode.Redirect;
                            redirtime           = Int32.Parse(value.Substring(0, end));
                            System.Threading.Thread.Sleep(redirtime * 1000);
                        }
                    }
                }
            }
            if (response.Headers.Location != null)
            {
                result.RedirectingTo = response.Headers.Location.ToString();
            }
            // Mono won't add the baseurl to relative redirects.
            // e.g. a "Location: /index.php" header will result in the Uri "file:///index.php"
            // See issue #1200
            if (result.RedirectingTo != null && result.RedirectingTo.StartsWith("file://"))
            {
                var newRedirectingTo = result.RedirectingTo.Replace("file://", request.RequestUri.Scheme + "://" + request.RequestUri.Host);
                logger.Debug("[MONO relative redirect bug] Rewriting relative redirect URL from " + result.RedirectingTo + " to " + newRedirectingTo);
                result.RedirectingTo = newRedirectingTo;
            }
            result.Status = response.StatusCode;

            // Compatiblity issue between the cookie format and httpclient
            // Pull it out manually ignoring the expiry date then set it manually
            // http://stackoverflow.com/questions/14681144/httpclient-not-storing-cookies-in-cookiecontainer
            IEnumerable <string> cookieHeaders;
            var responseCookies = new List <Tuple <string, string> >();

            if (response.Headers.TryGetValues("set-cookie", out cookieHeaders))
            {
                foreach (var value in cookieHeaders)
                {
                    logger.Debug(value);
                    var nameSplit = value.IndexOf('=');
                    if (nameSplit > -1)
                    {
                        responseCookies.Add(new Tuple <string, string>(value.Substring(0, nameSplit), value.Substring(0, value.IndexOf(';') == -1 ? value.Length : (value.IndexOf(';'))) + ";"));
                    }
                }

                var cookieBuilder = new StringBuilder();
                foreach (var cookieGroup in responseCookies.GroupBy(c => c.Item1))
                {
                    cookieBuilder.AppendFormat("{0} ", cookieGroup.Last().Item2);
                }
                result.Cookies = cookieBuilder.ToString().Trim();
            }
            ServerUtil.ResureRedirectIsFullyQualified(webRequest, result);
            return(result);
        }
Beispiel #26
0
        /// <summary>
        /// Create a new Customer
        /// </summary>
        /// <returns></returns>
        public Response Create(Objects.Customer customer)
        {
            //Props
            int      statusCode = 201;
            Response response   = new Response();

            //Random Tokens
            customer.Id = ServerUtil.GenerateToken(TokenLengths.TokensLength);
            try
            {
                //Open MySqlConnection
                Database.Connection.Open();

                //Query
                string query = " INSERT INTO Customers (CustomerId, Code, FirstName, LastName, Email, PhoneNumber, Website, Address, " +
                               " PostCode, City, Country, IsFavorite, IsVerified, DateOfBirth, Sex) " +
                               " VALUES (@CustomerId, @Code, @FirstName, @LastName, @Email, @PhoneNumber, @Website, @Address, " +
                               " @PostCode, @City, @Country, @IsFavorite, @IsVerified, @DateOfBirth, @Sex) ";

                //Execute Query With MySqlConnection
                MySqlCommand Command = new MySqlCommand(query, Database.Connection);

                Command.Parameters.AddWithValue("CustomerId", customer.Id);
                Command.Parameters.AddWithValue("Code", customer.Code);
                Command.Parameters.AddWithValue("FirstName", customer.FirstName);
                Command.Parameters.AddWithValue("LastName", customer.LastName);
                Command.Parameters.AddWithValue("Email", customer.Email);
                Command.Parameters.AddWithValue("Sex", customer.Sex);
                Command.Parameters.AddWithValue("PhoneNumber", customer.PhoneNumber);
                Command.Parameters.AddWithValue("Website", customer.Website);
                Command.Parameters.AddWithValue("Address", customer.Address);
                Command.Parameters.AddWithValue("PostCode", customer.PostCode);
                Command.Parameters.AddWithValue("City", customer.City);
                Command.Parameters.AddWithValue("Country", customer.Country);
                Command.Parameters.AddWithValue("IsFavorite", Func.ToString(customer.IsFavorite));
                Command.Parameters.AddWithValue("IsVerified", Func.ToString(customer.IsVerified));
                Command.Parameters.AddWithValue("DateOfBirth", customer.DateOfBirth);

                Command.ExecuteNonQuery();

                //Close Connection
                Database.Connection.Close();

                // Status Code
                statusCode = 201;
            }
            catch (MySqlException e)
            {
                if (e.Message.Contains("Duplicate entry"))
                {
                    //Duplicate Key or Conflict
                    statusCode = 409;
                }
                else
                {
                    // Internal Server Error
                    statusCode = 500;
                }
                Logger.QueryError(e, "Customer", "Create");
            }
            //Close Connection if Open
            if (Database.Connection.State == ConnectionState.Open)
            {
                Database.Connection.Close();
            }

            //Response

            response.StatusCode = statusCode;
            response.Data       = customer;

            return(response);
        }
Beispiel #27
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));
        }
Beispiel #28
0
        private DTMConfigurations GetConfiguration(Document doc)
        {
            DTMConfigurations config = new DTMConfigurations();

            try
            {
                string projectFileId = DataStorageUtil.GetProjectFileId(doc).ToString();
                string centralPath   = FileInfoUtil.GetCentralFilePath(doc);
                if (projectFileId == Guid.Empty.ToString())
                {
                    //first time use
                    List <ProjectFile> items = ServerUtil.GetProjectFiles("centralpath/" + centralPath);
                    if (items.Count > 0)
                    {
                        //import file info by central path
                        ProjectFile projectFile = items.First();
                        bool        found       = ServerUtil.GetConfiguration(projectFile._id, out config);
                        projectFileId = projectFile._id;
                    }
                    else
                    {
                        //create file info
                        projectFileId = Guid.NewGuid().ToString();

                        Project        projectInfo  = FileInfoUtil.GetProjectInfo(centralPath);
                        List <Project> projects     = ServerUtil.GetProjects("");
                        var            projectFound = from p in projects where p.ProjectNumber == projectInfo.ProjectNumber && p.ProjectName == projectInfo.ProjectName select p;
                        if (projectFound.Count() > 0)
                        {
                            projectInfo = projectFound.First();
                        }
                        else
                        {
                            projectInfo._id = Guid.NewGuid().ToString();
                        }

                        ProjectFile pFile = new ProjectFile(projectFileId, centralPath, projectInfo._id, projectInfo);
                        config.ProjectFileInfo = pFile;

                        ProjectUpdater pUpdater = new ProjectUpdater(Guid.NewGuid().ToString(), DTMUpdater.updaterGuid.ToString(), dtmUpdater.GetUpdaterName(), addInGuid.ToString(), addInName, false, pFile._id);
                        foreach (string categoryName in updaterCategories)
                        {
                            CategoryTrigger catTrigger = new CategoryTrigger(Guid.NewGuid().ToString(), categoryName, pUpdater._id, false, Environment.UserName, DateTime.Now);
                            pUpdater.CategoryTriggers.Add(catTrigger);
                        }
                        config.ProjectUpdaters.Add(pUpdater);

                        string         content = "";
                        string         errMsg  = "";
                        HttpStatusCode status  = ServerUtil.PostConfiguration(out content, out errMsg, config);
                    }

                    bool stored = DataStorageUtil.StoreProjectFileId(doc, new Guid(projectFileId));
                }
                else
                {
                    bool found = ServerUtil.GetConfiguration(projectFileId, out config);
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message;
                MessageBox.Show("Failed to get configuration.\n" + ex.Message, "Get Configuration from Database", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            return(config);
        }
Beispiel #29
0
        private void ProcessUpdate(UpdaterConsoleOptions options)
        {
            var updateLocation = GetUpdateLocation();

            if (!(updateLocation.EndsWith("\\") || updateLocation.EndsWith("/")))
            {
                updateLocation += Path.DirectorySeparatorChar;
            }

            var pids = new int[] { };

            if (options.KillPids != null)
            {
                var pidsStr = options.KillPids.Split(',').Where(pid => !string.IsNullOrWhiteSpace(pid)).ToArray();
                pids = Array.ConvertAll(pidsStr, pid => int.Parse(pid));
            }

            var isWindows     = Environment.OSVersion.Platform == PlatformID.Win32NT;
            var trayRunning   = false;
            var trayProcesses = Process.GetProcessesByName("JackettTray");

            if (isWindows)
            {
                if (trayProcesses.Count() > 0)
                {
                    foreach (var proc in trayProcesses)
                    {
                        try
                        {
                            logger.Info("Killing tray process " + proc.Id);
                            proc.Kill();
                            trayRunning = true;
                        }
                        catch { }
                    }
                }

                // on unix we don't have to wait (we can overwrite files which are in use)
                // On unix we kill the PIDs after the update so e.g. systemd can automatically restart the process
                KillPids(pids);
            }
            logger.Info("Finding files in: " + updateLocation);
            var files = Directory.GetFiles(updateLocation, "*.*", SearchOption.AllDirectories);

            foreach (var file in files)
            {
                var fileName = Path.GetFileName(file).ToLowerInvariant();

                if (fileName.EndsWith(".zip") ||
                    fileName.EndsWith(".tar") ||
                    fileName.EndsWith(".gz"))
                {
                    continue;
                }
                try
                {
                    logger.Info("Copying " + fileName);
                    var dest    = Path.Combine(options.Path, file.Substring(updateLocation.Length));
                    var destDir = Path.GetDirectoryName(dest);
                    if (!Directory.Exists(destDir))
                    {
                        logger.Info("Creating directory " + destDir);
                        Directory.CreateDirectory(destDir);
                    }
                    File.Copy(file, dest, true);
                }
                catch (Exception e)
                {
                    logger.Error(e);
                }
            }

            // delete old dirs
            string[] oldDirs = new string[] { "Content/logos" };

            foreach (var oldDir in oldDirs)
            {
                try
                {
                    var deleteDir = Path.Combine(options.Path, oldDir);
                    if (Directory.Exists(deleteDir))
                    {
                        logger.Info("Deleting directory " + deleteDir);
                        Directory.Delete(deleteDir, true);
                    }
                }
                catch (Exception e)
                {
                    logger.Error(e);
                }
            }

            // delete old files
            string[] oldFiles = new string[] {
                "Content/css/jquery.dataTables.css",
                "Content/css/jquery.dataTables_themeroller.css",
                "Definitions/tspate.yml",
                "Definitions/freakstrackingsystem.yml",
                "Definitions/rarbg.yml",
                "Definitions/t411.yml",
                "Definitions/hdbc.yml", // renamed to hdbitscom
                "Definitions/maniatorrent.yml",
                "Definitions/nyaa.yml",
                "Definitions/nachtwerk.yml",
                "Definitions/leparadisdunet.yml",
                "Definitions/qctorrent.yml",
                "Definitions/dragonworld.yml",
                "Definitions/hdclub.yml",
                "Definitions/polishtracker.yml",
                "Definitions/zetorrents.yml",
                "Definitions/rapidetracker.yml",
                "Definitions/isohunt.yml",
                "Definitions/t411v2.yml",
                "Definitions/bithq.yml",
                "Definitions/blubits.yml",
                "Definitions/torrentproject.yml",
                "Definitions/torrentvault.yml",
                "Definitions/apollo.yml",       // migrated to C# gazelle base tracker
                "Definitions/secretcinema.yml", // migrated to C# gazelle base tracker
                "Definitions/utorrents.yml",    // same as SzeneFZ now
                "Definitions/ultrahdclub.yml",
                "Definitions/infinityt.yml",
                "Definitions/hachede-c.yml",
                "Definitions/hd4Free.yml",
                "Definitions/skytorrents.yml",
                "Definitions/gormogon.yml",
                "Definitions/czteam.yml",
                "Definitions/rockhardlossless.yml",
                "Definitions/oxtorrent.yml",
                "Definitions/tehconnection.yml",
                "Definitions/torrentwtf.yml",
                "Definitions/eotforum.yml",
                "Definitions/nexttorrent.yml",
                "appsettings.Development.json",
                "CurlSharp.dll",
                "CurlSharp.pdb",
                "Jackett.dll",
                "Jackett.dll.config",
                "Jackett.pdb",
                "Autofac.Integration.WebApi.dll",
                "Microsoft.Owin.dll",
                "Microsoft.Owin.FileSystems.dll",
                "Microsoft.Owin.Host.HttpListener.dll",
                "Microsoft.Owin.Hosting.dll",
                "Microsoft.Owin.StaticFiles.dll",
                "Owin.dll",
                "System.Web.Http.dll",
                "System.Web.Http.Owin.dll",
                "System.Web.Http.Tracing.dll",
            };

            foreach (var oldFile in oldFiles)
            {
                try
                {
                    var deleteFile = Path.Combine(options.Path, oldFile);
                    if (File.Exists(deleteFile))
                    {
                        logger.Info("Deleting file " + deleteFile);
                        File.Delete(deleteFile);
                    }
                }
                catch (Exception e)
                {
                    logger.Error(e);
                }
            }

            // kill pids after the update on UNIX
            if (!isWindows)
            {
                KillPids(pids);
            }

            if (options.NoRestart == false)
            {
                if (isWindows && (trayRunning || options.StartTray) && !string.Equals(options.Type, "WindowsService", StringComparison.OrdinalIgnoreCase))
                {
                    var startInfo = new ProcessStartInfo()
                    {
                        Arguments       = $"--UpdatedVersion \" {EnvironmentUtil.JackettVersion}\"",
                        FileName        = Path.Combine(options.Path, "JackettTray.exe"),
                        UseShellExecute = true
                    };

                    logger.Info("Starting Tray: " + startInfo.FileName + " " + startInfo.Arguments);
                    Process.Start(startInfo);

                    if (!windowsService.ServiceExists())
                    {
                        //User was running the tray icon, but not using the Windows service, starting Tray icon will start JackettConsole as well
                        return;
                    }
                }

                if (string.Equals(options.Type, "WindowsService", StringComparison.OrdinalIgnoreCase))
                {
                    logger.Info("Starting Windows service");

                    if (ServerUtil.IsUserAdministrator())
                    {
                        windowsService.Start();
                    }
                    else
                    {
                        try
                        {
                            var consolePath = Path.Combine(options.Path, "JackettConsole.exe");
                            processService.StartProcessAndLog(consolePath, "--Start", true);
                        }
                        catch
                        {
                            logger.Error("Failed to get admin rights to start the service.");
                        }
                    }
                }
                else
                {
                    var startInfo = new ProcessStartInfo()
                    {
                        Arguments       = options.Args,
                        FileName        = Path.Combine(options.Path, "JackettConsole.exe"),
                        UseShellExecute = true
                    };

                    if (isWindows)
                    {
                        //User didn't initiate the update from Windows service and wasn't running Jackett via the tray, must have started from the console
                        startInfo.Arguments      = $"/K {startInfo.FileName} {startInfo.Arguments}";
                        startInfo.FileName       = "cmd.exe";
                        startInfo.CreateNoWindow = false;
                        startInfo.WindowStyle    = ProcessWindowStyle.Normal;
                    }
                    else
                    {
                        startInfo.Arguments = startInfo.FileName + " " + startInfo.Arguments;
                        startInfo.FileName  = "mono";
                    }

                    logger.Info("Starting Jackett: " + startInfo.FileName + " " + startInfo.Arguments);
                    Process.Start(startInfo);
                }
            }
        }
        public ServerModeule() : base("Server")
        {
            Get["/Grid"] = r =>
            {
                return(View["Grid"]);
            };
            //保存数据
            Post["/"] = r =>
            {
                ServerUtil TaskUtil = this.Bind <ServerUtil>();
                return(Response.AsJson(ServerHelp.SaveServer(TaskUtil)));
            };

            Get["/Install/{Id}"] = r =>
            {
                ApiResult <string> result   = new ApiResult <string>();
                string             ServerId = r.Id;
                try
                {
                    ServerUtil serverUtil = ServerHelp.GetServerByID(ServerId);
                    string     Msg        = string.Empty;
                    ServerHelp.InstallWindowService(serverUtil, ref Msg);
                    result.Message = Msg;
                }
                catch (Exception ex)
                {
                    result.HasError = true;
                    result.Message  = ex.Message;
                }
                return(Response.AsJson(result));
            };
            Get["/UnInstall/{Id}"] = r =>
            {
                ApiResult <string> result   = new ApiResult <string>();
                string             ServerId = r.Id;
                try
                {
                    ServerUtil serverUtil = ServerHelp.GetServerByID(ServerId);
                    string     Msg        = string.Empty;
                    ServerHelp.UnInstallWindowService(serverUtil.ServerName, ref Msg);
                    result.Message = Msg;
                }
                catch (Exception ex)
                {
                    result.HasError = true;
                    result.Message  = ex.Message;
                }
                return(Response.AsJson(result));
            };
            Get["/Start/{Id}"] = r =>
            {
                ApiResult <string> result   = new ApiResult <string>();
                string             ServerId = r.Id;
                try
                {
                    ServerUtil serverUtil = ServerHelp.GetServerByID(ServerId);
                    string     Msg        = string.Empty;
                    bool       flag       = ServerHelp.StartWindowsService(serverUtil.ServerName, ref Msg);
                    if (flag)
                    {
                        serverUtil.Status = true;
                        ServerHelp.UpdateServer(serverUtil);
                    }
                    result.HasError = false;
                    result.Message  = Msg;
                }
                catch (Exception ex)
                {
                    result.HasError = true;
                    result.Message  = ex.Message;
                }
                return(Response.AsJson(result));
            };
            Get["/Stop/{Id}"] = r =>
            {
                ApiResult <string> result   = new ApiResult <string>();
                string             ServerId = r.Id;
                try
                {
                    ServerUtil serverUtil = ServerHelp.GetServerByID(ServerId);
                    string     Msg        = string.Empty;
                    bool       flag       = ServerHelp.StopWindowsService(serverUtil.ServerName, ref Msg);
                    if (flag)
                    {
                        serverUtil.Status = false;
                        ServerHelp.UpdateServer(serverUtil);
                    }
                    result.Message = Msg;
                }
                catch (Exception ex)
                {
                    result.HasError = true;
                    result.Message  = ex.Message;
                }
                return(Response.AsJson(result));
            };

            //任务编辑界面
            Get["/Edit"] = r =>
            {
                return(View["Edit"]);
            };
            //列表查询接口
            Post["/PostQuery"] = r =>
            {
                QueryCondition condition = this.Bind <QueryCondition>();
                return(Response.AsJson(ServerHelp.Query(condition)));
            };
        }