public async Task <IActionResult> PostAsync([FromBody] CouponRequest model, CancellationToken token) { var userId = _userManager.GetLongUserId(User); try { var command = new CreateCouponCommand(model.Code, model.CouponType, userId, model.Value, model.Expiration); await _commandBus.DispatchAsync(command, token); } catch (DuplicateRowException) { return(BadRequest("This coupon already exists")); } catch (SqlConstraintViolationException) { return(BadRequest("User need to be a tutor")); } catch (ArgumentOutOfRangeException) { return(BadRequest("Inavlid Value")); } catch (ArgumentException) { return(BadRequest("Value can not be more then 100%")); } return(Ok()); }
public override async Task OnConnectedAsync() { var httpContext = Context.GetHttpContext(); var request = httpContext.Request; var cookieVal = request.Query[QueryStringName].ToString(); if (string.IsNullOrEmpty(cookieVal)) { return; } var roomId = Guid.Parse(cookieVal); var userId = long.Parse(Context.UserIdentifier); var command = new ChangeStudyRoomOnlineStatusCommand(userId, true, roomId); await Clients.All.SendAsync("Online", userId); await Groups.AddToGroupAsync(Context.ConnectionId, cookieVal); await _commandBus.DispatchAsync(command, default); await base.OnConnectedAsync(); }
public async Task <IActionResult> CreateAsync([FromBody] CreateSubjectRequest request, CancellationToken token) { var command = new CreateSubjectCommand(request.EnSubjectName, request.HeSubjectName); await _commandBus.DispatchAsync(command, token); return(Ok()); }
public async Task <IActionResult> ApproveCourse([FromBody] ApproveCourseRequest model, CancellationToken token) { var command = new ApproveCourseCommand(model.Course, model.Subject, model.SchoolType); await _commandBus.DispatchAsync(command, token); return(Ok()); }
public async Task <IActionResult> ApproveTutorAsync([FromBody] ApproveTutorRequest model, CancellationToken token) { var command = new ApproveTutorCommand(model.Id); await _commandBus.DispatchAsync(command, token); return(Ok()); }
public async Task <ActionResult> DeleteAnswerAsync([FromQuery(Name = "id")] IEnumerable <Guid> ids, CancellationToken token) { foreach (var id in ids) { var command = new DeleteAnswerCommand(id); await _commandBus.DispatchAsync(command, token); } return(Ok()); }
public async Task <IActionResult> Delete([FromQuery(Name = "id"), MaxLength(200)] IEnumerable <long> ids, CancellationToken token) { foreach (var id in ids) { var command = new DeleteDocumentCommand(id); await _commandBus.DispatchAsync(command, token); } return(Ok()); }
public async Task <IActionResult> AssignUniversityAsync([FromBody] AssignUniversityRequest model, CancellationToken token) { var userId = _userManager.GetLongUserId(User); var command = new UserJoinUniversityCommand(userId, model.Id !.Value); await _commandBus.DispatchAsync(command, token); var user = await _userManager.GetUserAsync(User); await _signInManager.RefreshSignInAsync(user); return(Ok()); }
public async Task <IActionResult> SetCoursesAsync([FromBody] SetCourseRequest[] model, CancellationToken token) { var userId = _userManager.GetLongUserId(User); var command = new UserJoinCoursesCommand(model.Select(s => s.Name), userId); await _commandBus.DispatchAsync(command, token); var user = await _userManager.GetUserAsync(User); await _signInManager.RefreshSignInAsync(user); return(Ok(model)); }
public async Task <IActionResult> PostAsync([FromBody] ChatMessageRequest model, CancellationToken token) { var userId = _userManager.GetLongUserId(User); if (userId == model.OtherUser) { return(BadRequest()); } var command = new SendChatTextMessageCommand(model.Message, userId, model.OtherUser); await _commandBus.DispatchAsync(command, token); return(Ok()); }
public async Task UpdateDurationAsync(long id, IBinder binder, CancellationToken token) { //var id = RegEx.NumberExtractor.Match(assetName).Value; var containerName = await _videoService.GetAssetContainerAsync(id, AssetType.Long, token); var container = await binder.BindAsync <CloudBlobContainer>(new BlobAttribute(containerName), token); var blobs = await container.ListBlobsSegmentedAsync(null, null); var blob = blobs.Results.OfType <CloudBlockBlob>() .First(f => f.Name.EndsWith("manifest.json")); var str = await blob.DownloadTextAsync(); dynamic json = JToken.Parse(str); string durationXml = json.AssetFile[0].Duration; var v = XmlConvert.ToTimeSpan(durationXml); var blobDirectoryFiles = await binder.BindAsync <IEnumerable <CloudBlockBlob> >(new BlobAttribute($"spitball-files/files/{id}"), token); var originalVideoBlob = blobDirectoryFiles.Single(s => s.Name.Contains("/file-", StringComparison.OrdinalIgnoreCase)); var url = originalVideoBlob.GetDownloadLink(TimeSpan.FromHours(1)); await _videoService.CreatePreviewJobAsync(id, url.AbsoluteUri, v, token); var command = UpdateDocumentMetaCommand.Video(id, v); await _commandBus.DispatchAsync(command, token); }
public async Task <SuspendUserResponse> SuspendUserAsync(SuspendUserRequest model, [FromServices] ICommandBus commandBus, CancellationToken token) { foreach (var id in model.Ids) { DateTimeOffset lockout; switch (model.SuspendTime) { case SuspendTime.Day: lockout = DateTimeOffset.Now.AddSeconds(TimeConst.Day); break; case SuspendTime.Week: lockout = DateTimeOffset.Now.AddSeconds(TimeConst.Day * 7); break; case SuspendTime.Undecided: lockout = DateTimeOffset.MaxValue; break; case null: lockout = DateTimeOffset.MaxValue; break; default: throw new ArgumentOutOfRangeException(); } var command = new SuspendUserCommand(id, lockout, model.Reason); await commandBus.DispatchAsync(command, token); } return(new SuspendUserResponse()); }
public static async Task Run([TimerTrigger("0 0 0 28-31 * *")] TimerInfo myTimer, [Inject] ICommandBus commandBus, CancellationToken token) { var command = new UpdateCreditCardExpiredCommand(); await commandBus.DispatchAsync(command, token); }
public async Task<IActionResult> SetSessionDurationAsync([FromBody] SetSessionDurationRequest model, CancellationToken token) { var userId = _userManager.GetLongUserId(User); var command = new SetSessionDurationCommand(userId, model.SessionId, TimeSpan.FromMinutes(model.RealDuration)); await _commandBus.DispatchAsync(command, token); return Ok(); }
public async Task <ActionResult <ShortUrlDto> > AddShortUrlAsync([FromBody] AddShortUrlRequest model, CancellationToken token) { var destinationTest = Uri.TryCreate(model.Destination, UriKind.Absolute, out var _); if (!destinationTest && !model.Destination.StartsWith("/") && !model.Destination.StartsWith("www")) { model.Destination = $"/{model.Destination}"; } var command = new CreateShortUrlCommand(model.Identifier, model.Destination, model.Expiration); try { await _commandBus.DispatchAsync(command, token); } catch (DuplicateRowException) { return(Conflict()); } var url = $"{_configuration["Site"]}go/{model.Identifier}"; return(new ShortUrlDto(url, model.Destination, model.Expiration)); }
public async Task <IActionResult> SetChildNameAsync([FromBody] SetChildNameRequest model, [FromServices] ICommandBus commandBus, CancellationToken token) { var userId = _userManager.GetLongUserId(User); var command = new SetChildNameCommand(userId, model.Name, model.Grade); await commandBus.DispatchAsync(command, token); return(Ok()); }
public async Task <IActionResult> RedeemAsync(CancellationToken token) { try { var command = new CashOutCommand(_userManager.GetLongUserId(User) /*, model.Amount*/); await _commandBus.DispatchAsync(command, token); return(Ok()); } catch (InvalidOperationException e) { _logger.Exception(e, new Dictionary <string, string>() { ["user"] = _userManager.GetUserId(User) }); return(BadRequest()); } }
public async Task <IdentityResult> CreateAsync(User user, CancellationToken cancellationToken) { try { var command = new CreateUserCommand(user); await _bus.DispatchAsync(command, cancellationToken); return(IdentityResult.Success); } catch (DuplicateRowException) { return(IdentityResult.Failed(new IdentityError { Description = "Duplicate", Code = "Duplicate" })); } }
public static async Task UpdateChatRoomAdminStatusAsync( [TimerTrigger("0 0 0 * * *")] TimerInfo myTimer, [Inject] ICommandBus commandBus, CancellationToken token ) { var command = new UpdateChatRoomAdminStatusCommand(); await commandBus.DispatchAsync(command, token); }
public async Task <IActionResult> ChangeStatus( [FromRoute] string identifier, ChangeConversationStatusRequest model, CancellationToken token) { if (string.IsNullOrEmpty(identifier)) { return(BadRequest()); } var p = Enumeration.FromValue <ChatRoomStatus>(model.Status); var command = new ChangeConversationStatusCommand(identifier, p); await _commandBus.DispatchAsync(command, token); return(Ok()); }
public async Task <IActionResult> PayAsync([FromBody] PaymentRequest model, [FromServices] PayMeCredentials payMeCredentials, [FromServices] TelemetryClient client, CancellationToken token) { try { var command = new PaymentCommand(model.UserId, model.TutorId, model.StudentPay, model.SpitballPay, model.StudyRoomSessionId, payMeCredentials.BuyerKey, model.AdminDuration); await _commandBus.DispatchAsync(command, token); return(Ok()); } catch (HttpRequestException ex) { client.TrackException(ex, model.AsDictionary()); return(BadRequest(ex.Message)); } }
public async Task <ActionResult> PostAsync( [ModelBinder(typeof(CountryModelBinder))] string country, [FromBody] LoginRequest model, [FromHeader(Name = "User-Agent")] string agent, CancellationToken token) { var user = await _userManager.FindByEmailAsync(model.Email); if (user is null) { ModelState.AddModelError(nameof(model.Password), _localizer["BadLogin"]); return(BadRequest(ModelState)); } agent = agent?.Substring(0, Math.Min(agent.Length, 255)); var command = new AddUserLocationCommand(user, country, HttpContext.GetIpAddress(), model.FingerPrint, agent); var t1 = _commandBus.DispatchAsync(command, token); var t2 = _signInManager.CheckPasswordSignInAsync(user, model.Password, true); await Task.WhenAll(t1, t2); var result = t2.Result; if (result == SignInResult.Success) { await _userManager.ResetAccessFailedCountAsync(user); await _signInManager.SignInAsync(user, false); return(Ok(new { user.Country })); } if (result.IsLockedOut) { if (user.LockoutEnd == DateTimeOffset.MaxValue) { ModelState.AddModelError(nameof(model.Password), _localizer["LockOut"]); return(BadRequest(ModelState)); } ModelState.AddModelError(nameof(model.Password), _localizer["TempLockOut"]); return(BadRequest(ModelState)); } if (result.IsNotAllowed) { ModelState.AddModelError(nameof(model.Password), _localizer["NotAllowed"]); return(BadRequest(ModelState)); } ModelState.AddModelError(nameof(model.Password), _localizer["BadLogin"]); return(BadRequest(ModelState)); }
public async Task <IActionResult> CreateStudyRoomAsync(CreateStudyRoomRequest model, [FromServices] TelemetryClient client, CancellationToken token) { var tutorId = _userManager.GetLongUserId(User); try { var command = new CreateStudyRoomCommand(tutorId, model.UserId); await _commandBus.DispatchAsync(command, token); return(Ok()); } catch (DuplicateRowException) { return(BadRequest("Already active study room")); } catch (InvalidOperationException e) { client.TrackException(e, new Dictionary <string, string>() { ["UserId"] = model.UserId.ToString(), ["tutorId"] = tutorId.ToString() }); return(BadRequest()); } catch { return(BadRequest("User equals tutor")); } }
public static async Task QuestionPopulateAsync([TimerTrigger("0 */15 * * * *")] TimerInfo myTimer, [Inject] ICommandBus commandBus, [Inject] IQueryBus queryBus, CancellationToken token) { var questions = await queryBus.QueryAsync(new FictivePendingQuestionEmptyQuery(), token); if (questions.Count > 0) { var command = new ApproveQuestionCommand(questions.Select(s => s.Id)); await commandBus.DispatchAsync(command, token); } }
public async Task <IActionResult> ChangeLanguageAsync([FromBody] ChangeCultureRequest model, CancellationToken token) { var culture = model.Culture; Response.Cookies.Append( CookieRequestCultureProvider.DefaultCookieName, CookieRequestCultureProvider.MakeCookieValue(culture), new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) } ); if (!User.Identity.IsAuthenticated) { return(Ok()); } var userId = _userManager.GetLongUserId(User); var command = new UpdateUserCultureCommand(userId, culture.Culture.Name); await _commandBus.DispatchAsync(command, token); return(Ok()); }
public async Task DoOperationAsync(RequestTutorMessage message2, IBinder binder, CancellationToken token) { if (_configuration.Search.IsDevelop) //if (bool.Parse(_configuration["IsDevelop"])) { _email = "*****@*****.**"; } var query = new RequestTutorAdminEmailQuery(message2.LeadId); var result = await _queryBus.QueryAsync(query, token); if (result == null) { return; } foreach (var obj in result) { var code = _dataProtectionService.ProtectData(obj.UserId.ToString(), DateTimeOffset.UtcNow.AddDays(5)); var identifierChat = ShortId.Generate(true, false); var url = _urlBuilder.BuildChatEndpoint(code, new { utm_source = "request-tutor-admin-email" }); var commandChat = new CreateShortUrlCommand(identifierChat, url.PathAndQuery, DateTime.UtcNow.AddDays(5)); await _commandBus.DispatchAsync(commandChat, token); var whatsAppLink = new UriBuilder($"https://wa.me/{obj.UserPhone.Replace("+", string.Empty)}") .AddQuery(new { text = $"שובץ לך מורה ל{obj.CourseName} בשם {obj.TutorName}. לשוחח עם המורה לחץ {_urlBuilder.BuildShortUrlEndpoint(identifierChat)}" }); string body = whatsAppLink.ToString(); var message = new SendGridMessage() { Subject = "New Tutor request", HtmlContent = $"<html><body>{body.Replace(Environment.NewLine, "<br><br>")}</body></html>" }; message.AddTo(_email); var emailProvider = await binder.BindAsync <IAsyncCollector <SendGridMessage> >(new SendGridAttribute() { ApiKey = "SendgridKey", From = "Spitball <*****@*****.**>" }, token); await emailProvider.AddAsync(message, token); await emailProvider.FlushAsync(token); } }
public async Task <IActionResult> CreateAnswerAsync([FromBody] CreateAnswerRequest model, CancellationToken token) { var userId = _userManager.GetLongUserId(User); try { var command = new CreateAnswerCommand(model.QuestionId, model.Text, userId); await _commandBus.DispatchAsync(command, token); return(Ok()); } catch (QuotaExceededException) { ModelState.AddModelError(nameof(model.Text), _localizer["You exceed your quota of answers"]); return(BadRequest(ModelState)); } catch (ArgumentException) { ModelState.AddModelError(nameof(model.Text), _localizer["QuestionNotExists"]); return(BadRequest(ModelState)); } }
private async Task <IActionResult> FinishRegistrationAsync(User user, string country, string fingerPrint, string userAgent, CancellationToken token) { if (TempData[HomeController.Referral] != null) { if (Base62.TryParse(TempData[HomeController.Referral].ToString(), out var base62)) { try { var command = new ReferringUserCommand(base62, user.Id); await _commandBus.DispatchAsync(command, token); } catch (UserLockoutException) { _logger.Warning($"{user.Id} got locked referring user {TempData[HomeController.Referral]}"); } } else { _logger.Error($"{user.Id} got wrong referring user {TempData[HomeController.Referral]}"); } TempData.Remove(HomeController.Referral); } TempData.Clear(); var command2 = new AddUserLocationCommand(user, country, HttpContext.GetIpAddress(), fingerPrint, userAgent); var registrationBonusCommand = new FinishRegistrationCommand(user.Id); var t1 = _commandBus.DispatchAsync(command2, token); var t2 = _signInManager.SignInAsync(user, false); var t3 = _commandBus.DispatchAsync(registrationBonusCommand, token); await Task.WhenAll(t1, t2, t3); return(Ok(new { user.Id })); }
public async Task <IActionResult> CreateQuestionAsync([FromBody] CreateQuestionRequest model, [FromServices] IHubContext <SbHub> hubContext, CancellationToken token) { var userId = _userManager.GetLongUserId(User); var toasterMessage = _localizer["PostedQuestionToasterOk"]; try { var command = new CreateQuestionCommand(model.Text, userId, model.Course); await _commandBus.DispatchAsync(command, token); } catch (DuplicateRowException) { toasterMessage = _localizer["PostedQuestionToasterDuplicate"]; } catch (SqlConstraintViolationException) { toasterMessage = _localizer["PostedQuestionToasterCourseNotExists"]; //Console.WriteLine(e); //throw; } await hubContext.Clients.User(userId.ToString()).SendCoreAsync("Message", new object[] { new SignalRTransportType(SignalRType.System, SignalREventAction.Toaster, new { text = toasterMessage.Value } ) }, token); return(Ok()); }
public async Task <ActionResult> DownloadAsync(long id, [FromServices] ICommandBus commandBus, [FromServices] IBlobProvider blobProvider2, CancellationToken token) { var user = _userManager.GetLongUserId(User); var query = new DocumentById(id, user); var tItem = _queryBus.QueryAsync(query, token); var tFiles = _blobProvider.FilesInDirectoryAsync("file-", id.ToString(), token); await Task.WhenAll(tItem, tFiles); var item = tItem.Result; if (item == null) { return(NotFound()); } if (item.Document.DocumentType == DocumentType.Video) { return(Unauthorized()); } if (!item.IsPurchased) { return(Unauthorized()); } var files = tFiles.Result; var uri = files.First(); var file = uri.Segments.Last(); Task followTask = Task.CompletedTask; //blob.core.windows.net/spitball-files/files/6160/file-82925b5c-e3ba-4f88-962c-db3244eaf2b2-advanced-linux-programming.pdf if (item.Document.User.Id != user) { var command = new DownloadDocumentCommand(item.Document.Id, user); //var command = new FollowUserCommand(item.Document.User.Id, user); followTask = commandBus.DispatchAsync(command, token); } var messageTask = _queueProvider.InsertMessageAsync(new UpdateDocumentNumberOfDownloads(id), token); await Task.WhenAll(followTask, messageTask); var nameToDownload = item.Document.Title; var extension = Path.GetExtension(file); var url = blobProvider2.GenerateDownloadLink(uri, TimeSpan.FromMinutes(30), nameToDownload + extension); return(Redirect(url.AbsoluteUri)); }