Exemplo n.º 1
0
        public void EventToActivityAsyncShouldThrowArgumentNullException()
        {
            var slackApi = new Mock <SlackClientWrapper>(_testOptions);

            Assert.Throws <ArgumentNullException>(() =>
            {
                SlackHelper.EventToActivity(null, slackApi.Object);
            });
        }
Exemplo n.º 2
0
        public async Task CommandToActivityAsyncShouldThrowArgumentNullException()
        {
            var slackApi = new Mock <SlackClientWrapper>(_testOptions);

            await Assert.ThrowsAsync <ArgumentNullException>(async() =>
            {
                await SlackHelper.CommandToActivityAsync(null, slackApi.Object, new CancellationToken()).ConfigureAwait(false);
            });
        }
Exemplo n.º 3
0
        public async Task WriteAsyncShouldFailWithNullEncoding()
        {
            var httpResponse = new Mock <HttpResponse>();

            await Assert.ThrowsAsync <ArgumentNullException>(async() =>
            {
                await SlackHelper.WriteAsync(httpResponse.Object, HttpStatusCode.OK, "testText", null, new CancellationToken()).ConfigureAwait(false);
            });
        }
Exemplo n.º 4
0
        public async Task <ActionResult> Upload(
            string title,
            HttpPostedFileBase uploadImage,
            string youTubeLink,
            bool isNSFW)
        {
            if (string.IsNullOrEmpty(title))
            {
                throw new HttpException((int)HttpStatusCode.BadRequest, "Invalid input data!");
            }
            var   post  = DbContext.Posts.Create();
            Image image = null;

            if (uploadImage != null)
            {
                image = await ImagesHelper.SaveImageAsync(uploadImage, DbContext);

                post.Image = image;
            }
            else
            {
                string html;
                if (!YouTubeHelper.TryGetEmbedHtml(youTubeLink, out html))
                {
                    throw new HttpException((int)HttpStatusCode.BadRequest, "Invalid input data!");
                }
                post.YouTubeLink = html;
            }

            var owner = DbContext.Users.First(u => u.UserName == User.Identity.Name);

            if (string.IsNullOrEmpty(post.YouTubeLink) && image == null)
            {
                throw new HttpException((int)HttpStatusCode.InternalServerError, "Invalid input data!");
            }

            post.DateCreated = DateTime.Now;
            post.Title       = title;
            post.Owner       = owner;
            post.IsNSFW      = isNSFW;
            post.Votes.Add(new Vote()
            {
                Type  = VoteType.Up,
                Voter = owner
            });

            var dbPost = DbContext.Posts.Add(post);
            await DbContext.SaveChangesAsync();

            // Don't await so we dont slow down the upload.
            NotifySubscribedUsersForNewPost();
            SlackHelper.SendNotification(dbPost, GetCurrentWebsiteRoot());

            return(RedirectToAction("Index", "Home"));
        }
Exemplo n.º 5
0
        public async Task EventToActivityAsyncShouldReturnActivity()
        {
            var slackApi = new Mock <SlackClientWrapper>(_testOptions);

            var payload   = File.ReadAllText(Directory.GetCurrentDirectory() + @"/Files/MessageBody.json");
            var slackBody = JsonConvert.DeserializeObject <SlackRequestBody>(payload);

            var activity = await SlackHelper.EventToActivityAsync(slackBody.Event, slackApi.Object, new CancellationToken()).ConfigureAwait(false);

            Assert.Equal(slackBody.Event.Text, activity.Text);
        }
        public void EventToActivityAsyncShouldReturnActivity()
        {
            var slackApi = new Mock <SlackClientWrapper>(_testOptions);

            var payload   = File.ReadAllText(Directory.GetCurrentDirectory() + @"/Files/MessageBody.json");
            var slackBody = JsonConvert.DeserializeObject <EventRequest>(payload);

            var activity = SlackHelper.EventToActivity(slackBody, slackApi.Object);

            Assert.Equal(slackBody.Event.AdditionalProperties["text"].ToString(), activity.Text);
        }
