示例#1
0
        public static void UseNewLanguageFile(string fileName, long id, int msgId)
        {
            var msg = "Moving file to production..\n";

            msg += "Checking paths for duplicate language file...\n";
            Bot.Api.EditMessageTextAsync(id, msgId, msg).Wait();
            fileName += ".xml";
            var tempPath    = Bot.TempLanguageDirectory;
            var langPath    = Bot.LanguageDirectory;
            var newFilePath = Path.Combine(tempPath, fileName);
            var copyToPath  = Path.Combine(langPath, fileName);

            //get the new files language
            var doc = XDocument.Load(newFilePath);

            var newFileLang = new
            {
                Name    = doc.Descendants("language").First().Attribute("name").Value,
                Base    = doc.Descendants("language").First().Attribute("base").Value,
                Variant = doc.Descendants("language").First().Attribute("variant").Value
            };


            //check for existing file
            var langs = Directory.GetFiles(langPath, "*.xml").Select(x => new LangFile(x)).ToList();
            var lang  = langs.FirstOrDefault(x => x.Name == newFileLang.Name && x.FilePath != copyToPath);

            if (lang != null)
            {
                msg       += $"Found duplicate language (name attribute) with filename {Path.GetFileNameWithoutExtension(lang.FilePath)}\n";
                copyToPath = lang.FilePath;
            }
            else
            {
                lang = langs.FirstOrDefault(x => x.Base == newFileLang.Base && x.Variant == newFileLang.Variant && x.Name != newFileLang.Name);
                if (lang != null)
                {
                    msg += $"Found duplicate language (matching base and variant) with filename {Path.GetFileNameWithoutExtension(lang.FilePath)}\n";
                    msg += "Aborting!";
                    Bot.Api.EditMessageTextAsync(id, msgId, msg);
                    return;
                }
            }


            System.IO.File.Copy(newFilePath, copyToPath, true);
            msg += "File copied to bot\n";
            //#if RELEASE
            //            msg += $"File copied to bot 1\n";
            //#elif RELEASE2
            //            msg += $"File copied to bot 2\n";
            //#endif
            //Bot.Api.EditMessageTextAsync(id, msgId, msg);
            //#if RELEASE
            //            copyToPath = copyToPath.Replace("Werewolf 3.0", "Werewolf 3.0 Clone");
            //            System.IO.File.Copy(newFilePath, copyToPath, true);
            //            msg += $"File copied to bot 2\n";
            //            Bot.Api.EditMessageTextAsync(id, msgId, msg);
            //#endif
#if !DEBUG
            var gitPath = Path.Combine(@"C:\Werewolf Source\Werewolf\Werewolf for Telegram\Languages", Path.GetFileName(copyToPath));
            File.Copy(newFilePath, gitPath, true);
            System.IO.File.Delete(newFilePath);
            msg += $"File copied to git directory\n";
            if (Path.GetFileName(newFilePath) == Program.MasterLanguage)
            {
                var p = new Process
                {
                    StartInfo =
                    {
                        FileName               = @"C:\Werewolf Source\Werewolf\Werewolf for Telegram\Languages\commit.bat",
                        Arguments              = $"\"Syncing langfiles from Telegram (English.xml update)\"",
                        WorkingDirectory       = @"C:\Werewolf Source\Werewolf\Werewolf for Telegram\Languages",
                        UseShellExecute        = false,
                        RedirectStandardOutput = true,
                        RedirectStandardError  = true,
                        CreateNoWindow         = true
                    }
                };

                p.Start();
                msg += "Started the committing process. Reading output from git...";
                Bot.Edit(id, msgId, msg).Wait();

                var output = "";
                while (!p.StandardOutput.EndOfStream)
                {
                    output += p.StandardOutput.ReadLine() + Environment.NewLine;
                }
                while (!p.StandardError.EndOfStream)
                {
                    output += p.StandardError.ReadLine() + Environment.NewLine;
                }

                msg += "\nValidating the output...";
                Bot.Edit(id, msgId, msg).Wait();

                //validate the output
                if (output.Contains("failed"))
                {
                    msg += "\n<b>Failed</b> to commit files. See control output for information";
                    Console.WriteLine(output);
                }
                else if (output.Contains("nothing to commit"))
                {
                    msg += "\nNothing to commit.";
                }
                else
                {
                    //try to grab the commit
                    var regex  = new Regex("(\\[master .*])");
                    var match  = regex.Match(output);
                    var commit = "";
                    if (match.Success)
                    {
                        commit = match.Value.Replace("[master ", "").Replace("]", "");
                    }
                    msg += $"\n<b>Files committed successfully.</b> {(String.IsNullOrEmpty(commit) ? "" : $"<a href=\"https://github.com/GreyWolfDev/Werewolf/commit/" + commit + $"\">{commit}</a>")}";
                }
            }
