public PackageManager(Uri apiUrl, MainWindow mw, string RWPath)
        {
            ApiUrl     = apiUrl;
            MainWindow = mw;

            SqLiteAdapter     = new SqLiteAdapter(Path.Combine(RWPath, "main.dls"));
            InstalledPackages = SqLiteAdapter.LoadInstalledPackages();
            CachedPackages    = CachedPackages.Union(InstalledPackages).ToList();
            WebWrapper        = new WebWrapper(ApiUrl);
        }
        public async Task <List <int> > FindFile(string file_name, bool withDeps = true)
        {
            Package package = InstalledPackages.FirstOrDefault(x => x.FilesContained.Contains(file_name));

            if (package != default)
            {
                return new List <int>()
                       {
                           package.PackageId
                       }
            }
            ;

            lock (CachedPackages)
                package = CachedPackages.FirstOrDefault(x => x.FilesContained.Contains(file_name));

            if (package != default)
            {
                return new List <int>()
                       {
                           package.PackageId
                       }
            }
            ;

            Package onlinePackage = await WebWrapper.SearchForFile(file_name);

            if (onlinePackage != null && onlinePackage.PackageId > 0)
            {
                lock (CachedPackages)
                {
                    if (!CachedPackages.Any(x => x.PackageId == onlinePackage.PackageId))
                    {
                        CachedPackages.Add(onlinePackage);
                    }
                }

                HashSet <int> dependencyPkgIds = new HashSet <int>();

                if (withDeps)
                {
                    await GetDependencies(new HashSet <int>() { onlinePackage.PackageId }, dependencyPkgIds);
                }

                return(new List <int>()
                {
                    onlinePackage.PackageId
                }.Union(dependencyPkgIds).ToList());
            }

            return(new List <int>());
        }
        private void ContentDialog_SecondaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
        {
            string login = Username.Text;
            string pass  = Password.Password;

            if (string.IsNullOrWhiteSpace(login) || string.IsNullOrWhiteSpace(pass))
            {
                args.Cancel           = true;
                ErrorLabel.Content    = "You haven't filled all required fields.";
                ErrorLabel.Visibility = Visibility.Visible;
            }
            else
            {
                Task.Run(async() =>
                {
                    ObjectResult <LoginContent> result = await WebWrapper.Login(login.Trim(), pass, ApiUrl);
                    if (result != null && result.code == 1 && result.content?.privileges >= 0)
                    {
                        Settings.Default.Username = login.Trim();
                        Settings.Default.Password = Utils.PasswordEncryptor.Encrypt(pass, login.Trim());
                        Settings.Default.Save();
                        App.Token = result.content.token;
                        switch (Invoker)
                        {
                        case 0:
                            PM.DownloadDependencies();
                            break;

                        case 1:
                            PM.CheckUpdates();
                            break;
                        }
                    }
                    else
                    {
                        args.Cancel = true;

                        new Task(() =>
                        {
                            Dispatcher.Invoke(() =>
                            {
                                ErrorLabel.Content    = result.message;
                                ErrorLabel.Visibility = Visibility.Visible;
                            });
                        }).Start();
                    }
                }).Wait();
            }
        }
