public async Task <UrlResponse> CreateShortUrlAsync(UrlModel urlModel) { string urlTemp = urlModel.UrlString; if (!CheckValidUrl(ref urlTemp)) { return(new UrlResponse() { IsSuccessful = false, ErrorMessage = "String passed is not an URL. Please try again" }); } urlModel.UrlString = urlTemp; var authState = await _authenticationStateProvider.GetAuthenticationStateAsync(); var user = authState.User; DateTime?discardDate = GetDiscardDateFromUserType(user); //if(urlModel.ShortRelativeUrl == null || !user.IsInRole("premium")) //{ // //If redirect url already exists in the database return it's short url. Update creation date // var temp = await _context.UrlEntries.FirstOrDefaultAsync(url => url.RedirectUrl == urlModel.UrlString); // if (temp != null) // { // temp.DiscardDate = discardDate; // _context.Update(temp); // await _context.SaveChangesAsync(); // return new UrlResponse(temp.ShortUrl); // } //} var urlEntry = new UrlEntry(); urlEntry.DiscardDate = discardDate; urlEntry.RedirectUrl = urlModel.UrlString; if (urlModel.ShortRelativeUrl != null && user.IsInRole("premium")) { if (_reservedShortLinks.Contains(urlModel.ShortRelativeUrl)) { return(new UrlResponse() { IsSuccessful = false, ErrorMessage = "Reserved short URL, please try another one" }); } if (_context.UrlEntries.Where(url => url.ShortUrl == urlModel.ShortRelativeUrl).Any()) { return(new UrlResponse() { IsSuccessful = false, ErrorMessage = "Passed short URL is already taken" }); } else { urlEntry.ShortUrl = urlModel.ShortRelativeUrl; } } else { //Generate new short url for the url. If it already exists => retry until success do { urlEntry.ShortUrl = GenerateShortUrl(); } while (_context.UrlEntries.Where(url => url.ShortUrl == urlEntry.ShortUrl).Any() || _reservedShortLinks.Contains(urlEntry.ShortUrl)); } urlEntry.OwnerId = user.Identity.Name; if (!user.Identity.IsAuthenticated) { urlEntry.ShowAds = true; urlEntry.OwnerId = ""; } _context.UrlEntries.Add(urlEntry); await _context.SaveChangesAsync(); return(new UrlResponse(urlEntry.ShortUrl)); }
public UrlEntryResponse(UrlEntry result) { Result = result; IsSuccessful = true; }