Ejemplo n.º 1
0
        public ShortUrlResponse Shorten(ShortUrlRequest model)
        {
            var checkResult = _autoRefreshingCacheService.CheckCache(model.OriginalUrl);

            if (checkResult != null)
            {
                _logger.LogInformation("[Link Shorten Manager][Shorten Url return from cache memory with considaration of time limt.]");
                return(new ShortUrlResponse {
                    OriginalUrl = checkResult["OriginalUrl"] as string, ShortUrl = checkResult["ShortenUrl"] as string
                });
            }

            var shortUrl       = _linkShortenService.GenerateShortUrl();
            var uniqueId       = _linkShortenService.ShortUrlToId(shortUrl);
            var base62ShortUrl = _linkShortenService.IdToBase62(uniqueId);

            _logger.LogInformation("[Link Shorten Manager] " + "Plain Short Url:" + shortUrl + " Unique Id:" + uniqueId + " Base62 Short Url:" + base62ShortUrl);
            var entity = ShortenUrlMapper.ToEntity(model, base62ShortUrl, uniqueId, _appSettings.MemoryCache.RefreshTimeInDays);

            var result = _repository.InsertAsync(entity);

            _logger.LogInformation("[Link Shorten Manager][Shorten Url save to cahce memory and database, then return shorten url]");

            _autoRefreshingCacheService.SetCache(entity.OriginalUrl, entity.ShortUrl);
            return(ShortenUrlMapper.ToObject(result));
        }
Ejemplo n.º 2
0
        public async Task AddShortenedUrl_WithValidModel_WithSuggestedCodeAlreadyPresent_ExpectConflictStatusAndCorrectContentType()
        {
            using (var client = _factory
                                .WithWebHostBuilder(builder => { })
                                .CreateClient(new WebApplicationFactoryClientOptions
            {
                AllowAutoRedirect = false
            }))
            {
                var request = new ShortUrlRequest
                {
                    Url       = "www.youtube.com",
                    ShortCode = "Example"
                };

                HttpContent payload = new StringContent(
                    JsonConvert.SerializeObject(request),
                    Encoding.UTF8,
                    "application/json");


                var response = await client.PostAsync(PostUri, payload);

                Assert.Equal(HttpStatusCode.Conflict, response.StatusCode);

                var rawContent = await response.Content.ReadAsStringAsync();

                var content = JsonConvert.DeserializeObject <ErrorResponse>(rawContent);

                Assert.Equal((int)HttpStatusCode.Conflict, content.Error);
                Assert.Equal("The the desired shortcode is already in use. Shortcodes are case-sensitive.", content.Description);
                Assert.Equal(ExpectedContentType, response.Content.Headers.ContentType.ToString());
            }
        }
Ejemplo n.º 3
0
        public async Task AddShortenedUrl_WithValidModel_WithInvalidSuggestedCode_ExpectUnprocessableStatusAndCorrectContentType()
        {
            using (var client = _factory
                                .WithWebHostBuilder(builder => { })
                                .CreateClient(new WebApplicationFactoryClientOptions
            {
                AllowAutoRedirect = false
            }))
            {
                var request = new ShortUrlRequest
                {
                    Url       = "www.youtube.com",
                    ShortCode = "e"
                };

                HttpContent payload = new StringContent(
                    JsonConvert.SerializeObject(request),
                    Encoding.UTF8,
                    "application/json");

                var response = await client.PostAsync(PostUri, payload);

                Assert.Equal(UnprocessableEntityStatusCode, (int)response.StatusCode);

                var rawContent = await response.Content.ReadAsStringAsync();

                var content = JsonConvert.DeserializeObject <ErrorResponse>(rawContent);

                Assert.Equal(UnprocessableEntityStatusCode, content.Error);
                Assert.Equal("The shortcode fails to meet the following regexp: ^[0-9a-zA-Z_]{4,}$.", content.Description);
                Assert.Equal(ExpectedContentType, response.Content.Headers.ContentType.ToString());
            }
        }
        public void UnauthorizeLinkShortener()
        {
            ViewResult result = new ViewResult();

            try
            {
                var linkShortenerValidator = _serviceProvider.GetService <ILinkShortenerValidator>();
                var linkShortenManager     = _serviceProvider.GetService <ILinkShortenManager>();
                var logger = _serviceProvider.GetService <ILogger <LinkShortenerController> >();

                var             controller = new LinkShortenerController(linkShortenerValidator, linkShortenManager, logger);
                ShortUrlRequest model      = new ShortUrlRequest
                {
                    OriginalUrl = "https://eatigo.com/th/bangkok/en"
                };

                var request = new HttpRequestMessage();
                request.Headers.Add("Authorization", "");
                result = (ViewResult)controller.LinkShortener(model);
                Assert.NotNull(result);
            }
            catch
            {
                Assert.True(result.StatusCode == null);
            }
        }
