Exemplo n.º 1
0
 public void StoreTest()
 {
     ConfigStore store = new ConfigStore(CONNSTR);
     MXManager target = new MXManager(store); // TODO: Initialize to an appropriate value
     ConfigStore actual = target.Store;
     Assert.Equal(target.Store, actual);
     
 }
        public static Dictionary<string, string> GetCurrentValues(ConfigStore Store)
        {
            var result = new Dictionary<string, string>();

            foreach (FieldInfo f in Store.GetType().GetFields().Where(f => f.IsPublic))
            {
                var value = f.GetValue(Store).ToString();
                result.Add(f.Name, value);
            }

            return result;
        }
        public static void loadAdmins(ConfigStore store)
        {
            string fileName = SERVER_ADMINS_FILENAME;

            try
            {
                if (File.Exists(fileName))
                {
                    store.admins.Clear();
                    store.admins.AddRange(File.ReadAllLines(fileName));
                }
            }
            catch { }
        }
Exemplo n.º 4
0
        public static void loadWhitelist(ConfigStore Store)
        {
            string FileName = SERVER_WHITELIST_FILENAME;

            try
            {
                if (File.Exists(FileName))
                {
                    Store.whitelist.Clear();
                    Store.whitelist.AddRange(File.ReadAllLines(FileName));
                }
            }
            catch { }
        }
        public static void loadBans(ConfigStore Store)
        {
            string FileName = SERVER_BANS_FILENAME;

            try
            {
                if (File.Exists(FileName))
                {
                    Store.bans.Clear();

                    foreach (var l in File.ReadAllLines(FileName))
                    {
                        var Now = DateTime.Now;

                        try
                        {
                            if (l.StartsWith("#")) { continue; }
                            var parts = l.Split('\t');
                            var newBan = new BanRecord()
                            {
                                When = DateTime.Parse(parts[0]),
                                Expires = DateTime.Parse(parts[1]),
                                WhoBy = parts[2],
                                BannedIP = IPAddress.Parse(parts[3]),
                                BannedGUID = Guid.Parse(parts[4]),
                                BannedName = parts[5],
                                Why = parts[6],
                            };

                            if (newBan.Expires > Now)
                            {
                                Store.bans.Add(newBan);
                            }
                        }
                        catch
                        {
                            //Bad ban line. Don't care?
                        }
                    }
                }
            }
            catch { }
        }
Exemplo n.º 6
0
        public static void modifySetting(ConfigStore Store, string Key, string Value)
        {
            try
            {
                FieldInfo f = Store.GetType().GetFields().Where(fF => fF.Name.ToLowerInvariant() == Key.ToLowerInvariant()).First();
                object newValue;

                if (f.FieldType.IsEnum)
                {
                    newValue = Enum.Parse(f.FieldType, Value.ToString(), true);
                }
                else
                {
                    newValue = (f.FieldType == typeof(bool)) ? getBool(Value.ToString()) : Convert.ChangeType(Value, f.FieldType);
                }

                f.SetValue(Store, newValue);
            }
            catch
            {
                throw new ArgumentException(string.Format("{0} is not a valid value for {1}", Value, Key));
            }
        }
        public static void saveBans(ConfigStore Store)
        {
            string FileName = SERVER_BANS_FILENAME;

            try
            {
                if (File.Exists(FileName))
                {
                    File.SetAttributes(FileName, FileAttributes.Normal);
                }

                using (StreamWriter configWriter = new StreamWriter(FileName))
                {
                    configWriter.WriteLine("#When\tExpires\tWhoBy\tBannedIP\tBannedGUID\tBannedName\tWhy");

                    foreach (var b in Store.bans.Where(b => b.Expires > DateTime.Now))
                    {
                        configWriter.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}", b.When.ToString(), b.Expires.ToString(), b.WhoBy, b.BannedIP.ToString(), b.BannedGUID.ToString(), b.BannedName, b.Why);
                    }
                }
            }
            catch { }
        }
        public static void readFromFile(ConfigStore Store)
        {
            string FileName = SERVER_CONFIG_FILENAME;

            Dictionary<string, string> ConfigStore = new Dictionary<string, string>();

            //Read the settings file into a dictionary before shoving the values in the setting store.
            try
            {
                if (!File.Exists(FileName)) { writeToFile(Store);  return; }
                using (StreamReader configReader = new StreamReader(FileName))
                {
                    string CurrentLine;
                    string[] LineParts;

                    while (configReader.EndOfStream == false)
                    {
                        CurrentLine = configReader.ReadLine();

                        if (CurrentLine.StartsWith("#") || String.IsNullOrEmpty(CurrentLine)) { continue; }

                        LineParts = CurrentLine.Split(new char[] { '=' }, 2);
                        if (LineParts.Length < 2) { continue; }

                        LineParts[0] = LineParts[0].ToLowerInvariant();

                        ConfigStore.Add(LineParts[0].Trim(), LineParts[1].Trim());
                    }

                    configReader.Close();
                }
            }
            catch (Exception)
            {

            }

            foreach (FieldInfo f in Store.GetType().GetFields())
            {
                string node = f.Name.ToLowerInvariant();

                if (ConfigStore.ContainsKey(node))
                {
                    SetFieldValue(ConfigStore, Store, f, node);
                }
                else
                {
                    //Missing a node, no matter - default value will remain.
                }
            }
        }
        public async Task DeleteTest()
        {
            await Connection.DeleteAsync(WaitUntil.Completed);

            var exception = Assert.ThrowsAsync <RequestFailedException>(async() => { PrivateEndpointConnectionResource connection = await ConfigStore.GetPrivateEndpointConnections().GetAsync(Connection.Data.Name); });

            Assert.AreEqual(404, exception.Status);
        }
        public async Task <IActionResult> Index()
        {
            var config = await ConfigStore.GetConfigAsync();

            return(View(config.Tiles));
        }
