Passed
Push — master ( 64ad20...04166b )
by Dean
02:49
created

UpdateWSession.to_dict()   D

Complexity

Conditions 8

Size

Total Lines 86

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 72
Metric Value
cc 8
dl 0
loc 86
ccs 0
cts 35
cp 0
crap 72
rs 4.4597

How to fix   Long Method   

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:

1
from plugin.core.helpers.variable import to_integer, merge, resolve
2
from plugin.core.session_status import SessionStatus
3
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...
4
from plugin.managers.client import ClientManager
5
from plugin.managers.core.exceptions import FilteredException
6
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 63))

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.managers.user import UserManager
8
from plugin.models import Session
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
    def or_create(self, info, fetch=False):
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
            SessionStatus.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
        SessionStatus.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(obj.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...
79
            })
80
81
        # Retrieve session key
82
        session_key = to_integer(info.get('sessionKey'))
83
84
        if not session_key:
85
            log.info('Missing session key, unable to fetch session details')
86
            return result
87
88
        # Retrieve active sessions
89
        log.debug('Fetching details for session #%s', session_key)
90
91
        p_sessions = Plex['status'].sessions()
92
93
        if not p_sessions:
94
            log.info('Unable to retrieve active sessions')
95
            return result
96
97
        # Find session matching `session_key`
98
        p_item = p_sessions.get(session_key)
99
100
        if not p_item:
101
            log.info('Unable to find session with key %r', session_key)
102
            return result
103
104
        # Retrieve metadata and guid
105
        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...
106
107
        if not p_metadata:
108
            log.info('Unable to retrieve metadata for rating_key %r', p_item.rating_key)
109
            return result
110
111
        if not guid:
112
            return merge(result, {
113
                'duration': p_metadata.duration,
114
                '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...
115
            })
116
117
        try:
118
            # Create/Retrieve `Client` for session
119
            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...
120
                p_item.session.player,
121
122
                fetch=True,
123
                match=True,
124
                filtered_exception=True
125
            )
126
127
            # Create/Retrieve `User` for session
128
            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...
129
                p_item.session.user,
130
131
                fetch=True,
132
                match=True,
133
                filtered_exception=True
134
            )
135
136
            # Pick account from `client` or `user` objects
137
            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...
138
        except FilteredException:
139
            log.debug('Activity has been filtered')
140
141
            result['client'] = None
142
            result['user'] = None
143
144
            result['account'] = None
145
146
        return merge(result, {
147
            'duration': p_metadata.duration,
148
            '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...
149
        })
150
151
152
class WSessionManager(Manager):
0 ignored issues
show
Coding Style introduced by
This class has no __init__ method.
Loading history...
153
    get = GetWSession
154
    update = UpdateWSession
155
156
    model = Session
157