public async Task <Crate> ProcessUserEvents(IContainer container, string curExternalEventPayload)
        {
            var media = JsonConvert.DeserializeObject <InstagramMedia>(curExternalEventPayload.Substring(1, curExternalEventPayload.Length - 2));

            if (media.Object != "user")
            {
                throw new Exception("Unknown event source");
            }

            var instagramEventCM = new InstagramUserEventCM
            {
                MediaId        = media.MediaData.MediaId,
                UserId         = media.ObjectId,
                Time           = media.Time,
                SubscriptionId = media.SubscriptionId,
                ChangedAspect  = media.ChangedAspect
            };
            var eventReportContent = new EventReportCM
            {
                EventNames        = string.Join(",", instagramEventCM.ChangedAspect),
                ExternalAccountId = instagramEventCM.UserId,
                EventPayload      = new CrateStorage(Crate.FromContent("Instagram user event", instagramEventCM)),
                Manufacturer      = "Instagram"
            };
            ////prepare the event report
            var curEventReport = Crate.FromContent("Instagram user event", eventReportContent);

            return(curEventReport);
        }
Exemple #2
0
        public async Task <List <Crate> > ProcessUserEvents(IContainer container, string curExternalEventPayload)
        {
            var notification = JsonConvert.DeserializeObject <UserNotification>(curExternalEventPayload);

            if (notification.Object != "user")
            {
                throw new Exception("Unknown event source");
            }
            var eventList = new List <Crate>();

            foreach (var entry in notification.Entry)
            {
                var fbEventCM = new FacebookUserEventCM
                {
                    Id            = entry.Id,
                    ChangedFields = entry.ChangedFields,
                    Time          = entry.Time,
                    UserId        = entry.Uid
                };
                var eventReportContent = new EventReportCM
                {
                    EventNames        = string.Join(",", fbEventCM.ChangedFields),
                    EventPayload      = new CrateStorage(Crate.FromContent("Facebook user event", fbEventCM)),
                    Manufacturer      = "Facebook",
                    ExternalAccountId = fbEventCM.UserId
                };
                ////prepare the event report
                var curEventReport = Crate.FromContent("Facebook user event", eventReportContent);
                eventList.Add(curEventReport);
            }
            return(eventList);
        }
