Esempio n. 1
0
        public async Task GetUrlByCode_ReturnsActualUrlAsync()
        {
            //arrange
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase($"Db{Guid.NewGuid()}")
                          .Options;

            using (var context = new ApplicationDbContext(options))
            {
                var urlService = new UrlService(urlServiceOption.Object, logger.Object, context);

                //act
                var entity = new ShortenedUrl()
                {
                    Id           = Guid.NewGuid(),
                    Code         = await urlService.GetRandomCode(),
                    Url          = "https://github.com/alibghz",
                    CreatedAtUtc = DateTime.UtcNow,
                };
                context.Add(entity);
                context.SaveChanges();
                var url = await urlService.GetUrlByCode(entity.Code);

                //assert
                Assert.True(url == entity.Url);
            }
        }
Esempio n. 2
0
        private static void InitDefaultData_ShortenedUrls(ShortenedUrlContext context)
        {
            if (context.ShortenedUrls.Any())
            {
                return;
            }

            var shortenedUrls = new ShortenedUrl[]
            {
                new ShortenedUrl {
                    ShortenedPath = "TES1", TargetUrl = "http://www.google.com", LastUseTime = new DateTime(2019, 3, 1, 1, 2, 3), UseCount = 3
                },
                new ShortenedUrl {
                    ShortenedPath = "TES2", TargetUrl = "http://www.apple.com", LastUseTime = new DateTime(2019, 2, 28, 9, 30, 0), UseCount = 1
                },
                new ShortenedUrl {
                    ShortenedPath = "TES3", TargetUrl = "http://www.youtube.com", LastUseTime = new DateTime(2019, 2, 28, 19, 31, 12), UseCount = 2
                },
            };

            foreach (var shortenedUrl in shortenedUrls)
            {
                context.ShortenedUrls.Add(shortenedUrl);
            }
            context.SaveChanges();
        }
Esempio n. 3
0
        public AjaxResponseData AddNew(string text)
        {
            var response = new AjaxResponseData();

            if (IsValidUrl(text))
            {
                Uri    requestUrl  = HttpContext.Current.Request.Url;
                string requesthost = string.Format("{0}{1}{2}{3}",
                                                   requestUrl.Scheme,
                                                   Uri.SchemeDelimiter,
                                                   requestUrl.Authority,
                                                   "/");
                var entities = new UrlShortenerContext();
                var data     = new ShortenedUrl();
                data.OriginalUrl = text;
                entities.ShortUrls.Add(data);
                entities.SaveChanges();
                response.Success = true;
                response.Data    = requesthost + data.Id;
            }
            else
            {
                response.Success = false;
                response.Data    = "Please enter valid URL";
            }
            return(response);
        }
        public async ValueTask <ShortenedUrl> Create(ShortenedUrl shortenedUrl, CancellationToken cancellationToken = default(CancellationToken))
        {
            var entity = _dbContext.ShortenedUrls.Add(shortenedUrl);
            await _dbContext.SaveChangesAsync(cancellationToken);

            return(entity.Entity);
        }
Esempio n. 5
0
        public async Task <ShortenedUrl> AddShortenedUrlAsync(ShortenedUrl newShortenedUrl)
        {
            _dbContext.ShortenedUrls.Add(newShortenedUrl);
            await _dbContext.SaveChangesAsync();

            return(newShortenedUrl);
        }
Esempio n. 6
0
        public async Task <string> GetCodeByUrl(string url)
        {
            if (string.IsNullOrWhiteSpace(url))
            {
                throw new Exception("Empty Url");
            }

            if (!IsValidUrl(url))
            {
                throw new Exception("Invalid Url");
            }

            var code = await context.ShortenedUrls
                       .Where(x => x.Url == url)
                       .Select(x => x.Code)
                       .AsNoTracking().FirstOrDefaultAsync();

            if (string.IsNullOrWhiteSpace(code))
            {
                code = await GetRandomCode();

                var entity = new ShortenedUrl()
                {
                    Id = Guid.NewGuid(), Url = url, Code = code
                };
                context.Add(entity);
                await context.SaveChangesAsync();
            }
            return(code);
        }
