示例#1
0
        static void Main(string[] args)
        {
            LoggingHelper.ConfigureLogger();
            if (ConfigManager.GetSetting("FirstRun") == "true")
            {
                FirstTimeInit();
                ConfigManager.UpdateSetting("FirstRun", "false");
            }

            string credentials = ConfigManager.GetSetting("CredentialsPath");

            if (!File.Exists(credentials))
            {
                Logger.Fatal($"No credentials exists at: \"{credentials}\". Cannot proceed");
                InputManager.GetStringInput("Press Enter to exit");
                Environment.Exit(1);
            }

            Logger.Info("Initializing Google Drive API");
            GoogleDriveHandler googleDriveHandler =
                new GoogleDriveHandler(credentials, ConfigManager.GetSetting("TokenPath"));

            Logger.Info("Google Drive Initialized");

            SyncHandler syncHandler = new SyncHandler(googleDriveHandler);

            syncHandler.SyncLoop();
        }
示例#2
0
        public SyncHandler(GoogleDriveHandler googleDriveHandler)
        {
            this.m_googleDriveHandler = googleDriveHandler;
            this.InitGoogleDrive();

            this.InitSaveFiles();

            this.InitialSync();

            this.RegisterSaveFileChangeHandlers();

            this.RegisterGoogleDriveProgressChangeHandlers();
        }
        public static async Task <bool> StartEntryWeek(DiscordSocketClient client, double?days2end = null, bool?force = null, [Remainder] string theme = "")
        {
            SocketTextChannel channel = Utils.FindChannel(client, Storage.xs.Settings.GetWorkingChannel());

            if (channel == null)
            {
                return(false);
            }

            Storage.xs.History.RecordTrade(Storage.xs.Entries);
            await GoogleDriveHandler.UploadGoogleFile(Storage.xs.HISTORY_PATH);

            Storage.xs.ClearStorage(Storage.xs.Entries);
            Storage.xs.Settings.ActivateTrade(Storage.ApplicationSettings.TradeSegment.EntryWeek, null /*days2start*/, days2end, force, null /*bGDriveOn*/, true /*bResetPoll*/);
            Storage.xs.Entries.SetTheme(theme);

            string outMessage = $"{string.Format(Properties.Resources.ENTRY_WEEK, Config.CmdPrefix, "set entry", "about")}"
                                + (string.IsNullOrWhiteSpace(Storage.xs.Entries.GetTheme()) ? "" : $"\n{string.Format(Properties.Resources.TRADE_THIS_THEME, Storage.xs.Entries.GetTheme())}");

            await channel.SendMessageAsync(embed : Utils.EmbedMessage(client, outMessage, Utils.Emotion.positive));

            await Utils.CreateOrEditNaughtyList(client, Storage.xs.Settings.GetWorkingChannel());

            var subscribers = new List <ulong>(Storage.xs.Settings.GetSubscribers());

            // notify those that did not send their art on time
            var artHistory0 = Utils.GetAppDataFromHistory(0);

            foreach (Storage.UserData user in Utils.GetMissingArt(artHistory0))
            {
                subscribers.Remove(user.UserId); // don't notify subscribers twice

                SocketUser su = client.GetUser(user.UserId);
                if (su != null)
                {
                    await su.SendMessageAsync(embed : Utils.EmbedMessage(client, string.Format(Properties.Resources.TRADE_ART_LATE_DM, user.UserId, artHistory0.GetTheme())
                                                                         + $"\n{string.Format(Properties.Resources.GLOBAL_CMDHELP, Config.CmdPrefix, $"reveal art {artHistory0.GetTheme()}", "register the missing art")}", Utils.Emotion.negative));
                }
            }

            // notify those that subscribed for notifications
            if (string.IsNullOrWhiteSpace(Storage.xs.Entries.GetTheme()) && !await Utils.CreateThemePoll(client))
            {
                await Utils.NotifySubscribers(client, "the `entry week` started, please visit teanicorn art trade channel for more information", subscribers);
            }

            return(true);
        }
        public async Task Backup([Summary("string mode empty = checkpoint, json = send json files in DM, sync = sync to gDrive")] string mode = "")
        {
            var user = Context.Message.Author;

            if (!Utils.IsAdminUser(user))
            {
                await ReplyAsync(embed : Utils.EmbedMessage(Context.Client, string.Format(Properties.Resources.GLOBAL_ERROR, user.Id, "admin only command"), Utils.Emotion.neutral));

                return;
            }

            mode = mode.ToLower().Trim();
            if (mode.Equals("json"))
            {
                await user.SendFileAsync(Storage.xs.ENTRIES_PATH);

                await user.SendFileAsync(Storage.xs.HISTORY_PATH);

                await user.SendFileAsync(Storage.xs.SETTINGS_PATH);
                await ReplyAsync(embed : Utils.EmbedMessage(Context.Client, string.Format(Properties.Resources.GLOBAL_SUCCESS, user.Id, "all storages have been dumped"), Utils.Emotion.positive));
            }
            else if (mode.Equals("sync"))
            {
                if (!await GoogleDriveHandler.UploadGoogleFile(Storage.xs.ENTRIES_PATH))
                {
                    await ReplyAsync(embed : Utils.EmbedMessage(Context.Client, string.Format(Properties.Resources.GLOBAL_ERROR, user.Id, "unable to sent data to cloud"), Utils.Emotion.neutral));

                    return;
                }

                if (!await GoogleDriveHandler.UploadGoogleFile(Storage.xs.HISTORY_PATH))
                {
                    await ReplyAsync(embed : Utils.EmbedMessage(Context.Client, string.Format(Properties.Resources.GLOBAL_ERROR, user.Id, "unable to sent data to cloud"), Utils.Emotion.neutral));

                    return;
                }

                if (!await GoogleDriveHandler.UploadGoogleFile(Storage.xs.SETTINGS_PATH))
                {
                    await ReplyAsync(embed : Utils.EmbedMessage(Context.Client, string.Format(Properties.Resources.GLOBAL_ERROR, user.Id, "unable to sent data to cloud"), Utils.Emotion.neutral));

                    return;
                }

                await ReplyAsync(embed : Utils.EmbedMessage(Context.Client, string.Format(Properties.Resources.GLOBAL_SUCCESS, user.Id, "all storages have been synced with cloud"), Utils.Emotion.positive));
            }
            else if (mode.Equals("save"))
            {
                Storage.xs.Entries.Save();
                Storage.xs.Settings.Save();
                Storage.xs.History.Save();
                await ReplyAsync(embed : Utils.EmbedMessage(Context.Client, string.Format(Properties.Resources.GLOBAL_SUCCESS, user.Id, "all storages have been saved to disk"), Utils.Emotion.positive));
            }
            else
            {
                Storage.xs.BackupStorage(Storage.xs.Entries);
                Storage.xs.BackupStorage(Storage.xs.Settings);
                Storage.xs.BackupStorage(Storage.xs.History);
                await ReplyAsync(embed : Utils.EmbedMessage(Context.Client, string.Format(Properties.Resources.GLOBAL_SUCCESS, user.Id, "all storages have been backed up on disk"), Utils.Emotion.positive));
            }
        }
