<commit_before># Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

try:
    import simplejson as json
except ImportError:
    import json

import six
import pecan
import uuid
from pecan import abort
from pecan.rest import RestController
from six.moves.urllib import parse as urlparse
urljoin = urlparse.urljoin

from st2common import log as logging
from st2common.constants.triggers import WEBHOOK_TRIGGER_TYPES
from st2common.models.api.base import jsexpose
from st2common.models.api.trace import TraceContext
import st2common.services.triggers as trigger_service
from st2common.services.triggerwatcher import TriggerWatcher
from st2common.transport.reactor import TriggerDispatcher
from st2common.util.http import parse_content_type_header
from st2common.rbac.types import PermissionType
from st2common.rbac.decorators import request_user_has_webhook_permission

http_client = six.moves.http_client

LOG = logging.getLogger(__name__)

TRACE_TAG_HEADER = 'St2-Trace-Tag'


class HooksHolder(object):
    """
    Maintains a hook to Trigger mapping.
    """
    def __init__(self):
        self._triggers_by_hook = {}

    def __contains__(self, key):
        return key in self._triggers_by_hook

    def add_hook(self, hook, trigger):
        if hook not in self._triggers_by_hook:
            self._triggers_by_hook[hook] = []
        self._triggers_by_hook[hook].append(trigger)

    def remove_hook(self, hook, trigger):
        if hook not in self._triggers_by_hook:
            return False
        remove_index = -1
        for idx, item in enumerate(self._triggers_by_hook[hook]):
            if item['id'] == trigger['id']:
                remove_index = idx
                break
        if remove_index < 0:
            return False
        self._triggers_by_hook[hook].pop(remove_index)
        if not self._triggers_by_hook[hook]:
            del self._triggers_by_hook[hook]
        return True

    def get_triggers_for_hook(self, hook):
        return self._triggers_by_hook.get(hook, [])

    def get_all(self):
        triggers = []
        for values in six.itervalues(self._triggers_by_hook):
            triggers.extend(triggers)
        return triggers


class WebhooksController(RestController):
    def __init__(self, *args, **kwargs):
        super(WebhooksController, self).__init__(*args, **kwargs)
        self._hooks = HooksHolder()
        self._base_url = '/webhooks/'
        self._trigger_types = WEBHOOK_TRIGGER_TYPES.keys()

        self._trigger_dispatcher = TriggerDispatcher(LOG)
        queue_suffix = self.__class__.__name__<commit_msg>Fix obvious bug<commit_after># Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

try:
    import simplejson as json
except ImportError:
    import json

import six
import pecan
import uuid
from pecan import abort
from pecan.rest import RestController
from six.moves.urllib import parse as urlparse
urljoin = urlparse.urljoin

from st2common import log as logging
from st2common.constants.triggers import WEBHOOK_TRIGGER_TYPES
from st2common.models.api.base import jsexpose
from st2common.models.api.trace import TraceContext
import st2common.services.triggers as trigger_service
from st2common.services.triggerwatcher import TriggerWatcher
from st2common.transport.reactor import TriggerDispatcher
from st2common.util.http import parse_content_type_header
from st2common.rbac.types import PermissionType
from st2common.rbac.decorators import request_user_has_webhook_permission

http_client = six.moves.http_client

LOG = logging.getLogger(__name__)

TRACE_TAG_HEADER = 'St2-Trace-Tag'


class HooksHolder(object):
    """
    Maintains a hook to Trigger mapping.
    """
    def __init__(self):
        self._triggers_by_hook = {}

    def __contains__(self, key):
        return key in self._triggers_by_hook

    def add_hook(self, hook, trigger):
        if hook not in self._triggers_by_hook:
            self._triggers_by_hook[hook] = []
        self._triggers_by_hook[hook].append(trigger)

    def remove_hook(self, hook, trigger):
        if hook not in self._triggers_by_hook:
            return False
        remove_index = -1
        for idx, item in enumerate(self._triggers_by_hook[hook]):
            if item['id'] == trigger['id']:
                remove_index = idx
                break
        if remove_index < 0:
            return False
        self._triggers_by_hook[hook].pop(remove_index)
        if not self._triggers_by_hook[hook]:
            del self._triggers_by_hook[hook]
        return True

    def get_triggers_for_hook(self, hook):
        return self._triggers_by_hook.get(hook, [])

    def get_all(self):
        triggers = []
        for values in six.itervalues(self._triggers_by_hook):
            triggers.extend(values)
        return triggers


class WebhooksController(RestController):
    def __init__(self, *args, **kwargs):
        super(WebhooksController, self).__init__(*args, **kwargs)
        self._hooks = HooksHolder()
        self._base_url = '/webhooks/'
        self._trigger_types = WEBHOOK_TRIGGER_TYPES.keys()

        self._trigger_dispatcher = TriggerDispatcher(LOG)
        queue_suffix = self.__class__.__name__
{'fraction_non_alphanumeric': 0.07231467473524962, 'fraction_numerical': 0.005143721633888048, 'mean_word_length': 3.463875759621877, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7474282', 'n_tokens_mistral': 1904, 'n_tokens_neox': 1877, 'n_words': 583}