Exemplo n.º 7
0
        public async Task CommandToActivityAsyncShouldReturnActivity()
        {
            var slackApi = new Mock <SlackClientWrapper>(_testOptions);

            var payload     = File.ReadAllText(Directory.GetCurrentDirectory() + @"/Files/SlashCommandBody.txt");
            var commandBody = SlackHelper.QueryStringToDictionary(payload);
            var slackBody   = JsonConvert.DeserializeObject <SlackRequestBody>(JsonConvert.SerializeObject(commandBody));

            var activity = await SlackHelper.CommandToActivityAsync(slackBody, slackApi.Object, new CancellationToken()).ConfigureAwait(false);

            Assert.Equal(slackBody.TriggerId, activity.Id);
        }
        public void CommandToActivityAsyncShouldReturnActivity()
        {
            var slackApi = new Mock <SlackClientWrapper>(_testOptions);

            var payload     = File.ReadAllText(Directory.GetCurrentDirectory() + @"/Files/SlashCommandBody.txt");
            var commandBody = SlackHelper.QueryStringToDictionary(payload);
            var slackBody   = JsonConvert.DeserializeObject <CommandPayload>(JsonConvert.SerializeObject(commandBody));

            var activity = SlackHelper.CommandToActivity(slackBody, slackApi.Object);

            Assert.Equal(slackBody.TriggerId, activity.Id);
        }
Exemplo n.º 9
0
        public async Task EventToActivityAsyncShouldReturnActivityWithTeamId()
        {
            var slackApi = new Mock <SlackClientWrapper>(_testOptions);

            var payload   = File.ReadAllText(Directory.GetCurrentDirectory() + @"/Files/MessageBody.json");
            var slackBody = JsonConvert.DeserializeObject <EventRequest>(payload);

            slackBody.Event.Channel = null;

            var activity = await SlackHelper.EventToActivityAsync(slackBody, slackApi.Object, new CancellationToken()).ConfigureAwait(false);

            Assert.Equal(slackBody.Event.AdditionalProperties["team"].ToString(), activity.Conversation.Id);
        }
Exemplo n.º 10
0
        public static GymSearchListResponse searchByLocationImplementation(SearchGymRequest request)
        {
            var location = System.Data.Entity.Spatial.DbGeography.FromText(String.Format("POINT({0} {1})", request.longitude, request.latitude));

            GymSearchListResponse rv;

            using (var db = new UniversalGymEntities())
            {
                var searchRequest = new Data.SearchRequest
                {
                    SearchDate             = DateTime.Now,
                    Position               = location,
                    UniqueDeviceIdentifier = request.uniqueDeviceId,
                };

                var user = db.Users.SingleOrDefault(a => a.CurrentToken == request.authToken && a.UserId == request.accountId);
                if (user != null)
                {
                    searchRequest.UserId = user.UserId;
                }


                db.SearchRequests.Add(searchRequest);
                db.SaveChanges();

                var searchText = "DeviceId: "
                                 + request.uniqueDeviceId
                                 + Environment.NewLine;
                if (searchRequest.User != null)
                {
                    searchText = searchText
                                 + "User: "
                                 + searchRequest.User.Email;
                }

                SlackHelper.sendSearchChannel(searchText, request.latitude.ToString(), request.longitude.ToString());


                var gyms = db.Gyms.Where(w => w.Position != null).OrderBy(o => o.Position.Distance(location));
                rv = GymSearchListHelper.createGymSearchListResponse(gyms, location.Latitude, location.Longitude);
                if (user != null)
                {
                    rv.credits = user.Credits;
                }
                else
                {
                    rv.credits = 0;
                }
            }
            return(rv);
        }
