Completed
Pull Request — master (#404)
by Edward
02:08
created

ActiveCampaignWebhook   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 62
Duplicated Lines 0 %
Metric Value
dl 0
loc 62
rs 10
wmc 10

9 Methods

Rating   Name   Duplication   Size   Complexity  
A run() 0 2 1
A remove_trigger() 0 3 1
A _get_headers_as_dict() 0 5 2
A update_trigger() 0 3 1
A cleanup() 0 3 1
A setup() 0 23 3
A add_trigger() 0 3 1
A ac_events() 0 10 1
A status() 0 3 1
1
from st2reactor.sensor.base import Sensor
2
from flask import Flask, request
3
import json
4
5
6
WEBHOOK_TRIGGER_REF = "activecampaign.webhook"
7
8
9
class ActiveCampaignWebhook(Sensor):
10
    """
11
    Receives webhooks from ActiveCampaign. Implemented as standalone
12
    to be run on DMZ.
13
14
    * self._sensor_service
15
        - provides utilities like
16
            - get_logger() - returns logger instance specific to this sensor.
17
            - dispatch() for dispatching triggers into the system.
18
    * self._config
19
        - contains parsed configuration that was specified as
20
          config.yaml in the pack.
21
    """
22
23
    def setup(self):
24
        self.host = self._config['webhook']['host']
25
        self.port = self._config['webhook']['port']
26
        path = self._config['webhook']['path']
27
        route = '/{}/{}'.format(path, '<string:action>')
28
29
        self.app = Flask(__name__)
30
        self.log = self._sensor_service.get_logger(__name__)
31
32
        @self.app.route('/status')
33
        def status():
34
            return json.dumps({"response": "OK"})
35
36
        @self.app.route(route, methods=['POST'])
37
        def ac_events(action):
38
39
            payload = {}
40
            payload['headers'] = self._get_headers_as_dict(request.headers)
41
            payload['body'] = request.form.to_dict(flat=True)
42
            payload['action'] = action
43
44
            self._sensor_service.dispatch(WEBHOOK_TRIGGER_REF, payload)
45
            return json.dumps({"response": "triggerposted"})
46
47
    def run(self):
48
        self.app.run(host=self.host, port=self.port, debug=True)
49
50
    def cleanup(self):
51
        # This is called when the st2 system goes down.
52
        pass
53
54
    def add_trigger(self, trigger):
55
        # This method is called when trigger is created
56
        pass
57
58
    def update_trigger(self, trigger):
59
        # This method is called when trigger is updated
60
        pass
61
62
    def remove_trigger(self, trigger):
63
        # This method is called when trigger is deleted
64
        pass
65
66
    def _get_headers_as_dict(self, headers):
67
        headers_dict = {}
68
        for key, value in headers:
69
            headers_dict[key] = value
70
        return headers_dict
71