Passed
Push — master ( aeb165...d9ae97 )
by Dean
03:04
created

TraktAccount.refresh()   C

Complexity

Conditions 7

Size

Total Lines 32

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 48.2727
Metric Value
dl 0
loc 32
ccs 1
cts 18
cp 0.0556
rs 5.5
cc 7
crap 48.2727
1 1
from plugin.core.exceptions import AccountAuthenticationError
2 1
from plugin.models.core import db
3 1
from plugin.models.account import Account
4
5 1
from datetime import datetime, timedelta
6 1
from playhouse.apsw_ext import *
0 ignored issues
show
Coding Style introduced by
The usage of wildcard imports like playhouse.apsw_ext should generally be avoided.
Loading history...
7 1
from trakt import Trakt
8 1
from urllib import urlencode
0 ignored issues
show
Bug introduced by
The name urlencode does not seem to exist in module urllib.
Loading history...
9 1
from urlparse import urlparse, parse_qsl
0 ignored issues
show
Configuration introduced by
The import urlparse could not be resolved.

This can be caused by one of the following:

1. Missing Dependencies

This error could indicate a configuration issue of Pylint. Make sure that your libraries are available by adding the necessary commands.

# .scrutinizer.yml
before_commands:
    - sudo pip install abc # Python2
    - sudo pip3 install abc # Python3
Tip: We are currently not using virtualenv to run pylint, when installing your modules make sure to use the command for the correct version.

2. Missing __init__.py files

This error could also result from missing __init__.py files in your module folders. Make sure that you place one file in each sub-folder.

Loading history...
10 1
import logging
11
12 1
REFRESH_INTERVAL = timedelta(days=1)
13
14 1
log = logging.getLogger(__name__)
15
16
17 1
class TraktAccount(Model):
18 1
    class Meta:
19 1
        database = db
20 1
        db_table = 'trakt.account'
21
22 1
    account = ForeignKeyField(Account, 'trakt_accounts', unique=True)
23
24 1
    username = CharField(null=True, unique=True)
25 1
    thumb = TextField(null=True)
26
27 1
    cover = TextField(null=True)
28 1
    timezone = TextField(null=True)
29
30 1
    refreshed_at = DateTimeField(null=True)
31
32 1
    def __init__(self, *args, **kwargs):
33
        super(TraktAccount, self).__init__(*args, **kwargs)
34
35
        self._basic_credential = None
36
        self._oauth_credential = None
37
38 1
    @property
39
    def basic(self):
40
        if self._basic_credential:
41
            return self._basic_credential
42
43
        return self.basic_credentials.first()
0 ignored issues
show
Bug introduced by
The Instance of TraktAccount does not seem to have a member named basic_credentials.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
44
45 1
    @basic.setter
46
    def basic(self, value):
47
        self._basic_credential = value
48
49 1
    @property
50
    def oauth(self):
51
        if self._oauth_credential:
52
            return self._oauth_credential
53
54
        return self.oauth_credentials.first()
0 ignored issues
show
Bug introduced by
The Instance of TraktAccount does not seem to have a member named oauth_credentials.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
55
56 1
    @oauth.setter
57
    def oauth(self, value):
58
        self._oauth_credential = value
59
60 1
    def authorization(self):
61
        # OAuth
62
        oauth = self.oauth
63
64
        if oauth and oauth.is_valid():
65
            return self.oauth_authorization(oauth)
66
67
        # Basic (legacy)
68
        basic = self.basic
69
70
        if basic:
71
            return self.basic_authorization(basic)
72
73
        # No account authorization available
74
        raise AccountAuthenticationError("Trakt account hasn't been authenticated")
75
76 1
    def basic_authorization(self, basic_credential=None):
77
        if basic_credential is None:
78
            basic_credential = self.basic
79
80
        log.debug('Using basic authorization for %r', self)
81
82
        return Trakt.configuration.auth(self.username, basic_credential.token)
0 ignored issues
show
Bug introduced by
The Class Trakt does not seem to have a member named configuration.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
83
84 1
    def oauth_authorization(self, oauth_credential=None):
85
        if oauth_credential is None:
86
            oauth_credential = self.oauth
87
88
        log.debug('Using oauth authorization for %r', self)
89
90
        return Trakt.configuration.oauth.from_response(oauth_credential.to_response(), refresh=True)
0 ignored issues
show
Bug introduced by
The Class Trakt does not seem to have a member named configuration.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
91
92 1
    def refresh(self, force=False, save=True, settings=None):
93
        if not force and self.refreshed_at:
94
            # Only refresh account every `REFRESH_INTERVAL`
95
            since_refresh = datetime.utcnow() - self.refreshed_at
96
97
            if since_refresh < REFRESH_INTERVAL:
98
                return False
99
100
        if settings is None:
101
            # Fetch trakt account details
102
            with self.authorization().http(retry=force):
103
                settings = Trakt['users/settings'].get()
104
105
        # Update user details
106
        user = settings.get('user', {})
107
        avatar = user.get('images', {}).get('avatar', {})
108
109
        self.thumb = avatar.get('full')
110
111
        # Update account details
112
        account = settings.get('account', {})
113
114
        self.cover = account.get('cover_image')
115
        self.timezone = account.get('timezone')
116
117
        self.refreshed_at = datetime.utcnow()
118
119
        # Store changes in database
120
        if save:
121
            self.save()
122
123
        return True
124
125 1
    def thumb_url(self, default=None, rating='pg', size=256):
126
        if not self.thumb:
127
            return None
128
129
        thumb = urlparse(self.thumb)
130
131
        if not thumb.netloc.endswith('gravatar.com'):
132
            return None
133
134
        result = 'https://secure.gravatar.com%s' % thumb.path
135
136
        if default is None:
137
            query = dict(parse_qsl(thumb.query))
138
139
            default = query.get('d') or query.get('default')
140
141
        return result + '?' + urlencode({
142
            'd': default,
143
            'r': rating,
144
            's': size
145
        })
146
147 1
    def to_json(self, full=False):
148
        result = {
149
            'id': self.id,
0 ignored issues
show
Bug introduced by
The Instance of TraktAccount does not seem to have a member named id.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
150
            'username': self.username,
151
152
            'thumb_url': self.thumb_url()
153
        }
154
155
        if not full:
156
            return result
157
158
        # Merge authorization details
159
        result['authorization'] = {
160
            'basic': {'state': 'empty'},
161
            'oauth': {'state': 'empty'}
162
        }
163
164
        # - Basic credentials
165
        basic = self.basic
166
167
        if basic is not None:
168
            result['authorization']['basic'] = basic.to_json(self)
169
170
        # - OAuth credentials
171
        oauth = self.oauth
172
173
        if oauth is not None:
174
            result['authorization']['oauth'] = oauth.to_json()
175
176
        return result
177
178 1
    def __repr__(self):
179
        return '<TraktAccount username: %r>' % (
180
            self.username,
181
        )
182