Ejemplo n.º 5
0
        public async Task AddShortenedUrl_WithInvalidModel_ExpectBadRequestStatusAndCorrectContentType()
        {
            using (var client = _factory
                                .WithWebHostBuilder(_ => { })
                                .CreateClient(new WebApplicationFactoryClientOptions
            {
                AllowAutoRedirect = false
            }))
            {
                var request = new ShortUrlRequest();

                HttpContent payload = new StringContent(
                    JsonConvert.SerializeObject(request),
                    Encoding.UTF8,
                    "application/json");

                var response = await client.PostAsync(PostUri, payload);

                Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);

                var rawContent = await response.Content.ReadAsStringAsync();

                var content = JsonConvert.DeserializeObject <ErrorResponse>(rawContent);

                Assert.Equal((int)HttpStatusCode.BadRequest, content.Error);
                Assert.Equal("url is not present", content.Description);
                Assert.Equal(ExpectedContentType, response.Content.Headers.ContentType.ToString());
            }
        }
        public void Shorten()
        {
            var linkShortenManager = _serviceProvider.GetService <ILinkShortenManager>();

            ShortUrlRequest model = new ShortUrlRequest()
            {
                OriginalUrl = "https://eatigo.com/th/bangkok/en"
            };
            var response = linkShortenManager.Shorten(model);

            Assert.True(response != null);
        }
Ejemplo n.º 7
0
 public static ShortenUrl ToEntity(this ShortUrlRequest model, string base62ShortUrl, long uniqueId, int days)
 {
     return(new ShortenUrl()
     {
         UniqueId = uniqueId,
         OriginalUrl = model.OriginalUrl,
         ShortUrl = "https://eati.go" + "/" + base62ShortUrl,
         Domain = "eati.go",
         ShortString = base62ShortUrl,
         CreateDate = DateTime.Now.ToString(),
         ExpiryDate = DateTime.Now.AddDays(days).ToString()
     });
 }
Ejemplo n.º 8
0
        public async Task <IActionResult> Add([FromBody] ShortUrlRequest request)
        {
            if (string.IsNullOrEmpty(request.Url) || string.IsNullOrEmpty(request.UserId))
            {
                return(BadRequest());
            }

            if (!Uri.TryCreate(request.Url, UriKind.Absolute, out _))
            {
                return(BadRequest());
            }

            string slug = await _urlProvider.GenerateSlug(request.Url, request.UserId);

            return(Content(slug));
        }
        public IActionResult LinkShortener(ShortUrlRequest model)
        {
            _logger.LogInformation("[Link Shortener] " + JsonConvert.SerializeObject(model));
            var(statusCode, errorResult) = _linkShortenerValidator.PayloadValidator(Request.Headers[HeaderNames.Authorization], model.OriginalUrl);

            _logger.LogWarning("[Link Shortener] " + JsonConvert.SerializeObject(errorResult));
            if (statusCode != StatusCodes.Status200OK)
            {
                return(StatusCode(statusCode, errorResult));
            }

            var result = _linkShortenManager.Shorten(model);

            _logger.LogInformation("[Link Shortener] " + JsonConvert.SerializeObject(result));

            return(StatusCode(StatusCodes.Status200OK, result));
        }