Exemple #3
0
        public async Task <Crate> ProcessEvent(string curExternalEventPayload)
        {
            try
            {
                var curEventEnvelope = SalesforceNotificationParser.GetEnvelopeInformation(curExternalEventPayload);

                string accountId = string.Empty;

                if (curEventEnvelope.Body.Notifications.NotificationList != null && curEventEnvelope.Body.Notifications.NotificationList.Length > 0)
                {
                    accountId = curEventEnvelope.Body.Notifications.NotificationList[0].SObject.OwnerId;
                }

                //prepare the content from the external event payload
                var eventReportContent = new EventReportCM
                {
                    EventNames        = GetEventNames(curEventEnvelope),
                    EventPayload      = ExtractEventPayload(curEventEnvelope),
                    ExternalAccountId = accountId,
                    Manufacturer      = "Salesforce",
                };

                return(Crate.FromContent("Standard Event Report", eventReportContent));
            }
            catch (Exception e)
            {
                await _loggerService.ReportTerminalError(e);

                throw new Exception($"Error while processing. \r\n{curExternalEventPayload}");
            }
        }
        private Crate PayloadRaw()
        {
            List <KeyValueDTO> payloadFields = new List <KeyValueDTO>();

            payloadFields.Add(new KeyValueDTO()
            {
                Key = "user_id", Value = GoogleAccount
            });
            payloadFields.Add(new KeyValueDTO()
            {
                Key = "response", Value = "What is your pets name=cat&What is your favorite book?=book&Who is your favorite superhero?=hero&"
            });
            var eventReportContent = new EventReportCM
            {
                EventNames        = "Google Form Response",
                EventPayload      = WrapPayloadDataCrate(payloadFields),
                ExternalAccountId = GoogleAccount,
                Manufacturer      = "Google"
            };

            //prepare the event report
            var curEventReport = Crate.FromContent("Standard Event Report", eventReportContent);

            return(curEventReport);
        }
        public static PayloadDTO PayloadDTO1()
        {
            var curFields = new List <KeyValueDTO>
            {
                new KeyValueDTO {
                    Key = "EnvelopeId", Value = "EnvelopeIdValue"
                }
            };

            EventReportCM curEventReportMS = new EventReportCM();

            curEventReportMS.EventNames   = "DocuSign Envelope Sent";
            curEventReportMS.Manufacturer = "DocuSign";
            curEventReportMS.EventPayload.Add(Crate.FromContent("Standard Event Report", new StandardPayloadDataCM(curFields)));
            var payload = new PayloadDTO(TestContainer_Id_1());

            using (var crateStorage = ObjectFactory.GetInstance <ICrateManager>().GetUpdatableStorage(payload))
            {
                crateStorage.Add(Crate.FromContent("Standard Event Report", curEventReportMS));
            }

            AddOperationalStateCrate(payload);

            return(payload);
        }
        public async Task Run_ShouldTerminateExecutionWhenChangedFieldIsNotFeed()
        {
            var activity = New <Monitor_Feed_Posts_v1>();
            //Arrage
            var activityContext = await ConfigureMonitorFeedPosts(activity);

            var fbEventCM = new FacebookUserEventCM
            {
                Id            = "123",
                ChangedFields = new string[] { "test" },
                Time          = "123",
                UserId        = "123"
            };
            var eventReportCrate = new EventReportCM
            {
                EventNames   = "feed",
                EventPayload = new CrateStorage(Crate.FromContent("Facebook user event", fbEventCM))
            };
            var containerExecutionContext = new ContainerExecutionContext
            {
                PayloadStorage = new CrateStorage(Crate.FromContent(string.Empty, new OperationalStateCM()), Crate.FromContent("Facebook user event", eventReportCrate))
            };

            //Act
            containerExecutionContext = await RunMonitorFeedPosts(activity, activityContext, containerExecutionContext);

            var operationalStateCM = containerExecutionContext.PayloadStorage.CrateContentsOfType <OperationalStateCM>().Single();

            Assert.True(operationalStateCM.CurrentActivityResponse.Type == ActivityResponse.RequestTerminate.ToString(), "Monitor_Feed_Posts_v1 doesn't terminate container execution when changed field doesn't contain feed");
        }
