Passed
Push — develop ( c6fa42...950d5f )
by Dean
02:50
created

Main.update_proxies()   F

Complexity

Conditions 13

Size

Total Lines 62

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 62
rs 2.8934
cc 13

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like Main.update_proxies() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
from core.header import Header
0 ignored issues
show
Bug introduced by
The name header does not seem to exist in module core.
Loading history...
Configuration introduced by
The import core.header 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...
2
from core.helpers import get_class_name, spawn
0 ignored issues
show
Bug introduced by
The name helpers does not seem to exist in module core.
Loading history...
Configuration introduced by
The import core.helpers 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...
3
from core.logger import Logger
0 ignored issues
show
Bug introduced by
The name logger does not seem to exist in module core.
Loading history...
Configuration introduced by
The import core.logger 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...
4
from core.update_checker import UpdateChecker
0 ignored issues
show
Bug introduced by
The name update_checker does not seem to exist in module core.
Loading history...
Configuration introduced by
The import core.update_checker 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...
5
6
from plugin.core.constants import ACTIVITY_MODE, PLUGIN_VERSION
0 ignored issues
show
Configuration introduced by
The import plugin.core.constants 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...
7
from plugin.core.helpers.thread import module_start
0 ignored issues
show
Configuration introduced by
The import plugin.core.helpers.thread 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...
8
from plugin.core.logger import LOG_HANDLER, LoggerManager
0 ignored issues
show
Configuration introduced by
The import plugin.core.logger 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...
9
from plugin.managers.account import TraktAccountManager
0 ignored issues
show
Configuration introduced by
The import plugin.managers.account 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
from plugin.models import TraktAccount
0 ignored issues
show
Configuration introduced by
The import plugin.models 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...
11
from plugin.modules.core.manager import ModuleManager
0 ignored issues
show
Configuration introduced by
The import plugin.modules.core.manager 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...
12
from plugin.preferences import Preferences
0 ignored issues
show
Configuration introduced by
The import plugin.preferences 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...
13
from plugin.scrobbler.core.session_prefix import SessionPrefix
0 ignored issues
show
Configuration introduced by
The import plugin.scrobbler.core.session_prefix 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...
14
15
from plex import Plex
0 ignored issues
show
Configuration introduced by
The import plex 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...
16
from plex_activity import Activity
0 ignored issues
show
Configuration introduced by
The import plex_activity 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...
17
from plex_metadata import Metadata
0 ignored issues
show
Configuration introduced by
The import plex_metadata 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...
18
from six.moves.urllib.parse import quote_plus, urlsplit, urlunsplit
0 ignored issues
show
Configuration introduced by
The import six.moves.urllib.parse 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...
19
from requests.packages.urllib3.util import Retry
0 ignored issues
show
Bug introduced by
The name packages does not seem to exist in module requests.
Loading history...
Configuration introduced by
The import requests.packages.urllib3.util 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...
20
from trakt import Trakt
0 ignored issues
show
Configuration introduced by
The import trakt 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...
21
import os
22
import uuid
23
24
log = Logger()
25
26
27
class Main(object):
28
    modules = [
29
        # core
30
        UpdateChecker()
31
    ]
32
33
    def __init__(self):
34
        Header.show(self)
35
36
        # Initial configuration update
37
        self.on_configuration_changed()
38
39
        # Initialize clients
40
        self.init_trakt()
41
        self.init_plex()
42
        self.init()
43
44
        # Initialize modules
45
        ModuleManager.initialize()
46
47
    def init(self):
48
        names = []
49
50
        # Initialize modules
51
        for module in self.modules:
52
            names.append(get_class_name(module))
53
54
            if hasattr(module, 'initialize'):
55
                module.initialize()
56
57
        log.info('Initialized %s modules: %s', len(names), ', '.join(names))
58
59
    @staticmethod
60
    def init_plex():
61
        # Ensure client identifier has been generated
62
        if not Dict['plex.client.identifier']:
0 ignored issues
show
Comprehensibility Best Practice introduced by
Undefined variable 'Dict'
Loading history...
63
            # Generate identifier
64
            Dict['plex.client.identifier'] = uuid.uuid4()
0 ignored issues
show
Comprehensibility Best Practice introduced by
Undefined variable 'Dict'
Loading history...
65
66
        # Retrieve current client identifier
67
        client_id = Dict['plex.client.identifier']
0 ignored issues
show
Comprehensibility Best Practice introduced by
Undefined variable 'Dict'
Loading history...
68
69
        if isinstance(client_id, uuid.UUID):
70
            client_id = str(client_id)
71
72
        # plex.py
73
        Plex.configuration.defaults.authentication(
74
            os.environ.get('PLEXTOKEN')
75
        )
76
77
        Plex.configuration.defaults.client(
78
            identifier=client_id,
79
80
            product='trakt (for Plex)',
81
            version=PLUGIN_VERSION
82
        )
83
84
        # plex.activity.py
85
        path = os.path.join(LOG_HANDLER.baseFilename, '..', '..', 'Plex Media Server.log')
86
        path = os.path.abspath(path)
87
88
        Activity['logging'].add_hint(path)
89
90
        # plex.metadata.py
91
        Metadata.configure(
92
            client=Plex.client
93
        )
94
95
    @classmethod
96
    def init_trakt(cls):
97
        # Client
98
        Trakt.configuration.defaults.client(
99
            id='c9ccd3684988a7862a8542ae0000535e0fbd2d1c0ca35583af7ea4e784650a61',
100
            secret='bf00575b1ad252b514f14b2c6171fe650d474091daad5eb6fa890ef24d581f65'
101
        )
102
103
        # Application