Exemplo n.º 11
0
        private static async Task <IActionResult> DeleteProposal(IBinder binder, InteractiveMessagePayload payload, Proposal proposal)
        {
            var proposals = await binder.GetTable("proposals");

            if (proposal != null)
            {
                // Bloquer la suppression d'une proposition plannifiée
                if (!string.IsNullOrWhiteSpace(proposal.PlannedIn))
                {
                    var plan = await binder.GetTableRow <Plan>("plans", payload.PartitionKey, proposal.PlannedIn);

                    if (plan != null)
                    {
                        return(Utils.Ok(new SlackMessage {
                            Text = $"Ce vidéo est déjà planifié pour le {plan.Date:dddd d MMMM}.",
                            Attachments = { MessageHelpers.GetRemoveMessageAttachment() }
                        }));
                    }
                }

                var result = await proposals.ExecuteAsync(TableOperation.Delete(proposal));

                if (result.IsError())
                {
                    await MessageHelpers.PostErrorMessage(binder, payload);

                    return(Utils.Ok());
                }

                // Notifier le owner si c'est pas lui qui supprime sa proposition
                if (proposal.ProposedBy != payload.User.Id)
                {
                    await SlackHelper.PostMessage(binder, payload.Team.Id, new PostMessageRequest {
                        Channel     = proposal.ProposedBy,
                        Text        = $"<@{payload.User.Id}> vient de supprimer votre proposition de vidéo dans <#{payload.Channel.Id}>:",
                        Attachments = { await MessageHelpers.GetProposalAttachment(binder, proposal, allowActions: false) }
                    });
                }
            }

            // NOTE: Présentement la seule place qu'on peut supprimer une proposition c'est à partir de la liste de toutes les propositions.
            // Si ça change, va falloir ajouter plus de logique ici pour recréer le bon type de message.
            var allProposals = await ProposalHelpers.GetActiveProposals(proposals, payload.PartitionKey);

            var message = await MessageHelpers.GetListMessage(binder, allProposals, payload.Channel.Id);

            message.ReplaceOriginal = true;
            return(Utils.Ok(message));
        }
        public void ActivityToSlackShouldConvertHeroCardsToBlocks()
        {
            var serializeConversation = File.ReadAllText(Directory.GetCurrentDirectory() + @"/Files/SlackActivity.json");

            var card = new HeroCard
            {
                Title    = "BotFramework Hero Card",
                Subtitle = "Microsoft Bot Framework",
                Text     = "Build and connect intelligent bots to interact with your users naturally wherever they are," +
                           " from text/sms to Skype, Slack, Office 365 mail and other popular services.",
                Images = new List <CardImage> {
                    new CardImage("https://sec.ch9.ms/ch9/7ff5/e07cfef0-aa3b-40bb-9baa-7c9ef8ff7ff5/buildreactionbotframework_960.jpg")
                },
                Buttons = new List <CardAction>
                {
                    new CardAction(ActionTypes.OpenUrl, "OpenUrl", value: "https://docs.microsoft.com/bot-framework"),
                    new CardAction
                    {
                        Text        = "Some Action Text",
                        DisplayText = "ImBack",
                        Title       = "Some Action Title",
                        Value       = "Some Action Value",
                        Type        = ActionTypes.ImBack
                    }
                },
            };

            var activity = new Activity
            {
                Timestamp    = new DateTimeOffset(),
                Text         = "Hello!",
                Conversation = JsonConvert.DeserializeObject <ConversationAccount>(serializeConversation),
                Attachments  = new List <Attachment>
                {
                    card.ToAttachment()
                }
            };

            var message = SlackHelper.ActivityToSlack(activity);

            Assert.Equal(activity.Conversation.Id, message.Channel);
            Assert.Equal(activity.Conversation.Properties["thread_ts"].ToString(), message.ThreadTs);
            Assert.Equal(card.Title, (message.Blocks as JArray)[0]["text"]["text"]);
            Assert.Equal(card.Subtitle, (message.Blocks as JArray)[1]["elements"][0]["text"]);
            Assert.Equal(card.Images[0].Url, (message.Blocks as JArray)[2]["image_url"]);
            Assert.Equal(card.Text, (message.Blocks as JArray)[3]["text"]["text"]);
            Assert.Equal(card.Buttons[0].Value, (message.Blocks as JArray)[5]["elements"][0]["url"].ToString());
        }