Exemplo n.º 11
0
        /// <inheritdoc />
        public VirtualFileSystemEntry Build(VirtualDirectory root, List <Mod> enabledMods, string hostOutputPath = null, string gameName = null, bool useCompression = false, bool useExtracted = false)
        {
            gameName = Game.ToString();

            if (root == null)
            {
                throw new ArgumentNullException(nameof(root));
            }

            //Get game config
            var config = ConfigStore.Get(Game) as ModCpkGameConfig ?? throw new InvalidOperationException("Game config is missing.");

            Log.Builder.Info($"Building {gameName} Mod");
            Log.Builder.Info("Processing mod files");

            bool pc = Convert.ToBoolean(config.PC);
            var  modFilesDirectory = new VirtualDirectory();

            if (!pc)
            {
                modFilesDirectory = new VirtualDirectory(null, "mod");
            }
            else
            {
                modFilesDirectory = new VirtualDirectory(null, "");
            }

            foreach (var entry in root)
            {
                if (entry.EntryType == VirtualFileSystemEntryType.Directory)
                {
                    var directory = (VirtualDirectory)entry;
                    var name      = directory.Name.ToLowerInvariant();

                    switch (name)
                    {
                    case "mod":
                    case "data":
                    {
                        // Move files in 'cpk' directory to 'mod' directory
                        LogModFilesInDirectory(directory);

                        foreach (var modFileEntry in directory)
                        {
                            modFileEntry.CopyTo(modFilesDirectory);
                        }
                    }
                    break;

                    default:
                        // Move directory to 'mod' directory
                        Log.Builder.Trace($"Adding directory {entry.FullName} to mod.cpk");
                        entry.CopyTo(modFilesDirectory);
                        break;
                    }
                }
                else
                {
                    // Move file to 'mod' directory
                    Log.Builder.Trace($"Adding file {entry.FullName} to mod.cpk");
                    entry.CopyTo(modFilesDirectory);
                }
            }

            bool.TryParse(config.Compression, out useCompression);

            // If PC Mode is enabled, clear and replace contents
            if (pc)
            {
                if (Directory.Exists(hostOutputPath))
                {
                    foreach (var directory in Directory.GetDirectories(hostOutputPath))
                    {
                        Log.Builder.Info($"Replacing Output Path contents");
                        string[] stringArray = { "data00000", "data00001", "data00002", "data00003", "data00004", "data00005", "data00006", "movie00000", "movie00001", "movie00002", "snd", "data_e" };
                        if (stringArray.Any(Path.GetFileName(directory).ToLower().Equals))
                        {
                            Directory.Delete(directory, true);
                        }
                    }
                }

                Directory.CreateDirectory(Path.GetFullPath(hostOutputPath));
                modFilesDirectory.SaveToHost(hostOutputPath);
                Log.Builder.Info("Done!");
                return(modFilesDirectory);
            }
            else
            {
                // Build mod cpk
                Log.Builder.Info($"Building mod.cpk");
                var cpkModCompiler = new CpkModBuilder();

                if (hostOutputPath != null)
                {
                    Directory.CreateDirectory(hostOutputPath);
                }

                var cpkFilePath = hostOutputPath != null?Path.Combine(hostOutputPath, "mod.cpk") : null;

                var cpkNotWritable   = File.Exists(cpkFilePath) && FileHelper.IsFileInUse(cpkFilePath);
                var cpkFileBuildPath = hostOutputPath != null?cpkNotWritable?Path.Combine(Path.GetTempPath(), "mod.cpk") : cpkFilePath : null;

                var cpkFile = cpkModCompiler.Build(modFilesDirectory, enabledMods, cpkFileBuildPath, gameName, useCompression);

                if (cpkFileBuildPath != cpkFilePath)
                {
                    File.Copy(cpkFileBuildPath, cpkFilePath, true);
                    File.Delete(cpkFileBuildPath);
                    cpkFile = VirtualFile.FromHostFile(cpkFilePath);
                }
                Log.Builder.Info("Done!");
                return(cpkFile);
            }
        }
Exemplo n.º 12
0
        public async Task <IActionResult> Themes()
        {
            var config = await ConfigStore.GetConfigAsync();

            return(View(config.CurrentTheme));
        }
Exemplo n.º 13
0
        public async Task GetKeysTest()
        {
            List <ApiKey> keys = await ConfigStore.GetKeysAsync().ToEnumerableAsync();

            Assert.IsTrue(keys.Count >= 1);
        }
Exemplo n.º 14
0
        /// <inheritdoc />
        public VirtualFileSystemEntry Build(VirtualDirectory root, string hostOutputPath = null, string gameName = null, bool useCompression = false, bool useExtracted = false)
        {
            gameName = Game.Persona5.ToString();

            if (root == null)
            {
                throw new ArgumentNullException(nameof(root));
            }

            //Get game config
            var config = ConfigStore.Get <Persona5GameConfig>() ?? throw new InvalidOperationException("Game config is missing.");

            Log.Builder.Info("Building Persona 5 Mod");
            Log.Builder.Info("Processing mod files");

            var modFilesDirectory = new VirtualDirectory(null, "mod");

            foreach (var entry in root)
            {
                if (entry.EntryType == VirtualFileSystemEntryType.Directory)
                {
                    var directory = ( VirtualDirectory )entry;
                    var name      = directory.Name.ToLowerInvariant();

                    switch (name)
                    {
                    case "mod":
                    case "cache":
                    case "data":
                    case "ps3":
                    case "ps3sndjp":
                    case "patch1ps3":
                    case "patch3ps3":
                    case "ps4":
                    case "ps4sndjp":
                    {
                        // Move files in 'cpk' directory to 'mod' directory
                        LogModFilesInDirectory(directory);

                        foreach (var modFileEntry in directory)
                        {
                            modFileEntry.CopyTo(modFilesDirectory);
                        }
                    }
                    break;

                    default:
                        // Move directory to 'mod' directory
                        Log.Builder.Trace($"Adding directory {entry.FullName} to mod.cpk");
                        entry.CopyTo(modFilesDirectory);
                        break;
                    }
                }
                else
                {
                    // Move file to 'mod' directory
                    Log.Builder.Trace($"Adding file {entry.FullName} to mod.cpk");
                    entry.CopyTo(modFilesDirectory);
                }
            }

            bool.TryParse(config.Compression, out useCompression);

            // Build mod cpk
            Log.Builder.Info("Building mod.cpk");
            var cpkModCompiler = new CpkModBuilder();
            var cpkFilePath    = hostOutputPath != null?Path.Combine(hostOutputPath, "mod.cpk") : null;

            var cpkFileBuildPath = hostOutputPath != null?FileHelper.IsFileInUse(cpkFilePath) ? Path.Combine(Path.GetTempPath(), "mod.cpk") : cpkFilePath : null;

            var cpkFile = cpkModCompiler.Build(modFilesDirectory, cpkFileBuildPath, gameName, useCompression);

            if (cpkFileBuildPath != cpkFilePath)
            {
                File.Copy(cpkFileBuildPath, cpkFilePath, true);
                File.Delete(cpkFileBuildPath);
                cpkFile = VirtualFile.FromHostFile(cpkFilePath);
            }

            Log.Builder.Info("Done!");

            return(cpkFile);
        }
Exemplo n.º 15
0
        public async Task InitializeAsync()
        {
            // Read the state and update the config in the store and trigger update callback if needed

            // Check if the secret certificate has been updated or not
            // Get the current certificate from store
            string thumbprintFromManifest, x509StoreNameFromManifest;
            var    updateSecrets = false;
            var    configStore   = await ConfigStore.CreateOrGetConfigStore(this.statefulService);

            using (var transaction = this.statefulService.StateManager.CreateTransaction())
            {
                var val = await configStore.GetValueAsync(Common.Constants.SecretUpdateInProgress, transaction);

                // Check explicitly if the configured secret in manifest and the secret stored in ConfigStore are same or not
                var thumbprintFromStore = await configStore.GetValueAsync(Common.Constants.EncryptionCertThumbprintKey, transaction);

                // Initialize and fetch the thumbprint configured in manifest
                this.GetConfigFromNativeConfigStore(out thumbprintFromManifest, out x509StoreNameFromManifest);

                if (String.IsNullOrEmpty(val))
                {
                    if (String.IsNullOrEmpty(thumbprintFromManifest))
                    {
                        thumbprintFromManifest = null;
                    }

                    if (String.IsNullOrEmpty(thumbprintFromStore))
                    {
                        thumbprintFromStore = null;
                    }

                    // Thumbprint for encryption cert has changed, let's update secrets
                    if (!String.Equals(thumbprintFromManifest, thumbprintFromStore, StringComparison.InvariantCultureIgnoreCase))
                    {
                        BackupRestoreTrace.TraceSource.WriteInfo(TraceType, "The existing and new thumprints dont match, existing {0}, new {1}, triggering secrets udpate", thumbprintFromStore, thumbprintFromManifest);
                        updateSecrets = true;
                    }
                }
                else
                {
                    BackupRestoreTrace.TraceSource.WriteInfo(TraceType, "Detected update in progress flag, triggering secrets update");
                    // There is an update in progress, let's update secrets
                    updateSecrets = true;
                }

                if (updateSecrets)
                {
                    // Set secret update in progress flag by setting some random guid value.
                    await configStore.UpdateValueAsync(Common.Constants.SecretUpdateInProgress, Guid.NewGuid().ToString(), transaction);
                }

                await transaction.CommitAsync();
            }

            lock (Lock)
            {
                EncryprtionCertThumprint = thumbprintFromManifest;
                EncryptionCertStoreName  = x509StoreNameFromManifest;
            }

            if (updateSecrets)
            {
                BackupRestoreTrace.TraceSource.WriteInfo(TraceType, "Invoking update cert callback");

                // Trigger the update secrets callback
                this.updateCertCallback(thumbprintFromManifest, x509StoreNameFromManifest, this.runAsyncCancellationToken);
            }
        }
        public async Task GetTest()
        {
            List <AppConfigurationPrivateEndpointConnectionResource> connections = await ConfigStore.GetAppConfigurationPrivateEndpointConnections().GetAllAsync().ToEnumerableAsync();

            string privateEndpointConnectionName = connections.First().Data.Name;
            AppConfigurationPrivateEndpointConnectionResource privateEndpointConnection = await ConfigStore.GetAppConfigurationPrivateEndpointConnections().GetAsync(privateEndpointConnectionName);

            Assert.IsTrue(privateEndpointConnectionName.Equals(privateEndpointConnection.Data.Name));
            Assert.IsTrue(privateEndpointConnection.Data.ConnectionState.Status == Models.ConnectionStatus.Approved);
        }
