public void Run() { _handler = HandlerFactory.Instance.GetHandler(_handlerInfo); if (_handler != null) { _runner = HandlerRunnerFactory.Instance.GetAsync(_handlerInfo.HandlerType, _context.Request.HttpMethod); _runner.Start(_handler, _context).ContinueWith(RunContinuation); } else { throw new InvalidOperationException("Could not create handler handler."); } }
/// <summary> /// Initiates the asynchronous execution of the GetRemaining operation. /// <seealso cref="Amazon.DynamoDBv2.DocumentModel.Search.GetRemaining"/> /// </summary> /// <param name="cancellationToken">Token which can be used to cancel the task.</param> /// <returns>A Task that can be used to poll or wait for results, or both.</returns> public Task <List <Document> > GetRemainingAsync(CancellationToken cancellationToken = default(CancellationToken)) { return(AsyncRunner.Run(() => GetRemainingHelper(true), cancellationToken)); }
protected virtual int ProcessPictures(ImportExecuteContext context, IEnumerable <ImportRow <Category> > batch) { var allFileIds = batch .Where(row => row.HasDataValue("ImageUrl") && row.Entity.MediaFileId > 0) .Select(row => row.Entity.MediaFileId.Value) .Distinct() .ToArray(); var allFiles = _mediaService.GetFilesByIds(allFileIds).ToDictionary(x => x.Id, x => x.File); var catalogAlbumId = _folderService.GetNodeByPath(SystemAlbumProvider.Catalog).Value.Id; foreach (var row in batch) { try { var imageUrl = row.GetDataValue <string>("ImageUrl"); if (imageUrl.IsEmpty()) { continue; } var image = CreateDownloadImage(context, imageUrl, 1); if (image == null) { continue; } if (image.Url.HasValue() && !image.Success.HasValue) { AsyncRunner.RunSync(() => _fileDownloadManager.DownloadAsync(DownloaderContext, new FileDownloadManagerItem[] { image })); } if ((image.Success ?? false) && File.Exists(image.Path)) { Succeeded(image); using (var stream = File.OpenRead(image.Path)) { if ((stream?.Length ?? 0) > 0) { var assignedFile = allFiles.Get(row.Entity.MediaFileId ?? 0); MediaFile sourceFile = null; if (assignedFile != null && _mediaService.FindEqualFile(stream, new[] { assignedFile }, true, out var _)) { context.Result.AddInfo($"Found equal image in data store for '{image.FileName}'. Skipping file.", row.GetRowInfo(), "ImageUrl"); } else if (_mediaService.FindEqualFile(stream, image.FileName, catalogAlbumId, true, out sourceFile)) { context.Result.AddInfo($"Found equal image in catalog album for '{image.FileName}'. Assigning existing file instead.", row.GetRowInfo(), "ImageUrl"); } else { var path = _mediaService.CombinePaths(SystemAlbumProvider.Catalog, image.FileName); sourceFile = _mediaService.SaveFile(path, stream, false, DuplicateFileHandling.Rename)?.File; } if (sourceFile?.Id > 0) { row.Entity.MediaFileId = sourceFile.Id; _categoryRepository.Update(row.Entity); } } } } else if (image.Url.HasValue()) { context.Result.AddInfo("Download of an image failed.", row.GetRowInfo(), "ImageUrls"); } } catch (Exception ex) { context.Result.AddWarning(ex.ToAllMessages(), row.GetRowInfo(), "ImageUrls"); } } var num = _categoryRepository.Context.SaveChanges(); return(num); }
private void RegisterAsyncEvents() { AsyncRunner asyncRunner = new AsyncRunner(); this.btnTestEventHandler.Click += asyncRunner.CreateEventHandler(Guid.NewGuid().ToString(), ButtonClickTask); }
/// <summary> /// Initiates the asynchronous execution of the Load operation. /// <seealso cref="Amazon.DynamoDBv2.DataModel.DynamoDBContext.Load"/> /// </summary> /// <typeparam name="T">Type to populate.</typeparam> /// <param name="hashKey">Hash key element of the target item.</param> /// <param name="rangeKey">Range key element of the target item.</param> /// <param name="operationConfig">Overriding configuration.</param> /// <param name="cancellationToken">Token which can be used to cancel the task.</param> /// <returns>A Task that can be used to poll or wait for results, or both.</returns> public Task <T> LoadAsync <T>(object hashKey, object rangeKey, DynamoDBOperationConfig operationConfig, CancellationToken cancellationToken = default(CancellationToken)) { return(AsyncRunner.Run(() => LoadHelper <T>(hashKey, rangeKey, operationConfig, true), cancellationToken)); }
public void Import(ProductImportModel model) { var controllingData = ConnectionCache.ControllingData(); if (!controllingData.IsImportEnabled) { _services.Notifier.Error(T("Plugins.SmartStore.ShopConnector.ImportNotActive")); return; } if (_asyncState.Exists <ShopConnectorProcessingInfo>(ShopConnectorPlugin.SystemName)) { _asyncState.Remove <ShopConnectorProcessingInfo>(ShopConnectorPlugin.SystemName); } var utcNow = DateTime.UtcNow; var state = new ShopConnectorImportState { ImportCategories = model.ImportCategories, ImportAll = model.ImportAll, ImportFile = model.ImportFile, UpdateExistingProducts = model.UpdateExistingProducts, UpdateExistingCategories = model.UpdateExistingCategories, DeleteImportFile = model.DeleteImportFile, TaxCategoryId = model.TaxCategoryId, LimitedToStores = model.LimitedToStores, EventPublishEntityCount = 100, Publish = model.Publish, DisableBuyButton = model.DisableBuyButton, DisableWishlistButton = model.DisableWishlistButton }; try { state.IgnoreEntityNames = _shopConnectorSettings.IgnoreEntityNames .SplitSafe(",") .Select(x => x.TrimSafe()) .ToList(); if (model.SelectedStoreIds != null && model.SelectedStoreIds.Any()) { state.SelectedStoreIds = model.SelectedStoreIds.ToList(); } if (!model.ImportAll && !string.IsNullOrWhiteSpace(model.SelectedProductIds)) { state.SelectedProductIds = model.SelectedProductIds.SplitSafe(",").Select(x => x.ToInt()).ToDictionarySafe(x => x, x => 0); } var task = AsyncRunner.Run((c, ct, x) => { var obj = x as ShopConnectorImportState; c.Resolve <IShopConnectorImportService>().StartProductImport(obj); }, state); _services.Notifier.Information(new LocalizedString(T("Plugins.SmartStore.ShopConnector.ImportInProgress"))); task.Wait(500); } catch (Exception ex) { _services.Notifier.Error(ex.ToAllMessages()); Logger.Error(ex); } }
public override async Task CustomRun(CommandParametersModel parameters) { await this.RefundCooldown(parameters); if (this.runParameters == null) { this.runParameters = parameters; this.runUsers[parameters.User] = parameters; #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed AsyncRunner.RunAsyncBackground(async(cancellationToken) => { await DelayNoThrow(this.TimeLimit * 1000, cancellationToken); if (this.runUsers.Count < this.MinimumParticipants) { await this.RunSubCommand(this.NotEnoughPlayersCommand, this.runParameters); foreach (var kvp in this.runUsers.ToList()) { await this.Requirements.Refund(kvp.Value); } await this.PerformCooldown(this.runParameters); this.ClearData(); return; } List <CommandParametersModel> participants = new List <CommandParametersModel>(); List <CommandParametersModel> winners = new List <CommandParametersModel>(); int totalPayout = 0; foreach (CommandParametersModel participant in this.runUsers.Values.ToList()) { if (this.GenerateProbability() <= this.UserSuccessOutcome.GetRoleProbabilityPayout(parameters.User).Probability) { winners.Add(participant); totalPayout += await this.RunOutcome(participant, this.UserSuccessOutcome); } else { await this.RunSubCommand(this.UserFailureCommand, participant); } } this.SetGameWinners(this.runParameters, winners); this.runParameters.SpecialIdentifiers[GameCommandModelBase.GameAllPayoutSpecialIdentifier] = totalPayout.ToString(); double successRate = Convert.ToDouble(winners.Count) / Convert.ToDouble(this.runUsers.Count); if (successRate == 1.0) { await this.RunSubCommand(this.AllSucceedCommand, this.runParameters); } else if (successRate > (2.0 / 3.0)) { await this.RunSubCommand(this.TopThirdsSucceedCommand, this.runParameters); } else if (successRate > (1.0 / 3.0)) { await this.RunSubCommand(this.MiddleThirdsSucceedCommand, this.runParameters); } else if (successRate > 0) { await this.RunSubCommand(this.LowThirdsSucceedCommand, this.runParameters); } else { await this.RunSubCommand(this.NoneSucceedCommand, this.runParameters); } await this.PerformCooldown(this.runParameters); this.ClearData(); }, new CancellationToken()); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed await this.RunSubCommand(this.StartedCommand, this.runParameters); await this.RunSubCommand(this.UserJoinCommand, this.runParameters); return; } else if (this.runParameters != null && !this.runUsers.ContainsKey(parameters.User)) { this.runUsers[parameters.User] = parameters; await this.RunSubCommand(this.UserJoinCommand, parameters); return; } else { await ChannelSession.Services.Chat.SendMessage(MixItUp.Base.Resources.GameCommandAlreadyUnderway); } await this.Requirements.Refund(parameters); }
public bool RunScheduleTask() { if (ScheduleTask.IsRunning) { Notifier.Information(GetProgressInfo()); return(true); } string scheduleTaskType = ScheduleTaskType; var task = AsyncRunner.Run(container => { try { var svc = container.Resolve <IScheduleTaskService>(); var scheduleTask = svc.GetTaskByType(scheduleTaskType); if (scheduleTask == null) { throw new Exception("Schedule task cannot be loaded"); } var job = new Job(scheduleTask); job.Enabled = true; job.Execute(container, false); } catch (Exception exc) { exc.Dump(); try { _scheduleTaskService.EnsureTaskIsNotRunning(scheduleTaskType); } catch (Exception) { } } }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); task.Wait(100); if (task.IsCompleted) { if (!task.IsFaulted) { Notifier.Success(GetResource("Admin.System.ScheduleTasks.RunNow.Completed")); } else { var exc = task.Exception.Flatten().InnerException; Notifier.Error(exc.Message); Logger.Error(exc.Message, exc); } } else { Notifier.Information(GetResource("Admin.System.ScheduleTasks.RunNow.Progress")); return(true); } return(false); }
/// <summary> /// Initiates the asynchronous execution of the Execute operation. /// <seealso cref="Amazon.DynamoDBv2.DataModel.MultiTableBatchWrite.Execute"/> /// </summary> /// <param name="cancellationToken">Token which can be used to cancel the task.</param> /// /// <returns>A Task that can be used to poll or wait for results, or both.</returns> public Task ExecuteAsync(CancellationToken cancellationToken = default(CancellationToken)) { return(AsyncRunner.Run(() => ExecuteHelper(true), cancellationToken)); }
protected override async Task <bool> ValidateRequirements(CommandParametersModel parameters) { this.SetPrimaryCurrencyRequirementArgumentIndex(argumentIndex: 1); if (this.gameActive) { if (this.betsClosed) { if (parameters.User.HasPermissionsTo(this.StarterRole)) { // At least to arguments // 1st must be "answer" // 2nd must be a number from 1 to option count if (parameters.Arguments.Count == 2 && string.Equals(parameters.Arguments[0], MixItUp.Base.Resources.Answer, StringComparison.CurrentCultureIgnoreCase) && int.TryParse(parameters.Arguments[1], out int answer) && answer > 0 && answer <= this.BetOptions.Count) { this.gameActive = false; this.betsClosed = false; GameOutcomeModel winningOutcome = this.BetOptions[answer - 1]; this.runParameters.SpecialIdentifiers[BetGameCommandModel.GameBetWinningOptionSpecialIdentifier] = winningOutcome.Name; await this.GameCompleteCommand.Perform(this.runParameters); foreach (CommandParametersModel winner in this.runUserSelections.Where(kvp => kvp.Value == answer).Select(kvp => this.runUsers[kvp.Key])) { winner.SpecialIdentifiers[BetGameCommandModel.GameBetWinningOptionSpecialIdentifier] = winningOutcome.Name; await this.PerformOutcome(winner, winningOutcome); } await this.PerformCooldown(this.runParameters); this.ClearData(); } else { string trigger = this.GetFullTriggers().FirstOrDefault() ?? "!bet"; await ChannelSession.Services.Chat.SendMessage(string.Format(MixItUp.Base.Resources.GameCommandBetAnswerExample, trigger)); } } else { await ChannelSession.Services.Chat.SendMessage(string.Format(MixItUp.Base.Resources.RoleErrorInsufficientRole, this.StarterRole)); } } else { if (parameters.Arguments.Count > 0 && int.TryParse(parameters.Arguments[0], out int choice) && choice > 0 && choice <= this.BetOptions.Count) { return(await base.ValidateRequirements(parameters)); } await ChannelSession.Services.Chat.SendMessage(string.Format(MixItUp.Base.Resources.GameCommandBetInvalidSelection, parameters.User.Username)); } } else { if (parameters.User.HasPermissionsTo(this.StarterRole)) { this.gameActive = true; this.runParameters = parameters; int i = 1; List <string> betOptions = new List <string>(); foreach (GameOutcomeModel betOption in this.BetOptions) { betOptions.Add($"{i}) {betOption.Name}"); i++; } this.runParameters.SpecialIdentifiers[BetGameCommandModel.GameBetOptionsSpecialIdentifier] = string.Join(", ", betOptions); #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed AsyncRunner.RunAsyncBackground(async(cancellationToken) => { await DelayNoThrow(this.TimeLimit * 1000, cancellationToken); if (this.runUsers.Count < this.MinimumParticipants) { await this.NotEnoughPlayersCommand.Perform(this.runParameters); foreach (var kvp in this.runUsers.ToList()) { await this.Requirements.Refund(kvp.Value); } await this.PerformCooldown(this.runParameters); this.ClearData(); return; } this.betsClosed = true; await this.BetsClosedCommand.Perform(this.runParameters); }, new CancellationToken()); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed await this.StartedCommand.Perform(parameters); return(false); } await ChannelSession.Services.Chat.SendMessage(string.Format(MixItUp.Base.Resources.RoleErrorInsufficientRole, this.StarterRole)); } return(false); }
public void Invoke <TMessage>(ConsumerDescriptor descriptor, IConsumer consumer, ConsumeContext <TMessage> envelope) where TMessage : class { var d = descriptor; var p = descriptor.WithEnvelope ? (object)envelope : envelope.Message; var fastInvoker = FastInvoker.GetInvoker(d.Method); if (!d.FireForget && !d.IsAsync) { // The all synch case try { InvokeCore(); } catch (Exception ex) { HandleException(ex, d); } } else if (!d.FireForget && d.IsAsync) { //// The awaitable Task case //BeginInvoke((Task)InvokeCore(cancelToken: AsyncRunner.AppShutdownCancellationToken), EndInvoke, d); // For now we must go with the AsyncRunner, the above call to BeginInvoke (APM > TPL) does not always // guarantee that the task is awaited and throws exceptions especially when EF is involved. using (var runner = AsyncRunner.Create()) { try { runner.Run((Task)InvokeCore(cancelToken: AsyncRunner.AppShutdownCancellationToken)); } catch (Exception ex) { HandleException(ex, d); } } } else if (d.FireForget && !d.IsAsync) { // A synch method should be executed async (without awaiting) AsyncRunner.Run((c, ct, state) => InvokeCore(c, ct), d) .ContinueWith(t => EndInvoke(t), /*TaskContinuationOptions.OnlyOnFaulted*/ TaskContinuationOptions.None) .ConfigureAwait(false); } else if (d.FireForget && d.IsAsync) { // An async (Task) method should be executed without awaiting AsyncRunner.Run((c, ct) => (Task)InvokeCore(c, ct), d) .ContinueWith(t => EndInvoke(t), TaskContinuationOptions.OnlyOnFaulted) .ConfigureAwait(false); } object InvokeCore(IComponentContext c = null, CancellationToken cancelToken = default(CancellationToken)) { if (d.Parameters.Length == 0) { // Only one method param: the message! return(fastInvoker.Invoke(consumer, p)); } var parameters = new object[d.Parameters.Length + 1]; parameters[0] = p; int i = 0; foreach (var obj in ResolveParameters(c, d, cancelToken).ToArray()) { i++; parameters[i] = obj; } return(fastInvoker.Invoke(consumer, parameters)); } }
public StoreInfoViewModel(INavigationService navigationService, IAppService appService) : base(navigationService) { _appService = appService; AsyncRunner.Run(LoadVoucherItems()); }
protected override async Task PerformInternal(CommandParametersModel parameters) { if (this.ActionType == TwitchActionType.Host) { string channelName = await ReplaceStringWithSpecialModifiers(this.Username, parameters); await ChannelSession.Services.Chat.SendMessage("/host @" + channelName, sendAsStreamer : true, platform : StreamingPlatformTypeEnum.Twitch); } else if (this.ActionType == TwitchActionType.Raid) { string channelName = await ReplaceStringWithSpecialModifiers(this.Username, parameters); await ChannelSession.Services.Chat.SendMessage("/raid @" + channelName, sendAsStreamer : true, platform : StreamingPlatformTypeEnum.Twitch); } else if (this.ActionType == TwitchActionType.RunAd) { AdResponseModel response = await ChannelSession.TwitchUserConnection.RunAd(ChannelSession.TwitchUserNewAPI, this.AdLength); if (response == null) { await ChannelSession.Services.Chat.SendMessage("ERROR: We were unable to run an ad, please try again later"); } else if (!string.IsNullOrEmpty(response.message) && !response.message.Contains(StartinCommercialBreakMessage, System.StringComparison.OrdinalIgnoreCase)) { await ChannelSession.Services.Chat.SendMessage("ERROR: " + response.message); } } else if (this.ActionType == TwitchActionType.VIPUser || this.ActionType == TwitchActionType.UnVIPUser) { string targetUsername = null; if (!string.IsNullOrEmpty(this.Username)) { targetUsername = await ReplaceStringWithSpecialModifiers(this.Username, parameters); } else { targetUsername = parameters.User.TwitchUsername; } if (targetUsername != null) { if (this.ActionType == TwitchActionType.VIPUser) { await ChannelSession.Services.Chat.SendMessage("/vip @" + targetUsername, sendAsStreamer : true, platform : StreamingPlatformTypeEnum.Twitch); } else if (this.ActionType == TwitchActionType.UnVIPUser) { await ChannelSession.Services.Chat.SendMessage("/unvip @" + targetUsername, sendAsStreamer : true, platform : StreamingPlatformTypeEnum.Twitch); } } } else if (this.ActionType == TwitchActionType.Clip) { ClipCreationModel clipCreation = await ChannelSession.TwitchUserConnection.CreateClip(ChannelSession.TwitchUserNewAPI, this.ClipIncludeDelay); if (clipCreation != null) { for (int i = 0; i < 12; i++) { await Task.Delay(5000); ClipModel clip = await ChannelSession.TwitchUserConnection.GetClip(clipCreation); if (clip != null && !string.IsNullOrEmpty(clip.url)) { if (this.ShowInfoInChat) { await ChannelSession.Services.Chat.SendMessage(string.Format(MixItUp.Base.Resources.ClipCreatedMessage, clip.url)); } parameters.SpecialIdentifiers[ClipURLSpecialIdentifier] = clip.url; GlobalEvents.TwitchClipCreated(clip); return; } } } await ChannelSession.Services.Chat.SendMessage(MixItUp.Base.Resources.ClipCreationFailed); } else if (this.ActionType == TwitchActionType.StreamMarker) { string description = await ReplaceStringWithSpecialModifiers(this.StreamMarkerDescription, parameters); if (!string.IsNullOrEmpty(description) && description.Length > TwitchActionModel.StreamMarkerMaxDescriptionLength) { description = description.Substring(0, TwitchActionModel.StreamMarkerMaxDescriptionLength); } CreatedStreamMarkerModel streamMarker = await ChannelSession.TwitchUserConnection.CreateStreamMarker(ChannelSession.TwitchUserNewAPI, description); if (streamMarker != null) { if (this.ShowInfoInChat) { await ChannelSession.Services.Chat.SendMessage(string.Format(MixItUp.Base.Resources.StreamMarkerCreatedMessage, streamMarker.URL)); } parameters.SpecialIdentifiers[StreamMarkerURLSpecialIdentifier] = streamMarker.URL; return; } await ChannelSession.Services.Chat.SendMessage(MixItUp.Base.Resources.StreamMarkerCreationFailed); } else if (this.ActionType == TwitchActionType.UpdateChannelPointReward) { JObject jobj = new JObject() { { "is_enabled", this.ChannelPointRewardState }, }; #pragma warning disable CS0612 // Type or member is obsolete if (this.ChannelPointRewardCost >= 0) { this.ChannelPointRewardCostString = this.ChannelPointRewardCost.ToString(); this.ChannelPointRewardMaxPerStreamString = this.ChannelPointRewardMaxPerStream.ToString(); this.ChannelPointRewardMaxPerUserString = this.ChannelPointRewardMaxPerUser.ToString(); this.ChannelPointRewardGlobalCooldownString = this.ChannelPointRewardGlobalCooldown.ToString(); this.ChannelPointRewardCost = -1; this.ChannelPointRewardMaxPerStream = -1; this.ChannelPointRewardMaxPerUser = -1; this.ChannelPointRewardGlobalCooldown = -1; } #pragma warning restore CS0612 // Type or member is obsolete int.TryParse(await ReplaceStringWithSpecialModifiers(this.ChannelPointRewardCostString, parameters), out int cost); if (cost > 0) { jobj["cost"] = cost; } if (this.ChannelPointRewardUpdateCooldownsAndLimits) { int.TryParse(await ReplaceStringWithSpecialModifiers(this.ChannelPointRewardMaxPerStreamString, parameters), out int maxPerStream); if (maxPerStream > 0) { jobj["max_per_stream_setting"] = new JObject() { { "is_enabled", true }, { "max_per_stream", maxPerStream } }; } else { jobj["max_per_stream_setting"] = new JObject() { { "is_enabled", false }, }; } int.TryParse(await ReplaceStringWithSpecialModifiers(this.ChannelPointRewardMaxPerUserString, parameters), out int maxPerUser); if (maxPerUser > 0) { jobj["max_per_user_per_stream_setting"] = new JObject() { { "is_enabled", true }, { "max_per_user_per_stream", maxPerUser } }; } else { jobj["max_per_user_per_stream_setting"] = new JObject() { { "is_enabled", false }, }; } int.TryParse(await ReplaceStringWithSpecialModifiers(this.ChannelPointRewardGlobalCooldownString, parameters), out int globalCooldown); if (globalCooldown > 0) { jobj["global_cooldown_setting"] = new JObject() { { "is_enabled", true }, { "global_cooldown_seconds", globalCooldown * 60 } }; } else { jobj["global_cooldown_setting"] = new JObject() { { "is_enabled", false }, }; } } CustomChannelPointRewardModel reward = await ChannelSession.TwitchUserConnection.UpdateCustomChannelPointReward(ChannelSession.TwitchUserNewAPI, this.ChannelPointRewardID, jobj); if (reward == null) { await ChannelSession.Services.Chat.SendMessage(MixItUp.Base.Resources.TwitchActionChannelPointRewardCouldNotBeUpdated); } } else if (this.ActionType == TwitchActionType.CreatePoll) { List <CreatePollChoiceModel> choices = new List <CreatePollChoiceModel>(); foreach (string choice in this.PollChoices) { choices.Add(new CreatePollChoiceModel() { title = await ReplaceStringWithSpecialModifiers(choice, parameters) }); } PollModel poll = await ChannelSession.TwitchUserConnection.CreatePoll(new CreatePollModel() { broadcaster_id = ChannelSession.TwitchUserNewAPI.id, title = await ReplaceStringWithSpecialModifiers(this.PollTitle, parameters), duration = this.PollDurationSeconds, channel_points_voting_enabled = this.PollChannelPointsCost > 0, channel_points_per_vote = this.PollChannelPointsCost, bits_voting_enabled = this.PollBitsCost > 0, bits_per_vote = this.PollBitsCost, choices = choices }); if (poll == null) { await ChannelSession.Services.Chat.SendMessage(MixItUp.Base.Resources.TwitchPollFailedToCreate); return; } if (this.Actions.Count > 0) { #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed AsyncRunner.RunAsyncBackground(async(cancellationToken) => { await Task.Delay(1000 * (this.PollDurationSeconds + 2)); for (int i = 0; i < 5; i++) { PollModel results = await ChannelSession.TwitchUserConnection.GetPoll(ChannelSession.TwitchUserNewAPI, poll.id); if (results != null) { if (string.Equals(results.status, "COMPLETED", StringComparison.OrdinalIgnoreCase)) { int maxVotes = results.choices.Max(c => c.votes); IEnumerable <PollChoiceModel> winningChoices = results.choices.Where(c => c.votes == maxVotes); parameters.SpecialIdentifiers[PollChoiceSpecialIdentifier] = string.Join(" & ", winningChoices.Select(c => c.title)); await ChannelSession.Services.Command.RunDirectly(new CommandInstanceModel(this.Actions, parameters)); return; } else if (!string.Equals(results.status, "ACTIVE", StringComparison.OrdinalIgnoreCase)) { return; } } await Task.Delay(2000); } await ChannelSession.Services.Chat.SendMessage(MixItUp.Base.Resources.TwitchPollFailedToGetResults); }, new CancellationToken()); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed } } else if (this.ActionType == TwitchActionType.CreatePrediction) { List <CreatePredictionOutcomeModel> outcomes = new List <CreatePredictionOutcomeModel>(); foreach (string outcome in this.PredictionOutcomes) { outcomes.Add(new CreatePredictionOutcomeModel() { title = await ReplaceStringWithSpecialModifiers(outcome, parameters) }); } PredictionModel prediction = await ChannelSession.TwitchUserConnection.CreatePrediction(new CreatePredictionModel() { broadcaster_id = ChannelSession.TwitchUserNewAPI.id, title = await ReplaceStringWithSpecialModifiers(this.PredictionTitle, parameters), prediction_window = this.PredictionDurationSeconds, outcomes = outcomes }); if (prediction == null) { await ChannelSession.Services.Chat.SendMessage(MixItUp.Base.Resources.TwitchPredictionFailedToCreate); return; } if (this.Actions.Count > 0) { #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed AsyncRunner.RunAsyncBackground(async(cancellationToken) => { await Task.Delay(1000 * this.PredictionDurationSeconds); while (true) { await Task.Delay(10000); PredictionModel results = await ChannelSession.TwitchUserConnection.GetPrediction(ChannelSession.TwitchUserNewAPI, prediction.id); if (results != null) { if (string.Equals(results.status, "RESOLVED", StringComparison.OrdinalIgnoreCase)) { PredictionOutcomeModel outcome = results.outcomes.FirstOrDefault(o => string.Equals(o.id, results.winning_outcome_id)); parameters.SpecialIdentifiers[PredictionOutcomeSpecialIdentifier] = outcome?.title; await ChannelSession.Services.Command.RunDirectly(new CommandInstanceModel(this.Actions, parameters)); return; } else if (string.Equals(results.status, "CANCELED", StringComparison.OrdinalIgnoreCase)) { return; } } } }, new CancellationToken()); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed } } }
public async Task <Result> Connect() { this.IsConnected = false; if (ChannelSession.TwitchUserConnection != null) { return(await this.AttemptConnect((Func <Task <Result> >)(async() => { try { this.pubSub = new PubSubClient(ChannelSession.TwitchUserConnection.Connection); if (ChannelSession.AppSettings.DiagnosticLogging) { this.pubSub.OnSentOccurred += PubSub_OnSentOccurred; this.pubSub.OnTextReceivedOccurred += PubSub_OnTextReceivedOccurred; this.pubSub.OnMessageReceived += PubSub_OnMessageReceived; } this.pubSub.OnReconnectReceived += PubSub_OnReconnectReceived; this.pubSub.OnDisconnectOccurred += PubSub_OnDisconnectOccurred; this.pubSub.OnPongReceived += PubSub_OnPongReceived; this.pubSub.OnResponseReceived += PubSub_OnResponseReceived; this.pubSub.OnWhisperReceived += PubSub_OnWhisperReceived; this.pubSub.OnBitsV2Received += PubSub_OnBitsV2Received; this.pubSub.OnSubscribedReceived += PubSub_OnSubscribedReceived; this.pubSub.OnSubscriptionsGiftedReceived += PubSub_OnSubscriptionsGiftedReceived; this.pubSub.OnChannelPointsRedeemed += PubSub_OnChannelPointsRedeemed; await this.pubSub.Connect(); await Task.Delay(1000); List <PubSubListenTopicModel> topics = new List <PubSubListenTopicModel>(); foreach (PubSubTopicsEnum topic in TwitchEventService.topicTypes) { topics.Add(new PubSubListenTopicModel(topic, (string)ChannelSession.TwitchUserNewAPI.id)); } await this.pubSub.Listen(topics); await Task.Delay(1000); await this.pubSub.Ping(); this.cancellationTokenSource = new CancellationTokenSource(); #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed AsyncRunner.RunAsyncBackground(this.BackgroundEventChecks, this.cancellationTokenSource.Token, 60000); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed this.IsConnected = true; return new Result(); } catch (Exception ex) { Logger.Log(ex); return new Result(ex); } }))); } return(new Result(Resources.TwitchConnectionFailed)); }
public static async Task <bool> InitializeSession() { try { TwitchNewAPI.Users.UserModel twitchChannelNew = await ChannelSession.TwitchUserConnection.GetNewAPICurrentUser(); TwitchV5API.Channel.ChannelModel twitchChannelv5 = await ChannelSession.TwitchUserConnection.GetCurrentV5APIChannel(); if (twitchChannelNew != null && twitchChannelv5 != null) { try { ChannelSession.TwitchUserNewAPI = twitchChannelNew; ChannelSession.TwitchChannelV5 = twitchChannelv5; ChannelSession.TwitchStreamNewAPI = await ChannelSession.TwitchUserConnection.GetStream(ChannelSession.TwitchUserNewAPI); ChannelSession.TwitchStreamV5 = await ChannelSession.TwitchUserConnection.GetV5LiveStream(ChannelSession.TwitchChannelV5); IEnumerable <TwitchV5API.Users.UserModel> channelEditors = await ChannelSession.TwitchUserConnection.GetV5APIChannelEditors(ChannelSession.TwitchChannelV5); if (channelEditors != null) { foreach (TwitchV5API.Users.UserModel channelEditor in channelEditors) { ChannelSession.TwitchChannelEditorsV5.Add(channelEditor.id); } } if (ChannelSession.Settings == null) { IEnumerable <SettingsV2Model> currentSettings = await ChannelSession.Services.Settings.GetAllSettings(); if (currentSettings.Any(s => !string.IsNullOrEmpty(s.TwitchChannelID) && string.Equals(s.TwitchChannelID, twitchChannelNew.id))) { GlobalEvents.ShowMessageBox($"There already exists settings for the account {twitchChannelNew.display_name}. Please sign in with a different account or re-launch Mix It Up to select those settings from the drop-down."); return(false); } ChannelSession.Settings = await ChannelSession.Services.Settings.Create(twitchChannelNew.display_name, isStreamer : true); } await ChannelSession.Services.Settings.Initialize(ChannelSession.Settings); if (!string.IsNullOrEmpty(ChannelSession.Settings.TwitchUserID) && !string.Equals(ChannelSession.TwitchUserNewAPI.id, ChannelSession.Settings.TwitchUserID)) { Logger.Log(LogLevel.Error, $"Signed in account does not match settings account: {ChannelSession.TwitchUserNewAPI.display_name} - {ChannelSession.TwitchUserNewAPI.id} - {ChannelSession.Settings.TwitchUserID}"); GlobalEvents.ShowMessageBox("The account you are logged in as on Twitch does not match the account for this settings. Please log in as the correct account on Twitch."); ChannelSession.Settings.TwitchUserOAuthToken.accessToken = string.Empty; ChannelSession.Settings.TwitchUserOAuthToken.refreshToken = string.Empty; ChannelSession.Settings.TwitchUserOAuthToken.expiresIn = 0; return(false); } ChannelSession.Settings.Name = ChannelSession.TwitchUserNewAPI.display_name; ChannelSession.Settings.TwitchUserID = ChannelSession.TwitchUserNewAPI.id; ChannelSession.Settings.TwitchChannelID = ChannelSession.TwitchUserNewAPI.id; } catch (Exception ex) { Logger.Log(ex); Logger.Log(LogLevel.Error, "Initialize Settings - " + JSONSerializerHelper.SerializeToString(ex)); await DialogHelper.ShowMessage("Failed to initialize settings. If this continues, please visit the Mix It Up Discord for assistance." + Environment.NewLine + Environment.NewLine + "Error Details: " + ex.Message); return(false); } try { await ChannelSession.Services.Telemetry.Connect(); ChannelSession.Services.Telemetry.SetUserID(ChannelSession.Settings.TelemetryUserID); TwitchChatService twitchChatService = new TwitchChatService(); TwitchEventService twitchEventService = new TwitchEventService(); List <Task <Result> > twitchPlatformServiceTasks = new List <Task <Result> >(); twitchPlatformServiceTasks.Add(twitchChatService.ConnectUser()); twitchPlatformServiceTasks.Add(twitchEventService.Connect()); await Task.WhenAll(twitchPlatformServiceTasks); if (twitchPlatformServiceTasks.Any(c => !c.Result.Success)) { string errors = string.Join(Environment.NewLine, twitchPlatformServiceTasks.Where(c => !c.Result.Success).Select(c => c.Result.Message)); GlobalEvents.ShowMessageBox("Failed to connect to Twitch services:" + Environment.NewLine + Environment.NewLine + errors); return(false); } await ChannelSession.Services.Chat.Initialize(twitchChatService); await ChannelSession.Services.Events.Initialize(twitchEventService); } catch (Exception ex) { Logger.Log(ex); Logger.Log(LogLevel.Error, "Twitch Services - " + JSONSerializerHelper.SerializeToString(ex)); await DialogHelper.ShowMessage("Failed to connect to Twitch services. If this continues, please visit the Mix It Up Discord for assistance." + Environment.NewLine + Environment.NewLine + "Error Details: " + ex.Message); return(false); } if (ChannelSession.IsStreamer) { Result result = await ChannelSession.InitializeBotInternal(); if (!result.Success) { await DialogHelper.ShowMessage("Failed to initialize Bot account"); return(false); } try { // Connect External Services Dictionary <IExternalService, OAuthTokenModel> externalServiceToConnect = new Dictionary <IExternalService, OAuthTokenModel>(); if (ChannelSession.Settings.StreamlabsOAuthToken != null) { externalServiceToConnect[ChannelSession.Services.Streamlabs] = ChannelSession.Settings.StreamlabsOAuthToken; } if (ChannelSession.Settings.StreamElementsOAuthToken != null) { externalServiceToConnect[ChannelSession.Services.StreamElements] = ChannelSession.Settings.StreamElementsOAuthToken; } if (ChannelSession.Settings.StreamJarOAuthToken != null) { externalServiceToConnect[ChannelSession.Services.StreamJar] = ChannelSession.Settings.StreamJarOAuthToken; } if (ChannelSession.Settings.TipeeeStreamOAuthToken != null) { externalServiceToConnect[ChannelSession.Services.TipeeeStream] = ChannelSession.Settings.TipeeeStreamOAuthToken; } if (ChannelSession.Settings.TreatStreamOAuthToken != null) { externalServiceToConnect[ChannelSession.Services.TreatStream] = ChannelSession.Settings.TreatStreamOAuthToken; } if (ChannelSession.Settings.StreamlootsOAuthToken != null) { externalServiceToConnect[ChannelSession.Services.Streamloots] = ChannelSession.Settings.StreamlootsOAuthToken; } if (ChannelSession.Settings.TiltifyOAuthToken != null) { externalServiceToConnect[ChannelSession.Services.Tiltify] = ChannelSession.Settings.TiltifyOAuthToken; } if (ChannelSession.Settings.JustGivingOAuthToken != null) { externalServiceToConnect[ChannelSession.Services.JustGiving] = ChannelSession.Settings.JustGivingOAuthToken; } if (ChannelSession.Settings.IFTTTOAuthToken != null) { externalServiceToConnect[ChannelSession.Services.IFTTT] = ChannelSession.Settings.IFTTTOAuthToken; } if (ChannelSession.Settings.ExtraLifeTeamID > 0) { externalServiceToConnect[ChannelSession.Services.ExtraLife] = new OAuthTokenModel(); } if (ChannelSession.Settings.PatreonOAuthToken != null) { externalServiceToConnect[ChannelSession.Services.Patreon] = ChannelSession.Settings.PatreonOAuthToken; } if (ChannelSession.Settings.DiscordOAuthToken != null) { externalServiceToConnect[ChannelSession.Services.Discord] = ChannelSession.Settings.DiscordOAuthToken; } if (ChannelSession.Settings.TwitterOAuthToken != null) { externalServiceToConnect[ChannelSession.Services.Twitter] = ChannelSession.Settings.TwitterOAuthToken; } if (ChannelSession.Services.OBSStudio.IsEnabled) { externalServiceToConnect[ChannelSession.Services.OBSStudio] = null; } if (ChannelSession.Services.StreamlabsOBS.IsEnabled) { externalServiceToConnect[ChannelSession.Services.StreamlabsOBS] = null; } if (ChannelSession.Services.XSplit.IsEnabled) { externalServiceToConnect[ChannelSession.Services.XSplit] = null; } if (!string.IsNullOrEmpty(ChannelSession.Settings.OvrStreamServerIP)) { externalServiceToConnect[ChannelSession.Services.OvrStream] = null; } if (ChannelSession.Settings.EnableOverlay) { externalServiceToConnect[ChannelSession.Services.Overlay] = null; } if (ChannelSession.Settings.EnableDeveloperAPI) { externalServiceToConnect[ChannelSession.Services.DeveloperAPI] = null; } if (externalServiceToConnect.Count > 0) { Dictionary <IExternalService, Task <Result> > externalServiceTasks = new Dictionary <IExternalService, Task <Result> >(); foreach (var kvp in externalServiceToConnect) { Logger.Log(LogLevel.Debug, "Trying automatic OAuth service connection: " + kvp.Key.Name); try { if (kvp.Key is IOAuthExternalService && kvp.Value != null) { externalServiceTasks[kvp.Key] = ((IOAuthExternalService)kvp.Key).Connect(kvp.Value); } else { externalServiceTasks[kvp.Key] = kvp.Key.Connect(); } } catch (Exception sex) { Logger.Log(LogLevel.Error, "Error in external service initial connection: " + kvp.Key.Name); Logger.Log(sex); } } try { await Task.WhenAll(externalServiceTasks.Values); } catch (Exception sex) { Logger.Log(LogLevel.Error, "Error in batch external service connection"); Logger.Log(sex); } List <IExternalService> failedServices = new List <IExternalService>(); foreach (var kvp in externalServiceTasks) { try { if (kvp.Value.Result != null && !kvp.Value.Result.Success && kvp.Key is IOAuthExternalService) { Logger.Log(LogLevel.Debug, "Automatic OAuth token connection failed, trying manual connection: " + kvp.Key.Name); result = await kvp.Key.Connect(); if (!result.Success) { failedServices.Add(kvp.Key); } } } catch (Exception sex) { Logger.Log(LogLevel.Error, "Error in external service failed re-connection: " + kvp.Key.Name); Logger.Log(sex); failedServices.Add(kvp.Key); } } if (failedServices.Count > 0) { Logger.Log(LogLevel.Debug, "Connection failed for services: " + string.Join(", ", failedServices.Select(s => s.Name))); StringBuilder message = new StringBuilder(); message.AppendLine("The following services could not be connected:"); message.AppendLine(); foreach (IExternalService service in failedServices) { message.AppendLine(" - " + service.Name); } message.AppendLine(); message.Append("Please go to the Services page to reconnect them manually."); await DialogHelper.ShowMessage(message.ToString()); } } } catch (Exception ex) { Logger.Log(ex); Logger.Log(LogLevel.Error, "External Services - " + JSONSerializerHelper.SerializeToString(ex)); await DialogHelper.ShowMessage("Failed to initialize external services. If this continues, please visit the Mix It Up Discord for assistance." + Environment.NewLine + Environment.NewLine + "Error Details: " + ex.Message); return(false); } try { //if (ChannelSession.Settings.RemoteHostConnection != null) //{ // await ChannelSession.Services.RemoteService.InitializeConnection(ChannelSession.Settings.RemoteHostConnection); //} foreach (CurrencyModel currency in ChannelSession.Settings.Currency.Values) { if (currency.ShouldBeReset()) { await currency.Reset(); } } if (ChannelSession.Settings.ModerationResetStrikesOnLaunch) { foreach (UserDataModel userData in ChannelSession.Settings.UserData.Values) { if (userData.ModerationStrikes > 0) { userData.ModerationStrikes = 0; ChannelSession.Settings.UserData.ManualValueChanged(userData.ID); } } } ChannelSession.PreMadeChatCommands.Clear(); foreach (PreMadeChatCommand command in ReflectionHelper.CreateInstancesOfImplementingType <PreMadeChatCommand>()) { #pragma warning disable CS0612 // Type or member is obsolete if (!(command is ObsoletePreMadeCommand)) { ChannelSession.PreMadeChatCommands.Add(command); } #pragma warning restore CS0612 // Type or member is obsolete } foreach (PreMadeChatCommandSettings commandSetting in ChannelSession.Settings.PreMadeChatCommandSettings) { PreMadeChatCommand command = ChannelSession.PreMadeChatCommands.FirstOrDefault(c => c.Name.Equals(commandSetting.Name)); if (command != null) { command.UpdateFromSettings(commandSetting); } } ChannelSession.Services.Chat.RebuildCommandTriggers(); ChannelSession.Services.TimerService.Initialize(); await ChannelSession.Services.Moderation.Initialize(); } catch (Exception ex) { Logger.Log(ex); Logger.Log(LogLevel.Error, "Streamer Services - " + JSONSerializerHelper.SerializeToString(ex)); await DialogHelper.ShowMessage("Failed to initialize streamer-based services. If this continues, please visit the Mix It Up Discord for assistance." + Environment.NewLine + Environment.NewLine + "Error Details: " + ex.Message); return(false); } } try { ChannelSession.Services.Statistics.Initialize(); ChannelSession.Services.InputService.HotKeyPressed += InputService_HotKeyPressed; foreach (RedemptionStoreProductModel product in ChannelSession.Settings.RedemptionStoreProducts.Values) { product.ReplenishAmount(); } foreach (RedemptionStorePurchaseModel purchase in ChannelSession.Settings.RedemptionStorePurchases.ToList()) { if (purchase.State != RedemptionStorePurchaseRedemptionState.ManualRedeemNeeded) { ChannelSession.Settings.RedemptionStorePurchases.Remove(purchase); } } ChannelSession.Services.Telemetry.TrackLogin(ChannelSession.Settings.TelemetryUserID, ChannelSession.TwitchUserNewAPI?.broadcaster_type); await ChannelSession.SaveSettings(); await ChannelSession.Services.Settings.SaveLocalBackup(ChannelSession.Settings); await ChannelSession.Services.Settings.PerformAutomaticBackupIfApplicable(ChannelSession.Settings); AsyncRunner.RunBackgroundTask(sessionBackgroundCancellationTokenSource.Token, 60000, SessionBackgroundTask); } catch (Exception ex) { Logger.Log(ex); Logger.Log(LogLevel.Error, "Finalize Initialization - " + JSONSerializerHelper.SerializeToString(ex)); await DialogHelper.ShowMessage("Failed to finalize initialization. If this continues, please visit the Mix It Up Discord for assistance." + Environment.NewLine + Environment.NewLine + "Error Details: " + ex.Message); return(false); } return(true); } } catch (Exception ex) { Logger.Log(ex); Logger.Log(LogLevel.Error, "Channel Information - " + JSONSerializerHelper.SerializeToString(ex)); await DialogHelper.ShowMessage("Failed to get channel information. If this continues, please visit the Mix It Up Discord for assistance." + Environment.NewLine + Environment.NewLine + "Error Details: " + ex.Message); } return(false); }
public async Task PerformTradeCommand(UserViewModel user, IEnumerable <string> arguments = null, StreamingPlatformTypeEnum platform = StreamingPlatformTypeEnum.None) { try { if (ChannelSession.Services.Chat != null && arguments != null) { if (this.tradeReceiver == null && arguments.Count() >= 2) { UserViewModel targetUser = await SpecialIdentifierStringBuilder.GetUserFromArgument(arguments.First(), platform); if (targetUser == null) { await ChannelSession.Services.Chat.SendMessage("The specified user does not exist"); return; } int amount = 1; IEnumerable <string> itemArgs = arguments.Skip(1); UserInventoryItemModel item = this.GetItem(string.Join(" ", itemArgs)); if (item == null && itemArgs.Count() > 1) { itemArgs = itemArgs.Take(itemArgs.Count() - 1); item = this.GetItem(string.Join(" ", itemArgs)); if (item != null) { if (!int.TryParse(arguments.Last(), out amount) || amount <= 0) { await ChannelSession.Services.Chat.SendMessage("A valid amount greater than 0 must be specified"); return; } } } if (item == null) { await ChannelSession.Services.Chat.SendMessage("The item you specified does not exist"); return; } if (!this.HasAmount(user.Data, item, amount)) { await ChannelSession.Services.Chat.SendMessage(string.Format("You do not have the required {0} {1} to trade", amount, item.Name)); return; } this.tradeSender = new UserInventoryTradeModel() { User = user, Item = item, Amount = amount }; this.tradeReceiver = new UserInventoryTradeModel() { User = targetUser }; this.tradeTimeCheckToken = new CancellationTokenSource(); #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed AsyncRunner.RunBackgroundTask(this.tradeTimeCheckToken.Token, async(token) => { await Task.Delay(60000); if (!token.IsCancellationRequested) { this.tradeSender = null; this.tradeReceiver = null; this.tradeTimeCheckToken = null; await ChannelSession.Services.Chat.SendMessage("The trade could not be completed in time and was cancelled..."); } }); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed await ChannelSession.Services.Chat.SendMessage(string.Format("@{0} has started a trade with @{1} for {2} {3}. Type {4} <ITEM NAME> [AMOUNT] in chat to reply back with your offer in the next 60 seconds.", this.tradeSender.User.Username, this.tradeReceiver.User.Username, this.tradeSender.Amount, this.tradeSender.Item.Name, this.TradeCommand)); return; } else if (this.tradeSender != null && this.tradeReceiver != null && this.tradeReceiver.User.Equals(user) && this.tradeReceiver.Amount == 0 && arguments.Count() >= 1) { int amount = 1; IEnumerable <string> itemArgs = arguments.ToList(); UserInventoryItemModel item = this.GetItem(string.Join(" ", itemArgs)); if (item == null && itemArgs.Count() > 1) { itemArgs = itemArgs.Take(itemArgs.Count() - 1); item = this.GetItem(string.Join(" ", itemArgs)); if (item != null) { if (!int.TryParse(arguments.Last(), out amount) || amount <= 0) { await ChannelSession.Services.Chat.SendMessage("A valid amount greater than 0 must be specified"); return; } } } if (item == null) { await ChannelSession.Services.Chat.SendMessage("The item you specified does not exist"); return; } if (!this.HasAmount(user.Data, item, amount)) { await ChannelSession.Services.Chat.SendMessage(string.Format("You do not have the required {0} {1} to trade", amount, item.Name)); return; } this.tradeReceiver.Item = item; this.tradeReceiver.Amount = amount; await ChannelSession.Services.Chat.SendMessage(string.Format("@{0} has replied back to the offer by @{1} with {2} {3}. Type {4} in chat to accept the trade.", this.tradeReceiver.User.Username, this.tradeSender.User.Username, this.tradeReceiver.Amount, this.tradeReceiver.Item.Name, this.TradeCommand)); return; } else if (this.tradeSender != null && this.tradeReceiver != null && this.tradeReceiver.Amount > 0 && this.tradeSender.User.Equals(user)) { int senderItemMaxAmount = (this.tradeReceiver.Item.HasMaxAmount) ? this.tradeReceiver.Item.MaxAmount : this.DefaultMaxAmount; if ((this.GetAmount(this.tradeSender.User.Data, this.tradeReceiver.Item) + this.tradeReceiver.Amount) > senderItemMaxAmount) { await ChannelSession.Services.Chat.SendMessage(string.Format("You can only have {0} {1} in total", senderItemMaxAmount, this.tradeReceiver.Item.Name)); return; } int receiverItemMaxAmount = (this.tradeSender.Item.HasMaxAmount) ? this.tradeSender.Item.MaxAmount : this.DefaultMaxAmount; if ((this.GetAmount(this.tradeReceiver.User.Data, this.tradeSender.Item) + this.tradeSender.Amount) > receiverItemMaxAmount) { await ChannelSession.Services.Chat.SendMessage(string.Format("You can only have {0} {1} in total", receiverItemMaxAmount, this.tradeSender.Item.Name)); return; } this.SubtractAmount(this.tradeSender.User.Data, this.tradeSender.Item, this.tradeSender.Amount); this.AddAmount(this.tradeReceiver.User.Data, this.tradeSender.Item, this.tradeSender.Amount); this.SubtractAmount(this.tradeReceiver.User.Data, this.tradeReceiver.Item, this.tradeReceiver.Amount); this.AddAmount(this.tradeSender.User.Data, this.tradeReceiver.Item, this.tradeReceiver.Amount); if (this.ItemsTradedCommand != null) { Dictionary <string, string> specialIdentifiers = new Dictionary <string, string>(); specialIdentifiers["itemtotal"] = this.tradeSender.Amount.ToString(); specialIdentifiers["itemname"] = this.tradeSender.Item.Name; specialIdentifiers["targetitemtotal"] = this.tradeReceiver.Amount.ToString(); specialIdentifiers["targetitemname"] = this.tradeReceiver.Item.Name; await this.ItemsTradedCommand.Perform(user, arguments : new string[] { this.tradeReceiver.User.Username }, extraSpecialIdentifiers : specialIdentifiers); } this.tradeSender = null; this.tradeReceiver = null; this.tradeTimeCheckToken.Cancel(); this.tradeTimeCheckToken = null; return; } else if (this.tradeSender != null && this.tradeReceiver != null && !this.tradeReceiver.User.Equals(user)) { await ChannelSession.Services.Chat.SendMessage("A trade is already underway, please wait until it is completed"); return; } } await ChannelSession.Services.Chat.SendMessage(this.TradeCommand + " <USERNAME> <ITEM NAME> [AMOUNT] = Trades 1 or the amount specified of the item to the specified user"); } catch (Exception ex) { Logger.Log(ex); } }
public async Task <JsonResult> Install(InstallModel model) { var t = AsyncRunner.Run((c, ct, state) => InstallCore(c, (InstallModel)state), model); return(Json(await t)); }
protected virtual int ProcessPictures( ImportExecuteContext context, IEnumerable <ImportRow <Category> > batch, Dictionary <int, ImportCategoryMapping> srcToDestId) { Picture picture = null; var equalPictureId = 0; foreach (var row in batch) { try { var srcId = row.GetDataValue <int>("Id"); var urlOrPath = row.GetDataValue <string>("ImageUrl"); if (srcId != 0 && srcToDestId.ContainsKey(srcId) && urlOrPath.HasValue()) { var currentPictures = new List <Picture>(); var category = _categoryRepository.GetById(srcToDestId[srcId].DestinationId); var seoName = _pictureService.GetPictureSeName(row.EntityDisplayName); var image = CreateDownloadImage(urlOrPath, seoName, 1); if (category != null && image != null) { if (image.Url.HasValue() && !image.Success.HasValue) { AsyncRunner.RunSync(() => _fileDownloadManager.DownloadAsync(DownloaderContext, new FileDownloadManagerItem[] { image })); } if ((image.Success ?? false) && File.Exists(image.Path)) { Succeeded(image); var pictureBinary = File.ReadAllBytes(image.Path); if (pictureBinary != null && pictureBinary.Length > 0) { if (category.PictureId.HasValue && (picture = _pictureRepository.GetById(category.PictureId.Value)) != null) { currentPictures.Add(picture); } pictureBinary = _pictureService.ValidatePicture(pictureBinary); pictureBinary = _pictureService.FindEqualPicture(pictureBinary, currentPictures, out equalPictureId); if (pictureBinary != null && pictureBinary.Length > 0) { if ((picture = _pictureService.InsertPicture(pictureBinary, image.MimeType, seoName, true, false, false)) != null) { category.PictureId = picture.Id; _categoryRepository.Update(category); } } else { context.Result.AddInfo("Found equal picture in data store. Skipping field.", row.GetRowInfo(), "ImageUrls"); } } } else if (image.Url.HasValue()) { context.Result.AddInfo("Download of an image failed.", row.GetRowInfo(), "ImageUrls"); } } } } catch (Exception exception) { context.Result.AddWarning(exception.ToAllMessages(), row.GetRowInfo(), "ImageUrls"); } } var num = _categoryRepository.Context.SaveChanges(); return(num); }
public FileSystemMediaStorageProvider(IMediaFileSystem fileSystem, AsyncRunner asyncRunner) { _fileSystem = fileSystem; _asyncRunner = asyncRunner; }
protected virtual int ProcessAvatars( ImportExecuteContext context, IEnumerable <ImportRow <Customer> > batch) { foreach (var row in batch) { var urlOrPath = row.GetDataValue <string>("AvatarPictureUrl"); if (urlOrPath.IsEmpty()) { continue; } var equalPictureId = 0; var currentPictures = new List <Picture>(); var seoName = _pictureService.GetPictureSeName(row.EntityDisplayName); var image = CreateDownloadImage(urlOrPath, seoName, 1); if (image == null) { continue; } if (image.Url.HasValue() && !image.Success.HasValue) { AsyncRunner.RunSync(() => _fileDownloadManager.DownloadAsync(DownloaderContext, new FileDownloadManagerItem[] { image })); } if ((image.Success ?? false) && File.Exists(image.Path)) { Succeeded(image); var pictureBinary = File.ReadAllBytes(image.Path); if (pictureBinary != null && pictureBinary.Length > 0) { var pictureId = row.Entity.GetAttribute <int>(SystemCustomerAttributeNames.AvatarPictureId); if (pictureId != 0) { var picture = _pictureRepository.TableUntracked.Expand(x => x.MediaStorage).FirstOrDefault(x => x.Id == pictureId); if (picture != null) { currentPictures.Add(picture); } } var size = Size.Empty; pictureBinary = _pictureService.ValidatePicture(pictureBinary, image.MimeType, out size); pictureBinary = _pictureService.FindEqualPicture(pictureBinary, currentPictures, out equalPictureId); if (pictureBinary != null && pictureBinary.Length > 0) { var picture = _pictureService.InsertPicture(pictureBinary, image.MimeType, seoName, true, size.Width, size.Height, false); if (picture != null) { SaveAttribute(row, SystemCustomerAttributeNames.AvatarPictureId, picture.Id); } } else { context.Result.AddInfo("Found equal picture in data store. Skipping field.", row.GetRowInfo(), "AvatarPictureUrl"); } } } else { context.Result.AddInfo("Download of an image failed.", row.GetRowInfo(), "AvatarPictureUrl"); } } return(_services.DbContext.SaveChanges()); }
private void ProcessProductPictures(IImportExecuteContext context, ImportRow <Product>[] batch) { // true, cause pictures must be saved and assigned an id prior adding a mapping. _productPictureRepository.AutoCommitEnabled = true; ProductPicture lastInserted = null; var equalPictureId = 0; foreach (var row in batch) { var imageUrls = row.GetDataValue <List <string> >("ImageUrls"); if (imageUrls == null || !imageUrls.Any()) { continue; } var imageNumber = 0; var displayOrder = -1; var seoName = _pictureService.GetPictureSeName(row.EntityDisplayName); var imageFiles = new List <FileDownloadManagerItem>(); // collect required image file infos foreach (var urlOrPath in imageUrls) { var image = CreateDownloadImage(urlOrPath, seoName, ++imageNumber); if (image != null) { imageFiles.Add(image); } } // download images if (imageFiles.Any(x => x.Url.HasValue())) { // async downloading in batch processing is inefficient cause only the image processing benefits from async, // not the record processing itself. a per record processing may speed up the import. AsyncRunner.RunSync(() => _fileDownloadManager.DownloadAsync(DownloaderContext, imageFiles.Where(x => x.Url.HasValue() && !x.Success.HasValue))); } // import images foreach (var image in imageFiles.OrderBy(x => x.DisplayOrder)) { try { if ((image.Success ?? false) && File.Exists(image.Path)) { Succeeded(image); var pictureBinary = File.ReadAllBytes(image.Path); if (pictureBinary != null && pictureBinary.Length > 0) { var currentProductPictures = _productPictureRepository.TableUntracked.Expand(x => x.Picture) .Where(x => x.ProductId == row.Entity.Id) .ToList(); var currentPictures = currentProductPictures .Select(x => x.Picture) .ToList(); if (displayOrder == -1) { displayOrder = (currentProductPictures.Any() ? currentProductPictures.Select(x => x.DisplayOrder).Max() : 0); } pictureBinary = _pictureService.ValidatePicture(pictureBinary); pictureBinary = _pictureService.FindEqualPicture(pictureBinary, currentPictures, out equalPictureId); if (pictureBinary != null && pictureBinary.Length > 0) { // no equal picture found in sequence var newPicture = _pictureService.InsertPicture(pictureBinary, image.MimeType, seoName, true, false, false); if (newPicture != null) { var mapping = new ProductPicture { ProductId = row.Entity.Id, PictureId = newPicture.Id, DisplayOrder = ++displayOrder }; _productPictureRepository.Insert(mapping); lastInserted = mapping; } } else { context.Result.AddInfo("Found equal picture in data store. Skipping field.", row.GetRowInfo(), "ImageUrls" + image.DisplayOrder.ToString()); } } } else if (image.Url.HasValue()) { context.Result.AddInfo("Download of an image failed.", row.GetRowInfo(), "ImageUrls" + image.DisplayOrder.ToString()); } } catch (Exception exception) { context.Result.AddWarning(exception.ToAllMessages(), row.GetRowInfo(), "ImageUrls" + image.DisplayOrder.ToString()); } } } // Perf: notify only about LAST insertion and update if (lastInserted != null) { _services.EventPublisher.EntityInserted(lastInserted); } }
/// <summary> /// Initiates the asynchronous execution of the Load operation. /// <seealso cref="Amazon.DynamoDBv2.DataModel.DynamoDBContext.Load"/> /// </summary> /// <typeparam name="T">Type to populate.</typeparam> /// <param name="hashKey">Hash key element of the target item.</param> /// <param name="rangeKey">Range key element of the target item.</param> /// <param name="cancellationToken">Token which can be used to cancel the task.</param> /// <returns>A Task that can be used to poll or wait for results, or both.</returns> public Task <T> LoadAsync <T>(object hashKey, object rangeKey, CancellationToken cancellationToken = default(CancellationToken)) { return(AsyncRunner.Run(() => LoadHelper <T>(hashKey, rangeKey, null, true), cancellationToken)); }
public void Invoke <TMessage>(ConsumerDescriptor descriptor, IConsumer consumer, ConsumeContext <TMessage> envelope) where TMessage : class { var d = descriptor; var p = descriptor.WithEnvelope ? (object)envelope : envelope.Message; var fastInvoker = FastInvoker.GetInvoker(d.Method); var items = HttpContext.Current.GetItem("ConsumerInvoker", () => new List <ConsumerDescriptor>()); items.Add(d); if (!d.FireForget && !d.IsAsync) { // The all synch case try { InvokeCore(); } catch (Exception ex) { HandleException(ex, d); } } else if (!d.FireForget && d.IsAsync) { // The awaitable Task case BeginInvoke((Task)InvokeCore(cancelToken: AsyncRunner.AppShutdownCancellationToken), EndInvoke, d); } else if (d.FireForget && !d.IsAsync) { // A synch method should be executed async (without awaiting) AsyncRunner.Run((c, ct, state) => InvokeCore(c, ct), d) .ContinueWith(t => EndInvoke(t), /*TaskContinuationOptions.OnlyOnFaulted*/ TaskContinuationOptions.None) .ConfigureAwait(false); } else if (d.FireForget && d.IsAsync) { // An async (Task) method should be executed without awaiting AsyncRunner.Run((c, ct) => (Task)InvokeCore(c, ct), d) .ContinueWith(t => EndInvoke(t), TaskContinuationOptions.OnlyOnFaulted) .ConfigureAwait(false); } object InvokeCore(IComponentContext c = null, CancellationToken cancelToken = default(CancellationToken)) { if (d.Parameters.Length == 0) { // Only one method param: the message! return(fastInvoker.Invoke(consumer, p)); } var parameters = new object[d.Parameters.Length + 1]; parameters[0] = p; int i = 0; foreach (var obj in ResolveParameters(c, d, cancelToken).ToArray()) { i++; parameters[i] = obj; } return(fastInvoker.Invoke(consumer, parameters)); } }
public override async Task CustomRun(CommandParametersModel parameters) { await this.RefundCooldown(parameters); if (this.runParameters == null) { this.runBetAmount = this.GetPrimaryBetAmount(parameters); this.runParameters = parameters; this.runUsers[parameters.User] = parameters; this.GetPrimaryCurrencyRequirement()?.SetTemporaryAmount(this.runBetAmount); #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed AsyncRunner.RunAsyncBackground(async(cancellationToken) => { await DelayNoThrow(this.TimeLimit * 1000, cancellationToken); this.runParameters.SpecialIdentifiers[HitmanGameCommandModel.GameHitmanNameSpecialIdentifier] = this.runHitmanName = await this.GetRandomWord(this.CustomWordsFilePath); if (this.runUsers.Count < this.MinimumParticipants) { await this.RunSubCommand(this.NotEnoughPlayersCommand, this.runParameters); foreach (var kvp in this.runUsers.ToList()) { await this.Requirements.Refund(kvp.Value); } await this.PerformCooldown(this.runParameters); this.ClearData(); return; } await this.RunSubCommand(this.HitmanApproachingCommand, this.runParameters); await DelayNoThrow(5000, cancellationToken); GlobalEvents.OnChatMessageReceived += GlobalEvents_OnChatMessageReceived; await this.RunSubCommand(this.HitmanAppearsCommand, this.runParameters); for (int i = 0; i < this.HitmanTimeLimit && this.gameActive; i++) { await DelayNoThrow(1000, cancellationToken); } GlobalEvents.OnChatMessageReceived -= GlobalEvents_OnChatMessageReceived; if (this.gameActive && !string.IsNullOrEmpty(this.runHitmanName)) { await this.RunSubCommand(this.UserFailureCommand, this.runParameters); await this.PerformCooldown(this.runParameters); } this.gameActive = false; this.ClearData(); }, new CancellationToken()); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed this.gameActive = true; await this.RunSubCommand(this.StartedCommand, this.runParameters); await this.RunSubCommand(this.UserJoinCommand, this.runParameters); return; } else if (string.IsNullOrEmpty(this.runHitmanName) && !this.runUsers.ContainsKey(parameters.User)) { this.runUsers[parameters.User] = parameters; await this.RunSubCommand(this.UserJoinCommand, parameters); return; } else { await ChannelSession.Services.Chat.SendMessage(MixItUp.Base.Resources.GameCommandAlreadyUnderway); } await this.Requirements.Refund(parameters); }
protected override async Task PerformInternal(CommandParametersModel parameters) { if (!this.runUsers.ContainsKey(parameters.User)) { string betType = parameters.Arguments[0].ToLower(); this.runUsers[parameters.User] = parameters; if (this.runParameters == null) { this.runParameters = parameters; #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed AsyncRunner.RunAsyncBackground(async(cancellationToken) => { await DelayNoThrow(this.TimeLimit * 1000, cancellationToken); if (this.runUsers.Count < this.MinimumParticipants) { await this.NotEnoughPlayersCommand.Perform(this.runParameters); foreach (var kvp in this.runUsers.ToList()) { await this.Requirements.Refund(kvp.Value); } await this.PerformCooldown(this.runParameters); this.ClearData(); return; } string winningBetType = this.BetOptions.Random(); List <CommandParametersModel> winners = new List <CommandParametersModel>(); int totalPayout = 0; foreach (CommandParametersModel participant in this.runUsers.Values.ToList()) { participant.SpecialIdentifiers[RouletteGameCommandModel.GameRouletteWinningBetTypeSpecialIdentifier] = winningBetType; if (string.Equals(winningBetType, participant.Arguments[0], StringComparison.CurrentCultureIgnoreCase)) { winners.Add(participant); totalPayout += await this.PerformOutcome(participant, this.UserSuccessOutcome); } else { await this.UserFailureCommand.Perform(participant); } } this.runParameters.SpecialIdentifiers[GameCommandModelBase.GameWinnersCountSpecialIdentifier] = winners.Count.ToString(); this.runParameters.SpecialIdentifiers[GameCommandModelBase.GameWinnersSpecialIdentifier] = string.Join(", ", winners.Select(u => "@" + u.User.Username)); this.runParameters.SpecialIdentifiers[GameCommandModelBase.GameAllPayoutSpecialIdentifier] = totalPayout.ToString(); this.runParameters.SpecialIdentifiers[RouletteGameCommandModel.GameRouletteWinningBetTypeSpecialIdentifier] = winningBetType; await this.GameCompleteCommand.Perform(this.runParameters); await this.PerformCooldown(this.runParameters); this.ClearData(); }, new CancellationToken()); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed this.runParameters.SpecialIdentifiers[RouletteGameCommandModel.GameRouletteValidBetTypesSpecialIdentifier] = this.GetValidBetTypes(); await this.StartedCommand.Perform(this.runParameters); } parameters.SpecialIdentifiers[RouletteGameCommandModel.GameRouletteBetTypeSpecialIdentifier] = betType; await this.UserJoinCommand.Perform(parameters); return; } else { await ChannelSession.Services.Chat.SendMessage(MixItUp.Base.Resources.GameCommandAlreadyUnderway); } await this.Requirements.Refund(parameters); }
private void RunContinuation(Task<Status> t, IScopedHandler handler, IContext context, AsyncRunner runner) { try { if (t.IsFaulted && t.Exception != null) { new ErrorHelper(context).WriteError(t.Exception.InnerException); } else { try { runner.End(handler.Handler, context, t.Result); } catch (Exception ex) { new ErrorHelper(context).WriteError(ex); } } } finally { handler.Dispose(); } }
protected override async Task PerformInternal(CommandParametersModel parameters) { if (this.runParameters == null) { this.runBetAmount = this.GetPrimaryBetAmount(parameters); this.runParameters = parameters; this.runUsers[parameters.User] = parameters; this.GetPrimaryCurrencyRequirement().SetTemporaryAmount(this.runBetAmount); #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed AsyncRunner.RunAsyncBackground(async(cancellationToken) => { await DelayNoThrow(this.TimeLimit * 1000, cancellationToken); if (this.runUsers.Count < this.MinimumParticipants) { await this.NotEnoughPlayersCommand.Perform(this.runParameters); foreach (var kvp in this.runUsers.ToList()) { await this.Requirements.Refund(kvp.Value); } await this.PerformCooldown(this.runParameters); this.ClearData(); return; } IEnumerable <CommandParametersModel> shuffledParticipants = this.runUsers.Values.Shuffle(); this.runUserTypes[shuffledParticipants.ElementAt(0).User] = WinLosePlayerType.King; double thiefDecimalPercentage = ((double)this.ThiefPlayerPercentage) / 100.0; int totalThieves = (int)Math.Ceiling(thiefDecimalPercentage * (double)shuffledParticipants.Count()); foreach (CommandParametersModel participant in shuffledParticipants.Skip(1).Take(totalThieves)) { this.runUserTypes[participant.User] = WinLosePlayerType.Thief; } foreach (CommandParametersModel participant in shuffledParticipants.Skip(1 + totalThieves)) { this.runUserTypes[participant.User] = WinLosePlayerType.Knight; } foreach (CommandParametersModel participant in shuffledParticipants) { if (this.runUserTypes[participant.User] == WinLosePlayerType.Thief) { await this.ThiefUserCommand.Perform(participant); } else if (this.runUserTypes[participant.User] == WinLosePlayerType.Thief) { await this.ThiefUserCommand.Perform(participant); } } await this.KingUserCommand.Perform(shuffledParticipants.ElementAt(0)); await DelayNoThrow(this.KingTimeLimit * 1000, cancellationToken); if (this.gameActive && this.runParameters != null) { await this.PerformCooldown(this.runParameters); this.ClearData(); } this.gameActive = false; }, new CancellationToken()); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed this.gameActive = true; await this.StartedCommand.Perform(this.runParameters); await this.UserJoinCommand.Perform(this.runParameters); return; } else if (this.runParameters != null) { if (this.runUserTypes.Count > 0 && this.runUserTypes[parameters.User] == WinLosePlayerType.King) { await parameters.SetTargetUser(); if (parameters.TargetUser != null && this.runUserTypes.ContainsKey(parameters.TargetUser)) { this.gameActive = false; WinLosePlayerType selectedType = (this.runUserTypes[parameters.TargetUser] == WinLosePlayerType.Knight) ? WinLosePlayerType.Knight : WinLosePlayerType.Thief; var winners = (selectedType == WinLosePlayerType.Knight) ? this.runUserTypes.Where(kvp => kvp.Value != WinLosePlayerType.Thief) : this.runUserTypes.Where(kvp => kvp.Value == WinLosePlayerType.Thief); IEnumerable <CommandParametersModel> winnerParameters = winners.Select(kvp => this.runUsers[kvp.Key]); int payout = this.runBetAmount * this.runUsers.Count; int individualPayout = payout / winnerParameters.Count(); foreach (CommandParametersModel winner in winnerParameters) { this.PerformPrimarySetPayout(winner.User, individualPayout); } parameters.SpecialIdentifiers[GameCommandModelBase.GamePayoutSpecialIdentifier] = individualPayout.ToString(); parameters.SpecialIdentifiers[GameCommandModelBase.GameAllPayoutSpecialIdentifier] = payout.ToString(); parameters.SpecialIdentifiers[GameCommandModelBase.GameWinnersCountSpecialIdentifier] = winnerParameters.Count().ToString(); parameters.SpecialIdentifiers[GameCommandModelBase.GameWinnersSpecialIdentifier] = string.Join(", ", winnerParameters.Select(u => "@" + u.User.Username)); if (selectedType == WinLosePlayerType.Knight) { await this.KnightSelectedCommand.Perform(parameters); } else { await this.ThiefSelectedCommand.Perform(parameters); } await this.PerformCooldown(this.runParameters); this.ClearData(); } else { await ChannelSession.Services.Chat.SendMessage(MixItUp.Base.Resources.GameCommandCouldNotFindUser); } } else if (!this.runUsers.ContainsKey(parameters.User)) { this.runUsers[parameters.User] = parameters; await this.UserJoinCommand.Perform(parameters); return; } } else { await ChannelSession.Services.Chat.SendMessage(MixItUp.Base.Resources.GameCommandAlreadyUnderway); } await this.Requirements.Refund(parameters); }