Exemplo n.º 13
0
        public static async Task PrepareVideoReminder(
            [TimerTrigger("0 30 11 * * *")] TimerInfo timer, //11:30 daily
            [Table("plans")] CloudTable plansTable,
            IBinder binder)
        {
            Utils.SetCulture();

            var plans = await GetTodayPlansWithVideoAndResponsible(plansTable);

            foreach (var plan in plans)
            {
                var message = await MessageHelpers.GetPrepareVideoReminder(binder, plan);

                await SlackHelper.PostMessage(binder, plan.Team, message);
            }
        }
        public void EventToActivityAsyncShouldReturnActivityWithAttachmentsWhenFileSharing()
        {
            var slackApi = new Mock <SlackClientWrapper>(_testOptions);

            var payload   = File.ReadAllText(Directory.GetCurrentDirectory() + @"/Files/MessageBodyWithFileShare.json");
            var slackBody = JsonConvert.DeserializeObject <EventRequest>(payload);

            var activity = SlackHelper.EventToActivity(slackBody, slackApi.Object);

            Assert.Equal(ActivityTypes.Message, activity.Type);
            Assert.Equal(slackBody.Event.Type, activity.Type);
            Assert.Equal(slackBody.Event.AdditionalProperties["text"].ToString(), activity.Text);
            Assert.Equal(slackBody.Event.AdditionalProperties["files"][0]["mimetype"].ToString(), activity.Attachments[0].ContentType);
            Assert.Equal(slackBody.Event.AdditionalProperties["files"][0]["url_private_download"].ToString(), activity.Attachments[0].ContentUrl);
            Assert.Equal(slackBody.Event.AdditionalProperties["files"][0]["name"].ToString(), activity.Attachments[0].Name);
        }
        public void ActivityToSlackShouldReturnMessageWithThreadTs()
        {
            var serializeConversation = File.ReadAllText(Directory.GetCurrentDirectory() + @"/Files/SlackActivity.json");

            var activity = new Activity
            {
                Timestamp    = new DateTimeOffset(),
                Text         = "Hello!",
                Conversation = JsonConvert.DeserializeObject <ConversationAccount>(serializeConversation),
            };

            var message = SlackHelper.ActivityToSlack(activity);

            Assert.Equal(activity.Conversation.Id, message.Channel);
            Assert.Equal(activity.Conversation.Properties["thread_ts"].ToString(), message.ThreadTs);
        }
Exemplo n.º 16
0
        public static async Task PlanResponsibleSecondReminder(
            [TimerTrigger("0 15 11 * * *")] TimerInfo timer, // 11:15AM daily
            [Table("plans")] CloudTable plansTable,
            IBinder binder)
        {
            Utils.SetCulture();

            var plans = await GetTodayPlansWithoutResponsible(plansTable);

            foreach (var plan in plans)
            {
                await SlackHelper.PostMessage(binder, plan.Team, new PostMessageRequest {
                    Channel     = plan.Channel,
                    Text        = "<!channel> Rappel: Le Lunch & Watch de ce midi a besoin d'un responsable!",
                    Attachments = { await MessageHelpers.GetPlanAttachment(binder, plan) }
                });
            }
        }
        public void ActivityToSlackShouldReturnMessage()
        {
            var activity = new Activity
            {
                Timestamp   = new DateTimeOffset(),
                Text        = "Hello!",
                Attachments = new List <Attachment>
                {
                    new Attachment(name: "image", thumbnailUrl: ImageUrl),
                },
                Conversation = new ConversationAccount(id: "testId"),
            };

            var message = SlackHelper.ActivityToSlack(activity);

            Assert.Equal(activity.Conversation.Id, message.Channel);
            Assert.Equal(activity.Attachments[0].Name, message.Attachments[0].AuthorName);
        }
Exemplo n.º 18
0
        public static async Task PlanResponsibleFinalReminder(
            [TimerTrigger("0 55 11 * * *")] TimerInfo timer, // 11:55AM daily
            [Table("plans")] CloudTable plansTable,
            IBinder binder)
        {
            Utils.SetCulture();

            var plans = await GetTodayPlansWithoutResponsible(plansTable);

            foreach (var plan in plans)
            {
                await SlackHelper.PostMessage(binder, plan.Team, new PostMessageRequest {
                    Channel     = plan.Channel,
                    Text        = "<!channel> *Dernier rappel*: Le Lunch & Watch de ce midi a besoin d'un responsable! Si personne ne se manifeste, l'événement sera annulé.",
                    Attachments = { await MessageHelpers.GetPlanAttachment(binder, plan) }
                });
            }
        }
