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.

Simkl   A
last analyzed

Complexity

Total Complexity 31

Size/Duplication

Total Lines 129
Duplicated Lines 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 129
rs 9.92
wmc 31

8 Methods

Rating   Name   Duplication   Size   Complexity  
A pin_success() 0 2 1
A _http() 0 13 4
A __init__() 0 18 4
A get_user_settings() 0 8 2
A pin_check() 0 9 3
A login() 0 18 5
C mark_as_watched() 0 47 10
A detect_by_file() 0 6 2
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
            if r is None: return False
137
            break
138
        return True
139
140
    def _http(self, url, headers={}, body=None, is_json=True):
141
        try:
142
            con = httplib.HTTPSConnection("api.simkl.com")
143
            con.request("GET", url, headers=headers, body=body)
144
            r = con.getresponse().read().decode("utf-8")
145
            if r.find('user_token_failed') != -1:
146
                self.isLoggedIn = False
147
                set_setting('token', '')
148
                notify(get_str(32031))
149
                return False
150
            return json.loads(r) if is_json else r
151
        except Exception:
152
            return None
153