Exemple #4
0
        public PackageManager(Uri apiUrl, MainWindow mw, string RWPath)
        {
            ApiUrl     = apiUrl;
            MainWindow = mw;
            WebWrapper = new WebWrapper(ApiUrl);

            SqLiteAdapter     = new SqLiteAdapter(Path.Combine(RWPath, "main.dls"), true);
            InstalledPackages = SqLiteAdapter.LoadPackages();
            Task.Run(async() =>
            {
                await VerifyCache();
                //CachedPackages = CachedPackages.Union(InstalledPackages).ToList();
                CacheInit.Set();
            });
        }
        internal bool CheckUpdates(Uri apiUrl)
        {
            bool isThereNewer = false;

            Task.Run(async() =>
            {
                ObjectResult <AppVersionContent> jsonResult = await WebWrapper.GetAppVersion(apiUrl);
                if (jsonResult != null && Utils.IsSuccessStatusCode(jsonResult.code) && jsonResult.content.version_name != App.Version)
                {
                    isThereNewer = true;
                    UpdateUrl    = new Uri(jsonResult.content.file_path);
                }
            }).Wait();

            return(isThereNewer);
        }
        public void CheckUpdates()
        {
            Task.Run(async() =>
            {
                Dictionary <int, int> pkgsToUpdate = new Dictionary <int, int>();
                List <int> packagesId = InstalledPackages.Select(x => x.PackageId).ToList();
                Dictionary <int, int> serverVersions = await WebWrapper.GetVersions(packagesId);
                if (serverVersions.Count == 0)
                {
                    return;
                }

                foreach (Package package in InstalledPackages)
                {
                    if (serverVersions.ContainsKey(package.PackageId) && package.Version < serverVersions[package.PackageId])
                    {
                        Task <ContentDialogResult> t = null;
                        MainWindow.Dispatcher.Invoke(() =>
                        {
                            MainWindow.ContentDialog.Title               = "Newer package found!";
                            MainWindow.ContentDialog.Content             = string.Format("Newer version of following package was found on server:\n{0}\nDo you want to update it?", package.DisplayName);
                            MainWindow.ContentDialog.PrimaryButtonText   = "Yes, update";
                            MainWindow.ContentDialog.SecondaryButtonText = "No, keep local";
                            MainWindow.ContentDialog.Owner               = MainWindow;
                            t = MainWindow.ContentDialog.ShowAsync();
                        });

                        ContentDialogResult result = await t;
                        if (result == ContentDialogResult.Primary)
                        {
                            pkgsToUpdate[package.PackageId] = serverVersions[package.PackageId];
                        }
                    }
                }

                if (await CheckLogin(1) < 0 || pkgsToUpdate.Count == 0 || App.IsDownloading)
                {
                    return;
                }

                App.IsDownloading = true;
                MainWindow.Dispatcher.Invoke(() => { MainWindow.DownloadDialog.ShowAsync(); }); // TODO: Check if works
                MainWindow.DownloadDialog.UpdatePackages(pkgsToUpdate, InstalledPackages, WebWrapper, SqLiteAdapter).Wait();
                App.IsDownloading = false;
                MainWindow.RW_CrawlingComplete();
            });
        }
Exemple #7
0
        private void ContentDialog_SecondaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
        {
            string login = Username.Text;
            string pass  = Password.Password;

            if (string.IsNullOrWhiteSpace(login) || string.IsNullOrWhiteSpace(pass))
            {
                args.Cancel           = true;
                ErrorLabel.Content    = Localization.Strings.LoginMissingField;
                ErrorLabel.Visibility = Visibility.Visible;
            }
            else
            {
                Task.Run(async() =>
                {
                    ObjectResult <LoginContent> result = await WebWrapper.Login(login.Trim(), pass, ApiUrl);
                    if (result != null && Utils.IsSuccessStatusCode(result.code) && result.content?.privileges >= 0)
                    {
                        Settings.Default.Username = login.Trim();
                        Settings.Default.Password = Utils.PasswordEncryptor.Encrypt(pass, login.Trim());
                        Settings.Default.Save();
                        App.Token = result.content.token;
                        CallBack();
                    }
                    else
                    {
                        args.Cancel = true;

                        new Task(() =>
                        {
                            Dispatcher.Invoke(() =>
                            {
                                if (result != null)
                                {
                                    ErrorLabel.Content = result.message;
                                }
                                else
                                {
                                    ErrorLabel.Content = Localization.Strings.UnknownError;
                                }
                                ErrorLabel.Visibility = Visibility.Visible;
                            });
                        }).Start();
                    }
                }).Wait();
            }
        }
