Ejemplo n.º 1
0
        protected override IEnumerable <WebApiSubscription> DoGetItems()
        {
            var client       = GetClient <ServiceHooksPublisherHttpClient>();
            var subscription = GetParameter <object>(nameof(GetServiceHookSubscription.Subscription));
            var eventType    = GetParameter <string>(nameof(GetServiceHookSubscription.EventType));

            var publisher = HasParameter(nameof(GetServiceHookSubscription.Publisher))?
                            GetItem <WebApiPublisher>(): null;
            var consumer = HasParameter(nameof(GetServiceHookSubscription.Consumer))?
                           GetItem <WebApiConsumer>(): null;

            while (true)
            {
                switch (subscription)
                {
                case WebApiSubscription p:
                {
                    yield return(p);

                    yield break;
                }

                case string s:
                {
                    var query = new SubscriptionsQuery()
                    {
                        PublisherId = publisher?.Id,
                        ConsumerId  = consumer?.Id,
                        EventType   = eventType
                    };

                    var result = client.QuerySubscriptionsAsync(query)
                                 .GetResult("Error getting service hook subscriptions")
                                 .Results
                                 .Where(sub => sub.ActionDescription.IsLike(s));

                    foreach (var r in result)
                    {
                        yield return(r);
                    }
                    yield break;
                }

                default:
                {
                    throw new ArgumentException($"Invalid or non-existent Subscription '{subscription}'");
                }
                }
            }
        }
        internal async Task <Guid> AddAsync(string projectName, string @event, EventFilters filters, InstanceName instance, string ruleName, CancellationToken cancellationToken)
        {
            logger.WriteVerbose($"Reading Azure DevOps project data...");
            var projectClient = devops.GetClient <ProjectHttpClient>();
            var project       = await projectClient.GetProject(projectName);

            logger.WriteInfo($"Project {projectName} data read.");

            var rules = new AggregatorRules(azure, logger);

            logger.WriteVerbose($"Retrieving {ruleName} Function Key...");
            (string ruleUrl, string ruleKey) = await rules.GetInvocationUrlAndKey(instance, ruleName, cancellationToken);

            logger.WriteInfo($"{ruleName} Function Key retrieved.");

            var serviceHooksClient = devops.GetClient <ServiceHooksPublisherHttpClient>();

            // check if the subscription already exists and bail out
            var query = new SubscriptionsQuery {
                PublisherId           = DevOpsEvents.PublisherId,
                PublisherInputFilters = new InputFilter[] {
                    new InputFilter {
                        Conditions = new List <InputFilterCondition> {
                            new InputFilterCondition
                            {
                                InputId       = "projectId",
                                InputValue    = project.Id.ToString(),
                                Operator      = InputFilterOperator.Equals,
                                CaseSensitive = false
                            }
                        }
                    }
                },
                EventType            = @event,
                ConsumerInputFilters = new InputFilter[] {
                    new InputFilter {
                        Conditions = new List <InputFilterCondition> {
                            new InputFilterCondition
                            {
                                InputId       = "url",
                                InputValue    = ruleUrl,
                                Operator      = InputFilterOperator.Equals,
                                CaseSensitive = false
                            }
                        }
                    }
                }
            };

            cancellationToken.ThrowIfCancellationRequested();
            var queryResult = await serviceHooksClient.QuerySubscriptionsAsync(query);

            if (queryResult.Results.Any())
            {
                logger.WriteWarning($"There is already such a mapping.");
                return(Guid.Empty);
            }

            // see https://docs.microsoft.com/en-us/azure/devops/service-hooks/consumers?toc=%2Fvsts%2Fintegrate%2Ftoc.json&bc=%2Fvsts%2Fintegrate%2Fbreadcrumb%2Ftoc.json&view=vsts#web-hooks
            var subscriptionParameters = new Subscription()
            {
                ConsumerId       = "webHooks",
                ConsumerActionId = "httpRequest",
                ConsumerInputs   = new Dictionary <string, string>
                {
                    { "url", ruleUrl },
                    { "httpHeaders", $"x-functions-key:{ruleKey}" },
                    // careful with casing!
                    { "resourceDetailsToSend", "all" },
                    { "messagesToSend", "none" },
                    { "detailedMessagesToSend", "none" },
                },
                EventType       = @event,
                PublisherId     = DevOpsEvents.PublisherId,
                PublisherInputs = new Dictionary <string, string>
                {
                    { "projectId", project.Id.ToString() },

                    /* TODO consider offering additional filters using the following
                     * { "tfsSubscriptionId", devops.ServerId },
                     * { "teamId", null },
                     * // The string that must be found in the comment.
                     * { "commentPattern", null },
                     */
                },
            };

            if (!string.IsNullOrWhiteSpace(filters.AreaPath))
            {
                // Filter events to include only work items under the specified area path.
                subscriptionParameters.PublisherInputs.Add("areaPath", filters.AreaPath);
            }
            if (!string.IsNullOrWhiteSpace(filters.Type))
            {
                // Filter events to include only work items of the specified type.
                subscriptionParameters.PublisherInputs.Add("workItemType", filters.Type);
            }
            if (!string.IsNullOrWhiteSpace(filters.Tag))
            {
                // Filter events to include only work items containing the specified tag.
                subscriptionParameters.PublisherInputs.Add("tag", filters.Tag);
            }
            if (filters.Fields.Any())
            {
                // Filter events to include only work items with the specified field(s) changed
                subscriptionParameters.PublisherInputs.Add("changedFields", string.Join(',', filters.Fields));
            }

            logger.WriteVerbose($"Adding mapping for {@event}...");
            var newSubscription = await serviceHooksClient.CreateSubscriptionAsync(subscriptionParameters);

            logger.WriteInfo($"Event subscription {newSubscription.Id} setup.");
            return(newSubscription.Id);
        }