Esempio n. 7
0
        public void Shortened_url_should_have_zero_visits_after_creation()
        {
            var url          = "https://foo.bar";
            var shortenedUrl = new ShortenedUrl(url);

            Assert.That(shortenedUrl.VisitCount, Is.Zero);
        }
        public async Task <IActionResult> ShortenUrl(string longUrl)
        {
            // get shortened url collection
            var shortenedUrlCollection = mongoDatabase.GetCollection <ShortenedUrl>("shortened-urls");
            // first check if we have the url stored
            var shortenedUrl = await shortenedUrlCollection
                               .AsQueryable()
                               .FirstOrDefaultAsync(x => x.OriginalUrl == longUrl);

            // if the long url has not been shortened
            if (shortenedUrl == null)
            {
                var shortCode = ShortId.Generate(length: 8);
                shortenedUrl = new ShortenedUrl
                {
                    CreatedAt   = DateTime.UtcNow,
                    OriginalUrl = longUrl,
                    ShortCode   = shortCode,
                    ShortUrl    = $"{ServiceUrl}?u={shortCode}"
                };
                // add to database
                await shortenedUrlCollection.InsertOneAsync(shortenedUrl);
            }

            return(View(shortenedUrl));
        }
        public async Task <ActionResult <ShortenedUrl> > PostShortenedUrl(ShortenedUrl shortenedUrl)
        {
            shortenedUrl.ShortenedLinkId = Guid.NewGuid().ToString();
            _context.ShortenedUrls.Add(shortenedUrl);
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (ShortenedUrlExists(shortenedUrl.ShortenedLinkId))
                {
                    return(Conflict());
                }
                else
                {
                    throw;
                }
            }


            String baseUrl = string.Format("{0}://{1}{2}/", Request.Scheme, Request.Host, Request.Path);

            shortenedUrl.ShortUrl = baseUrl + shortenedUrl.ShortenedLinkId;

            return(CreatedAtAction("GetShortenedUrl", new { id = shortenedUrl.ShortenedLinkId }, shortenedUrl));
        }
Esempio n. 10
0
        public int Save(ShortenedUrl shortUrl)
        {
            _context.ShortUrls.Add(shortUrl);
            _context.SaveChanges();

            return(shortUrl.Id);
        }
Esempio n. 11
0
        public ActionResult Create(ShortenedUrl shortUrl)
        {
            ModelError shortTokenError = EnsureValidShortToken(shortUrl);

            if (shortTokenError != null)
            {
                ModelState.AddModelError("ShortToken", shortTokenError.ErrorMessage);
            }

            if (ModelState.IsValid)
            {
                shortUrl.TargetUrl = EnsureHasHttpScheme(shortUrl.TargetUrl);
                if (IsValidUri(shortUrl.TargetUrl) == false)
                {
                    ModelState.AddModelError("TargetUrl", "That isn't a valid URL");
                    return(View(shortUrl));
                }

                shortUrl.CreatedBy    = HttpContext.User.Identity.Name;
                shortUrl.CreatedOnUTC = DateTime.UtcNow;
                webApi.CreateNewUrl(shortUrl);

                return(RedirectToAction("Index"));
            }
            else
            {
                return(View("Index", shortUrl));
            }
        }