#endif
            using (var db = new WWContext())
            {
                var newFile = new LangFile(copyToPath);

                // search for language file entry and update it or add it if it's not present yet
                Language language = db.Language.FirstOrDefault(x => x.FileName == newFile.FileName);
                if (language == null)
                {
                    language = db.Language.Add(new Language {
                        FileName = newFile.FileName
                    });
                }
                language.Base      = newFile.Base;
                language.IsDefault = newFile.IsDefault;
                language.LangCode  = newFile.LangCode;
                language.Name      = newFile.Name;
                language.Variant   = newFile.Variant;

                db.SaveChanges();
            }

            var info = new ReloadLangInfo
            {
                LangName = Path.GetFileNameWithoutExtension(copyToPath)
            };
            var json = JsonConvert.SerializeObject(info);

            foreach (var n in Bot.Nodes)
            {
                n.Broadcast(json);
            }

            msg += "\n<b>Operation complete.</b>";
            Bot.Edit(id, msgId, msg, parsemode: ParseMode.Html);
        }
示例#2
0
        internal static async void MonitorUpdates()
        {
#if !DEBUG
            try
#endif
            {
                var baseDirectory   = Path.Combine(Bot.RootDirectory, ".."); //go up one directory
                var updateDirectory = Path.Combine(Bot.RootDirectory, "Update");
                while (Bot.Nodes.Count == 0)
                {
                    await Task.Delay(500);
                }
                var currentVersion = Bot.Nodes.Max(x => Version.Parse(x.Version));
                var currentChoice  = new NodeChoice();
                while (true)
                {
                    //check nodes first
                    foreach (var dir in Directory.GetDirectories(baseDirectory, "*Node*"))
                    {
                        //get the node exe in this directory
                        var     file = Directory.GetFiles(dir, "Werewolf Node.exe").First();
                        Version fvi  = Version.Parse(FileVersionInfo.GetVersionInfo(file).FileVersion);
                        if (fvi > currentChoice.Version)
                        {
                            currentChoice.Path    = file;
                            currentChoice.Version = fvi;
                        }
                    }
                    if (currentChoice.Version > currentVersion)
                    {
                        currentVersion = currentChoice.Version;
                        //alert dev group
                        Bot.Send($"New node with version {currentVersion} found.  Stopping old nodes.", -1001077134233);
                        //kill existing nodes
                        foreach (var node in Bot.Nodes)
                        {
                            node.ShutDown();
                        }
                        await Task.Delay(500);

                        foreach (var node in Bot.Nodes)
                        {
                            node.ShutDown();
                        }
                    }

                    //now check for Control update
                    if (Directory.GetFiles(updateDirectory).Count() > 1)
                    {
                        //update available
                        //sleep 5 seconds to allow any nodes to connect and whatnot.
                        await Task.Delay(5000);

                        //await Bot.Send($"New control found.  Updating.", -1001077134233);
                        //fire off the updater
                        Process.Start(Path.Combine(Bot.RootDirectory, "Resources\\update.exe"), "-1001077134233");
                        Bot.Running     = false;
                        Program.Running = false;
                        Bot.Api.StopReceiving();
                        //Thread.Sleep(500);
                        using (var db = new WWContext())
                        {
                            var bot =
#if DEBUG
                                4;
#elif BETA
                                3;
#elif RELEASE
                                1;
#elif RELEASE2
                                2;
#endif

#if !DEBUG
                            var status = await db.BotStatus.FindAsync(bot);

                            status.BotStatus = "Updating";
                            await db.SaveChangesAsync();
#endif
                        }
                        Environment.Exit(1);
                    }


                    //check once every 5 seconds
                    await Task.Delay(5000);
                }
                //now we have the most recent version, launch one
            }
#if !DEBUG
            catch (Exception e)
            {
                Bot.Send($"Error in update monitor: {e.Message}\n{e.StackTrace}", -1001077134233, parseMode: ParseMode.Default);
            }
#endif
        }