Exemple #7
0
        public Task <Crate> Process(string externalEventPayload)
        {
            if (string.IsNullOrEmpty(externalEventPayload))
            {
                return(null);
            }
            externalEventPayload = externalEventPayload.Trim('\"');
            var payloadFields = ParseSlackPayloadData(externalEventPayload);
            //This is for backwards compatibility. Messages received from Slack RTM mechanism will contain the owner of subscription whereas messegas received from WebHooks not
            var userName = payloadFields.FirstOrDefault(x => x.Key == "owner_name")?.Value ?? payloadFields.FirstOrDefault(x => x.Key == "user_name")?.Value;
            var teamId   = payloadFields.FirstOrDefault(x => x.Key == "team_id")?.Value;

            if (string.IsNullOrEmpty(userName) && string.IsNullOrEmpty(teamId))
            {
                return(null);
            }
            var eventReportContent = new EventReportCM
            {
                EventNames        = "Slack Outgoing Message",
                EventPayload      = WrapPayloadDataCrate(payloadFields),
                ExternalAccountId = userName,
                //Now plans won't be run for entire team but rather for specific user again
                //ExternalDomainId = teamId,
                Manufacturer = "Slack",
            };
            var curEventReport = Crate.FromContent("Standard Event Report", eventReportContent);

            return(Task.FromResult((Crate)curEventReport));
        }
        public async Task Run_ShouldTerminateExecutionWhenItCantFindPost()
        {
            var fbIntegrationService = new Mock <IFacebookIntegration>();

            fbIntegrationService.Setup(x => x.GetPostById(It.IsAny <string>(), It.IsAny <string>())).ReturnsAsync(null);
            ObjectFactory.Container.Inject(typeof(IFacebookIntegration), fbIntegrationService.Object);

            var activity = New <Monitor_Feed_Posts_v1>();
            //Arrage
            var activityContext = await ConfigureMonitorFeedPosts(activity);

            var fbEventCM = new FacebookUserEventCM
            {
                Id            = "123",
                ChangedFields = new string[] { "feed" },
                Time          = "123",
                UserId        = "123"
            };
            var eventReportCrate = new EventReportCM
            {
                EventNames   = "feed",
                EventPayload = new CrateStorage(Crate.FromContent("Facebook user event", fbEventCM))
            };
            var containerExecutionContext = new ContainerExecutionContext
            {
                PayloadStorage = new CrateStorage(Crate.FromContent(string.Empty, new OperationalStateCM()), Crate.FromContent("Facebook user event", eventReportCrate))
            };

            //Act
            containerExecutionContext = await RunMonitorFeedPosts(activity, activityContext, containerExecutionContext);

            var operationalStateCM = containerExecutionContext.PayloadStorage.CrateContentsOfType <OperationalStateCM>().Single();

            Assert.True(operationalStateCM.CurrentActivityResponse.Type == ActivityResponse.RequestTerminate.ToString(), "Monitor_Feed_Posts_v1 doesn't terminate container execution when activity can't find related post on facebook");
        }
Exemple #9
0
        public static Crate RawStandardEventReportFormat()
        {
            var eventReportMS = new EventReportCM()
            {
                EventNames = "DocuSign Envelope Sent"
            };

            return(Crate.FromContent("Standard Event Report", eventReportMS));
        }
Exemple #10
0
        public static ICrateStorage GetDirectMessageEventPayload()
        {
            var payload = new CrateStorage();

            payload.Add(Crate.FromContent(string.Empty, new OperationalStateCM()));
            var eventReport = new EventReportCM();

            eventReport.EventPayload.Add(Crate.FromContent(string.Empty, new StandardPayloadDataCM(new KeyValueDTO("channel_id", "D001"), new KeyValueDTO("user_name", "notuser"))));
            payload.Add(Crate.FromContent(string.Empty, eventReport));
            return(payload);
        }
        public static Crate Create(String eventName, String palletId, IEnumerable <Crate> crates)
        {
            var eventDTO = new EventReportCM
            {
                EventNames        = eventName,
                ExternalAccountId = "*****@*****.**"
            };

            eventDTO.EventPayload.AddRange(crates);

            return(Crate.FromContent("Fr8 Terminal Fact or Incident Report", eventDTO));
        }
Exemple #12
0
        public static CrateDTO CrateDTOForEvents(string externalAccountId)
        {
            EventReportCM curEventReportMS = new EventReportCM();

            curEventReportMS.EventNames = "DocuSign Envelope Sent";
            curEventReportMS.EventPayload.Add(FixtureData.GetEnvelopeIdCrate());
            curEventReportMS.ExternalAccountId = externalAccountId;
            curEventReportMS.Manufacturer      = "DocuSign";
            var curEventReport = Crate.FromContent("Standard Event Report", curEventReportMS);

            return(new CrateManager().ToDto(curEventReport));
        }
Exemple #13
0
        public void GetStandardEventSubscribers_ReturnsPlans()
        {
            FixtureData.TestPlanWithSubscribeEvent();
            IPlan         curPlan        = ObjectFactory.GetInstance <IPlan>();
            EventReportCM curEventReport = FixtureData.StandardEventReportFormat();

            var result = curPlan.GetMatchingPlans("testuser1", curEventReport);

            Assert.IsNotNull(result);
            Assert.Greater(result.Count, 0);
            Assert.Greater(result.Where(name => name.Name.Contains("StandardEventTesting")).Count(), 0);
        }
