Completed
Push — master ( 7a81b9...200bfb )
by Fox
01:33
created

ServiceTodoist.__init__()   A

Complexity

Conditions 2

Size

Total Lines 11

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 11
rs 9.4285
1
# coding: utf-8
2
3
# Oauth2Session
4
from requests_oauthlib import OAuth2Session
5
6
# TodoistAPI
7
from todoist import TodoistAPI
8
9
# django classes
10
from django.conf import settings
11
from django.utils.log import getLogger
12
from django.core.cache import caches
13
14
# django_th classes
15
from django_th.models import UserService, ServicesActivated
16
from django_th.services.services import ServicesMgr
17
18
19
"""
20
    handle process with todoist
21
    put the following in settings.py
22
23
    TH_TODOIST = {
24
        'client_id': 'abcdefghijklmnopqrstuvwxyz',
25
        'client_secret': 'abcdefghijklmnopqrstuvwxyz',
26
    }
27
    TH_SERVICES = (
28
        ...
29
        'th_todoist.my_todoist.ServiceTodoist',
30
        ...
31
    )
32
"""
33
34
logger = getLogger('django_th.trigger_happy')
35
36
cache = caches['th_todoist']
37
38
39
class ServiceTodoist(ServicesMgr):
40
41
    def __init__(self, token=None, **kwargs):
42
        super(ServiceTodoist, self).__init__(token, **kwargs)
43
        self.AUTH_URL = 'https://todoist.com/oauth/authorize'
44
        self.ACC_TOKEN = 'https://todoist.com/oauth/access_token'
45
        self.REQ_TOKEN = 'https://todoist.com/oauth/authorize'
46
        self.consumer_key = settings.TH_TODOIST['client_id']
47
        self.consumer_secret = settings.TH_TODOIST['client_secret']
48
        self.scope = 'task:add,data:read,data:read_write'
49
        if token:
50
            self.token = token
51
            self.todoist = TodoistAPI(token)
52
53
    def read_data(self, **kwargs):
54
        """
55
            get the data from the service
56
            as the pocket service does not have any date
57
            in its API linked to the note,
58
            add the triggered date to the dict data
59
            thus the service will be triggered when data will be found
60
61
            :param kwargs: contain keyword args : trigger_id at least
62
            :type kwargs: dict
63
64
            :rtype: list
65
        """
66
        trigger_id = kwargs['trigger_id']
67
        data = list()
68
        cache.set('th_todoist_' + str(trigger_id), data)
69
70
    def save_data(self, trigger_id, **data):
71
        """
72
            let's save the data
73
            :param trigger_id: trigger ID from which to save data
74
            :param data: the data to check to be used and save
75
            :type trigger_id: int
76
            :type data:  dict
77
            :return: the status of the save statement
78
            :rtype: boolean
79
        """
80
        kwargs = {}
81
82
        title, content = super(ServiceTodoist, self).save_data(trigger_id,
83
                                                               data, **kwargs)
84
85
        if self.token:
86
            if title or content or \
87
                            (data.get('link') and len(data.get('link'))) > 0:
88
                content = title + ' ' + content + ' ' + data.get('link')
89
90
                self.todoist.add_item(content)
91
92
                sentence = str('todoist {} created').format(data.get('link'))
93
                logger.debug(sentence)
94
                status = True
95
            else:
96
                status = False
97
        else:
98
            logger.critical("no token or link provided for "
99
                            "trigger ID {} ".format(trigger_id))
100
            status = False
101
        return status
102
103
    def auth(self, request):
104
        """
105
            let's auth the user to the Service
106
            :param request: request object
107
            :return: callback url
108
            :rtype: string that contains the url to redirect after auth
109
        """
110
        callback_url = self.callback_url(request, 'todoist')
111
        oauth = OAuth2Session(client_id=self.consumer_key,
112
                              redirect_uri=callback_url,
113
                              scope=self.scope)
114
        authorization_url, state = oauth.authorization_url(self.AUTH_URL)
115
116
        return authorization_url
117
118
    def callback(self, request, **kwargs):
119
        """
120
            Called from the Service when the user accept to activate it
121
        """
122
        callback_url = self.callback_url(request, 'todoist')
123
        oauth = OAuth2Session(client_id=self.consumer_key,
124
                              redirect_uri=callback_url,
125
                              scope=self.scope)
126
        request_token = oauth.fetch_token(self.ACC_TOKEN,
127
                                          code=request.GET.get('code', ''),
128
                                          authorization_response=callback_url,
129
                                          client_secret=self.consumer_secret)
130
        token = request_token.get('access_token')
131
        service_name = ServicesActivated.objects.get(name='ServiceTodoist')
132
        UserService.objects.filter(user=request.user,
133
                                   name=service_name
134
                                   ).update(token=token)
135
136
        return 'todoist/callback.html'
137