Test Failed
Push — develop ( db2443...9e1b8b )
by Dean
05:56 queued 03:05
created

UpdateWSession.to_dict()   F

Complexity

Conditions 10

Size

Total Lines 113

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 110

Importance

Changes 0
Metric Value
dl 0
loc 113
ccs 0
cts 39
cp 0
rs 3.1304
c 0
b 0
f 0
cc 10
crap 110

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 UpdateWSession.to_dict() 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 plugin.core.helpers.variable import to_integer, merge, resolve
2
from plugin.managers.core.base import Manager
0 ignored issues
show
Bug introduced by
The name base does not seem to exist in module plugin.managers.core.
Loading history...
Configuration introduced by
Unable to import 'plugin.managers.core.base' (invalid syntax (<string>, line 39))

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 plugin.managers.client import ClientManager
4
from plugin.managers.core.exceptions import FilteredException
5
from plugin.managers.session.base import GetSession, UpdateSession
0 ignored issues
show
Bug introduced by
The name base does not seem to exist in module plugin.managers.session.
Loading history...
Configuration introduced by
Unable to import 'plugin.managers.session.base' (invalid syntax (<string>, line 64))

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...
6
from plugin.managers.user import UserManager
7
from plugin.models import Session
8
from plugin.modules.core.manager import ModuleManager
0 ignored issues
show
Bug introduced by
The name manager does not seem to exist in module plugin.modules.core.
Loading history...
Configuration introduced by
Unable to import 'plugin.modules.core.manager' (invalid syntax (<string>, line 38))

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
10
from datetime import datetime
11
from plex import Plex
12
import apsw
0 ignored issues
show
Configuration introduced by
The import apsw 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
import logging
14
import peewee
15
16
17
log = logging.getLogger(__name__)
18
19
20
class GetWSession(GetSession):
0 ignored issues
show
Coding Style introduced by
This class has no __init__ method.
Loading history...
21
    def __call__(self, info):
22
        session_key = to_integer(info.get('sessionKey'))
23
24
        return super(GetWSession, self).__call__(
25
            Session.session_key == self.build_session_key(session_key)
0 ignored issues
show
Bug introduced by
The Instance of GetWSession does not seem to have a member named build_session_key.

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...
26
        )
27
28 View Code Duplication
    def or_create(self, info, fetch=False):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
29
        session_key = to_integer(info.get('sessionKey'))
30
31
        try:
32
            # Create new session
33
            obj = self.manager.create(
0 ignored issues
show
Bug introduced by
The Instance of GetWSession does not seem to have a member named manager.

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...
34
                rating_key=to_integer(info.get('ratingKey')),
35
                session_key=self.build_session_key(session_key),
0 ignored issues
show
Bug introduced by
The Instance of GetWSession does not seem to have a member named build_session_key.

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...
36
37
                state='create'
38
            )
39
40
            # Update newly created object
41
            self.manager.update(obj, info, fetch)
0 ignored issues
show
Bug introduced by
The Instance of GetWSession does not seem to have a member named manager.

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...
42
43
            # Update active sessions
44
            ModuleManager['sessions'].on_created(obj)
45
46
            return obj
47
        except (apsw.ConstraintError, peewee.IntegrityError):
48
            # Return existing object
49
            return self(info)
50
51
52
class UpdateWSession(UpdateSession):
0 ignored issues
show
Coding Style introduced by
This class has no __init__ method.
Loading history...
53
    def __call__(self, obj, info, fetch=False):
54
        data = self.to_dict(obj, info, fetch)
55
56
        success = super(UpdateWSession, self).__call__(
57
            obj, data
58
        )
59
60
        ModuleManager['sessions'].on_updated(obj)
61
        return success
62
63
    def to_dict(self, obj, info, fetch=False):
64
        fetch = resolve(fetch, obj, info)
65
66
        view_offset = to_integer(info.get('viewOffset'))
67
68
        result = {
69
            'rating_key': to_integer(info.get('ratingKey')),
70
            'view_offset': view_offset,
71
72
            'updated_at': datetime.utcnow()
73
        }
74
75
        if not fetch:
76
            # Return simple update