Exemplo n.º 17
0
        private async void ManifestIDSelector_LoadAsync(object sender, EventArgs e)
        {
Refresh:
            this.Text = Resources.GettingManifestHistory;
            //var doc = await webClient.LoadFromWebAsync("https://steamdb.info/depot/" + PendingDepotID.ToString() + "/manifests/");
            if (!Program.ManifestHistoryCache.ContainsKey(PendingDepotID))
            {
                if (!(ConfigStore.TheConfig.StoredCookies.ContainsKey("__cfduid") &&
                      ConfigStore.TheConfig.StoredCookies.ContainsKey("cf_clearance")))
                {
                    do
                    {
                        string CookieStr = "__cfduid=cookie1;cf_clearance=cookie2";
                        System.Diagnostics.Process.Start("https://steamdb.info");
                        if (Util.InputBox(Resources.InputSteamDBCookies, Resources.InputSteamDBCookies, ref CookieStr) == DialogResult.OK)
                        {
                            string[] Cookies = CookieStr.Split(';');
                            Dictionary <string, string> tmpCookieContainner = new Dictionary <string, string>();
                            for (int i = 0; i < Cookies.Length; i++)
                            {
                                string[] CookieItem = Cookies[i].Split('=');
                                if (CookieItem.Length < 2)
                                {
                                    break;
                                }
                                tmpCookieContainner.Add(CookieItem[0], CookieItem[1]);
                            }
                            if (tmpCookieContainner.ContainsKey("__cfduid") && tmpCookieContainner.ContainsKey("cf_clearance"))
                            {
                                ConfigStore.TheConfig.StoredCookies["__cfduid"]     = tmpCookieContainner["__cfduid"];
                                ConfigStore.TheConfig.StoredCookies["cf_clearance"] = tmpCookieContainner["cf_clearance"];
                                ConfigStore.Save();
                                break;
                            }
                        }
                        MessageBox.Show(Resources.InvalidCookies, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    } while (false);
                }
                var webClient = new WebClient();
                webClient.Encoding = Encoding.UTF8;
                webClient.Headers.Add(HttpRequestHeader.Cookie,
                                      string.Format("__cfduid={0}; cf_clearance={1}", ConfigStore.TheConfig.StoredCookies["__cfduid"],
                                                    ConfigStore.TheConfig.StoredCookies["cf_clearance"]));
                webClient.Headers.Add(HttpRequestHeader.Accept, "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3");
                webClient.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.19 Safari/537.36 Edg/77.0.235.9");
                //webClient.Headers.Add(HttpRequestHeader.re)
                string webPageStr;
                try
                {
                    webPageStr = await webClient.DownloadStringTaskAsync("https://steamdb.info/depot/" + PendingDepotID.ToString() + "/manifests/");
                }
                catch
                {
                    if (MessageBox.Show(Resources.FailedToGetManifestHistory + "\n" + Resources.refreshCookieRequest
                                        , "SteamDepotDownloaderGUI", MessageBoxButtons.YesNo, MessageBoxIcon.Error) == DialogResult.Yes)
                    {
                        ConfigStore.TheConfig.StoredCookies.Remove("__cfduid");
                        ConfigStore.TheConfig.StoredCookies.Remove("cf_clearance");
                        goto Refresh;
                    }
                    PendingReturnManifestID = ContentDownloader.INVALID_MANIFEST_ID;
                    Close();
                    return;
                }
                HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                doc.LoadHtml(webPageStr);
                if (doc.DocumentNode.SelectSingleNode("//title").GetDirectInnerText() == "Just a moment... · Steam Database")
                {
                    /*if (MessageBox.Show(Resources.FailedToGetManifestHistory + "\n" + Resources.refreshCookieRequest
                    *   , "SteamDepotDownloaderGUI", MessageBoxButtons.YesNo, MessageBoxIcon.Error) == DialogResult.Yes)*/
                    {
                        ConfigStore.TheConfig.StoredCookies.Remove("__cfduid");
                        ConfigStore.TheConfig.StoredCookies.Remove("cf_clearance");
                        goto Refresh;
                    }

                    /*PendingReturnManifestID = ContentDownloader.INVALID_MANIFEST_ID;
                     * Close();
                     * return;*/
                }
                ManifestHistoryRecord manifestHistoryRecord = new ManifestHistoryRecord();
                var DepotInfoNode = doc.DocumentNode.SelectNodes("//div[@class='wrapper-info scope-depot']/div/table/tbody/tr");
                //Check if xpath is succeed.
                if (DepotInfoNode != null)
                {
                    //The sequence for these data seems to be fixed,so use Index directly.
                    //Actually maybe use ChildNodes[0] will be better?
                    manifestHistoryRecord.DepotID    = DepotInfoNode[0].ChildNodes[3].GetDirectInnerText();
                    manifestHistoryRecord.BuildID    = DepotInfoNode[1].ChildNodes[3].GetDirectInnerText();
                    manifestHistoryRecord.ManifestID = DepotInfoNode[2].ChildNodes[3].GetDirectInnerText();
                    manifestHistoryRecord.DepotName  = DepotInfoNode[3].ChildNodes[3].GetDirectInnerText();
                    manifestHistoryRecord.LastUpdate = DepotInfoNode[4].SelectSingleNode("//i").GetDirectInnerText();
                }
                else
                {
                    MessageBox.Show(Resources.nomanifesthistory, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Close();
                    return;
                }
                DepotInfoNode = doc.DocumentNode.SelectNodes("//div[@id='manifests']/div[@class='table-responsive']/table/tbody/tr");
                manifestHistoryRecord.HistoryCollection = new List <ManifestHistoryRecord.ManifestHistoryRecordSingle>();
                for (int i = 0; i < DepotInfoNode.Count; i++)
                {
                    ManifestHistoryRecord.ManifestHistoryRecordSingle tmpRecord;
                    //Text,Tr,Text,Tr,Text,Tr,Text
                    //We only need,1,3,5
                    tmpRecord.Date = DepotInfoNode[i].ChildNodes[1].GetDirectInnerText();
                    var    relativeDate = DateTime.Now - DateTime.Parse(DepotInfoNode[i].ChildNodes[3].Attributes["title"].Value);
                    string relativeDateStr;
                    if (relativeDate.TotalDays > 365)
                    {
                        relativeDateStr = ((int)(relativeDate.TotalDays / 365)).ToString() + " Year" + (relativeDate.TotalDays / 365 >= 2 ? "s" : "") + " Ago";
                    }
                    else if (relativeDate.TotalDays > 30)
                    {
                        relativeDateStr = ((int)(relativeDate.TotalDays / 30)).ToString() + " Month" + (relativeDate.TotalDays / 30 >= 2 ? "s" : "") + " Ago";
                    }
                    else
                    {
                        relativeDateStr = ((int)relativeDate.TotalDays).ToString() + " Day" + (relativeDate.TotalDays >= 2 ? "s" : "") + " Ago";
                    }
                    tmpRecord.RelativeDate = relativeDateStr;
                    tmpRecord.ManifestID   = ulong.Parse(DepotInfoNode[i].ChildNodes[5].GetDirectInnerText());
                    manifestHistoryRecord.HistoryCollection.Add(tmpRecord);
                }
                Program.ManifestHistoryCache.Add(PendingDepotID, manifestHistoryRecord);
            }
            var ManifestRecord = Program.ManifestHistoryCache[PendingDepotID];

            //The sequence for these data seems to be fixed,so use Index directly.
            //Actually maybe use ChildNodes[0] will be better?
            labelDepotID.Text    = string.Format(Resources.mids_DepotID, ManifestRecord.DepotID);
            labelBuildID.Text    = string.Format(Resources.mids_BuildID, ManifestRecord.BuildID);
            labelManifestID.Text = string.Format(Resources.mids_ManifestID, ManifestRecord.ManifestID);
            labelDepotName.Text  = string.Format(Resources.mids_DepotName, ManifestRecord.DepotName);
            labelLastUpdate.Text = string.Format(Resources.mids_LastUpdate, ManifestRecord.LastUpdate);
            this.listViewManifests.Items.Clear();
            for (int i = 0; i < ManifestRecord.HistoryCollection.Count; i++)
            {
                ListViewItem curHistory = new ListViewItem();
                curHistory.Text = ManifestRecord.HistoryCollection[i].Date;
                curHistory.SubItems.Add(ManifestRecord.HistoryCollection[i].RelativeDate);
                curHistory.SubItems.Add(ManifestRecord.HistoryCollection[i].ManifestID.ToString());
                this.listViewManifests.Items.Add(curHistory);
            }
            this.Text = "ManifestID Selelctor";
        }
Exemplo n.º 18
0
 public DomainController()
 {
     _configStore = Service.Current.Store;
     _logger      = Log.For(this);
 }
Exemplo n.º 19
0
        public async Task GetAvailableLocationsTest()
        {
            IEnumerable <AzureLocation> locations = await ConfigStore.GetAvailableLocationsAsync();

            Assert.IsTrue(locations.Count() >= 0);
        }
Exemplo n.º 20
0
        //Write the setting store out to a file by reflecting over its members.
        public static void writeToFile(ConfigStore Store)
        {
            string FileName = SERVER_CONFIG_FILENAME;

            try
            {
                if (File.Exists(FileName))
                {
                    File.SetAttributes(FileName, FileAttributes.Normal);
                }

                using (StreamWriter configWriter = new StreamWriter(FileName))
                {
                    foreach (FieldInfo f in Store.GetType().GetFields().Where(f => f.IsPublic))
                    {
                        var value = f.GetValue(Store).ToString();
                        string data = string.Format("{0}={1}", f.Name, value);
                        configWriter.WriteLine(data);
                    }
                }
            }
            catch (Exception)
            {

            }
        }
Exemplo n.º 21
0
        public void CreateUpdateAndLoadBoatWithUpdatingOpinions()
        {
            for (var i = 0; i < _testCount; i++)
            {
                var config      = new ConfigStore(Platform.Windows);
                var crew        = CreateInitialCrew(config);
                var gameManager = new GameManager();
                gameManager.NewGame(Path.Combine(Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName, "Testing"), "Testy McTestFace", new Color(0, 0, 0), new Color(0, 0, 0), "Player Manager", false, "English", crew);

                var skip = gameManager.Team.CrewMembers["Skippy Skip"];
                var nav  = gameManager.Team.CrewMembers["Wise Nav"];
                var bow  = gameManager.Team.CrewMembers["Dim Wobnam"];
                skip.AddOrUpdateOpinion(gameManager.Team.ManagerName, 5);
                skip.AddOrUpdateOpinion(nav.Name, 1);
                skip.AddOrUpdateOpinion(bow.Name, -3);
                nav.AddOrUpdateOpinion(gameManager.Team.ManagerName, -3);
                nav.AddOrUpdateOpinion(skip.Name, 1);
                nav.AddOrUpdateOpinion(bow.Name, -1);
                bow.AddOrUpdateOpinion(gameManager.Team.ManagerName, -5);
                bow.AddOrUpdateOpinion(skip.Name, -3);
                bow.AddOrUpdateOpinion(nav.Name, -5);

                gameManager.Team.Boat.AssignCrewMember(Position.Skipper, gameManager.Team.CrewMembers["Skippy Skip"]);
                gameManager.Team.Boat.UpdateScore(gameManager.Team.ManagerName);
                Assert.AreEqual(15, gameManager.Team.Boat.Score);
                gameManager.Team.Boat.AssignCrewMember(Position.Navigator, gameManager.Team.CrewMembers["Wise Nav"]);
                gameManager.Team.Boat.UpdateScore(gameManager.Team.ManagerName);
                Assert.AreEqual(24, gameManager.Team.Boat.Score);
                gameManager.Team.Boat.AssignCrewMember(Position.MidBowman, gameManager.Team.CrewMembers["Dim Wobnam"]);
                gameManager.Team.Boat.UpdateScore(gameManager.Team.ManagerName);
                Assert.AreEqual(22, gameManager.Team.Boat.Score);
                gameManager.SaveLineUp(0);
                Assert.AreEqual(22, gameManager.Team.Boat.Score);
                //Assert.AreEqual(24, gameManager.Team.Boat.Score); opinion changes

                gameManager.LoadGame(Path.Combine(Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName, "Testing"), "Testy McTestFace");

                Assert.AreEqual("Testy McTestFace", gameManager.Team.Name);
                Assert.AreEqual("Player Manager", gameManager.Team.ManagerName);
                //Assert.AreEqual(gameManager.Team.CrewMembers.Count - gameManager.Boat.PositionCount, gameManager.Boat.UnassignedCrew.Count);
                gameManager.Team.Boat.UpdateScore(gameManager.Team.ManagerName);
                Assert.AreEqual(22, gameManager.Team.Boat.Score);
                //Assert.AreEqual(24, gameManager.Team.Boat.Score); opinion changes

                skip = gameManager.Team.CrewMembers["Skippy Skip"];
                nav  = gameManager.Team.CrewMembers["Wise Nav"];
                bow  = gameManager.Team.CrewMembers["Dim Wobnam"];

                skip.AddOrUpdateOpinion(gameManager.Team.ManagerName, 2);
                skip.AddOrUpdateOpinion(nav.Name, 2);
                skip.AddOrUpdateOpinion(bow.Name, 2);
                gameManager.Team.Boat.UpdateScore(gameManager.Team.ManagerName);
                Assert.AreEqual(24, gameManager.Team.Boat.Score);
                //Assert.AreEqual(26, gameManager.Team.Boat.Score); opinion changes
                nav.AddOrUpdateOpinion(gameManager.Team.ManagerName, -1);
                nav.AddOrUpdateOpinion(skip.Name, 2);
                nav.AddOrUpdateOpinion(bow.Name, -3);
                gameManager.Team.Boat.UpdateScore(gameManager.Team.ManagerName);
                Assert.AreEqual(23, gameManager.Team.Boat.Score);
                //Assert.AreEqual(25, gameManager.Team.Boat.Score); opinion changes
                bow.AddOrUpdateOpinion(gameManager.Team.ManagerName, 1);
                bow.AddOrUpdateOpinion(skip.Name, 1);
                bow.AddOrUpdateOpinion(nav.Name, -2);
                gameManager.Team.Boat.UpdateScore(gameManager.Team.ManagerName);
                Assert.AreEqual(25, gameManager.Team.Boat.Score);
                //Assert.AreEqual(27, gameManager.Team.Boat.Score); opinion changes
                gameManager.SaveLineUp(0);
                Assert.AreEqual(25, gameManager.Team.Boat.Score);
                //Assert.AreEqual(29, gameManager.Team.Boat.Score); opinion changes

                gameManager.LoadGame(Path.Combine(Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName, "Testing"), "Testy McTestFace");

                gameManager.Team.Boat.UpdateScore(gameManager.Team.ManagerName);
                Assert.AreEqual(25, gameManager.Team.Boat.Score);
                //Assert.AreEqual(29, gameManager.Team.Boat.Score); opinion changes
            }
        }
Exemplo n.º 22
0
 public ResolverViewModel(ConfigStore left, ConfigStore right)
 {
     Left  = left;
     Right = right;
 }
Exemplo n.º 23
0
 internal List <CrewMember> CreateInitialCrew(ConfigStore config)
 {
     CrewMember[] crew =
     {
         new CrewMember
         {
             Name   = "Skippy Skip",
             Age    = 35,
             Gender = "M",
             Skills = new Dictionary <Skill, int>()
             {
                 { Skill.Body,        2 },
                 { Skill.Charisma,   10 },
                 { Skill.Perception,  2 },
                 { Skill.Quickness,   2 },
                 { Skill.Wisdom,     10 },
                 { Skill.Willpower,  10 }
             }
         },
         new CrewMember
         {
             Name   = "Wise Nav",
             Age    = 28,
             Gender = "M",
             Skills = new Dictionary <Skill, int>()
             {
                 { Skill.Body,        2 },
                 { Skill.Charisma,    2 },
                 { Skill.Perception, 10 },
                 { Skill.Quickness,   2 },
                 { Skill.Wisdom,     10 },
                 { Skill.Willpower,   2 }
             }
         },
         new CrewMember
         {
             Name   = "Dim Wobnam",
             Age    = 19,
             Gender = "M",
             Skills = new Dictionary <Skill, int>()
             {
                 { Skill.Body,       10 },
                 { Skill.Charisma,    2 },
                 { Skill.Perception,  2 },
                 { Skill.Quickness,  10 },
                 { Skill.Wisdom,      2 },
                 { Skill.Willpower,  10 }
             }
         },
         new CrewMember
         {
             Name   = "Rav Age",
             Age    = 25,
             Gender = "M",
             Skills = new Dictionary <Skill, int>()
             {
                 { Skill.Body,        5 },
                 { Skill.Charisma,    5 },
                 { Skill.Perception,  5 },
                 { Skill.Quickness,   5 },
                 { Skill.Wisdom,      5 },
                 { Skill.Willpower,   5 }
             }
         },
         new CrewMember
         {
             Name   = "Nick Pony",
             Age    = 32,
             Gender = "M",
             Skills = new Dictionary <Skill, int>()
             {
                 { Skill.Body,        7 },
                 { Skill.Charisma,    7 },
                 { Skill.Perception,  7 },
                 { Skill.Quickness,   3 },
                 { Skill.Wisdom,      3 },
                 { Skill.Willpower,   3 }
             }
         }
     };
     return(crew.ToList());
 }
Exemplo n.º 24
0
        private async void Start()
        {
            var aggregator = new MessageAggregator();

            _relay = aggregator;
            IConfigStore       configStore  = new ConfigStore(Application.persistentDataPath);
            IPreviewImageStore previewStore = new PreviewImageStore(Application.persistentDataPath);

            _library = new Library(configStore, _previewBuilder, previewStore, _relay);
            var factory = new ImportFolderFactory(_library);

            // Misc
            var checker         = new UpdateChecker(_relay);
            var appVersionModel = new AppVersionDisplayModel(_relay);

            _tracker = new SelectionTracker(_library);

            // Main View
            var progressModel    = new ProgressModel();
            var applicationModel = new ApplicationModel(_relay);
            var searchViewModel  = new SearchModel(_library, _relay);
            var itemsViewModel   = new ItemsModel(_library, _relay);

            // Main Menu
            var importFoldersViewModel = new ImportFoldersModel(configStore, factory, _relay);
            var savedSearchesViewModel = new SavedSearchesModel(configStore, _relay);
            var collectionsViewModel   = new CollectionsModel(configStore, _library, _relay);

            // Detail Menu
            var detailMenuModel = new DetailMenuModel(_library, _relay);

            // Dialogs
            var addCollectionModel       = new AddCollectionModel(_relay);
            var addSavedSearchViewModel  = new AddSavedSearchModel(_relay);
            var addImportFolderViewModel = new AddImportFolderModel(_relay);
            var applicationSettingsModel = new ApplicationSettingsModel(configStore);
            var userFeedbackModel        = new UserFeedbackModel();
            var updateNotificationModel  = new UpdateNotificationModel(configStore);
            var exitingModel             = new ExitingModel(_library, OnShutdownComplete);
            var editScreenModel          = new EditScreenModel(_library);

            BindViewModels();
            BindSettings();

            // Wire up misc items
            _disposables.Add(importFoldersViewModel);
            _editScreen.MainView = _mainGroup;

            // Also restores app settings for import etc.
            await applicationSettingsModel.InitializeAsync();

            await _library.InitializeAsync();

            InitializeViewModelsAsync();

            aggregator.Subscribe(
                // Main View
                progressModel,
                searchViewModel,
                itemsViewModel,

                // Main Menu
                importFoldersViewModel,
                savedSearchesViewModel,
                collectionsViewModel,

                // DetailMenu
                detailMenuModel,

                // Misc
                appVersionModel,
                _tracker,

                // Dialogs
                addCollectionModel,
                addSavedSearchViewModel,
                addImportFolderViewModel,
                applicationSettingsModel,
                userFeedbackModel,
                updateNotificationModel,
                exitingModel,
                editScreenModel);

            void BindViewModels()
            {
                // Main View
                _progressView.BindTo(progressModel);
                _applicationView.BindTo(applicationModel);
                _searchView.BindTo(searchViewModel);
                _libraryView.BindTo(itemsViewModel);

                // Main Menu
                _importFoldersView.BindTo(importFoldersViewModel);
                _savedSearchesView.BindTo(savedSearchesViewModel);
                _collectionsView.BindTo(collectionsViewModel);

                // Detail Menu
                _detailMenu.BindTo(detailMenuModel);

                // Misc
                _versionButton.BindTo(appVersionModel);

                // Dialogs
                _addCollectionDialog.BindTo(addCollectionModel);
                _addImportFolderDialog.BindTo(addImportFolderViewModel);
                _addSavedSearchDialog.BindTo(addSavedSearchViewModel);
                _applicationSettingsDialog.BindTo(applicationSettingsModel);
                _userFeedbackDialog.BindTo(userFeedbackModel);
                _updateNotificationDialog.BindTo(updateNotificationModel);
                _exitingDialog.BindTo(exitingModel);
                _editScreen.BindTo(editScreenModel);
            }

            void BindSettings()
            {
                var rt = applicationSettingsModel.RuntimeSettings;

                rt.ImportParallelism.ValueChanged += factor => _library.Parallelism = factor;
                rt.LogLevel.ValueChanged          += logLevel => UnityLogger.LogLevel = logLevel;

                rt.UiScalePercent.ValueChanged += factor =>
                {
                    foreach (var canvas in FindObjectsOfTypeAll <CanvasScaler>())
                    {
                        canvas.scaleFactor = applicationSettingsModel.UiScalePercent / 125f;
                    }
                };

                rt.ScrollSensitivity.ValueChanged += sensitivity =>
                {
                    foreach (var area in FindObjectsOfType <ScrollRect>())
                    {
                        area.scrollSensitivity = sensitivity;
                    }
                };

                rt.PreviewResolution.ValueChanged  += res => _previewBuilder.PreviewResolution.Value = Mathf.RoundToInt(Mathf.Pow(2f, res));
                rt.PreviewJpegQuality.ValueChanged += quality => _previewBuilder.Quality = quality;
            }

            async void InitializeViewModelsAsync()
            {
                await savedSearchesViewModel.InitializeAsync();

                await importFoldersViewModel.InitializeAsync();

                await collectionsViewModel.InitializeAsync();

                await updateNotificationModel.InitializeAsync();

                // run update checks
                await checker.CheckForUpdatesAsync();
            }
        }
Exemplo n.º 25
0
 public BlobFacts()
 {
     m_store = CreateConfigStore();
 }
Exemplo n.º 26
0
 static MultiThreadTests()
 {
     s_store = new ConfigStore(ConnectionStringTimeout, TimeSpan.FromMinutes(2));
 }
Exemplo n.º 27
0
        /// <inheritdoc />
        public VirtualFileSystemEntry Build(VirtualDirectory root, string hostOutputPath = null, string gameName = null, bool useCompression = false, bool useExtracted = false)
        {
            if (root == null)
            {
                throw new ArgumentNullException(nameof(root));
            }

            Log.Builder.Info($"Building {Game} Mod");
            if (hostOutputPath != null)
            {
                Log.Builder.Info($"Output directory: {hostOutputPath}");
            }

            // Get game config
            var config = ConfigStore.Get(Game) as Persona34GameConfig ?? throw new InvalidOperationException("Game config is missing.");

            if (string.IsNullOrWhiteSpace(config.DvdRootOrIsoPath))
            {
                throw new InvalidConfigException("Dvd root path/ISO path is not specified.");
            }

            // Get files
            Log.Builder.Trace($"DvdRootOrIsoPath = {config.DvdRootOrIsoPath}");
            var dvdRootDirectory = Persona34Common.GetRootDirectory(config, out var isoFileSystem);

            // Find system config
            var systemConfigFile = dvdRootDirectory["SYSTEM.CNF"] as VirtualFile ?? throw new MissingFileException("SYSTEM.CNF is missing from the file source.");

            string executablePath;

            using (var systemConfigStream = systemConfigFile.Open())
            {
                bool leaveOpen = isoFileSystem == null;
                executablePath = Ps2SystemConfig.GetExecutablePath(systemConfigStream, leaveOpen, true);
            }

            if (executablePath == null)
            {
                throw new MissingFileException("Executable file path is not specified in SYSTEM.CNF; Unable to locate executable file.");
            }

            Log.Builder.Info($"Executable path: {executablePath}");

            var executableFile = ( VirtualFile )dvdRootDirectory[executablePath] ?? throw new MissingFileException("The executable file is missing from the dvd root file source.");

            // Some basic checks have been done, let's start generating the cvms
            var dvdRootDirectoryPath = hostOutputPath ?? Path.Combine(Path.GetTempPath(), "Persona34ModCompilerTemp_" + Path.GetRandomFileName());

            Log.Builder.Trace($"Creating (temp?) output directory: {dvdRootDirectoryPath}");
            Directory.CreateDirectory(dvdRootDirectoryPath);

            var bgmCvmFile      = ( VirtualFile )dvdRootDirectory["BGM.CVM"];
            var bgmCvmModified  = false;
            var btlCvmFile      = ( VirtualFile )dvdRootDirectory["BTL.CVM"];
            var btlCvmModified  = false;
            var dataCvmFile     = ( VirtualFile )dvdRootDirectory["DATA.CVM"];
            var dataCvmModified = false;
            var envCvmFile      = ( VirtualFile )dvdRootDirectory["ENV.CVM"];
            var envCvmModified  = false;

            var newDvdRootDirectory = new VirtualDirectory();

            // Process mod files
            Log.Builder.Info("Processing mod files");
            foreach (var entry in root)
            {
                if (entry.EntryType == VirtualFileSystemEntryType.File)
                {
                    Log.Builder.Info($"Adding file {entry.Name} to root directory");
                    entry.MoveTo(newDvdRootDirectory, true);
                    continue;
                }

                var name      = entry.Name.ToLowerInvariant();
                var directory = ( VirtualDirectory )entry;

                switch (name)
                {
                case "bgm":
                    UpdateAndRecompileCvm(ref bgmCvmFile, directory, Path.Combine(dvdRootDirectoryPath, "bgm.cvm"), newDvdRootDirectory);
                    bgmCvmModified = true;
                    break;

                case "btl":
                    UpdateAndRecompileCvm(ref btlCvmFile, directory, Path.Combine(dvdRootDirectoryPath, "btl.cvm"), newDvdRootDirectory);
                    btlCvmModified = true;
                    break;

                case "data":
                    UpdateAndRecompileCvm(ref dataCvmFile, directory, Path.Combine(dvdRootDirectoryPath, "data.cvm"), newDvdRootDirectory);
                    dataCvmModified = true;
                    break;

                case "env":
                {
                    Log.Builder.Info("Replacing files in env.cvm");

                    if (envCvmFile == null)
                    {
                        throw new MissingFileException("Mod replaces files in env.cvm but env.cvm isn't present.");
                    }

                    UpdateAndRecompileCvm(ref envCvmFile, directory, Path.Combine(dvdRootDirectoryPath, "env.cvm"), newDvdRootDirectory);
                    envCvmModified = true;
                }
                break;

                default:
                    Log.Builder.Info($"Adding directory {entry.Name} to root directory");
                    entry.MoveTo(newDvdRootDirectory, true);
                    break;
                }
            }

            // Patch executable
            var executableFilePath = executableFile.SaveToHost(dvdRootDirectoryPath);

            Log.Builder.Info($"Patching executable");
            Log.Builder.Trace($"Executable file path: {executableFilePath}");
            if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows))
            {
                if (bgmCvmModified)
                {
                    PatchExecutable(executableFilePath, bgmCvmFile.HostPath);
                }

                if (btlCvmModified)
                {
                    PatchExecutable(executableFilePath, btlCvmFile.HostPath);
                }

                if (dataCvmModified)
                {
                    PatchExecutable(executableFilePath, dataCvmFile.HostPath);
                }

                if (envCvmModified)
                {
                    PatchExecutable(executableFilePath, envCvmFile.HostPath);
                }
            }
            else
            {
                if (bgmCvmModified)
                {
                    PatchExecutableLinux(executableFilePath, bgmCvmFile.HostPath);
                }

                if (btlCvmModified)
                {
                    PatchExecutableLinux(executableFilePath, btlCvmFile.HostPath);
                }

                if (dataCvmModified)
                {
                    PatchExecutableLinux(executableFilePath, dataCvmFile.HostPath);
                }

                if (envCvmModified)
                {
                    PatchExecutableLinux(executableFilePath, envCvmFile.HostPath);
                }
            }

            executableFile = VirtualFile.FromHostFile(executableFilePath);
            executableFile.MoveTo(newDvdRootDirectory, true);

            if (hostOutputPath != null)
            {
                Log.Builder.Info($"Copying files to output directory (might take a while): {hostOutputPath}");
                newDvdRootDirectory.SaveToHost(hostOutputPath);
            }

            if (hostOutputPath != null && isoFileSystem != null)
            {
                isoFileSystem.Dispose();
            }

            Log.Builder.Info("Done");

            return(newDvdRootDirectory);
        }
