Exemple #1
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequestMessage req,
            ILogger log,
            ExecutionContext context)
        {
            log.LogInformation($"C# HTTP trigger function processed this request: {req}");

            var result = new ListResponse();
            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables()
                         .Build();

            StorageTableHelper stgHelper = new StorageTableHelper(config["UlsDataStorage"]);

            try
            {
                result.UrlList = await stgHelper.GetAllShortUrlEntities();

                result.UrlList = result.UrlList.Where(p => !(p.IsArchived ?? false)).ToList();
                var host = req.RequestUri.GetLeftPart(UriPartial.Authority);
                foreach (ShortUrlEntity url in result.UrlList)
                {
                    url.ShortUrl = Utility.GetShortUrl(host, url.RowKey);
                }
            }
            catch (Exception ex)
            {
                log.LogError(ex, "An unexpected error was encountered.");
                return(req.CreateResponse(HttpStatusCode.BadRequest, ex));
            }

            return(req.CreateResponse(HttpStatusCode.OK, result));
        }
Exemple #2
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequestMessage req,
            ILogger log,
            ExecutionContext context)
        {
            log.LogInformation($"C# HTTP trigger function processed this request: {req}");

            var result = new WebhookListResponse();
            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables()
                         .Build();

            StorageTableHelper stgHelper = new StorageTableHelper(config["UlsDataStorage"]);

            try
            {
                result.UrlList = await stgHelper.GetAllWebhooks();
            }
            catch (Exception ex)
            {
                log.LogError(ex, "An unexpected error was encountered.");
                return(req.CreateResponse(HttpStatusCode.BadRequest, ex));
            }

            return(req.CreateResponse(HttpStatusCode.OK, result));
        }
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "UrlRedirect/{shortUrl}")] HttpRequestMessage req,
            string shortUrl,
            ExecutionContext context,
            ILogger log)
        {
            log.LogInformation($"C# HTTP trigger function processed for Url: {shortUrl}");

            string redirectUrl = "https://costv.guide";

            if (!string.IsNullOrWhiteSpace(shortUrl))
            {
                var config = new ConfigurationBuilder()
                             .SetBasePath(context.FunctionAppDirectory)
                             .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                             .AddEnvironmentVariables()
                             .Build();

                redirectUrl = config["defaultRedirectUrl"];

                StorageTableHelper stgHelper = new StorageTableHelper(config["UlsDataStorage"]);

                var tempUrl = new ShortUrlEntity(string.Empty, shortUrl);

                var newUrl = await stgHelper.GetShortUrlEntity(tempUrl);

                if (newUrl != null)
                {
                    log.LogInformation($"Found it: {newUrl.Url}");
                    newUrl.Clicks++;
                    stgHelper.SaveClickStatsEntity(new ClickStatsEntity(newUrl.RowKey));
                    await stgHelper.SaveShortUrlEntity(newUrl);

                    redirectUrl = WebUtility.UrlDecode(newUrl.Url);
                }
            }
            else
            {
                log.LogInformation("Bad Link, resorting to fallback.");
            }

            var currentQuery = HttpUtility.ParseQueryString(req.RequestUri.Query);

            var redirectUriBuilder = new UriBuilder(redirectUrl);
            var redirectQuery      = HttpUtility.ParseQueryString(redirectUriBuilder.Query);

            foreach (var key in currentQuery.AllKeys)
            {
                redirectQuery[key] = currentQuery[key];

                redirectUriBuilder.Query = redirectQuery.ToString();
            }

            var response = req.CreateResponse(HttpStatusCode.Redirect);

            response.Headers.Add("Location", redirectUriBuilder.ToString());

            return(response);
        }
