ServicePocket.__init__()   A
last analyzed

Complexity

Conditions 3

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
c 0
b 0
f 0
dl 0
loc 13
rs 9.4285
1
# coding: utf-8
2
import arrow
3
4
# pocket API
5
from pocket import Pocket, AuthException, RateLimitException
6
7
# django classes
8
from django.conf import settings
9
from logging import getLogger
10
from django.core.cache import caches
11
12
# django_th classes
13
from django_th.models import update_result, UserService
14
from django_th.services.services import ServicesMgr
15
from django_th.html_entities import HtmlEntities
16
17
"""
18
    handle process with pocket
19
    put the following in settings.py
20
21
    TH_POCKET = {
22
        'consumer_key': 'abcdefghijklmnopqrstuvwxyz',
23
    }
24
25
    TH_SERVICES = (
26
        ...
27
        'th_pocket.my_pocket.ServicePocket',
28
        ...
29
    )
30
31
"""
32
33
logger = getLogger('django_th.trigger_happy')
34
35
cache = caches['django_th']
36
37
38
class ServicePocket(ServicesMgr):
39
    """
40
        Service Pocket
41
    """
42
    def __init__(self, token=None, **kwargs):
43
        super(ServicePocket, self).__init__(token, **kwargs)
44
        self.consumer_key = settings.TH_POCKET_KEY['consumer_key']
45
        self.token = token
46
        self.oauth = 'oauth1'
47
        self.service = 'ServicePocket'
48
        if token:
49
            try:
50
                self.pocket = Pocket(self.consumer_key, token)
51
            except (AuthException, RateLimitException) as e:
52
                us = UserService.objects.get(token=token)
53
                logger.error(e.msg, e.error_code)
54
                update_result(us.trigger_id, msg=e.msg, status=False)
55
56
    def _create_entry(self, url, title, tags):
57
        """
58
            Create an entry
59
            :param url:  url to save
60
            :param title: title to set
61
            :param tags: tags to set
62
            :return: status
63
        """
64
        try:
65
            self.pocket.add(url=url, title=title, tags=tags)
66
            sentence = str('pocket {} created').format(url)
67
            logger.debug(sentence)
68
            status = True
69
        except Exception as e:
70
            logger.critical(e)
71
            update_result(self.trigger_id, msg=e, status=False)
72
            status = False
73
        return status
74
75
    def read_data(self, **kwargs):
76
        """
77
            get the data from the service
78
            as the pocket service does not have any date
79
            in its API linked to the note,
80
            add the triggered date to the dict data
81
            thus the service will be triggered when data will be found
82
83
            :param kwargs: contain keyword args : trigger_id at least
84
            :type kwargs: dict
85
86
            :rtype: list
87
        """
88
        trigger_id = kwargs.get('trigger_id')
89
        date_triggered = kwargs.get('date_triggered')
90
91
        data = list()
92
        # pocket uses a timestamp date format
93
        since = arrow.get(date_triggered).timestamp
94
        if self.token is not None:
95
96
            # get the data from the last time the trigger have been started
97
            # timestamp form
98
            pockets = self.pocket.get(since=since, state="unread")
99
            content = ''
100
            if pockets is not None and len(pockets[0]['list']) > 0:
101
                for my_pocket in pockets[0]['list'].values():
102
                    if my_pocket.get('excerpt'):
103
                        content = my_pocket['excerpt']
104
                    elif my_pocket.get('given_title'):
105
                        content = my_pocket['given_title']
106
                    my_date = arrow.get(str(date_triggered),
107
                                        'YYYY-MM-DD HH:mm:ss')\
108
                        .to(settings.TIME_ZONE)
109
                    data.append({'my_date': str(my_date),
110
                                 'tag': '',
111
                                 'link': my_pocket['given_url'],
112
                                 'title': my_pocket['given_title'],
113
                                 'content': content,
114
                                 'tweet_id': 0})
115
                    # digester
116
                    self.send_digest_event(trigger_id,
117
                                           my_pocket['given_title'],
118
                                           my_pocket['given_url'])
119
                cache.set('th_pocket_' + str(trigger_id), data)
120
121
        return data
122
123
    def save_data(self, trigger_id, **data):
124
        """
125
            let's save the data
126
127
            :param trigger_id: trigger ID from which to save data
128
            :param data: the data to check to be used and save
129
            :type trigger_id: int
130
            :type data:  dict
131
            :return: the status of the save statement
132
            :rtype: boolean
133
        """
134
        if data.get('link'):
135
            if len(data.get('link')) > 0:
136
                # get the pocket data of this trigger
137
                from th_pocket.models import Pocket as PocketModel
138
                trigger = PocketModel.objects.get(trigger_id=trigger_id)
139
140
                title = self.set_title(data)
141
                # convert htmlentities
142
                title = HtmlEntities(title).html_entity_decode
143
144
                status = self._create_entry(url=data.get('link'),
145
                                            title=title,
146
                                            tags=(trigger.tag.lower()))
147
            else:
148
                msg = "no link provided for trigger ID {}," \
149
                      " so we ignore it".format(trigger_id)
150
                logger.warning(msg)
151
                update_result(trigger_id, msg=msg, status=True)
152
                status = True
153
        else:
154
            msg = "no token provided for trigger ID {}".format(trigger_id)
155
            logger.critical(msg)
156
            update_result(trigger_id, msg=msg, status=False)
157
            status = False
158
        return status
159
160
    def auth(self, request):
161
        """
162
            let's auth the user to the Service
163
            :param request: request object
164
            :return: callback url
165
            :rtype: string that contains the url to redirect after auth
166
        """
167
        callback_url = self.callback_url(request)
168
169
        request_token = Pocket.get_request_token(
170
            consumer_key=self.consumer_key,
171
            redirect_uri=callback_url)
172
173
        # Save the request token information for later
174
        request.session['request_token'] = request_token
175
176
        # URL to redirect user to, to authorize your app
177
        auth_url = Pocket.get_auth_url(
178
            code=request_token, redirect_uri=callback_url)
179
180
        return auth_url
181
182
    def callback(self, request, **kwargs):
183
        """
184
            Called from the Service when the user accept to activate it
185
            :param request: request object
186
            :return: callback url
187
            :rtype: string , path to the template
188
        """
189
        access_token = Pocket.get_access_token(
190
            consumer_key=self.consumer_key,
191
            code=request.session['request_token'])
192
193
        kwargs = {'access_token': access_token}
194
195
        return super(ServicePocket, self).callback(request, **kwargs)
196