Exemplo n.º 28
0
 private void GameComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
 {
     SelectedGame = ( Game )(GameComboBox.SelectedIndex + 1);
     GameConfig   = ConfigStore.Get(SelectedGame);
     RefreshMods();
 }
Exemplo n.º 29
0
        public async Task <IActionResult> Settings()
        {
            var config = await ConfigStore.GetConfigAsync();

            return(View(config.Settings));
        }
Exemplo n.º 30
0
 private void UpdateConfigChangesAndSave()
 {
     UpdateGameConfigEnabledMods();
     UpdateWindowConfig();
     ConfigStore.Save();
 }
Exemplo n.º 31
0
 private void Window_Closed(object sender, EventArgs e)
 {
     PipeListener.staticpipelistener.OnMusicPlay -= UpdatePlayingSongView;
     windowinstance = null;
     ConfigStore.SaveConfig(ConfigStore.StaticConfig);
 }
Exemplo n.º 32
0
 protected override Persona34GameConfig GetConfig() => ConfigStore.Get <Persona4GameConfig>();
Exemplo n.º 33
0
        //    private async Task CheckDuplicateModuleNames()
        //    {
        //        var modnames = CService.Modules.Select(m => m.Name).ToList();
        //        var multiples = modnames.Where(name => modnames.Count(str => str.Equals(name, StringComparison.OrdinalIgnoreCase)) > 1);

        //        if (multiples.Any())
        //        {
        //            var error = $@"Multiple modules with the same Name have been registered, SimplePermissions cannot function.
        //Duplicate names: {String.Join(", ", multiples.Distinct())}.";
        //            await Log(LogSeverity.Error, error).ConfigureAwait(false);
        //            throw new Exception(error);
        //        }

        //        if (SocketClient != null)
        //        {
        //            SocketClient.Ready -= CheckDuplicateModuleNames;
        //            //using (var config = ConfigStore.Load())
        //            //{
        //            //    await _cachedConfig.Synchronize(SocketClient, config).ConfigureAwait(false);
        //            //}
        //        }
        //        //if (ShardedClient != null)
        //        //    ShardedClient.GetShard(0).Ready -= CheckDuplicateModuleNames;



        //    }

        internal IPermissionConfig LoadConfig() => ConfigStore.Load();