Exemple #4
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequestMessage req,
            ILogger log,
            ExecutionContext context)
        {
            log.LogInformation($"C# HTTP trigger function processed this request: {req}");

            // Validation of the inputs
            if (req == null)
            {
                return(req.CreateResponse(HttpStatusCode.NotFound));
            }

            ShortUrlEntity input = await req.Content.ReadAsAsync <ShortUrlEntity>();

            if (input == null)
            {
                return(req.CreateResponse(HttpStatusCode.NotFound));
            }


            // If the Url parameter only contains whitespaces or is empty return with BadRequest.
            if (string.IsNullOrWhiteSpace(input.Url))
            {
                return(req.CreateErrorResponse(HttpStatusCode.BadRequest, "The url parameter can not be empty."));
            }

            // Validates if input.url is a valid aboslute url, aka is a complete refrence to the resource, ex: http(s)://google.com
            if (!Uri.IsWellFormedUriString(input.Url, UriKind.Absolute))
            {
                return(req.CreateErrorResponse(HttpStatusCode.BadRequest, $"{input.Url} is not a valid absolute Url. The Url parameter must start with 'http://' or 'http://'."));
            }

            ShortUrlEntity result;
            var            config = new ConfigurationBuilder()
                                    .SetBasePath(context.FunctionAppDirectory)
                                    .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                                    .AddEnvironmentVariables()
                                    .Build();

            StorageTableHelper stgHelper = new StorageTableHelper(config["UrlsDataStorage"]);

            try
            {
                result = await stgHelper.UpdateShortUrlEntity(input);

                var host = req.RequestUri.GetLeftPart(UriPartial.Authority);
                result.ShortUrl = Utility.GetShortUrl(host, result.RowKey);
            }
            catch (Exception ex)
            {
                log.LogError(ex, "An unexpected error was encountered.");
                return(req.CreateResponse(HttpStatusCode.BadRequest, ex));
            }

            return(req.CreateResponse(HttpStatusCode.OK, result));
        }
        public InverterMonitor(ILoggerFactory loggerFactory, ILogger <InverterMonitor> logger, IOptions <AppConfig> appConfig)
        {
            _loggerFactory = loggerFactory;
            _logger        = logger;
            _appConfig     = appConfig.Value;

            _logger.LogDebug("StorrageConnectionString: {StorageConnectionstring}", _appConfig.StorageConnectionstring);

            _storageTableHelper = new StorageTableHelper(_appConfig.StorageConnectionstring);
        }
Exemple #6
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
            ILogger log,
            ExecutionContext context,
            ClaimsPrincipal principal)
        {
            log.LogInformation($"C# HTTP trigger function processed this request: {req}");

            var    result = new ListResponse();
            string userId = string.Empty;
            var    config = new ConfigurationBuilder()
                            .SetBasePath(context.FunctionAppDirectory)
                            .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                            .AddEnvironmentVariables()
                            .Build();

            StorageTableHelper stgHelper = new StorageTableHelper(config["UlsDataStorage"]);

            try
            {
                var invalidRequest = Utility.CatchUnauthorize(principal, log);
                if (invalidRequest != null)
                {
                    return(invalidRequest);
                }
                else
                {
                    userId = principal.FindFirst(ClaimTypes.GivenName).Value;
                    log.LogInformation("Authenticated user {user}.", userId);
                }

                result.UrlList = await stgHelper.GetAllShortUrlEntities();

                result.UrlList = result.UrlList.Where(p => !(p.IsArchived ?? false)).ToList();
                //var host = req.HttpContext.RequestUri.GetLeftPart(UriPartial.Authority);
                var host = req.Host.Host;
                foreach (ShortUrlEntity url in result.UrlList)
                {
                    url.ShortUrl = Utility.GetShortUrl(host, url.RowKey);
                }
            }
            catch (Exception ex)
            {
                log.LogError(ex, "An unexpected error was encountered.");
                return(new BadRequestObjectResult(new
                {
                    message = ex.Message,
                    StatusCode = HttpStatusCode.BadRequest
                }));
            }

            return(new OkObjectResult(result));
        }
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "UrlRedirect/{shortUrl}")] HttpRequestMessage req,
            string shortUrl,
            ExecutionContext context,
            ILogger log)
        {
            log.LogInformation($"C# HTTP trigger function processed for Url: {shortUrl}");

            string redirectUrl = "https://azure.com";

            if (!String.IsNullOrWhiteSpace(shortUrl))
            {
                var config = new ConfigurationBuilder()
                             .SetBasePath(context.FunctionAppDirectory)
                             .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                             .AddEnvironmentVariables()
                             .Build();

                redirectUrl = config["defaultRedirectUrl"];

                StorageTableHelper stgHelper = new StorageTableHelper(config["UlsDataStorage"]);

                var tempUrl = new ShortUrlEntity(string.Empty, shortUrl);

                var newUrl = await stgHelper.GetShortUrlEntity(tempUrl);

                if (newUrl != null)
                {
                    log.LogInformation($"Found it: {newUrl.Url}");
                    newUrl.Clicks++;

                    var host            = req.RequestUri.GetLeftPart(UriPartial.Authority);
                    var shortUrlAddress = Utility.GetShortUrl(host, shortUrl);

                    await RunWebhooks(stgHelper, new ClickStatsResponse(newUrl.Title, shortUrlAddress, newUrl.Url, newUrl.Clicks));

                    stgHelper.SaveClickStatsEntity(new ClickStatsEntity(newUrl.RowKey));
                    await stgHelper.SaveShortUrlEntity(newUrl);

                    redirectUrl = newUrl.Url;
                }
            }
            else
            {
                log.LogInformation("Bad Link, resorting to fallback.");
            }

            var res = req.CreateResponse(HttpStatusCode.Redirect);

            res.Headers.Add("Location", redirectUrl);
            return(res);
        }
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequestMessage req,
            ILogger log,
            ExecutionContext context)
        {
            log.LogInformation($"C# HTTP trigger function processed this request: {req}");

            // Validation of the inputs
            if (req == null)
            {
                return(req.CreateResponse(HttpStatusCode.NotFound));
            }

            ShortUrlEntity input = await req.Content.ReadAsAsync <ShortUrlEntity>();

            if (input == null)
            {
                return(req.CreateResponse(HttpStatusCode.NotFound));
            }

            if (!Regex.IsMatch(input.Url, @"https:\/\/[a-z]*.*clashofstreamers.tv"))
            {
                return(req.CreateResponse(HttpStatusCode.NotFound));
            }

            ShortUrlEntity result;
            var            config = new ConfigurationBuilder()
                                    .SetBasePath(context.FunctionAppDirectory)
                                    .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                                    .AddEnvironmentVariables()
                                    .Build();

            StorageTableHelper stgHelper = new StorageTableHelper(config["UlsDataStorage"]);

            try
            {
                result = await stgHelper.UpdateShortUrlEntity(input);

                var host = req.RequestUri.GetLeftPart(UriPartial.Authority);
                result.ShortUrl = Utility.GetShortUrl(host, result.RowKey);
            }
            catch (Exception ex)
            {
                log.LogError(ex, "An unexpected error was encountered.");
                return(req.CreateResponse(HttpStatusCode.BadRequest, ex));
            }

            return(req.CreateResponse(HttpStatusCode.OK, result));
        }
        private static async Task RunWebhooks(StorageTableHelper stgHelper, ClickStatsResponse response)
        {
            var hooks = await stgHelper.GetAllWebhooks();

            using (var client = new HttpClient())
                using (var httpContent = CreateHttpContent(response))
                {
                    foreach (var hook in hooks)
                    {
                        using (var request = new HttpRequestMessage(HttpMethod.Post, hook.Url))
                        {
                            request.Content = httpContent;
                            await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
                        }
                    }
                }
        }
