Passed
Push — develop ( 2798d2...d1b463 )
by Dean
02:48
created

TraktAccount

Size/Duplication

Total Lines 168
Duplicated Lines 0 %

Test Coverage

Coverage 25.29%

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 168
ccs 22
cts 87
cp 0.2529

10 Methods

Rating   Name   Duplication   Size   Complexity  
A basic_authorization() 0 7 2
A oauth() 0 6 1
A __init__() 0 5 1
A basic() 0 6 1
C refresh() 0 32 7
B to_json() 0 30 4
B authorization() 0 15 5
A oauth_authorization() 0 10 2
A thumb_url() 0 20 4
A __repr__() 0 3 1
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 exception_wrappers.libraries.playhouse.apsw_ext import *
0 ignored issues
show
Coding Style introduced by
The usage of wildcard imports like exception_wrappers.libraries.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 and basic.is_valid():
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(
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
            oauth_credential.to_response(),
92
            refresh=True,
93
            username=self.username
94
        )
95
96 1
    def refresh(self, force=False, save=True, settings=None):
97
        if not force and self.refreshed_at:
98
            # Only refresh account every `REFRESH_INTERVAL`
99
            since_refresh = datetime.utcnow() - self.refreshed_at
100
101
            if since_refresh < REFRESH_INTERVAL:
102
                return False
103
104
        if settings is None:
105
            # Fetch trakt account details
106
            with self.authorization().http(retry=force):
107
                settings = Trakt['users/settings'].get()
108
109
        # Update user details
110
        user = settings.get('user', {})
111
        avatar = user.get('images', {}).get('avatar', {})
112
113
        self.thumb = avatar.get('full')
114
115
        # Update account details
116
        account = settings.get('account', {})
117
118
        self.cover = account.get('cover_image')
119
        self.timezone = account.get('timezone')
120
121
        self.refreshed_at = datetime.utcnow()
122
123
        # Store changes in database
124
        if save:
125
            self.save()
126
127
        return True
128
129 1
    def thumb_url(self, default=None, rating='pg', size=256):
130
        if not self.thumb:
131
            return None
132
133
        thumb = urlparse(self.thumb)
134
135
        if not thumb.netloc.endswith('gravatar.com'):
136
            return None
137
138
        result = 'https://secure.gravatar.com%s' % thumb.path
139
140
        if default is None:
141
            query = dict(parse_qsl(thumb.query))
142
143
            default = query.get('d') or query.get('default')
144
145
        return result + '?' + urlencode({
146
            'd': default,
147
            'r': rating,
148
            's': size
149
        })
150
151 1
    def to_json(self, full=False):
152
        result = {
153
            '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...
154
            'username': self.username,
155
156
            'thumb_url': self.thumb_url()
157
        }
158
159
        if not full:
160
            return result
161
162
        # Merge authorization details
163
        result['authorization'] = {
164
            'basic': {'state': 'empty'},
165
            'oauth': {'state': 'empty'}
166
        }
167
168
        # - Basic credentials
169
        basic = self.basic
170
171
        if basic is not None:
172
            result['authorization']['basic'] = basic.to_json(self)
173
174
        # - OAuth credentials
175
        oauth = self.oauth
176
177
        if oauth is not None:
178
            result['authorization']['oauth'] = oauth.to_json()
179
180
        return result
181
182 1
    def __repr__(self):
183
        return '<TraktAccount username: %r>' % (
184
            self.username,
185
        )
186