Exemplo n.º 19
0
        public static async Task <IActionResult> OnPropose(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "slack/commands/propose")] HttpRequest req,
            IBinder binder, ExecutionContext context)
        {
            Utils.SetCulture();

            var body = await SlackHelper.ReadSlackRequest(req, context);

            var parameters = SlackHelper.ParseBody(body);

            var dialogRequest = new OpenDialogRequest {
                TriggerId = parameters["trigger_id"],
                Dialog    = DialogHelpers.GetProposeDialog(defaultName: parameters["text"])
            };

            await SlackHelper.OpenDialog(binder, parameters["team_id"], dialogRequest);

            return(Utils.Ok());
        }
Exemplo n.º 20
0
        private static async Task <IActionResult> ProcessDialogAction(IBinder binder, InteractiveMessagePayload payload)
        {
            var action = payload.Actions.First();

            if (action.Name == "plan")
            {
                var dialogRequest = new OpenDialogRequest {
                    TriggerId = payload.TriggerId,
                    Dialog    = await DialogHelpers.GetPlanDialog(binder, action.Value)
                };

                await SlackHelper.OpenDialog(binder, payload.Team.Id, dialogRequest);
            }

            // NOTE: Présentement toutes les dialog_actions suppriment le message original
            return(Utils.Ok(new SlackMessage {
                DeleteOriginal = true
            }));
        }
Exemplo n.º 21
0
        public int AddCredit(User toUser, User fromUser, int creditToAdd, int charged)
        {
            toUser.Credits += creditToAdd;
            var item = new GiveCredit()
            {
                AmountToGiveNewUser = creditToAdd,
                DateTime            = DateTime.UtcNow,
                UserIdToGiveCredits = toUser.UserId,
                AmountCharged       = charged,
            };

            if (fromUser != null)
            {
                item.UserIdWhoGiveCredits = fromUser.UserId;
                // If we are giving a referal bonus eventually
                //item.AmountToGiveReferer = 0;
            }
            Db.GiveCredits.Add(item);
            Db.SaveChanges();

            var giveCreditText = "Credit"
                                 + Environment.NewLine
                                 + "To: "
                                 + toUser.Email
                                 + Environment.NewLine;

            if (fromUser != null)
            {
                giveCreditText = giveCreditText
                                 + "From: "
                                 + fromUser.Email
                                 + Environment.NewLine;
            }

            giveCreditText = giveCreditText
                             + "$"
                             + item.AmountToGiveNewUser;

            SlackHelper.sendGiveCreditChannel(giveCreditText);

            return(toUser.Credits);
        }
Exemplo n.º 22
0
        public static async Task <IActionResult> OnList(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "slack/commands/list")] HttpRequest req,
            [Table("proposals")] CloudTable proposalsTable,
            IBinder binder, ExecutionContext context)
        {
            Utils.SetCulture();

            var body = await SlackHelper.ReadSlackRequest(req, context);

            var parameters = SlackHelper.ParseBody(body);

            var team    = parameters["team_id"];
            var channel = parameters["channel_id"];

            var allProposals = await ProposalHelpers.GetActiveProposals(proposalsTable, Utils.GetPartitionKey(team, channel));

            var message = await MessageHelpers.GetListMessage(binder, allProposals, channel);

            return(Utils.Ok(message));
        }
Exemplo n.º 23
0
        static void Main(string[] args)
        {
            var arguments = LoadArguments(args);

            switch (arguments.Option)
            {
            case ProgramOption.Help:
                PrintHelp();
                return;

            case ProgramOption.Update:
            case ProgramOption.Post:

                var restaurantSettingses = JsonParser.ParseRestaurantSetting(arguments.JsonFilePath);
                var slackSettings        = JsonParser.ParseSlackSetting(arguments.SlackFilePath);

                var menus = MenuParser.GetMenuFromMenicka(restaurantSettingses);

                if (CheckMenu(menus) == false)
                {
                    ScheduleUdate();
                }
                else
                {
                    ScheduleEnd();
                }

                var slackHelper = new SlackHelper(slackSettings);

                if (arguments.Option == ProgramOption.Post)
                {
                    slackHelper.PostMenu(menus);
                }
                else
                {
                    slackHelper.UpdateMenu(menus);
                }

                break;
            }
        }