Exemple #10
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Function, "delete", Route = null)] HttpRequestMessage req,
            ILogger log,
            ExecutionContext context)
        {
            log.LogInformation($"C# HTTP trigger function processed this request: {req}");

            // Validation of the inputs
            if (req == null)
            {
                return(req.CreateResponse(HttpStatusCode.NotFound));
            }

            ShortUrlEntity input = await req.Content.ReadAsAsync <ShortUrlEntity>();

            if (input == null)
            {
                return(req.CreateResponse(HttpStatusCode.NotFound));
            }

            ShortUrlEntity result;
            var            config = new ConfigurationBuilder()
                                    .SetBasePath(context.FunctionAppDirectory)
                                    .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                                    .AddEnvironmentVariables()
                                    .Build();

            StorageTableHelper stgHelper = new StorageTableHelper(config["UlsDataStorage"]);

            try
            {
                result = await stgHelper.ArchiveShortUrlEntity(input);
            }
            catch (Exception ex)
            {
                log.LogError(ex, "An unexpected error was encountered.");
                return(req.CreateResponse(HttpStatusCode.BadRequest, ex));
            }

            return(req.CreateResponse(HttpStatusCode.OK));
        }
Exemple #11
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "UrlRedirect/{shortUrl}")] HttpRequestMessage req,
            string shortUrl,
            ExecutionContext context,
            ILogger log)
        {
            log.LogInformation($"C# HTTP trigger function processed for Url: {shortUrl}");

            var redirectUrl = "http://azure.com";

            if (!String.IsNullOrWhiteSpace(shortUrl))
            {
                var config = new ConfigurationBuilder()
                             .SetBasePath(context.FunctionAppDirectory)
                             .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                             .AddEnvironmentVariables()
                             .Build();

                StorageTableHelper stgHelper = new StorageTableHelper(config["UlsDataStorage"]);

                var tempUrl = new ShortUrlEntity(string.Empty, shortUrl);

                var newUrl = await stgHelper.GetShortUrlEntity(tempUrl);

                if (newUrl != null)
                {
                    log.LogInformation($"Found it: {newUrl.Url}");
                    redirectUrl = WebUtility.UrlDecode(newUrl.Url);
                }
            }
            else
            {
                log.LogInformation("Bad Link, resorting to fallback.");
            }

            var res = req.CreateResponse(HttpStatusCode.Redirect);

            res.Headers.Add("Location", redirectUrl);
            return(res);
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
            ILogger log,
            ExecutionContext context,
            ClaimsPrincipal principal)
        {
            log.LogInformation($"C# HTTP trigger function processed this request: {req}");

            string         userId = string.Empty;
            ShortUrlEntity input;
            ShortUrlEntity result;

            try
            {
                var invalidRequest = Utility.CatchUnauthorize(principal, log);
                if (invalidRequest != null)
                {
                    return(invalidRequest);
                }
                else
                {
                    userId = principal.FindFirst(ClaimTypes.GivenName).Value;
                    log.LogInformation("Authenticated user {user}.", userId);
                }

                // Validation of the inputs
                if (req == null)
                {
                    return(new BadRequestObjectResult(new { StatusCode = HttpStatusCode.NotFound }));
                }

                using (var reader = new StreamReader(req.Body))
                {
                    var body = reader.ReadToEnd();
                    input = JsonSerializer.Deserialize <ShortUrlEntity>(body, new JsonSerializerOptions {
                        PropertyNameCaseInsensitive = true
                    });
                    if (input == null)
                    {
                        return(new BadRequestObjectResult(new { StatusCode = HttpStatusCode.NotFound }));
                    }
                }

                var config = new ConfigurationBuilder()
                             .SetBasePath(context.FunctionAppDirectory)
                             .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                             .AddEnvironmentVariables()
                             .Build();

                StorageTableHelper stgHelper = new StorageTableHelper(config["UlsDataStorage"]);

                result = await stgHelper.ArchiveShortUrlEntity(input);
            }
            catch (Exception ex)
            {
                log.LogError(ex, "An unexpected error was encountered.");
                return(new BadRequestObjectResult(new {
                    message = ex.Message,
                    StatusCode = HttpStatusCode.BadRequest
                }));
            }

            return(new OkObjectResult(result));
        }
 public UrlRepository(StorageTableHelper storageTableHelper)
 {
     _storageTableHelper = storageTableHelper ?? throw new ArgumentNullException(nameof(storageTableHelper));
 }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
            ILogger log,
            ExecutionContext context,
            ClaimsPrincipal principal)
        {
            log.LogInformation($"C# HTTP trigger function processed this request: {req}");

            string userId = string.Empty;
            UrlClickStatsRequest input;
            var result = new ClickDateList();

            var invalidRequest = Utility.CatchUnauthorize(principal, log);

            if (invalidRequest != null)
            {
                return(invalidRequest);
            }
            else
            {
                userId = principal.FindFirst(ClaimTypes.NameIdentifier).Value;
                log.LogInformation("Authenticated user {user}.", userId);
            }

            // Validation of the inputs
            if (req == null)
            {
                return(new BadRequestObjectResult(new { StatusCode = HttpStatusCode.NotFound }));
            }

            try
            {
                using (var reader = new StreamReader(req.Body))
                {
                    var strBody = reader.ReadToEnd();
                    input = JsonSerializer.Deserialize <UrlClickStatsRequest>(strBody, new JsonSerializerOptions {
                        PropertyNameCaseInsensitive = true
                    });
                    if (input == null)
                    {
                        return(new BadRequestObjectResult(new { StatusCode = HttpStatusCode.NotFound }));
                    }
                }

                var config = new ConfigurationBuilder()
                             .SetBasePath(context.FunctionAppDirectory)
                             .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                             .AddEnvironmentVariables()
                             .Build();

                StorageTableHelper stgHelper = new StorageTableHelper(config["UlsDataStorage"]);

                // string searchingKey = "";
                // log.LogInformation($"Fetching for {input.Vanity}.");
                // if(!string.IsNullOrEmpty(input.Vanity)){
                //     searchingKey = input.Vanity;
                // }
                // log.LogInformation($"Now Looking for {searchingKey}.");

                var rawStats = await stgHelper.GetAllStatsByVanity(input.Vanity);


                result.Items = rawStats.GroupBy(s => DateTime.Parse(s.Datetime).Date)
                               .Select(stat => new ClickDate {
                    DateClicked = stat.Key.ToString("yyyy-MM-dd"),
                    Count       = stat.Count()
                }).OrderBy(s => DateTime.Parse(s.DateClicked).Date).ToList <ClickDate>();

                var host = string.IsNullOrEmpty(config["customDomain"]) ? req.Host.Host: config["customDomain"].ToString();
                result.Url = Utility.GetShortUrl(host, input.Vanity);
            }
            catch (Exception ex)
            {
                log.LogError(ex, "An unexpected error was encountered.");
                return(new BadRequestObjectResult(new
                {
                    message = ex.Message,
                    StatusCode = HttpStatusCode.BadRequest
                }));
            }

            return(new OkObjectResult(result));
        }