Esempio n. 12
0
        public IActionResult ShortenUrl(string url)
        {
            if (url.IsValidUrl())
            {
                ShortenedUrl newUrl = ShortenerHelper.ShortenUrl(_dbContext, url, _config.ShortenerConfig.UrlLength);

                if (User.Identity.IsAuthenticated)
                {
                    Users.Models.User foundUser = UserHelper.GetUser(_dbContext, User.Identity.Name);
                    if (foundUser != null)
                    {
                        newUrl.UserId = foundUser.UserId;
                    }
                }

                _dbContext.ShortenedUrls.Add(newUrl);
                _dbContext.SaveChanges();

                string shortUrl = string.Format("{0}://{1}/{2}", Request.Scheme, _config.ShortenerConfig.ShortenerHost, newUrl.ShortUrl);
                if (_config.DevEnvironment)
                {
                    shortUrl = Url.SubRouteUrl("shortened", "Shortener.View", new { url = newUrl.ShortUrl });
                }

                return(Json(new { result = new { shortUrl = shortUrl, originalUrl = url } }));
            }
            return(Json(new { error = "Must be a valid Url" }));
        }
Esempio n. 13
0
        public async Task <string> ShortenUrl(string longUrl)
        {
            var existingLongUrl = await _urlRepository.SearchFirstAsync(nameof(ShortenedUrl.LongUrl), longUrl.ToLower());

            if (existingLongUrl != null)
            {
                return(existingLongUrl.ShortUrl);
            }

            while (true)
            {
                var shortUrl         = Guid.NewGuid().ToString("N").Substring(0, Constants.KeyLength);
                var existingShortUrl = await _urlRepository.SearchFirstAsync(nameof(ShortenedUrl.ShortUrl), shortUrl);

                if (existingShortUrl != null)
                {
                    continue;
                }

                var shortenedUrl = new ShortenedUrl(longUrl, shortUrl);
                await _urlRepository.AddAsync(shortenedUrl);

                return(shortUrl);
            }
        }
Esempio n. 14
0
        public int Handle(Create command)
        {
            var Url = new ShortenedUrl(command.Url);

            urlShortnerRepository.add(Url);
            unitOfWork.Commit();
            return(Url.Id);
        }
Esempio n. 15
0
        public void Short_url_should_contain_only_valid_uri_characters()
        {
            var validCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;=";
            var url             = "https://foo.bar";
            var shortenedUrl    = new ShortenedUrl(url);

            Assert.That(shortenedUrl.ShortUrl.All(c => validCharacters.Contains(c)), Is.True);
        }
Esempio n. 16
0
        public async Task <ShortenedUrl> AddAsync(ShortenedUrl shortenedUrl)
        {
            await _dbContext.ShortenedUrls.AddAsync(shortenedUrl);

            await _dbContext.SaveChangesAsync();

            return(shortenedUrl);
        }
Esempio n. 17
0
        public void Different_shorten_attempts_should_yield_different_results()
        {
            var url = "https://foo.bar";
            var firstShortenedUrl  = new ShortenedUrl(url);
            var secondShortenedUrl = new ShortenedUrl(url);

            Assert.That(firstShortenedUrl.ShortUrl, Is.Not.EqualTo(secondShortenedUrl.ShortUrl));
        }
Esempio n. 18
0
 private static ShortenedUrlModel toModel(ShortenedUrl shortenedUrl)
 {
     return(new ShortenedUrlModel
     {
         OriginalUrl = shortenedUrl.OriginalUrl,
         ShortUrl = shortenedUrl.ShortUrl,
         VisitCount = shortenedUrl.VisitCount
     });
 }
Esempio n. 19
0
 public static ShortenedUrlDto MapDtoFromModel(ShortenedUrl obj)
 {
     return(new ShortenedUrlDto
     {
         Url = obj.Url,
         ShortCode = obj.ShortCode,
         LastSeenDate = obj.UpdatedOn?.Date,
         StartDate = obj.CreatedOn,
         RedirectCount = obj.NumRedirectCalls
     });
 }
Esempio n. 20
0
        public ShortenedUrl Create(UrlData url)
        {
            var shortUrl = new ShortenedUrl()
            {
                Id       = Math.Abs(url.GetHashCode()),
                Url      = url.Url,
                HashedId = _converter.toBase62(Math.Abs(url.GetHashCode()))
            };

            _shortUrls.InsertOne(shortUrl);
            return(shortUrl);
        }