Exemple #14
0
        public async Task <PollingDataDTO> Poll(PollingDataDTO pollingData)
        {
            if (string.IsNullOrEmpty(pollingData.AdditionalConfigAttributes))
            {
                pollingData.Result = false;
                return(pollingData);
            }

            var attributesObject = JObject.Parse(pollingData.AdditionalConfigAttributes);

            var groupId = attributesObject["GroupId"]?.ToString();
            var statId  = attributesObject["StatId"]?.ToString();

            if (string.IsNullOrEmpty(groupId) || string.IsNullOrEmpty(statId))
            {
                pollingData.Result = false;
                return(pollingData);
            }

            if (string.IsNullOrEmpty(pollingData.Payload))
            {
                //polling is called for the first time
                var latestStatWithValues = await GetLatestStatItem(pollingData.AuthToken, groupId, statId);

                pollingData.Payload = JsonConvert.SerializeObject(latestStatWithValues);
            }
            else
            {
                var statXCM = JsonConvert.DeserializeObject <StatXItemCM>(pollingData.Payload);
                var latestStatWithValues = await GetLatestStatItem(pollingData.AuthToken, groupId, statId);

                //check value by value to see if a difference exist.
                if (StatXUtilities.CompareStatsForValueChanges(statXCM, latestStatWithValues))
                {
                    var eventReportContent = new EventReportCM
                    {
                        EventNames        = "StatXValueChange_" + statId.Substring(0, 18),
                        EventPayload      = new CrateStorage(Crate.FromContent("StatXValueChange", latestStatWithValues)),
                        Manufacturer      = "StatX",
                        ExternalAccountId = pollingData.ExternalAccountId
                    };

                    pollingData.Payload = JsonConvert.SerializeObject(latestStatWithValues);

                    await _hubReporter.Broadcast(Crate.FromContent("Standard Event Report", eventReportContent));
                }
            }

            pollingData.Result = true;
            return(pollingData);
        }
Exemple #15
0
        private EventRouter GetEventRouter(EventReportCM eventCm)
        {
            if (eventCm.EventNames.Equals("Terminal Incident"))
            {
                return(HandleTerminalIncident);
            }

            if (eventCm.EventNames.Equals("Terminal Fact"))
            {
                return(HandleTerminalEvent);
            }

            throw new InvalidOperationException("Unknown EventDTO with name: " + eventCm.EventNames);
        }