Exemplo n.º 34
0
        public static void saveAdmins(ConfigStore Store)
        {
            string FileName = SERVER_ADMINS_FILENAME;

            try
            {
                if (File.Exists(FileName))
                {
                    File.SetAttributes(FileName, FileAttributes.Normal);
                }

                using (StreamWriter configWriter = new StreamWriter(FileName))
                {
                    foreach (var u in Store.admins)
                    {
                        configWriter.WriteLine(u);
                    }
                }
            }
            catch { }
        }
Exemplo n.º 35
0
        protected DocumentStoreBase(ConfigStore configStore, ILoggerFactory logFactory)
        {
            Ensure.ArgumentNotNull(configStore, nameof(configStore));

            this._configStore = configStore;
        }
Exemplo n.º 36
0
        public static void saveWhitelist(ConfigStore Store)
        {
            string FileName = SERVER_WHITELIST_FILENAME;

            try
            {
                if (File.Exists(FileName))
                {
                    File.SetAttributes(FileName, FileAttributes.Normal);
                }

                using (StreamWriter configWriter = new StreamWriter(FileName))
                {
                    foreach (var u in Store.whitelist)
                    {
                        configWriter.WriteLine(u.ToLowerInvariant());
                    }
                }
            }
            catch { }
        }
Exemplo n.º 37
0
        /// <inheritdoc />
        public VirtualFileSystemEntry Build(VirtualDirectory root, string hostOutputPath = null, string gameName = null, bool useCompression = false, bool useExtracted = false)
        {
            gameName = Game.ToString();

            if (root == null)
            {
                throw new ArgumentNullException(nameof(root));
            }

            // Get game config
            var config = ConfigStore.Get(Game) as CatherineFullBodyGameConfig;

            if (config == null)
            {
                // Unlikely
                throw new InvalidOperationException("Game config is missing.");
            }

            if (string.IsNullOrWhiteSpace(config.CpkRootOrPath))
            {
                throw new InvalidConfigException("CPK path is not specified.");
            }

            // Create temp folder
            var cpkRootDirectoryPath = Path.Combine(Path.GetTempPath(), $"{Game}ModCompilerTemp_" + Path.GetRandomFileName());

            Log.Builder.Trace($"Creating temp output directory: {cpkRootDirectoryPath}");
            Directory.CreateDirectory(cpkRootDirectoryPath);

            // Get files from CPK
            VirtualDirectory cpkRootDirectory;

            Log.Builder.Trace($"{nameof(config.CpkRootOrPath)} = {config.CpkRootOrPath}");

            if (config.CpkRootOrPath.EndsWith(".cpk"))
            {
                // If extraction is enabled, use files from CPK path
                useExtracted = Convert.ToBoolean(config.Extract);
                if (useExtracted)
                {
                    Log.Builder.Info($"Extracting CPK: {config.CpkRootOrPath}");

                    if (!File.Exists(config.CpkRootOrPath))
                    {
                        throw new InvalidConfigException($"CPK root path references a CPK file that does not exist: {config.CpkRootOrPath}.");
                    }

                    string[] args = { "-x", "-i", config.CpkRootOrPath, "-d", cpkRootDirectoryPath };
                    CriPakTools.Program.Main(args);
                }
                // Cpk file found & extracted, convert it to our virtual file system
                cpkRootDirectory      = VirtualDirectory.FromHostDirectory(cpkRootDirectoryPath);
                cpkRootDirectory.Name = Path.GetFileNameWithoutExtension(config.CpkRootOrPath);
            }
            else
            {
                Log.Builder.Info($"Mounting directory: {config.CpkRootOrPath}");

                if (!Directory.Exists(config.CpkRootOrPath))
                {
                    throw new InvalidConfigException($"CPK root path references a directory that does not exist: {config.CpkRootOrPath}.");
                }

                // No CPK file found, assume files are extracted
                cpkRootDirectory      = VirtualDirectory.FromHostDirectory(config.CpkRootOrPath);
                cpkRootDirectory.Name = Path.GetDirectoryName(config.CpkRootOrPath);
            }

            Log.Builder.Info("Processing mod files");
            foreach (var entry in root)
            {
                if (entry.EntryType == VirtualFileSystemEntryType.Directory)
                {
                    var directory = (VirtualDirectory)entry;
                    var name      = directory.Name.ToLowerInvariant();

                    switch (name)
                    {
                    case "mod":
                    case "cache":
                    case "umd0":
                    case "umd1":
                    case "vita":
                    case "patch":
                    case "memst":
                    {
                        // Move files in 'cpk' directory to 'mod' directory
                        LogModFilesInDirectory(directory);

                        foreach (var modFileEntry in directory)
                        {
                            modFileEntry.CopyTo(cpkRootDirectory);
                        }
                    }
                    break;

                    default:
                        // Move directory to 'mod' directory
                        Log.Builder.Trace($"Adding directory {entry.FullName} to {cpkRootDirectory.Name}.cpk");
                        entry.CopyTo(cpkRootDirectory);
                        break;
                    }
                }
                else
                {
                    // Move file to 'mod' directory
                    Log.Builder.Trace($"Adding file {entry.FullName} to {cpkRootDirectory.Name}.cpk");
                    entry.CopyTo(cpkRootDirectory);
                }
            }

            useCompression = Convert.ToBoolean(config.Compression);

            // Build mod cpk
            var cpkModCompiler = new CpkModBuilder();
            var cpkFilePath    = hostOutputPath != null?Path.Combine(hostOutputPath, $"{cpkRootDirectory.Name}.cpk") : null;

            var cpkFile = cpkModCompiler.Build(cpkRootDirectory, cpkFilePath, gameName, useCompression);

            Log.Builder.Info("Done!");
            return(cpkFile);
        }