Ejemplo n.º 10
0
        public async Task AddShortenedUrl_WithValidModel_WithSuggestedShortCode_ExpectCreatedStatusAndCorrectContentType()
        {
            using (var client = _factory
                                .WithWebHostBuilder(_ => {})
                                .CreateClient(new WebApplicationFactoryClientOptions
            {
                AllowAutoRedirect = false
            }))
            {
                var request = new ShortUrlRequest
                {
                    Url       = "www.example_one.com",
                    ShortCode = "example_one"
                };

                HttpContent payload = new StringContent(
                    JsonConvert.SerializeObject(request),
                    Encoding.UTF8,
                    "application/json");

                var response = await client.PostAsync(PostUri, payload);

                Assert.Equal(HttpStatusCode.Created, response.StatusCode);
                Assert.Equal("/example_one/stats", response.Headers.Location.ToString());

                var rawContent = await response.Content.ReadAsStringAsync();

                var content = JsonConvert.DeserializeObject <ShortenedUrl>(rawContent);

                Assert.Equal("example_one", content.ShortCode);
                Assert.Null(content.Url);
                Assert.NotNull(content.CreatedOn);
                Assert.Null(content.UpdatedOn);
                Assert.True(content.NumRedirectCalls == 0);
                Assert.Equal(ExpectedContentType, response.Content.Headers.ContentType.ToString());
            }
        }
Ejemplo n.º 11
0
        public void GetLongUrl()
        {
            Guid           webSetId         = Guid.Parse("28670136-C253-4B88-962F-F99E81806D5E");
            WebSettingInfo webSettingEntity = new WebSettingBLL().GetWebSettingInfo(webSetId.ToString());
            string         url = webSettingEntity.Param1Value;

            try
            {
                string shortUrlKey   = string.Empty;
                int    functonType   = 0;
                int    shareToolType = 0;
                GetSharedAddressKey(ref shortUrlKey, ref functonType, ref shareToolType);    //获取段地址的key、功能类型、分享类型
                if (functonType > 0 && shareToolType > 0)
                {
                    string sharedUrl = GetSharedAddress(functonType, shareToolType);//获取分享设置表中对应功能、分享类型的url
                    if (!string.IsNullOrEmpty(sharedUrl))
                    {
                        url = sharedUrl;
                    }
                }
                //ShortUrlService serviceShortUrl = new ShortUrlService();
                ShortUrlRequest requestShortUrl = new ShortUrlRequest();
                requestShortUrl.ShortUrlKey = shortUrlKey;
                TuanDai.InfoSystem.Model.RequestContentApi reqApi = new TuanDai.InfoSystem.Model.RequestContentApi();
                reqApi.Data = JsonConvert.SerializeObject(requestShortUrl);
                ReplyContentApi      repApi = null;
                InfoSystemClient_New client = new InfoSystemClient_New();
                string errorMsg             = "";

                repApi = client.getlongurl(reqApi, out errorMsg);

                List <UserExtendShortUrl> shortUrList = new List <UserExtendShortUrl>();
                if (errorMsg == "" && repApi.Data != null && repApi.ReturnCode == 1)
                {
                    shortUrList = JsonConvert.DeserializeObject <List <UserExtendShortUrl> >(repApi.Data.ToString());
                }
                if (shortUrList.Count <= 0)
                {
                    Response.Redirect(url);
                }

                string             resultUrl     = string.Empty;
                UserExtendShortUrl shortUrEntity = shortUrList.FirstOrDefault();
                if (shortUrEntity != null && !string.IsNullOrEmpty(shortUrEntity.LongUrl))
                {
                    resultUrl = url + shortUrEntity.LongUrl;
                }
                if (!string.IsNullOrEmpty(resultUrl))
                {
                    Response.Redirect(resultUrl, false);
                }
                else
                {
                    Response.Redirect(url, false);
                }
            }
            catch (Exception ex)
            {
                SysLogHelper.WriteErrorLog("GetLongUrl应用系统错误:" + ex.TargetSite.Name, ex.ToString());
                Response.Redirect(url, false);
            }
            finally
            {
                Response.End();
            }
        }
Ejemplo n.º 12
0
 public ShortUrlResponse Post(ShortUrlRequest shortUrlRequest)
 {
     return(String.IsNullOrWhiteSpace(shortUrlRequest.CustomPath) ?
            MakeShortUrlResponse(shortener => shortener.Shorten(shortUrlRequest.Url)) :
            MakeShortUrlResponse(shortener => shortener.ShortenWithCustomHash(shortUrlRequest.Url, shortUrlRequest.CustomPath)));
 }