Exemple #8
0
 public void ReportDLC()
 {
     Task.Run(async() =>
     {
         RW_CheckingDLC(false);
         List <SteamManager.DLC> dlcList = App.SteamManager.GetInstalledDLCFiles();
         IEnumerable <Package> pkgs      = await WebWrapper.ReportDLC(dlcList, App.Token, ApiUrl);
         PM.InstalledPackages            = PM.InstalledPackages.Union(pkgs).ToList();
         new Task(() =>
         {
             foreach (Package pkg in pkgs)
             {
                 PM.SqLiteAdapter.SavePackage(pkg);
             }
             PM.SqLiteAdapter.FlushToFile(true);
         }).Start();
         PM.CacheInit.WaitOne();
         PM.CachedPackages = PM.CachedPackages.Union(PM.InstalledPackages).ToList();
         dlcReportFinishedHandler.Set();
         ReportedDLC = true;
         RW_CheckingDLC(true);
     });
 }
Exemple #9
0
        public MainWindow()
        {
            try
            {
                InitializeComponent();

                Title = $"Railworks DLS client v{App.Version}";

                App.Window = this;

                try
                {
                    App.SteamManager = new SteamManager();
                }
                catch
                {
                    Debug.Assert(false, "Initialision of SteamManager failed!");
                }

                Closing += MainWindowDialog_Closing;

                string savedRWPath = Settings.Default.RailworksLocation;
                App.Railworks = new Railworks(string.IsNullOrWhiteSpace(savedRWPath) ? App.SteamManager.RWPath : savedRWPath);
                App.Railworks.ProgressUpdated  += RW_ProgressUpdated;
                App.Railworks.RouteSaving      += RW_RouteSaving;
                App.Railworks.CrawlingComplete += RW_CrawlingComplete;

                RW = App.Railworks;

                try
                {
                    Updater updater = new Updater();
#if !DEBUG
                    if (updater.CheckUpdates(ApiUrl))
                    {
                        Task.Run(async() =>
                        {
                            await updater.UpdateAsync();
                        });
                    }
                    else
                    {
#endif
                    if (string.IsNullOrWhiteSpace(RW.RWPath))
                    {
                        RailworksPathDialog rpd = new RailworksPathDialog();
                        rpd.ShowAsync();
                    }

                    if (string.IsNullOrWhiteSpace(Settings.Default.RailworksLocation) && !string.IsNullOrWhiteSpace(RW.RWPath))
                    {
                        Settings.Default.RailworksLocation = RW.RWPath;
                        Settings.Default.Save();
                    }

                    PathChanged();

                    Settings.Default.PropertyChanged += PropertyChanged;

                    DownloadDialog.Owner = this;

                    RegistryKey key = Registry.CurrentUser.OpenSubKey("Software", true).OpenSubKey("Classes", true).CreateSubKey("dls");
                    key.SetValue("URL Protocol", "");
                    //key.SetValue("DefaultIcon", "");
                    key.CreateSubKey(@"shell\open\command").SetValue("", $"\"{System.Reflection.Assembly.GetEntryAssembly().Location}\" \"%1\"");

                    if (RW.RWPath != null && System.IO.Directory.Exists(RW.RWPath))
                    {
                        Task.Run(async() =>
                        {
                            RW_CheckingDLC(false);
                            List <SteamManager.DLC> dlcList = App.SteamManager.GetInstalledDLCFiles();
                            await WebWrapper.ReportDLC(dlcList, ApiUrl);
                            RW_CheckingDLC(true);
                        });
                    }
#if !DEBUG
                }
#endif
                }
                catch (Exception e)
                {
                    Trace.Assert(false, $"Updater panic!\n{e}");
                }
            }
            catch (Exception e)
            {
                if (e.GetType() != typeof(ThreadInterruptedException) && e.GetType() != typeof(ThreadAbortException))
                {
                    Trace.Assert(false, e.ToString());
                }
            }
        }
        public async Task ReceiveMSMQ()
        {
            string           queueFile  = Path.Combine(Path.GetTempPath(), "DLS.queue");
            HashSet <string> queuedPkgs = File.Exists(queueFile) ? File.ReadAllText(queueFile).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToHashSet() : new HashSet <string>();

            if (queuedPkgs.Count > 0)
            {
                MainWindow.Dispatcher.Invoke(() => { MainWindow.Activate(); });
                if (await CheckLogin(1) < 0 || App.IsDownloading)
                {
                    File.WriteAllText(queueFile, string.Empty);
                    return;
                }

                int idToDownload = Convert.ToInt32(queuedPkgs.PopOne());

                if (!InstalledPackages.Exists(x => x.PackageId == idToDownload))
                {
                    Task.Run(async() =>
                    {
                        Package packageToDownload = await WebWrapper.GetPackage(idToDownload);
                        lock (CachedPackages)
                        {
                            if (!CachedPackages.Any(x => x.PackageId == packageToDownload.PackageId))
                            {
                                CachedPackages.Add(packageToDownload);
                            }
                        }

                        if (packageToDownload.IsPaid)
                        {
                            App.Window.Dispatcher.Invoke(() =>
                            {
                                MainWindow.ErrorDialog = new ContentDialog()
                                {
                                    Title               = "Cannot download package",
                                    Content             = "This is paid package. Paid packages cannot be downloaded through this app.",
                                    SecondaryButtonText = "OK",
                                    Owner               = App.Window
                                };

                                MainWindow.ErrorDialog.ShowAsync();
                            });

                            return;
                        }

                        HashSet <int> depsPkgs = new HashSet <int>();
                        await GetDependencies(new HashSet <int>()
                        {
                            packageToDownload.PackageId
                        }, depsPkgs);
                        HashSet <int> packageIds = new HashSet <int>()
                        {
                            packageToDownload.PackageId
                        }.Union(depsPkgs).ToHashSet();

                        if (packageIds.Count > 0)
                        {
                            App.IsDownloading = true;
                            MainWindow.Dispatcher.Invoke(() => { MainWindow.DownloadDialog.ShowAsync(); });
                            await MainWindow.DownloadDialog.DownloadPackages(packageIds, CachedPackages, InstalledPackages, WebWrapper, SqLiteAdapter);
                            App.IsDownloading = false;
                        }
                        else
                        {
                            new Task(() =>
                            {
                                App.Window.Dispatcher.Invoke(() =>
                                {
                                    MainWindow.ErrorDialog = new ContentDialog()
                                    {
                                        Title               = "Cannot download packages",
                                        Content             = "An error ocured when trying to install package.",
                                        SecondaryButtonText = "OK",
                                        Owner               = App.Window
                                    };

                                    MainWindow.ErrorDialog.ShowAsync();
                                });
                            }).Start();
                        }
                    }).Wait();
                }
                else
                {
                    App.Window.Dispatcher.Invoke(() =>
                    {
                        MainWindow.ErrorDialog = new ContentDialog()
                        {
                            Title               = "Cannot download package",
                            Content             = "This package is already downloaded.",
                            SecondaryButtonText = "OK",
                            Owner               = App.Window
                        };

                        MainWindow.ErrorDialog.ShowAsync();
                    });
                }

                File.WriteAllText(queueFile, string.Join(",", queuedPkgs));
                await ReceiveMSMQ();
            }
        }
 public async Task <HashSet <string> > GetPaidDependencies(HashSet <string> globalDependencies)
 {
     return((await WebWrapper.QueryArray("listPaid")).Intersect(globalDependencies).ToHashSet());
 }
        public async Task <HashSet <string> > GetDownloadableDependencies(HashSet <string> globalDependencies, HashSet <string> existing, MainWindow mw)
        {
            InstalledPackages = SqLiteAdapter.LoadInstalledPackages();

            HashSet <string> allDownloadableDeps = await WebWrapper.QueryArray("listFiles");

            HashSet <string> conflictDeps = existing.Intersect(allDownloadableDeps).Except(InstalledPackages.SelectMany(x => x.FilesContained)).ToHashSet();

            HashSet <int> conflictPackages = new HashSet <int>();

            int maxThreads = Math.Min(Environment.ProcessorCount, conflictDeps.Count);

            Parallel.For(0, maxThreads, workerId =>
            {
                Task.Run(async() =>
                {
                    int max = conflictDeps.Count * (workerId + 1) / maxThreads;
                    for (int i = conflictDeps.Count * workerId / maxThreads; i < max; i++)
                    {
                        List <int> packages = await FindFile(conflictDeps.ElementAt(i), false);

                        Trace.Assert(packages.Count > 0, $"FindFile for {conflictDeps.ElementAt(i)} returned no packages!");

                        if (packages.Count > 0)
                        {
                            int id = packages.First();
                            lock (conflictPackages)
                            {
                                if (conflictPackages.Contains(id))
                                {
                                    continue;
                                }

                                conflictPackages.Add(id);
                            }
                        }
                    }
                }).Wait();
            });

            bool rewriteAll = false;
            bool keepAll    = false;

            for (int i = 0; i < conflictPackages.Count; i++)
            {
                int id = conflictPackages.ElementAt(i);

                if (Settings.Default.IgnoredPackages?.Contains(id) == true)
                {
                    continue;
                }

                Package p = CachedPackages.FirstOrDefault(x => x.PackageId == id);

                bool rewrite = false;
                if (!rewriteAll && !keepAll)
                {
                    Task <ContentDialogResult> t = null;
                    mw.Dispatcher.Invoke(() =>
                    {
                        MainWindow.ContentDialog = new ConflictPackageDialog(p.DisplayName);
                        t = MainWindow.ContentDialog.ShowAsync();
                    });

                    ContentDialogResult result = await t;

                    ConflictPackageDialog dlg = (ConflictPackageDialog)MainWindow.ContentDialog;

                    rewrite    = dlg.RewriteLocal;
                    rewriteAll = dlg.RewriteAll;
                    keepAll    = dlg.KeepAll;
                }

                if (rewrite || rewriteAll)
                {
                    PkgsToDownload.Add(id);
                    HashSet <int> depsPkgs = new HashSet <int>();
                    await GetDependencies(new HashSet <int>() { id }, depsPkgs);

                    PkgsToDownload.UnionWith(depsPkgs);
                }
                else
                {
                    if (Settings.Default.IgnoredPackages == null)
                    {
                        Settings.Default.IgnoredPackages = new List <int>();
                    }

                    Settings.Default.IgnoredPackages.Add(id);
                    Settings.Default.Save();
                }
            }

            CheckUpdates();

            DownloadableDeps = allDownloadableDeps.Intersect(globalDependencies).ToHashSet();
            return(DownloadableDeps);
        }