Esempio n. 21
0
        internal async Task <ShortenedUrl> AddShortUrlAsync(string id, string url, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var shortenedUrl = new ShortenedUrl(id, url);

            await ShortenedUrls.AddAsync(shortenedUrl, cancellationToken).ConfigureAwait(false);

            await SaveChangesAsync(cancellationToken).ConfigureAwait(false);

            return(shortenedUrl);
        }
Esempio n. 22
0
        public IActionResult RedirectToUrl(string url)
        {
            ShortenedUrl shortUrl = _dbContext.ShortenedUrls.Where(s => s.ShortUrl == url).FirstOrDefault();

            if (shortUrl != null)
            {
                shortUrl.Views += 1;
                _dbContext.Entry(shortUrl).State = EntityState.Modified;
                _dbContext.SaveChanges();
                return(Redirect(shortUrl.OriginalUrl));
            }
            return(new StatusCodeResult(StatusCodes.Status404NotFound));
        }
Esempio n. 23
0
        public IActionResult Delete(string id)
        {
            ShortenedUrl shortenedUrl = _dbContext.ShortenedUrls.Where(s => s.ShortUrl == id).FirstOrDefault();

            if (shortenedUrl != null)
            {
                if (shortenedUrl.User.Username == User.Identity.Name)
                {
                    _dbContext.ShortenedUrls.Remove(shortenedUrl);
                    _dbContext.SaveChanges();

                    return(Json(new { result = true }));
                }
                return(Json(new { error = new { message = "You do not have permission to edit this Shortened URL" } }));
            }
            return(Json(new { error = new { message = "This Shortened URL does not exist" } }));
        }
Esempio n. 24
0
        public async Task <ShortenedUrl> CreateByUserId(string userId, string longUrl, string domain, string token)
        {
            var shortenUrl = new ShortenedUrl()
            {
                Token     = token,
                LongUrl   = longUrl,
                ShortUrl  = GetShortUrl(domain, token),
                Domain    = domain,
                CreatedBy = userId,
                CreatedOn = DateTime.Now
            };

            _context.Add(shortenUrl);
            await _context.SaveChangesAsync();

            return(shortenUrl);
        }
Esempio n. 25
0
        public static ShortenedUrl ShortenUrl(TeknikEntities db, string url, int length)
        {
            // Generate the shortened url
            string shortUrl = StringHelper.RandomString(length);

            while (db.ShortenedUrls.Where(s => s.ShortUrl == shortUrl).FirstOrDefault() != null)
            {
                shortUrl = StringHelper.RandomString(length);
            }

            ShortenedUrl newUrl = new ShortenedUrl();

            newUrl.OriginalUrl = url;
            newUrl.ShortUrl    = shortUrl;
            newUrl.DateAdded   = DateTime.Now;

            return(newUrl);
        }
Esempio n. 26
0
 /// <summary>
 /// Ensure the supplied short token isn't taken and or is URL encoded.
 /// </summary>
 /// <param name="shortUrl"></param>
 public ModelError EnsureValidShortToken(ShortenedUrl shortUrl)
 {
     if (shortUrl.ShortToken.IsNullOrWhiteSpace())
     {
         do
         {
             shortUrl.ShortToken = Data.RandomStringGenerator.GenerateRandomString(4);
         } while (ShortTokenIsAvailable(shortUrl.ShortToken) == false);
     }
     else
     {
         if (ShortTokenIsAvailable(shortUrl.ShortToken) == false)
         {
             return(new ModelError("Token [{0}] has already been taken.".FormatWith(shortUrl.ShortToken)));
         }
     }
     return(null);
 }