Exemplo n.º 24
0
        public static async Task <IActionResult> OnPlan(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "slack/commands/plan")] HttpRequest req,
            [Table("proposals")] CloudTable proposalsTable,
            IBinder binder, ExecutionContext context)
        {
            Utils.SetCulture();

            var body = await SlackHelper.ReadSlackRequest(req, context);

            var parameters   = SlackHelper.ParseBody(body);
            var partitionKey = Utils.GetPartitionKey(parameters["team_id"], parameters["channel_id"]);

            var dialogRequest = new OpenDialogRequest {
                TriggerId = parameters["trigger_id"],
                Dialog    = await DialogHelpers.GetPlanDialog(binder, partitionKey, defaultDate : parameters["text"])
            };

            await SlackHelper.OpenDialog(binder, parameters["team_id"], dialogRequest);

            return(Utils.Ok());
        }
Exemplo n.º 25
0
        public void ActivityToSlackShouldReturnMessageFromChannelData()
        {
            const string messageText = "Hello from message";

            var activity = new Activity
            {
                Timestamp   = new DateTimeOffset(),
                Text        = "Hello!",
                Recipient   = new ChannelAccount("testRecipientId"),
                ChannelData = new NewSlackMessage
                {
                    Text      = messageText,
                    Ephemeral = "testEphemeral"
                },
                Conversation = new ConversationAccount(id: "testId"),
            };

            var message = SlackHelper.ActivityToSlack(activity);

            Assert.Equal(messageText, message.Text);
        }
Exemplo n.º 26
0
        public static async Task <IActionResult> InstallCallback(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "install")] HttpRequest req,
            [Table("teams")] CloudTable teamsTable,
            ExecutionContext context)
        {
            if (!req.GetQueryParameterDictionary().TryGetValue("code", out var code))
            {
                return(new ContentResult {
                    Content = "Something went wrong: no code",
                    StatusCode = 400
                });
            }

            var accessTokenResponse = await SlackHelper.RequestAccessToken(code, context);

            var team = new Team(accessTokenResponse.TeamId, accessTokenResponse.AccessToken);
            await teamsTable.ExecuteAsync(TableOperation.InsertOrReplace(team));

            return(new ContentResult {
                Content = "All set!"
            });
        }
Exemplo n.º 27
0
        public static async Task CompletePlans(
            [TimerTrigger("0 0 13 * * *")] TimerInfo timer, // 1:00PM daily
            [Table("plans")] CloudTable plansTable,
            [Table("proposals")] CloudTable proposalsTable,
            IBinder binder)
        {
            Utils.SetCulture();

            var plans = await GetTodayPlansWithVideoAndResponsible(plansTable);

            foreach (var plan in plans)
            {
                var proposal = await proposalsTable.Retrieve <Proposal>(plan.PartitionKey, plan.Video);

                proposal.Complete = true;
                await proposalsTable.ExecuteAsync(TableOperation.Replace(proposal));

                await SlackHelper.PostMessage(binder, plan.Team, new PostMessageRequest {
                    Channel     = plan.Owner,
                    Text        = $"Avez-vous terminé l'écoute du vidéo _{proposal.Name}_?\nSi vous choisissez Non, alors le vidéo sera automatiquement re-proposé pour le continuer plus tard.",
                    Attachments =
                    {
                        new MessageAttachment     {
                            CallbackId = "proposal_action",
                            Actions    = new List <MessageAction> {
                                new MessageAction {
                                    Type = "button", Text = "Oui, le vidéo est terminé", Name = "done", Value = $"{plan.PartitionKey}/{plan.Video}"
                                },
                                new MessageAction {
                                    Type = "button", Text = "Non, pas encore", Name = "incomplete", Value = $"{plan.PartitionKey}/{plan.Video}"
                                }
                            }
                        }
                    }
                });

                await binder.RecordChannelActivity(proposal.Team, proposal.Channel);
            }
        }
        public async Task Run(
            [TimerTrigger(scheduleExpression)] TimerInfo myTimer,
            [Table(Constants.Repositories.TableName)] CloudTable table,
            ILogger log)
        {
            var version = Assembly.GetExecutingAssembly().GetCustomAttribute <AssemblyInformationalVersionAttribute>().InformationalVersion;
            var github  = new GitHubClient(new ProductHeaderValue($"{typeof(NewReleaseCheck).GetType().Namespace}", version));

            TableContinuationToken token = null;
            var repositoriesToCheck      = new List <RepositoryEntity>();

            do
            {
                var queryResult = await table.ExecuteQuerySegmentedAsync(new TableQuery <RepositoryEntity>(), token);

                repositoriesToCheck.AddRange(queryResult.Results);
                token = queryResult.ContinuationToken;
            } while (token != null);

            foreach (var repositoryToCheck in repositoriesToCheck)
            {
                var sourceRepository = $"{repositoryToCheck.Owner}/{repositoryToCheck.Name}";

                log.LogInformation($"Checking for new release in {sourceRepository}...");
                var latestSourceRelease = await github.Repository.Release.GetLatest(repositoryToCheck.Owner, repositoryToCheck.Name);

                if (repositoryToCheck.LastUpdated == null || repositoryToCheck.LastUpdated < latestSourceRelease.PublishedAt)
                {
                    await SlackHelper.SendReleaseNotification($"New release {latestSourceRelease.Name} in {sourceRepository} was found.", log);

                    repositoryToCheck.LastUpdated = DateTime.UtcNow;
                    await table.ExecuteAsync(TableOperation.Replace(repositoryToCheck));

                    continue;
                }

                log.LogInformation($"No new release in {sourceRepository} was found. Next check will be at {myTimer.Schedule.GetNextOccurrence(DateTime.Now)}", log);
            }
        }