Exemple #13
0
        public async Task ReceiveMSMQ()
        {
            string           queueFile  = Path.Combine(Path.GetTempPath(), "DLS.queue");
            HashSet <string> queuedPkgs = File.Exists(queueFile) ? File.ReadAllText(queueFile).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToHashSet() : new HashSet <string>();

            if (queuedPkgs.Count > 0)
            {
                MainWindow.Dispatcher.Invoke(() => { MainWindow.Activate(); });
                if (!await Utils.CheckLogin(async delegate
                {
                    await ReceiveMSMQ();
                    MSMQRunning = false;
                }, MainWindow, ApiUrl) || App.IsDownloading)
                {
                    //File.WriteAllText(queueFile, string.Empty);
                    return;
                }

                int idToDownload = Convert.ToInt32(queuedPkgs.PopOne());

                if (!InstalledPackages.Exists(x => x.PackageId == idToDownload))
                {
                    Task.Run(async() =>
                    {
                        Package packageToDownload = await WebWrapper.GetPackage(idToDownload);
                        lock (CachedPackages)
                        {
                            if (!CachedPackages.Any(x => x.PackageId == packageToDownload.PackageId))
                            {
                                CachedPackages.Add(packageToDownload);
                            }
                        }

                        if (packageToDownload.IsPaid)
                        {
                            App.Window.Dispatcher.Invoke(() =>
                            {
                                MainWindow.ErrorDialog = new ContentDialog()
                                {
                                    Title               = Localization.Strings.CantDownload,
                                    Content             = Localization.Strings.PaidPackageFail,
                                    SecondaryButtonText = Localization.Strings.Ok,
                                    Owner               = App.Window
                                };

                                MainWindow.ErrorDialog.ShowAsync();
                            });

                            return;
                        }

                        HashSet <int> depsPkgs = new HashSet <int>();
                        await GetDependencies(new HashSet <int>()
                        {
                            packageToDownload.PackageId
                        }, depsPkgs);
                        HashSet <int> packageIds = new HashSet <int>()
                        {
                            packageToDownload.PackageId
                        }.Union(depsPkgs).ToHashSet();

                        if (packageIds.Count > 0)
                        {
                            App.IsDownloading = true;
                            MainWindow.Dispatcher.Invoke(() => { MainWindow.DownloadDialog.ShowAsync(); });
                            await MainWindow.DownloadDialog.DownloadPackages(packageIds, CachedPackages, InstalledPackages, WebWrapper, SqLiteAdapter);
                            App.IsDownloading = false;
                        }
                        else
                        {
                            new Task(() =>
                            {
                                App.Window.Dispatcher.Invoke(() =>
                                {
                                    MainWindow.ErrorDialog = new ContentDialog()
                                    {
                                        Title               = Localization.Strings.CantDownload,
                                        Content             = Localization.Strings.InstalFail,
                                        SecondaryButtonText = Localization.Strings.Ok,
                                        Owner               = App.Window
                                    };

                                    MainWindow.ErrorDialog.ShowAsync();
                                });
                            }).Start();
                        }
                    }).Wait();
                }
                else
                {
                    App.Window.Dispatcher.Invoke(() =>
                    {
                        MainWindow.ErrorDialog = new ContentDialog()
                        {
                            Title               = Localization.Strings.CantDownload,
                            Content             = Localization.Strings.AlreadyInstalFail,
                            SecondaryButtonText = Localization.Strings.Ok,
                            Owner               = App.Window
                        };

                        MainWindow.ErrorDialog.ShowAsync();
                    });
                }

                File.WriteAllText(queueFile, string.Join(",", queuedPkgs));
                await ReceiveMSMQ();
            }
        }