104
        Trakt.configuration.defaults.app(
105
            name='trakt (for Plex)',
106
            version=PLUGIN_VERSION
107
        )
108
109
        # Setup request retrying
110
        Trakt.http.adapter_kwargs = {'max_retries': Retry(total=3, read=0)}
111
        Trakt.http.rebuild()
112
113
        Trakt.on('oauth.token_refreshed', cls.on_token_refreshed)
114
115
    @classmethod
116
    def on_token_refreshed(cls, authorization):
117
        log.debug('Authentication - PIN authorization refreshed')
118
119
        # Retrieve trakt account matching this `authorization`
120
        with Trakt.configuration.http(retry=True).oauth(token=authorization.get('access_token')):
121
            settings = Trakt['users/settings'].get()
122
123
        if not settings:
124
            log.warn('Authentication - Unable to retrieve account details for authorization')
125
            return
126
127
        # Retrieve trakt account username from `settings`
128
        username = settings.get('user', {}).get('username')
129
130
        if not username:
131
            log.warn('Authentication - Unable to retrieve username for authorization')
132
            return None
133
134
        # Find matching trakt account
135
        trakt_account = (TraktAccount
136
            .select()
137
            .where(
138
                TraktAccount.username == username
139
            )
140
        ).first()
141
142
        if not trakt_account:
143
            log.warn('Authentication - Unable to find TraktAccount with the username %r', username)
144
145
        # Update oauth credential
146
        TraktAccountManager.update.from_dict(trakt_account, {
147
            'authorization': {
148
                'oauth': authorization
149
            }
150
        })
151
152
        log.info('Authentication - Updated OAuth credential for %r', trakt_account)
153
154
    def start(self):
155
        # Construct main thread
156
        spawn(self.run, daemon=True, thread_name='main')
157
158
    def run(self):
159
        # Check for authentication token
160
        log.info('X-Plex-Token: %s', 'available' if os.environ.get('PLEXTOKEN') else 'unavailable')
161
162
        # Process server startup state
163
        self.process_server_state()
164
165
        # Start new-style modules
166
        module_start()
167
168
        # Start modules
169
        names = []
170
171
        for module in self.modules:
172
            if not hasattr(module, 'start'):
173
                continue
174
175
            names.append(get_class_name(module))
176
177
            module.start()
178
179
        log.info('Started %s modules: %s', len(names), ', '.join(names))
180
181
        ModuleManager.start()
182
183
        # Start plex.activity.py
184
        Activity.start(ACTIVITY_MODE.get(Preferences.get('activity.mode')))
185
186
    @classmethod
187
    def process_server_state(cls):
188
        # Check startup state
189
        server = Plex.detail()
190
191
        if server is None:
192
            log.info('Unable to check startup state, detail request failed')
193
            return
194
195
        # Check server startup state
196
        if server.start_state is None:
197
            return
198
199
        if server.start_state == 'startingPlugins':
200
            return cls.on_starting_plugins()
201
202
        log.error('Unhandled server start state %r', server.start_state)
203
204
    @staticmethod
205
    def on_starting_plugins():
206
        log.debug('on_starting_plugins')
207
208
        SessionPrefix.increment()
209
210
    @classmethod
211
    def on_configuration_changed(cls):
212
        # Update proxies (for requests)
213
        cls.update_proxies()
214
215
        # Refresh loggers
216
        LoggerManager.refresh()
217
218
    @staticmethod
219
    def update_proxies():
220
        # Retrieve proxy host
221
        host = Prefs['proxy_host']
0 ignored issues
show
Comprehensibility Best Practice introduced by
Undefined variable 'Prefs'
Loading history...
222
223
        if not host:
224
            if not Trakt.http.proxies and not os.environ.get('HTTP_PROXY') and not os.environ.get('HTTPS_PROXY'):
225
                return
226
227
            # Update trakt client
228
            Trakt.http.proxies = {}
229
230
            # Update environment variables
231
            if 'HTTP_PROXY' in os.environ:
232
                del os.environ['HTTP_PROXY']
233
234
            if 'HTTPS_PROXY' in os.environ:
235
                del os.environ['HTTPS_PROXY']
236
237
            log.info('HTTP Proxy has been disabled')
238
            return
239
240
        # Parse URL
241
        host_parsed = urlsplit(host)
242
243
        # Expand components
244
        scheme, netloc, path, query, fragment = host_parsed
245
246
        if not scheme:
247
            scheme = 'http'
248
249
        # Retrieve proxy credentials
250
        username = Prefs['proxy_username']
0 ignored issues
show
Comprehensibility Best Practice introduced by
Undefined variable 'Prefs'
Loading history...
251
        password = Prefs['proxy_password']
0 ignored issues
show
Comprehensibility Best Practice introduced by
Undefined variable 'Prefs'
Loading history...
252
253
        # Build URL
254
        if username and password and '@' not in netloc:
255
            netloc = '%s:%s@%s' % (
256
                quote_plus(username),
257
                quote_plus(password),
258
                netloc
259
            )
260
261
        url = urlunsplit((scheme, netloc, path, query, fragment))
262
263
        # Update trakt client
264
        Trakt.http.proxies = {
265
            'http': url,
266
            'https': url
267
        }
268
269
        # Update environment variables
270
        os.environ.update({
271
            'HTTP_PROXY': url,
272
            'HTTPS_PROXY': url
273
        })
274
275
        # Display message in log file
276
        if not host_parsed.username and not host_parsed.password:
277
            log.info('HTTP Proxy has been enabled (host: %r)', host)
278
        else:
279
            log.info('HTTP Proxy has been enabled (host: <sensitive>)')
280