Exemple #16
0
        public static void ConfigureHubToReturnPayloadWithChannelMessageEvent()
        {
            var result = new PayloadDTO(Guid.Empty);

            using (var storage = CrateManager.GetUpdatableStorage(result))
            {
                storage.Add(Crate.FromContent(string.Empty, new OperationalStateCM()));
                var eventReport = new EventReportCM();
                eventReport.EventPayload.Add(Crate.FromContent(string.Empty, new StandardPayloadDataCM(new KeyValueDTO("channel_id", "C001"), new KeyValueDTO("user_name", "notuser"))));
                storage.Add(Crate.FromContent(string.Empty, eventReport));
            }
            ObjectFactory.Container.GetInstance <Mock <IHubCommunicator> >().Setup(x => x.GetPayload(It.IsAny <Guid>()))
            .Returns(Task.FromResult(result));
        }
        private async Task PushEnvelopesToTerminalEndpoint(IEnumerable <DocuSignEnvelopeCM_v2> envelopesToNotify)
        {
            foreach (var envelope in envelopesToNotify)
            {
                var eventReportContent = new EventReportCM
                {
                    EventNames        = DocuSignEventParser.GetEventNames(envelope),
                    EventPayload      = new CrateStorage(Crate.FromContent("DocuSign Connect Event", envelope)),
                    Manufacturer      = "DocuSign",
                    ExternalAccountId = envelope.ExternalAccountId
                };

                await _reporter.Broadcast(Crate.FromContent("Standard Event Report", eventReportContent));
            }
        }
        private Crate PayloadEmptyRaw()
        {
            List <KeyValueDTO> payloadFields = new List <KeyValueDTO>();
            var eventReportContent           = new EventReportCM
            {
                EventNames        = "Google Form Response",
                EventPayload      = WrapPayloadDataCrate(payloadFields),
                ExternalAccountId = GoogleAccount,
                Manufacturer      = "Google"
            };

            //prepare the event report
            var curEventReport = Crate.FromContent("Standard Event Report", eventReportContent);

            return(curEventReport);
        }
        public static EventReportCM TestTerminalEventDto()
        {
            var loggingDataCrate = LoggingDataCrateFactory.Create(new LoggingDataCM
            {
                PrimaryCategory   = "Operations",
                SecondaryCategory = "Action"
            });
            var eventDto = new EventReportCM
            {
                EventNames        = "Terminal Fact",
                ExternalAccountId = "*****@*****.**"
            };

            eventDto.EventPayload.Add(loggingDataCrate);

            return(eventDto);
        }
Exemple #20
0
        private void FindAndExecuteAccountPlans(
            IUnitOfWork uow,
            EventReportCM eventReportMS,
            Crate curCrateStandardEventReport,
            string curDockyardAccountId = null)
        {
            //find this Account's Plans
            var initialPlansList = uow.PlanRepository.GetPlanQueryUncached()
                                   .Where(pt => pt.Fr8AccountId == curDockyardAccountId && (pt.PlanState == PlanState.Executing || pt.PlanState == PlanState.Active)).ToList();
            var subscribingPlans = _plan.MatchEvents(initialPlansList, eventReportMS);

            Logger.GetLogger().Info($"Upon receiving event for account '{eventReportMS.ExternalAccountId}' {subscribingPlans.Count} of {initialPlansList.Count} will be notified");
            //When there's a match, it means that it's time to launch a new Process based on this Plan,
            foreach (var plan in subscribingPlans.Where(p => p.PlanState != PlanState.Inactive))
            {
                _plan.Enqueue(plan.Id, curCrateStandardEventReport);
            }
        }