Ejemplo n.º 3
0
        internal async Task <Guid> AddAsync(string projectName, string @event, EventFilters filters, InstanceName instance, string ruleName, bool impersonateExecution, CancellationToken cancellationToken)
        {
            logger.WriteVerbose($"Reading Azure DevOps project data...");
            var projectClient = devops.GetClient <ProjectHttpClient>();
            var project       = await projectClient.GetProject(projectName);

            logger.WriteInfo($"Project {projectName} data read.");

            var rules = new AggregatorRules(azure, logger);

            logger.WriteVerbose($"Retrieving {ruleName} Function Key...");
            (Uri ruleUrl, string ruleKey) = await rules.GetInvocationUrlAndKey(instance, ruleName, cancellationToken);

            logger.WriteInfo($"{ruleName} Function Key retrieved.");

            ruleUrl = ruleUrl.AddToUrl(impersonate: impersonateExecution);

            // check if the subscription already exists and bail out
            var query = new SubscriptionsQuery {
                PublisherId           = DevOpsEvents.PublisherId,
                PublisherInputFilters = new InputFilter[] {
                    new InputFilter {
                        Conditions = new List <InputFilterCondition> (filters.ToFilterConditions())
                        {
                            new InputFilterCondition
                            {
                                InputId       = "projectId",
                                InputValue    = project.Id.ToString(),
                                Operator      = InputFilterOperator.Equals,
                                CaseSensitive = false
                            }
                        }
                    }
                },
                EventType            = @event,
                ConsumerInputFilters = new InputFilter[] {
                    new InputFilter {
                        Conditions = new List <InputFilterCondition> {
                            new InputFilterCondition
                            {
                                InputId       = "url",
                                InputValue    = ruleUrl.ToString(),
                                Operator      = InputFilterOperator.Equals,
                                CaseSensitive = false
                            }
                        }
                    }
                }
            };

            cancellationToken.ThrowIfCancellationRequested();
            var serviceHooksClient = devops.GetClient <ServiceHooksPublisherHttpClient>();
            var queryResult        = await serviceHooksClient.QuerySubscriptionsAsync(query);

            if (queryResult.Results.Any())
            {
                logger.WriteWarning($"There is already such a mapping.");
                return(Guid.Empty);
            }

            // see https://docs.microsoft.com/en-us/azure/devops/service-hooks/consumers?toc=%2Fvsts%2Fintegrate%2Ftoc.json&bc=%2Fvsts%2Fintegrate%2Fbreadcrumb%2Ftoc.json&view=vsts#web-hooks
            var subscriptionParameters = new Subscription()
            {
                ConsumerId       = "webHooks",
                ConsumerActionId = "httpRequest",
                ConsumerInputs   = new Dictionary <string, string>
                {
                    { "url", ruleUrl.ToString() },
                    { "httpHeaders", $"x-functions-key:{ruleKey}" },
                    // careful with casing!
                    { "resourceDetailsToSend", "all" },
                    { "messagesToSend", "none" },
                    { "detailedMessagesToSend", "none" },
                },
                EventType       = @event,
                PublisherId     = DevOpsEvents.PublisherId,
                PublisherInputs = new Dictionary <string, string> (filters.ToInputs())
                {
                    { "projectId", project.Id.ToString() },

                    /* TODO consider offering additional filters using the following
                     * { "tfsSubscriptionId", devops.ServerId },
                     * { "teamId", null },
                     * // The string that must be found in the comment.
                     * { "commentPattern", null },
                     */
                },
                // Resource Version 1.0 currently needed for WorkItems, newer Version send EMPTY Relation Information.
                ResourceVersion = "1.0",
            };

            logger.WriteVerbose($"Adding mapping for {@event}...");
            var newSubscription = await serviceHooksClient.CreateSubscriptionAsync(subscriptionParameters);

            logger.WriteInfo($"Event subscription {newSubscription.Id} setup.");
            return(newSubscription.Id);
        }
Ejemplo n.º 4
0
 /// <summary>
 /// Gets static list of stocks for a subscription
 /// </summary>
 /// <param name="subscriptionId"></param>
 /// <returns></returns>
 public IEnumerable <Stock> GetStaticStocksForSubscription(int subscriptionId)
 {
     return(SubscriptionsQuery.Where(s => s.ID == subscriptionId).Include("Stocks").SelectMany(s => s.Stocks));
 }
Ejemplo n.º 5
0
 /// <summary>
 /// Gets a single subscription by id
 /// </summary>
 /// <param name="subscriptionId"></param>
 /// <returns></returns>
 public Subscription GetSubscription(int subscriptionId)
 {
     return(SubscriptionsQuery.Include("DataProvider")
            .Include("StockListProvider")
            .FirstOrDefault(s => s.ID == subscriptionId));
 }
Ejemplo n.º 6
0
 /// <summary>
 /// Gets all subscriptions
 /// </summary>
 /// <returns></returns>
 public IEnumerable <Subscription> GetAllActiveSubscriptions()
 {
     return(SubscriptionsQuery.Include("DataProvider")
            .Include("StockListProvider")
            .Where(s => s.Active));
 }