示例#3
0
        public static void DoUpdate(CallbackQuery query)
        {
            var msg        = "Beginning file moving...";
            var updateType = query.Data.Split('|')[1];

            try
            {
                Bot.ReplyToCallback(query, msg);
                //directories
                var uDir       = "c:\\build\\";
                var controlDir = uDir + "Werewolf Control\\bin\\";
                var nodeDir    = uDir + "Werewolf Node\\bin\\";

                var botBaseDir = "c:\\BOT\\Werewolf 4.0 ";


                //files
                var baseFiles = new[]
                {
                    "Database.dll", "Database.pdb", "TcpFramework.dll", "TcpFramework.pdb", "Telegram.Bot.dll",
                    "Telegram.Bot.xml"
                };
                //control has different names for each bot
                //node we will just copy the entire folder

                //stage the control files in the update folder
                foreach (var b in Builds)
                {
                    if (updateType.StartsWith("beta") && b.BuildName != "Beta")
                    {
                        continue;                      //if beta update, don't update release
                    }
                    if (!updateType.Contains("nodes")) //if nodes only, don't update control
                    {
                        foreach (
                            var file in
                            Directory.GetFiles(controlDir + b.BuildName)
                            .Where(
                                x =>
                                baseFiles.Contains(Path.GetFileName(x)) ||
                                Path.GetFileName(x).Contains(b.ControlExeName))
                            )
                        {
                            var fName = Path.GetFileName(file);
                            System.IO.File.Copy(file, botBaseDir + b.BotDirSuffix + "\\Control\\Update\\" + fName, true);
                        }
                        msg += $"\nCopied {b.BuildName} Control files";
                        Bot.ReplyToCallback(query, msg);
                    }

                    if (!updateType.Contains("control")) //if control only, don't update nodes
                    {
                        //now find the oldest node folder

                        var copied = false;

                        foreach (
                            var d in Directory.GetDirectories(botBaseDir + b.BotDirSuffix, "*Node*"))
                        {
                            //get the version of werewolf
                            //copy the node files to it
                            foreach (var file in Directory.GetFiles(nodeDir + b.BuildName))
                            {
                                var fName = Path.GetFileName(file);
                                copied = true;
                                try
                                {
                                    System.IO.File.Copy(file, Path.Combine(d, fName), true);
                                }
                                catch (Exception e)
                                {
                                    if (e.Message.Contains("because it is being used by another process"))
                                    //nodes in this folder are still active D:
                                    {
                                        copied = false;
                                        break;
                                    }
                                    else
                                    {
                                        throw;
                                    }
                                }
                            }

                            if (copied)
                            {
                                msg += $"\nCopied {b.BuildName} Node files to " + d.Substring(d.LastIndexOf("\\") + 1);
                                Bot.ReplyToCallback(query, msg);
                                break;
                            }
                        }

                        if (!copied)
                        {
                            throw new Exception("Unable to copy Node files to a directory.");
                        }
                    }
                }


                //tell each bot to replace nodes

                //tell each bot to update
                msg += "\n\nCompleted Call, bots should now auto load updated files";
                Bot.ReplyToCallback(query, msg);
            }
            catch (Exception e)
            {
                Bot.ReplyToCallback(query, msg + "\n" + e.Message);
            }
        }
示例#4
0
        private static void ServerOnDataReceived(object sender, Message message)
        {
            try
            {
                var messages = message.MessageString.Split('\u0013');
                foreach (var msg in messages)
                {
                    if (String.IsNullOrWhiteSpace(msg) || String.IsNullOrWhiteSpace(msg.Replace("\0", "")))
                    {
                        continue;
                    }
                    dynamic m = JsonConvert.DeserializeObject(msg);
                    string  t = m.JType?.ToString();
                    if (t != null)
                    {
                        Node node;
                        switch (t)
                        {
                        case "ClientRegistrationInfo":
                            var cri = JsonConvert.DeserializeObject <ClientRegistrationInfo>(msg);
                            //validate the client
                            if (cri.Secret == Settings.TcpSecret)
                            {
                                //we can register
                                var n = new Node {
                                    ClientId = cri.ClientId, TcpClient = message.TcpClient
                                };
                                Bot.Nodes.Add(n);
                                Bot.NodeConnected(n);
                                //n.Broadcast("Registered");
                                Program.Log($"Client registered: {cri.ClientId}");
                            }
                            break;

                        case "NodeInfo":
                            var ni = JsonConvert.DeserializeObject <NodeInfo>(msg);
                            node = Bot.Nodes.FirstOrDefault(x => x.ClientId == ni.ClientId);
                            if (node == null)
                            {
                                node = new Node {
                                    ClientId = ni.ClientId, TcpClient = message.TcpClient
                                };
                                Bot.Nodes.Add(node);
                                Bot.NodeConnected(node);
                            }
                            node.CurrentGames          = ni.CurrentGames;
                            node.CurrentPlayers        = ni.CurrentPlayers;
                            node.DuplicateGamesRemoved = ni.DuplicateGamesRemoved;
                            node.ThreadCount           = ni.ThreadCount;
                            node.TotalGames            = ni.TotalGames;
                            node.TotalPlayers          = ni.TotalPlayers;
                            node.Uptime       = ni.Uptime;
                            node.Games        = ni.Games;
                            node.Version      = ni.Version;
                            node.ShuttingDown = ni.ShuttingDown;
                            if (ni.Version.Contains("5984.20648"))
                            {
                                node.ShuttingDown = true;
                            }
                            break;

                        case "GameEndInfo":
                            var gei = JsonConvert.DeserializeObject <GameEndInfo>(msg);
                            node = Bot.Nodes.FirstOrDefault(x => x.ClientId == gei.ClientId);
                            node?.EndGame(gei);
                            break;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Program.Log($"Error in message received: {e.Message}\n{message.MessageString}", true);
            }
        }