Exemple #21
0
        private Crate ProcessConnectEvent(string curExternalEventPayload)
        {
            // Connect events come only for a single envelope
            var curDocuSignEnvelopeInfo = DocuSignEventParser.GetEnvelopeInformation(curExternalEventPayload);
            // transform XML structure into DocuSignEnvelopeCM_v2
            var curDocuSingEnvelopCM = DocuSignEventParser.ParseXMLintoCM(curDocuSignEnvelopeInfo);
            var eventReportContent   = new EventReportCM
            {
                EventNames        = DocuSignEventParser.GetEventNames(curDocuSignEnvelopeInfo),
                EventPayload      = new CrateStorage(Crate.FromContent("DocuSign Connect Event", curDocuSingEnvelopCM)),
                Manufacturer      = "DocuSign",
                ExternalAccountId = curDocuSignEnvelopeInfo.EnvelopeStatus.Email
            };

            ////prepare the event report
            var curEventReport = Crate.FromContent("Standard Event Report", eventReportContent);

            return(curEventReport);
        }
        public async Task <Crate> ProcessExternalEvents(string curExternalEventPayload)
        {
            var issue            = JsonConvert.DeserializeObject <Models.JiraIssueEvent>(curExternalEventPayload);
            var atlassianEventCM = new JiraIssueWithCustomFieldsCM
            {
                JiraIssue = new AtlassianIssueEvent
                {
                    IssueKey      = issue.Issue.Key,
                    IssueId       = issue.Issue.Id,
                    UserId        = issue.User.Email,
                    Time          = issue.Timestamp,
                    ChangedAspect = issue.Issue.Fields.Project.Name,
                    EventType     = issue.IssueEventTypeName,
                    IssueEvent    = new Fr8.Infrastructure.Data.Manifests.JiraIssueEvent
                    {
                        IssueAssigneeName         = issue.Issue.Fields.Assignee.DisplayName,
                        IssueType                 = issue.Issue.Fields.IssueType.Name,
                        IssueAssigneeEmailAddress = issue.Issue.Fields.Assignee.EmailAddress,
                        IssuePriority             = issue.Issue.Fields.Priority.Name,
                        IssueResolution           = issue.Issue.Fields.Resolution,
                        IssueStatus               = issue.Issue.Fields.Status.Name,
                        IssueSummary              = issue.Issue.Fields.Summary,
                        ProjectName               = issue.Issue.Fields.Project.Name,
                        Timestamp                 = issue.Timestamp,
                        UserName     = issue.User.DisplayName,
                        WebhookEvent = issue.WebhookEvent,
                        Description  = issue.Issue.Fields.Description
                    }
                },
                CustomFields = null
            };
            var eventReportContent = new EventReportCM
            {
                EventNames        = string.Join(",", atlassianEventCM.JiraIssue.ChangedAspect),
                ExternalAccountId = atlassianEventCM.JiraIssue.UserId,
                EventPayload      = new CrateStorage(Crate.FromContent("Atlassian Issue Event", atlassianEventCM)),
                Manufacturer      = "Atlassian"
            };

            var curEventReport = Crate.FromContent("Atlassian Issue Event", eventReportContent);

            return(curEventReport);
        }
Exemple #23
0
        public async Task <Crate> Process(IContainer container, string externalEventPayload)
        {
            if (string.IsNullOrEmpty(externalEventPayload))
            {
                return(null);
            }

            var payloadFields = ParseGoogleFormPayloadData(externalEventPayload);

            if (payloadFields.Count == 0)
            {
                var jo           = (JObject)JsonConvert.DeserializeObject(externalEventPayload);
                var curFr8UserId = jo["fr8_user_id"].Value <string>();
                if (!string.IsNullOrEmpty(curFr8UserId))
                {
                    var hub  = container.GetInstance <IHubCommunicator>();
                    var plan = new GoogleMTSFPlan(curFr8UserId, hub, "alexed", "general");
                    await plan.CreateAndActivateNewMTSFPlan();
                }
            }

            var externalAccountId = payloadFields.FirstOrDefault(x => x.Key == "user_id");

            if (externalAccountId == null || string.IsNullOrEmpty(externalAccountId.Value))
            {
                return(null);
            }

            var eventReportContent = new EventReportCM
            {
                EventNames        = "Google Form Response",
                EventPayload      = WrapPayloadDataCrate(payloadFields),
                ExternalAccountId = externalAccountId.Value,
                Manufacturer      = "Google"
            };

            //prepare the event report
            var curEventReport = Crate.FromContent("Standard Event Report", eventReportContent);

            return(curEventReport);
        }
Exemple #24
0
        public IList <PlanDO> GetMatchingPlans(string userId, EventReportCM curEventReport)
        {
            if (String.IsNullOrEmpty(userId))
            {
                throw new ArgumentNullException("Parameter UserId is null");
            }

            if (curEventReport == null)
            {
                throw new ArgumentNullException("Parameter Standard Event Report is null");
            }

            //1. Query all PlanDO that are Active
            //2. are associated with the determined DockyardAccount
            //3. their first Activity has a Crate of  Class "Standard Event Subscriptions" which has inside of it an event name that matches the event name
            //in the Crate of Class "Standard Event Reports" which was passed in.
            var curPlans = _dockyardAccount.GetActivePlans(userId).ToList();

            return(MatchEvents(curPlans, curEventReport));
            //3. Get ActivityDO
        }
