GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Push — master ( 0b346f...8ed2a5 )
by
unknown
43s
created

Simkl.mark_as_watched()   D

Complexity

Conditions 11

Size

Total Lines 56

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 11
dl 0
loc 56
rs 4.4262
c 1
b 1
f 0

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 Simkl.mark_as_watched() 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
#!/usr/bin/python
2
# -*- coding: UTF-8 -*-
3
4
import sys
5
import json
6
import time
7
import xbmc
8
9
import httplib
10
11
from interface import notify
12
from interface import LoginDialog
13
from utils import get_str
14
from utils import get_setting
15
from utils import set_setting
16
from utils import log
17
from utils import __addon__
18
19
REDIRECT_URI = "http://simkl.com"
20
APIKEY = '62a587ec2a82dbed02c6ab48b923d72e775cb1096d2de60d04502413e36ef100'
21
SECRET = '3e9d1563659a94a930c282d3d38cc01ece2ab5d769ae449cff1ff6f13d9b732e'
22
23
24
class Simkl:
25
    def __init__(self):
26
        self.userSettings = {}
27
        self.isLoggedIn = False
28
        self.loginInProgress = False
29
30
        self.headers = {"Content-Type": "application-json", "simkl-api-key": APIKEY}
31
        # set_setting('token', '')
32
        token = get_setting('token')
33
        if token:
34
            self.headers["authorization"] = "Bearer " + token
35
            r = self.get_user_settings()
36
            if r:
37
                notify(get_str(32025).format(self.userSettings["user"]["name"]))
38
                return
39
            elif r is None:
40
                notify(get_str(32027))
41
                return
42
        self.login()
43
44
    def get_user_settings(self):
45
        r = self._http("/users/settings", headers=self.headers)
46
        if isinstance(r, dict):
47
            self.userSettings = r
48
            self.isLoggedIn = True
49
            log("Usersettings = " + str(self.userSettings))
50
            return True
51
        return r
52
53
    def login(self):
54
        if self.loginInProgress: return
55
        self.loginInProgress = True
56
57
        if not self.isLoggedIn:
58
            rdic = self._http("/oauth/pin?client_id=" + APIKEY + "&redirect=" + REDIRECT_URI, headers=self.headers)
59
60
            if isinstance(rdic, dict) and "error" not in rdic.keys():
61
                pin = rdic["user_code"]
62
                url = rdic["verification_url"]
63
64
                login = LoginDialog("simkl-LoginDialog.xml", __addon__.getAddonInfo("path"), pin=pin, url=url,
65
                                    pin_check=self.pin_check, pin_success=self.pin_success)
66
                login.doModal()
67
                del login
68
        else:
69
            notify(get_str(32025).format(self.userSettings["user"]["name"]))
70
        self.loginInProgress = False
71
72
    def pin_check(self, pin):
73
        r = self._http("/oauth/pin/" + pin + "?client_id=" + APIKEY, headers=self.headers)
74
        log("PIN Check = " + str(r))
75
        if r["result"] == "OK":
76
            set_setting('token', r["access_token"])
77
            self.headers["authorization"] = "Bearer " + r["access_token"]
78
            return self.get_user_settings()
79
        elif r["result"] == "KO":
80
            return False
81
82
    def pin_success(self):
83
        notify(get_str(32030).format(self.userSettings["user"]["name"]))
84
85
    def detect_by_file(self, filename):
86
        values = json.dumps({"file": filename})
87
        r = self._http("/search/file/", headers=self.headers, body=values)
88
        if r:
89
            log("Response: {0}".format(r))
90
        return r
91
92
    def mark_as_watched(self, item):
93
        if not item: return False
94
95
        log("MARK: {0}".format(item))
96
        _watched_at = time.strftime('%Y-%m-%d %H:%M:%S')
97
        _count = 0
98
99
        s_data = {}
100
        if item["type"] == "episodes":
101
            s_data[item["type"]] = [{
102
                "watched_at": _watched_at,
103
                "ids": {
104
                    "simkl": item["simkl"]
105
                }
106
            }]
107
        elif item["type"] == "shows":
108
            # TESTED
109
            s_data[item["type"]] = [{
110
                "title": item["title"],
111
                "ids": {
112
                    "tvdb": item["tvdb"]
113
                },
114
                "seasons": [{
115
                    "number": item['season'],
116
                    "episodes": [{
117
                        "number": item['episode']
118
                    }]
119
                }]
120
            }]
121
        elif item["type"] == "movies":
122
            _prep = {
123
                "title": item["title"],
124
                "year": item["year"],
125
            }
126
            if "simkl" in item:
127
                _prep["ids"] = {"simkl": item["simkl"]}
128
            elif "imdb" in item:
129
                _prep["ids"] = {"imdb": item["imdb"]}
130
131
            s_data[item["type"]] = [_prep]
132
133
        log("Send: {0}".format(json.dumps(s_data)))
134
        while True and s_data:
135
            r = self._http("/sync/history/", body=json.dumps(s_data), headers=self.headers)
136
137
            #retry 3 times
138
            if r is None:
139
                _count += 1
140
                if _count <= 3:
141
                    notify(get_str(32029).format(_count))
142
                    time.sleep(10)
143
                    continue
144
                notify(get_str(32027))
145
                return False
146
            break
147
        return True
148
149
    def _http(self, url, headers={}, body=None, is_json=True):
150
        try:
151
            con = httplib.HTTPSConnection("api.simkl.com")
152
            con.request("GET", url, headers=headers, body=body)
153
            r = con.getresponse().read().decode("utf-8")
154
            if r.find('user_token_failed') != -1:
155
                self.isLoggedIn = False
156
                set_setting('token', '')
157
                notify(get_str(32031))
158
                return False
159
            return json.loads(r) if is_json else r
160
        except Exception:
161
            return None
162