77
            return merge(result, {
78
                'progress': self.get_progress(
0 ignored issues
show
Bug introduced by
The Instance of UpdateWSession does not seem to have a member named get_progress.

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...
79
                    obj.duration, view_offset,
80
                    obj.part, obj.part_count, obj.part_duration
81
                )
82
            })
83
84
        # Retrieve session key
85
        session_key = to_integer(info.get('sessionKey'))
86
87
        if not session_key:
88
            log.info('Missing session key, unable to fetch session details')
89
            return result
90
91
        # Retrieve active sessions
92
        log.debug('Fetching details for session #%s', session_key)
93
94
        p_sessions = Plex['status'].sessions()
95
96
        if not p_sessions:
97
            log.info('Unable to retrieve active sessions')
98
            return result
99
100
        # Find session matching `session_key`
101
        p_item = p_sessions.get(session_key)
102
103
        if not p_item:
104
            log.info('Unable to find session with key %r', session_key)
105
            return result
106
107
        # Retrieve metadata and guid
108
        p_metadata, guid = self.get_metadata(p_item.rating_key)
0 ignored issues
show
Bug introduced by
The Instance of UpdateWSession does not seem to have a member named get_metadata.

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...
109
110
        if not p_metadata:
111
            log.info('Unable to retrieve metadata for rating_key %r', p_item.rating_key)
112
            return result
113
114
        if not guid:
115
            return merge(result, {
116
                'duration': p_metadata.duration,
117
                'progress': self.get_progress(p_metadata.duration, view_offset)
0 ignored issues
show
Bug introduced by
The Instance of UpdateWSession does not seem to have a member named get_progress.

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...
118
            })
119
120
        # Parse episode with matcher
121
        part = 1
122
        part_count = 1
123
        part_duration = p_metadata.duration
124
125
        if p_metadata.type == 'episode':
126
            p_season, p_episodes = ModuleManager['matcher'].process(p_metadata)
0 ignored issues
show
Unused Code introduced by
The variable p_season seems to be unused.
Loading history...
127
128
            # Determine the current part number
129
            part_duration, part = self.get_part(p_metadata.duration, view_offset, len(p_episodes))
0 ignored issues
show
Bug introduced by
The Instance of UpdateWSession does not seem to have a member named get_part.

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...
130
131
            # Update `part_count` attribute
132
            part_count = len(p_episodes)
133
134
            if part_count > 1:
135
                log.debug('Current part: %s (part_count: %s, part_duration: %s)', part, part_count, part_duration)
136
137
        # Find matching client + user for session
138
        try:
139
            # Create/Retrieve `Client` for session
140
            result['client'] = ClientManager.get.or_create(
0 ignored issues
show
Bug introduced by
It seems like a value for argument player is missing in the unbound method call.
Loading history...
141
                p_item.session.player,
142
143
                fetch=True,
144
                match=True,
145
                filtered_exception=True
146
            )
147
148
            # Create/Retrieve `User` for session
149
            result['user'] = UserManager.get.or_create(
0 ignored issues
show
Bug introduced by
It seems like a value for argument user is missing in the unbound method call.
Loading history...
150
                p_item.session.user,
151
152
                fetch=True,
153
                match=True,
154
                filtered_exception=True
155
            )
156
157
            # Pick account from `client` or `user` objects
158
            result['account'] = self.get_account(result)
0 ignored issues
show
Bug introduced by
The Instance of UpdateWSession does not seem to have a member named get_account.

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...
159
        except FilteredException:
160
            log.debug('Activity has been filtered')
161
162
            result['client'] = None
163
            result['user'] = None
164
165
            result['account'] = None
166
167
        return merge(result, {
168
            'part': part,
169
            'part_count': part_count,
170
            'part_duration': part_duration,
171
172
            'duration': p_metadata.duration,
173
            'progress': self.get_progress(
0 ignored issues
show
Bug introduced by
The Instance of UpdateWSession does not seem to have a member named get_progress.

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...
174
                p_metadata.duration, view_offset,
175
                part, part_count, part_duration
176
            )
177
        })
178
179
180
class WSessionManager(Manager):
0 ignored issues
show
Coding Style introduced by
This class has no __init__ method.
Loading history...
181
    get = GetWSession
182
    update = UpdateWSession
183
184
    model = Session
185