Exemple #15
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req,
            ILogger log,
            ExecutionContext context)
        {
            log.LogInformation($"C# HTTP trigger function processed this request: {req}");

            // Validation of the inputs
            if (req == null)
            {
                return(req.CreateResponse(HttpStatusCode.NotFound));
            }

            ShortRequest input = await req.Content.ReadAsAsync <ShortRequest>();

            if (input == null)
            {
                return(req.CreateResponse(HttpStatusCode.NotFound));
            }

            var result = new ShortResponse();
            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables()
                         .Build();

            StorageTableHelper stgHelper = new StorageTableHelper(config["UlsDataStorage"]);

            try
            {
                string longUrl = input.Url.Trim();
                string vanity  = input.Vanity.Trim();

                ShortUrlEntity newRow;

                if (!string.IsNullOrEmpty(vanity))
                {
                    newRow = new ShortUrlEntity(longUrl, vanity);
                    if (await stgHelper.IfShortUrlEntityExist(newRow))
                    {
                        return(req.CreateResponse(HttpStatusCode.Conflict, "This Short URL already exist."));
                    }
                }
                else
                {
                    newRow = new ShortUrlEntity(longUrl, await Utility.GetValidEndUrl(vanity, stgHelper));
                }

                await stgHelper.SaveShortUrlEntity(newRow);

                var host = req.RequestUri.GetLeftPart(UriPartial.Authority);
                log.LogInformation($"-> host = {host}");
                result = new ShortResponse(host, newRow.Url, newRow.RowKey);

                log.LogInformation("Short Url created.");
            }
            catch (Exception ex)
            {
                log.LogError(ex, "An unexpected error was encountered.");
                return(req.CreateResponse(HttpStatusCode.BadRequest, ex));
            }

            return(req.CreateResponse(HttpStatusCode.OK, result));
        }
