Exemplo n.º 1
0
        public static async Task <IActionResult> RunGetAllSessions(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "data/sessions")] HttpRequest req,
            [Table(TableNames.Cache)] CloudTable cacheTable,
            ILogger log,
            ExecutionContext context)
        {
            string sessionData = await GetSession.GetAllSessions(cacheTable, log, context);

            if (sessionData != null)
            {
                return(new ContentResult {
                    ContentType = "application/json",
                    Content = sessionData
                });
            }
            else
            {
                return(new NotFoundResult());
            }
        }
Exemplo n.º 2
0
        public static async Task <IActionResult> RunGetSessionById(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "calendar/session/{id}")] HttpRequest req,
            [Table(TableNames.Cache)] CloudTable cacheTable,
            [Queue(QueueNames.ProcessRedirectClicks), StorageAccount("AzureWebJobsStorage")] ICollector <HttpRequestEntity> processRedirectQueue,
            string id,
            ILogger log,
            ExecutionContext context)
        {
            id = id ?? req.Query["id"];
            bool ical = req.Query.ContainsKey("ical");
            bool link = req.Query.ContainsKey("link");

            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);

            id = id ?? data?.id;

            int numericId = 0;

            int.TryParse(id, out numericId);
            if (numericId > 0)
            {
                id = numericId.ToString();
            }

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

            string jsonData = await GetSession.GetAllSessions(cacheTable, log, context);

            if (jsonData != null)
            {
                #nullable enable
                Session?foundSession = GetSession.ById(jsonData, id, req, true);
                #nullable disable
                if (foundSession != null)
Exemplo n.º 3
0
        public static async Task <IActionResult> RunRedirectSession(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "redirect/session/{id}/")] HttpRequest req,
            [Table(TableNames.Cache)] CloudTable cacheTable,
            [Table(TableNames.RedirectSessions)] CloudTable sessionRedirectTable,
            [Queue(QueueNames.ProcessRedirectClicks), StorageAccount("AzureWebJobsStorage")] ICollector <HttpRequestEntity> processRedirectQueue,
            string id,
            ILogger log,
            ExecutionContext context)
        {
            id = id ?? req.Query["id"];

            int numericId = 0;

            int.TryParse(id, out numericId);
            if (numericId > 0)
            {
                id = numericId.ToString();
            }

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

            RedirectEntity redirect = await RedirectEntity.get(sessionRedirectTable, id);

            Session foundSession = GetSession.ById(await GetSession.GetAllSessions(cacheTable, log, context), id, req, true);

            if (redirect != null && redirect.RedirectTo != null)
            {
                int startRedirectingMinutes = (redirect.StartRedirectingMinutes == null) ? -5 : redirect.StartRedirectingMinutes.Value;

                if (foundSession != null && foundSession.startsAt != null)
                {
                    DateTime startRedirecting = foundSession.startsAt.Value.ToUniversalTime().AddMinutes(startRedirectingMinutes);
                    DateTime now = DateTime.Now;

                    if (DateTime.Compare(now, startRedirecting) >= 0)
                    {
                        log.LogInformation($"Start redirecting condition met for {req.Path} - redirect time was {startRedirecting} (current time {now})");

                        if (req.QueryString.ToString().IndexOf("check") < 0)
                        {
                            processRedirectQueue.Add(new HttpRequestEntity(req));

                            if (redirect.RedirectTo.StartsWith("/") && redirect.RedirectTo.Substring(1, 1) != "/")
                            {
                                return(new RedirectResult($"{config["REDIRECT_DESTINATION_HOST"]}{redirect.RedirectTo}", false));
                            }

                            return(new RedirectResult($"{redirect.RedirectTo}", false));
                        }

                        return(new AcceptedResult());
                    }
                    else
                    {
                        log.LogInformation($"Start redirecting condition not met for {req.Path} - waiting until {startRedirecting} (current time {now})");

                        if (req.QueryString.ToString().IndexOf("check") >= 0)
                        {
                            return(new OkObjectResult($"Session found, waiting until {startRedirecting} before redirecting (current time {now})"));
                        }
                    }
                }
                else
                {
                    log.LogInformation($"Start redirecting condition not met for {req.Path} - session has no start time)");

                    if (req.QueryString.ToString().IndexOf("check") >= 0)
                    {
                        return(new OkObjectResult($"Session found, but has no start time in sessionize"));
                    }
                }
            }

            if (foundSession != null)
            {
                if (req.QueryString.ToString().IndexOf("check") >= 0)
                {
                    return(new OkObjectResult($"Session found, wait for redirect"));
                }

                string holdingPageUrl = $"{config["HOLDPAGE_SESSION"]}";
                holdingPageUrl = holdingPageUrl.Replace("{id}", foundSession.id ??= string.Empty);

                int  holdpageCacheMinutes = 0;
                bool foundConfig          = int.TryParse(config["HOLDPAGE_CACHE_MINUTES"], out holdpageCacheMinutes);
                if (!foundConfig)
                {
                    holdpageCacheMinutes = 10;
                }

                CacheEntity cachedSessionPage = await CacheEntity.get(cacheTable, CacheType.Session, $"session-{id}", new TimeSpan(0, holdpageCacheMinutes, 0));

                if (cachedSessionPage != null)
                {
                    string value = cachedSessionPage.GetValue();

                    return(new ContentResult {
                        ContentType = "text/html; charset=UTF-8",
                        Content = value
                    });
                }

                log.LogInformation($"Looking up holding page content: {holdingPageUrl}.");

                var client      = new HttpClient();
                var getResponse = await client.GetAsync(holdingPageUrl);

                if (getResponse.IsSuccessStatusCode)
                {
                    string value = await getResponse.Content.ReadAsStringAsync();

                    int  redirectDelay      = 10;
                    bool foundRedirectDelay = int.TryParse(config["REDIRECT_DELAY"], out redirectDelay);
                    if (!foundRedirectDelay)
                    {
                        redirectDelay = 10;
                    }

                    value = value.Replace("{title}", foundSession.title ??= string.Empty);
                    value = value.Replace("{description}", foundSession.description ??= string.Empty);
                    value = value.Replace("{id}", foundSession.id ??= string.Empty);
                    value = value.Replace("{url}", foundSession.url ??= string.Empty);
                    value = value.Replace("{ical}", foundSession.ical ??= string.Empty);
                    value = value.Replace("{speakers}", string.Join(", ", foundSession.speakers.Select(speaker => speaker.name)));
                    value = value.Replace("{redirect-js}", Constants.REDIRECT_JS.Replace("{url}", $"{req.Path}?check")).Replace("{redirect-delay}", (redirectDelay * 1000).ToString());
                    value = value.Replace("{embed-js}", EMBED_JS);

                    if (value.IndexOf("{speaker-profiles}") >= 0)
                    {
                        string speakerData = await GetSpeaker.GetAllSpeakers(cacheTable, log, context);

                        value = value.Replace("{speaker-profiles}", string.Join("", foundSession.speakers.Select(speaker => {
                            SpeakerInformation foundSpeaker = GetSpeaker.ById(speakerData, speaker.id, req, false);
                            return(SpeakerInformation.ProcessSpeakerTokens(Constants.SPEAKER_HTML, foundSpeaker));
                        })));
                    }

                    await CacheEntity.put(cacheTable, CacheType.Session, $"session-{id}", value, 600);

                    return(new ContentResult {
                        ContentType = "text/html; charset=UTF-8",
                        Content = value
                    });
                }
                else
                {
                    return(new NotFoundObjectResult($"{config["HOLDPAGE_SESSION"]} template page not found"));
                }
            }

            return(new NotFoundResult());
        }