Completed
Branch master (5db784)
by Fox
01:52 queued 20s
created

ServiceTrello.process_data()   A

Complexity

Conditions 1

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 1
Metric Value
cc 1
c 4
b 0
f 1
dl 0
loc 9
rs 9.6666
1
# coding: utf-8
2
# Trello API
3
from trello import TrelloClient
4
5
# django classes
6
from django.conf import settings
7
from django.utils.translation import ugettext as _
8
from django.utils.log import getLogger
9
from django.core.cache import caches
10
11
# django_th classes
12
from django_th.apps import DjangoThConfig
13
from django_th.services.services import ServicesMgr
14
15
"""
16
    handle process with Trello
17
    put the following in settings.py
18
19
    TH_TRELLO = {
20
        'consumer_key': 'abcdefghijklmnopqrstuvwxyz',
21
        'consumer_secret': 'abcdefghijklmnopqrstuvwxyz',
22
    }
23
24
    TH_SERVICES = (
25
        ...
26
        'th_trello.my_trello.ServiceTrello',
27
        ...
28
    )
29
30
"""
31
32
logger = getLogger('django_th.trigger_happy')
33
34
cache = caches['th_trello']
35
36
37
class ServiceTrello(ServicesMgr):
38
39
    # Boards own Lists own Cards
40
41 View Code Duplication
    def __init__(self, token=None):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
42
        super(ServiceTrello, self).__init__(token)
43
        # app name
44
        self.app_name = DjangoThConfig.verbose_name
45
        # expiration
46
        self.expiry = "30days"
47
        # scope define the rights access
48
        self.scope = 'read,write'
49
50
        base = 'https://www.trello.com'
51
        self.AUTH_URL = '{}/1/OAuthAuthorizeToken'.format(base)
52
        self.REQ_TOKEN = '{}/1/OAuthGetRequestToken'.format(base)
53
        self.ACC_TOKEN = '{}/1/OAuthGetAccessToken'.format(base)
54
        self.consumer_key = settings.TH_TRELLO['consumer_key']
55
        self.consumer_secret = settings.TH_TRELLO['consumer_secret']
56
        if token:
57
            token_key, token_secret = token.split('#TH#')
58
            self.trello_instance = TrelloClient(self.consumer_key,
59
                                                self.consumer_secret,
60
                                                token_key,
61
                                                token_secret)
62
63
    def read_data(self, **kwargs):
64
        """
65
            get the data from the service
66
67
            :param kwargs: contain keyword args : trigger_id at least
68
            :type kwargs: dict
69
        """
70
        trigger_id = kwargs['trigger_id']
71
        data = list()
72
        cache.set('th_trello_' + str(trigger_id), data)
73
74
    def save_data(self, trigger_id, **data):
75
        """
76
            let's save the data
77
78
            :param trigger_id: trigger ID from which to save data
79
            :param data: the data to check to be used and save
80
            :type trigger_id: int
81
            :type data:  dict
82
            :return: the status of the save statement
83
            :rtype: boolean
84
        """
85
        from th_trello.models import Trello
86
87
        kwargs = {'output_format': 'md'}
88
        title, content = super(ServiceTrello, self).save_data(trigger_id,
89
                                                              data,
90
                                                              **kwargs)
91
92
        if len(title):
93
            # get the data of this trigger
94
            t = Trello.objects.get(trigger_id=trigger_id)
95
            # footer of the card
96
            footer = self.set_card_footer(data, t)
97
            content += footer
98
99
            # 1 - we need to search the list and board where we will
100
            # store the card so ...
101
102
            # 1.a search the board_id by its name
103
            # by retrieving all the boards
104
            boards = self.trello_instance.list_boards()
105
106
            board_id = ''
107
            my_list = ''
108
            for board in boards:
109
                if t.board_name == board.name.decode('utf-8'):
110
                    board_id = board.id
111
                    break
112
113
            if board_id:
114
                # 1.b search the list_id by its name
115
                my_board = self.trello_instance.get_board(board_id)
116
                lists = my_board.open_lists()
117
                # just get the open list ; not all the archive ones
118
                for list_in_board in lists:
119
                    # search the name of the list we set in the form
120
                    if t.list_name == list_in_board.name.decode('utf-8'):
121
                        # return the (trello) list object
122
                        # to be able to add card at step 3
123
                        my_list = my_board.get_list(list_in_board.id)
124
                        break
125
                # we didnt find the list in that board
126
                # create it
127
                if my_list == '':
128
                    my_list = my_board.add_list(t.list_name)
129
130
            else:
131
                # 2 if board_id and/or list_id does not exist, create it/them
132
                my_board = self.trello_instance.add_board(t.board_name)
133
                # add the list that didnt exists and
134
                # return a (trello) list object
135
                my_list = my_board.add_list(t.list_name)
136
137
            # 3 create the card
138
            # create the Trello card
139
            my_list.add_card(title, content)
140
141
            sentence = str('trello {} created').format(data['link'])
142
            logger.debug(sentence)
143
            status = True
144
        else:
145
            sentence = "no token or link provided for trigger ID {}"
146
            logger.critical(sentence.format(trigger_id))
147
            status = False
148
149
        return status
150
151
    @staticmethod
152
    def set_card_footer(data, trigger):
153
        """
154
            handle the footer of the note
155
        """
156
        footer = ''
157
        if 'link' in data:
158
            provided_by = _('Provided by')
159
            provided_from = _('from')
160
            footer_from = "<br/><br/>{} <em>{}</em> {} <a href='{}'>{}</a>"
161
162
            description = trigger.trigger.description
163
            footer = footer_from.format(
164
                provided_by, description, provided_from,
165
                data['link'], data['link'])
166
167
            import pypandoc
168
            footer = pypandoc.convert(footer, 'md', format='html')
169
170
        return footer
171
172
    def auth(self, request):
173
        """
174
            let's auth the user to the Service
175
            :param request: request object
176
            :return: callback url
177
            :rtype: string that contains the url to redirect after auth
178
        """
179
        request_token = super(ServiceTrello, self).auth(request)
180
        callback_url = self.callback_url(request, 'trello')
181
182
        # URL to redirect user to, to authorize your app
183
        auth_url_str = '{auth_url}?oauth_token={token}'
184
        auth_url_str += '&scope={scope}&name={name}'
185
        auth_url_str += '&expiration={expiry}&oauth_callback={callback_url}'
186
        auth_url = auth_url_str.format(auth_url=self.AUTH_URL,
187
                                       token=request_token['oauth_token'],
188
                                       scope=self.scope,
189
                                       name=self.app_name,
190
                                       expiry=self.expiry,
191
                                       callback_url=callback_url)
192
193
        return auth_url
194
195
    def callback(self, request, **kwargs):
196
        """
197
            Called from the Service when the user accept to activate it
198
            :param request: request object
199
            :return: callback url
200
            :rtype: string , path to the template
201
        """
202
        kwargs = {'access_token': '', 'service': 'ServiceTrello',
203
                  'return': 'trello'}
204
        return super(ServiceTrello, self).callback(request, **kwargs)
205