Exemple #16
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log,
            ExecutionContext context,
            ClaimsPrincipal principal)
        {
            log.LogInformation($"C# HTTP trigger function processed this request: {req}");
            string       userId = string.Empty;
            ShortRequest input;
            var          result = new ShortResponse();

            try
            {
                var invalidRequest = Utility.CatchUnauthorize(principal, log);

                if (invalidRequest != null)
                {
                    return(invalidRequest);
                }
                else
                {
                    userId = principal.FindFirst(ClaimTypes.GivenName).Value;
                    log.LogInformation("Authenticated user {user}.", userId);
                }

                // Validation of the inputs
                if (req == null)
                {
                    return(new BadRequestObjectResult(new { StatusCode = HttpStatusCode.NotFound }));
                }

                using (var reader = new StreamReader(req.Body))
                {
                    var strBody = reader.ReadToEnd();
                    input = JsonSerializer.Deserialize <ShortRequest>(strBody, new JsonSerializerOptions {
                        PropertyNameCaseInsensitive = true
                    });
                    if (input == null)
                    {
                        return(new BadRequestObjectResult(new { StatusCode = HttpStatusCode.NotFound }));
                    }
                }

                // If the Url parameter only contains whitespaces or is empty return with BadRequest.
                if (string.IsNullOrWhiteSpace(input.Url))
                {
                    return(new BadRequestObjectResult(new { StatusCode = HttpStatusCode.BadRequest, Message = "The url parameter can not be empty." }));
                }

                // Validates if input.url is a valid aboslute url, aka is a complete refrence to the resource, ex: http(s)://google.com
                if (!Uri.IsWellFormedUriString(input.Url, UriKind.Absolute))
                {
                    return(new BadRequestObjectResult(new
                    {
                        StatusCode = HttpStatusCode.BadRequest,
                        Message = $"{input.Url} is not a valid absolute Url. The Url parameter must start with 'http://' or 'http://'."
                    }));
                }

                var config = new ConfigurationBuilder()
                             .SetBasePath(context.FunctionAppDirectory)
                             .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                             .AddEnvironmentVariables()
                             .Build();

                StorageTableHelper stgHelper = new StorageTableHelper(config["UlsDataStorage"]);


                string longUrl = input.Url.Trim();
                string vanity  = string.IsNullOrWhiteSpace(input.Vanity) ? "" : input.Vanity.Trim();
                string title   = string.IsNullOrWhiteSpace(input.Title) ? "" : input.Title.Trim();


                ShortUrlEntity newRow;

                if (!string.IsNullOrEmpty(vanity))
                {
                    newRow = new ShortUrlEntity(longUrl, vanity, title, input.Schedules);
                    if (await stgHelper.IfShortUrlEntityExist(newRow))
                    {
                        return(new ConflictObjectResult(new{ Message = "This Short URL already exist." }));
                    }
                }
                else
                {
                    newRow = new ShortUrlEntity(longUrl, await Utility.GetValidEndUrl(vanity, stgHelper), title, input.Schedules);
                }

                await stgHelper.SaveShortUrlEntity(newRow);

                var host = string.IsNullOrEmpty(config["customDomain"]) ? req.Host.Host: config["customDomain"].ToString();
                result = new ShortResponse(host, newRow.Url, newRow.RowKey, newRow.Title);

                log.LogInformation("Short Url created.");
            }
            catch (Exception ex)
            {
                log.LogError(ex, "An unexpected error was encountered.");
                return(new BadRequestObjectResult(new
                {
                    message = ex.Message,
                    StatusCode = HttpStatusCode.BadRequest
                }));
            }

            return(new OkObjectResult(result));
        }