示例#5
0
        public void TerminalCommand(String command)
        {
            Console.WriteLine(command);
            try
            {
                command = command.ToLower();
                if (String.IsNullOrEmpty(command) || String.IsNullOrWhiteSpace(command))
                {
                    Console.WriteLine("That's not a valid command... Type \'help\' if you don\'t know what command to use.");
                    return;
                }
                String[] commands = command.Split(' ');
                String   head     = commands[0];



                if (head == "neuralnetwork")
                {
                    Model network = NeuralNetworkHandler.network;
                    if (commands.Length == 1)
                    {
                        if (network == null)
                        {
                            Console.WriteLine("There is no Network currently loaded.");
                        }
                        else
                        {
                            String message =
                                "Current loaded network:\n" +
                                "\tName:\t" + network.Name + "\n" +
                                "\tType:\t" + network.Type;
                            Console.WriteLine(message);
                        }
                    }
                    else if (commands[1] == "create")
                    {
                        if (network == null)
                        {
                            List <LayerBase> layers = new List <LayerBase>();

                            for (int i = 4; i < commands.Length; i += 2)
                            {
                                LayerBase l = null;
                                if (commands[i] == "input")
                                {
                                    l = new InputLayer();
                                }
                                else if (commands[i] == "lrelu")
                                {
                                    l = new LeakyReluLayer();
                                }
                                else if (commands[i] == "sigmoid")
                                {
                                    l = new SigmoidLayer();
                                }
                                else
                                {
                                    Console.Error.WriteLine(String.Format("Layer type {0} does not exist.", commands[i]));
                                    return;
                                }
                                l.nodes = int.Parse(commands[i + 1]);
                                layers.Add(l);
                            }
                            NeuralNetworkHandler.CreateNetwork(layers.ToArray(), commands[2], commands[3]);
                            Console.WriteLine("Neural Network successfully created.");
                            return;
                        }
                    }
                    else if (commands[1] == "load")
                    {
                        Console.WriteLine(NeuralNetworkHandler.LoadNetwork(commands[2]));
                    }
                    else if (commands[1] == "save")
                    {
                        if (commands.Length == 2)
                        {
                            Console.WriteLine(NeuralNetworkHandler.SaveNetwork());
                        }
                        else
                        {
                            Console.WriteLine(NeuralNetworkHandler.SaveNetwork(commands[2]));
                        }
                    }
                    else if (commands[1] == "randomize")
                    {
                        Console.WriteLine(NeuralNetworkHandler.RandomizeNetwork());
                    }
                    else if (commands[1] == "train")
                    {
                        if (network == null)
                        {
                            Console.Error.WriteLine("No network loaded.");
                            return;
                        }
                        if (NeuralNetworkHandler.keeper == null)
                        {
                            Console.Error.WriteLine("No dataset loaded.");
                            return;
                        }

                        int epochs = 1;
                        if (commands.Length != 2)
                        {
                            epochs = int.Parse(commands[2]);
                        }
                        NeuralNetworkHandler.train = new Thread(() => NeuralNetworkHandler.TrainNetwork(epochs));
                        NeuralNetworkHandler.train.IsBackground = true;
                        NeuralNetworkHandler.train.Name         = "Training Thread";


                        NeuralNetworkHandler.train.Start();
                    }
                    else if (commands[1] == "learningrate")
                    {
                        if (commands.Length == 2)
                        {
                            Console.WriteLine("Learning rate: " + Model.LearningRate);
                        }
                        else
                        {
                            Model.LearningRate = float.Parse(commands[2]);
                        }
                    }
                }
                else if (head == "test")
                {
                    Data[] data = new Data[3600];

                    float x = 0;

                    for (int i = 0; i < data.Length; i++)
                    {
                        data[i]        = new Data();
                        data[i].Inputs = new Matrix(1, 1)
                        {
                            data = new float[, ] {
                                { (1f / 360f) * x }
                            }
                        };
                        data[i].Targets = new Matrix(1, 1)
                        {
                            data = new float[, ] {
                                { (float)Math.Sin(x * (Math.PI / 180)) }
                            }
                        };
                        x += 0.1f;
                    }

                    NeuralNetworkHandler.keeper         = new DataKeeper();
                    NeuralNetworkHandler.keeper.DataSet = data;
                    NeuralNetworkHandler.keeper.Name    = "sinusfunction";
                }
                else if (head == "dataset")
                {
                    if (commands.Length == 1)
                    {
                        if (NeuralNetworkHandler.keeper == null)
                        {
                            Console.WriteLine("There is no dataset loaded yet.");
                        }
                        else
                        {
                            Console.WriteLine(String.Format("The dataset with the name {0} is currently loaded.", NeuralNetworkHandler.keeper.Name));
                        }
                    }
                    else if (commands[1] == "load")
                    {
                        Console.WriteLine(DataKeeper.LoadDataSet(commands[2]));
                    }
                    else if (commands[1] == "save")
                    {
                        if (commands.Length == 2)
                        {
                            Console.WriteLine(DataKeeper.SaveDataSet());
                        }
                        else
                        {
                            Console.WriteLine(DataKeeper.SaveDataSet(commands[2]));
                        }
                    }
                    else if (commands[1] == "unload")
                    {
                        NeuralNetworkHandler.keeper = null;
                    }
                    else if (commands[1] == "view")
                    {
                        if (NeuralNetworkHandler.keeper == null)
                        {
                            Console.Error.WriteLine("No dataset loaded.");
                            return;
                        }
                        for (int i = 0; i < NeuralNetworkHandler.keeper.DataSet.Length; i++)
                        {
                            Console.WriteLine("Data " + i + ":");
                            Console.WriteLine("Inputs:");
                            Console.WriteLine(NeuralNetworkHandler.keeper.DataSet[i].getInputString());
                            Console.WriteLine("Targets:");
                            Console.WriteLine(NeuralNetworkHandler.keeper.DataSet[i].getTargetsString());
                            Console.WriteLine("");
                        }
                    }
                }
                else if (head == "googledrive")
                {
                    if (commands[1] == "login")
                    {
                        GoogleDriveHandler.GoogleDriveLogin(HttpRuntime.AppDomainAppPath + "/credentials.json");
                        Console.WriteLine("Successfully logged in on Google Drive.");
                    }
                    else if (commands[1] == "logout")
                    {
                        GoogleDriveHandler.GoogleDriveLogout("credentials.json");
                        Console.WriteLine("Successfully logged out from Google Drive.");
                    }
                    else if (commands[1] == "list")
                    {
                        IList <Google.Apis.Drive.v3.Data.File> list = GoogleDriveHandler.GetFileList();

                        foreach (var file in list)
                        {
                            Console.WriteLine(String.Format("{0} ({1})", file.Name, file.Id));
                        }
                    }
                }
                else
                {
                    Console.Error.WriteLine("That's not a valid command... Type \'help\' if you don\'t know what command to use.");
                }
            } catch (Exception e)
            {
                Console.Error.WriteLine("Command resolved in an error.");
                Console.Error.WriteLine(e.Message);
                Console.Error.WriteLine(e.StackTrace);
            }
        }
        public async Task RevealArt([Remainder][Summary("theme of the art trade for which you want to register your art (`optional`)")] string theme = null)
        {
            var user = Context.Message.Author;

            Storage.ApplicationData foundTrade = null;

            if (!string.IsNullOrWhiteSpace(theme))
            {
                theme = theme.ToLower();

                for (int i = 0; i < Storage.xs.History.Count() && i < 3; ++i)
                {
                    var d = Storage.xs.History.GetTrade(i);
                    if (d == null)
                    {
                        continue;
                    }
                    if (string.IsNullOrWhiteSpace(d.GetTheme()))
                    {
                        continue;
                    }
                    if (!theme.Contains(d.GetTheme().ToLower().Trim()))
                    {
                        continue;
                    }

                    foundTrade = d;
                    break;
                }
            }

            if (foundTrade == null)
            {
                foundTrade = Storage.xs.Entries;
            }

            bool bCurrentTrade = foundTrade == Storage.xs.Entries;

            if (bCurrentTrade && !Storage.xs.Settings.IsTradeMonthActive())
            {
                await ReplyAsync(embed : Utils.EmbedMessage(Context.Client, string.Format(Properties.Resources.GLOBAL_ERROR, user.Id, "entry week in progress, partners haven't been assigned yet"), Utils.Emotion.neutral));

                return;
            }

            bool bPostponeReveal = false;

            if (bCurrentTrade && !Storage.xs.Settings.HasNotifyFlag(Storage.ApplicationSettings.NofifyFlags.Closing))
            {
                string outputMsg = await Utils.CleanupWrongChannelMessage(Context, "please wait for the trade to end or submit your art in a direct message");

                if (string.IsNullOrWhiteSpace(outputMsg))
                {
                    bPostponeReveal = true;
                }
                else
                {
                    await ReplyAsync(embed : Utils.EmbedMessage(Context.Client, string.Format(Properties.Resources.GLOBAL_ERROR, user.Id, outputMsg), Utils.Emotion.neutral));

                    return;
                }
            }

            var attachments = Context.Message.Attachments;

            if (attachments.Count <= 0)
            {
                await ReplyAsync(embed : Utils.EmbedMessage(Context.Client, string.Format(Properties.Resources.GLOBAL_MISSING_INPUT, user.Id, "embeded image"), Utils.Emotion.neutral));

                return;
            }

            var data = foundTrade.Get(user.Id);

            if (data == null)
            {
                await ReplyAsync(embed : Utils.EmbedMessage(Context.Client, string.Format(Properties.Resources.GLOBAL_ITEM_NOT_FOUND, user.Id, "entry"), Utils.Emotion.neutral));

                return;
            }

            Storage.UserData nextUserData;
            if (foundTrade.Next(user.Id, out nextUserData))
            {
                data.ArtUrl = attachments.FirstOrDefault().Url;
                foundTrade.Set(data);

                if (!bCurrentTrade)
                {
                    await GoogleDriveHandler.UploadGoogleFile(Storage.xs.HISTORY_PATH);
                }

                var client   = Context.Client;
                var nextUser = client.GetUser(nextUserData.UserId);
                if (nextUser == null)
                {
                    await ReplyAsync(embed : Utils.EmbedMessage(Context.Client, string.Format(Properties.Resources.GLOBAL_ERROR, user.Id, "could not find your partner"), Utils.Emotion.neutral));

                    return;
                }

                if (bPostponeReveal)
                {
                    await ReplyAsync(embed : Utils.EmbedMessage(Context.Client, string.Format(Properties.Resources.GLOBAL_WARNING, user.Id, "your art has been saved, but it won't be revealed to your partner until the trade ends"), Utils.Emotion.neutral));
                }
                else
                {
                    string monthTheme = Storage.xs.Entries.GetTheme();
                    if (!bCurrentTrade)
                    {
                        monthTheme = foundTrade.GetTheme();
                        await Utils.CreateOrEditNaughtyList(Context.Client, Storage.xs.Settings.GetWorkingChannel(), user);
                    }

                    if (await SendPartnerArtResponse(Context.Client, data, nextUser, monthTheme))
                    {
                        await ReplyAsync(embed : Utils.EmbedMessage(Context.Client, string.Format(Properties.Resources.REF_REVEAL_NOTIFY, user.Id, nextUser.Id), Utils.Emotion.positive));
                    }
                    else
                    {
                        await ReplyAsync(embed : Utils.EmbedMessage(Context.Client, string.Format(Properties.Resources.GLOBAL_ERROR, user.Id, "could not notify your partner"), Utils.Emotion.neutral));
                    }
                }
            }
            else
            {
                await ReplyAsync(embed : Utils.EmbedMessage(Context.Client, string.Format(Properties.Resources.GLOBAL_ITEM_NOT_FOUND, user.Id, "partner"), Utils.Emotion.neutral));
            }
        }