Exemple #14
0
        public async Task VerifyCache()
        {
            List <Package> localCache = SqLiteAdapter.LoadPackages(true);

            ServerVersions = new Dictionary <int, int>();
            localCache.ForEach(x => ServerVersions[x.PackageId] = x.Version);
            Tuple <IEnumerable <Package>, HashSet <int> > tRemoteCache = await WebWrapper.ValidateCache(ServerVersions);

            IEnumerable <Package> remoteCache    = tRemoteCache.Item1;
            HashSet <int>         remoteVersions = tRemoteCache.Item2;

            lock (CachedPackages)
            {
                CachedPackages = remoteCache.ToList();
                localCache.ForEach(x =>
                {
                    if (!remoteVersions.Contains(x.PackageId))
                    {
                        CachedPackages.Add(x);
                    }
                    else
                    {
                        ServerVersions[x.PackageId] = CachedPackages.First(y => y.PackageId == x.PackageId).Version;
                    }
                });
                foreach (Package pkg in remoteCache)
                {
                    ServerVersions[pkg.PackageId] = pkg.Version;
                }
            }
            if (remoteVersions.Count > 0)
            {
                new Task(() =>
                {
                    foreach (Package pkg in CachedPackages)
                    {
                        SqLiteAdapter.SavePackage(pkg, true);
                    }
                    SqLiteAdapter.FlushToFile(true);
                }).Start();
            }
            CachedPackages.ForEach(x =>
            {
                if (x.IsPaid)
                {
                    x.FilesContained.ForEach(y =>
                    {
                        DownloadablePaidDepsPackages[y] = x.PackageId;
                        DownloadablePaidDeps.Add(y);
                    });
                }
                else
                {
                    x.FilesContained.ForEach(y =>
                    {
                        DownloadableDepsPackages[y] = x.PackageId;
                        DownloadableDeps.Add(y);
                    });
                }
            });
        }