Exemple #25
0
        public static ContainerExecutionContext FalseInstagramContainerExecutionContext()
        {
            var instagramEventCM = new InstagramUserEventCM
            {
                MediaId        = "123",
                UserId         = "123",
                ChangedAspect  = "test",
                Time           = "123",
                SubscriptionId = "123"
            };
            var eventReportCrate = new EventReportCM
            {
                EventNames   = "media",
                EventPayload = new CrateStorage(Crate.FromContent("Instagram user event", instagramEventCM))
            };
            var containerExecutionContext = new ContainerExecutionContext
            {
                PayloadStorage = new CrateStorage(Crate.FromContent(string.Empty, new OperationalStateCM()), Crate.FromContent("Instagram user event", eventReportCrate))
            };

            return(containerExecutionContext);
        }
Exemple #26
0
        public List <PlanDO> MatchEvents(List <PlanDO> curPlans, EventReportCM curEventReport)
        {
            List <PlanDO> subscribingPlans = new List <PlanDO>();

            foreach (var curPlan in curPlans)
            {
                // Get the first activity
                var actionDO = GetFirstActivityWithEventSubscriptions(curPlan.Id);

                if (actionDO != null)
                {
                    var storage = _crate.GetStorage(actionDO.CrateStorage);

                    foreach (var subscriptionsList in storage.CrateContentsOfType <EventSubscriptionCM>())
                    {
                        var  manufacturer = subscriptionsList.Manufacturer;
                        bool hasEvents;
                        if (string.IsNullOrEmpty(manufacturer) || string.IsNullOrEmpty(curEventReport.Manufacturer))
                        {
                            hasEvents = subscriptionsList.Subscriptions.Any(events => curEventReport.EventNames.ToUpper().Trim().Replace(" ", "").Contains(events.ToUpper().Trim().Replace(" ", "")));
                        }
                        else
                        {
                            hasEvents = subscriptionsList.Subscriptions.Any(events => curEventReport.Manufacturer == manufacturer &&
                                                                            curEventReport.EventNames.ToUpper().Trim().Replace(" ", "").Contains(events.ToUpper().Trim().Replace(" ", "")));
                        }

                        if (hasEvents)
                        {
                            subscribingPlans.Add(curPlan);
                        }
                    }
                }
            }
            return(subscribingPlans);
        }
        public async Task <PollingDataDTO> Poll(PollingDataDTO pollingData, GDrivePollingType pollingType)
        {
            var googleAuthToken = JsonConvert.DeserializeObject <GoogleAuthDTO>(pollingData.AuthToken);
            var driveService    = await _googleDrive.CreateDriveService(googleAuthToken);

            string startPageToken;

            if (string.IsNullOrEmpty(pollingData.Payload))
            {
                var response = driveService.Changes.GetStartPageToken().Execute();
                startPageToken = response.StartPageTokenValue;
            }
            else
            {
                startPageToken = pollingData.Payload;
            }

            var changedFiles = new Dictionary <string, string>();

            var pageToken = startPageToken;

            while (pageToken != null)
            {
                var request = driveService.Changes.List(pageToken);
                request.Fields = "changes,kind,newStartPageToken,nextPageToken";
                request.Spaces = "drive";

                var changes = request.Execute();
                foreach (var change in changes.Changes)
                {
                    if (!string.IsNullOrEmpty(change.File.MimeType) &&
                        change.File.MimeType.ToUpper() == _fileTypes[pollingType])
                    {
                        if (!changedFiles.ContainsKey(change.FileId))
                        {
                            changedFiles.Add(change.FileId, change.File.Name);
                        }
                    }
                }

                if (!string.IsNullOrEmpty(changes.NewStartPageToken))
                {
                    startPageToken = changes.NewStartPageToken;
                }

                pageToken = changes.NextPageToken;
            }

            if (changedFiles.Count > 0)
            {
                var changedFilesCM = new KeyValueListCM();
                foreach (var pair in changedFiles)
                {
                    changedFilesCM.Values.Add(new KeyValueDTO(pair.Key, pair.Value));
                }

                var eventReportContent = new EventReportCM
                {
                    EventNames        = _eventNames[pollingType],
                    EventPayload      = new CrateStorage(Crate.FromContent("ChangedFiles", changedFilesCM)),
                    Manufacturer      = "Google",
                    ExternalAccountId = pollingData.ExternalAccountId
                };

                Logger.Info("Polling for Google Drive: changed files of type \"" + pollingType.ToString() + "\"");
                await _reporter.Broadcast(Crate.FromContent("Standard Event Report", eventReportContent));
            }

            pollingData.Payload = startPageToken;
            return(pollingData);
        }
        public async Task <PollingDataDTO> Poll(PollingDataDTO pollingData)
        {
            Logger.Info($"Polling for Gmail was launched {pollingData.ExternalAccountId}");

            var serv            = new GoogleGmail();
            var googleAuthToken = JsonConvert.DeserializeObject <GoogleAuthDTO>(pollingData.AuthToken);
            var service         = await serv.CreateGmailService(googleAuthToken);

            if (string.IsNullOrEmpty(pollingData.Payload))
            {
                //Polling is called for the first time
                //we have no history id to synchronise partitially, so we request the last message from the inbox
                UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List(pollingData.ExternalAccountId);
                request.RequestParameters["maxResults"] = new Parameter()
                {
                    DefaultValue = "1", Name = "maxResults", ParameterType = "query"
                };
                var list = request.Execute();

                //then we have to get its details and historyId (to use with history listing API method)

                pollingData.Payload = GetHistoryId(service, list.Messages.FirstOrDefault().Id, pollingData.ExternalAccountId);
                Logger.Info($"Polling for Gmail {pollingData.ExternalAccountId}: remembered the last email in the inbox");
            }
            else
            {
                var request = service.Users.History.List(pollingData.ExternalAccountId);
                request.StartHistoryId = ulong.Parse(pollingData.Payload);
                var result = request.Execute();
                Logger.Info($"Polling for Gmail {pollingData.ExternalAccountId}: received a history of changes");
                if (result.History != null)
                {
                    foreach (var historyRecord in result.History)
                    {
                        if (historyRecord.MessagesAdded != null)
                        {
                            foreach (var mail in historyRecord.MessagesAdded.Reverse())
                            {
                                //TODO: make a batch request for emails, instead of calling one by one
                                var email = GetEmail(service, mail.Message.Id, pollingData.ExternalAccountId);
                                var eventReportContent = new EventReportCM
                                {
                                    EventNames        = "GmailInbox",
                                    EventPayload      = new CrateStorage(Crate.FromContent("GmailInbox", email)),
                                    Manufacturer      = "Google",
                                    ExternalAccountId = pollingData.ExternalAccountId
                                };

                                pollingData.Payload = email.MessageID;
                                Logger.Info("Polling for Gmail: got a new email, broadcasting an event to the Hub");
                                await _reporter.Broadcast(Crate.FromContent("Standard Event Report", eventReportContent));
                            }
                        }
                    }
                }
                else
                {
                    Logger.Info($"Polling for Gmail {pollingData.ExternalAccountId}: no new emails");
                }
            }
            pollingData.Result = true;
            return(pollingData);
        }
Exemple #29
0
 public List <PlanDO> MatchEvents(List <PlanDO> curPlans, EventReportCM curEventReport)
 {
     return(_target.MatchEvents(curPlans, curEventReport));
 }
Exemple #30
0
 public IList <PlanDO> GetMatchingPlans(string userId, EventReportCM curEventReport)
 {
     return(_target.GetMatchingPlans(userId, curEventReport));
 }