Exemple #17
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req,
            ILogger log,
            ExecutionContext context)
        {
            log.LogInformation($"C# HTTP trigger function processed this request: {req}");

            // Validation of the inputs
            if (req == null)
            {
                return(req.CreateResponse(HttpStatusCode.NotFound));
            }

            ShortRequest input = await req.Content.ReadAsAsync <ShortRequest>();

            if (input == null)
            {
                return(req.CreateResponse(HttpStatusCode.NotFound));
            }

            // Validates if input.url is a valid aboslute url, aka is a complete refrence to the resource, ex: http(s)://google.com
            if (!Uri.IsWellFormedUriString(input.Url, UriKind.Absolute))
            {
                return(req.CreateErrorResponse(HttpStatusCode.BadRequest, $"{input.Url} is not a valid absolute Url. The Url parameter must start with 'http://' or 'http://'."));
            }

            var result = new ShortResponse();
            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables()
                         .Build();

            StorageTableHelper stgHelper = new StorageTableHelper(config["UlsDataStorage"]);

            try
            {
                string longUrl = input.Url.Trim();
                string vanity  = string.IsNullOrWhiteSpace(input.Vanity) ? "" : input.Vanity.Trim();
                string title   = string.IsNullOrWhiteSpace(input.Title) ? "" : input.Title.Trim();

                ShortUrlEntity newRow;

                if (!string.IsNullOrEmpty(vanity))
                {
                    newRow = new ShortUrlEntity(longUrl, vanity, title);
                    if (await stgHelper.IfShortUrlEntityExist(newRow))
                    {
                        return(req.CreateResponse(HttpStatusCode.Conflict, "This Short URL already exist."));
                    }
                }
                else
                {
                    newRow = new ShortUrlEntity(longUrl, await Utility.GetValidEndUrl(vanity, stgHelper), title);
                }

                await stgHelper.SaveShortUrlEntity(newRow);

                var host = req.RequestUri.GetLeftPart(UriPartial.Authority);
                log.LogInformation($"-> host = {host}");
                result = new ShortResponse(host, newRow.Url, newRow.RowKey, newRow.Title);

                log.LogInformation("Short Url created.");
            }
            catch (Exception ex)
            {
                log.LogError(ex, "An unexpected error was encountered.");
                return(req.CreateResponse(HttpStatusCode.BadRequest, ex));
            }

            return(req.CreateResponse(HttpStatusCode.OK, result));
        }