Esempio n. 27
0
        public IActionResult Shorten(ShortenAPIv1Model model)
        {
            try
            {
                if (model.url.IsValidUrl())
                {
                    ShortenedUrl newUrl = ShortenerHelper.ShortenUrl(_dbContext, model.url, _config.ShortenerConfig.UrlLength);

                    // Associate this with the user if they are logged in
                    if (User.Identity.IsAuthenticated)
                    {
                        User foundUser = UserHelper.GetUser(_dbContext, User.Identity.Name);
                        if (foundUser != null)
                        {
                            newUrl.UserId = foundUser.UserId;
                        }
                    }

                    _dbContext.ShortenedUrls.Add(newUrl);
                    _dbContext.SaveChanges();

                    string shortUrl = string.Format("{0}://{1}/{2}", HttpContext.Request.Scheme, _config.ShortenerConfig.ShortenerHost, newUrl.ShortUrl);
                    if (_config.DevEnvironment)
                    {
                        shortUrl = Url.SubRouteUrl("shortened", "Shortener.View", new { url = newUrl.ShortUrl });
                    }

                    return(Json(new
                    {
                        result = new
                        {
                            shortUrl = shortUrl,
                            originalUrl = model.url
                        }
                    }));
                }
                return(Json(new { error = new { message = "Must be a valid Url" } }));
            }
            catch (Exception ex)
            {
                return(Json(new { error = new { message = "Exception: " + ex.Message } }));
            }
        }
Esempio n. 28
0
        public IActionResult ShortenUrl(string originalUrl)
        {
            ShortenedUrl url     = null;
            var          urlRepo = new ShortenedUrlsRepository(_connectionString);

            if (User.Identity.IsAuthenticated)
            {
                url = urlRepo.GetByOriginalUrlForUser(User.Identity.Name, originalUrl);
            }
            else
            {
                url = urlRepo.GetByOriginalUrl(originalUrl);
            }

            if (url == null)
            {
                var hash = ShortId.Generate(7);
                while (urlRepo.HashExists(hash))
                {
                    hash = ShortId.Generate(7);
                }
                url = new ShortenedUrl
                {
                    OriginalUrl = originalUrl,
                    UrlHash     = hash
                };
                if (User.Identity.IsAuthenticated)
                {
                    var userRepo = new UserRepository(_connectionString);
                    var user     = userRepo.GetByEmail(User.Identity.Name);
                    url.UserId = user.Id;
                }

                urlRepo.Add(url);
            }

            return(Json(new { shortUrl = GetFullUrl(url.UrlHash) }));
        }
Esempio n. 29
0
        public async Task <IActionResult> OnGetShortenLinkAsync(string originalUrl)
        {
            ShortenedUrl newShortUrl = new ShortenedUrl();

            originalUrl = originalUrl.ToLower();
            if (!originalUrl.StartsWith("https://") && !originalUrl.StartsWith("http://"))
            {
                originalUrl = "https://" + originalUrl;
            }
            newShortUrl.Url      = originalUrl;
            newShortUrl.ShortUrl = GetRandomString();

            var tempList = HttpContext.Session.GetObject <TempDb>("TempDb");

            tempList.urlList.Add(newShortUrl);
            HttpContext.Session.SetObject("TempDb", tempList);

            return(new JsonResult(newShortUrl)
            {
                ContentType = "text/json",
                StatusCode = 200,
            });
        }
Esempio n. 30
0
        // [ValidateAntiForgeryToken]
        public IActionResult Create([FromBody] string originalUrl)
        {
            if (UrlValidation.IsValidUrl(originalUrl))
            {
                var shortUrl = new ShortenedUrl
                {
                    OriginalUrl = originalUrl
                };

                TryValidateModel(shortUrl);
                if (ModelState.IsValid)
                {
                    _service.Save(shortUrl);
                }

                var returnedUrl = ShortUrlHelper.Encode(shortUrl.Id);
                return(Ok("http://shrturl.keith-pearce.co.uk/url/" + returnedUrl));
            }
            else
            {
                return(BadRequest("Please enter a valid URL"));
            }
        }