Completed
Push — master ( 69fa9b...92a354 )
by Fox
01:16
created

ServiceSlack.save_data()   B

Complexity

Conditions 2

Size

Total Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
c 1
b 0
f 0
dl 0
loc 33
rs 8.8571
1
# coding: utf-8
2
import requests
3
4
# django classes
5
from django.utils.log import getLogger
6
from django.core.cache import caches
7
8
# django_th classes
9
from django_th.services.services import ServicesMgr
10
from django_th.models import TriggerService
11
from th_slack.models import Slack
12
13
logger = getLogger('django_th.trigger_happy')
14
15
cache = caches['th_slack']
16
17
18
class ServiceSlack(ServicesMgr):
19
    """
20
        Service Slack
21
    """
22
    def __init__(self, token=None, **kwargs):
23
        super(ServiceSlack, self).__init__(token, **kwargs)
24
25
    def read_data(self, **kwargs):
26
        """
27
            get the data from the service
28
29
            :param kwargs: contain keyword args : trigger_id and model name
30
            :type kwargs: dict
31
            :rtype: dict
32
        """
33
        trigger_id = kwargs.get('trigger_id')
34
        kwargs['model_name'] = 'Slack'
35
36
        # get the URL from the trigger id
37
        data = super(ServiceSlack, self).read_data(**kwargs)
38
        cache.set('th_slack_' + str(trigger_id), data)
39
        # return the data
40
        return data
41
42
    def save_data(self, trigger_id, **data):
43
        """
44
            get the data from the service
45
46
            :param trigger_id: id of the trigger
47
            :params data, dict
48
            :rtype: dict
49
        """
50
        status = False
51
        service = TriggerService.objects.get(id=trigger_id)
52
        desc = service.description
53
54
        slack = Slack.objects.get(trigger_id=trigger_id)
55
56
        title = data.get('subject')
57
        type_action = data.get('type_action')
58
59
        # set the bot username of Slack to the name of the
60
        # provider service
61
        username = service.provider.name.name.split('Service')[1]
62
        # 'build' a link
63
        title_link = '<' + data.get('permalink') + '|' + title + '>'
64
        data = '*' + desc + '*: ' + type_action + ': ' + title_link
65
66
        payload = {'username': username,
67
                   'text': data}
68
69
        r = requests.post(slack.webhook_url, json=payload)
70
71
        if r.status_code == requests.codes.ok:
72
            status = True
73
        # return the data
74
        return status
75