Exemplo n.º 38
0
        public async Task <IActionResult> Index([FromRoute] string page)
        {
            var config = await ConfigStore.GetConfigAsync();

            return(View(config[page].Tiles));
        }
Exemplo n.º 39
0
 public IDictionary <OsuSetting, string> GetLoggableState() =>
 new Dictionary <OsuSetting, string>(ConfigStore.Where(kvp => !keyContainsPrivateInformation(kvp.Key)).ToDictionary(kvp => kvp.Key, kvp => kvp.Value.ToString()));
        public async Task InvokeAsync(HttpContext context)
        {
            var config = await ConfigStore.GetConfigAsync();

            if (!string.IsNullOrWhiteSpace(config?.Settings?.BaseUri) && (!string.IsNullOrWhiteSpace(config?.Settings?.AccessToken) || !string.IsNullOrWhiteSpace(SupervisorEnvironment.GetSupervisorToken())))
            {
                if (!ClientFactory.IsInitialized)
                {
                    if (config.Settings.IsHassIo)
                    {
                        Log.LogInformation($"Auto-initializing HACC via Hass.io addon.");
                        ClientFactory.Initialize(config.Settings.BaseUri, SupervisorEnvironment.GetSupervisorToken());

                        var discovery = ClientFactory.GetClient <DiscoveryClient>();
                        var discInfo  = await discovery.GetDiscoveryInfo();

                        await ConfigStore.ManipulateConfig(c => c.Settings.ExternalBaseUri = discInfo.BaseUrl);
                    }
                    else
                    {
                        Log.LogInformation($"Initializing HACC API with URL {config?.Settings?.BaseUri ?? "[NULL]"} and access token [{new string(config?.Settings?.AccessToken.Take(6).ToArray())}•••••••••••{new string(config?.Settings?.AccessToken.TakeLast(6).ToArray())}].");
                        ClientFactory.Initialize(config.Settings.BaseUri, config.Settings.AccessToken);
                    }
                }
            }
            else
            {
                ClientFactory.Reset();
            }

            if (!ClientFactory.IsInitialized)
            {
                // If we're in Hass.io mode, set the base URI and redirect to the admin homepage.
                if (!string.IsNullOrWhiteSpace(SupervisorEnvironment.GetSupervisorToken()))
                {
                    await ConfigStore.ManipulateConfig(c =>
                    {
                        c.Settings = new SystemSettings
                        {
                            BaseUri     = "http://hassio/homeassistant",
                            AccessToken = null,
                            IsHassIo    = true
                        };

                        context.Response.StatusCode = 303;
                        context.Response.Redirect("/admin");
                    });
                }

                // Otherwise, if we aren't on one of the approved pages, redirect to the settings page and prompt for setup.
                if (context.Request.Path.ToString().ToLower() != "/admin/settings" && context.Request.Path.ToString().ToLower() != "/admin")
                {
                    Log.LogInformation($"Client factory is not initialized, redirecting user to settings area...");

                    context.Response.Redirect("/admin/settings?setup=1");
                    return;
                }
            }

            // Pages Migration

#pragma warning disable CS0612
            if ((config.TileLayout?.Count > 0 || config.Tiles?.Count > 0) && (config.Pages?.Count ?? 0) == 0)
            {
                await ConfigStore.ManipulateConfig(config =>
                {
                    config.Pages ??= new List <Page>();
                    config.Pages.Add(new Page
                    {
                        Name           = "default",
                        Description    = "[Automatically generated from previous configuration.]",
                        IsDefaultPage  = true,
                        Tiles          = config.Tiles,
                        TileLayout     = config.TileLayout,
                        LayoutSettings = config.LayoutSettings
                    });
                    config.TileLayout     = null;
                    config.Tiles          = null;
                    config.LayoutSettings = null;
                });

                context.Response.Redirect("/admin/pageMigration");
            }
            else if (config.Pages.Count == 0)
            {
                await ConfigStore.ManipulateConfig(config =>
                {
                    config.Pages = new List <Page>
                    {
                        new Page
                        {
                            Name           = "default",
                            Description    = "Default Page",
                            IsDefaultPage  = true,
                            Tiles          = new List <BaseTile>(),
                            TileLayout     = new List <TileLayout>(),
                            LayoutSettings = new LayoutSettings
                            {
                                DeviceHeightPx = 1280,
                                DeviceWidthPx  = 720,
                                BaseTileSizePx = 92,
                                TileSpacingPx  = 6,
                            }
                        }
                    };
                });
            }
#pragma warning restore CS0612

            await Next(context);
        }
        public async Task CreateOrUpdateTest()
        {
            // Only support update
            List <AppConfigurationPrivateEndpointConnectionResource> connections = await ConfigStore.GetAppConfigurationPrivateEndpointConnections().GetAllAsync().ToEnumerableAsync();

            string privateEndpointConnectionName = connections.FirstOrDefault().Data.Name;
            AppConfigurationPrivateEndpointConnectionData privateEndpointConnectionData = connections.FirstOrDefault().Data;

            privateEndpointConnectionData.ConnectionState.Description = "Update descriptions";
            AppConfigurationPrivateEndpointConnectionResource privateEndpointConnection = (await ConfigStore.GetAppConfigurationPrivateEndpointConnections().CreateOrUpdateAsync(WaitUntil.Completed, privateEndpointConnectionName, privateEndpointConnectionData)).Value;

            Assert.IsTrue(privateEndpointConnectionName.Equals(privateEndpointConnection.Data.Name));
            Assert.IsTrue(PrivateEndpointResource.Data.Id.Equals(privateEndpointConnection.Data.PrivateEndpoint.Id));
            Assert.IsTrue(privateEndpointConnection.Data.ConnectionState.Description.Equals("Update descriptions"));
        }