public UserDataViewModel(DbDataReader dataReader, IChannelSettings settings) : this(uint.Parse(dataReader["ID"].ToString()), dataReader["UserName"].ToString()) { this.ViewingMinutes = int.Parse(dataReader["ViewingMinutes"].ToString()); Dictionary <Guid, int> currencyAmounts = JsonConvert.DeserializeObject <Dictionary <Guid, int> >(dataReader["CurrencyAmounts"].ToString()); if (currencyAmounts != null) { foreach (var kvp in currencyAmounts) { if (settings.Currencies.ContainsKey(kvp.Key)) { this.SetCurrencyAmount(settings.Currencies[kvp.Key], kvp.Value); } } } if (dataReader["CustomCommands"] != null && !string.IsNullOrEmpty(dataReader["CustomCommands"].ToString())) { this.CustomCommands.AddRange(SerializerHelper.DeserializeFromString <List <ChatCommand> >(dataReader["CustomCommands"].ToString())); } if (dataReader["Options"] != null && !string.IsNullOrEmpty(dataReader["Options"].ToString())) { JObject optionsJObj = JObject.Parse(dataReader["Options"].ToString()); if (optionsJObj["EntranceCommand"] != null) { this.EntranceCommand = SerializerHelper.DeserializeFromString <CustomCommand>(optionsJObj["EntranceCommand"].ToString()); } this.IsSparkExempt = this.GetOptionValue <bool>(optionsJObj, "IsSparkExempt"); this.IsCurrencyRankExempt = this.GetOptionValue <bool>(optionsJObj, "IsCurrencyRankExempt"); this.GameWispUserID = this.GetOptionValue <uint>(optionsJObj, "GameWispUserID"); } }
public static ApplicationSettings Load() { ApplicationSettings settings = new ApplicationSettings(); if (File.Exists(ApplicationSettingsFileName)) { using (StreamReader reader = new StreamReader(File.OpenRead(ApplicationSettingsFileName))) { settings = SerializerHelper.DeserializeFromString <ApplicationSettings>(reader.ReadToEnd()); if (settings == null) { settings = new ApplicationSettings(); } #pragma warning disable CS0612 // Type or member is obsolete if (!string.IsNullOrEmpty(settings.ThemeName)) { settings.BackgroundColor = settings.ThemeName; settings.ThemeName = null; } #pragma warning restore CS0612 // Type or member is obsolete } } return(settings); }
private static async Task Version15Upgrade(int version, string filePath) { if (version < 15) { DesktopChannelSettings settings = await SerializerHelper.DeserializeFromFile <DesktopChannelSettings>(filePath); await ChannelSession.Services.Settings.Initialize(settings); #pragma warning disable CS0612 // Type or member is obsolete EventCommand donationCommand = settings.EventCommands.FirstOrDefault(c => c.MatchesEvent(EnumHelper.GetEnumName(OtherEventTypeEnum.Donation))); #pragma warning restore CS0612 // Type or member is obsolete if (donationCommand != null) { string donationCommandJson = SerializerHelper.SerializeToString(donationCommand); EventCommand streamlabsCommand = SerializerHelper.DeserializeFromString <EventCommand>(donationCommandJson); streamlabsCommand.OtherEventType = OtherEventTypeEnum.StreamlabsDonation; settings.EventCommands.Add(streamlabsCommand); EventCommand gawkBoxCommand = SerializerHelper.DeserializeFromString <EventCommand>(donationCommandJson); gawkBoxCommand.OtherEventType = OtherEventTypeEnum.GawkBoxDonation; settings.EventCommands.Add(gawkBoxCommand); settings.EventCommands.Remove(donationCommand); } await ChannelSession.Services.Settings.Save(settings); } }
public List <ActionBase> GetActions() { if (!string.IsNullOrEmpty(this.Data)) { return(SerializerHelper.DeserializeFromString <List <ActionBase> >(this.Data)); } return(new List <ActionBase>()); }
public UserDataViewModel(DbDataReader dataReader, IChannelSettings settings) : this(uint.Parse(dataReader["ID"].ToString()), dataReader["UserName"].ToString()) { this.ViewingMinutes = int.Parse(dataReader["ViewingMinutes"].ToString()); if (dataReader.ColumnExists("CurrencyAmounts")) { Dictionary <Guid, int> currencyAmounts = JsonConvert.DeserializeObject <Dictionary <Guid, int> >(dataReader["CurrencyAmounts"].ToString()); if (currencyAmounts != null) { foreach (var kvp in currencyAmounts) { if (settings.Currencies.ContainsKey(kvp.Key)) { this.SetCurrencyAmount(settings.Currencies[kvp.Key], kvp.Value); } } } } if (dataReader.ColumnExists("InventoryAmounts")) { Dictionary <Guid, Dictionary <string, int> > inventoryAmounts = JsonConvert.DeserializeObject <Dictionary <Guid, Dictionary <string, int> > >(dataReader["InventoryAmounts"].ToString()); if (inventoryAmounts != null) { foreach (var kvp in inventoryAmounts) { if (settings.Inventories.ContainsKey(kvp.Key)) { UserInventoryViewModel inventory = settings.Inventories[kvp.Key]; this.InventoryAmounts[inventory] = new UserInventoryDataViewModel(this, inventory, kvp.Value); } } } } if (dataReader.ColumnExists("CustomCommands") && !string.IsNullOrEmpty(dataReader["CustomCommands"].ToString())) { this.CustomCommands.AddRange(SerializerHelper.DeserializeFromString <List <ChatCommand> >(dataReader["CustomCommands"].ToString())); } if (dataReader.ColumnExists("Options") && !string.IsNullOrEmpty(dataReader["Options"].ToString())) { JObject optionsJObj = JObject.Parse(dataReader["Options"].ToString()); if (optionsJObj.ContainsKey("EntranceCommand") && optionsJObj["EntranceCommand"] != null) { this.EntranceCommand = SerializerHelper.DeserializeFromString <CustomCommand>(optionsJObj["EntranceCommand"].ToString()); } this.IsSparkExempt = this.GetOptionValue <bool>(optionsJObj, "IsSparkExempt"); this.IsCurrencyRankExempt = this.GetOptionValue <bool>(optionsJObj, "IsCurrencyRankExempt"); this.GameWispUserID = this.GetOptionValue <uint>(optionsJObj, "GameWispUserID"); this.PatreonUserID = this.GetOptionValue <string>(optionsJObj, "PatreonUserID"); this.ModerationStrikes = this.GetOptionValue <uint>(optionsJObj, "ModerationStrikes"); this.CustomTitle = this.GetOptionValue <string>(optionsJObj, "CustomTitle"); } }
public override async Task Connect() { await base.Connect(); this.SocketReceiveWrapper("connect", (data) => { this.Connected = true; }); this.SocketReceiveWrapper("new-event", (data) => { if (data != null) { TipeeeStreamResponse response = SerializerHelper.DeserializeFromString <TipeeeStreamResponse>(data.ToString()); if (response.Event.Type.Equals("donation")) { this.service.DonationOccurred(response.Event); Task.Run(async() => { UserDonationModel donation = response.Event.ToGenericDonation(); await EventCommand.ProcessDonationEventCommand(donation, OtherEventTypeEnum.TipeeeStreamDonation); }); } } }); this.SocketReceiveWrapper("error", (errorData) => { MixItUp.Base.Util.Logger.Log(errorData.ToString()); this.service.WebSocketDisconnectedOccurred(); }); this.SocketReceiveWrapper("disconnect", (errorData) => { MixItUp.Base.Util.Logger.Log(errorData.ToString()); this.service.WebSocketDisconnectedOccurred(); }); JObject joinRoomJObj = new JObject(); joinRoomJObj["room"] = this.apiKey; joinRoomJObj["username"] = this.username; this.SocketSendWrapper("join-room", joinRoomJObj); for (int i = 0; i < 10 && !this.Connected; i++) { await Task.Delay(1000); } if (this.Connected) { this.service.WebSocketConnectedOccurred(); } }
public static ApplicationSettings Load() { if (File.Exists(ApplicationSettingsFileName)) { using (StreamReader reader = new StreamReader(File.OpenRead(ApplicationSettingsFileName))) { return(SerializerHelper.DeserializeFromString <ApplicationSettings>(reader.ReadToEnd())); } } return(new ApplicationSettings()); }
protected override async Task ProcessReceivedPacket(string packetJSON) { try { DiscordWebSocketPacket packet = SerializerHelper.DeserializeFromString <DiscordWebSocketPacket>(packetJSON); this.lastSequenceNumber = packet.Sequence; switch (packet.OPCodeType) { case DiscordWebSocketPacketTypeEnum.Other: if (packet.IsReadyPacket) { this.BotUser = new DiscordUser((JObject)packet.Data["user"]); this.sessionID = packet.Data["session_id"].ToString(); this.IsReady = true; } break; case DiscordWebSocketPacketTypeEnum.Heartbeat: break; case DiscordWebSocketPacketTypeEnum.Hello: this.heartbeatTime = (int)packet.Data["heartbeat_interval"]; JObject data = new JObject(); data["token"] = this.botToken; data["large_threshold"] = 100; JObject propertiesObj = new JObject(); propertiesObj["$device"] = "Mix It Up"; data["properties"] = propertiesObj; DiscordWebSocketPacket identifyPacket = new DiscordWebSocketPacket() { OPCodeType = DiscordWebSocketPacketTypeEnum.Identify, Data = data }; await this.Send(identifyPacket); break; case DiscordWebSocketPacketTypeEnum.HeartbeatAck: break; default: break; } } catch (Exception ex) { Logger.Log(ex); } }
public override async Task Connect() { await base.Connect(); this.SocketReceiveWrapper("connect", (data) => { this.Connected = true; }); this.SocketReceiveWrapper("realTimeTreat", (data) => { if (data != null) { TreatStreamEvent tsEvent = SerializerHelper.DeserializeFromString <TreatStreamEvent>(data.ToString()); if (tsEvent != null) { this.service.DonationOccurred(tsEvent); Task.Run(async() => { UserDonationModel donation = tsEvent.ToGenericDonation(); await EventCommand.ProcessDonationEventCommand(donation, OtherEventTypeEnum.TreatStreamDonation); }); } } }); this.SocketReceiveWrapper("error", (errorData) => { MixItUp.Base.Util.Logger.Log(errorData.ToString()); this.service.WebSocketDisconnectedOccurred(); }); this.SocketReceiveWrapper("disconnect", (errorData) => { MixItUp.Base.Util.Logger.Log(errorData.ToString()); this.service.WebSocketDisconnectedOccurred(); }); for (int i = 0; i < 10 && !this.Connected; i++) { await Task.Delay(1000); } if (this.Connected) { this.service.WebSocketConnectedOccurred(); } }
private async Task <T> GetAsync <T>(string endpoint) { try { using (HttpClientWrapper client = new HttpClientWrapper(MixItUpAPIEndpoint)) { HttpResponseMessage response = await client.GetAsync(endpoint); if (response.StatusCode == HttpStatusCode.OK) { string content = await response.Content.ReadAsStringAsync(); return(SerializerHelper.DeserializeFromString <T>(content)); } } } catch (Exception) { } return(default(T)); }
private async Task <T> PostAsyncWithResult <T>(string endpoint, object data) { try { using (HttpClientWrapper client = new HttpClientWrapper(MixItUpAPIEndpoint)) { string content = SerializerHelper.SerializeToString(data); HttpResponseMessage response = await client.PostAsync(endpoint, new StringContent(content, Encoding.UTF8, "application/json")); if (response.StatusCode == HttpStatusCode.OK) { string resultContent = await response.Content.ReadAsStringAsync(); return(SerializerHelper.DeserializeFromString <T>(resultContent)); } } } catch (Exception) { } return(default(T)); }
public async Task <bool> Connect() { PatronageStatusModel patronageStatus = await ChannelSession.Connection.GetPatronageStatus(ChannelSession.Channel); if (patronageStatus != null) { PatronagePeriodModel patronagePeriod = await ChannelSession.Connection.GetPatronagePeriod(patronageStatus); if (patronagePeriod != null) { this.allPatronageMilestones = new List <PatronageMilestoneModel>(patronagePeriod.milestoneGroups.SelectMany(mg => mg.milestones)); this.remainingPatronageMilestones = new List <PatronageMilestoneModel>(this.allPatronageMilestones.Where(m => m.target > patronageStatus.patronageEarned)); } } this.skillCatalog = await ChannelSession.Connection.GetSkillCatalog(ChannelSession.Channel); // Hacky workaround until auth issue is fixed for Skill Catalog try { using (HttpClient httpClient = new HttpClient()) { string data = await httpClient.GetStringAsync("https://raw.githubusercontent.com/SaviorXTanren/mixer-mixitup/master/MixItUp.Base/SkillsCatalogData.txt"); if (!string.IsNullOrEmpty(data)) { this.skillCatalog = SerializerHelper.DeserializeFromString <SkillCatalogModel>(data); if (this.skillCatalog != null) { this.availableSkills = new Dictionary <Guid, SkillModel>(this.skillCatalog.skills.ToDictionary(s => s.id, s => s)); } } } } catch (Exception ex) { Util.Logger.Log(ex); } return(await this.AttemptConnect()); }
public void SetStatus(string result) { this.status = SerializerHelper.DeserializeFromString <SongRequestCurrentlyPlayingModel>(result); }
private static async Task Version11Upgrade(int version, string filePath) { if (version < 11) { string data = File.ReadAllText(filePath); data = data.Replace("MixItUp.Base.Actions.OverlayAction, MixItUp.Base", "MixItUp.Desktop.Services.LegacyOverlayAction, MixItUp.Desktop"); DesktopChannelSettings legacySettings = SerializerHelper.DeserializeFromString <DesktopChannelSettings>(data); await ChannelSession.Services.Settings.Initialize(legacySettings); Dictionary <Guid, LegacyOverlayAction> legacyOverlayActions = new Dictionary <Guid, LegacyOverlayAction>(); List <CommandBase> commands = new List <CommandBase>(); commands.AddRange(legacySettings.ChatCommands); commands.AddRange(legacySettings.EventCommands); commands.AddRange(legacySettings.InteractiveCommands); commands.AddRange(legacySettings.TimerCommands); commands.AddRange(legacySettings.ActionGroupCommands); commands.AddRange(legacySettings.GameCommands); commands.AddRange(legacySettings.RemoteCommands); foreach (CommandBase command in commands) { foreach (ActionBase action in command.Actions) { if (action is LegacyOverlayAction) { legacyOverlayActions[action.ID] = (LegacyOverlayAction)action; } } } DesktopChannelSettings settings = await SerializerHelper.DeserializeFromFile <LegacyDesktopChannelSettings>(filePath); await ChannelSession.Services.Settings.Initialize(settings); commands.Clear(); commands.AddRange(settings.ChatCommands); commands.AddRange(settings.EventCommands); commands.AddRange(settings.InteractiveCommands); commands.AddRange(settings.TimerCommands); commands.AddRange(settings.ActionGroupCommands); commands.AddRange(settings.GameCommands); commands.AddRange(settings.RemoteCommands); foreach (CommandBase command in commands) { foreach (ActionBase action in command.Actions) { if (action is OverlayAction && legacyOverlayActions.ContainsKey(action.ID)) { OverlayAction overlayAction = (OverlayAction)action; LegacyOverlayAction legacyOverlayAction = legacyOverlayActions[action.ID]; OverlayEffectEntranceAnimationTypeEnum entrance = OverlayEffectEntranceAnimationTypeEnum.None; OverlayEffectExitAnimationTypeEnum exit = OverlayEffectExitAnimationTypeEnum.None; if (legacyOverlayAction.FadeDuration > 0) { entrance = OverlayEffectEntranceAnimationTypeEnum.FadeIn; exit = OverlayEffectExitAnimationTypeEnum.FadeOut; } if (!string.IsNullOrEmpty(legacyOverlayAction.ImagePath)) { overlayAction.Effect = new OverlayImageEffect(legacyOverlayAction.ImagePath, legacyOverlayAction.ImageWidth, legacyOverlayAction.ImageHeight, entrance, OverlayEffectVisibleAnimationTypeEnum.None, exit, legacyOverlayAction.Duration, legacyOverlayAction.Horizontal, legacyOverlayAction.Vertical); } else if (!string.IsNullOrEmpty(legacyOverlayAction.Text)) { overlayAction.Effect = new OverlayTextEffect(legacyOverlayAction.Text, legacyOverlayAction.Color, legacyOverlayAction.FontSize, entrance, OverlayEffectVisibleAnimationTypeEnum.None, exit, legacyOverlayAction.Duration, legacyOverlayAction.Horizontal, legacyOverlayAction.Vertical); } else if (!string.IsNullOrEmpty(legacyOverlayAction.youtubeVideoID)) { overlayAction.Effect = new OverlayYoutubeEffect(legacyOverlayAction.youtubeVideoID, legacyOverlayAction.youtubeStartTime, legacyOverlayAction.VideoWidth, legacyOverlayAction.VideoHeight, entrance, OverlayEffectVisibleAnimationTypeEnum.None, exit, legacyOverlayAction.Duration, legacyOverlayAction.Horizontal, legacyOverlayAction.Vertical); } else if (!string.IsNullOrEmpty(legacyOverlayAction.localVideoFilePath)) { overlayAction.Effect = new OverlayVideoEffect(legacyOverlayAction.localVideoFilePath, legacyOverlayAction.VideoWidth, legacyOverlayAction.VideoHeight, entrance, OverlayEffectVisibleAnimationTypeEnum.None, exit, legacyOverlayAction.Duration, legacyOverlayAction.Horizontal, legacyOverlayAction.Vertical); } else if (!string.IsNullOrEmpty(legacyOverlayAction.HTMLText)) { overlayAction.Effect = new OverlayHTMLEffect(legacyOverlayAction.HTMLText, entrance, OverlayEffectVisibleAnimationTypeEnum.None, exit, legacyOverlayAction.Duration, legacyOverlayAction.Horizontal, legacyOverlayAction.Vertical); } } else if (action is CounterAction) { CounterAction counterAction = (CounterAction)action; if (counterAction.SaveToFile) { counterAction.ResetOnLoad = !counterAction.ResetOnLoad; } } } } await ChannelSession.Services.Settings.Save(settings); } }
private async Task ProcessDeveloperAPIRequest(HttpListenerContext listenerContext, string httpMethod, List <string> urlSegments, string data) { if (urlSegments[0].Equals("mixer")) { if (urlSegments.Count() == 3 && urlSegments[1].Equals("users")) { if (httpMethod.Equals(GetHttpMethod)) { string identifier = urlSegments[2]; UserModel user = null; if (uint.TryParse(identifier, out uint userID)) { user = ChannelSession.Connection.GetUser(userID).Result; } else { user = ChannelSession.Connection.GetUser(identifier).Result; } if (user != null) { await this.CloseConnection(listenerContext, HttpStatusCode.OK, SerializerHelper.SerializeToString(user)); return; } else { await this.CloseConnection(listenerContext, HttpStatusCode.NotFound, "Could not find the user specified"); return; } } } } else if (urlSegments[0].Equals("users") && urlSegments.Count() >= 2) { string identifier = urlSegments[1]; UserDataViewModel user = null; if (uint.TryParse(identifier, out uint userID) && ChannelSession.Settings.UserData.ContainsKey(userID)) { user = ChannelSession.Settings.UserData[userID]; } else { user = ChannelSession.Settings.UserData.Values.FirstOrDefault(u => u.UserName.ToLower().Equals(identifier)); } if (httpMethod.Equals(GetHttpMethod)) { if (user != null) { await this.CloseConnection(listenerContext, HttpStatusCode.OK, SerializerHelper.SerializeToString(new UserDeveloperAPIModel(user))); return; } else { await this.CloseConnection(listenerContext, HttpStatusCode.NotFound, "Could not find the user specified"); return; } } else if (httpMethod.Equals(PutHttpMethod) || httpMethod.Equals(PatchHttpMethod)) { UserDeveloperAPIModel updatedUserData = SerializerHelper.DeserializeFromString <UserDeveloperAPIModel>(data); if (updatedUserData != null && updatedUserData.ID.Equals(user.ID)) { user.ViewingMinutes = updatedUserData.ViewingMinutes; foreach (UserCurrencyDeveloperAPIModel currencyData in updatedUserData.CurrencyAmounts) { if (ChannelSession.Settings.Currencies.ContainsKey(currencyData.ID)) { user.SetCurrencyAmount(ChannelSession.Settings.Currencies[currencyData.ID], currencyData.Amount); } } await this.CloseConnection(listenerContext, HttpStatusCode.OK, SerializerHelper.SerializeToString(new UserDeveloperAPIModel(user))); return; } else { await this.CloseConnection(listenerContext, HttpStatusCode.NotFound, "Invalid data/could not find matching user"); return; } } } else if (urlSegments[0].Equals("currency") && urlSegments.Count() == 2) { if (httpMethod.Equals(GetHttpMethod)) { string identifier = urlSegments[1]; if (Guid.TryParse(identifier, out Guid currencyID) && ChannelSession.Settings.Currencies.ContainsKey(currencyID)) { await this.CloseConnection(listenerContext, HttpStatusCode.OK, SerializerHelper.SerializeToString(ChannelSession.Settings.Currencies[currencyID])); return; } else { await this.CloseConnection(listenerContext, HttpStatusCode.NotFound, "Could not find the currency specified"); return; } } } else if (urlSegments[0].Equals("commands")) { List <CommandBase> allCommands = new List <CommandBase>(); allCommands.AddRange(ChannelSession.Settings.ChatCommands); allCommands.AddRange(ChannelSession.Settings.InteractiveCommands); allCommands.AddRange(ChannelSession.Settings.EventCommands); allCommands.AddRange(ChannelSession.Settings.TimerCommands); allCommands.AddRange(ChannelSession.Settings.ActionGroupCommands); allCommands.AddRange(ChannelSession.Settings.GameCommands); if (httpMethod.Equals(GetHttpMethod)) { if (urlSegments.Count() == 1) { await this.CloseConnection(listenerContext, HttpStatusCode.OK, SerializerHelper.SerializeToString(allCommands)); return; } else if (urlSegments.Count() == 2 && Guid.TryParse(urlSegments[1], out Guid ID)) { CommandBase command = allCommands.FirstOrDefault(c => c.ID.Equals(ID)); if (command != null) { await this.CloseConnection(listenerContext, HttpStatusCode.OK, SerializerHelper.SerializeToString(command)); return; } else { await this.CloseConnection(listenerContext, HttpStatusCode.NotFound, "Could not find the command specified"); return; } } } else if (httpMethod.Equals(PostHttpMethod)) { if (urlSegments.Count() == 2 && Guid.TryParse(urlSegments[1], out Guid ID)) { CommandBase command = allCommands.FirstOrDefault(c => c.ID.Equals(ID)); if (command != null) { #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed command.Perform(); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed await this.CloseConnection(listenerContext, HttpStatusCode.OK, SerializerHelper.SerializeToString(command)); return; } else { await this.CloseConnection(listenerContext, HttpStatusCode.NotFound, "Could not find the command specified"); return; } } } else if (httpMethod.Equals(PutHttpMethod) || httpMethod.Equals(PatchHttpMethod)) { if (urlSegments.Count() == 2 && Guid.TryParse(urlSegments[1], out Guid ID)) { CommandBase commandData = SerializerHelper.DeserializeAbstractFromString <CommandBase>(data); CommandBase matchedCommand = allCommands.FirstOrDefault(c => c.ID.Equals(ID)); if (matchedCommand != null) { matchedCommand.IsEnabled = commandData.IsEnabled; await this.CloseConnection(listenerContext, HttpStatusCode.OK, SerializerHelper.SerializeToString(matchedCommand)); return; } else { await this.CloseConnection(listenerContext, HttpStatusCode.NotFound, "Invalid data/could not find matching command"); return; } } } } else if (urlSegments[0].Equals("spotify") && urlSegments.Count() >= 2) { if (ChannelSession.Services.Spotify != null) { if (httpMethod.Equals(GetHttpMethod)) { if (urlSegments.Count() == 2) { if (urlSegments[1].Equals("current")) { await this.CloseConnection(listenerContext, HttpStatusCode.OK, SerializerHelper.SerializeToString(await ChannelSession.Services.Spotify.GetCurrentlyPlaying())); return; } else if (urlSegments[1].StartsWith("search?query=")) { string search = urlSegments[1].Replace("search?query=", ""); search = HttpUtility.UrlDecode(search); await this.CloseConnection(listenerContext, HttpStatusCode.OK, SerializerHelper.SerializeToString(await ChannelSession.Services.Spotify.SearchSongs(search))); return; } } } else if (httpMethod.Equals(PostHttpMethod)) { if (urlSegments.Count() == 2) { if (urlSegments[1].Equals("play")) { if (string.IsNullOrEmpty(data)) { await ChannelSession.Services.Spotify.PlayCurrentlyPlaying(); await this.CloseConnection(listenerContext, HttpStatusCode.OK, string.Empty); return; } else { if (await ChannelSession.Services.Spotify.PlaySong(data)) { await this.CloseConnection(listenerContext, HttpStatusCode.OK, string.Empty); } else { await this.CloseConnection(listenerContext, HttpStatusCode.BadRequest, "We were unable to play the uri you specified. If your uri is correct, please try again in a moment"); } return; } } else if (urlSegments[1].Equals("pause")) { await ChannelSession.Services.Spotify.PauseCurrentlyPlaying(); await this.CloseConnection(listenerContext, HttpStatusCode.OK, string.Empty); return; } else if (urlSegments[1].Equals("next")) { await ChannelSession.Services.Spotify.NextCurrentlyPlaying(); await this.CloseConnection(listenerContext, HttpStatusCode.OK, string.Empty); return; } else if (urlSegments[1].Equals("previous")) { await ChannelSession.Services.Spotify.PreviousCurrentlyPlaying(); await this.CloseConnection(listenerContext, HttpStatusCode.OK, string.Empty); return; } } } } else { await this.CloseConnection(listenerContext, HttpStatusCode.ServiceUnavailable, "The Spotify service is not currently connected in Mix It Up"); } } await this.CloseConnection(listenerContext, HttpStatusCode.BadRequest, "This is not a valid API"); }
private static async Task Version14Upgrade(int version, string filePath) { if (version < 14) { string data = File.ReadAllText(filePath); JObject dataJObj = JObject.Parse(data); if (dataJObj.ContainsKey("interactiveCommandsInternal")) { JArray interactiveCommands = (JArray)dataJObj["interactiveCommandsInternal"]; foreach (JToken interactiveCommand in interactiveCommands) { interactiveCommand["$type"] = "MixItUp.Base.Commands.InteractiveButtonCommand, MixItUp.Base"; } } data = SerializerHelper.SerializeToString(dataJObj); DesktopChannelSettings settings = SerializerHelper.DeserializeFromString <DesktopChannelSettings>(data); await ChannelSession.Services.Settings.Initialize(settings); List <PermissionsCommandBase> permissionCommands = new List <PermissionsCommandBase>(); permissionCommands.AddRange(settings.ChatCommands); permissionCommands.AddRange(settings.GameCommands); permissionCommands.AddRange(settings.InteractiveCommands); foreach (PermissionsCommandBase command in permissionCommands) { command.Requirements.Role.MixerRole = ConvertLegacyRoles(command.Requirements.Role.MixerRole); } List <CommandBase> commands = new List <CommandBase>(); commands.AddRange(settings.ChatCommands); commands.AddRange(settings.EventCommands); commands.AddRange(settings.InteractiveCommands); commands.AddRange(settings.TimerCommands); commands.AddRange(settings.ActionGroupCommands); commands.AddRange(settings.GameCommands); commands.AddRange(settings.RemoteCommands); foreach (CommandBase command in commands) { foreach (ActionBase action in command.Actions) { if (action is InteractiveAction) { InteractiveAction iAction = (InteractiveAction)action; iAction.RoleRequirement = ConvertLegacyRoles(iAction.RoleRequirement); } } } foreach (PreMadeChatCommandSettings preMadeCommandSettings in settings.PreMadeChatCommandSettings) { preMadeCommandSettings.Permissions = ConvertLegacyRoles(preMadeCommandSettings.Permissions); } foreach (InteractiveUserGroupViewModel userGroup in settings.InteractiveUserGroups.Values.SelectMany(ug => ug)) { userGroup.AssociatedUserRole = ConvertLegacyRoles(userGroup.AssociatedUserRole); } foreach (GameCommandBase command in settings.GameCommands) { if (command is OutcomeGameCommandBase) { OutcomeGameCommandBase outcomeGame = (OutcomeGameCommandBase)command; foreach (GameOutcomeGroup group in outcomeGame.Groups) { group.Role = ConvertLegacyRoles(group.Role); } } } settings.ModerationFilteredWordsExcempt = ConvertLegacyRoles(settings.ModerationFilteredWordsExcempt); settings.ModerationChatTextExcempt = ConvertLegacyRoles(settings.ModerationChatTextExcempt); settings.ModerationBlockLinksExcempt = ConvertLegacyRoles(settings.ModerationBlockLinksExcempt); IEnumerable <InteractiveCommand> oldInteractiveCommand = settings.InteractiveCommands.ToList(); settings.InteractiveCommands.Clear(); foreach (InteractiveCommand command in oldInteractiveCommand) { settings.InteractiveCommands.Add(new InteractiveButtonCommand() { ID = command.ID, Name = command.Name, Type = command.Type, Commands = command.Commands, Actions = command.Actions, IsEnabled = command.IsEnabled, IsBasic = command.IsBasic, Unlocked = command.Unlocked, Requirements = command.Requirements, GameID = command.GameID, SceneID = command.SceneID, Control = command.Control, Trigger = EnumHelper.GetEnumValueFromString <InteractiveButtonCommandTriggerType>(command.CommandsString), }); } await ChannelSession.Services.Settings.Save(settings); } }
public T Copy <T>() { return(SerializerHelper.DeserializeFromString <T>(SerializerHelper.SerializeToString(this))); }
public void SetStatus(string result) { this.status = SerializerHelper.DeserializeFromString <SongRequestItem>(result); }
private static async Task Version16Upgrade(int version, string filePath) { if (version < 16) { string data = File.ReadAllText(filePath); DesktopChannelSettings settings = SerializerHelper.DeserializeFromString <DesktopChannelSettings>(data); await ChannelSession.Services.Settings.Initialize(settings); List <CommandBase> commands = new List <CommandBase>(); commands.AddRange(settings.ChatCommands); commands.AddRange(settings.EventCommands); commands.AddRange(settings.InteractiveCommands); commands.AddRange(settings.TimerCommands); commands.AddRange(settings.ActionGroupCommands); commands.AddRange(settings.GameCommands); foreach (CommandBase command in commands) { for (int i = 0; i < command.Actions.Count; i++) { ActionBase action = command.Actions[i]; #pragma warning disable CS0612 // Type or member is obsolete if (action is OBSStudioAction || action is XSplitAction || action is StreamlabsOBSAction) { StreamingSoftwareTypeEnum type = StreamingSoftwareTypeEnum.OBSStudio; string scene = null; string source = null; bool visible = false; string text = null; string textPath = null; string url = null; StreamingSourceDimensions dimensions = null; if (action is OBSStudioAction) { type = StreamingSoftwareTypeEnum.OBSStudio; OBSStudioAction obsAction = (OBSStudioAction)action; scene = obsAction.SceneName; source = obsAction.SourceName; visible = obsAction.SourceVisible; text = obsAction.SourceText; url = obsAction.SourceURL; dimensions = obsAction.SourceDimensions; if (!string.IsNullOrEmpty(source)) { textPath = GetDefaultReferenceFilePath(OBSStudioReferenceTextFilesDirectory, source); } } else if (action is XSplitAction) { type = StreamingSoftwareTypeEnum.XSplit; XSplitAction xsplitAction = (XSplitAction)action; scene = xsplitAction.SceneName; source = xsplitAction.SourceName; visible = xsplitAction.SourceVisible; text = xsplitAction.SourceText; url = xsplitAction.SourceURL; if (!string.IsNullOrEmpty(source)) { textPath = GetDefaultReferenceFilePath(XSplitReferenceTextFilesDirectory, source); } } else if (action is StreamlabsOBSAction) { type = StreamingSoftwareTypeEnum.StreamlabsOBS; StreamlabsOBSAction slobsAction = (StreamlabsOBSAction)action; scene = slobsAction.SceneName; source = slobsAction.SourceName; visible = slobsAction.SourceVisible; text = slobsAction.SourceText; if (!string.IsNullOrEmpty(source)) { textPath = GetDefaultReferenceFilePath(StreamlabsOBSStudioReferenceTextFilesDirectory, source); } } #pragma warning restore CS0612 // Type or member is obsolete StreamingSoftwareAction sAction = null; if (!string.IsNullOrEmpty(scene)) { sAction = StreamingSoftwareAction.CreateSceneAction(type, scene); } else if (!string.IsNullOrEmpty(text)) { sAction = StreamingSoftwareAction.CreateTextSourceAction(type, source, visible, text, textPath); } else if (!string.IsNullOrEmpty(url)) { sAction = StreamingSoftwareAction.CreateWebBrowserSourceAction(type, source, visible, url); } else if (dimensions != null) { sAction = StreamingSoftwareAction.CreateSourceDimensionsAction(type, source, visible, dimensions); } else { sAction = StreamingSoftwareAction.CreateSourceVisibilityAction(type, source, visible); } command.Actions[i] = sAction; } } } await ChannelSession.Services.Settings.Save(settings); } }
protected override HttpStatusCode RequestReceived(HttpListenerRequest request, string data, out string result) { if (!string.IsNullOrEmpty(request.RawUrl) && request.RawUrl.ToLower().StartsWith("/api")) { List <string> urlSegments = new List <string>(request.RawUrl.ToLower().Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries)); urlSegments.RemoveAt(0); if (urlSegments.Count() == 0) { result = "Welcome to the Mix It Up Developer API! More detailed documentation about this service, please visit https://github.com/SaviorXTanren/mixer-mixitup/wiki/Developer-API"; return(HttpStatusCode.OK); } else if (urlSegments[0].Equals("mixer")) { if (urlSegments.Count() == 3 && urlSegments[1].Equals("users")) { if (request.HttpMethod.Equals("GET")) { string identifier = urlSegments[2]; UserModel user = null; if (uint.TryParse(identifier, out uint userID)) { user = ChannelSession.Connection.GetUser(userID).Result; } else { user = ChannelSession.Connection.GetUser(identifier).Result; } if (user != null) { result = SerializerHelper.SerializeToString(user); return(HttpStatusCode.OK); } else { result = "Could not find the user specified"; return(HttpStatusCode.NotFound); } } } } else if (urlSegments[0].Equals("users") && urlSegments.Count >= 2) { string identifier = urlSegments[1]; UserDataViewModel user = null; if (uint.TryParse(identifier, out uint userID) && ChannelSession.Settings.UserData.ContainsKey(userID)) { user = ChannelSession.Settings.UserData[userID]; } else { user = ChannelSession.Settings.UserData.Values.FirstOrDefault(u => u.UserName.ToLower().Equals(identifier)); } if (request.HttpMethod.Equals("GET")) { if (user != null) { result = SerializerHelper.SerializeToString(new UserDeveloperAPIModel(user)); return(HttpStatusCode.OK); } else { result = "Could not find the user specified"; return(HttpStatusCode.NotFound); } } else if (request.HttpMethod.Equals("PUT") || request.HttpMethod.Equals("PATCH")) { UserDeveloperAPIModel updatedUserData = SerializerHelper.DeserializeFromString <UserDeveloperAPIModel>(data); if (updatedUserData != null && updatedUserData.ID.Equals(user.ID)) { user.ViewingMinutes = updatedUserData.ViewingMinutes; foreach (UserCurrencyDeveloperAPIModel currencyData in updatedUserData.CurrencyAmounts) { if (ChannelSession.Settings.Currencies.ContainsKey(currencyData.ID)) { user.SetCurrencyAmount(ChannelSession.Settings.Currencies[currencyData.ID], currencyData.Amount); } } result = SerializerHelper.SerializeToString(new UserDeveloperAPIModel(user)); return(HttpStatusCode.OK); } else { result = "Invalid data/could not find matching user"; return(HttpStatusCode.NotFound); } } } else if (urlSegments[0].Equals("currency") && urlSegments.Count() == 2) { if (request.HttpMethod.Equals("GET")) { string identifier = urlSegments[1]; if (Guid.TryParse(identifier, out Guid currencyID) && ChannelSession.Settings.Currencies.ContainsKey(currencyID)) { result = SerializerHelper.SerializeToString(ChannelSession.Settings.Currencies[currencyID]); return(HttpStatusCode.OK); } else { result = "Could not find the currency specified"; return(HttpStatusCode.NotFound); } } } else if (urlSegments[0].Equals("commands")) { List <CommandBase> allCommands = new List <CommandBase>(); allCommands.AddRange(ChannelSession.AllChatCommands); allCommands.AddRange(ChannelSession.Settings.InteractiveCommands); allCommands.AddRange(ChannelSession.Settings.EventCommands); allCommands.AddRange(ChannelSession.Settings.TimerCommands); allCommands.AddRange(ChannelSession.Settings.ActionGroupCommands); if (request.HttpMethod.Equals("GET")) { if (urlSegments.Count() == 1) { result = SerializerHelper.SerializeToString(allCommands); return(HttpStatusCode.OK); } else if (urlSegments.Count() == 2 && Guid.TryParse(urlSegments[1], out Guid ID)) { CommandBase command = allCommands.FirstOrDefault(c => c.ID.Equals(ID)); if (command != null) { result = SerializerHelper.SerializeToString(command); return(HttpStatusCode.OK); } else { result = "Could not find the command specified"; return(HttpStatusCode.NotFound); } } } else if (request.HttpMethod.Equals("POST") && urlSegments.Count() == 2 && Guid.TryParse(urlSegments[1], out Guid ID)) { CommandBase command = allCommands.FirstOrDefault(c => c.ID.Equals(ID)); if (command != null) { #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed command.Perform(); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed result = ""; return(HttpStatusCode.OK); } else { result = "Could not find the command specified"; return(HttpStatusCode.NotFound); } } } result = "This is not a valid API"; return(HttpStatusCode.BadRequest); } else { result = "This is not a valid API"; return(HttpStatusCode.BadRequest); } }