/// <summary> /// init the static instance of the DiscordHandler /// </summary> public static async void Initialize() { if (DiscordHandler.Instance == null) { Instance = new DiscordHandler(); // setup the client bool installKeyPresent = false; string ik; ik = MednaNetSettings.GetInstallKey(); if (ik != null && ik.Trim() != "") { installKeyPresent = true; Instance.InstallKey = ik; } // Instantiate client if (installKeyPresent == true) { Instance.Client = new Client(Instance.EndPointAddress, Instance.EndPointPort, ik); } else { Instance.Client = new Client(Instance.EndPointAddress, Instance.EndPointPort); } // get the current install object from the API if (installKeyPresent == true) { try { Instance.CurrentInstall = await Instance.Client.Install.GetCurrentInstall(Instance.InstallKey); } catch (Exception ex) { Instance.APIDisconnected(ex); return; } } if (installKeyPresent == false) { try { Instance.CurrentInstall = await Instance.Client.Install.GetCurrentInstall(""); } catch (Exception ex) { Instance.APIDisconnected(ex); return; } Instance.InstallKey = Instance.CurrentInstall.code; MednaNetSettings.SetInstallKey(Instance.InstallKey); } Instance.IsConnected = true; } Instance.HistoryInMinutes = MednaNetSettings.GetChatHistoryInMinutes(); Timer.Interval = new TimeSpan(0, 0, Instance.TimerIntervalInSeconds); DiscordHandler.Timer.Start(); Instance.IsConnected = true; }
/* * public void SaveToLoggingDatabase(List<Messages> messages) * { * var lookup = db.DiscordMessages.GetAllMessages(); * * using (var db = new MednaLogDbContext()) * { * List<DiscordMessages> mes = new List<DiscordMessages>(); * * foreach (var m in messages) * { * DiscordMessages me = new DiscordMessages(); * me.APITimeReceived = m.postedOn; * me.ChannelId = m.channel; * me.LocalTimeReceived = DateTime.Now; * me.MessageId = m.id; * me.MessageString = m.message; * me.NickName = m.user.username; * me.UserId = m.user.id; * if (m.user.discordId == null || m.user.discordId == "") * me.IsAPIUser = true; * else * me.IsAPIUser = false; * * mes.Add(me); * } * * List<DiscordMessages> toAdd = new List<DiscordMessages>(); * List<DiscordMessages> toUpdate = new List<DiscordMessages>(); * * foreach (var v in mes) * { * var l = (from a in lookup * where a.MessageId == v.MessageId * select a).ToList().FirstOrDefault(); * * if (l == null) * toAdd.Add(v); * else * toUpdate.Add(v); * } * * db.DiscordMessages.AddRange(toAdd); * db.DiscordMessages.UpdateRange(toUpdate); * db.SaveChanges(); * } * } * * * public List<Messages> GetFromDatabase(int daysHistory) * { * var data = DiscordMessages.GetAllMessages().Where(a => a.APITimeReceived > DateTime.Now.AddDays(-daysHistory)); * } * */ /// <summary> /// checks whether the local Username differs from the CurrentInstall username (i.e., has been changed) /// if so, asyncronously send username change over the API /// on await return the username in the MedLaunch.db is updated /// </summary> private async void ChangeUsernameAsync() { // if the specified local username differs from API, set it if (Username != CurrentInstall.username) { CurrentInstall.username = Username; try { await Client.Install.UpdateUsername(CurrentInstall); } catch (Exception ex) { APIDisconnected(ex); return; } MednaNetSettings.SetUsername(Username); } }
/// <summary> /// default contructor /// </summary> public DiscordVisualHandler() { mw = Application.Current.Windows.OfType <MainWindow>().FirstOrDefault(); APIConnected = false; // get misc controls tbDiscordName = (TextBox)mw.FindName("tbDiscordName"); btnDiscordConnect = (Button)mw.FindName("btnDiscordConnect"); scrlDiscordChannels = (ScrollViewer)mw.FindName("scrlDiscordChannels"); scrlDiscordUsers = (ScrollViewer)mw.FindName("scrlDiscordUsers"); tbDiscordMessageBox = (TextBox)mw.FindName("tbDiscordMessageBox"); btnDiscordChatSend = (Button)mw.FindName("btnDiscordChatSend"); DiscordSelectorWrapPanel = (StackPanel)mw.FindName("DiscordSelectorWrapPanel"); DiscordUserListWrapPanel = (StackPanel)mw.FindName("DiscordUserListWrapPanel"); expDiscordUsersOnline = (Expander)mw.FindName("expDiscordUsersOnline"); // chat text window rtbDocument = (RichTextBox)mw.FindName("rtbDocument"); // set username from database tbDiscordName.Text = MednaNetSettings.GetUsername(); // get channel radios // get user buttons // get labels lblConnectedStatus = (Label)mw.FindName("lblConnectedStatus"); // set connected status SetConnectedStatus(false); // initialise channels object (empty) channels = new DiscordChannels(); // init user object (empty) users = new DiscordUsers(); // initialise richtextbox paragraph = new Paragraph(); rtbDocument.Document = new FlowDocument(paragraph); rtbDocument.IsDocumentEnabled = true; initialParagraph = paragraph; UpdateChannelButtons(); UpdateUsers(); }
private async void LoadClient() { bool installKeyPresent = false; string ik; ik = MednaNetSettings.GetInstallKey(); if (ik != null && ik.Trim() != "") { installKeyPresent = true; InstallKey = ik; } // Instantiate client if (installKeyPresent == true) { Client = new Client(EndPointAddress, EndPointPort, ik); } else { Client = new Client(EndPointAddress, EndPointPort); } // get the current install object from the API if (installKeyPresent == true) { try { CurrentInstall = await Client.Install.GetCurrentInstall(InstallKey); } catch (Exception ex) { APIDisconnected(ex); return; } } if (installKeyPresent == false) { try { CurrentInstall = await Client.Install.GetCurrentInstall(""); } catch (Exception ex) { APIDisconnected(ex); return; } InstallKey = CurrentInstall.code; MednaNetSettings.SetInstallKey(InstallKey); } isConnected = true; DoPoll(); // start the timer Timer.Start(); }
/// <summary> /// constructor /// </summary> public DiscordHandler() { // get username from database Username = Models.MednaNetSettings.GetUsername(); // api endpoint information EndPointAddress = "mednanet.medlaunch.info"; EndPointPort = "443"; // get mainwindow instance MW = Application.Current.Windows.OfType <MainWindow>().FirstOrDefault(); if (Username == null || Username.Trim() == "") { Username = MW.tbDiscordName.Text; } // get visual handler reference DVH = MW.DVH; Channels = new List <MednaNetAPIClient.Models.Channels>(); Users = new List <MednaNetAPIClient.Models.Users>(); MessageList = new List <DiscordMessages>(); LastChannelMessages = new Dictionary <int, int>(); // setup polling bools UsersIsPolling = false; ChannelsIsPolling = false; MessagesIsPolling = false; MessageDBSync = false; IsConnected = false; // setup the timer TimerIntervalInSeconds = MednaNetSettings.GetPollTimerInterval(); Timer.Tick += new EventHandler(Timer_Tick); //Timer.Interval = new TimeSpan(0, 0, 5); }
public static void InitialSeed() { // check whether initial seed needs to continue bool doSeed = false; using (var db = new MyDbContext()) { var se = db.GlobalSettings.FirstOrDefault(); if (se == null || se.databaseGenerated == false) { doSeed = true; } } if (doSeed == true) { // populate Versions table Versions version = Versions.GetVersionDefaults(); using (var context = new MyDbContext()) { context.Versions.Add(version); context.SaveChanges(); } // default netplay settings ConfigNetplaySettings npSettings = ConfigNetplaySettings.GetNetplayDefaults(); using (var context = new MyDbContext()) { context.ConfigNetplaySettings.Add(npSettings); context.SaveChanges(); } // default ConfigBaseSettings population ConfigBaseSettings cfbs = ConfigBaseSettings.GetConfigDefaults(); cfbs.ConfigId = 2000000000; // base configuration using (var context = new MyDbContext()) { context.ConfigBaseSettings.Add(cfbs); context.SaveChanges(); } // create system specific configs (set to disabled by default) List <GSystem> gamesystems = GSystem.GetSystems(); using (var gsContext = new MyDbContext()) { // iterate through each system and create a default config for them - setting them to disabled, setting their ID to 2000000000 + SystemID // and setting their systemident to systemid foreach (GSystem System in gamesystems) { int def = 2000000000; ConfigBaseSettings c = ConfigBaseSettings.GetConfigDefaults(); c.ConfigId = def + System.systemId; c.systemIdent = System.systemId; c.isEnabled = false; // add to databsae gsContext.ConfigBaseSettings.Add(c); gsContext.SaveChanges(); } } // Populate Servers List <ConfigServerSettings> servers = ConfigServerSettings.GetServerDefaults(); using (var context = new MyDbContext()) { context.ConfigServerSettings.AddRange(servers); context.SaveChanges(); } // Create General Settings Entry GlobalSettings gs = GlobalSettings.GetGlobalDefaults(); using (var context = new MyDbContext()) { context.GlobalSettings.Add(gs); context.SaveChanges(); } // create mednanet general entry MednaNetSettings ms = MednaNetSettings.GetMednaNetDefaults(); using (var context = new MyDbContext()) { context.MednaNetSettings.Add(ms); context.SaveChanges(); } // create Paths entry Paths paths = new Paths { pathId = 1 }; using (var context = new MyDbContext()) { context.Paths.Add(paths); context.SaveChanges(); } // initial seeding complete. mark GeneralSettings table so that regeneration does not occur GlobalSettings set; using (var context = new MyDbContext()) { set = (from a in context.GlobalSettings where a.settingsId == 1 select a).FirstOrDefault <GlobalSettings>(); } if (set != null) { set.databaseGenerated = true; } using (var dbCtx = new MyDbContext()) { dbCtx.Entry(set).State = EntityState.Modified; dbCtx.SaveChanges(); } } }
/// <summary> /// Save settings based on settings group /// </summary> /// <param name="settingGroup"></param> public static void SaveSettings(SettingGroup settingGroup) { MainWindow mw = Application.Current.Windows.OfType <MainWindow>().FirstOrDefault(); switch (settingGroup) { case SettingGroup.BiosPaths: ConfigBaseSettings.SaveBiosPaths(); break; case SettingGroup.GamePaths: TextBox tbPathMednafen = (TextBox)mw.FindName("tbPathMednafen"); TextBox tbPathGb = (TextBox)mw.FindName("tbPathGb"); TextBox tbPathGba = (TextBox)mw.FindName("tbPathGba"); TextBox tbPathGg = (TextBox)mw.FindName("tbPathGg"); TextBox tbPathLynx = (TextBox)mw.FindName("tbPathLynx"); TextBox tbPathMd = (TextBox)mw.FindName("tbPathMd"); TextBox tbPathNes = (TextBox)mw.FindName("tbPathNes"); TextBox tbPathSnes = (TextBox)mw.FindName("tbPathSnes"); TextBox tbPathNgp = (TextBox)mw.FindName("tbPathNgp"); TextBox tbPathPce = (TextBox)mw.FindName("tbPathPce"); TextBox tbPathPcfx = (TextBox)mw.FindName("tbPathPcfx"); TextBox tbPathPsx = (TextBox)mw.FindName("tbPathPsx"); TextBox tbPathSs = (TextBox)mw.FindName("tbPathSs"); TextBox tbPathSms = (TextBox)mw.FindName("tbPathSms"); TextBox tbPathVb = (TextBox)mw.FindName("tbPathVb"); TextBox tbPathWswan = (TextBox)mw.FindName("tbPathWswan"); TextBox tbPathPceCd = (TextBox)mw.FindName("tbPathPceCd"); Paths.SavePathSettings(tbPathMednafen, tbPathGb, tbPathGba, tbPathGg, tbPathLynx, tbPathMd, tbPathNes, tbPathSnes, tbPathNgp, tbPathPce, tbPathPcfx, tbPathSms, tbPathVb, tbPathWswan, tbPathPsx, tbPathSs, tbPathPceCd); break; case SettingGroup.GlobalSettings: GlobalSettings gs = GlobalSettings.GetGlobals(); Slider slFanrtsPerHost = (Slider)mw.FindName("slFanrtsPerHost"); Slider slScreenshotsPerHost = (Slider)mw.FindName("slScreenshotsPerHost"); ComboBox comboImageTooltipSize = (ComboBox)mw.FindName("comboImageTooltipSize"); ComboBox cbFormatGameTitles = (ComboBox)mw.FindName("cbFormatGameTitles"); gs.maxFanarts = slFanrtsPerHost.Value; gs.maxScreenshots = slScreenshotsPerHost.Value; gs.imageToolTipPercentage = Convert.ToDouble(comboImageTooltipSize.SelectedValue, System.Globalization.CultureInfo.InvariantCulture); gs.changeTitleCase = Convert.ToInt32(cbFormatGameTitles.SelectedValue); GlobalSettings.SetGlobals(gs); break; case SettingGroup.MednaNetSettings: MednaNetSettings ms = MednaNetSettings.GetGlobals(); Slider slDiscordChatHistory = (Slider)mw.FindName("slDiscordChatHistory"); Slider slApiPollingFrequency = (Slider)mw.FindName("slApiPollingFrequency"); ms.ChatHistoryInMinutes = Convert.ToInt32(slDiscordChatHistory.Value, System.Globalization.CultureInfo.InvariantCulture); ms.PollTimerIntervalInSeconds = Convert.ToInt32(slApiPollingFrequency.Value, System.Globalization.CultureInfo.InvariantCulture); MednaNetSettings.SetGlobals(ms); break; case SettingGroup.MednafenPaths: ConfigBaseSettings.SaveMednafenPaths(); break; case SettingGroup.NetplaySettings: TextBox tbNetplayNick = (TextBox)mw.FindName("tbNetplayNick"); Slider slLocalPlayersValue = (Slider)mw.FindName("slLocalPlayersValue"); Slider slConsoleLinesValue = (Slider)mw.FindName("slConsoleLinesValue"); Slider slConsoleScaleValue = (Slider)mw.FindName("slConsoleScaleValue"); RadioButton resOne = (RadioButton)mw.FindName("resOne"); RadioButton resTwo = (RadioButton)mw.FindName("resTwo"); RadioButton resThree = (RadioButton)mw.FindName("resThree"); RadioButton resFour = (RadioButton)mw.FindName("resFour"); RadioButton resFive = (RadioButton)mw.FindName("resFive"); ConfigNetplaySettings.SaveNetplaySettings(tbNetplayNick, slLocalPlayersValue, slConsoleLinesValue, slConsoleScaleValue, resOne, resTwo, resThree, resFour, resFive); break; case SettingGroup.ServerSettings: TextBox tbServerDesc = (TextBox)mw.FindName("tbServerDesc"); TextBox tbHostname = (TextBox)mw.FindName("tbHostname"); Slider slServerPort = (Slider)mw.FindName("slServerPort"); TextBox tbPassword = (TextBox)mw.FindName("tbPassword"); TextBox tbGameKey = (TextBox)mw.FindName("tbGameKey"); ConfigServerSettings.SaveCustomServerSettings(tbServerDesc, tbHostname, slServerPort, tbPassword, tbGameKey); break; default: break; } }
public async void DoPoll() { AbortThread = true; isPolling = true; Timer.Stop(); if (isConnected == false) { return; } /* Set Username */ // if the specified local username differs from API, set it if (Username != CurrentInstall.username) { CurrentInstall.username = Username; try { await Client.Install.UpdateUsername(CurrentInstall); } catch (Exception ex) { APIDisconnected(ex); return; } MednaNetSettings.SetUsername(Username); } /* Update Channels */ try { Channels = await Client.Channels.GetChannels(); } catch (Exception ex) { APIDisconnected(ex); return; } // update channel list foreach (var c in Channels.OrderBy(a => a.discordId)) { DVH.channels.UpdateChannel(c.id, c.channelName); } // Update the UI DVH.UpdateChannelButtons(); // make sure at least one channel is selected DVH.CheckChannelSelection(); /* Update Users */ // query API try { Users = await Client.Users.GetAllUsers(); } catch (Exception ex) { APIDisconnected(ex); return; } // update user list foreach (var u in Users) { if (u.discordId == null) // && u.isOnline == false) { //continue; } ClientType ct = ClientType.discord; if (u.discordId == null) { ct = ClientType.medlaunch; } DVH.users.UpdateUser(u.id, u.username, ct, true); } // Update the UI DVH.UpdateUsers(); /* Update messages */ List <Messages> foundMessages = new List <Messages>(); // loop through each channel foreach (var c in Channels) { // get the last received message from this channel //var lookup = DiscordMessages.GetLastMessageId(c.id); int lookup = 0; var lookupA = AllMessages.Where(a => a.channel == c.id).OrderBy(b => b.id).LastOrDefault(); if (lookupA != null) { lookup = lookupA.id; } if (lookup == 0) { // no message found - get all messages using the timeframe specified try { foundMessages.AddRange((await Client.Channels.GetChannelMessagesFrom(c.id, DateTime.Now.AddMinutes(MessageHistoryInMinutes))).ToList()); } catch (Exception ex) { APIDisconnected(ex); return; } } else { // result found - get messages from the API after this message ID try { foundMessages.AddRange((await Client.Channels.GetChannelMessagesAfterMessageId(c.id, lookup)).ToList()); } catch (Exception ex) { APIDisconnected(ex); return; } } // get the last messageId for this channel already posted to the screen int lastWritten = 0; if (LastChannelMessages.ContainsKey(c.id)) { lastWritten = LastChannelMessages[c.id]; } // get the last messageId received on this channel int lastId = lookup; //var look2 = DiscordMessages.GetLastMessageId(c.id); int look2 = 0; var look2a = AllMessages.Where(a => a.channel == c.id).OrderBy(b => b.id).LastOrDefault(); if (look2a != null) { look2 = look2a.id; } if (look2 > lookup) { lastId = look2; } // update the dictionary LastChannelMessages[c.id] = lastId; } // add foundMessages to the database //DiscordMessages.SaveToDatabase(foundMessages); // add foundMessages to AllMessages AllMessages.AddRange(foundMessages); AllMessages.Distinct(); // now post new messages based on the currently selected channel foreach (var c in Channels) { int last = LastChannelMessages[c.id]; //var newMessages = DiscordMessages.GetAllMessages().Where(a => a.MessageId > last).OrderBy(b => b.MessageId).ToList(); var newMessages = AllMessages.Where(a => a.id > last).OrderBy(b => b.id).ToList().OrderBy(d => d.id).ToList(); foreach (var me in newMessages) { // create discordmessage format DiscordMessage d = new DiscordMessage(); d.channel = me.channel; d.code = me.code; d.message = me.message; d.messageId = me.id; //d.name = me.name; d.postedOn = me.postedOn; // write the message to the relevant local channel MednaNetAPI.Instance.DVH.PostMessage(d); //DVH.PostMessage(me, c.id); } } AbortThread = false; isPolling = false; Timer.Start(); /* * foreach (var c in Channels) * { * // get last message ID recorded for this channel * var lookup = MessageLog.GetLastChannelMessage(c.id); * * if (lookup == null) * { * // no messages found locally for this channel, get all messages from the last day * try * { * var messages = await Client.Channels.GetChannelMessagesFrom(c.id, DateTime.Now.AddMinutes(-600)); * * // add to new messages * foreach (var m in messages.OrderBy(a => a.id)) * { * if (m.channel == 1) * { * * } * * // check that is isnt one that we have posted ourself * var allZeros = from a in MednaNetAPI.Instance.MessageArchive * where a.APIMessage.channel == c.id && a.APIMessage.id == 0 && a.APIMessage.message == m.message && a.HasBeenParsed == true * select a; * * if (allZeros.Count() > 0) * { * // message found, do nothing * } * else * { * MessageLog.AddMessage(m); * } * } * } * catch (Exception ex) { APIDisconnected(ex); return; } * * * } * else * { * // query the API for newer messages * try * { * var messages = await Client.Channels.GetChannelMessagesAfterMessageId(c.id, lookup.id); * // add to new messages * foreach (var m in messages) * { * MessageLog.AddMessage(m); * } * } * catch (Exception ex) { APIDisconnected(ex); return; } * } * } * * // process new messages * MessageLog.PostNewMessages(); * AbortThread = false; * isPolling = false; * Timer.Start(); * */ }