Exemplo n.º 29
0
        public static BasicResponse contactFormImplementation(ContactFormRequest request)
        {
            if (String.IsNullOrWhiteSpace(request.email))
            {
                return(new BasicResponse {
                    message = "Please enter an email", status = 200, success = false
                });
            }
            else if (String.IsNullOrWhiteSpace(request.name))
            {
                return(new BasicResponse {
                    message = "Please enter a name", status = 200, success = false
                });
            }
            else if (String.IsNullOrWhiteSpace(request.message))
            {
                return(new BasicResponse {
                    message = "Please enter a message.", status = 200, success = false
                });
            }

            var contactFormBody = "Name: "
                                  + request.name
                                  + Environment.NewLine
                                  + "Email: "
                                  + request.email
                                  + Environment.NewLine
                                  + "Message: "
                                  + request.message;

            SlackHelper.sendSupportChannel(contactFormBody);

            EmailNoTemplateHelper.SendEmail("Pedal Contact", "*****@*****.**", contactFormBody);
            EmailTemplateHelper.SendEmail("Pedal Contact", request.email, Constants.PedalWebUrl, request.name, "contact_form.html", request.message);

            return(new BasicResponse {
                message = "Success", status = 200, success = true
            });
        }
Exemplo n.º 30
0
        public static async Task CancelOrphanPlans(
            [TimerTrigger("0 05 12 * * *")] TimerInfo timer, // 12:05AM daily
            [Table("plans")] CloudTable plansTable,
            [Table("proposals")] CloudTable proposalsTable,
            IBinder binder)
        {
            Utils.SetCulture();

            var plans = await GetTodayPlansWithoutResponsible(plansTable);

            foreach (var plan in plans)
            {
                if (!string.IsNullOrWhiteSpace(plan.Video))
                {
                    var proposal = await proposalsTable.Retrieve <Proposal>(plan.PartitionKey, plan.Video);

                    if (proposal != null)
                    {
                        proposal.PlannedIn = "";
                        await proposalsTable.ExecuteAsync(TableOperation.Replace(proposal));
                    }
                }

                var result = await plansTable.ExecuteAsync(TableOperation.Delete(plan));

                if (result.IsError())
                {
                    continue;
                }

                await SlackHelper.PostMessage(binder, plan.Team, new PostMessageRequest {
                    Channel = plan.Channel,
                    Text    = "Le Lunch & Watch de ce midi a été annulé car aucun responsable ne s'est manifesté."
                });
            }
        }